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

It turned out that was a lot harder than I had originally thought... Here's what I did.

first attempt

function superMin() {
    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

Block of code above looks terrible for anyone, but it gets the job done at least..

Second attempt

function superMin() {
    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

Decided to replace while loop with for loop. It still needs to compare first argument and second argument then the winner will be used to compare the rest. It looks slightly cleaner than the first one but do I 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

I 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 done 💯

Clone this wiki locally