Skip to content

Instantly share code, notes, and snippets.

@aisuii
Created June 23, 2011 09:26
Show Gist options
  • Save aisuii/1042224 to your computer and use it in GitHub Desktop.
Save aisuii/1042224 to your computer and use it in GitHub Desktop.
function fibs(n) {
var generator = (function(){
var beforeNum = 0;
var nextNum = 1;
var resultNum;
var f = function() {
resultNum = beforeNum;
beforeNum = nextNum;
nextNum = resultNum + nextNum;
return resultNum;
};
return f;
})();
var counter = 0;
var result = [];
while (counter < n) {
result.push(generator());
counter++;
}
return result;
}
function isPrime(n) {
var counter = 2;
if (n <= 1) return false;
while (counter < n) {
if (n % counter == 0) return false;
counter++;
}
return true;
}
function fizzbuzz(n) {
var result = [];
var counter = 1;
while (counter <= n) {
if (counter % 15 == 0)
result.push('FizzBuzz');
else if (counter % 5 == 0)
result.push('Fizz');
else if (counter % 3 == 0)
result.push('Buzz');
else
result.push(counter);
counter++
}
return result;
}
function pyramidString(n) {
var times = function(timesNum, f) {
var counter = 0;
while(counter < timesNum) {
f(counter);
counter++;
}
};
var formatter = function (stepNum, pad) {
var str = "";
times(pad, function() { str += " "; });
times(stepNum, function() { str += "*"; });
times(stepNum - 1, function() { str += "*"; });
return str;
};
var results = [];
times(n, function(i){ results.push(formatter(i + 1, n - i + 1)); });
return results.join("\n");
}
function commaize(n) {
var numStr = "" + n;
var tmpDigit = "";
var digits = [];
while (numStr.length >= 4) {
tmpDigit = numStr.slice(-3);
numStr = numStr.slice(0, -3);
digits.unshift(tmpDigit);
}
if (numStr.length > 0) digits.unshift(numStr);
return digits.join(',');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment