UNPKG

locutus

Version:

Locutus other languages' standard libraries to JavaScript for fun and educational purposes

29 lines (28 loc) 1.17 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.runningFold = runningFold; function runningFold(values, initial, operation) { // discuss at: https://locutus.io/kotlin/collections/runningFold/ // original by: Kevin van Zonneveld (https://kvz.io) // note 1: Returns successive accumulation values including initial, like Kotlin runningFold. // example 1: runningFold([1, 2, 3, 4], 0, (acc, value) => acc + value) // returns 1: [0, 1, 3, 6, 10] // example 2: runningFold(['a', 'b', 'c'], '', (acc, value) => acc + value) // returns 2: ['', 'a', 'ab', 'abc'] // example 3: runningFold([], 10, (acc, value) => acc + value) // returns 3: [10] if (typeof operation !== 'function') { throw new TypeError('runningFold(): operation must be a function'); } if (!Array.isArray(values)) { return [initial]; } const array = values; const out = [initial]; let accumulator = initial; for (let i = 0; i < array.length; i++) { accumulator = operation(accumulator, array[i], i, array); out.push(accumulator); } return out; }