Skip to content

Instantly share code, notes, and snippets.

@justinobney
Last active November 27, 2019 20:32
Show Gist options
  • Save justinobney/2258aa08cf4253f5923b to your computer and use it in GitHub Desktop.
Save justinobney/2258aa08cf4253f5923b to your computer and use it in GitHub Desktop.
const identity = x=>x;
/**
* Reducing Function - Turns an array of values into a single value
* n => 1
* @param {array} array - The values to reduce into a single value.
* @param {callback} aggregatingFunction - called for each item in the array
* - given:
* - aggregatedValue
* - currentArrayItem
* - currentArrayIndex
* - array
* - should return aggregatedValue;
* @param {callback} startingValue
* - will be aggregatedValue in first iteration of loop.
*/
const reduce = (arr, fn, startingVal) => {
let prevResult = startingVal;
// behold! the mighty for loop
for (let i = 0; i < arr.length; i++) {
prevResult = fn(prevResult, arr[i], i, arr);
}
return prevResult;
}
reduce(
[1,2,3],
(acc, val) => acc + val,
0
); // returns: 6
// n => n
const map = (arr, fn) => reduce(
arr,
(aggregator, val, idx, coll) => {
aggregator.push(fn(val, idx, coll));
return aggregator;
},
[]
)
// n => <=n
const filter = (arr, fn) => reduce(
arr,
(aggregator, val, idx, coll) => {
if(fn(val, idx, coll)){
aggregator.push(val);
}
return aggregator;
},
[]
)
const flatten = (array) => reduce(
array,
(agg, val) => agg.concat(val),
[]
)
const shallowCopy = (arr) => map(arr, identity);
const slice = (arr, start, take) => {
start = start || 0;
take = take || 0;
const reducingFn = (prev, val, idx, coll) => {
if(idx >= start && (idx < start + take || !take)){
return prev.concat([val])
} else {
return prev
}
}
return reduce(shallowCopy(arr), reducingFn, [])
}
const partial = (fn, ...params) => {
return (...args) => {
const allArgs = params.concat(args);
return fn(...allArgs);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment