Tuesday, July 21, 2020

Seduced by reduce

It's hard to resist functional programming.

Functional programming helps us eliminate side-effects in code.

reduce function is one of those functions that let the developer adhere to functional programming paradigm.

However, there's no built-in way to break early from reduce's iteration. Why we need to break early? Optimization of course.

There's a way to break early from reduce's iteration, empty out the array so it won't have anything to iterate on next. splice can do the job of emptying out the array.

splice can introduce side-effects if the code is working on source input, or if there's another statement that depends on splice's source array.

With that said, in the code below there's no side effects since there's no way that splice can alter the input argument (str), and the str argument is not the source array of splice. There's no side-effects too as there's no succeeding statement that depends on slice's source array after the slice below executes.

const fearNotLetter = str => 
    str.split('').reduce((currentLetter, nextToCurrentLetter, currentLetterIndex, letters) => 
        currentLetter.charCodeAt(0) + 1 === nextToCurrentLetter.charCodeAt(0) ?
            (currentLetterIndex < str.length - 1 ? nextToCurrentLetter : undefined)
        :  
            (letters.splice(currentLetterIndex), String.fromCharCode(currentLetter.charCodeAt(0) + 1))
    );


console.log(fearNotLetter("abce"));
console.log(fearNotLetter("abcdefghjklmno"));
console.log(fearNotLetter("stvwx"));
console.log(fearNotLetter("bcdf"));
console.log(fearNotLetter("abcdefghijklmnopqrstuvwxyz"));
Output:
d
i
u
e
undefined
Puzzle from: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/missing-letters

No comments:

Post a Comment