Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. const Decimal = require('./types/decimal128');
  6. const ObjectId = require('./types/objectid');
  7. const PromiseProvider = require('./promise_provider');
  8. const cloneRegExp = require('regexp-clone');
  9. const get = require('./helpers/get');
  10. const sliced = require('sliced');
  11. const mpath = require('mpath');
  12. const ms = require('ms');
  13. const Buffer = require('safe-buffer').Buffer;
  14. const emittedSymbol = Symbol.for('mongoose:emitted');
  15. let MongooseBuffer;
  16. let MongooseArray;
  17. let Document;
  18. const specialProperties = new Set(['__proto__', 'constructor', 'prototype']);
  19. exports.specialProperties = specialProperties;
  20. /*!
  21. * Produces a collection name from model `name`. By default, just returns
  22. * the model name
  23. *
  24. * @param {String} name a model name
  25. * @param {Function} pluralize function that pluralizes the collection name
  26. * @return {String} a collection name
  27. * @api private
  28. */
  29. exports.toCollectionName = function(name, pluralize) {
  30. if (name === 'system.profile') {
  31. return name;
  32. }
  33. if (name === 'system.indexes') {
  34. return name;
  35. }
  36. if (typeof pluralize === 'function') {
  37. return pluralize(name);
  38. }
  39. return name;
  40. };
  41. /*!
  42. * Determines if `a` and `b` are deep equal.
  43. *
  44. * Modified from node/lib/assert.js
  45. *
  46. * @param {any} a a value to compare to `b`
  47. * @param {any} b a value to compare to `a`
  48. * @return {Boolean}
  49. * @api private
  50. */
  51. exports.deepEqual = function deepEqual(a, b) {
  52. if (a === b) {
  53. return true;
  54. }
  55. if (a instanceof Date && b instanceof Date) {
  56. return a.getTime() === b.getTime();
  57. }
  58. if ((isBsonType(a, 'ObjectID') && isBsonType(b, 'ObjectID')) ||
  59. (isBsonType(a, 'Decimal128') && isBsonType(b, 'Decimal128'))) {
  60. return a.toString() === b.toString();
  61. }
  62. if (a instanceof RegExp && b instanceof RegExp) {
  63. return a.source === b.source &&
  64. a.ignoreCase === b.ignoreCase &&
  65. a.multiline === b.multiline &&
  66. a.global === b.global;
  67. }
  68. if (typeof a !== 'object' && typeof b !== 'object') {
  69. return a == b;
  70. }
  71. if (a === null || b === null || a === undefined || b === undefined) {
  72. return false;
  73. }
  74. if (a.prototype !== b.prototype) {
  75. return false;
  76. }
  77. // Handle MongooseNumbers
  78. if (a instanceof Number && b instanceof Number) {
  79. return a.valueOf() === b.valueOf();
  80. }
  81. if (Buffer.isBuffer(a)) {
  82. return exports.buffer.areEqual(a, b);
  83. }
  84. if (isMongooseObject(a)) {
  85. a = a.toObject();
  86. }
  87. if (isMongooseObject(b)) {
  88. b = b.toObject();
  89. }
  90. let ka;
  91. let kb;
  92. let key;
  93. let i;
  94. try {
  95. ka = Object.keys(a);
  96. kb = Object.keys(b);
  97. } catch (e) {
  98. // happens when one is a string literal and the other isn't
  99. return false;
  100. }
  101. // having the same number of owned properties (keys incorporates
  102. // hasOwnProperty)
  103. if (ka.length !== kb.length) {
  104. return false;
  105. }
  106. // the same set of keys (although not necessarily the same order),
  107. ka.sort();
  108. kb.sort();
  109. // ~~~cheap key test
  110. for (i = ka.length - 1; i >= 0; i--) {
  111. if (ka[i] !== kb[i]) {
  112. return false;
  113. }
  114. }
  115. // equivalent values for every corresponding key, and
  116. // ~~~possibly expensive deep test
  117. for (i = ka.length - 1; i >= 0; i--) {
  118. key = ka[i];
  119. if (!deepEqual(a[key], b[key])) {
  120. return false;
  121. }
  122. }
  123. return true;
  124. };
  125. /*!
  126. * Get the bson type, if it exists
  127. */
  128. function isBsonType(obj, typename) {
  129. return get(obj, '_bsontype', void 0) === typename;
  130. }
  131. /*!
  132. * Get the last element of an array
  133. */
  134. exports.last = function(arr) {
  135. if (arr.length > 0) {
  136. return arr[arr.length - 1];
  137. }
  138. return void 0;
  139. };
  140. /*!
  141. * Object clone with Mongoose natives support.
  142. *
  143. * If options.minimize is true, creates a minimal data object. Empty objects and undefined values will not be cloned. This makes the data payload sent to MongoDB as small as possible.
  144. *
  145. * Functions are never cloned.
  146. *
  147. * @param {Object} obj the object to clone
  148. * @param {Object} options
  149. * @param {Boolean} isArrayChild true if cloning immediately underneath an array. Special case for minimize.
  150. * @return {Object} the cloned object
  151. * @api private
  152. */
  153. exports.clone = function clone(obj, options, isArrayChild) {
  154. if (obj == null) {
  155. return obj;
  156. }
  157. if (Array.isArray(obj)) {
  158. return cloneArray(obj, options);
  159. }
  160. if (isMongooseObject(obj)) {
  161. if (options && options.json && typeof obj.toJSON === 'function') {
  162. return obj.toJSON(options);
  163. }
  164. return obj.toObject(options);
  165. }
  166. if (obj.constructor) {
  167. switch (exports.getFunctionName(obj.constructor)) {
  168. case 'Object':
  169. return cloneObject(obj, options, isArrayChild);
  170. case 'Date':
  171. return new obj.constructor(+obj);
  172. case 'RegExp':
  173. return cloneRegExp(obj);
  174. default:
  175. // ignore
  176. break;
  177. }
  178. }
  179. if (obj instanceof ObjectId) {
  180. return new ObjectId(obj.id);
  181. }
  182. if (isBsonType(obj, 'Decimal128')) {
  183. if (options && options.flattenDecimals) {
  184. return obj.toJSON();
  185. }
  186. return Decimal.fromString(obj.toString());
  187. }
  188. if (!obj.constructor && exports.isObject(obj)) {
  189. // object created with Object.create(null)
  190. return cloneObject(obj, options, isArrayChild);
  191. }
  192. if (obj.valueOf) {
  193. return obj.valueOf();
  194. }
  195. return cloneObject(obj, options, isArrayChild);
  196. };
  197. const clone = exports.clone;
  198. /*!
  199. * ignore
  200. */
  201. exports.promiseOrCallback = function promiseOrCallback(callback, fn, ee) {
  202. if (typeof callback === 'function') {
  203. return fn(function(error) {
  204. if (error != null) {
  205. if (ee != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) {
  206. error[emittedSymbol] = true;
  207. ee.emit('error', error);
  208. }
  209. try {
  210. callback(error);
  211. } catch (error) {
  212. return process.nextTick(() => {
  213. throw error;
  214. });
  215. }
  216. return;
  217. }
  218. callback.apply(this, arguments);
  219. });
  220. }
  221. const Promise = PromiseProvider.get();
  222. return new Promise((resolve, reject) => {
  223. fn(function(error, res) {
  224. if (error != null) {
  225. if (ee != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) {
  226. error[emittedSymbol] = true;
  227. ee.emit('error', error);
  228. }
  229. return reject(error);
  230. }
  231. if (arguments.length > 2) {
  232. return resolve(Array.prototype.slice.call(arguments, 1));
  233. }
  234. resolve(res);
  235. });
  236. });
  237. };
  238. /*!
  239. * ignore
  240. */
  241. function cloneObject(obj, options, isArrayChild) {
  242. const minimize = options && options.minimize;
  243. const ret = {};
  244. let hasKeys;
  245. for (const k in obj) {
  246. if (specialProperties.has(k)) {
  247. continue;
  248. }
  249. // Don't pass `isArrayChild` down
  250. const val = clone(obj[k], options);
  251. if (!minimize || (typeof val !== 'undefined')) {
  252. hasKeys || (hasKeys = true);
  253. ret[k] = val;
  254. }
  255. }
  256. return minimize && !isArrayChild ? hasKeys && ret : ret;
  257. }
  258. function cloneArray(arr, options) {
  259. const ret = [];
  260. for (let i = 0, l = arr.length; i < l; i++) {
  261. ret.push(clone(arr[i], options, true));
  262. }
  263. return ret;
  264. }
  265. /*!
  266. * Shallow copies defaults into options.
  267. *
  268. * @param {Object} defaults
  269. * @param {Object} options
  270. * @return {Object} the merged object
  271. * @api private
  272. */
  273. exports.options = function(defaults, options) {
  274. const keys = Object.keys(defaults);
  275. let i = keys.length;
  276. let k;
  277. options = options || {};
  278. while (i--) {
  279. k = keys[i];
  280. if (!(k in options)) {
  281. options[k] = defaults[k];
  282. }
  283. }
  284. return options;
  285. };
  286. /*!
  287. * Generates a random string
  288. *
  289. * @api private
  290. */
  291. exports.random = function() {
  292. return Math.random().toString().substr(3);
  293. };
  294. /*!
  295. * Merges `from` into `to` without overwriting existing properties.
  296. *
  297. * @param {Object} to
  298. * @param {Object} from
  299. * @api private
  300. */
  301. exports.merge = function merge(to, from, options, path) {
  302. options = options || {};
  303. const keys = Object.keys(from);
  304. let i = 0;
  305. const len = keys.length;
  306. let key;
  307. path = path || '';
  308. const omitNested = options.omitNested || {};
  309. while (i < len) {
  310. key = keys[i++];
  311. if (options.omit && options.omit[key]) {
  312. continue;
  313. }
  314. if (omitNested[path]) {
  315. continue;
  316. }
  317. if (specialProperties.has(key)) {
  318. continue;
  319. }
  320. if (to[key] == null) {
  321. to[key] = from[key];
  322. } else if (exports.isObject(from[key])) {
  323. if (!exports.isObject(to[key])) {
  324. to[key] = {};
  325. }
  326. if (from[key] != null) {
  327. if (from[key].instanceOfSchema) {
  328. to[key] = from[key].clone();
  329. continue;
  330. } else if (from[key] instanceof ObjectId) {
  331. to[key] = new ObjectId(from[key]);
  332. continue;
  333. }
  334. }
  335. merge(to[key], from[key], options, path ? path + '.' + key : key);
  336. } else if (options.overwrite) {
  337. to[key] = from[key];
  338. }
  339. }
  340. };
  341. /*!
  342. * Applies toObject recursively.
  343. *
  344. * @param {Document|Array|Object} obj
  345. * @return {Object}
  346. * @api private
  347. */
  348. exports.toObject = function toObject(obj) {
  349. Document || (Document = require('./document'));
  350. let ret;
  351. if (obj == null) {
  352. return obj;
  353. }
  354. if (obj instanceof Document) {
  355. return obj.toObject();
  356. }
  357. if (Array.isArray(obj)) {
  358. ret = [];
  359. for (let i = 0, len = obj.length; i < len; ++i) {
  360. ret.push(toObject(obj[i]));
  361. }
  362. return ret;
  363. }
  364. if ((obj.constructor && exports.getFunctionName(obj.constructor) === 'Object') ||
  365. (!obj.constructor && exports.isObject(obj))) {
  366. ret = {};
  367. for (const k in obj) {
  368. if (specialProperties.has(k)) {
  369. continue;
  370. }
  371. ret[k] = toObject(obj[k]);
  372. }
  373. return ret;
  374. }
  375. return obj;
  376. };
  377. /*!
  378. * Determines if `arg` is an object.
  379. *
  380. * @param {Object|Array|String|Function|RegExp|any} arg
  381. * @api private
  382. * @return {Boolean}
  383. */
  384. exports.isObject = function(arg) {
  385. if (Buffer.isBuffer(arg)) {
  386. return true;
  387. }
  388. return Object.prototype.toString.call(arg) === '[object Object]';
  389. };
  390. /*!
  391. * Determines if `arg` is a plain object.
  392. *
  393. * @param {Object|Array|String|Function|RegExp|any} arg
  394. * @api private
  395. * @return {Boolean}
  396. */
  397. exports.isPOJO = function(arg) {
  398. return arg instanceof Object && arg.constructor.name === 'Object';
  399. };
  400. /*!
  401. * A faster Array.prototype.slice.call(arguments) alternative
  402. * @api private
  403. */
  404. exports.args = sliced;
  405. /*!
  406. * process.nextTick helper.
  407. *
  408. * Wraps `callback` in a try/catch + nextTick.
  409. *
  410. * node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback.
  411. *
  412. * @param {Function} callback
  413. * @api private
  414. */
  415. exports.tick = function tick(callback) {
  416. if (typeof callback !== 'function') {
  417. return;
  418. }
  419. return function() {
  420. try {
  421. callback.apply(this, arguments);
  422. } catch (err) {
  423. // only nextTick on err to get out of
  424. // the event loop and avoid state corruption.
  425. process.nextTick(function() {
  426. throw err;
  427. });
  428. }
  429. };
  430. };
  431. /*!
  432. * Returns if `v` is a mongoose object that has a `toObject()` method we can use.
  433. *
  434. * This is for compatibility with libs like Date.js which do foolish things to Natives.
  435. *
  436. * @param {any} v
  437. * @api private
  438. */
  439. exports.isMongooseObject = function(v) {
  440. Document || (Document = require('./document'));
  441. MongooseArray || (MongooseArray = require('./types').Array);
  442. MongooseBuffer || (MongooseBuffer = require('./types').Buffer);
  443. if (v == null) {
  444. return false;
  445. }
  446. return v.$__ != null || // Document
  447. v.isMongooseArray || // Array or Document Array
  448. v.isMongooseBuffer || // Buffer
  449. v.$isMongooseMap; // Map
  450. };
  451. const isMongooseObject = exports.isMongooseObject;
  452. /*!
  453. * Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB.
  454. *
  455. * @param {Object} object
  456. * @api private
  457. */
  458. exports.expires = function expires(object) {
  459. if (!(object && object.constructor.name === 'Object')) {
  460. return;
  461. }
  462. if (!('expires' in object)) {
  463. return;
  464. }
  465. let when;
  466. if (typeof object.expires !== 'string') {
  467. when = object.expires;
  468. } else {
  469. when = Math.round(ms(object.expires) / 1000);
  470. }
  471. object.expireAfterSeconds = when;
  472. delete object.expires;
  473. };
  474. /*!
  475. * Populate options constructor
  476. */
  477. function PopulateOptions(obj) {
  478. this.path = obj.path;
  479. this.match = obj.match;
  480. this.select = obj.select;
  481. this.options = obj.options;
  482. this.model = obj.model;
  483. if (typeof obj.subPopulate === 'object') {
  484. this.populate = obj.subPopulate;
  485. }
  486. if (obj.justOne != null) {
  487. this.justOne = obj.justOne;
  488. }
  489. if (obj.count != null) {
  490. this.count = obj.count;
  491. }
  492. this._docs = {};
  493. }
  494. // make it compatible with utils.clone
  495. PopulateOptions.prototype.constructor = Object;
  496. // expose
  497. exports.PopulateOptions = PopulateOptions;
  498. /*!
  499. * populate helper
  500. */
  501. exports.populate = function populate(path, select, model, match, options, subPopulate, justOne, count) {
  502. // The order of select/conditions args is opposite Model.find but
  503. // necessary to keep backward compatibility (select could be
  504. // an array, string, or object literal).
  505. function makeSingles(arr) {
  506. const ret = [];
  507. arr.forEach(function(obj) {
  508. if (/[\s]/.test(obj.path)) {
  509. const paths = obj.path.split(' ');
  510. paths.forEach(function(p) {
  511. const copy = Object.assign({}, obj);
  512. copy.path = p;
  513. ret.push(copy);
  514. });
  515. } else {
  516. ret.push(obj);
  517. }
  518. });
  519. return ret;
  520. }
  521. // might have passed an object specifying all arguments
  522. if (arguments.length === 1) {
  523. if (path instanceof PopulateOptions) {
  524. return [path];
  525. }
  526. if (Array.isArray(path)) {
  527. const singles = makeSingles(path);
  528. return singles.map(function(o) {
  529. if (o.populate && !(o.match || o.options)) {
  530. return exports.populate(o)[0];
  531. } else {
  532. return exports.populate(o)[0];
  533. }
  534. });
  535. }
  536. if (exports.isObject(path)) {
  537. match = path.match;
  538. options = path.options;
  539. select = path.select;
  540. model = path.model;
  541. subPopulate = path.populate;
  542. justOne = path.justOne;
  543. path = path.path;
  544. count = path.count;
  545. }
  546. } else if (typeof model === 'object') {
  547. options = match;
  548. match = model;
  549. model = undefined;
  550. }
  551. if (typeof path !== 'string') {
  552. throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`');
  553. }
  554. if (Array.isArray(subPopulate)) {
  555. const ret = [];
  556. subPopulate.forEach(function(obj) {
  557. if (/[\s]/.test(obj.path)) {
  558. const copy = Object.assign({}, obj);
  559. const paths = copy.path.split(' ');
  560. paths.forEach(function(p) {
  561. copy.path = p;
  562. ret.push(exports.populate(copy)[0]);
  563. });
  564. } else {
  565. ret.push(exports.populate(obj)[0]);
  566. }
  567. });
  568. subPopulate = exports.populate(ret);
  569. } else if (typeof subPopulate === 'object') {
  570. subPopulate = exports.populate(subPopulate);
  571. }
  572. const ret = [];
  573. const paths = path.split(' ');
  574. options = exports.clone(options);
  575. for (let i = 0; i < paths.length; ++i) {
  576. ret.push(new PopulateOptions({
  577. path: paths[i],
  578. select: select,
  579. match: match,
  580. options: options,
  581. model: model,
  582. subPopulate: subPopulate,
  583. justOne: justOne,
  584. count: count
  585. }));
  586. }
  587. return ret;
  588. };
  589. /*!
  590. * Return the value of `obj` at the given `path`.
  591. *
  592. * @param {String} path
  593. * @param {Object} obj
  594. */
  595. exports.getValue = function(path, obj, map) {
  596. return mpath.get(path, obj, '_doc', map);
  597. };
  598. /*!
  599. * Sets the value of `obj` at the given `path`.
  600. *
  601. * @param {String} path
  602. * @param {Anything} val
  603. * @param {Object} obj
  604. */
  605. exports.setValue = function(path, val, obj, map, _copying) {
  606. mpath.set(path, val, obj, '_doc', map, _copying);
  607. };
  608. /*!
  609. * Returns an array of values from object `o`.
  610. *
  611. * @param {Object} o
  612. * @return {Array}
  613. * @private
  614. */
  615. exports.object = {};
  616. exports.object.vals = function vals(o) {
  617. const keys = Object.keys(o);
  618. let i = keys.length;
  619. const ret = [];
  620. while (i--) {
  621. ret.push(o[keys[i]]);
  622. }
  623. return ret;
  624. };
  625. /*!
  626. * @see exports.options
  627. */
  628. exports.object.shallowCopy = exports.options;
  629. /*!
  630. * Safer helper for hasOwnProperty checks
  631. *
  632. * @param {Object} obj
  633. * @param {String} prop
  634. */
  635. const hop = Object.prototype.hasOwnProperty;
  636. exports.object.hasOwnProperty = function(obj, prop) {
  637. return hop.call(obj, prop);
  638. };
  639. /*!
  640. * Determine if `val` is null or undefined
  641. *
  642. * @return {Boolean}
  643. */
  644. exports.isNullOrUndefined = function(val) {
  645. return val === null || val === undefined;
  646. };
  647. /*!
  648. * ignore
  649. */
  650. exports.array = {};
  651. /*!
  652. * Flattens an array.
  653. *
  654. * [ 1, [ 2, 3, [4] ]] -> [1,2,3,4]
  655. *
  656. * @param {Array} arr
  657. * @param {Function} [filter] If passed, will be invoked with each item in the array. If `filter` returns a falsey value, the item will not be included in the results.
  658. * @return {Array}
  659. * @private
  660. */
  661. exports.array.flatten = function flatten(arr, filter, ret) {
  662. ret || (ret = []);
  663. arr.forEach(function(item) {
  664. if (Array.isArray(item)) {
  665. flatten(item, filter, ret);
  666. } else {
  667. if (!filter || filter(item)) {
  668. ret.push(item);
  669. }
  670. }
  671. });
  672. return ret;
  673. };
  674. /*!
  675. * Removes duplicate values from an array
  676. *
  677. * [1, 2, 3, 3, 5] => [1, 2, 3, 5]
  678. * [ ObjectId("550988ba0c19d57f697dc45e"), ObjectId("550988ba0c19d57f697dc45e") ]
  679. * => [ObjectId("550988ba0c19d57f697dc45e")]
  680. *
  681. * @param {Array} arr
  682. * @return {Array}
  683. * @private
  684. */
  685. exports.array.unique = function(arr) {
  686. const primitives = {};
  687. const ids = {};
  688. const ret = [];
  689. const length = arr.length;
  690. for (let i = 0; i < length; ++i) {
  691. if (typeof arr[i] === 'number' || typeof arr[i] === 'string' || arr[i] == null) {
  692. if (primitives[arr[i]]) {
  693. continue;
  694. }
  695. ret.push(arr[i]);
  696. primitives[arr[i]] = true;
  697. } else if (arr[i] instanceof ObjectId) {
  698. if (ids[arr[i].toString()]) {
  699. continue;
  700. }
  701. ret.push(arr[i]);
  702. ids[arr[i].toString()] = true;
  703. } else {
  704. ret.push(arr[i]);
  705. }
  706. }
  707. return ret;
  708. };
  709. /*!
  710. * Determines if two buffers are equal.
  711. *
  712. * @param {Buffer} a
  713. * @param {Object} b
  714. */
  715. exports.buffer = {};
  716. exports.buffer.areEqual = function(a, b) {
  717. if (!Buffer.isBuffer(a)) {
  718. return false;
  719. }
  720. if (!Buffer.isBuffer(b)) {
  721. return false;
  722. }
  723. if (a.length !== b.length) {
  724. return false;
  725. }
  726. for (let i = 0, len = a.length; i < len; ++i) {
  727. if (a[i] !== b[i]) {
  728. return false;
  729. }
  730. }
  731. return true;
  732. };
  733. exports.getFunctionName = function(fn) {
  734. if (fn.name) {
  735. return fn.name;
  736. }
  737. return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1];
  738. };
  739. /*!
  740. * Decorate buffers
  741. */
  742. exports.decorate = function(destination, source) {
  743. for (const key in source) {
  744. if (specialProperties.has(key)) {
  745. continue;
  746. }
  747. destination[key] = source[key];
  748. }
  749. };
  750. /**
  751. * merges to with a copy of from
  752. *
  753. * @param {Object} to
  754. * @param {Object} fromObj
  755. * @api private
  756. */
  757. exports.mergeClone = function(to, fromObj) {
  758. if (isMongooseObject(fromObj)) {
  759. fromObj = fromObj.toObject({
  760. transform: false,
  761. virtuals: false,
  762. depopulate: true,
  763. getters: false,
  764. flattenDecimals: false
  765. });
  766. }
  767. const keys = Object.keys(fromObj);
  768. const len = keys.length;
  769. let i = 0;
  770. let key;
  771. while (i < len) {
  772. key = keys[i++];
  773. if (specialProperties.has(key)) {
  774. continue;
  775. }
  776. if (typeof to[key] === 'undefined') {
  777. to[key] = exports.clone(fromObj[key], {
  778. transform: false,
  779. virtuals: false,
  780. depopulate: true,
  781. getters: false,
  782. flattenDecimals: false
  783. });
  784. } else {
  785. let val = fromObj[key];
  786. if (val != null && val.valueOf && !(val instanceof Date)) {
  787. val = val.valueOf();
  788. }
  789. if (exports.isObject(val)) {
  790. let obj = val;
  791. if (isMongooseObject(val) && !val.isMongooseBuffer) {
  792. obj = obj.toObject({
  793. transform: false,
  794. virtuals: false,
  795. depopulate: true,
  796. getters: false,
  797. flattenDecimals: false
  798. });
  799. }
  800. if (val.isMongooseBuffer) {
  801. obj = Buffer.from(obj);
  802. }
  803. exports.mergeClone(to[key], obj);
  804. } else {
  805. to[key] = exports.clone(val, {
  806. flattenDecimals: false
  807. });
  808. }
  809. }
  810. }
  811. };
  812. /**
  813. * Executes a function on each element of an array (like _.each)
  814. *
  815. * @param {Array} arr
  816. * @param {Function} fn
  817. * @api private
  818. */
  819. exports.each = function(arr, fn) {
  820. for (let i = 0; i < arr.length; ++i) {
  821. fn(arr[i]);
  822. }
  823. };
  824. /*!
  825. * ignore
  826. */
  827. exports.noop = function() {};