Code of the day: Javascript convert bytes to KB, MB, GB, etc


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: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94

Note: This uses the IEC standard. That means 1 KB = 1024, not 1000 like the SI standard.

/**
* @function: getBytesWithUnit()
* @purpose: Converts bytes to the most simplified unit.
* @param: (number) bytes, the amount of bytes
* @returns: (string)
*/
var getBytesWithUnit = function( bytes ){
	if( isNaN( bytes ) ){ return; }
	var units = [ ' bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB' ];
	var amountOf2s = Math.floor( Math.log( +bytes )/Math.log(2) );
	if( amountOf2s < 1 ){
		amountOf2s = 0;
	}
	var i = Math.floor( amountOf2s / 10 );
	bytes = +bytes / Math.pow( 2, 10*i );
 
	// Rounds to 3 decimals places.
        if( bytes.toString().length > bytes.toFixed(3).toString().length ){
            bytes = bytes.toFixed(3);
        }
	return bytes + units[i];
};

Output:

console.log( getBytesWithUnit( ) );			// returns undefined.
console.log( getBytesWithUnit( 'non a number.' ) );	// returns undefined.
console.log( getBytesWithUnit( '123' ));		// returns '123 bytes'.
console.log( getBytesWithUnit( 1024 ));		// returns '1 KB'.
console.log( getBytesWithUnit( (1024 * 1024) + 1024 )); // returns '1.001 MB'.
console.log( getBytesWithUnit( 1024 * 1024 * 1024 )); // returns '1 GB'.
console.log( getBytesWithUnit( 1024 * 1024 * 64 )); // returns '64 MB'.

Update
I updated the script to support both the SI and IEC standard.
Check it out here http://bateru.com/news/2012/03/code-of-the-day-converts-bytes-to-unit/

Larry Battle

Larry Battle

I love to program, and discover new tech. Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube

Code of the day: Check to see if a element has a event.


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: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94
// hasEvent checks to see if a element contains a event.
// @requires jQuery 1.3.2+
// @params el: string, jQuery object, node element.
// @params eventName: string, name of the event.
// @returns boolean
var hasEvent = function( el, eventName ){
	if( !$( el ).length || !$( el ).data( 'events' ) ){
		return false;
	}
	return !!$( el ).data( 'events' )[ eventName ];
};

Demo: (requires firebug or google chrome)

var el = $( '<div/>' ).click( $.noop );
console.clear();
console.log( hasEvent( el, 'click' ) );// returns true;
 
console.log( hasEvent( el, 'focusNow' ) );// returns false;
el.bind( 'focusNow', $.noop );
console.log( hasEvent( el, 'focusNow' ) );// returns true;
 
console.log( hasEvent( document.body, 'onload' ) );// returns false;
$(document.body).bind( 'onload', $.noop );
console.log( hasEvent( document.body, 'onload' ) );// returns true;
Larry Battle

Larry Battle

I love to program, and discover new tech. Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube

jQuizMe Example: Simple Math Quiz


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

Warning: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94

Here’s an example of jQuizMe.
Goal: Make a quiz for Addition, Subtraction and Multiplication for two digit numbers.

Steps:

  1. Make a random number generator.
  2. Make a function to form a question and answers.
  3. Form the quiz.
  4. Call jQuizMe

Step 1:
I wrote a random number generator in javascript here.

1
2
3
4
var getRandomNum = function( i, decLen ){
	var powOf10s = Math.pow( 10, decLen || 0 );
	return i ?  Math.floor( powOf10s * Math.random() * i ) / powOf10s : Math.random();
};

Or.. you could just use Math.floor( Math.random() * number ).

Step 2 & 3: (Due to time constraints I combined step 2 and 3.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var link = "http://bateru.com/news/2011/04/learn-sig-figs-in-no-time/";
var ops = operations = [ " + ", " - ", " * ", " / " ];
var precision = 2;
 
var arrOfRandomNum = function( arrLength, max, decLen ){
	if( arrLength < 0 ){ return false; }
	var arr = [], i = arrLength;
	while( i-- ){
		arr[ i ] = getRandomNum( max, decLen );
	}
	return arr;
};
var makeQuiz = function(){
	var quiz = { "fill":[] };
	var question = '', nums = [];
	var i = questionLength = 10;
	while( i-- ){
		nums = arrOfRandomNum( 2, 19 );
		question = nums.join( ops[ getRandomNum( ops.length ) ] );
		quiz.fill.push({
			ques: question,
			ans: eval( question ).toPrecision(precision)
		});
	}
	return quiz;
}

Step 4:

1
2
3
$( "#quiz" ).jQuizMe( makeQuiz(), {
	intro: ops.join(',') + " quiz.<br>Note: Your answer must have " + precision + " <a href='"+link+"'>sig figs</a>."
});

Here’s the working demo.

Larry Battle

Larry Battle

I love to program, and discover new tech. Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube

Code of the Day: Javascript Fibonacci Numbers the fast way


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: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94
1
2
3
4
5
6
7
8
//Programmer: Larry Battle
//Date: April 18, 2011
//Purpose: Get Fibonacci numbers in O(1) time.
var getFibonacciNum = function( n ){
    var s5 = Math.sqrt(5);
    var phi1 = (1+s5)/2, phi2 = (1-s5)/2;
    return Math.round((Math.pow( phi1, n ) - Math.pow( phi2, n) )/s5);
};

Demo:

Output for 0 to 4

F(0) = 0
F(1) = 1
F(2) = 1
F(3) = 2
F(4) = 3
Larry Battle

Larry Battle

I love to program, and discover new tech. Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube