Skip to content

Commit

Permalink
Add Number.isSafeInteger (#667)
Browse files Browse the repository at this point in the history
  • Loading branch information
PiotrKasperski authored Dec 4, 2023
1 parent 9b3a698 commit 0885713
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
2 changes: 1 addition & 1 deletion jacdac-ts
Submodule jacdac-ts updated 1 files
+1 −1 jacdac-spec
18 changes: 18 additions & 0 deletions packages/runtime/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,4 +273,22 @@ describe("number", () => {
checkNot(false)
checkNot([NaN])
})
test("isSafeInteger", () => {
const check = (v: unknown) => expect(Number.isSafeInteger(v)).toBe(true)
const checkNot = (v: unknown) =>
expect(Number.isSafeInteger(v)).toBe(false)

check(3)
check(3.0)
check(2 ** 53 - 1)
check(-(2 ** 53 - 1))

checkNot(2 ** 53)
checkNot(-(2 ** 53))
checkNot(NaN)
checkNot(Infinity)
checkNot(-Infinity)
checkNot("3")
checkNot(3.1)
})
})
12 changes: 12 additions & 0 deletions packages/runtime/src/number.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,16 @@ export class Number {
static isNaN(number: unknown): boolean {
return isNaN(number as number)
}
/**
* The boolean value true if the given value is a number that is a safe integer. Otherwise false.
* @param The value to be tested for being a safe integer.
*/
static isSafeInteger(number: unknown): boolean {
return (
number >= -(2 ** 53 - 1) &&
number <= 2 ** 53 - 1 &&
typeof number === "number" &&
number === Math.round(number)
)
}
}

0 comments on commit 0885713

Please sign in to comment.