DEV Community

Discussion on: What’s your alternative solution? Challenge #3

Collapse
 
aminnairi profile image
Amin

I prefered to return an array of objects containing all the part of the multiplication, and let the developer-user of the function choose how to format the output, that way it makes it an O(n) solution.

"use strict";

const printMultiplicationTable = (limit, number, callback, ...parameters) => {
    if (0 !== parameters.length) {
        throw new ReferenceError("too much parameters");
    }

    if ("number" !== typeof limit) {
        throw new TypeError("first argument expected to be a number");
    }

    if (!Number.isInteger(limit)) {
        throw new TypeError("first argument expected to be an integer");
    }

    if (1 > limit) {
        throw new RangeError("first argument expected to be greater than zero");
    }

    if ("number" !== typeof number) {
        throw new TypeError("second argument expected to be a number");
    }

    if (!Number.isInteger(number)) {
        throw new TypeError("second argument expected to be an integer");
    }

    if (1 > number) {
        throw new RangeError("second argument expected to be greater than zero");
    }

    if ("function" !== typeof callback) {
        throw new TypeError("third argument expected to be a function");
    }

    for (let index = 0; index < limit; index++) {
        const current = index + 1;

        if (1 !== callback.length) {
            throw new Error("third argument expect to be a function receiving only one argument");
        }

        callback({
            operand1: number,
            operand2: current,
            result: number * current
        });
    }
}

printMultiplicationTable(10, 7, ({operand1, operand2, result}) => {
    console.log(`${operand1} * ${operand2} = ${result}`);
});

// 7 * 1 = 7
// 7 * 2 = 14
// 7 * 3 = 21
// 7 * 4 = 28
// 7 * 5 = 35
// 7 * 6 = 42
// 7 * 7 = 49
// 7 * 8 = 56
// 7 * 9 = 63
// 7 * 10 = 70
Enter fullscreen mode Exit fullscreen mode