diff --git a/package.json b/package.json index 977fb6c..bb8ff9f 100644 --- a/package.json +++ b/package.json @@ -45,8 +45,10 @@ "posttest": "npm run lint", "test": "vitest", "doc": "typedoc src/index.ts . --name xen-dev-utils", - "prebenchmark": "tsc -p tsconfig-benchmark.json", - "benchmark": "node benchmarks/__benchmarks__/monzo.mark.js" + "premonzo-benchmark": "tsc -p tsconfig-benchmark.json", + "monzo-benchmark": "node benchmarks/__benchmarks__/monzo.mark.js", + "preprimes-benchmark": "tsc -p tsconfig-benchmark.json", + "primes-benchmark": "node benchmarks/__benchmarks__/primes.mark.js" }, "engines": { "node": ">=10.6.0" diff --git a/src/__benchmarks__/primes.mark.ts b/src/__benchmarks__/primes.mark.ts new file mode 100644 index 0000000..c8bab18 --- /dev/null +++ b/src/__benchmarks__/primes.mark.ts @@ -0,0 +1,41 @@ +// @ts-ignore +import Benchmark = require('benchmark'); +import {PRIMES, isPrime} from '../primes'; + +function withoutInclusionCheck(n: number) { + if (!Number.isInteger(n) || n < 2) { + return false; + } + if (n > 62837328) { + throw new Error('Prime check only implemented up to 62837328'); + } + for (const prime of PRIMES) { + if (prime * prime > n) { + return true; + } + if (n % prime === 0) { + return false; + } + } + return true; +} + +function randSmallInt() { + return Math.floor(Math.random() * 10000); +} + +const primalityCheckSuite = new Benchmark.Suite(); +primalityCheckSuite + .add('primality check (with array inclusion)', () => isPrime(randSmallInt())) + .add('primality check (without array inclusion)', () => + withoutInclusionCheck(randSmallInt()) + ) + .on('cycle', (event: {target: any}) => { + console.log(String(event.target)); + }) + .on('complete', () => { + console.log( + 'Fastest is ' + primalityCheckSuite.filter('fastest').map('name') + ); + }) + .run({async: true}); diff --git a/src/primes.ts b/src/primes.ts index 48d776b..cb3767e 100644 --- a/src/primes.ts +++ b/src/primes.ts @@ -108,12 +108,12 @@ export const BIG_INT_PRIMES = PRIMES.map(BigInt); * @returns True if the number is prime, false otherwise. */ export function isPrime(n: number) { - if (!Number.isInteger(n) || n < 2) { - return false; - } if (n < 7927) { return PRIMES.includes(n); } + if (!Number.isInteger(n)) { + return false; + } if (n > 62837328) { throw new Error('Prime check only implemented up to 62837328'); } diff --git a/tsconfig-benchmark.json b/tsconfig-benchmark.json index fd803f7..ce95009 100644 --- a/tsconfig-benchmark.json +++ b/tsconfig-benchmark.json @@ -2,7 +2,11 @@ "extends": "./node_modules/gts/tsconfig-google.json", "compilerOptions": { "rootDir": "./src/", - "outDir": "benchmarks" + "outDir": "benchmarks", + "lib": [ + "es2020" + ], + "target": "es2020" }, "include": [ "src/__benchmarks__/*"