diff options
Diffstat (limited to 'src/sjs.mjs')
| -rw-r--r-- | src/sjs.mjs | 41 |
1 files changed, 25 insertions, 16 deletions
diff --git a/src/sjs.mjs b/src/sjs.mjs index aae85a7..600a1f5 100644 --- a/src/sjs.mjs +++ b/src/sjs.mjs @@ -292,20 +292,16 @@ export const isReduced = x => x instanceof Reduced; export const reduced = x => new Reduced(x); -const reduceRec = (coll, fn, acc, index) => - isReduced(acc) ? acc.value : - index === coll.length ? acc : - reduceRec( - coll, - fn, - fn(acc, coll[index], index, coll), - index + 1, - ); +export const reduce = (coll, fn, init) => { + let acc = init === undefined ? coll[0] : init; + let start = init === undefined ? 1 : 0; + for (let i = start; i < coll.length; i++) { + acc = fn(acc, coll[i], i, coll); + if (isReduced(acc)) return acc.value; + } + return acc; +}; -export const reduce = (coll, fn, init) => - init === undefined - ? reduceRec(coll.slice(1), fn, coll[0], 0) - : reduceRec(coll, fn, init, 0); const reductionsRec = (coll, fn, acc, index, steps) => { if (isReduced(acc)) { @@ -342,6 +338,17 @@ export const mapValues = (obj, fn) => export const repeat = (n, x) => (new Array(n)).fill(x); +export const collectStdin = async stdin => { + const chunks = []; + for await (const chunk of stdin) { + chunks.push(chunk); + } + return Buffer.concat(chunks); +}; + +export const readStdin = async stdin => + (await collectStdin(stdin)).toString("utf-8"); + export const red = s => `\x1b[0;31m${s}\x1b[0m`; export const redb = s => `\x1b[1;31m${s}\x1b[0m`; export const green = s => `\x1b[0;32m${s}\x1b[0m`; @@ -450,13 +457,15 @@ const mappings = { node: async () => { const assert = await import("node:assert/strict"); const process = await import("node:process"); + const id = s => s; + const c = fn => process.stderr.isTTY ? fn : id; return { err: x => process.stderr.write(x), assertEq: assert.deepEqual, colors: { - red, - green, - yellow, + red: c(red), + green: c(green), + yellow: c(yellow), }, }; }, |
