Monthly Archives: May 2012

Code of the Day: Javascript, create object without calling new on the Constructor

Here’s a simple trick to avoid having to call new on a constructor. All you have to do is have the constructor do it for you. Here’s how.

Check if the `this` variable is an instanceof of the Constructor. If not, then return a new instance of the constructor whiling passing the same arguments. `new ConstructorName(arg1, arg2, … argN)`.

If you call a constructor without using this trick, `this` will be referenced to the scope to which the constructor is contained within. Which in most cases is `window`.

Example:

var Person = function( name ){
    if(!(this instanceof Person)){
        return new Person(name);
    }
    this.name = name || "NA" ;
    return this;
};

Live Demo:*click the results tab*

Larry Battle

Hello, I'm Larry Battle and I love to program, fix problems and discover new technologies. Check out my stackoverflow and github accounts. I also do book reviews on amazon.com. I'm not the best of writers but I do enjoy spreading my knowledge through my short blogs at bateru.com/news. So please leave some feedback. It would be greatly appreciated.

More Posts - Website

Follow Me:
Twitter

Code of the Day: Javascript Decimal Expansion a.k.a Division


Today’s Code of the Day is about decimal expansion, which is just division.

So you might be asking yourself, “if decimal expansion is divsion. Then why not use a/b?”.
Well the problem is that Javascript has a ton of problems when dealing with floating point operations because of the way they are stored.

Examples:

var a = 1/3;
a.toString()     // returns  "0.3333333333333333"
a.toFixed(25);   // returns "0.3333333333333333148296163"
0.1 + 0.2;       // returns 0.30000000000000004

Source for decimalExpansion()

// borrowed from jQuery 1.7.2
var isNumeric = function(val){
	return !isNaN(parseFloat(val)) && isFinite(val);
};
/**
* @author Larry Battle <http://bateru.com/news/contact-me>
* @date May 16, 2012
* @license MIT and GPLv3
*/
//decimalExpansion returns a string representation of a divided by b to a fixed length.
// All the paramaters must be whole numbers.
// Example: decimalExpansion( 1, 3, 3 ) === "0.333"
var decimalExpansion = function (top, bottom, decLength) {
	if (!isNumeric(top) || !isNumeric(bottom) || !isNumeric(decLength) || !bottom) {
		return null;
	}
	var sign = ((top * bottom) != Math.abs(top * bottom)) ? "-" : "";
	top = Math.abs(top);
	bottom = Math.abs(bottom);
	decLength = Math.abs(decLength);
 
	var result = Math.floor(top / bottom),
	remainder = top % bottom,
	maxDecimal = 100,
	i = Math.min(Math.max(0, decLength), maxDecimal) + 1;
 
	if (1 < i) {
		result += ".";
		while (i--) {
			top = remainder * 10;
			remainder = top % bottom;
			result += "" + Math.floor(top / bottom);
		}
		result = result.replace(/(\d)(\d)$/, function (match, a, b) {
				return +b > 4 ? +a + 1 : a;
			});
	}
	return sign + result;
};

Test cases:

Demo:

Here are excellent links over the topic.
Wolfram MathWorld: Decimal Expansion
Wikipedia.org: Fraction (mathematics)
Oracle: What Every Computer Scientist Should Know About Floating-Point Arithmetic

Larry Battle

Hello, I'm Larry Battle and I love to program, fix problems and discover new technologies. Check out my stackoverflow and github accounts. I also do book reviews on amazon.com. I'm not the best of writers but I do enjoy spreading my knowledge through my short blogs at bateru.com/news. So please leave some feedback. It would be greatly appreciated.

More Posts - Website

Follow Me:
Twitter

Code of the Day: Javascript, Fix for isNaN

Javascript is a dynamically typed langauges. This feature causes for Arrays, Booleans, and other types to be converted to a numeric values depending on usage.
However this feature can cause headarches when trying to detect numbers.

For example, isNaN() detects if a value is a non-number. That’s what NaN stands for, “Not a number”.
So you might think that the opposite result from isNaN() would indicate if a value is a number.

// Works for most cases but not for strict comparisons.
var isNumber = function(val){
	return !isNaN( val );
};

Example:
Note: Click the “result” tab to run the test cases in jsfiddle.net.

Solution:
So here’s a simple fix for isNaN and isNumber.

// isNaN2 returns a boolean for if a value is not a number or +-Infinity
var isNaN2 = (function (global) {
    var _isNaN = global.isNaN;
    return function (val) {
        return _isNaN("" + val) || (typeof val === "object" && !(val || "").hasOwnProperty('push'));
    };
}(this));
// isNumeric returns a boolean for if a value is a number or +-Infinity
var isNumeric = (function (global) {
    var _isNaN = global.isNaN;
    return function (val) {
        return !_isNaN("" + val)&&(typeof val !== "object" || (val || "").hasOwnProperty('push'));
    };
}(this));


isNaN vs isNaN2

Testcases for isNaN2 and isNumeric

*Update*
Well it turns out that jQuery has a better implementation. The only difference is that infinity is not a number, which is correct.

$.isNumeric = function( obj ){
    return !isNaN( parseFloat( obj ) ) && isFinite( obj );
};


api.jquery.com/jQuery.isNumeric

Larry Battle

Hello, I'm Larry Battle and I love to program, fix problems and discover new technologies. Check out my stackoverflow and github accounts. I also do book reviews on amazon.com. I'm not the best of writers but I do enjoy spreading my knowledge through my short blogs at bateru.com/news. So please leave some feedback. It would be greatly appreciated.

More Posts - Website

Follow Me:
Twitter

Code of the Day: Javascript, Prime Factors of a Number

Javascript: Prime Factorization

Today’s code is a enhancement of Code Renaissance‘s version of “Finding Prime Numbers in Javascript”.
Main difference are the following.

  1. Faster performance by eliminating recursion and caching Math.sqrt.
  2. Whole numbers bigger than 1 return an empty array, since they’re not prime numbers.
  3. Decimal values are converted to whole numbers.

/**
* @author Larry Battle - http://bateru.com/news/contact-me
* @date May 11, 2012
* @license MIT and GPL v3
* @purpose Return the prime factors of a number.
* @info - http://bateru.com/news/?s=prime+factors
*/
var getPrimeFactors = function(num) {
    num = Math.floor(num);
    var root, factors = [], x, sqrt = Math.sqrt, doLoop = 1 < num;
    while( doLoop ){
        root = sqrt(num);
        x = 2;
        if (num % x) {
            x = 3;
            while ((num % x) && ((x += 2) < root));
        }
        x = (x > root) ? num : x;
        factors.push(x);
        doLoop = ( x != num );
        num /= x;
    }
    return factors;
}

Example:
getPrimeFactors(15120) // returns [2, 2, 2, 3, 3, 3, 7]

Demo:

Larry Battle

Hello, I'm Larry Battle and I love to program, fix problems and discover new technologies. Check out my stackoverflow and github accounts. I also do book reviews on amazon.com. I'm not the best of writers but I do enjoy spreading my knowledge through my short blogs at bateru.com/news. So please leave some feedback. It would be greatly appreciated.

More Posts - Website

Follow Me:
Twitter