eshellborn eshellborn - 1 month ago 16
Javascript Question

Javascript call a function several times with the arguments

This isn't totally necessary, I'm just trying to simplify my code. This is what I have:

function fillWebsitePlaceFiller(number) {
document.getElementById("placefillerWebsite" + number).innerHTML = placefillerWebsite;
}

fillWebsitePlaceFiller(1);
fillWebsitePlaceFiller(2);
fillWebsitePlaceFiller(3);
fillWebsitePlaceFiller(4);
fillWebsitePlaceFiller(5);
fillWebsitePlaceFiller(6);
fillWebsitePlaceFiller(7);


Is there a way I can call the function just once, and it will run through it 7 times with each argument?

Answer

Method 1 - iteration

for (int i = 1; i < 8; i++) fillWebsitePlaceFilter(i);

Method 2 - recursion

(function repeat(number) {
    fillWebsitePlaceFiller(number);
    if (number < 7) repeat(number + 1);
})(1);

Method 3 - functor application

[1, 2, 3, 4, 5, 6, 7].forEach(fillWebsitePlaceFiller);

Method 4 - internal iteration

function fillWebsitePlaceFiller(times) {
    for (var number = 1; number <= times; number++) {
        document.getElementById("placefillerWebsite" + number).innerHTML = placefillerWebsite;
    }
}

Method 5 - extend function behaviour

Function.prototype.sequence = function(from, to) {
    for (var i = from; i <= to; i++) this.call(null, i);
};

fillWebsitePlaceFiller.sequence(1, 7);

Method 6 - XPath (warning: not tested)

var query = '//*[@id[starts-with(., "placefillerWebsite"]]';
var result = document.evaluate(query, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
while (var node = result.iterateNext()) node.innerHTML = placefillerWebsite;