@darwino/darwino
Version:
A set of Javascript classes and utilities
360 lines (334 loc) • 10.7 kB
JavaScript
/*!COPYRIGHT HEADER! - CONFIDENTIAL
*
* Darwino Inc Confidential.
*
* (c) Copyright Darwino Inc. 2014-2016.
*
* Notice: The information contained in the source code for these files is the property
* of Darwino Inc. which, with its licensors, if any, owns all the intellectual property
* rights, including all copyright rights thereto. Such information may only be used
* for debugging, troubleshooting and informational purposes. All other uses of this information,
* including any production or commercial uses, are prohibited.
*/
//
// General purpose JavaScript utilities
//
var Utils = {
//
// Type checking
//
isString: function isString(v) {
return v && (typeof v === "string" || v instanceof String);
},
isObject: function isObject(v) {
return v && (typeof v === "object" || v instanceof Object);
},
isArray: function isArray(v) {
return v && (typeof v === "array" || v instanceof Array);
},
isNumber: function isNumber(v) {
return v && (typeof v === "number" || v instanceof Number);
},
isBoolean: function isBoolean(v) {
return v && (typeof v === "boolean" || v instanceof Boolean);
},
isDate: function isDate(v) {
return v && v instanceof Date;
},
isFunction: function isFunction(v) {
return v && typeof v === "function";
},
//
// Handling paths
//
concatPath: function concatPath()
/*paths*/
{
var s = "";
for (var i = 0; i < arguments.length; i++) {
if (arguments[i]) {
s = Utils.removeTrailingSep(s);
s += s ? '/' + Utils.removeLeadingSep(arguments[i]) : arguments[i];
}
}
return s;
},
addTrailingSep: function addTrailingSep(p) {
return Utils.endsWith(p, '/') ? p : p + '/';
},
removeTrailingSep: function removeTrailingSep(p) {
return Utils.endsWith(p, '/') ? Utils.left(p, -1) : p;
},
addLeadingSep: function addLeadingSep(p) {
return Utils.startsWith(p, '/') ? p : '/' + p;
},
removeLeadingSep: function removeLeadingSep(p) {
return Utils.startsWith(p, '/') ? p.substring(1) : p;
},
//
// Handling JSON
//
toJson: function toJson(value, compact) {
if (value) {
return compact ? JSON.stringify(value) : JSON.stringify(value, null, 4);
}
return "";
},
fromJson: function fromJson(json) {
if (json) {
// Makes JSON more permissive (ex: {a:"A"} instead of {"a":"A"}
//return JSON.parse(json)
return eval("(" + json + ")");
}
return null;
},
jsonPath: null,
// See support libs
//
// Object utilities
//
isEmptyObject: function isEmptyObject(o) {
if (o) {
for (var n in o) {
return false;
}
}
return true;
},
//
// String utilities
//
left: function left(s, length) {
if (length < 0) length = s.length + length;
return s.substring(0, Math.min(length, s.length));
},
startsWith: function startsWith(s, prefix) {
return s.length >= prefix.length && s.substring(0, prefix.length) == prefix;
},
startsWithIgnoreCase: function startsWithIgnoreCase(s, prefix) {
return s.length >= prefix.length && s.substring(0, prefix.length).toLowerCase() == prefix.toLowerCase();
},
endsWith: function endsWith(s, suffix) {
return s.length >= suffix.length && s.substring(s.length - suffix.length) == suffix;
},
endsWithIgnoreCase: function endsWithIgnoreCase(s, suffix) {
return s.length >= suffix.length && s.substring(s.length - suffix.length).toLowerCase() == suffix.toLowerCase();
},
equals: function equals(s1, s2) {
if (!s1) return !s2;
if (!s2) return false;
return s1 == s2;
},
equalsIgnoreCase: function equalsIgnoreCase(s1, s2) {
if (!s1) return !s2;
if (!s2) return false;
return s1.toLowerCase() == s2.toLowerCase();
},
uuid: function uuid() {
// Keep the UUID 32 characters to handle some replicated system with only 32 ch (ex: FlowBuilder)
//var tmpl = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
var tmpl = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx';
return tmpl.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0;
var v = c == 'x' ? r : r & 0x3 | 0x8;
return v.toString(16).toUpperCase(); // Make sure it is upper case as UNID should be like this
});
},
format: function format(msg) {
for (var i = 1; i < arguments.length; i++) {
msg = (msg || "").replace("{" + (i - 1) + "}", arguments[i]);
}
return msg;
},
toUtf8: function toUtf8(argString) {
// From: http://phpjs.org/functions
// + original by: Webtoolkit.info (http://www.webtoolkit.info/)
// + improved by: Kevin van Zonneveld (https://github.com/kvz/phpjs)
if (argString === null || typeof argString === "undefined") {
return "";
}
var string = argString + ''; // .replace(/\r\n/g,
// "\n").replace(/\r/g, "\n");
var utftext = '',
start,
end,
stringl = 0;
start = end = 0;
stringl = string.length;
for (var n = 0; n < stringl; n++) {
var c1 = string.charCodeAt(n);
var enc = null;
if (c1 < 128) {
end++;
} else if (c1 > 127 && c1 < 2048) {
enc = String.fromCharCode(c1 >> 6 | 192, c1 & 63 | 128);
} else if (c1 & 0xF800 != 0xD800) {
enc = String.fromCharCode(c1 >> 12 | 224, c1 >> 6 & 63 | 128, c1 & 63 | 128);
} else {
// surrogate pairs
if (c1 & 0xFC00 != 0xD800) {
throw new RangeError("Unmatched trail surrogate at " + n);
}
var c2 = string.charCodeAt(++n);
if (c2 & 0xFC00 != 0xDC00) {
throw new RangeError("Unmatched lead surrogate at " + (n - 1));
}
c1 = ((c1 & 0x3FF) << 10) + (c2 & 0x3FF) + 0x10000;
enc = String.fromCharCode(c1 >> 18 | 240, c1 >> 12 & 63 | 128, c1 >> 6 & 63 | 128, c1 & 63 | 128);
}
if (enc !== null) {
if (end > start) {
utftext += string.slice(start, end);
}
utftext += enc;
start = end = n + 1;
}
}
if (end > start) {
utftext += string.slice(start, stringl);
}
return utftext;
},
fromUtf8: function fromUtf8(str_data) {
// From: http://phpjs.org/functions
// + original by: Webtoolkit.info (http://www.webtoolkit.info/)
// + input by: Aman Gupta
// + improved by: Kevin van Zonneveld
// (http://kevin.vanzonneveld.net)
// + improved by: Norman "zEh" Fuchs
// + bugfixed by: hitwork
// + bugfixed by: Onno Marsman
// + input by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: Kevin van Zonneveld
// (http://kevin.vanzonneveld.net)
// + bugfixed by: kirilloid
// * example 1: utf8_decode('Kevin van Zonneveld');
// * returns 1: 'Kevin van Zonneveld'
var tmp_arr = [],
i = 0,
ac = 0,
c1 = 0,
c2 = 0,
c3 = 0,
c4 = 0;
str_data += '';
while (i < str_data.length) {
c1 = str_data.charCodeAt(i);
if (c1 <= 191) {
tmp_arr[ac++] = String.fromCharCode(c1);
i++;
} else if (c1 <= 223) {
c2 = str_data.charCodeAt(i + 1);
tmp_arr[ac++] = String.fromCharCode((c1 & 31) << 6 | c2 & 63);
i += 2;
} else if (c1 <= 239) {
// http://en.wikipedia.org/wiki/UTF-8#Codepage_layout
c2 = str_data.charCodeAt(i + 1);
c3 = str_data.charCodeAt(i + 2);
tmp_arr[ac++] = String.fromCharCode((c1 & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
i += 3;
} else {
c2 = str_data.charCodeAt(i + 1);
c3 = str_data.charCodeAt(i + 2);
c4 = str_data.charCodeAt(i + 3);
c1 = (c1 & 7) << 18 | (c2 & 63) << 12 | (c3 & 63) << 6 | c4 & 63;
c1 -= 0x10000;
tmp_arr[ac++] = String.fromCharCode(0xD800 | c1 >> 10 & 0x3FF);
tmp_arr[ac++] = String.fromCharCode(0xDC00 | c1 & 0x3FF);
i += 4;
}
}
return tmp_arr.join('');
},
//
// XML Utilities
//
parseXml: function parseXml(xml) {
var xmlDoc = null;
try {
if (!document.evaluate) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xml);
} else {
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(xml, "text/xml");
}
}
} catch (ex) {
xmlDoc = undefined;
}
return xmlDoc;
},
xmlString: function xmlString(xmlDoc) {
if (!xmlDoc) {
return "";
} else if (window.ActiveXObject) {
return xmlDoc.xml;
} else {
return new XMLSerializer().serializeToString(xmlDoc);
}
},
//
// Date Utilities
//
dateToString: function dateToString(d) {
// always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ. The timezone is always zero UTC offset, as denoted by the suffix "Z".
return d ? d.toISOString() : null;
},
stringToDate: function stringToDate(date) {
// Test here: https://regex101.com/
var regexp = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{1,3})?(Z|(?:[+-](\d{2}):(\d{2})))?$/g;
var match = regexp.exec(date);
if (!match) return null;
var year = parseInt(match[1]);
var month = parseInt(match[2]);
var day = parseInt(match[3]);
var hour = parseInt(match[4]);
var minutes = parseInt(match[5]);
var seconds = parseInt(match[6]);
var milliseconds = match[7] ? parseInt(match[7].substring(1)) : 0; // timezone
// it is supposed to be mandatory, at least 'Z', but if missing we assume 'Z'
// In JS, we only support 'Z' and +/-HH:MM
var tzOffset = 0;
if (match.length > 8 && match[8]) {
var timezoneIndicator = match[8].charAt(0);
if (timezoneIndicator == '+' || timezoneIndicator == '-') {
var tzh = parseInt(match[9]);
var tzm = parseInt(match[10]);
tzOffset = tzh * 60 * 60 * 1000 + tzm * 60 * 1000;
if (timezoneIndicator == '+') tzOffset = -tzOffset; //} else if (timezoneIndicator == 'Z') {
// // already UTC...
}
}
var dt = Date.UTC(year, month - 1, day, hour, minutes, seconds, milliseconds);
return new Date(dt + tzOffset);
},
//
// Base64
//
atob: window.atob,
btoa: window.btoa,
//
// Misc utilities
//
now: function now() {
return new Date().getTime();
},
intAsString: function intAsString(l) {
return l.toFixed();
},
//
// Execute a callback asynchronously
//
execAsyncCb: function execAsyncCb(cb, value, loaded) {
if (cb) {
setTimeout(function () {
(cb.success || cb)(value, loaded);
});
}
}
};
export default Utils;
//# sourceMappingURL=Utils.js.map