Last active
August 31, 2016 12:54
-
-
Save mgtitimoli/b531357de1beecd574cc4c2a832039db to your computer and use it in GitHub Desktop.
Reduce While: Applies a reduce function as long as filter function returns true and returns the last value returned by reduceFn
This file contains hidden or 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
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; | |
const numbersNames = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; | |
const namesOfNumbersLessThan = maxNumber => reduceWhile( | |
numbers, | |
number => number < maxNumber, | |
(result, number, index) => result.concat(numbersNames[index]) | |
); | |
console.log(namesOfNumbersLessThan(5)); // ['zero', 'one', 'two', 'three', 'four'] |
This file contains hidden or 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
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; | |
const numbersNames = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; | |
const lettersOfNumbersLessThan = maxNumber => reduceWhile( | |
numbers, | |
number => number < maxNumber, | |
(result, number, index) => result + numbersNames[index].length, | |
0 | |
); | |
console.log(lettersOfNumbersLessThan(5)); // 19 |
This file contains hidden or 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
const defaultReduceFn = (result, element) => result.concat(element); | |
export default function reduceWhile( | |
elements, | |
filterFn, | |
reduceFn = defaultReduceFn, | |
initialValue = [] | |
) { | |
let result = initialValue; | |
elements.every((...args) => { | |
const shouldContinue = filterFn(...args); | |
if (shouldContinue) { | |
result = reduceFn(result, ...args); | |
} | |
return shouldContinue; | |
}); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment