I have been asked to print arbitrary multiplication tables for kids.
Note the usage of 'bind', very handy, and the absence of 'for loops'.
function mul (x, y) {
return x * y
}
function multTables(tables = []) {
tables.map(n => {
let mulby = mul.bind(null, n)
app.innerHTML += `
<div>
<ul>
${[...Array(10)]
.map((_, v) => v + 1)
.map(mulby)
.map((x, i) => `
<li>
<span>${n}</span>
<span>x</span>
<span>${i + 1}</span>
<span>=</span>
<span class="result">${x}</span>
</li>`
).join('')}
</ul>
</div>`
});
}
multTables([3, 4, 6, 13])
Result :
You can play with it here : Tables
Top comments (6)
Hy, is there any advantage of not using "for"-loops?
Hy Eckehard,
When you mainly use composition, for loops are not very easy to use.
I invite you to discover what is really functional programming, map, filter, reduce, transducers, monads ...
It s not a replacement of POO, but a complement.
You will see then why for loop is not the most used construct.
Look here : vonheikemen.github.io/devlog/tags/...
There are situations when using chained functions is handy, but here we have a simple 2-dimensional loop. So, it would be most logical to use a simple 2-dimensional loop instead of any sophisticated structure:
It´s hard to see how the functional approach should be "easier" in any respect? For me it is just more confusing.
I see your point, but for me , what is confusing is having to deal with indexes when I only want to apply a function to a collection.
At this level, it is a matter of taste...
Exactly. And different tastes make our world rich, so it´s nice to know different solutions :-) .
You are wise Eckehard :-)