Skip to content

Instantly share code, notes, and snippets.

@servel333
Created September 20, 2013 17:14
Show Gist options
  • Save servel333/6640757 to your computer and use it in GitHub Desktop.
Save servel333/6640757 to your computer and use it in GitHub Desktop.
A collection of simple JavaScript utilities.
////////////////////////////////////////////////////////////////////////////////
// Type utils
var is_object = function(o) { return o !== null && typeof o === 'object'; };
var is_number = function(o) { return !isNaN(parseFloat(o)) && isFinite(o); };
var is_string = function(o) { return typeof o === 'string'; };
var is_regexp = function(o) { return Object.prototype.toString.call( o ) === '[object RegExp]'; };
var is_regexp_duck = function(o) { return !!(o && o.test && o.exec && (o.ignoreCase || o.ignoreCase === false)); };
var get_internal_type = function(o) { return Object.prototype.toString.call(o).slice(8, -1); };
// get_internal_type( undefined ); => "Undefined"
// get_internal_type( null ); => "Null"
// get_internal_type( new Array() ); => "Array"
// get_internal_type( [] ); => "Array"
// get_internal_type( {} ); => "Object"
// get_internal_type( /a/ ); => "RegExp"
// get_internal_type( '' ); => "String"
// get_internal_type( window ); => "global"
// get_internal_type( location ); => "Location"
// get_internal_type( function(){} ); => "Function"
// get_internal_type( new (function(){})() ); => "Object"
// (function(){ return get_internal_type( arguments ); })(); => "Arguments"
// typeof window => "object"
////////////////////////////////////////////////////////////////////////////////
// Error
var error_to_string = function(err) {
if (typeof err === 'string') return 'Error: '+err;
var m = '';
var indent = ' ';
var append = function(message) { m += "\n"+message; };
var prop = function(name) { if (undefined !== err[name] ) append(indent+'.'+name+' => '+err[name]); };
m += 'Error: ';
if (''+err !== '[object Error]') m += err;
if (err.toString() !== '[object Error]'
&& ''+err !== err.toString())
append(indent+err.toString());
prop('message' ); // Standard
if (err.message !== err.description)
prop('description' ); // Microsoft
prop('name' ); // Standard
prop('fileName' ); // Microsoft
prop('lineNumber' ); // Microsoft
prop('columnNumber'); // Microsoft
prop('number' ); // Microsoft
prop('stack' ); // Mozilla
return m;
};
////////////////////////////////////////////////////////////////////////////////
// Array
var is_array = function(maybe_array) {
if (Array.isArray) return Array.isArray( maybe_array );
//return maybe_array instanceof Array;
return Object.prototype.toString.call( maybe_array ) === '[object Array]';
};
var to_array = function(a) { return Array.prototype.slice.call(a); };
Object.prototype.toArray = function(){return to_array(this)};
var array_each = function(array, on_item) {
for (var i = 0; i < array.length; i++) {
if (on_item(i, array[i])) {
return i;
}
}
return null;
};
Array.prototype.each = function(c){return array_each(this, c)};
var array_next = function(array, index, on_next) {
if(index >= 0 && index < array.length - 1) {
on_next(index+1, array[index+1]);
return index+1;
}
return null;
};
Array.prototype.next = function(i,c){return array_next(this,i,c)};
var array_map = function(array, on_item) {
var new_array = [];
array_each(array, function(i,v) {
new_array.push(on_item(i,v));
});
return new_array;
};
Array.prototype.map = function(c){return array_map(this,c)};
var array_keep = function(array, on_should_keep) {
on_should_keep = on_should_keep || function(v,i) { return !!v; };
var new_array = [];
array_each(array, function(v,i) {
if (on_should_keep(i,v)) {
new_array.push(v);
}
});
return new_array;
};
Array.prototype.keep = function(c){return array_keep(this,c)};
var array_contains = function(array, needle) {
return null !== array_each(array, function(i,v) {
return v == needle;
});
};
Array.prototype.contains = function(n){return array_contains(this,n)};
var array_uniq = function(array) {
var new_array = [];
array_each(array, function(i,v) {
if (!array_contains(new_array, v)) {
new_array.push(v);
}
});
return new_array;
};
Array.prototype.uniq = function(){return array_uniq(this)};
var array_flatten = function(array) { return Array.prototype.concat.apply([], array); };
Array.prototype.flatten = function(){return array_flatten(this);};
var array_msort = function(array, compare) {
var length = array.length,
middle = Math.floor(length / 2);
if (!compare) {
compare = function(left, right) {
if (left < right) return -1;
if (left == right) return 0;
else return 1;
};
}
if (length < 2) return array;
return array_msort.merge(
array_msort( Array.prototype.slice.call(array, 0, middle), compare ),
array_msort( Array.prototype.slice.call(array, middle, length), compare ),
compare
);
};
array_msort.merge = function(left, right, compare) {
var result = [];
while (left.length > 0 || right.length > 0) {
if (left.length > 0 && right.length > 0) {
if (compare(left[0], right[0]) <= 0) {
result.push(left[0]);
left = left.slice(1);
}
else {
result.push(right[0]);
right = right.slice(1);
}
}
else if (left.length > 0) {
result.push(left[0]);
left = left.slice(1);
}
else if (right.length > 0) {
result.push(right[0]);
right = right.slice(1);
}
}
return result;
};
Array.prototype.msort = function(compare){return array_msort(this, compare);};
////////////////////////////////////////////////////////////////////////////////
// Object
var object_each = function(obj, on_item, hasOwnProperty) {
hasOwnProperty = hasOwnProperty === undefined ? obj.hasOwnProperty : hasOwnProperty;
for (var prop in obj) {
if (hasOwnProperty(prop)) {
if (on_item(prop, obj[prop])) {
return prop;
}
}
}
return null;
};
/// Switch keys and values
/// { 'k1' : 'v1', 'k2' : 'v2' } => { 'v1' : 'k1', 'v2' : 'k2' }
var object_invert = function(obj, hasOwnProperty) {
var new_obj = {};
object_each(obj, function(k,v) {
new_obj[v] = k;
}, hasOwnProperty);
return new_obj;
};
////////////////////////////////////////////////////////////////////////////////
// Utils
var now = function() { return (new Date()).getTime(); };
var join_as_lines = function() { return Array.prototype.concat.apply([], arguments).join("\n"); };
////////////////////////////////////////////////////////////////////////////////
// Examples
var arguments_to_array = function() {
args = Array.prototype.slice.call(arguments);
return args;
};
var ExampleClass = function() {
var self = this;
};
(function(Class){
Class.create = function(){ return new Class(); };
})(ExampleClass);
var exampleClass = new ExampleClass();
////////////////////////////////////////////////////////////////////////////////
// Browser
var _log = function(message) {
if (window.console && typeof window.console.log === 'function') {
window.console.log(message);
}
};
var is_top_window = function(w) { w = w || window; return (w === w.top); };
/**
* Extracts parts of the hostname. Not intended to match the hostname from a URI.
* @remarks
* all , first , middle , sub , top
* ["a.com" , undefined , undefined , "a" , "com" ]
* ["b.a.com" , "b" , undefined , "a" , "com" ]
* ["c.b.a.com" , "c" , "b" , "a" , "com" ]
* ["d.c.b.a.com" , "d" , "c.b" , "a" , "com" ]
* ["e.d.c.b.a.com" , "e" , "d.c.b" , "a" , "com" ]
* ["f.e.d.c.b.a.com", "f" , "e.d.c.b" , "a" , "com" ]
*/
var get_host_parts = function(hostname) {
hostname = hostname || window.location.hostname;
m = string.match(/^(?:([\w\d_-]+)\.)?(?:((?:[\w\d_-]+\.){0,}(?:[\w\d_-]+))\.)?([\w\d_-]+)\.([\w\d_-]+)$/);
return { all:m[0], first:m[1], middle:m[2], sub:m[3], top:m[4] };
};
/**
* Returns the sub-domain and top-level domain.
* @returns
* "window.floor.light.com" => "light.com"
*/
var get_subdomain = function(hostname) {
hostname = hostname || window.location.hostname;
return hostname.replace(/^(?:[\w\d_-]+\.){0,}([\w\d_-]+\.[\w\d_-]+)$/,"$1");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment