UNPKG

2.09 kBJavaScriptView Raw
1/*!
2 * A MongoDB inspired ES6 Map() query language. - Copyright (c) 2017 Louis T. (https://lou.ist/)
3 * Licensed under the MIT license https://raw.githubusercontent.com/LouisT/MapQL/master/LICENSE
4 */
5'use strict';
6const Helpers = require('./Helpers');
7
8class Cursor extends Array {
9 constructor () {
10 super();
11 }
12
13 /*
14 * Check if the Cursor already has a Document.
15 */
16 has (doc) {
17 return !(this.indexOf(doc) <= -1);
18 }
19
20 /*
21 * If `docs` is a valid Document object, add it to the Cursor if it doesn't already exist.
22 */
23 add (docs = []) {
24 Array.prototype.push.apply(this, (Array.isArray(docs) ? docs : [docs]).filter((doc) => {
25 return doc.isDocument && !this.has(doc);
26 }));
27
28 return this;
29 }
30
31 /*
32 * Check if this is empty or not.
33 */
34 empty () {
35 return !(this.length >= 1);
36 }
37
38 /*
39 * Sort by object keys, -1 for descending.
40 */
41 sort (sort = {}) {
42 let obj = Helpers.is(sort, 'Object') ? sort : { default: sort };
43 Object.keys(obj).forEach((key, idx) => {
44 Array.prototype.sort.call(this, (a, b) => {
45 let vals = (Helpers.is(a.value, 'Object') && Helpers.is(b.value, 'Object')) ? Helpers.dotNotation(key, [a.value, b.value]) : [a, b];
46 return (vals[0] < vals[1]) ? -1 : ((vals[0] > vals[1]) ? 1 : 0);
47 })[obj[key] === -1 ? 'reverse' : 'valueOf']().forEach((val, idx2) => {
48 return this[idx2] = val;
49 });
50 });
51 return this;
52 }
53
54 /*
55 * Return a specified number of results, default to 1.
56 */
57 limit (num = false) {
58 return Helpers.is(num, 'Number') ? this.slice(0, num) : this;
59 }
60
61 /*
62 * Allow the class to have a custom object string tag.
63 */
64 get [Symbol.toStringTag]() {
65 return (this.constructor.name || 'Cursor');
66 }
67}
68
69/*
70 * Export the `Cursor` class for use!
71 */
72module.exports = Cursor;