Hemanth's Scribes

javascript

Top 5 JavaScript oneliners

Author Photo

Hemanth HM

Thumbnail

JavaScript is such a beautiful language, where everything can be minified to one line ;)

But in this post I have tried to collect 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 = Math.floor(Math.random() * (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 if mail id is valid:

function is_email(id) {
  return (/^([\w!.%+\-\*])+@([\w\-])+(?:\.[\w\-]+)+$/).test(id);
}

// Sample:
is_email('[email protected]')  // true
is_email('A@b@[email protected]')  // false

PS: trying to fix it to allow user@[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.sign = function(num) { 
  return (num > 0) - (num < 0); 
}

Do share your fav one liners or functions in JavaScript! Happy Hacking!

UPDATE 1: As many argued these are not (simple) one liners, 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); };
#javascript
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.