UNPKG

@quinck/collections

Version:

Allows extra operations on JavaScript collections: Array, Map and Set.

39 lines (38 loc) 1.55 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.match = void 0; function match(predicate, matchedMapper) { return [predicate, matchedMapper]; } exports.match = match; Array.prototype.singleCollect = function (predicate, matchedMapper, otherwiseMapper, thisArg) { const _self = this; if (otherwiseMapper) return _self.map((item, index, array) => predicate(item, index, array) ? matchedMapper(item, index, array) : otherwiseMapper(item, index, array), thisArg); return _self.flatMap((item, index, array) => predicate(item, index, array) ? [matchedMapper(item, index, array)] : [], thisArg); }; Array.prototype.collect = function (matchCases, otherwiseMapper, thisArg) { const _self = this; if (otherwiseMapper) { return _self.map((item, index, array) => { const matchingCase = matchCases.find(([filter]) => filter(item, index, array)); if (matchingCase != undefined) { const [, matchedMapper] = matchingCase; return matchedMapper(item, index, array); } return otherwiseMapper(item, index, array); }, thisArg); } return _self.flatMap((item, index, array) => { const matchingCase = matchCases.find(([filter]) => filter(item, index, array)); if (matchingCase != undefined) { const [, matchedMapper] = matchingCase; return [matchedMapper(item, index, array)]; } return []; }); };