Best practice of creating object from reduce

Asked

Viewed 76 times

1

I wrote an algorithm using reduce which creates an object with two other objects inside, however I found unreadable.

In search of inspiration to refactor the algorithm I ended up searching in codegrepper and google, but I did not get.

I believe that the algorithm is relatively easy and used within systems, if anyone makes a suggestion I will be grateful.

Follow code I wrote firsthand:

let isbns = [
    '64646464',
    '978-8575228050',
    '978-8573076103',
    '6586057043'
]
let links = ['Nenhum resultado para 64646464.',
    '/Problemas-Cl%C3%A1ssicos-Ci%C3%AAncia-Computa%C3%A7%C3%A3o-Python/dp/8575228056',
    '/Padr%C3%B5es-Projetos-Solu%C3%A7%C3%B5es-Reutiliz%C3%A1veis-Orientados/dp/8573076100',
    '/Migrando-Sistemas-Monol%C3%ADticos-Para-Microsservi%C3%A7os/dp/6586057043'
]

const validatingIsbn = (isbns, links) => {
    let invalidos = {}, validos = {}
    return isbns.reduce((obj, isbn, index) => {
        let result 
        if (links[index] == `Nenhum resultado para ${[isbn]}.`) {
            let invalido = Object.assign(invalidos, {[isbn] : links[index]})
            result = {...obj, invalido}
        } else {
            let valido = Object.assign(validos, {[isbn] : links[index]})
            result = {...obj, valido}
        }
        return result
    }, {})
}

console.log(validatingIsbn(isbns, links))

1 answer

8

Best practice to use reduce is: do not use reduce where it is not appropriate to use that method.

reduce is a very flexible method, you can use it to create new arrays, create objects, filter elements, apply mathematical operations, but the method is not very idiomatic for most of these uses (the last being the exception).

Using it to calculate the total values contained in an object array is simple and idiomatic, you might even call it elegant. Use it to create an object indexed with array values, not so much, no readability gains or lines of code.

So, my suggestion, something totally subjective and not applicable the answer of this site, but what I’m giving anyway, is not using the reduce for these scenarios.

And here’s a hint of how to refactor function to a way that I see as more readable:

function validatingIsbn(isbns, links) {
    const validos = {}, invalidos = {};

    for (let i = 0; i < links.length; i++) {
        const categoria = links[i] === `Nenhum resultado para ${isbns[i]}` ? invalidos : validos;
        categoria[isbns[i]] = links[i];
    }

    return { validos, invalidos };
}
  • 4

    In fact I would say that it is appropriate to the site yes because its argument has some foundation behind. Exit using reduce everywhere, as many people do, can greatly impair the readability of the code. Good conclusion and useful response. :)

  • 2

    Perfect, not only the for is simpler and clear, as it is most often more efficient, because with reduce there is a function call for each element of the array (that cost is usually neglected because for a few small arrays, the difference is not noticeable). Anyway, in this case - and in many others - the gain in readability is another advantage of the simple loop. And as already said, your response is reasonable to the site yes, because it has foundation (unlike many "fanatics" who advocate the use of reduce for everything, claiming that "functional is better" and other fallacies...)

  • 3

    It’s worth the same to map and other "shortenings" of meaningless code. Unfortunately the weak people of theory use these things indiscriminately all the time (unfortunately the vast majority of "programmers" will never be true, but the market absorbs by absurd few qualified people). It’s not just about readability, it’s about total waste of resources. Use reduce, map and similar where perfectly fit a for is usually a sign of unprepared.

  • 1

    Here is a comparison between the for simple vs reduce (the for is much faster): https://jsbench.me/k7ks9594pm/1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.