0.0.7 • Published 7 years ago
toox v0.0.7
TOOlboX
A set of useful utilities, somewhat tested.
Installation
npm install --save-dev toox
or as a git submodule:
git submodule add <full repo url> toox
to update the submodule to the latest version (git submodule update doesn't do it)
cd toox
git pull
The Good Bits
const toox = require('toox')
range(a, b, n) - a Python style range function
> toox.range(50,85,5)
[ 50, 55, 60, 65, 70, 75, 80 ]
fill(n, x) - an array of size n, filled with x
> toox.fill(10,'hi')
[ 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi' ]
ellipses(str, n=80) - truncate strings if needed
> toox.ellipses(JSON.stringify(toox.fill(100,'hi')), 40)
'["hi","hi","hi","hi","hi","hi","hi","...'
eachPair(obj, func) - iterate through key/value pairs of plain objects
The returned value from the callback is the new value, unless toox.DELETE
or undefined
is returned, in which case the k/v pair does not appear in the result
> toox.eachPair({a: 'hello', b: 'world'}, (k, v) => v + ':' + k)
{ a: 'hello:a', b: 'world:b' }
sleep - promisified setTimeout
> toox.sleep(5000).then(() => console.log('hello'))
... some time passes
hello
formatMs - tersely display durations from milliseconds to hours
> toox.formatMs(53)
'53ms'
> toox.formatMs(5300)
'5.30s'
> toox.formatMs(530000)
'8m50'
> toox.formatMs(53000000)
'14h43'
stopwatch suite - measure and report time intervals
> (async () => {
... toox.stopwatch.start('test1')
... await toox.sleep(1500)
... toox.stopwatch.endReport('test1')
... })()
test1 finished 1.51s
shuffle(array) - randomize the order of array elements
> toox.shuffle([1,2,3,4,5])
[ 2, 5, 4, 3, 1 ]
after(ms, value) - a promise that resolves to a given value after a time
> toox.after(5000, 'hello').then(console.log)
... some time passes
hello
asyncAllObjectValues(obj) - like Promise.all but for object values
> toox.asyncAllObjectValues({a: toox.after(1000, 'hello'), b: toox.after(2000, 'world')}).then(console.log)
... some time passes
{ a: 'hello', b: 'world' }
parallelize(arrayOfFunctionsThatReturnPromises, poolSize=4, timeout=null, tries=1)
Run some async functions in parallel, at most poolSize
at once. Give each one timeout
ms to complete, retry tries
times or until no error is thrown.
If a function throws an error more than tries
times, the error is returned in the results. This may cause problems if your functions return (not throw) errors.