UNPKG

locutus

Version:

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

40 lines (39 loc) 1.36 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.noInitializer = void 0; exports.pythonReduce = pythonReduce; exports.noInitializer = Symbol('noInitializer'); function pythonReduce(func, iterable, initializer = exports.noInitializer) { const iterator = toIterator(iterable, 'reduce'); let accumulator; if (initializer !== exports.noInitializer) { accumulator = initializer; } else { const first = iterator.next(); if (first.done) { throw new TypeError('reduce() of empty sequence with no initial value'); } accumulator = first.value; } while (true) { const next = iterator.next(); if (next.done) { return accumulator; } accumulator = func(accumulator, next.value); } } function toIterator(iterable, functionName) { if (typeof iterable === 'string') { return iterable[Symbol.iterator](); } if ((typeof iterable === 'object' || typeof iterable === 'function') && iterable !== null) { const iterableValue = iterable; const iteratorFactory = iterableValue[Symbol.iterator]; if (typeof iteratorFactory === 'function') { return iteratorFactory.call(iterableValue); } } throw new TypeError(`${functionName}() expected an iterable`); }