Skip to content

Instantly share code, notes, and snippets.

@arthurkushman
Last active December 22, 2015 21:39
Show Gist options
  • Save arthurkushman/2e515be53537bfeadebf to your computer and use it in GitHub Desktop.
Save arthurkushman/2e515be53537bfeadebf to your computer and use it in GitHub Desktop.
Lightning class offers frequently (daily) used methods (functions) to free programmer`s hands, avoiding regular/repeated practices
/*
* Lightning class offers frequently (daily) used methods (functions)
* to free programmer`s hands, avoiding regular/repeated practices
*
* Some functions have been inherited from PHP stdlib (like numberFormat, htmlspecialchars)
* to make lives easier
*
* Copyright (C) <2015> <Arthur Kushman>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
var lightning = {
/**
* @return (string) - browser name lowercase
**/
getBrowser: function () {
var bros = ['firefox', 'msie', 'chrome',
'safari', 'opera', 'torch', 'maxthon', 'seamonkey', 'avant', 'dolphin', 'tor'];
for (var k in bros) {
var regExp = new RegExp(bros[k], 'i');
if (regExp.test(navigator.userAgent))
return bros[k];
}
},
/**
* @startNum (int) - number to start from
* @endNum (int) - number to end
* @return (int) - random value bitween startNum and endNum
*/
rand: function (startNum, endNum) {
var endBorder = endNum - startNum + 1;
return Math.floor(Math.random() * endBorder) + startNum;
},
/**
* @num (float) - number to round (started from 0)
* @return (int) - rounded number
**/
round: function (num) {
return Math.round(num * 100) / 100;
},
/**
* @html to be encoded
* @extraChars array - optional
* @return encoded html String
*/
htmlspecialchars: function (text, extraChars) {
var tagsToReplace = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;'
};
var escapeRegExp = function (string) {
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
if (extraChars != null) {
for (var key in extraChars) {
tagsToReplace[key] = extraChars[key];
}
}
for (var key in tagsToReplace) {
text = text.replace(new RegExp(escapeRegExp(key), 'g'), tagsToReplace[key]);
}
return text;
},
pageBack: function () {
location.history.back();
},
pageForward: function () {
location.history.forward();
},
/**
*
* @param {array} params
* @returns {string} uri with one or several params set
*/
setUrlParams: function (url, params)
{
for (var paramName in params) {
if (url.indexOf(paramName + "=") >= 0)
{
var prefix = url.substring(0, url.indexOf(paramName));
var suffix = url.substring(url.indexOf(paramName));
suffix = suffix.substring(suffix.indexOf("=") + 1);
suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
url = prefix + paramName + "=" + params[paramName] + suffix;
}
else
{
if (url.indexOf("?") < 0) {
url += "?" + paramName + "=" + params[paramName];
} else {
url += "&" + paramName + "=" + params[paramName];
}
}
}
return url;
},
/**
*
* @param {int|float} number
* @param {int} decimals
* @param {char} decPoint
* @param {string} thousandsSep
* @returns {string} custom formated human readable number
*/
numberFormat: function (number, decimals, decPoint, thousandsSep) {
number = (number + '')
.replace(/[^0-9+\-Ee.]/g, '');
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep,
dec = (typeof decPoint === 'undefined') ? '.' : decPoint,
s = '',
toFixedFix = function (n, prec) {
var k = Math.pow(10, prec);
return '' + (Math.round(n * k) / k)
.toFixed(prec);
};
// Fix for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n))
.split('.');
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
}
if ((s[1] || '')
.length < prec) {
s[1] = s[1] || '';
s[1] += new Array(prec - s[1].length + 1)
.join('0');
}
return s.join(dec);
},
// encodes/decodes and hash algorithms
base64_encode: function (data) {
var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
enc = '',
tmp_arr = [];
if (!data) {
return data;
}
do {
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
var r = data.length % 3;
return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
},
base64_decode: function (data) {
var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
dec = '',
tmp_arr = [];
if (!data) {
return data;
}
data += '';
do {
h1 = b64.indexOf(data.charAt(i++));
h2 = b64.indexOf(data.charAt(i++));
h3 = b64.indexOf(data.charAt(i++));
h4 = b64.indexOf(data.charAt(i++));
bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
o1 = bits >> 16 & 0xff;
o2 = bits >> 8 & 0xff;
o3 = bits & 0xff;
if (h3 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1);
} else if (h4 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1, o2);
} else {
tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
}
} while (i < data.length);
dec = tmp_arr.join('');
return dec.replace(/\0+$/, '');
},
/**
* Calculate the sha1 hash of a string
* @param {string} str
* @returns {string} the sha1 hash in hex
*/
sha1: function (str) {
var rotate_left = function (n, s) {
var t4 = (n << s) | (n >>> (32 - s));
return t4;
};
/*var lsb_hex = function (val) {
// Not in use; needed?
var str="";
var i;
var vh;
var vl;
for ( i=0; i<=6; i+=2 ) {
vh = (val>>>(i*4+4))&0x0f;
vl = (val>>>(i*4))&0x0f;
str += vh.toString(16) + vl.toString(16);
}
return str;
};*/
var cvt_hex = function (val) {
var str = '';
var i;
var v;
for (i = 7; i >= 0; i--) {
v = (val >>> (i * 4)) & 0x0f;
str += v.toString(16);
}
return str;
};
var blockstart;
var i, j;
var W = new Array(80);
var H0 = 0x67452301;
var H1 = 0xEFCDAB89;
var H2 = 0x98BADCFE;
var H3 = 0x10325476;
var H4 = 0xC3D2E1F0;
var A, B, C, D, E;
var temp;
// utf8_encode
str = unescape(encodeURIComponent(str));
var str_len = str.length;
var word_array = [];
for (i = 0; i < str_len - 3; i += 4) {
j = str.charCodeAt(i) << 24 | str.charCodeAt(i + 1) << 16 | str.charCodeAt(i + 2) << 8 | str.charCodeAt(i + 3);
word_array.push(j);
}
switch (str_len % 4) {
case 0:
i = 0x080000000;
break;
case 1:
i = str.charCodeAt(str_len - 1) << 24 | 0x0800000;
break;
case 2:
i = str.charCodeAt(str_len - 2) << 24 | str.charCodeAt(str_len - 1) << 16 | 0x08000;
break;
case 3:
i = str.charCodeAt(str_len - 3) << 24 | str.charCodeAt(str_len - 2) << 16 | str.charCodeAt(str_len - 1) <<
8 | 0x80;
break;
}
word_array.push(i);
while ((word_array.length % 16) != 14) {
word_array.push(0);
}
word_array.push(str_len >>> 29);
word_array.push((str_len << 3) & 0x0ffffffff);
for (blockstart = 0; blockstart < word_array.length; blockstart += 16) {
for (i = 0; i < 16; i++) {
W[i] = word_array[blockstart + i];
}
for (i = 16; i <= 79; i++) {
W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
}
A = H0;
B = H1;
C = H2;
D = H3;
E = H4;
for (i = 0; i <= 19; i++) {
temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B, 30);
B = A;
A = temp;
}
for (i = 20; i <= 39; i++) {
temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B, 30);
B = A;
A = temp;
}
for (i = 40; i <= 59; i++) {
temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B, 30);
B = A;
A = temp;
}
for (i = 60; i <= 79; i++) {
temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B, 30);
B = A;
A = temp;
}
H0 = (H0 + A) & 0x0ffffffff;
H1 = (H1 + B) & 0x0ffffffff;
H2 = (H2 + C) & 0x0ffffffff;
H3 = (H3 + D) & 0x0ffffffff;
H4 = (H4 + E) & 0x0ffffffff;
}
temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);
return temp.toLowerCase();
},
getHeaders: function (url, format) {
var req = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
var tmp, headers, pair, i, j = 0;
req.open('HEAD', url, false);
req.send(null);
if (req.readyState < 3) {
return false;
}
tmp = req.getAllResponseHeaders();
tmp = tmp.split('\n');
headers = format ? {} : [];
for (var i in tmp) {
if (format) {
pair = tmp[i].split(':');
headers[pair.splice(0, 1)] = pair.join(':')
.substring(1);
} else {
headers[j++] = tmp[i];
}
}
return headers;
}
};
@arthurkushman
Copy link
Author

