function repeat(str, num) {
var singles = [];
if (num <= 0){
repeatedStr="";
}
for(i=0;i<num;i++){
singles.push(str);
repeatedStr = singles.join("");
}
return repeatedStr;
}
repeat("abc", 3);
Critics:
- I still make stupid mistakes regarding variables scope and had at first put
var singles = []; inside the for loop...- I repeat myself when instead of directly returning
singles.join("") I assign it first to repeatedStr. Only advantage I could see is if we further down the road would want to access this variable.---
Now, FFC on their wiki, have this similar one:
function repeat(str, num) {
var newstr = [];
for (var i = 0; i < num; i++) {
newstr.push(str);
};
return newstr.join('');
}
repeat("abc", 3, "");
Ok, it's still a simple one but more elegant, it gets rid of the
if condition by inserting the empty string as an argument. Since we havn't seen this in the previous Javascript Waypoints, I assume it means a sort of "false default" value. I've tried to google it but since I don't know how this notation style is named, it's very hard to find something relevant. If anyone got any idea feel free to tell in the comments.
No comments:
Post a Comment