@orchidjs/sifter 0.9.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +3 -1
  2. package/dist/cjs/sifter.js +783 -60
  3. package/dist/cjs/sifter.js.map +1 -1
  4. package/dist/esm/lib/sifter.js +368 -0
  5. package/dist/esm/lib/sifter.js.map +1 -0
  6. package/dist/{cjs → esm/lib}/utils.js +5 -24
  7. package/dist/esm/lib/utils.js.map +1 -0
  8. package/dist/esm/node_modules/@orchidjs/unicode-variants/dist/esm/index.js +508 -0
  9. package/dist/esm/node_modules/@orchidjs/unicode-variants/dist/esm/index.js.map +1 -0
  10. package/dist/esm/node_modules/@orchidjs/unicode-variants/dist/esm/regex.js +113 -0
  11. package/dist/esm/node_modules/@orchidjs/unicode-variants/dist/esm/regex.js.map +1 -0
  12. package/dist/esm/node_modules/@orchidjs/unicode-variants/dist/esm/strings.js +29 -0
  13. package/dist/esm/node_modules/@orchidjs/unicode-variants/dist/esm/strings.js.map +1 -0
  14. package/dist/esm/sifter.js +40 -48
  15. package/dist/esm/sifter.js.map +1 -1
  16. package/dist/esm/utils.js +3 -12
  17. package/dist/esm/utils.js.map +1 -1
  18. package/dist/types/sifter.d.ts +14 -7
  19. package/dist/types/types.d.ts +8 -7
  20. package/dist/types/utils.d.ts +3 -7
  21. package/dist/umd/sifter.js +1101 -646
  22. package/dist/umd/sifter.js.map +1 -1
  23. package/dist/umd/sifter.min.js +110 -79
  24. package/dist/umd/sifter.min.js.map +1 -1
  25. package/lib/sifter.ts +55 -64
  26. package/lib/types.ts +14 -10
  27. package/lib/utils.ts +4 -14
  28. package/package.json +6 -3
  29. package/dist/cjs/diacritics.js +0 -186
  30. package/dist/cjs/diacritics.js.map +0 -1
  31. package/dist/cjs/utils.js.map +0 -1
  32. package/dist/esm/diacritics.js +0 -177
  33. package/dist/esm/diacritics.js.map +0 -1
  34. package/dist/types/diacritics.d.ts +0 -35
  35. package/lib/diacritics.ts +0 -199
@@ -1,651 +1,1106 @@
1
1
  /*! sifter.js | https://github.com/orchidjs/sifter.js | Apache License (v2) */