Lightning examples

* setUrlParams

Let`s try to modify url setting parameters and then modify only the value of particular one.

      var arr = {'param1': 'val1', 'param2':'val2'};
      var url = lightning.setUrlParams(window.location.href, arr);
      console.log(url); // outputs - http://example.com/main/#part?param1=val1&param2=val2

      url = lightning.setUrlParams(url, {'param1':'valChanged'});
      console.log(url); // outputs - http://example.com/main/#part?param1=valChanged&param2=val2

This is especially convenient when needed to add/set any parameters within the hash tag, because You can make it done only on client-side.

* numberFormat

This is the similar function as in PHP number_format, let`s assume You develop the shop and needs some correlation between PHP/JS of prices for ex. in basket.

      var price = lightning.numberFormat(2345.678, 2, ',', ' ');      
      console.log(price);

Result : 2 345,68

For some purposes U may need to use text special chars conversion to valid W3C symbols like htmlspecialchars function in PHP does, here we go:

      var text = '1 is less then 3, so 1 < 3, also A & B & C - alphabet';
      var cleanHtml = lightning.htmlspecialchars(text, {'-':'&ndash;'});
      console.log(cleanHtml); // 1 is less then 3, so 1 &lt; 3, also A &amp; B &amp; C &ndash; alphabet

How many times You ggl around for functions like rand(min, max) in JS?

* rand

      var rd = lightning.rand(5, 99);
      console.log(rd);

Result numbers between 5 and 99 inclusively.

What if You don`t need to grab all the details of the browser like their version and/or OS, just want to get the browser name: firefox, opera, chrome etc.
And the idea of including another HUGE js lib just to identify browser seems ridiculous.

* getBrowser

      var browser = lightning.getBrowser();
      console.log(browser);

Result: firefox (in my case :-) )

Encrypt/Decrypt algorithms in base64

* base64_encode
* base64_decode

      var someText = 'some text here';
      var b64Encoded = lightning.base64_encode(someText);
      console.log('text: '+ someText + ', base64: ' + b64Encoded);
      b64Decoded = lightning.base64_decode(b64Encoded);
      console.log('base64: ' + b64Encoded + ', text: ' + b64Decoded);

Outputs:
text: some text here, base64: c29tZSB0ZXh0IGhlcmU=
base64: c29tZSB0ZXh0IGhlcmU=, text: some text here

Definitely most popular, useful and secured hash algorithm - sha1.

* sha1

      var sha1Hex = lightning.sha1('the cruel world of crackers now secured');
      console.log(sha1Hex);

Outputs: 31ec5719da855b05a8b8b8209877b296db6b71ba

Get headers information.

      var headers = lightning.getHeaders(location.href);
      console.log(headers);

Output sample: ["Date: Wed, 15 Apr 2015 13:28:08 GMT\r", "Server: Apache/2.2.25 (Win32) PHP/5.4.23\r", "X-Powered-By: PHP/5.4.23\r", "Keep-Alive: timeout=5, max=98\r", "Connection: Keep-Alive\r", "Content-Type: text/html\r", ""]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment