Re-implementation of Javascript’s Array.prototype.concat()


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Just for fun I decided to see if I could write a faster version of `Array.prototype.concat()`.

var concat = function (arr) {
	var args = arguments,
	len = args.length,
	ArrayTypeOf = "[object Array]",
	toString = Object.prototype.toString,
	push = Array.prototype.push;
 
	for (var i = 1; i < len; i++) {
		if (toString.call(args[i]) === ArrayTypeOf) {
			push.apply(arr, args[i]);
		} else {
			arr.push(args[i]);
		}
	}
	return arr;
};

Benchmark Script.

console.time("native concat()");
for(var i = 0, len = 2020; i < len; i++) console.log( [].concat( new Array(1000).join("ax").split("") ).length );
console.timeEnd("native concat()");
 
console.time("custom concat()");
for(var i = 0, len = 2020; i < len; i++) console.log( concat( [], new Array(1000).join("ax").split("") ).length );
console.timeEnd("custom concat()");

Benchmark results:

native concat(): 386.000ms
custom concat(): 400.000ms

Well, I got quite close but didn’t surpass the raw power of native code.
Here are some other alternatives to concat but with limited functionality.
http://jsperf.com/concat-vs-push-apply/19

Code of the Day: Chop up an array into groups using Underscore.js


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Shrink an array into a group of smaller arrays using underscore.js

// Make sure to include underscore.js 
_.mixin({
    chunk : function (array, unit) {
        if (!_.isArray(array)) return array;
        unit = Math.abs(unit);
        var results = [],
        length = Math.ceil(array.length / unit);
 
        for (var i = 0; i < length; i++) {
            results.push(array.slice( i * unit, (i + 1) * unit));
        }
        return results;
    }
});

Example:

JSON.stringify( _.chunk([1,2,3,4,5,6,7,8,9], 2) ); 
// returns "[[1,2],[3,4],[5,6],[7,8],[9]]"

Here’s the same thing without using Underscore.js

var chunk = function (array, unit) {
	if (typeof array !== "object")
		return array;
	unit = Math.abs(unit);
	var results = [],
	length = Math.ceil(array.length / unit);
 
	for (var i = 0; i < length; i++) {
		results.push(array.slice(i * unit, (i + 1) * unit));
	}
	return results;
}

Tutorial – VIM in under 30 minutes

“Vim is a text editor written by Bram Moolenaar and first released publicly in 1991. Based on the vi editor common to Unix-like systems, Vim is designed for use both from a command line interface and as a standalone application in a graphical user interface.”

From: Wikipedia.org

The vi/vim editor – Lesson 1

The vi Editor – Lesson 2 – Navigation Commands

The vi Editor – Lesson 3 – Inserting Text

The vi Editor – Lesson 4 – Deleting Text

VI/VIM CheatSheet

Download VIM here

Code of the day – FizzBuzz in Javascript


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

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