2
2
  (function (global, factory) {
3
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
4
- typeof define === 'function' && define.amd ? define(factory) :
5
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.sifter = factory());
6
- }(this, (function () { 'use strict';
7
-
8
- // @ts-ignore TS2691 "An import path cannot end with a '.ts' extension"
9
- // https://github.com/andrewrk/node-diacritics/blob/master/index.js
10
- var latin_pat;
11
- const accent_pat = '[\u0300-\u036F\u{b7}\u{2be}]'; // \u{2bc}
12
-
13
- const accent_reg = new RegExp(accent_pat, 'gu');
14
- var diacritic_patterns;
15
- const latin_convert = {
16
- 'æ': 'ae',
17
- 'ⱥ': 'a',
18
- 'ø': 'o'
19
- };
20
- const convert_pat = new RegExp(Object.keys(latin_convert).join('|'), 'gu');
21
- const code_points = [[0, 65535]];
22
- /**
23
- * Remove accents
24
- * via https://github.com/krisk/Fuse/issues/133#issuecomment-318692703
25
- *
26
- */
27
-
28
- const asciifold = str => {
29
- return str.normalize('NFKD').replace(accent_reg, '').toLowerCase().replace(convert_pat, function (foreignletter) {
30
- return latin_convert[foreignletter];
31
- });
32
- };
33
- /**
34
- * Convert array of strings to a regular expression
35
- * ex ['ab','a'] => (?:ab|a)
36
- * ex ['a','b'] => [ab]
37
- *
38
- */
39
-
40
- const arrayToPattern = (chars, glue = '|') => {
41
- if (chars.length == 1) {
42
- return chars[0];
43
- }
44
-
45
- var longest = 1;
46
- chars.forEach(a => {
47
- longest = Math.max(longest, a.length);
48
- });
49
-
50
- if (longest == 1) {
51
- return '[' + chars.join('') + ']';
52
- }
53
-
54
- return '(?:' + chars.join(glue) + ')';
55
- };
56
- const escapeToPattern = chars => {
57
- const escaped = chars.map(diacritic => escape_regex(diacritic));
58
- return arrayToPattern(escaped);
59
- };
60
- /**
61
- * Get all possible combinations of substrings that add up to the given string
62
- * https://stackoverflow.com/questions/30169587/find-all-the-combination-of-substrings-that-add-up-to-the-given-string
63
- *
64
- */
65
-
66
- const allSubstrings = input => {
67
- if (input.length === 1) return [[input]];
68
- var result = [];
69
- allSubstrings(input.substring(1)).forEach(function (subresult) {
70
- var tmp = subresult.slice(0);
71
- tmp[0] = input.charAt(0) + tmp[0];
72
- result.push(tmp);
73
- tmp = subresult.slice(0);
74
- tmp.unshift(input.charAt(0));
75
- result.push(tmp);
76
- });
77
- return result;
78
- };
79
- /**
80
- * Generate a list of diacritics from the list of code points
81
- *
82
- */
83
-
84
- const generateDiacritics = code_points => {
85
- var diacritics = {};
86
- code_points.forEach(code_range => {
87
- for (let i = code_range[0]; i <= code_range[1]; i++) {
88
- let diacritic = String.fromCharCode(i);
89
- let latin = asciifold(diacritic);
90
-
91
- if (latin == diacritic.toLowerCase()) {
92
- continue;
93
- } // skip when latin is a string longer than 3 characters long
94
- // bc the resulting regex patterns will be long
95
- // eg:
96
- // latin صلى الله عليه وسلم length 18 code point 65018
97
- // latin جل جلاله length 8 code point 65019
98
-
99
-
100
- if (latin.length > 3) {
101
- continue;
102
- }
103
-
104
- if (!(latin in diacritics)) {
105
- diacritics[latin] = [latin];
106
- }
107
-
108
- var patt = new RegExp(escapeToPattern(diacritics[latin]), 'iu');
109
-
110
- if (diacritic.match(patt)) {
111
- continue;
112
- }
113
-
114
- diacritics[latin].push(diacritic);
115
- }
116
- }); // filter out if there's only one character in the list
117
-
118
- let latin_chars = Object.keys(diacritics);
119
-
120
- for (let i = 0; i < latin_chars.length; i++) {
121
- const latin = latin_chars[i];
122
-
123
- if (diacritics[latin].length < 2) {
124
- delete diacritics[latin];
125
- }
126
- } // latin character pattern
127
- // match longer substrings first
128
-
129
-
130
- latin_chars = Object.keys(diacritics).sort((a, b) => b.length - a.length);
131
- latin_pat = new RegExp('(' + escapeToPattern(latin_chars) + accent_pat + '*)', 'gu'); // build diacritic patterns
132
- // ae needs:
133
- // (?:(?:ae|Æ|Ǽ|Ǣ)|(?:A|Ⓐ|A...)(?:E|ɛ|Ⓔ...))
134
-
135
- var diacritic_patterns = {};
136
- latin_chars.sort((a, b) => a.length - b.length).forEach(latin => {
137
- var substrings = allSubstrings(latin);
138
- var pattern = substrings.map(sub_pat => {
139
- sub_pat = sub_pat.map(l => {
140
- if (diacritics.hasOwnProperty(l)) {
141
- return escapeToPattern(diacritics[l]);
142
- }
143
-
144
- return l;
145
- });
146
- return arrayToPattern(sub_pat, '');
147
- });
148
- diacritic_patterns[latin] = arrayToPattern(pattern);
149
- });
150
- return diacritic_patterns;
151
- };
152
- /**
153
- * Expand a regular expression pattern to include diacritics
154
- * eg /a/ becomes /aⓐaẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐɑAⒶAÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄȺⱯ/
155
- *
156
- */
157
-
158
- const diacriticRegexPoints = regex => {
159
- if (diacritic_patterns === undefined) {
160
- diacritic_patterns = generateDiacritics(code_points);
161
- }
162
-
163
- const decomposed = regex.normalize('NFKD').toLowerCase();
164
- return decomposed.split(latin_pat).map(part => {
165
- // "ffl" or "ffl"
166
- const no_accent = asciifold(part);
167
-
168
- if (no_accent == '') {
169
- return '';
170
- }
171
-
172
- if (diacritic_patterns.hasOwnProperty(no_accent)) {
173
- return diacritic_patterns[no_accent];
174
- }
175
-
176
- return part;
177
- }).join('');
178
- };
179
-
180
- // @ts-ignore TS2691 "An import path cannot end with a '.ts' extension"
181
-
182
- /**
183
- * A property getter resolving dot-notation
184
- * @param {Object} obj The root object to fetch property on
185
- * @param {String} name The optionally dotted property name to fetch
186
- * @return {Object} The resolved property value
187
- */
188
- const getAttr = (obj, name) => {
189
- if (!obj) return;
190
- return obj[name];
191
- };
192
- /**
193
- * A property getter resolving dot-notation
194
- * @param {Object} obj The root object to fetch property on
195
- * @param {String} name The optionally dotted property name to fetch
196
- * @return {Object} The resolved property value
197
- */
198
-
199
- const getAttrNesting = (obj, name) => {
200
- if (!obj) return;
201
- var part,
202
- names = name.split(".");
203
-
204
- while ((part = names.shift()) && (obj = obj[part]));
205
-
206
- return obj;
207
- };
208
- /**
209
- * Calculates how close of a match the
210
- * given value is against a search token.
211
- *
212
- */
213
-
214
- const scoreValue = (value, token, weight) => {
215
- var score, pos;
216
- if (!value) return 0;
217
- value = value + '';
218
- pos = value.search(token.regex);
219
- if (pos === -1) return 0;
220
- score = token.string.length / value.length;
221
- if (pos === 0) score += 0.5;
222
- return score * weight;
223
- };
224
- /**
225
- *
226
- * https://stackoverflow.com/questions/63006601/why-does-u-throw-an-invalid-escape-error
227
- */
228
-
229
- const escape_regex = str => {
230
- return (str + '').replace(/([\$\(-\+\.\?\[-\^\{-\}])/g, '\\$1');
231
- };
232
- /**
233
- * Cast object property to an array if it exists and has a value
234
- *
235
- */
236
-
237
- const propToArray = (obj, key) => {
238
- var value = obj[key];
239
- if (typeof value == 'function') return value;
240
-
241
- if (value && !Array.isArray(value)) {
242
- obj[key] = [value];
243
- }
244
- };
245
- /**
246
- * Iterates over arrays and hashes.
247
- *
248
- * ```
249
- * iterate(this.items, function(item, id) {
250
- * // invoked for each item
251
- * });
252
- * ```
253
- *
254
- */
255
-
256
- const iterate = (object, callback) => {
257
- if (Array.isArray(object)) {
258
- object.forEach(callback);
259
- } else {
260
- for (var key in object) {
261
- if (object.hasOwnProperty(key)) {
262
- callback(object[key], key);
263
- }
264
- }
265
- }
266
- };
267
- const cmp = (a, b) => {
268
- if (typeof a === 'number' && typeof b === 'number') {
269
- return a > b ? 1 : a < b ? -1 : 0;
270
- }
271
-
272
- a = asciifold(a + '').toLowerCase();
273
- b = asciifold(b + '').toLowerCase();
274
- if (a > b) return 1;
275
- if (b > a) return -1;
276
- return 0;
277
- };
278
-
279
- /**
280
- * sifter.js
281
- * Copyright (c) 2013–2020 Brian Reavis & contributors
282
- *
283
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
284
- * file except in compliance with the License. You may obtain a copy of the License at:
285
- * http://www.apache.org/licenses/LICENSE-2.0
286
- *
287
- * Unless required by applicable law or agreed to in writing, software distributed under
288
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
289
- * ANY KIND, either express or implied. See the License for the specific language
290
- * governing permissions and limitations under the License.
291
- *
292
- * @author Brian Reavis <brian@thirdroute.com>
293
- */
294
-
295
- class Sifter {
296
- // []|{};
297
-
298
- /**
299
- * Textually searches arrays and hashes of objects
300
- * by property (or multiple properties). Designed
301
- * specifically for autocomplete.
302
- *
303
- */
304
- constructor(items, settings) {
305
- this.items = void 0;
306
- this.settings = void 0;
307
- this.items = items;
308
- this.settings = settings || {
309
- diacritics: true
310
- };
311
- }
312
-
313
- /**
314
- * Splits a search string into an array of individual
315
- * regexps to be used to match results.
316
- *
317
- */
318
- tokenize(query, respect_word_boundaries, weights) {
319
- if (!query || !query.length) return [];
320
- const tokens = [];
321
- const words = query.split(/\s+/);
322
- var field_regex;
323
-
324
- if (weights) {
325
- field_regex = new RegExp('^(' + Object.keys(weights).map(escape_regex).join('|') + ')\:(.*)$');
326
- }
327
-
328
- words.forEach(word => {
329
- let field_match;
330
- let field = null;
331
- let regex = null; // look for "field:query" tokens
332
-
333
- if (field_regex && (field_match = word.match(field_regex))) {
334
- field = field_match[1];
335
- word = field_match[2];
336
- }
337
-
338
- if (word.length > 0) {
339
- if (this.settings.diacritics) {
340
- regex = diacriticRegexPoints(word);
341
- } else {
342
- regex = escape_regex(word);
343
- }
344
-
345
- if (respect_word_boundaries) regex = "\\b" + regex;
346
- }
347
-
348
- tokens.push({
349
- string: word,
350
- regex: regex ? new RegExp(regex, 'iu') : null,
351
- field: field
352
- });
353
- });
354
- return tokens;
355
- }
356
-
357
- /**
358
- * Returns a function to be used to score individual results.
359
- *
360
- * Good matches will have a higher score than poor matches.
361
- * If an item is not a match, 0 will be returned by the function.
362
- *
363
- * @returns {function}
364
- */
365
- getScoreFunction(query, options) {
366
- var search = this.prepareSearch(query, options);
367
- return this._getScoreFunction(search);
368
- }
369
-
370
- _getScoreFunction(search) {
371
- const tokens = search.tokens,
372
- token_count = tokens.length;
373
-
374
- if (!token_count) {
375
- return function () {
376
- return 0;
377
- };
378
- }
379
-
380
- const fields = search.options.fields,
381
- weights = search.weights,
382
- field_count = fields.length,
383
- getAttrFn = search.getAttrFn;
384
-
385
- if (!field_count) {
386
- return function () {
387
- return 1;
388
- };
389
- }
390
- /**
391
- * Calculates the score of an object
392
- * against the search query.
393
- *
394
- */
395
-
396
-
397
- const scoreObject = function () {
398
- if (field_count === 1) {
399
- return function (token, data) {
400
- const field = fields[0].field;
401
- return scoreValue(getAttrFn(data, field), token, weights[field]);
402
- };
403
- }
404
-
405
- return function (token, data) {
406
- var sum = 0; // is the token specific to a field?
407
-
408
- if (token.field) {
409
- const value = getAttrFn(data, token.field);
410
-
411
- if (!token.regex && value) {
412
- sum += 1 / field_count;
413
- } else {
414
- sum += scoreValue(value, token, 1);
415
- }
416
- } else {
417
- iterate(weights, (weight, field) => {
418
- sum += scoreValue(getAttrFn(data, field), token, weight);
419
- });
420
- }
421
-
422
- return sum / field_count;
423
- };
424
- }();
425
-
426
- if (token_count === 1) {
427
- return function (data) {
428
- return scoreObject(tokens[0], data);
429
- };
430
- }
431
-
432
- if (search.options.conjunction === 'and') {
433
- return function (data) {
434
- var i = 0,
435
- score,
436
- sum = 0;
437
-
438
- for (; i < token_count; i++) {
439
- score = scoreObject(tokens[i], data);
440
- if (score <= 0) return 0;
441
- sum += score;
442
- }
443
-
444
- return sum / token_count;
445
- };
446
- } else {
447
- return function (data) {
448
- var sum = 0;
449
- iterate(tokens, token => {
450
- sum += scoreObject(token, data);
451
- });
452
- return sum / token_count;
453
- };
454
- }
455
- }
456
-
457
- /**
458
- * Returns a function that can be used to compare two
459
- * results, for sorting purposes. If no sorting should
460
- * be performed, `null` will be returned.
461
- *
462
- * @return function(a,b)
463
- */
464
- getSortFunction(query, options) {
465
- var search = this.prepareSearch(query, options);
466
- return this._getSortFunction(search);
467
- }
468
-
469
- _getSortFunction(search) {
470
- var i, n, implicit_score;
471
- const self = this,
472
- options = search.options,
473
- sort = !search.query && options.sort_empty ? options.sort_empty : options.sort,
474
- sort_flds = [],
475
- multipliers = [];
476
-
477
- if (typeof sort == 'function') {
478
- return sort.bind(this);
479
- }
480
- /**
481
- * Fetches the specified sort field value
482
- * from a search result item.
483
- *
484
- */
485
-
486
-
487
- const get_field = function get_field(name, result) {
488
- if (name === '$score') return result.score;
489
- return search.getAttrFn(self.items[result.id], name);
490
- }; // parse options
491
-
492
-
493
- if (sort) {
494
- for (i = 0, n = sort.length; i < n; i++) {
495
- if (search.query || sort[i].field !== '$score') {
496
- sort_flds.push(sort[i]);
497
- }
498
- }
499
- } // the "$score" field is implied to be the primary
500
- // sort field, unless it's manually specified
501
-
502
-
503
- if (search.query) {
504
- implicit_score = true;
505
-
506
- for (i = 0, n = sort_flds.length; i < n; i++) {
507
- if (sort_flds[i].field === '$score') {
508
- implicit_score = false;
509
- break;
510
- }
511
- }
512
-
513
- if (implicit_score) {
514
- sort_flds.unshift({
515
- field: '$score',
516
- direction: 'desc'
517
- });
518
- }
519
- } else {
520
- for (i = 0, n = sort_flds.length; i < n; i++) {
521
- if (sort_flds[i].field === '$score') {
522
- sort_flds.splice(i, 1);
523
- break;
524
- }
525
- }
526
- }
527
-
528
- for (i = 0, n = sort_flds.length; i < n; i++) {
529
- multipliers.push(sort_flds[i].direction === 'desc' ? -1 : 1);
530
- } // build function
531
-
532
-
533
- const sort_flds_count = sort_flds.length;
534
-
535
- if (!sort_flds_count) {
536
- return null;
537
- } else if (sort_flds_count === 1) {
538
- const sort_fld = sort_flds[0].field;
539
- const multiplier = multipliers[0];
540
- return function (a, b) {
541
- return multiplier * cmp(get_field(sort_fld, a), get_field(sort_fld, b));
542
- };
543
- } else {
544
- return function (a, b) {
545
- var i, result, field;
546
-
547
- for (i = 0; i < sort_flds_count; i++) {
548
- field = sort_flds[i].field;
549
- result = multipliers[i] * cmp(get_field(field, a), get_field(field, b));
550
- if (result) return result;
551
- }
552
-
553
- return 0;
554
- };
555
- }
556
- }
557
-
558
- /**
559
- * Parses a search query and returns an object
560
- * with tokens and fields ready to be populated
561
- * with results.
562
- *
563
- */
564
- prepareSearch(query, optsUser) {
565
- const weights = {};
566
- var options = Object.assign({}, optsUser);
567
- propToArray(options, 'sort');
568
- propToArray(options, 'sort_empty'); // convert fields to new format
569
-
570
- if (options.fields) {
571
- propToArray(options, 'fields');
572
- const fields = [];
573
- options.fields.forEach(field => {
574
- if (typeof field == 'string') {
575
- field = {
576
- field: field,
577
- weight: 1
578
- };
579
- }
580
-
581
- fields.push(field);
582
- weights[field.field] = 'weight' in field ? field.weight : 1;
583
- });
584
- options.fields = fields;
585
- }
586
-
587
- return {
588
- options: options,
589
- query: query.toLowerCase().trim(),
590
- tokens: this.tokenize(query, options.respect_word_boundaries, weights),
591
- total: 0,
592
- items: [],
593
- weights: weights,
594
- getAttrFn: options.nesting ? getAttrNesting : getAttr
595
- };
596
- }
597
-
598
- /**
599
- * Searches through all items and returns a sorted array of matches.
600
- *
601
- */
602
- search(query, options) {
603
- var self = this,
604
- score,
605
- search;
606
- search = this.prepareSearch(query, options);
607
- options = search.options;
608
- query = search.query; // generate result scoring function
609
-
610
- const fn_score = options.score || self._getScoreFunction(search); // perform search and sort
611
-
612
-
613
- if (query.length) {
614
- iterate(self.items, (item, id) => {
615
- score = fn_score(item);
616
-
617
- if (options.filter === false || score > 0) {
618
- search.items.push({
619
- 'score': score,
620
- 'id': id
621
- });
622
- }
623
- });
624
- } else {
625
- iterate(self.items, (_, id) => {
626
- search.items.push({
627
- 'score': 1,
628
- 'id': id
629
- });
630
- });
631
- }
632
-
633
- const fn_sort = self._getSortFunction(search);
634
-
635
- if (fn_sort) search.items.sort(fn_sort); // apply limits
636
-
637
- search.total = search.items.length;
638
-
639
- if (typeof options.limit === 'number') {
640
- search.items = search.items.slice(0, options.limit);
641
- }
642
-
643
- return search;
644
- }
645
-
646
- }
647
-
648
- return Sifter;
3
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
4
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
5
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.sifter = {}));
6
+ }(this, (function (exports) { 'use strict';
7
+
8
+ /*! @orchidjs/unicode-variants | https://github.com/orchidjs/unicode-variants | Apache License (v2) */
9
+
10
+ /**
11
+ * Convert array of strings to a regular expression
12
+ * ex ['ab','a'] => (?:ab|a)
13
+ * ex ['a','b'] => [ab]
14
+ * @param {string[]} chars
15
+ * @return {string}
16
+ */
17
+ const arrayToPattern = chars => {
18
+ chars = chars.filter(Boolean);
19
+
20
+ if (chars.length < 2) {
21
+ return chars[0] || '';
22
+ }
23
+
24
+ return maxValueLength(chars) == 1 ? '[' + chars.join('') + ']' : '(?:' + chars.join('|') + ')';
25
+ };
26
+ /**
27
+ * @param {string[]} array
28
+ * @return {string}
29
+ */
30
+
31
+
32
+ const sequencePattern = array => {
33
+ if (!hasDuplicates(array)) {
34
+ return array.join('');
35
+ }
36
+
37
+ let pattern = '';
38
+ let prev_char_count = 0;
39
+
40
+ const prev_pattern = () => {
41
+ if (prev_char_count > 1) {
42
+ pattern += '{' + prev_char_count + '}';
43
+ }
44
+ };
45
+
46
+ array.forEach((char, i) => {
47
+ if (char === array[i - 1]) {
48
+ prev_char_count++;
49
+ return;
50
+ }
51
+
52
+ prev_pattern();
53
+ pattern += char;
54
+ prev_char_count = 1;
55
+ });
56
+ prev_pattern();
57
+ return pattern;
58
+ };
59
+ /**
60
+ * Convert array of strings to a regular expression
61
+ * ex ['ab','a'] => (?:ab|a)
62
+ * ex ['a','b'] => [ab]
63
+ * @param {Set<string>} chars
64
+ * @return {string}
65
+ */
66
+
67
+
68
+ const setToPattern = chars => {
69
+ let array = toArray(chars);
70
+ return arrayToPattern(array);
71
+ };
72
+ /**
73
+ *
74
+ * https://stackoverflow.com/questions/7376598/in-javascript-how-do-i-check-if-an-array-has-duplicate-values
75
+ * @param {any[]} array
76
+ */
77
+
78
+
79
+ const hasDuplicates = array => {
80
+ return new Set(array).size !== array.length;
81
+ };
82
+ /**
83
+ * https://stackoverflow.com/questions/63006601/why-does-u-throw-an-invalid-escape-error
84
+ * @param {string} str
85
+ * @return {string}
86
+ */
87
+
88
+
89
+ const escape_regex = str => {
90
+ return (str + '').replace(/([\$\(-\+\.\?\[-\^\{-\}])/g, '\\$1');
91
+ };
92
+ /**
93
+ * Return the max length of array values
94
+ * @param {string[]} array
95
+ *
96
+ */
97
+
98
+
99
+ const maxValueLength = array => {
100
+ return array.reduce((longest, value) => Math.max(longest, unicodeLength(value)), 0);
101
+ };
102
+ /**
103
+ * @param {string} str
104
+ */
105
+
106
+
107
+ const unicodeLength = str => {
108
+ return toArray(str).length;
109
+ };
110
+ /**
111
+ * @param {any} p
112
+ * @return {any[]}
113
+ */
114
+
115
+
116
+ const toArray = p => Array.from(p);
117
+
118
+ /*! @orchidjs/unicode-variants | https://github.com/orchidjs/unicode-variants | Apache License (v2) */
119
+
120
+ /**
121
+ * Get all possible combinations of substrings that add up to the given string
122
+ * https://stackoverflow.com/questions/30169587/find-all-the-combination-of-substrings-that-add-up-to-the-given-string
123
+ * @param {string} input
124
+ * @return {string[][]}
125
+ */
126
+ const allSubstrings = input => {
127
+ if (input.length === 1) return [[input]];
128
+ /** @type {string[][]} */
129
+
130
+ let result = [];
131
+ const start = input.substring(1);
132
+ const suba = allSubstrings(start);
133
+ suba.forEach(function (subresult) {
134
+ let tmp = subresult.slice(0);
135
+ tmp[0] = input.charAt(0) + tmp[0];
136
+ result.push(tmp);
137
+ tmp = subresult.slice(0);
138
+ tmp.unshift(input.charAt(0));
139
+ result.push(tmp);
140
+ });
141
+ return result;
142
+ };
143
+
144
+ /*! @orchidjs/unicode-variants | https://github.com/orchidjs/unicode-variants | Apache License (v2) */
145
+ /**
146
+ * @typedef {{[key:string]:string}} TUnicodeMap
147
+ * @typedef {{[key:string]:Set<string>}} TUnicodeSets
148
+ * @typedef {[[number,number]]} TCodePoints
149
+ * @typedef {{folded:string,composed:string,code_point:number}} TCodePointObj
150
+ * @typedef {{start:number,end:number,length:number,substr:string}} TSequencePart
151
+ */
152
+
153
+ /** @type {TCodePoints} */
154
+
155
+ const code_points = [[0, 65535]];
156
+ const accent_pat = '[\u0300-\u036F\u{b7}\u{2be}]'; // \u{2bc}
157
+
158
+ /** @type {TUnicodeMap} */
159
+
160
+ let unicode_map;
161
+ /** @type {RegExp} */
162
+
163
+ let multi_char_reg;
164
+ const max_char_length = 3;
165
+ /** @type {TUnicodeMap} */
166
+
167
+ const latin_convert = {
168
+ 'æ': 'ae',
169
+ 'ⱥ': 'a',
170
+ 'ø': 'o',
171
+ '⁄': '/',
172
+ '∕': '/'
173
+ };
174
+ const convert_pat = new RegExp(Object.keys(latin_convert).join('|') + '|' + accent_pat, 'gu');
175
+ /**
176
+ * Initialize the unicode_map from the give code point ranges
177
+ *
178
+ * @param {TCodePoints=} _code_points
179
+ */
180
+
181
+ const initialize = _code_points => {
182
+ if (unicode_map !== undefined) return;
183
+ unicode_map = generateMap(_code_points || code_points);
184
+ };
185
+ /**
186
+ * Helper method for normalize a string
187
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize
188
+ * @param {string} str
189
+ * @param {string} form
190
+ */
191
+
192
+
193
+ const normalize = (str, form = 'NFKD') => str.normalize(form);
194
+ /**
195
+ * Compatibility Decomposition without reordering string
196
+ * calling str.normalize('NFKD') on \u{594}\u{595}\u{596} becomes \u{596}\u{594}\u{595}
197
+ * @param {string} str
198
+ */
199
+
200
+
201
+ const decompose = str => {
202
+ if (str.match(/[\u0f71-\u0f81]/)) {
203
+ return toArray(str).reduce(
204
+ /**
205
+ * @param {string} result
206
+ * @param {string} char
207
+ */
208
+ (result, char) => {
209
+ return result + normalize(char);
210
+ }, '');
211
+ }
212
+
213
+ return normalize(str);
214
+ };
215
+ /**
216
+ * Remove accents
217
+ * via https://github.com/krisk/Fuse/issues/133#issuecomment-318692703
218
+ * @param {string} str
219
+ * @return {string}
220
+ */
221
+
222
+
223
+ const asciifold = str => {
224
+ return decompose(str).toLowerCase().replace(convert_pat,
225
+ /** @type {string} */
226
+ char => {
227
+ return latin_convert[char] || '';
228
+ });
229
+ };
230
+ /**
231
+ * Generate a list of unicode variants from the list of code points
232
+ * @param {TCodePoints} code_points
233
+ * @yield {TCodePointObj}
234
+ */
235
+
236
+
237
+ function* generator(code_points) {
238
+ for (const [code_point_min, code_point_max] of code_points) {
239
+ for (let i = code_point_min; i <= code_point_max; i++) {
240
+ let composed = String.fromCharCode(i);
241
+ let folded = asciifold(composed);
242
+
243
+ if (folded == composed.toLowerCase()) {
244
+ continue;
245
+ } // skip when folded is a string longer than 3 characters long
246
+ // bc the resulting regex patterns will be long
247
+ // eg:
248
+ // folded صلى الله عليه وسلم length 18 code point 65018
249
+ // folded جل جلاله length 8 code point 65019
250
+
251
+
252
+ if (folded.length > max_char_length) {
253
+ continue;
254
+ }
255
+
256
+ if (folded.length == 0) {
257
+ continue;
258
+ }
259
+
260
+ let decomposed = normalize(composed);
261
+ let recomposed = normalize(decomposed, 'NFC');
262
+
263
+ if (recomposed === composed && folded === decomposed) {
264
+ continue;
265
+ }
266
+
267
+ yield {
268
+ folded: folded,
269
+ composed: composed,
270
+ code_point: i
271
+ };
272
+ }
273
+ }
274
+ }
275
+ /**
276
+ * Generate a unicode map from the list of code points
277
+ * @param {TCodePoints} code_points
278
+ * @return {TUnicodeSets}
279
+ */
280
+
281
+
282
+ const generateSets = code_points => {
283
+ /** @type {{[key:string]:Set<string>}} */
284
+ const unicode_sets = {};
285
+ /**
286
+ * @param {string} folded
287
+ * @param {string} to_add
288
+ */
289
+
290
+ const addMatching = (folded, to_add) => {
291
+ /** @type {Set<string>} */
292
+ const folded_set = unicode_sets[folded] || new Set();
293
+ const patt = new RegExp('^' + setToPattern(folded_set) + '$', 'iu');
294
+
295
+ if (to_add.match(patt)) {
296
+ return;
297
+ }
298
+
299
+ folded_set.add(escape_regex(to_add));
300
+ unicode_sets[folded] = folded_set;
301
+ };
302
+
303
+ for (let value of generator(code_points)) {
304
+ addMatching(value.folded, value.folded);
305
+ addMatching(value.folded, value.composed);
306
+ }
307
+
308
+ return unicode_sets;
309
+ };
310
+ /**
311
+ * Generate a unicode map from the list of code points
312
+ * ae => (?:(?:ae|Æ|Ǽ|Ǣ)|(?:A|Ⓐ|A...)(?:E|ɛ|Ⓔ...))
313
+ *
314
+ * @param {TCodePoints} code_points
315
+ * @return {TUnicodeMap}
316
+ */
317
+
318
+
319
+ const generateMap = code_points => {
320
+ /** @type {TUnicodeSets} */
321
+ const unicode_sets = generateSets(code_points);
322
+ /** @type {TUnicodeMap} */
323
+
324
+ const unicode_map = {};
325
+ /** @type {string[]} */
326
+
327
+ let multi_char = [];
328
+
329
+ for (let folded in unicode_sets) {
330
+ let set = unicode_sets[folded];
331
+
332
+ if (set) {
333
+ unicode_map[folded] = setToPattern(set);
334
+ }
335
+
336
+ if (folded.length > 1) {
337
+ multi_char.push(escape_regex(folded));
338
+ }
339
+ }
340
+
341
+ multi_char.sort((a, b) => b.length - a.length);
342
+ const multi_char_patt = arrayToPattern(multi_char);
343
+ multi_char_reg = new RegExp('^' + multi_char_patt, 'u');
344
+ return unicode_map;
345
+ };
346
+ /**
347
+ * Map each element of an array from it's folded value to all possible unicode matches
348
+ * @param {string[]} strings
349
+ * @param {number} min_replacement
350
+ * @return {string}
351
+ */
352
+
353
+
354
+ const mapSequence = (strings, min_replacement = 1) => {
355
+ let chars_replaced = 0;
356
+ strings = strings.map(str => {
357
+ if (unicode_map[str]) {
358
+ chars_replaced += str.length;
359
+ }
360
+
361
+ return unicode_map[str] || str;
362
+ });
363
+
364
+ if (chars_replaced >= min_replacement) {
365
+ return sequencePattern(strings);
366
+ }
367
+
368
+ return '';
369
+ };
370
+ /**
371
+ * Convert a short string and split it into all possible patterns
372
+ * Keep a pattern only if min_replacement is met
373
+ *
374
+ * 'abc'
375
+ * => [['abc'],['ab','c'],['a','bc'],['a','b','c']]
376
+ * => ['abc-pattern','ab-c-pattern'...]
377
+ *
378
+ *
379
+ * @param {string} str
380
+ * @param {number} min_replacement
381
+ * @return {string}
382
+ */
383
+
384
+
385
+ const substringsToPattern = (str, min_replacement = 1) => {
386
+ min_replacement = Math.max(min_replacement, str.length - 1);
387
+ return arrayToPattern(allSubstrings(str).map(sub_pat => {
388
+ return mapSequence(sub_pat, min_replacement);
389
+ }));
390
+ };
391
+ /**
392
+ * Convert an array of sequences into a pattern
393
+ * [{start:0,end:3,length:3,substr:'iii'}...] => (?:iii...)
394
+ *
395
+ * @param {Sequence[]} sequences
396
+ * @param {boolean} all
397
+ */
398
+
399
+
400
+ const sequencesToPattern = (sequences, all = true) => {
401
+ let min_replacement = sequences.length > 1 ? 1 : 0;
402
+ return arrayToPattern(sequences.map(sequence => {
403
+ let seq = [];
404
+ const len = all ? sequence.length() : sequence.length() - 1;
405
+
406
+ for (let j = 0; j < len; j++) {
407
+ seq.push(substringsToPattern(sequence.substrs[j] || '', min_replacement));
408
+ }
409
+
410
+ return sequencePattern(seq);
411
+ }));
412
+ };
413
+ /**
414
+ * Return true if the sequence is already in the sequences
415
+ * @param {Sequence} needle_seq
416
+ * @param {Sequence[]} sequences
417
+ */
418
+
419
+
420
+ const inSequences = (needle_seq, sequences) => {
421
+ for (const seq of sequences) {
422
+ if (seq.start != needle_seq.start || seq.end != needle_seq.end) {
423
+ continue;
424
+ }
425
+
426
+ if (seq.substrs.join('') !== needle_seq.substrs.join('')) {
427
+ continue;
428
+ }
429
+
430
+ let needle_parts = needle_seq.parts;
431
+ /**
432
+ * @param {TSequencePart} part
433
+ */
434
+
435
+ const filter = part => {
436
+ for (const needle_part of needle_parts) {
437
+ if (needle_part.start === part.start && needle_part.substr === part.substr) {
438
+ return false;
439
+ }
440
+
441
+ if (part.length == 1 || needle_part.length == 1) {
442
+ continue;
443
+ } // check for overlapping parts
444
+ // a = ['::=','==']
445
+ // b = ['::','===']
446
+ // a = ['r','sm']
447
+ // b = ['rs','m']
448
+
449
+
450
+ if (part.start < needle_part.start && part.end > needle_part.start) {
451
+ return true;
452
+ }
453
+
454
+ if (needle_part.start < part.start && needle_part.end > part.start) {
455
+ return true;
456
+ }
457
+ }
458
+
459
+ return false;
460
+ };
461
+
462
+ let filtered = seq.parts.filter(filter);
463
+
464
+ if (filtered.length > 0) {
465
+ continue;
466
+ }
467
+
468
+ return true;
469
+ }
470
+
471
+ return false;
472
+ };
473
+
474
+ class Sequence {
475
+ constructor() {
476
+ /** @type {TSequencePart[]} */
477
+ this.parts = [];
478
+ /** @type {string[]} */
479
+
480
+ this.substrs = [];
481
+ this.start = 0;
482
+ this.end = 0;
483
+ }
484
+ /**
485
+ * @param {TSequencePart|undefined} part
486
+ */
487
+
488
+
489
+ add(part) {
490
+ if (part) {
491
+ this.parts.push(part);
492
+ this.substrs.push(part.substr);
493
+ this.start = Math.min(part.start, this.start);
494
+ this.end = Math.max(part.end, this.end);
495
+ }
496
+ }
497
+
498
+ last() {
499
+ return this.parts[this.parts.length - 1];
500
+ }
501
+
502
+ length() {
503
+ return this.parts.length;
504
+ }
505
+ /**
506
+ * @param {number} position
507
+ * @param {TSequencePart} last_piece
508
+ */
509
+
510
+
511
+ clone(position, last_piece) {
512
+ let clone = new Sequence();
513
+ let parts = JSON.parse(JSON.stringify(this.parts));
514
+ let last_part = parts.pop();
515
+
516
+ for (const part of parts) {
517
+ clone.add(part);
518
+ }
519
+
520
+ let last_substr = last_piece.substr.substring(0, position - last_part.start);
521
+ let clone_last_len = last_substr.length;
522
+ clone.add({
523
+ start: last_part.start,
524
+ end: last_part.start + clone_last_len,
525
+ length: clone_last_len,
526
+ substr: last_substr
527
+ });
528
+ return clone;
529
+ }
530
+
531
+ }
532
+ /**
533
+ * Expand a regular expression pattern to include unicode variants
534
+ * eg /a/ becomes /aⓐaẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐɑAⒶAÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄȺⱯ/
535
+ *
536
+ * Issue:
537
+ * ﺊﺋ [ 'ﺊ = \\u{fe8a}', 'ﺋ = \\u{fe8b}' ]
538
+ * becomes: ئئ [ 'ي = \\u{64a}', 'ٔ = \\u{654}', 'ي = \\u{64a}', 'ٔ = \\u{654}' ]
539
+ *
540
+ * İIJ = IIJ = ⅡJ
541
+ *
542
+ * 1/2/4
543
+ *
544
+ * @param {string} str
545
+ * @return {string|undefined}
546
+ */
547
+
548
+
549
+ const getPattern = str => {
550
+ initialize();
551
+ str = asciifold(str);
552
+ let pattern = '';
553
+ let sequences = [new Sequence()];
554
+
555
+ for (let i = 0; i < str.length; i++) {
556
+ let substr = str.substring(i);
557
+ let match = substr.match(multi_char_reg);
558
+ const char = str.substring(i, i + 1);
559
+ const match_str = match ? match[0] : null; // loop through sequences
560
+ // add either the char or multi_match
561
+
562
+ let overlapping = [];
563
+ let added_types = new Set();
564
+
565
+ for (const sequence of sequences) {
566
+ const last_piece = sequence.last();
567
+
568
+ if (!last_piece || last_piece.length == 1 || last_piece.end <= i) {
569
+ // if we have a multi match
570
+ if (match_str) {
571
+ const len = match_str.length;
572
+ sequence.add({
573
+ start: i,
574
+ end: i + len,
575
+ length: len,
576
+ substr: match_str
577
+ });
578
+ added_types.add('1');
579
+ } else {
580
+ sequence.add({
581
+ start: i,
582
+ end: i + 1,
583
+ length: 1,
584
+ substr: char
585
+ });
586
+ added_types.add('2');
587
+ }
588
+ } else if (match_str) {
589
+ let clone = sequence.clone(i, last_piece);
590
+ const len = match_str.length;
591
+ clone.add({
592
+ start: i,
593
+ end: i + len,
594
+ length: len,
595
+ substr: match_str
596
+ });
597
+ overlapping.push(clone);
598
+ } else {
599
+ // don't add char
600
+ // adding would create invalid patterns: 234 => [2,34,4]
601
+ added_types.add('3');
602
+ }
603
+ } // if we have overlapping
604
+
605
+
606
+ if (overlapping.length > 0) {
607
+ // ['ii','iii'] before ['i','i','iii']
608
+ overlapping = overlapping.sort((a, b) => {
609
+ return a.length() - b.length();
610
+ });
611
+
612
+ for (let clone of overlapping) {
613
+ // don't add if we already have an equivalent sequence
614
+ if (inSequences(clone, sequences)) {
615
+ continue;
616
+ }
617
+
618
+ sequences.push(clone);
619
+ }
620
+
621
+ continue;
622
+ } // if we haven't done anything unique
623
+ // clean up the patterns
624
+ // helps keep patterns smaller
625
+ // if str = 'r₨㎧aarss', pattern will be 446 instead of 655
626
+
627
+
628
+ if (i > 0 && added_types.size == 1 && !added_types.has('3')) {
629
+ pattern += sequencesToPattern(sequences, false);
630
+ let new_seq = new Sequence();
631
+ const old_seq = sequences[0];
632
+
633
+ if (old_seq) {
634
+ new_seq.add(old_seq.last());
635
+ }
636
+
637
+ sequences = [new_seq];
638
+ }
639
+ }
640
+
641
+ pattern += sequencesToPattern(sequences, true);
642
+ return pattern;
643
+ };
644
+
645
+ /**
646
+ * A property getter resolving dot-notation
647
+ * @param {Object} obj The root object to fetch property on
648
+ * @param {String} name The optionally dotted property name to fetch
649
+ * @return {Object} The resolved property value
650
+ */
651
+ const getAttr = (obj, name) => {
652
+ if (!obj) return;
653
+ return obj[name];
654
+ };
655
+ /**
656
+ * A property getter resolving dot-notation
657
+ * @param {Object} obj The root object to fetch property on
658
+ * @param {String} name The optionally dotted property name to fetch
659
+ * @return {Object} The resolved property value
660
+ */
661
+
662
+ const getAttrNesting = (obj, name) => {
663
+ if (!obj) return;
664
+ var part,
665
+ names = name.split(".");
666
+
667
+ while ((part = names.shift()) && (obj = obj[part]));
668
+
669
+ return obj;
670
+ };
671
+ /**
672
+ * Calculates how close of a match the
673
+ * given value is against a search token.
674
+ *
675
+ */
676
+
677
+ const scoreValue = (value, token, weight) => {
678
+ var score, pos;
679
+ if (!value) return 0;
680
+ value = value + '';
681
+ if (token.regex == null) return 0;
682
+ pos = value.search(token.regex);
683
+ if (pos === -1) return 0;
684
+ score = token.string.length / value.length;
685
+ if (pos === 0) score += 0.5;
686
+ return score * weight;
687
+ };
688
+ /**
689
+ * Cast object property to an array if it exists and has a value
690
+ *
691
+ */
692
+
693
+ const propToArray = (obj, key) => {
694
+ var value = obj[key];
695
+ if (typeof value == 'function') return value;
696
+
697
+ if (value && !Array.isArray(value)) {
698
+ obj[key] = [value];
699
+ }
700
+ };
701
+ /**
702
+ * Iterates over arrays and hashes.
703
+ *
704
+ * ```
705
+ * iterate(this.items, function(item, id) {
706
+ * // invoked for each item
707
+ * });
708
+ * ```
709
+ *
710
+ */
711
+
712
+ const iterate = (object, callback) => {
713
+ if (Array.isArray(object)) {
714
+ object.forEach(callback);
715
+ } else {
716
+ for (var key in object) {
717
+ if (object.hasOwnProperty(key)) {
718
+ callback(object[key], key);
719
+ }
720
+ }
721
+ }
722
+ };
723
+ const cmp = (a, b) => {
724
+ if (typeof a === 'number' && typeof b === 'number') {
725
+ return a > b ? 1 : a < b ? -1 : 0;
726
+ }
727
+
728
+ a = asciifold(a + '').toLowerCase();
729
+ b = asciifold(b + '').toLowerCase();
730
+ if (a > b) return 1;
731
+ if (b > a) return -1;
732
+ return 0;
733
+ };
734
+
735
+ /**
736
+ * sifter.js
737
+ * Copyright (c) 2013–2020 Brian Reavis & contributors
738
+ *
739
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
740
+ * file except in compliance with the License. You may obtain a copy of the License at:
741
+ * http://www.apache.org/licenses/LICENSE-2.0
742
+ *
743
+ * Unless required by applicable law or agreed to in writing, software distributed under
744
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
745
+ * ANY KIND, either express or implied. See the License for the specific language
746
+ * governing permissions and limitations under the License.
747
+ *
748
+ * @author Brian Reavis <brian@thirdroute.com>
749
+ */
750
+
751
+ class Sifter {
752
+ // []|{};
753
+
754
+ /**
755
+ * Textually searches arrays and hashes of objects
756
+ * by property (or multiple properties). Designed
757
+ * specifically for autocomplete.
758
+ *
759
+ */
760
+ constructor(items, settings) {
761
+ this.items = void 0;
762
+ this.settings = void 0;
763
+ this.items = items;
764
+ this.settings = settings || {
765
+ diacritics: true
766
+ };
767
+ }
768
+
769
+ /**
770
+ * Splits a search string into an array of individual
771
+ * regexps to be used to match results.
772
+ *
773
+ */
774
+ tokenize(query, respect_word_boundaries, weights) {
775
+ if (!query || !query.length) return [];
776
+ const tokens = [];
777
+ const words = query.split(/\s+/);
778
+ var field_regex;
779
+
780
+ if (weights) {
781
+ field_regex = new RegExp('^(' + Object.keys(weights).map(escape_regex).join('|') + ')\:(.*)$');
782
+ }
783
+
784
+ words.forEach(word => {
785
+ let field_match;
786
+ let field = null;
787
+ let regex = null; // look for "field:query" tokens
788
+
789
+ if (field_regex && (field_match = word.match(field_regex))) {
790
+ field = field_match[1];
791
+ word = field_match[2];
792
+ }
793
+
794
+ if (word.length > 0) {
795
+ if (this.settings.diacritics) {
796
+ regex = getPattern(word) || null;
797
+ } else {
798
+ regex = escape_regex(word);
799
+ }
800
+
801
+ if (regex && respect_word_boundaries) regex = "\\b" + regex;
802
+ }
803
+
804
+ tokens.push({
805
+ string: word,
806
+ regex: regex ? new RegExp(regex, 'iu') : null,
807
+ field: field
808
+ });
809
+ });
810
+ return tokens;
811
+ }
812
+
813
+ /**
814
+ * Returns a function to be used to score individual results.
815
+ *
816
+ * Good matches will have a higher score than poor matches.
817
+ * If an item is not a match, 0 will be returned by the function.
818
+ *
819
+ * @returns {T.ScoreFn}
820
+ */
821
+ getScoreFunction(query, options) {
822
+ var search = this.prepareSearch(query, options);
823
+ return this._getScoreFunction(search);
824
+ }
825
+ /**
826
+ * @returns {T.ScoreFn}
827
+ *
828
+ */
829
+
830
+
831
+ _getScoreFunction(search) {
832
+ const tokens = search.tokens,
833
+ token_count = tokens.length;
834
+
835
+ if (!token_count) {
836
+ return function () {
837
+ return 0;
838
+ };
839
+ }
840
+
841
+ const fields = search.options.fields,
842
+ weights = search.weights,
843
+ field_count = fields.length,
844
+ getAttrFn = search.getAttrFn;
845
+
846
+ if (!field_count) {
847
+ return function () {
848
+ return 1;
849
+ };
850
+ }
851
+ /**
852
+ * Calculates the score of an object
853
+ * against the search query.
854
+ *
855
+ */
856
+
857
+
858
+ const scoreObject = function () {
859
+ if (field_count === 1) {
860
+ return function (token, data) {
861
+ const field = fields[0].field;
862
+ return scoreValue(getAttrFn(data, field), token, weights[field] || 1);
863
+ };
864
+ }
865
+
866
+ return function (token, data) {
867
+ var sum = 0; // is the token specific to a field?
868
+
869
+ if (token.field) {
870
+ const value = getAttrFn(data, token.field);
871
+
872
+ if (!token.regex && value) {
873
+ sum += 1 / field_count;
874
+ } else {
875
+ sum += scoreValue(value, token, 1);
876
+ }
877
+ } else {
878
+ iterate(weights, (weight, field) => {
879
+ sum += scoreValue(getAttrFn(data, field), token, weight);
880
+ });
881
+ }
882
+
883
+ return sum / field_count;
884
+ };
885
+ }();
886
+
887
+ if (token_count === 1) {
888
+ return function (data) {
889
+ return scoreObject(tokens[0], data);
890
+ };
891
+ }
892
+
893
+ if (search.options.conjunction === 'and') {
894
+ return function (data) {
895
+ var score,
896
+ sum = 0;
897
+
898
+ for (let token of tokens) {
899
+ score = scoreObject(token, data);
900
+ if (score <= 0) return 0;
901
+ sum += score;
902
+ }
903
+
904
+ return sum / token_count;
905
+ };
906
+ } else {
907
+ return function (data) {
908
+ var sum = 0;
909
+ iterate(tokens, token => {
910
+ sum += scoreObject(token, data);
911
+ });
912
+ return sum / token_count;
913
+ };
914
+ }
915
+ }
916
+
917
+ /**
918
+ * Returns a function that can be used to compare two
919
+ * results, for sorting purposes. If no sorting should
920
+ * be performed, `null` will be returned.
921
+ *
922
+ * @return function(a,b)
923
+ */
924
+ getSortFunction(query, options) {
925
+ var search = this.prepareSearch(query, options);
926
+ return this._getSortFunction(search);
927
+ }
928
+
929
+ _getSortFunction(search) {
930
+ var implicit_score,
931
+ sort_flds = [];
932
+ const self = this,
933
+ options = search.options,
934
+ sort = !search.query && options.sort_empty ? options.sort_empty : options.sort;
935
+
936
+ if (typeof sort == 'function') {
937
+ return sort.bind(this);
938
+ }
939
+ /**
940
+ * Fetches the specified sort field value
941
+ * from a search result item.
942
+ *
943
+ */
944
+
945
+
946
+ const get_field = function get_field(name, result) {
947
+ if (name === '$score') return result.score;
948
+ return search.getAttrFn(self.items[result.id], name);
949
+ }; // parse options
950
+
951
+
952
+ if (sort) {
953
+ for (let s of sort) {
954
+ if (search.query || s.field !== '$score') {
955
+ sort_flds.push(s);
956
+ }
957
+ }
958
+ } // the "$score" field is implied to be the primary
959
+ // sort field, unless it's manually specified
960
+
961
+
962
+ if (search.query) {
963
+ implicit_score = true;
964
+
965
+ for (let fld of sort_flds) {
966
+ if (fld.field === '$score') {
967
+ implicit_score = false;
968
+ break;
969
+ }
970
+ }
971
+
972
+ if (implicit_score) {
973
+ sort_flds.unshift({
974
+ field: '$score',
975
+ direction: 'desc'
976
+ });
977
+ } // without a search.query, all items will have the same score
978
+
979
+ } else {
980
+ sort_flds = sort_flds.filter(fld => fld.field !== '$score');
981
+ } // build function
982
+
983
+
984
+ const sort_flds_count = sort_flds.length;
985
+
986
+ if (!sort_flds_count) {
987
+ return null;
988
+ }
989
+
990
+ return function (a, b) {
991
+ var result, field;
992
+
993
+ for (let sort_fld of sort_flds) {
994
+ field = sort_fld.field;
995
+ let multiplier = sort_fld.direction === 'desc' ? -1 : 1;
996
+ result = multiplier * cmp(get_field(field, a), get_field(field, b));
997
+ if (result) return result;
998
+ }
999
+
1000
+ return 0;
1001
+ };
1002
+ }
1003
+
1004
+ /**
1005
+ * Parses a search query and returns an object
1006
+ * with tokens and fields ready to be populated
1007
+ * with results.
1008
+ *
1009
+ */
1010
+ prepareSearch(query, optsUser) {
1011
+ const weights = {};
1012
+ var options = Object.assign({}, optsUser);
1013
+ propToArray(options, 'sort');
1014
+ propToArray(options, 'sort_empty'); // convert fields to new format
1015
+
1016
+ if (options.fields) {
1017
+ propToArray(options, 'fields');
1018
+ const fields = [];
1019
+ options.fields.forEach(field => {
1020
+ if (typeof field == 'string') {
1021
+ field = {
1022
+ field: field,
1023
+ weight: 1
1024
+ };
1025
+ }
1026
+
1027
+ fields.push(field);
1028
+ weights[field.field] = 'weight' in field ? field.weight : 1;
1029
+ });
1030
+ options.fields = fields;
1031
+ }
1032
+
1033
+ return {
1034
+ options: options,
1035
+ query: query.toLowerCase().trim(),
1036
+ tokens: this.tokenize(query, options.respect_word_boundaries, weights),
1037
+ total: 0,
1038
+ items: [],
1039
+ weights: weights,
1040
+ getAttrFn: options.nesting ? getAttrNesting : getAttr
1041
+ };
1042
+ }
1043
+
1044
+ /**
1045
+ * Searches through all items and returns a sorted array of matches.
1046
+ *
1047
+ */
1048
+ search(query, options) {
1049
+ var self = this,
1050
+ score,
1051
+ search;
1052
+ search = this.prepareSearch(query, options);
1053
+ options = search.options;
1054
+ query = search.query; // generate result scoring function
1055
+
1056
+ const fn_score = options.score || self._getScoreFunction(search); // perform search and sort
1057
+
1058
+
1059
+ if (query.length) {
1060
+ iterate(self.items, (item, id) => {
1061
+ score = fn_score(item);
1062
+
1063
+ if (options.filter === false || score > 0) {
1064
+ search.items.push({
1065
+ 'score': score,
1066
+ 'id': id
1067
+ });
1068
+ }
1069
+ });
1070
+ } else {
1071
+ iterate(self.items, (_, id) => {
1072
+ search.items.push({
1073
+ 'score': 1,
1074
+ 'id': id
1075
+ });
1076
+ });
1077
+ }
1078
+
1079
+ const fn_sort = self._getSortFunction(search);
1080
+
1081
+ if (fn_sort) search.items.sort(fn_sort); // apply limits
1082
+
1083
+ search.total = search.items.length;
1084
+
1085
+ if (typeof options.limit === 'number') {
1086
+ search.items = search.items.slice(0, options.limit);
1087
+ }
1088
+
1089
+ return search;
1090
+ }
1091
+
1092
+ }
1093
+
1094
+ exports.Sifter = Sifter;
1095
+ exports.cmp = cmp;
1096
+ exports.getAttr = getAttr;
1097
+ exports.getAttrNesting = getAttrNesting;
1098
+ exports.getPattern = getPattern;
1099
+ exports.iterate = iterate;
1100
+ exports.propToArray = propToArray;
1101
+ exports.scoreValue = scoreValue;
1102
+
1103
+ Object.defineProperty(exports, '__esModule', { value: true });
649
1104
 
650
1105
  })));
651
1106
  //# sourceMappingURL=sifter.js.map