UNPKG

joola.io.engine

Version:
409 lines (346 loc) 11.9 kB
/** * joola.io * * Copyright Joola Smart Solutions, Ltd. <info@joo.la> * * Licensed under GNU General Public License 3.0 or later. * Some rights reserved. See LICENSE, AUTHORS. * * @license GPL-3.0+ <http://spdx.org/licenses/GPL-3.0+> */ var async = require('async'), ce = require('cloneextend'); global._ = require('underscore'); global.fork = function (async_calls, shared_callback) { async.parallel(async_calls, shared_callback); }; global.forkSeries = function (async_calls, shared_callback) { async.series(async_calls, shared_callback); }; global.randomBetween = function (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }; global.chunk = function (array, chunkSize) { var lists = _.groupBy(array, function (a, b) { return Math.floor(b / chunkSize); }); lists = _.toArray(lists); return lists; }; try { Object.defineProperty(global, '__stack', { get: function () { var orig = Error.prepareStackTrace; Error.prepareStackTrace = function (_, stack) { return stack; }; var err = new Error; Error.captureStackTrace(err, arguments.callee); var stack = err.stack; Error.prepareStackTrace = orig; return stack; } }); Object.defineProperty(global, '__caller_line', { get: function () { return __stack[1].getLineNumber(); } }); Object.defineProperty(global, '__caller_function', { get: function () { return __stack[1].getFunctionName(); } }); } catch (ex) { } /** * Generates a random string of characters for the specific number of bits * * @method randomString * @param {int} bits number of bits to use * @return {string} A random string of characters */ exports.randomString = function (bits) { var chars, rand, i, ret; chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; ret = ''; // in v8, Math.random() yields 32 pseudo-random bits (in spidermonkey it gives 53) while (bits > 0) { rand = Math.floor(Math.random() * 0x100000000); // 32-bit integer // base 64 means 6 bits per character, so we use the top 30 bits from rand to give 30/6=5 characters. for (i = 26; i > 0 && bits > 0; i -= 6, bits -= 6) ret += chars[0x3F & rand >>> i] } return ret; }; function formatDate(formatDate, formatString, adjustGMT) { if (adjustGMT) { formatDate = new Date(formatDate); var sign = (formatDate.getTimezoneOffset() > 0) ? 1 : -1; var offset = Math.abs(formatDate.getTimezoneOffset()); var hours = Math.floor(offset / 60); formatDate.setHours(formatDate.getHours() + (sign * hours)); } if (formatDate instanceof Date) { var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var yyyy = formatDate.getFullYear(); var yy = yyyy.toString().substring(2); var m = formatDate.getMonth() + 1; var mm = m < 10 ? "0" + m : m; var mmm = months[m - 1]; var d = formatDate.getDate(); var dd = d < 10 ? "0" + d : d; var fff = formatDate.getMilliseconds(); fff = (fff < 100 ? fff < 10 ? '00' + fff : +'0' + fff : fff); var h = formatDate.getHours(); var hh = h < 10 ? "0" + h : h; var n = formatDate.getMinutes(); var nn = n < 10 ? "0" + n : n; var s = formatDate.getSeconds(); var ss = s < 10 ? "0" + s : s; if (formatString == null) formatString = jarvis.dateformat; formatString = formatString.replace(/yyyy/i, yyyy); formatString = formatString.replace(/yy/i, yy); formatString = formatString.replace(/mmm/i, mmm); formatString = formatString.replace(/mm/i, mm); //formatString = formatString.replace(/m/i, m); formatString = formatString.replace(/dd/i, dd); //formatString = formatString.replace(/d/i, d); formatString = formatString.replace(/hh/i, hh); //formatString = formatString.replace(/h/i, h); formatString = formatString.replace(/nn/i, nn); //formatString = formatString.replace(/n/i, n); formatString = formatString.replace(/ss/i, ss); formatString = formatString.replace(/fff/i, fff); //formatString = formatString.replace(/s/i, s); return formatString; } else { return ""; } } /** * Used to format date according to standard formatting options * * @method formatDate * @param {string} formatDate date to format * @param {string} formatString format to convert the date by * @param {bool} adjustGMT should GMT adjustments be applied * @return {string} formatted date */ exports.formatDate = formatDate; Date.prototype.fixDate = function (force, direction, isZ) { date = this; if (!force) return date; var sign; if (!direction) sign = (date.getTimezoneOffset() > 0) ? 1 : -1; else sign = (date.getTimezoneOffset() > 0) ? -1 : 1; var offset = Math.abs(date.getTimezoneOffset()); var hours = Math.floor(offset / 60); if (isZ) { date.addHours(hours); } date.setHours(date.getHours() + (sign * hours)); return date; }; /* function pad(str, char, length) { while (str.length < length) str = char + str; return str; } String.prototype.pad = function (char, length) { return this.length >= length ? this : pad(this, char, 2); };*/ Date.prototype.clean = function () { return formatDate(this, 'yyyy-mm-dd hh:nn:ss').clean(); }; Date.prototype.getWeek = function () { var onejan = new Date(this.getFullYear(), 0, 1); return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7); }; Date.prototype.roundYear = function () { return new Date(this.getFullYear(), 0, 0, 0, 0, 0, 0); }; Date.prototype.roundMonth = function () { return new Date(this.getFullYear(), this.getMonth(), 0, 0, 0, 0, 0); }; Date.prototype.roundDay = function () { return new Date(this.getYear(), this.getMonth(), this.getDate(), 0, 0, 0, 0); }; Date.prototype.roundHour = function () { return new Date(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), 0, 0, 0); }; Date.prototype.roundMinute = function () { return new Date(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), 0, 0); }; Date.prototype.roundSecond = function () { return new Date(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), 0); }; String.prototype.clean = function () { var result = this; result = result.replace(/ /g, ''); result = result.replace(/\./g, ''); result = result.replace(/-/g, ''); result = result.replace(/\\/g, ''); result = result.replace(/\//g, ''); result = result.replace(/:/g, ''); result = result.replace(/{/g, ''); result = result.replace(/}/g, ''); result = result.replace(/"/g, ''); return result; }; String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ''); }; /* String.prototype.ltrim = function () { return this.replace(/^\s+/, ''); }; String.prototype.rtrim = function () { return this.replace(/\s+$/, ''); }; String.prototype.fulltrim = function () { return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, '').replace(/\s+/g, ' '); }; */ Date.prototype.dateDiff = function (comparedtodate) { var first = this; // Copy date parts of the timestamps, discarding the time parts. var one = new Date(first.getFullYear(), first.getMonth(), first.getDate()); var two = new Date(comparedtodate.getFullYear(), comparedtodate.getMonth(), comparedtodate.getDate()); // Do the math. var millisecondsPerDay = 1000 * 60 * 60 * 24; var millisBetween = two.getTime() - one.getTime(); var days = millisBetween / millisecondsPerDay; // Round down. return Math.floor(Math.abs(days)); }; Date.prototype.msDiff = function (comparedtodate) { var first = this; // Copy date parts of the timestamps, discarding the time parts. var one = new Date(first.getFullYear(), first.getMonth(), first.getDate()); var two = new Date(comparedtodate.getFullYear(), comparedtodate.getMonth(), comparedtodate.getDate()); // Do the math. var millisBetween = two.getTime() - one.getTime(); // Round down. return Math.floor(Math.abs(millisBetween)); }; exports.cleanObject = function (obj) { var _this = ce.clone(obj); _.each(_this, function (value, key) { if (key.substring(0, 1) == '_') delete _this[key]; }); return _this; }; exports.shorten = function () { return Math.floor(Math.random() * 10) + parseInt(new Date().getTime()).toString(36).toLowerCase(); }; global.stringify = function (obj) { var placeholder = '____PLACEHOLDER____'; var fns = []; var json = JSON.stringify(obj, function (key, value) { if (typeof value === 'function') { fns.push(value); return placeholder; } return value; }, 2); json = json.replace(new RegExp('"' + placeholder + '"', 'g'), function () { return fns.shift(); }); return json; }; // adds an element to the array if it does not already exist using a comparer // function global.pushU = function (array, element) { var found = false; for (var i = 0; i < array.length; i++) { if (array[i].id == element.id) found = true; } if (!found) { array.push(element); } }; Date.prototype.weekNumber = function () { // Copy date so don't modify original var d = new Date(this); d.setHours(0); // Set to nearest Thursday: current date + 4 - current day number // Make Sunday's day number 7 d.setDate(d.getDate() + 4 - (d.getDay() || 7)); // Get first day of year var yearStart = new Date(d.getFullYear(), 0, 1); // Calculate full weeks to nearest Thursday var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1) / 7); // Return array of year and week number return [d.getFullYear(), weekNo]; }; Date.prototype.quarterNumber = function () { var d = new Date(this); d = d || new Date(); // If no date supplied, use today var q = [1, 2, 3, 4]; return q[Math.floor(d.getMonth() / 3)]; }; Date.prototype.dayName = function () { var d = new Date(this); var weekday = new Array(7); weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; return weekday[d.getDay()]; }; Date.prototype.format = function (formatString) { var formatDate = this; var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var yyyy = formatDate.getFullYear(); var yy = yyyy.toString().substring(2); var m = formatDate.getMonth() + 1; var mm = m < 10 ? "0" + m : m; var mmm = months[m - 1]; var d = formatDate.getDate(); var dd = d < 10 ? "0" + d : d; var fff = formatDate.getMilliseconds(); fff = (fff < 100 ? fff < 10 ? '00' + fff.toString() : +'0' + fff.toString() : fff.toString()); var h = formatDate.getHours(); var hh = h < 10 ? "0" + h : h; var n = formatDate.getMinutes(); var nn = n < 10 ? "0" + n : n; var s = formatDate.getSeconds(); var ss = s < 10 ? "0" + s : s; formatString = formatString.replace(/yyyy/i, yyyy); formatString = formatString.replace(/yy/i, yy); formatString = formatString.replace(/mmm/i, mmm); formatString = formatString.replace(/mm/i, mm); formatString = formatString.replace(/m/i, m); formatString = formatString.replace(/dd/i, dd); formatString = formatString.replace(/d/i, d); formatString = formatString.replace(/hh/i, hh); //formatString = formatString.replace(/h/i, h); formatString = formatString.replace(/nn/i, nn); //formatString = formatString.replace(/n/i, n); formatString = formatString.replace(/ss/i, ss); formatString = formatString.replace(/fff/i, fff); //formatString = formatString.replace(/s/i, s); return formatString; }; Array.prototype.unique = function () { var a = this.concat(); for (var i = 0; i < a.length; ++i) { for (var j = i + 1; j < a.length; ++j) { if (a[i] === a[j]) a.splice(j--, 1); } } return a; };