Skip to content

Instantly share code, notes, and snippets.

@korutx
Last active October 25, 2018 14:11
Show Gist options
  • Save korutx/7d5a64ba644d85bda4bec4069efb086c to your computer and use it in GitHub Desktop.
Save korutx/7d5a64ba644d85bda4bec4069efb086c to your computer and use it in GitHub Desktop.
/**
* Hight-Order Funcion
* Returns a single item by iterating through the list, successively calling the iterator function and passing it an accumulator value and
* the current value from the array, and then passing the result to the next call.
* @param {Array} list Array of element
* @param {Function} fn Functor. The iterator function. Receives two values, the accumulator and the current element from the array.
* @param {*} acc The accumulator value.
* @return {*} The final, accumulated value.
*/
const reduce = (list, fn, acc) => {
for(let i of list) {
acc = fn(acc, i)
}
return acc
}
/**
* Returns a new list by pulling every item out of it (and all its sub-arrays) and putting them in a new array, depth-first.
* Recursion aproach
* @param {Array} list The array to consider.
* @return {Array} The flattened list.
*/
const flatten = list => reduce(list, (acc, el) => el instanceof Array ? acc.concat( flatten(el) ) : acc.concat([ el ]), [] )
/**
* Returns a new list by pulling every item out of it (and all its sub-arrays) and putting them in a new array.
* O(n) fast flatten aproach
* @param {Array} list The array to consider.
* @return {Array} The flattened list.
*/
const fast_flatten = list => {
let ret = []
for(let el; el = list.pop(); ){
if (el instanceof Array) {
list.push.apply(list, el)
} else {
ret.push(el)
}
}
ret.reverse()
return ret
}
flatten([ [1,2, [3 ]], 4])
//[ 1, 2, 3, 4 ]
fast_flatten([ [1,2, [3 ]], 4])
//[ 1, 2, 3, 4 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment