Last active
June 19, 2019 20:43
-
-
Save aquaductape/35e81fb5b6aeeaf910603a6456d75a54 to your computer and use it in GitHub Desktop.
emulating reduce method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Array prototype method, however this is not safe, since it is added to the global scope | |
// definedProperty makes method non-enumerable as well as adding new property to in this case, to Array prototype | |
Object.defineProperty(Array.prototype, 'myReduce', { | |
value: function(callback, initialValue) { | |
if (typeof callback !== 'function') { | |
throw new TypeError(`${callback} is not a function`); | |
} | |
// throw error if array is empty, even a sparse array | |
// use filter(or use myFilter) method to remove empty values | |
// haven't found a way to check if array is sparse other than using filter | |
if (initialValue === undefined && !this.filter(() => true).length) { | |
throw new TypeError('Reduce of empty array with no initial value'); | |
} | |
const length = this.length; | |
let accumulator = initialValue; | |
let i = 0; | |
if (initialValue === undefined) { | |
accumulator = this[0]; | |
i = 1; | |
} | |
while (i < length) { | |
if (i in this) { | |
accumulator = callback(accumulator, this[i], i, this); | |
} | |
i++; | |
} | |
return accumulator; | |
}, | |
}); | |
// class alternative, safe since methods are locally scoped | |
class MyMethods { | |
constructor() {} | |
reduce(arr, callback, initialValue) { | |
if (typeof callback !== 'function') { | |
throw new TypeError(`${callback} is not a function`); | |
} | |
if (initialValue === undefined && !arr.filter(() => true).length) { | |
throw new TypeError('Reduce of empty array with no initial value'); | |
} | |
const length = arr.length; | |
let accumulator = initialValue; | |
let i = 0; | |
if (initialValue === undefined) { | |
accumulator = arr[0]; | |
i = 1; | |
} | |
while (i < length) { | |
if (i in arr) { | |
accumulator = callback(accumulator, arr[i], i, arr); | |
} | |
i++; | |
} | |
return accumulator; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment