locutus
Version:
Locutus other languages' standard libraries to JavaScript for fun and educational purposes
36 lines (35 loc) • 1.21 kB
JavaScript
export const noInitializer = Symbol('noInitializer');
export function pythonReduce(func, iterable, initializer = noInitializer) {
const iterator = toIterator(iterable, 'reduce');
let accumulator;
if (initializer !== 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`);
}