UNPKG

11.9 kBJavaScriptView Raw
1/**
2 * joola.io
3 *
4 * Copyright Joola Smart Solutions, Ltd. <info@joo.la>
5 *
6 * Licensed under GNU General Public License 3.0 or later.
7 * Some rights reserved. See LICENSE, AUTHORS.
8 *
9 * @license GPL-3.0+ <http://spdx.org/licenses/GPL-3.0+>
10 */
11
12var
13 async = require('async'),
14 ce = require('cloneextend');
15
16global._ = require('underscore');
17
18global.fork = function (async_calls, shared_callback) {
19 async.parallel(async_calls, shared_callback);
20};
21
22global.forkSeries = function (async_calls, shared_callback) {
23 async.series(async_calls, shared_callback);
24};
25
26global.randomBetween = function (min, max) {
27 return Math.floor(Math.random() * (max - min + 1)) + min;
28};
29
30global.chunk = function (array, chunkSize) {
31 var lists = _.groupBy(array, function (a, b) {
32 return Math.floor(b / chunkSize);
33 });
34 lists = _.toArray(lists);
35 return lists;
36};
37
38try {
39 Object.defineProperty(global, '__stack', {
40 get: function () {
41 var orig = Error.prepareStackTrace;
42 Error.prepareStackTrace = function (_, stack) {
43 return stack;
44 };
45 var err = new Error;
46 Error.captureStackTrace(err, arguments.callee);
47 var stack = err.stack;
48 Error.prepareStackTrace = orig;
49 return stack;
50 }
51 });
52
53 Object.defineProperty(global, '__caller_line', {
54 get: function () {
55 return __stack[1].getLineNumber();
56 }
57 });
58
59 Object.defineProperty(global, '__caller_function', {
60 get: function () {
61 return __stack[1].getFunctionName();
62 }
63 });
64}
65catch (ex) {
66
67}
68
69/**
70 * Generates a random string of characters for the specific number of bits
71 *
72 * @method randomString
73 * @param {int} bits number of bits to use
74 * @return {string} A random string of characters
75 */
76exports.randomString = function (bits) {
77 var chars, rand, i, ret;
78 chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
79 ret = '';
80
81 // in v8, Math.random() yields 32 pseudo-random bits (in spidermonkey it gives 53)
82 while (bits > 0) {
83 rand = Math.floor(Math.random() * 0x100000000); // 32-bit integer
84 // base 64 means 6 bits per character, so we use the top 30 bits from rand to give 30/6=5 characters.
85 for (i = 26; i > 0 && bits > 0; i -= 6, bits -= 6) ret += chars[0x3F & rand >>> i]
86 }
87
88 return ret;
89};
90
91function formatDate(formatDate, formatString, adjustGMT) {
92 if (adjustGMT&&false) {
93 formatDate = new Date(formatDate);
94
95 var sign = (formatDate.getTimezoneOffset() > 0) ? 1 : -1;
96 var offset = Math.abs(formatDate.getTimezoneOffset());
97 var hours = Math.floor(offset / 60);
98
99 formatDate.setHours(formatDate.getHours() + (sign * hours));
100 }
101 if (formatDate instanceof Date) {
102 var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
103 var yyyy = formatDate.getFullYear();
104 var yy = yyyy.toString().substring(2);
105 var m = formatDate.getMonth() + 1;
106 var mm = m < 10 ? "0" + m : m;
107 var mmm = months[m - 1];
108 var d = formatDate.getDate();
109 var dd = d < 10 ? "0" + d : d;
110 var fff = formatDate.getMilliseconds();
111 fff = (fff < 100 ? fff < 10 ? '00' + fff : +'0' + fff : fff);
112 var h = formatDate.getHours();
113 var hh = h < 10 ? "0" + h : h;
114 var n = formatDate.getMinutes();
115 var nn = n < 10 ? "0" + n : n;
116 var s = formatDate.getSeconds();
117 var ss = s < 10 ? "0" + s : s;
118
119 if (formatString == null)
120 formatString = jarvis.dateformat;
121
122 formatString = formatString.replace(/yyyy/i, yyyy);
123 formatString = formatString.replace(/yy/i, yy);
124 formatString = formatString.replace(/mmm/i, mmm);
125 formatString = formatString.replace(/mm/i, mm);
126 //formatString = formatString.replace(/m/i, m);
127 formatString = formatString.replace(/dd/i, dd);
128 //formatString = formatString.replace(/d/i, d);
129 formatString = formatString.replace(/hh/i, hh);
130 //formatString = formatString.replace(/h/i, h);
131 formatString = formatString.replace(/nn/i, nn);
132 //formatString = formatString.replace(/n/i, n);
133 formatString = formatString.replace(/ss/i, ss);
134 formatString = formatString.replace(/fff/i, fff);
135 //formatString = formatString.replace(/s/i, s);
136
137 return formatString;
138 } else {
139 return "";
140 }
141}
142
143/**
144 * Used to format date according to standard formatting options
145 *
146 * @method formatDate
147 * @param {string} formatDate date to format
148 * @param {string} formatString format to convert the date by
149 * @param {bool} adjustGMT should GMT adjustments be applied
150 * @return {string} formatted date
151 */
152exports.formatDate = formatDate;
153
154Date.prototype.fixDate = function (force, direction, isZ) {
155 return this;
156
157 date = this;
158 if (!force)
159 return date;
160
161 var sign;
162 if (!direction)
163 sign = (date.getTimezoneOffset() > 0) ? 1 : -1;
164 else
165 sign = (date.getTimezoneOffset() > 0) ? -1 : 1;
166
167 var offset = Math.abs(date.getTimezoneOffset());
168 var hours = Math.floor(offset / 60);
169 if (isZ) {
170 date.addHours(hours);
171 }
172 date.setHours(date.getHours() + (sign * hours));
173
174 return date;
175};
176/*
177function pad(str, char, length) {
178 while (str.length < length)
179 str = char + str;
180 return str;
181}
182
183
184String.prototype.pad = function (char, length) {
185 return this.length >= length ? this : pad(this, char, 2);
186};*/
187
188Date.prototype.clean = function () {
189 return formatDate(this, 'yyyy-mm-dd hh:nn:ss').clean();
190};
191
192Date.prototype.getWeek = function () {
193 var onejan = new Date(this.getFullYear(), 0, 1);
194 return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
195};
196
197Date.prototype.roundYear = function () {
198 return new Date(this.getFullYear(), 0, 0, 0, 0, 0, 0);
199};
200
201Date.prototype.roundMonth = function () {
202 return new Date(this.getFullYear(), this.getMonth(), 0, 0, 0, 0, 0);
203};
204
205Date.prototype.roundDay = function () {
206 return new Date(this.getYear(), this.getMonth(), this.getDate(), 0, 0, 0, 0);
207};
208
209Date.prototype.roundHour = function () {
210 return new Date(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), 0, 0, 0);
211};
212
213Date.prototype.roundMinute = function () {
214 return new Date(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), 0, 0);
215};
216
217Date.prototype.roundSecond = function () {
218 return new Date(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), 0);
219};
220
221
222String.prototype.clean = function () {
223 var result = this;
224 result = result.replace(/ /g, '');
225 result = result.replace(/\./g, '');
226 result = result.replace(/-/g, '');
227 result = result.replace(/\\/g, '');
228 result = result.replace(/\//g, '');
229 result = result.replace(/:/g, '');
230 result = result.replace(/{/g, '');
231 result = result.replace(/}/g, '');
232 result = result.replace(/"/g, '');
233 return result;
234};
235
236String.prototype.trim = function () {
237 return this.replace(/^\s+|\s+$/g, '');
238};
239/*
240String.prototype.ltrim = function () {
241 return this.replace(/^\s+/, '');
242};
243
244String.prototype.rtrim = function () {
245 return this.replace(/\s+$/, '');
246};
247
248String.prototype.fulltrim = function () {
249 return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, '').replace(/\s+/g, ' ');
250};
251*/
252
253Date.prototype.dateDiff = function (comparedtodate) {
254
255 var first = this;
256 // Copy date parts of the timestamps, discarding the time parts.
257 var one = new Date(first.getFullYear(), first.getMonth(), first.getDate());
258 var two = new Date(comparedtodate.getFullYear(), comparedtodate.getMonth(), comparedtodate.getDate());
259
260 // Do the math.
261 var millisecondsPerDay = 1000 * 60 * 60 * 24;
262 var millisBetween = two.getTime() - one.getTime();
263 var days = millisBetween / millisecondsPerDay;
264
265 // Round down.
266 return Math.floor(Math.abs(days));
267};
268
269exports.cleanObject = function (obj) {
270 var _this = ce.clone(obj);
271
272 _.each(_this, function (value, key) {
273 if (key.substring(0, 1) == '_')
274 delete _this[key];
275 });
276
277 return _this;
278};
279
280exports.shorten = function () {
281 return Math.floor(Math.random() * 10) + parseInt(new Date().getTime()).toString(36).toLowerCase();
282};
283
284global.stringify = function (obj) {
285 var placeholder = '____PLACEHOLDER____';
286 var fns = [];
287 var json = JSON.stringify(obj, function (key, value) {
288 if (typeof value === 'function') {
289 fns.push(value);
290 return placeholder;
291 }
292 return value;
293 }, 2);
294 json = json.replace(new RegExp('"' + placeholder + '"', 'g'), function () {
295 return fns.shift();
296 });
297 return json;
298};
299
300// adds an element to the array if it does not already exist using a comparer
301// function
302global.pushU = function (array, element) {
303 var found = false;
304 for (var i = 0; i < array.length; i++) {
305 if (array[i].id == element.id)
306 found = true;
307 }
308 if (!found) {
309 array.push(element);
310 }
311};
312
313Date.prototype.weekNumber = function () {
314 // Copy date so don't modify original
315 var d = new Date(this);
316 d.setHours(0);
317 // Set to nearest Thursday: current date + 4 - current day number
318 // Make Sunday's day number 7
319 d.setDate(d.getDate() + 4 - (d.getDay() || 7));
320 // Get first day of year
321 var yearStart = new Date(d.getFullYear(), 0, 1);
322 // Calculate full weeks to nearest Thursday
323 var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1) / 7);
324 // Return array of year and week number
325 return [d.getFullYear(), weekNo];
326};
327
328Date.prototype.quarterNumber = function () {
329 var d = new Date(this);
330 d = d || new Date(); // If no date supplied, use today
331 var q = [1, 2, 3, 4];
332 return q[Math.floor(d.getMonth() / 3)];
333};
334
335Date.prototype.dayName = function () {
336 var d = new Date(this);
337 var weekday = new Array(7);
338 weekday[0] = "Sunday";
339 weekday[1] = "Monday";
340 weekday[2] = "Tuesday";
341 weekday[3] = "Wednesday";
342 weekday[4] = "Thursday";
343 weekday[5] = "Friday";
344 weekday[6] = "Saturday";
345
346 return weekday[d.getDay()];
347};
348
349Date.prototype.format = function (formatString) {
350 var formatDate = this;
351 var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
352 var yyyy = formatDate.getFullYear();
353 var yy = yyyy.toString().substring(2);
354 var m = formatDate.getMonth() + 1;
355 var mm = m < 10 ? "0" + m : m;
356 var mmm = months[m - 1];
357 var d = formatDate.getDate();
358 var dd = d < 10 ? "0" + d : d;
359 var fff = formatDate.getMilliseconds().toString();
360 fff = (fff < 100 ? fff < 10 ? '00' + fff : +'0' + fff : fff);
361 var h = formatDate.getHours();
362 var hh = h < 10 ? "0" + h : h;
363 var n = formatDate.getMinutes();
364 var nn = n < 10 ? "0" + n : n;
365 var s = formatDate.getSeconds();
366 var ss = s < 10 ? "0" + s : s;
367
368 formatString = formatString.replace(/yyyy/i, yyyy);
369 formatString = formatString.replace(/yy/i, yy);
370 formatString = formatString.replace(/mmm/i, mmm);
371 formatString = formatString.replace(/mm/i, mm);
372 formatString = formatString.replace(/m/i, m);
373 formatString = formatString.replace(/dd/i, dd);
374 formatString = formatString.replace(/d/i, d);
375 formatString = formatString.replace(/hh/i, hh);
376 //formatString = formatString.replace(/h/i, h);
377 formatString = formatString.replace(/nn/i, nn);
378 //formatString = formatString.replace(/n/i, n);
379 formatString = formatString.replace(/ss/i, ss);
380 formatString = formatString.replace(/fff/i, fff);
381 //formatString = formatString.replace(/s/i, s);
382
383 return formatString;
384};
385
386Array.prototype.unique = function() {
387 var a = this.concat();
388 for(var i=0; i<a.length; ++i) {
389 for(var j=i+1; j<a.length; ++j) {
390 if(a[i] === a[j])
391 a.splice(j--, 1);
392 }
393 }
394
395 return a;
396};
\No newline at end of file