Last active
December 9, 2015 06:48
-
-
Save haggen/1249653 to your computer and use it in GitHub Desktop.
JavaScript utility belt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//github.com/jed/140bytes/wiki/Byte-saving-techniques | |
Number.prototype.isPrime = function(n) { | |
var n = '1'.repeat(this); | |
return !n.match(/^1?$|^(11+?)\1+$/gi); | |
}; | |
// | |
String.prototype.repeat = function(n) { | |
return Array(n + 1).join(this); | |
}; | |
String.prototype.reverse = function() { | |
return this.split('').reverse().join(''); | |
}; | |
Array.prototype.shuffle = function() { | |
return this.sort(function() Math.random() - 0.5)); | |
}; | |
String.prototype.pad = function(n, padding) { | |
padding = padding.repeat(Math.abs(this.length - n)); | |
return n > 0 ? this + padding : padding + this; | |
}; | |
// | |
Math._random = Math.random; | |
Math.random = function(n, m) { | |
return n === undefined ? Math._random() : Math.ceil(Math._random() * (n - m) + m - 1); | |
}; | |
// | |
Object.forEach = function(object, fn) { | |
for(var key in object) { | |
if(object.hasOwnProperty(key)) { | |
fn.apply(object, key, object[key]); | |
} | |
} | |
}; | |
//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign | |
Object.assign = Object.assign || function() { | |
var hashes = [].slice.call(arguments) | |
, target = hashes.shift(); | |
hashes.forEach(function(hash) { | |
Object.forEach(hash, function(key, value) { | |
target[key] = value; | |
}); | |
}); | |
return target; | |
}; | |
}; | |
// | |
Date.prototype.addTime = function(n) { | |
return new Date(this.getTime() + n); | |
}; | |
Date.prototype.addSeconds = (n) { | |
return this.addTime(n * 1000); | |
} | |
Date.prototype.addMinutes = (n) { | |
return this.addSeconds(n * 60); | |
} | |
Date.prototype.addHours = (n) { | |
return this.addMinutes(n * 60); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment