DEV Community

artydev
artydev

Posted on • Updated on

Print Multiplication Tables

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])

Enter fullscreen mode Exit fullscreen mode

Result :

Image description

You can play with it here : Tables

Top comments (6)

Collapse
 
efpage profile image
Eckehard

Hy, is there any advantage of not using "for"-loops?

Collapse
 
artydev profile image
artydev • Edited

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/...

Collapse
 
efpage profile image
Eckehard

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:

function mkTable(ar) {
    let i, k, u
    for (k of ar) {
        u = []
        for (i = 1; i < 11; i++)
            u.push(
                `<span>${k}</span>
                <span> * </span>
                <span>${i}</span>
                <span> = </span>
                <span class="result">${i * k}</span>`)
        div(ul(u),{class: "app"})
    }
}
mkTable([3, 4, 6, 13])
Enter fullscreen mode Exit fullscreen mode

It´s hard to see how the functional approach should be "easier" in any respect? For me it is just more confusing.

Thread Thread
 
artydev profile image
artydev

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...

Thread Thread
 
efpage profile image
Eckehard

Exactly. And different tastes make our world rich, so it´s nice to know different solutions :-) .

Thread Thread
 
artydev profile image
artydev

You are wise Eckehard :-)