Monthly Archives: March 2012

Code of the day: Get unique objects from an array of json objects.

Inspired from Removing duplicate objects with Underscore for Javascript

Source:

/**
@function _.uniqObjects
@require Underscore.js and json.stringify
@purpose return an array of objects without duplicated objects.
*/
_.uniqObjects = function( arr ){
	return _.uniq( _.collect( arr, function( x ){
		return JSON.stringify( x );
	}));
};

Example:

var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];
_.uniqObject( foo );  // returns [ { "a" : "1" }, { "b" : "2" } ]

Larry Battle

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

More Posts - Website

Follow Me:
Twitter

Reimplementation of Number.prototype.toFixed

Number.prototype.toFixed was giving me too many problems, so I just rewrote it.
There’s the source.

/**
@author Larry Battle <a alt="contact me" href="bateru.com/news/contact">Contact Me</a>
@date	Mar 30, 2012
@purpose Provide the fix for Number.prototype.toFixed() function.
@info source at http://bateru.com/news/2012/03/reimplementation-of-number-prototype-tofixed
 */
Number.prototype.toFixed_fix = function (precision) {
	var num = this.toString(), zeros = '00000000000000000000', newNum, decLength, factor;
	if (0 > precision || precision > 20) {
		throw new RangeError("toFixed() digits argument must be between 0 and 20");
	}
	if (Math.abs(num) === Infinity || Math.abs(num) >= 1e21) {
		return num;
	}
	precision = parseInt(precision, 10) || 0;
	newNum = num = isNaN(parseInt(num, 10)) ? '0' : num;
	if (/\./.test(num)) {
		decLength = num.split('.')[1].length;
		if (decLength < precision) {
			newNum += zeros.substring(0, precision - decLength);
		} else {
			factor = Math.pow(10, precision);
			newNum = Math.round(num * factor) / factor;
		}
	} else {
		if (precision) {
			newNum += '.' + zeros.substring(0, precision);
		}
	}
	return newNum;
};

Test cases here

Want to learn more about Javascript?
Checkout this ‘Professional JavaScript for Web Developers’.

Larry Battle

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

More Posts - Website

Follow Me:
Twitter

Code of the day: Fix for Number.prototype.toFixed

In javascript, Number.prototype.toFixed has problems rounding.
Here’s the fix and some test cases.

Number.prototype.toFixed = (function () {
	var oldToFixed = Number.prototype.toFixed;
	return function (precision) {
		var value = this.toString(), power = Math.pow(10, precision || 0);
		return oldToFixed.call((Math.round(value * power) / power), precision);
	};
}());


Here’s a simple test.

// Programmer: Larry Battle
// Link: http://bateru.com/news/2012/03/code-of-the-day-fix-for-number-prototype-tofixed
(function (root) {
	"use strict";
	var log = function( str ){
		root.document.body.innerHTML += "log: " + str + "<br/>";
	},
	assert = function (a, b ) {
		var message = a + ' !== ' + b;
		message += ( a === b ) ? "=> true" : "=> false";
		log( message );
	};
	assert((0.595).toFixed(2), "0.59");
	assert((0.9).toFixed(0), "1");
	Number.prototype.toFixed = (function () {
		var oldToFixed = Number.prototype.toFixed;
		return function (precision) {
			var value = this.toString(), power = Math.pow(10, precision || 0);
			return oldToFixed.call((Math.round(value * power) / power), precision);
		};
	}
		());
	log("Applying the toFixed fix.");
	assert((0.595).toFixed(2), "0.60");
	assert((0.9).toFixed(0), "1");
}(this));

Demo: Link

Update!
Improved code here

Larry Battle

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

More Posts - Website

Follow Me:
Twitter

Javascript Error: ParseInt fails when supplied with large numbers

ParseInt returns 1 for when passed any number greater or equal to 1e+21.

var x = 1.0e+2;
console.log( x == 1e+2 );
console.log( parseInt( x, 10 ) == 100 );
console.log( parseFloat( x ) == 100 );
 
var x = 1.0e+21;
console.log( x == 1e+21 );
console.log( parseInt( x, 10 ) == 1 );
console.log( parseFloat( x ) == 1e+21 );

What do you think the problem is?
I think the problem by be because numbers 1e+21 and greater are represented as strings.
ParseInt might only be looking at valid numbers to parse the number to into an integer. Since e in ‘1e21’ is not a number, 1 is the item returned.

Demo: jsbin.com demo

Update:
V8 Issue Page

Larry Battle

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

More Posts - Website

Follow Me:
Twitter