Skip to content

Instantly share code, notes, and snippets.

@Error601
Last active August 29, 2015 14:11
Show Gist options
  • Save Error601/7e98026ec368e4affaa1 to your computer and use it in GitHub Desktop.
Save Error601/7e98026ec368e4affaa1 to your computer and use it in GitHub Desktop.
Some super basic JavaScript utility functions that I use a lot
/*!
* Very basic JavaScript utility functions
*/
function isObject(obj){
return Object.prototype.toString.call(obj) === '[object Object]';
}
function isFunction(func){
return typeof func == 'function';
}
function isArray(arr){
if ( Array.isArray ) {
return Array.isArray(arr);
}
else {
return Object.prototype.toString.call(arr) === '[object Array]';
}
}
// strict check for 'number' type (not string)
function isNumber(num){
return typeof num == 'number';
//return !isNan(parseInt(num),10);
}
// checks if a value is numeric (including numeric strings)
// straight from jQuery's $.isNumeric()
function isNumeric(num) {
return !Array.isArray(num) && num - parseFloat(num) >= 0;
}
// return existing array or create a new empty array
// if the argument passed is NOT an array
// (prevents 'undefined' errors)
// APP.arr = getArray(APP.arr);
function getArray(arr){
return isArray(arr) ? arr : [];
}
// return existing object or create a new empty object
// if the argument passed is NOT an (existing) object
// (prevents 'undefined' errors)
// APP.obj = getObject(APP.obj);
function getObject(obj){
return isObject(obj) ? obj : {};
}
// strong-arm comparison of two values by converting to strings
function isValue( a, b ){
if (arguments.length === 2 && typeof a != 'undefined'){
return (a.toString() === b.toString());
}
else {
return undefined;
}
}
// strong-arm check for boolean false
function isFalse(val){
return val.toString() === 'false';
}
// strong-arm check for boolean true
function isTrue(val){
return val.toString() === 'true';
}
// convert text list to real array
// use 'delim' as delimiter, or
// if '*' or '!' is the first item
// (character), use custom delimiter,
// or defaults to [,] (comma)
// usage:
// listToArray('!/foo/bar/baz/blah') // (custom delimiter '/')
// (or)
// listToArray('foo,bar,baz,blah') // (default delimiter ',')
// outputs:
// ['foo','bar','baz','blah']
function listToArray ( list, delim ){
var arr, shift = false;
if ( typeof list != 'string' ) return [];
// if first item/character is '*' or '!'
// then use custom delimiter (second character)
if ( ['*', '!'].indexOf(list.charAt(0)) !== -1 ) {
delim = list.charAt(1);
shift = true;
}
else {
delim = (typeof delim != 'undefined') ? delim : ',';
}
arr = list.split(delim).map(function(item){
// tolerate white space around delimiters
return item.trim();
});
if ( shift ) arr.shift();
return arr;
}
// pass an array to make sure ALL values are numbers
function allNumbers(arr) {
if (!Array.isArray(arr)) {
return false;
}
var i = -1;
while (++i < arr.length) {
if (typeof arr[i] != 'number') {
return false;
}
}
// if we make it through, we've got all numbers
return true;
}
// pass an array to make sure ALL values are numeric (including strings)
function allNumeric(arr) {
if (!Array.isArray(arr)) {
return false;
}
var i = -1;
// isNumeric() borrowed from jQuery $.isNumeric(num);
function isNumeric(num) {
return !Array.isArray(num) && num - parseFloat(num) >= 0;
}
while (++i < arr.length) {
if (!isNumeric(arr[i])) {
return false;
}
}
// if we make it through, we've got all numeric values
return true;
}
// utility for getting URL query string value
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return (results == null) ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// returns number as a string with leading zeros (or other character)
// thanks to - http://stackoverflow.com/a/10073788
// revised here - http://jsfiddle.net/rj0rf5hg/2/
// padNumber( 5 ) //=> '05'
// padNumber( 55, 4 ) //=> '0055'
// padNumber( 555, 6, 'X' ) //=> 'XXX555'
function padNumber( num, size, fill ) {
// only whole numbers
if (parseInt(num, 10) !== +num) {
return num+'';
}
// make sure 'num' is a string
num = num+'';
// make sure 'size' is a whole number
// defaults to 2 digits
size = (typeof size != 'undefined') ? parseInt(size, 10) : 2;
// default fill character is '0'
fill = fill || '0';
return (num.length >= size) ? num : new Array(size - num.length + 1).join(fill) + num;
}
// add commas to numbers
function addCommas(nStr) {
nStr += '';
var
x = nStr.split('.'),
x1 = x[0],
x2 = x.length > 1 ? '.' + x[1] : ''
;
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
// rounded to 2 decimal places
// (used in sizeFormat() function)
function roundNumber( num, dec ) {
return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}
// format file size numbers with decimals and units
function sizeFormat( size, round ) {
var KB = 1024,
MB = KB * KB,
GB = MB * KB,
TB = GB * KB;
// round to 2 decimal places by default
round = round || 2;
if (size >= TB) {
return roundNumber(size / TB, round) + ' TB';
}
if (size >= GB) {
return roundNumber(size / GB, round) + ' GB';
}
if (size >= MB) {
return roundNumber(size / MB, round) + ' MB';
}
if (size >= KB) {
return roundNumber(size / KB, round) + ' KB';
}
return size + ' B';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment