MCPcopy Create free account
hub / github.com/arktypeio/arktype / nearestFloat

Function nearestFloat

ark/util/numbers.ts:276–298  ·  view source on GitHub ↗
(n: number, direction: "+" | "-" = "+")

Source from the content-addressed store, hash-verified

274 * console.log(nearestFloat(-Infinity)); // -1.7976931348623157e+308
275 */
276export const nearestFloat = (n: number, direction: "+" | "-" = "+"): number => {
277 // stepping the bits of NaN or past an infinity writes NaN
278 if (Number.isNaN(n) || n === (direction === "+" ? Infinity : -Infinity)) {
279 return throwError(
280 `No float is ${direction === "+" ? "after" : "before"} ${n}`,
281 RangeError
282 )
283 }
284 const buffer = new ArrayBuffer(8)
285 const f64 = new Float64Array(buffer)
286 const u32 = new Uint32Array(buffer)
287
288 f64[0] = n
289
290 if (n === 0) {
291 u32[0] = 1
292 u32[1] = direction === "-" ? 1 << 31 : 0
293 } else if ((n > 0 && direction === "+") || (n < 0 && direction === "-")) {
294 if (u32[0]++ === 0xffffffff) u32[1]++
295 } else if (u32[0]-- === 0) u32[1]--
296
297 return f64[0]
298}
299
300// String writes a number below 1e-6 or from 1e21 with an exponent
301export const printDecimal = (n: number): string => {

Callers 3

numbers.test.tsFile · 0.90

Calls 1

throwErrorFunction · 0.90

Tested by

no test coverage detected