zondag 13 april 2014

Simplicity please

Sometimes programmers choose programmer solutions, which really can be too complex.

So I think this ...
function stringRepeat(str, num) {
    num = Number(num);
    var result = '';
    while (true) {
        if (num & 1) { // (1)
            result += str;
        }
        num >>>= 1; // (2)
        if (num <= 0) break;
        str += str;
    }
    return result;
}
[Found @ ②ality – JavaScript and more]

... (though nifty and nice code) can be replaced by:
function stringRepeat(str, num) {
    return Array( (num || 1) + 1 ).join(str);
}

Where num || 1 ensures that the initial string is always returned, even if num is not passed in the method call.

1 opmerking:

all out alien zei

We now have String.prototype.repeat