A looping function with a callback

from jquery ninja book

by dandoyon

HTML

<ul id="results"></ul>

CSS

#results li.pass { color: green; }
#results li.fail { color: red; }

JavaScript

function assert(value, desc) {
    var li = document.createElement("li");
    li.className = value ? "pass" : "fail";
    li.appendChild(document.createTextNode(desc));
    document.getElementById("results").appendChild(li);
}

function loop(array, fn) {
    for (var i = 0; i < array.length; i++) {
        // array is context
        if (fn.call(array, array[i], i) === false) {
            break; // stop looping if function returns false
        }
    }
}
var num = 0;
var numbers = [4, 5, 6];
loop(numbers, function(value, n) {
    assert(this === numbers, "Context is correct.");
    assert(n == num++, "Counter is as expected.");
    assert(value == numbers[n], "Value is as expected.");
});