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))
In fact I would say that it is appropriate to the site yes because its argument has some foundation behind. Exit using
reduceeverywhere, as many people do, can greatly impair the readability of the code. Good conclusion and useful response. :)– Luiz Felipe
Perfect, not only the
foris simpler and clear, as it is most often more efficient, because withreducethere 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 ofreducefor everything, claiming that "functional is better" and other fallacies...)– hkotsubo
It’s worth the same to
mapand 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.– Bacco
Here is a comparison between the
forsimple vsreduce(theforis much faster): https://jsbench.me/k7ks9594pm/1– hkotsubo