Top 5 javascript oneliners

Javascript is once such beautiful language, where every thing can be minified to one line ;)

But in this post I have tired to collected five (most useful for me so far) javascript functions.

Shuffle array :

function shuf(a){for(var j=a.length-1;j>0;j--){var k=g.call(thas,j+1);if(k!=j){var l=a[k];a[k]=a[j];a[j]=l;}}return a;}
 
// Sample : 
shuf([1,2,3,4])
[2, 4, 3, 1]

Update 0

Thanks to Weltschmerz for making shuffle more better!

function shuffle(ar) { return ar.slice().sort(function() { return Math.random() > 0.5 ? 1 : -1 }) }

Check is mail id is valid :

function is_email(id){return (/^([\w!.%+\-\*])[email protected]([\w\-])+(?:\.[\w\-]+)+$/).test(id);}
//Sample : 
is_email('*@gmail.com')
true
is_email('[email protected]@[email protected] ')
false

PS trying to fix it to allow [email protected][IPv6:2001:db8:1ff::a0b:dbd0] as this is a valid mail id now!

Check if object is empty :

function is_empty(obj){if(obj instanceof Array){return obj.length===0;}else if(obj instanceof Object){for(var i in obj)return false;return true;}else return !obj;}
 
// Sample
 
is_empty([])
true
 
is_empty({})
true
 
is_empty([1])
false

Check if it's a scalar object! :

function is_scalar(obj){return (/string|number|boolean/).test(typeof obj);}
 
// Sample :
 
is_scalar(1)
true
 
is_scalar({})
false

Check the sign of the number :

Math.prototype.sign = function(num){ return (num>0) - (num<0);}
 
// Sample :
 
Math.sign(-1)
-1
 
Math.sign(-0)
0
 
Math.sign(2)
1

Do share you fav one liners or functions in javascript! Happy Hacking!

UPDATE 1

As many argued these are not (simple) one liner here are few more :

Array.prototype.each = Array.prototype.forEach;
Array.prototype.clone = function() { return this.slice(0); };
Array.prototype.min = function() { return Math.min.apply(Math, this); };
Array.prototype.max = function() { return Math.max.apply(Math, this); };

Share this