/
utils.js
434 lines (363 loc) · 8.83 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
/**
* Module dependencies.
*/
var EventEmitter = require('events').EventEmitter
, ObjectId = require('./types/objectid')
, MongooseBuffer
, MongooseArray
, Document
/**
* Produces a collection name from a model name
*
* @param {String} model name
* @return {String} collection name
* @api private
*/
exports.toCollectionName = function (name) {
if ('system.profile' === name) return name;
if ('system.indexes' === name) return name;
return pluralize(name.toLowerCase());
};
/**
* Pluralization rules.
*/
var rules = [
[/(m)an$/gi, '$1en'],
[/(pe)rson$/gi, '$1ople'],
[/(child)$/gi, '$1ren'],
[/^(ox)$/gi, '$1en'],
[/(ax|test)is$/gi, '$1es'],
[/(octop|vir)us$/gi, '$1i'],
[/(alias|status)$/gi, '$1es'],
[/(bu)s$/gi, '$1ses'],
[/(buffal|tomat|potat)o$/gi, '$1oes'],
[/([ti])um$/gi, '$1a'],
[/sis$/gi, 'ses'],
[/(?:([^f])fe|([lr])f)$/gi, '$1$2ves'],
[/(hive)$/gi, '$1s'],
[/([^aeiouy]|qu)y$/gi, '$1ies'],
[/(x|ch|ss|sh)$/gi, '$1es'],
[/(matr|vert|ind)ix|ex$/gi, '$1ices'],
[/([m|l])ouse$/gi, '$1ice'],
[/(quiz)$/gi, '$1zes'],
[/s$/gi, 's'],
[/$/gi, 's']
];
/**
* Uncountable words.
*/
var uncountables = [
'advice',
'energy',
'excretion',
'digestion',
'cooperation',
'health',
'justice',
'labour',
'machinery',
'equipment',
'information',
'pollution',
'sewage',
'paper',
'money',
'species',
'series',
'rain',
'rice',
'fish',
'sheep',
'moose',
'deer',
'news'
];
/**
* Pluralize function.
*
* @author TJ Holowaychuk (extracted from _ext.js_)
* @param {String} string to pluralize
* @api private
*/
function pluralize (str) {
var rule, found;
if (!~uncountables.indexOf(str.toLowerCase())){
found = rules.filter(function(rule){
return str.match(rule[0]);
});
if (found[0]) return str.replace(found[0][0], found[0][1]);
}
return str;
};
/**
* Add `once` to EventEmitter if absent
*
* @param {String} event name
* @param {Function} listener
* @api private
*/
var Events = EventEmitter;
if (!('once' in EventEmitter.prototype)){
Events = function () {
EventEmitter.apply(this, arguments);
};
/**
* Inherit from EventEmitter.
*/
Events.prototype.__proto__ = EventEmitter.prototype;
/**
* Add `once`.
*/
Events.prototype.once = function (type, listener) {
var self = this;
self.on(type, function g(){
self.removeListener(type, g);
listener.apply(this, arguments);
});
};
}
exports.EventEmitter = Events;
// Modified from node/lib/assert.js
exports.deepEqual = function deepEqual (a, b) {
if (a === b) return true;
if (a instanceof Date && b instanceof Date)
return a.getTime() === b.getTime();
if (a instanceof ObjectId && b instanceof ObjectId) {
return a.toString() === b.toString();
}
if (typeof a !== 'object' && typeof b !== 'object')
return a == b;
if (a === null || b === null || a === undefined || b === undefined)
return false
if (a.prototype !== b.prototype) return false;
// Handle MongooseNumbers
if (a instanceof Number && b instanceof Number) {
return a.valueOf() === b.valueOf();
}
if (Buffer.isBuffer(a)) {
if (!Buffer.isBuffer(b)) return false;
if (a.length !== b.length) return false;
for (var i = 0, len = a.length; i < len; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
if (isMongooseObject(a)) a = a.toObject();
if (isMongooseObject(b)) b = b.toObject();
try {
var ka = Object.keys(a),
kb = Object.keys(b),
key, i;
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!deepEqual(a[key], b[key])) return false;
}
return true;
};
/**
* Object clone with Mongoose natives support.
* Creates a minimal data Object.
* It does not clone empty Arrays, empty Objects,
* and undefined values.
* This makes the data payload sent to MongoDB as minimal
* as possible.
*
* @param {Object} object to clone
* @param {Object} options - minimize , retainKeyOrder
* @return {Object} cloned object
* @api private
*/
var clone = exports.clone = function clone (obj, options) {
if (obj === undefined || obj === null)
return obj;
if (Array.isArray(obj))
return cloneArray(obj, options);
if (isMongooseObject(obj)) {
if (options && options.json && 'function' === typeof obj.toJSON) {
return obj.toJSON(options);
} else {
return obj.toObject(options);
}
}
if ('Object' === obj.constructor.name)
return cloneObject(obj, options);
if ('Date' === obj.constructor.name || 'Function' === obj.constructor.name)
return new obj.constructor(+obj);
if ('RegExp' === obj.constructor.name)
return new RegExp(obj.source);
if (obj instanceof ObjectId)
return ObjectId.fromString(ObjectId.toString(obj));
if (obj.valueOf)
return obj.valueOf();
};
function cloneObject (obj, options) {
var retainKeyOrder = options && options.retainKeyOrder
, minimize = options && options.minimize
, ret = {}
, hasKeys
, keys
, val
, k
, i
if (retainKeyOrder) {
for (k in obj) {
val = clone(obj[k], options);
if (!minimize || ('undefined' !== typeof val)) {
hasKeys || (hasKeys = true);
ret[k] = val;
}
}
} else {
// faster
keys = Object.keys(obj);
i = keys.length;
while (i--) {
k = keys[i];
val = clone(obj[k], options);
if (!minimize || ('undefined' !== typeof val)) {
if (!hasKeys) hasKeys = true;
ret[k] = val;
}
}
}
return minimize
? hasKeys && ret
: ret;
};
function cloneArray (arr, options) {
var ret = [];
for (var i = 0, l = arr.length; i < l; i++)
ret.push(clone(arr[i], options));
return ret;
};
/**
* Copies and merges options with defaults.
*
* @param {Object} defaults
* @param {Object} options
* @return {Object} (merged) object
* @api private
*/
exports.options = function (defaults, options) {
var keys = Object.keys(defaults)
, i = keys.length
, k ;
options = options || {};
while (i--) {
k = keys[i];
if (!(k in options)) {
options[k] = defaults[k];
}
}
return options;
};
/**
* Generates a random string
*
* @api private
*/
exports.random = function () {
return Math.random().toString().substr(3);
};
exports.inGroupsOf = function inGroupsOf (card, arr, fn) {
var group = [];
for (var i = 0, l = arr.length; i < l; i++) {
if (i && i % card === 0) {
fn.apply(this, group);
group.length = 0;
}
group.push(arr[i]);
}
fn.apply(this, group);
};
/**
* Merges `from` into `to` without overwriting
* existing properties of `to`.
*
* @param {Object} to
* @param {Object} from
*/
exports.merge = function merge (to, from) {
var keys = Object.keys(from)
, i = keys.length
, key
while (i--) {
key = keys[i];
if ('undefined' === typeof to[key]) {
to[key] = from[key];
} else {
merge(to[key], from[key]);
}
}
};
/**
* A faster Array.prototype.slice.call(arguments) alternative
*/
exports.args = function (args, slice, sliceEnd) {
var ret = [];
var start = slice || 0;
var end = 3 === arguments.length
? sliceEnd
: args.length;
for (var i = start; i < end; ++i) {
ret[i - start] = args[i];
}
return ret;
}
/**
* process.nextTick helper.
*
* Wraps `callback` in a try/catch + nextTick.
*
* -native has a habit of state corruption
* when an error is immediately thrown from within
* a collection callback.
*
* @param {Function} callback
* @api private
*/
exports.tick = function tick (callback) {
if ('function' !== typeof callback) return;
return function () {
try {
callback.apply(this, arguments);
} catch (err) {
// only nextTick on err to get out of
// the event loop and avoid state corruption.
process.nextTick(function () {
throw err;
});
}
}
}
/**
* Returns if `v` is a mongoose object that has
* a `toObject()` method we can use. This is for
* compatibility with libs like Date.js which do
* foolish things to Natives.
*/
var isMongooseObject = exports.isMongooseObject = function (v) {
Document || (Document = require('./document'));
MongooseArray || (MongooseArray = require('./types').Array);
MongooseBuffer || (MongooseBuffer = require('./types').Buffer);
return v instanceof Document ||
v instanceof MongooseArray ||
v instanceof MongooseBuffer
}