The coding problem
- I want to build up a list of pre-determined functions, then dynamically apply them to a list
For example
const list = [1,2,3,4,5,6,7,8,9,10];
function under8(i) { return i < 8 }
function over3(i) { return i > 3 }
function under6(i) { return i < 6 }
function over4(i) { return i > 4 }
let fns = []
// accumulate the list of functions to apply
fns = [under8, over3, under6, over4]
let filteredList;
// build a program that generates a filtered array from list
// Testing the program
console.log(filteredList) // -> 5
After only one bout of over-thinking, the solution hit me!
filteredList = fns.reduce((acc, fn) => {
return acc.filter(fn)
}, list)
How it works
- The array of functions is iterated through
- The sequence starts with the list of 10 numbers
- Each iteration, the current function is used to filter the list
- The resulting subset of items from list is carried through to the next iteration, where the next function is applied as a filter
- The result is saved as a new array into filteredList
- The output is list, after being filtered by each function that has been added to the fns list
Moments like this feel great. Celebrate them when you can.
Thank you, functional programming.
Top comments (0)