Skip to content

Instantly share code, notes, and snippets.

@mfalade
Created September 8, 2018 06:37
Show Gist options
  • Save mfalade/499d7106ce281053b14ffc405ca5d401 to your computer and use it in GitHub Desktop.
Save mfalade/499d7106ce281053b14ffc405ca5d401 to your computer and use it in GitHub Desktop.
A basic implementation of the Array.prototype.reduce method
Array.prototype.xreduce = myReduce;
function myReduce (action, defaultValue) {
var result = [];
var isObject = typeof defaultValue === 'object';
var initialAccVal = isObject ? (defaultValue.constructor === Object ? {} : []) : defaultValue;
var acc = isObject ? Object.assign(initialAccVal, defaultValue) : defaultValue;
for (var i = 0; i < this.length; i++) {
var args = [acc, this[i], i, this];
acc = action.apply(null, args);
}
return acc;
}
var res = [1, 2, 3].xreduce((acc, value, index, array) => {
acc.push(value + 4);
return acc;
}, []);
console.log(res, 'reduce output')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment