-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.js
44 lines (36 loc) · 1.3 KB
/
utils.js
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
const { createInterface } = require('node:readline')
// true if and only if the value is null or undefined
exports.isNil = x => undefined === x || null === x
// merge extra elements from array2 if it is longer
exports.mergeArray = (array1, array2) =>
array1.concat(array2.slice(array1.length))
// Inherit prototype
exports.inheritPrototype = (target, source) => {
Object.setPrototypeOf(
target,
Object.getPrototypeOf(source)
)
}
/**
* Send syncronous errors into nth callback of CPS function.
* Defaults to n = 2.
*
* @param {Function} cpsF - CPS function
* @param [{Number} n] - number of the callback
* @returns {Function} cpsF - CPS function receiving sync errors into its nth callback
*/
exports.err2cb = (cpsF, n=2) => (...cbs) =>
{ try {return cpsF(...cbs)} catch(err) {return cbs[n-1](err)} }
// ---- File/Stream utils ---- //
/**
* Transform Readable Node stream to CPS function with 3 callbacks (onRes, onErr, onEnd):
* - onRes receives content of each line from stream;
* - onErr receives errors;
* - onEnd receives `null` when stream ends.
*
* @param {Stream} input - Readable Node stream
* @returns {Function} - CPS function
*/
exports.stream2lines = input => exports.err2cb((onRes, onErr, onEnd) =>
createInterface(input).on('line', onRes).on('close', _ => onEnd(null))
)