DEV Community

Robert Mion
Robert Mion

Posted on

12 years later, a tough coding problem only took me 12 minutes to solve

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
Enter fullscreen mode Exit fullscreen mode

After only one bout of over-thinking, the solution hit me!

filteredList = fns.reduce((acc, fn) => {
  return acc.filter(fn)
}, list)
Enter fullscreen mode Exit fullscreen mode

How it works

  1. The array of functions is iterated through
  2. The sequence starts with the list of 10 numbers
  3. Each iteration, the current function is used to filter the list
  4. The resulting subset of items from list is carried through to the next iteration, where the next function is applied as a filter
  5. The result is saved as a new array into filteredList
  6. 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.

Discussion (0)