Created
April 4, 2014 16:07
-
-
Save azybler/9977808 to your computer and use it in GitHub Desktop.
Some useful JavaScript helper functions.
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
!function(window, document, undefined) { | |
var toStr = Object.prototype.toString; | |
window.SJ = { | |
// Check if the variable is an array. | |
IsArr: function(obj) { | |
return toStr.call(obj) === '[object Array]'; | |
}, | |
// Check if the variable is a function. | |
IsFunc: function(obj) { | |
return toStr.call(obj) === '[object Function]'; | |
}, | |
// Check if the variable is declared in the global scope. | |
IsDefined: function(name) { | |
return typeof(window[name]) != 'undefined'; | |
}, | |
FormatStr: function(str, token, val) { | |
return str.replace(token, val); | |
}, | |
GetUnixTime: function() { | |
return (new Date()).getTime(); | |
}, | |
EncodeURL: function(url) { | |
return encodeURIComponent(url); | |
}, | |
DecodeURL: function(url) { | |
return decodeURIComponent(url); | |
}, | |
GetKeyCode: function(e) { | |
return e.charCode ? e.charCode : e.keyCode; | |
}, | |
DoAsync: function(func) { | |
setTimeout(func, 0); | |
}, | |
ParseInt: function(str) { | |
return parseInt(str, 10); | |
}, | |
FindText: function(hayStack, needle) { | |
for (var i = 0; i < hayStack.length; ++i) { | |
if (hayStack.substring(i) == needle) { | |
return i; | |
} | |
} | |
return -1; | |
}, | |
GetStr: function(str) { | |
if (!str || null == str) { | |
return ''; | |
} else { | |
return str; | |
} | |
}, | |
Map: function(arr, func) { | |
for (var i = 0; i < arr.length; ++i) { | |
func(arr[i]); | |
} | |
}, | |
ArrayContains: function(arr, val) { | |
for (var i = 0; i < arr.length; ++i) { | |
if (arr[i] == val) { | |
return true; | |
} | |
} | |
return false; | |
} | |
}; | |
}(this, document); | |
window.SJ.Split = function(str, etc) { | |
var etcs; | |
if (SJ.IsArr(etc)) { | |
etcs = etc; | |
} else { | |
etcs = [etc]; | |
} | |
for (var i = 0; i < etcs.length; ++i) { | |
if ('&' == etcs[i]) { | |
str = str.replace(/&/g, etcs[0]); | |
} else { | |
str = str.replace(etcs[i], etcs[0]); | |
} | |
} | |
var tmp = str.split(etcs[0]); | |
var ret = []; | |
for (var i = 0; i < tmp.length; ++i) { | |
if (tmp[i].length > 0) { | |
ret.push(tmp[i]); | |
} | |
} | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment