Skip to content

Instantly share code, notes, and snippets.

@hinex
Last active May 7, 2021 13:06
Show Gist options
  • Save hinex/0e02b36f4f55e6b39c6e9fa648eef314 to your computer and use it in GitHub Desktop.
Save hinex/0e02b36f4f55e6b39c6e9fa648eef314 to your computer and use it in GitHub Desktop.
Array.prototype.reduceCustom = function(callback, initialValue) {
const array = this
if (!array.length) {
if (initialValue) {
return initialValue
}
throw new Error('TypeError: Reduce of empty array with no initial value')
}
if (!initialValue && array.length === 1) {
return array[0]
}
let accumulator = initialValue ?? array[0]
const startIndex = initialValue ? 0 : 1
for (let i = startIndex, length = array.length; i < length; i++) {
accumulator = callback(accumulator, array[i], i, array)
}
return accumulator
}
Array.prototype.flatCustom = function(depth = 1) {
const array = this
const makeFlat = (a, c) => a.concat(
Array.isArray(c) && depth > 1
? c.flatCustom(depth - 1)
: c
)
return array.reduceCustom(makeFlat, [])
}
// Reducer tests
const reduceTest = [1, 2, 3, 4, 5]
const sumCallback = (a, c) => (a + c)
console.log('Reducer - Sum', reduceTest.reduce(sumCallback))
console.log('CustomReducer - Sum', reduceTest.reduceCustom(sumCallback))
console.log('Reducer - Empty with Initial Value', [].reduce(sumCallback, 1))
console.log('CustomReducer - Empty with Initial Value', [].reduceCustom(sumCallback, 1))
console.log('Reducer - One Item with Initial Value', [2].reduce(sumCallback, 1))
console.log('CustomReducer - One Item with Initial Value', [2].reduceCustom(sumCallback, 1))
const commonResult = (a, c, i) => {
a.push({c, i})
return a
}
console.log('Reducer - Result', [2, 3].reduce(commonResult, []))
console.log('CustomReducer - Result', [2, 3].reduceCustom(commonResult, []))
// Flat Test
console.log('Flat', [2, 3, [4, 5], 1].flat())
console.log('FlatCustom', [2, 3, [4, 5], 1].flatCustom())
console.log('Flat - With depth 2', [2, 3, [4, 5, [6, 7, [8, 9]]], 1].flat(2))
console.log('flatCustom - With depth 2', [2, 3, [4, 5, [6, 7, [8, 9]]], 1].flatCustom(2))
console.log('Flat - With depth 3', [2, 3, [4, 5, [6, 7, [8, 9]]], 1].flat(3))
console.log('flatCustom - With depth 3', [2, 3, [4, 5, [6, 7, [8, 9]]], 1].flatCustom(3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment