@codibre/fluent-iterable
Version:
Provides LINQ-like fluent api operations for iterables and async iterables (ES2018+).
77 lines (76 loc) • 2.93 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.branchRecipe = branchRecipe;
let fluentAsync;
function getBranchedAsyncIterable(node, iterator, context) {
return {
[Symbol.asyncIterator]() {
return {
next() {
var _a;
let done = true;
let value;
if (node) {
value = node.value;
done = false;
if (!node.next) {
const promise = ((_a = context.next) !== null && _a !== void 0 ? _a : (context.next = iterator.next().then((next) => {
if (!next.done)
node.next = { value: next.value };
context.next = undefined;
})));
return promise.then(() => {
node = node.next;
return { done, value };
});
}
node = node.next;
}
return Promise.resolve({ done, value });
},
};
},
};
}
function getBranchedIterable(node, iterator) {
return {
[Symbol.asyncIterator]() {
return {
next() {
let done = true;
let value;
if (node) {
value = node.value;
done = false;
if (!node.next) {
const next = iterator.next();
if (!next.done)
node.next = { value: next.value };
}
node = node.next;
}
return Promise.resolve({ done, value });
},
};
},
};
}
async function getAsync(it, items) {
const context = {};
const iterator = it[Symbol.asyncIterator]();
const first = await iterator.next();
const node = first.done ? undefined : { value: first.value };
return Promise.all(items.map((cb) => cb(fluentAsync(getBranchedAsyncIterable(node, iterator, context)))));
}
function branchRecipe() {
return function branch(...items) {
fluentAsync !== null && fluentAsync !== void 0 ? fluentAsync : (fluentAsync = require('../fluent-async').fluentAsync);
if (Symbol.iterator in this) {
const iterator = this[Symbol.iterator]();
const first = iterator.next();
const node = first.done ? undefined : { value: first.value };
return Promise.all(items.map((cb) => cb(fluentAsync(getBranchedIterable(node, iterator)))));
}
return getAsync(this, items);
};
}