mykeels.com

The Relay Function Challenge

Some time back, I posted a tiny challenge in the JavaScript channel on Devcenter Square, and in a few minutes, there were awesome replies.

The Relay Function Challenge

Some time back, I posted a tiny challenge in the JavaScript channel on Devcenter Square, and in a few minutes, there were awesome replies.

The Challenge

Write a JavaScript function that takes in as many arguments as possible which are all functions. 
Each of these function arguments is executed one after the other, if and only if:
- it is the first function in the argument list
- or the previous function returns a truthy value

It’s like a relay switch in electronics which is used in making Christmas lights.

Christmas Lights on Display

Electric current flows through all the bulbs one by one, and if one bulb dies, all the other bulbs on the rest of the wire will not light up again, even if they are capable of lighting up.

The Answer

One really good answer to the challenge is

relay(...fns) {
  return fns.reduce((status, fn) => status && fn(), true) 
}

It makes use of the JavaScript spread operator to represent the arguments, so they can be handled like an Array.

So, to use relay, it would look something like:

relay(fn1, fn2, fn3 ...)

Where fn1, fn2, fn3 are JavaScript functions that may or may not return true.

The answer also used Array.prototype.reduce to well, reduce the function arguments array to a Boolean using the && operator.

Let’s Amp it up!

One way to amp up the challenge is to make it possible to pass arguments to the functions that the relay executes.

So, relay can return a function (making relay a higher-order function) which takes in arguments that are passed to the function arguments that were passed to relay.

Wow, that was a mouthful (fingerful?)!

Here’s the code:

relay(...fns) {
    return (...args) => {
        fns.reduce((status, fn) => {
            if (status)
               return fn(...args)
            else return false;
        }, true)
    }
}

Related Articles

Tags