-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecute.js
More file actions
81 lines (62 loc) · 1.97 KB
/
execute.js
File metadata and controls
81 lines (62 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Checks the command line for the dataset number (defaults to 0);
// runs a puzzle solution, reports the elapsed time.
'use strict'
const { basename } = require('path')
const { format } = require('util')
const assert = require('assert-fine')
const MAXN = BigInt(Number.MAX_SAFE_INTEGER)
const print = msg => process.stdout.write(msg)
const usecsFrom = t0 => {
const t1 = process.hrtime(t0)
return (t1[0] * 1e9 + t1[1]) / 1000
}
const appName = basename(require.main.filename)
const usage = `usage: node ${appName} [dataset-number, ...] [help] [debug]\n`
let cliArgs = [], debug = false, help
// label, fn, algorithm, ...defaults)
const execute = (label, fn, ...parms) => {
let args = cliArgs.slice(), [algorithm, ...defaults] = parms
if (typeof algorithm !== 'function') defaults = parms, algorithm = undefined
for (let i = 0; i < defaults.length; ++i) {
args[i] = i < cliArgs.length ? cliArgs[i] : defaults[i]
}
const t0 = process.hrtime()
let result = algorithm ? fn(algorithm, ...args) : fn(...args)
const usecs = Math.floor(usecsFrom(t0)) + ''
if (typeof result === 'bigint' && result < MAXN) {
result = Number(result)
}
print(format('\n%s / dataset %i: %o\n t:%s µsecs\n',
label, args[0], result, usecs.padStart(12)))
}
const assertionHook = (callback) => {
assert.hook(callback)
return assert
}
if (process.argv.length > 2) {
let bad = false, v
for (const arg of process.argv.slice(2)) {
if (arg[0] === 'd') {
debug = true
} else if (arg[0] === 'h') {
help = true
} else {
cliArgs.push(v = 1 * arg)
if (!(v >= 0)) bad = true
}
}
if (help) {
process.stdout.write(usage)
process.exit(0)
}
if (bad) {
process.stderr.write(`bad cliArgs: '` + process.argv.slice(2).join(' ') + `'\n`)
process.stdout.write(usage)
process.exit(1)
}
}
if (!cliArgs.length) cliArgs.push(0)
exports = module.exports = execute
Object.assign(exports,
{ assert, assertionHook, debug, execute }
)