Skip to content

Writing a function returns minimum value

Daisho Komiyama edited this page Apr 16, 2018 · 7 revisions

While reading Eloquent JavaScript, I was challenged this exercise.

Create a function which takes as many parameters as it can and returns minimum value among them.

It is like writing Math.min() from scratch. It sounded super easy when I read it.

But it turned out a lot harder than I had originally thought.

Here's what I did.

First attempt

function myMathMin() {
    var winner;
    var i = 0;
    var j = 1;
    if (arguments[0] < arguments[1])
        winner = arguments[0];
    else
        winner = arguments[1];

    while (i < arguments.length) {
        if (winner > arguments[j])
            winner = arguments[j];
        i++;
        j++;
    }
    return winner;
}

myMathMin(2, 3, 1, -10);
// -10
// Works!

I know block of code above looks terrible for anyone's eye, but it gets the job done at least..

Second attempt

function myMathMin() {
    var winner;
    var i = 0;
    var j = 1;
    if (arguments[i] < arguments[j])
        winner = arguments[i];
    else
        winner = arguments[j];
    
    for (var i = 0, j = 1; i < arguments.length; i++, j++) {
        if (winner > arguments[j])
            winner = arguments[j];
    }
    
    return winner;
}
myMathMin(2, 3, 1, -10);
// -10
// Still works!

Decided to replace while loop with for loop. It is still comparing first argument and second argument to create the winner. Then winner value is used to compare the rest. It looks slightly cleaner than the first one but it made me wonder I do still need to compare first argument and second argument to evaluate the rest?

Last attempt

function myMathMin() {
    var challenger = arguments[0];
    for (var i = 0, j = 1; i < arguments.length; i++, j++) {
        if (challenger > arguments[j])
            challenger = arguments[j];
    }
    return challenger;
}

myMathMin(2, 3, 1, -10);
// -10
// This is the best

I finally noticed that I didn't need to compare first and second arguments at all! All I needed was to create a challenger out of any argument (I chose first argument for simplicity) then put it in a competition against the rest which is for loop. This is how the job gets done 💯

Clone this wiki locally