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

It

Clone this wiki locally