Add samples

This commit is contained in:
Sami Turcotte 2018-12-03 00:38:17 -05:00
parent e41abfada4
commit 56fe20dc3c
9 changed files with 44 additions and 26 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "mhysa", "name": "mhysa",
"version": "0.6.0-beta.0", "version": "0.6.0-beta.1",
"description": "Streams and event emitter utils for Node.js", "description": "Streams and event emitter utils for Node.js",
"keywords": [ "keywords": [
"promise", "promise",

8
samples/async.js Normal file
View File

@ -0,0 +1,8 @@
const Mhysa = require("mhysa");
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.map(s => Promise.resolve(s + s)))
.pipe(Mhysa.flatMap(s => Promise.resolve([s, s.toUpperCase()])))
.pipe(Mhysa.filter(s => Promise.resolve(s !== "bb")))
.pipe(Mhysa.join(","))
.pipe(process.stdout);

View File

@ -16,4 +16,4 @@ Mhysa.concat(
fs.createReadStream(sourceFile1), fs.createReadStream(sourceFile1),
Mhysa.fromArray(["\n"]), Mhysa.fromArray(["\n"]),
fs.createReadStream(sourceFile2), fs.createReadStream(sourceFile2),
).pipe(fs.createWriteStream(outputFile)); ).pipe(process.stdout);

View File

@ -1,23 +0,0 @@
const {
utils: { sleep, delay, once },
...Mhysa
} = require("mhysa");
async function main() {
const collector = Mhysa.concat(
Mhysa.fromArray(["a\n", "b\n", "c\n"]),
Mhysa.fromArray(["d", "e"]).pipe(Mhysa.join("-")),
)
.pipe(Mhysa.split("\n"))
.pipe(
Mhysa.flatMap(async s => {
await sleep(100);
return delay([s, s.toUpperCase()], 100);
}),
)
.pipe(Mhysa.collect({ objectMode: true }));
const collected = await once(collector, "data");
console.log(collected); // [ 'a', 'A', 'b', 'B', 'c', 'C', 'd-e', 'D-E' ] (after 6 * 100 ms)
}
main();

6
samples/filter.js Normal file
View File

@ -0,0 +1,6 @@
const Mhysa = require("mhysa");
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.filter(s => s !== "b"))
.pipe(Mhysa.join(","))
.pipe(process.stdout);

6
samples/flatMap.js Normal file
View File

@ -0,0 +1,6 @@
const Mhysa = require("mhysa");
Mhysa.fromArray(["a", "AA"])
.pipe(Mhysa.flatMap(s => new Array(s.length).fill(s)))
.pipe(Mhysa.join(","))
.pipe(process.stdout);

6
samples/map.js Normal file
View File

@ -0,0 +1,6 @@
const Mhysa = require("mhysa");
Mhysa.fromArray(["a", "b"])
.pipe(Mhysa.map(s => s.toUpperCase()))
.pipe(Mhysa.join(","))
.pipe(process.stdout);

5
samples/reduce.js Normal file
View File

@ -0,0 +1,5 @@
const Mhysa = require("mhysa");
Mhysa.fromArray(["a", "b", "cc"])
.pipe(Mhysa.reduce((acc, s) => ({ ...acc, [s]: s.length }), {}))
.pipe(process.stdout);

View File

@ -182,7 +182,17 @@ export function reduce<T, R>(
} }
}, },
flush(callback) { flush(callback) {
callback(undefined, value); // Best effort attempt at yielding the final value (will throw if e.g. yielding an object and
// downstream doesn't expect objects)
try {
callback(undefined, value);
} catch (err) {
try {
this.emit("error", err);
} catch {
// Best effort was made
}
}
}, },
}); });
} }