javascriptfor-loopfunctional-programmingdeclarative-programming

javascript functional / declarative version of for loop (with this example)?


Having this code

const myMagic = (one, two, three, four) => `this is ${one} and ${two} and ${three} and ${four} as usual`

const txt = 'HELLO&ho&hy&hu&hq&HELLO&ho&hy&hu&hq&HELLO&ho&hy&hu&hq&HELLO&ho&hy&hu&hq&hx'
const fragments = txt.split('&')
const pieces = []

for (let i=0; i<fragments.length-1;i +=5) {
  pieces.push(fragments[i])
  pieces.push(myMagic(fragments[i+1],fragments[i+2],fragments[i+3],fragments[i+4]))
}

pieces.push(fragments[fragments.length-1])

console.log(pieces)

How could I transform it into a more declarative version?

The code is like that since the split is taking a regexp that parses the text only once, and then with these fragments I'm building as many components as needed with myMagic function

So is there any way to write this in a more declarative way without altering the logic?


Solution

  • You can always go for a recursive function to traverse lists:

    const myMagic = (one, two, three, four) => `this is ${one} and ${two} and ${three} and ${four} as usual`
    
    function pieces([zero, ...rest]) {
        if (!rest.length)
            return [zero];
        const [one, two, three, four, ...more] = rest;
        return [zero, myMagic(one, two, three, four), ...pieces(more)];
    }
    
    const txt = 'HELLO&ho&hy&hu&hq&HELLO&ho&hy&hu&hq&HELLO&ho&hy&hu&hq&HELLO&ho&hy&hu&hq&hx';
    console.log(pieces(txt.split('&')))

    I'd recommend to use some kind of chunk(5) function though and flatMap over its result.