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

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

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));``` ```

Update!
Improved code here

Larry Battle

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

Code of the day: Converts Bytes to Simplify Units

A few days ago I noticed that my “code of the day” article was wrong. So I spent some time fixing it and provided test cases to check my work.
The main difference about this script is that it allows you to support both the SI and IEC standard and fixes a few rounding errors.

``` ```// function: getBytesWithUnit // input: bytes (number) // input: useSI (boolean), if true then uses SI standard (1KB = 1000bytes), otherwise uses IEC (1KiB = 1024 bytes) // input: precision (number), sets the maximum length of decimal places. // input: useSISuffix (boolean), if true forces the suffix to be in SI standard. Useful if you want 1KB = 1024 bytes // returns (string), represents bytes is the most simplified form. var getBytesWithUnit = function (bytes, useSI, precision, useSISuffix) { "use strict"; if (!(!isNaN(bytes) && +bytes > -1 && isFinite(bytes))) { return false; } var units, obj, amountOfUnits, unitSelected, suffix; units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; obj = { base : useSI ? 10 : 2, unitDegreeDiff : useSI ? 3 : 10 }; amountOfUnits = Math.max(0, Math.floor(Math.round(Math.log(+bytes) / Math.log(obj.base) * 1e6) / 1e6)); unitSelected = Math.floor(amountOfUnits / obj.unitDegreeDiff); unitSelected = units.length > unitSelected ? unitSelected : units.length - 1; suffix = (useSI || useSISuffix) ? units[unitSelected] : units[unitSelected].replace('B', 'iB'); bytes = +bytes / Math.pow(obj.base, obj.unitDegreeDiff * unitSelected); precision = precision || 3; if (bytes.toString().length > bytes.toFixed(precision).toString().length) { bytes = bytes.toFixed(precision); } return bytes + " " + suffix; };``` ```

Demo: Test Script here

Check out this “Professional JavaScript for Web Developers”.

Larry Battle

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

Code of the Day: Javascript Decimal To Fraction

Source: mivk from StackOverflow.com
Code

```/** @function dec2frac @returns string @purpose Convert a decimal to a fraction */ function dec2frac(d) { var df = 1, top = 1, bot = 1; var limit = 1e5; //Increase the limit to get more precision.   while (df != d && limit-- > 0) { if (df < d) { top += 1; } else { bot += 1; top = parseInt(d * bot, 10); } df = top / bot; } return top + '/' + bot; }```

Demo

Example Output
dec2frac ( 0.1) returns “1/10”
dec2frac ( 0.2) returns “1/5”
dec2frac ( 0.5) returns “1/2”
dec2frac ( 0.9999) returns “9999/10000”
dec2frac ( 0.75) returns “3/4”
dec2frac ( 2.718281828459045) returns “135915/50000”, but this evaluates to 2.7183
dec2frac ( 3.141592653589793) returns “157079/50000”, but this evaluates to 3.14158

Larry Battle

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