DEV Community

Robert Mion
Robert Mion

Posted on

3 2

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay