Monthly Archives: October 2012

Code of the day – FizzBuzz in Javascript

FizzBuzz Test

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

c2.com

Here’s my solution:
Test Driven Development Approach

// TDD Readable
var getFizzBuzzStatements = function (len) {
	var arr = [],
	str = "";
	for (var i = 1; i <= len; i++) {
		str = (i % 3) ? "" : "Fizz";
		str += (i % 5) ? "" : "Buzz";
		arr.push(str||i);
	}
	return arr;
};
var fizzBuzz = function () {
	console.log(getFizzBuzzStatements(100).join("\n"));
};
fizzBuzz();

Alternative: One liner

// One liner
for (i = 1; i <= 100; i++)
	console.log((((i % 3) ? "" : "Fizz") + (i % 5 ? "" : "Buzz")||i) + "\n")

Alternative: Switches

var getFizzBuzzStatements = function (len) {
	var j,
	arr = [];
	for (var i = 1; i <= len; i++) {
		switch (i % 15) {
		case 0:
			arr.push("FizzBuzz");
			break;
		case 3:	case 6:	case 9:	case 12:
			arr.push("Fizz");
			break;
		case 5:	case 10:
			arr.push("Buzz");
			break;
		default:
			arr.push(i);
		}
	}
	return arr;
};
var fizzBuzz = function () {
	console.log(getFizzBuzzStatements(100).join("\n"));
};

Demo

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

More Posts - Website

Follow Me:
Twitter

Ratio.js – Fractions for javascript

Hey Everyone,
I created a project called Ratio.js. Basically the goal of the project is to provide an simple object for dealing with fractions in javascript.
Check it out here and tell me what this.

Ratio.js

Sample Code

 
// converts decimal values into the form of a fraction.
a = Ratio.parse(1/2);
a.toString() == "1/2";
 
// converts strings in the form of "a/b" to a fraction a/b.
a = Ratio.parse( "1/2" );
a.toString() == "1/2";
 
var result = Ratio.parse( 12.12121212121212 ).reduce().toString();
result == "400/33";

Simple Demo

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

More Posts - Website

Follow Me:
Twitter