UNPKG

@codibre/fluent-iterable

Version:

Provides LINQ-like fluent api operations for iterables and async iterables (ES2018+).

49 lines (48 loc) 1.72 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.flatJoinRecipe = flatJoinRecipe; const base_1 = require("./../types/base"); const is_iterable_1 = require("../is-iterable"); function flattable(value) { return typeof value !== 'string' && (0, is_iterable_1.isIterable)(value); } function fillField(result, field, subItem) { if (!result.hasOwnProperty(field)) { result[field] = subItem; } } function getNewResult(result, field, subItem) { result = { ...result, }; fillField(result, field, subItem); return result; } function flatMapFactory(ingredients, deepFlat) { return function flatMap(result, item, path, nextIndex) { const { flatten } = ingredients; const start = nextIndex; let current = item; for (let i = start; i < path.length; i++) { const field = path[i]; current = current[field]; if (flattable(current)) { return flatten.call(deepFlat(current), (subItem) => flatMap(getNewResult(result, field, subItem), subItem, path, i + 1)); } fillField(result, field, current); } result[base_1.head] = current; return [result]; }; } function flatJoinRecipe(ingredients) { const { flatten } = ingredients; const deepFlat = (x) => flatten.call(x, (y) => (flattable(y) ? deepFlat(y) : [y])); const flatMap = flatMapFactory(ingredients, deepFlat); return function (...path) { function process(y) { return flatMap({ [base_1.tail]: y }, y, path, 0); } return flatten.call(this, (x) => flattable(x) ? flatten.call(deepFlat(x), process) : process(x)); }; }