@orchidjs/sifter 0.9.3 → 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 +776 -49
  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 +32 -36
  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 +2 -6
  21. package/dist/umd/sifter.js +1101 -638
  22. package/dist/umd/sifter.js.map +1 -1
  23. package/dist/umd/sifter.min.js +110 -78
  24. package/dist/umd/sifter.min.js.map +1 -1
  25. package/lib/sifter.ts +41 -45
  26. package/lib/types.ts +14 -10
  27. package/lib/utils.ts +4 -14
  28. package/package.json +5 -2
  29. package/dist/cjs/diacritics.js +0 -182
  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 -173
  33. package/dist/esm/diacritics.js.map +0 -1
  34. package/dist/types/diacritics.d.ts +0 -35
  35. package/lib/diacritics.ts +0 -196
@@ -1,8 +1,734 @@
1
1
  /*! sifter.js | https://github.com/orchidjs/sifter.js | Apache License (v2) */
2
2
  'use strict';
3
3
 
4
- var utils = require('./utils.js');
5
- var diacritics = require('./diacritics.js');
4
+ Object.defineProperty(exports, '__esModule', { value: true });
5
+
6
+ /*! @orchidjs/unicode-variants | https://github.com/orchidjs/unicode-variants | Apache License (v2) */
7
+
8
+ /**
9
+ * Convert array of strings to a regular expression
10
+ * ex ['ab','a'] => (?:ab|a)
11
+ * ex ['a','b'] => [ab]
12
+ * @param {string[]} chars
13
+ * @return {string}
14
+ */
15
+ const arrayToPattern = chars => {
16
+ chars = chars.filter(Boolean);
17
+
18
+ if (chars.length < 2) {
19
+ return chars[0] || '';
20
+ }
21
+
22
+ return maxValueLength(chars) == 1 ? '[' + chars.join('') + ']' : '(?:' + chars.join('|') + ')';
23
+ };
24
+ /**
25
+ * @param {string[]} array
26
+ * @return {string}
27
+ */
28
+
29
+
30
+ const sequencePattern = array => {
31
+ if (!hasDuplicates(array)) {
32
+ return array.join('');
33
+ }
34
+
35
+ let pattern = '';
36
+ let prev_char_count = 0;
37
+
38
+ const prev_pattern = () => {
39
+ if (prev_char_count > 1) {
40
+ pattern += '{' + prev_char_count + '}';
41
+ }
42
+ };
43
+
44
+ array.forEach((char, i) => {
45
+ if (char === array[i - 1]) {
46
+ prev_char_count++;
47
+ return;
48
+ }
49
+
50
+ prev_pattern();
51
+ pattern += char;
52
+ prev_char_count = 1;
53
+ });
54
+ prev_pattern();
55
+ return pattern;
56
+ };
57
+ /**
58
+ * Convert array of strings to a regular expression
59
+ * ex ['ab','a'] => (?:ab|a)
60
+ * ex ['a','b'] => [ab]
61
+ * @param {Set<string>} chars
62
+ * @return {string}
63
+ */
64
+
65
+
66
+ const setToPattern = chars => {
67
+ let array = toArray(chars);
68
+ return arrayToPattern(array);
69
+ };
70
+ /**
71
+ *
72
+ * https://stackoverflow.com/questions/7376598/in-javascript-how-do-i-check-if-an-array-has-duplicate-values
73
+ * @param {any[]} array
74
+ */
75
+
76
+
77
+ const hasDuplicates = array => {
78
+ return new Set(array).size !== array.length;
79
+ };
80
+ /**
81
+ * https://stackoverflow.com/questions/63006601/why-does-u-throw-an-invalid-escape-error
82
+ * @param {string} str
83
+ * @return {string}
84
+ */
85
+
86
+
87
+ const escape_regex = str => {
88
+ return (str + '').replace(/([\$\(-\+\.\?\[-\^\{-\}])/g, '\\$1');
89
+ };
90
+ /**
91
+ * Return the max length of array values
92
+ * @param {string[]} array
93
+ *
94
+ */
95
+
96
+
97
+ const maxValueLength = array => {
98
+ return array.reduce((longest, value) => Math.max(longest, unicodeLength(value)), 0);
99
+ };
100
+ /**
101
+ * @param {string} str
102
+ */
103
+
104
+
105
+ const unicodeLength = str => {
106
+ return toArray(str).length;
107
+ };
108
+ /**
109
+ * @param {any} p
110
+ * @return {any[]}
111
+ */
112
+
113
+
114
+ const toArray = p => Array.from(p);
115
+
116
+ /*! @orchidjs/unicode-variants | https://github.com/orchidjs/unicode-variants | Apache License (v2) */
117
+
118
+ /**
119
+ * Get all possible combinations of substrings that add up to the given string
120
+ * https://stackoverflow.com/questions/30169587/find-all-the-combination-of-substrings-that-add-up-to-the-given-string
121
+ * @param {string} input
122
+ * @return {string[][]}
123
+ */
124
+ const allSubstrings = input => {
125
+ if (input.length === 1) return [[input]];
126
+ /** @type {string[][]} */
127
+
128
+ let result = [];
129
+ const start = input.substring(1);
130
+ const suba = allSubstrings(start);
131
+ suba.forEach(function (subresult) {
132
+ let tmp = subresult.slice(0);
133
+ tmp[0] = input.charAt(0) + tmp[0];
134
+ result.push(tmp);
135
+ tmp = subresult.slice(0);
136
+ tmp.unshift(input.charAt(0));
137
+ result.push(tmp);
138
+ });
139
+ return result;
140
+ };
141
+
142
+ /*! @orchidjs/unicode-variants | https://github.com/orchidjs/unicode-variants | Apache License (v2) */
143
+ /**
144
+ * @typedef {{[key:string]:string}} TUnicodeMap
145
+ * @typedef {{[key:string]:Set<string>}} TUnicodeSets
146
+ * @typedef {[[number,number]]} TCodePoints
147
+ * @typedef {{folded:string,composed:string,code_point:number}} TCodePointObj
148
+ * @typedef {{start:number,end:number,length:number,substr:string}} TSequencePart
149
+ */
150
+
151
+ /** @type {TCodePoints} */
152
+
153
+ const code_points = [[0, 65535]];
154
+ const accent_pat = '[\u0300-\u036F\u{b7}\u{2be}]'; // \u{2bc}
155
+
156
+ /** @type {TUnicodeMap} */
157
+
158
+ let unicode_map;
159
+ /** @type {RegExp} */
160
+
161
+ let multi_char_reg;
162
+ const max_char_length = 3;
163
+ /** @type {TUnicodeMap} */
164
+
165
+ const latin_convert = {
166
+ 'æ': 'ae',
167
+ 'ⱥ': 'a',
168
+ 'ø': 'o',
169
+ '⁄': '/',
170
+ '∕': '/'
171
+ };
172
+ const convert_pat = new RegExp(Object.keys(latin_convert).join('|') + '|' + accent_pat, 'gu');
173
+ /**
174
+ * Initialize the unicode_map from the give code point ranges
175
+ *
176
+ * @param {TCodePoints=} _code_points
177
+ */
178
+
179
+ const initialize = _code_points => {
180
+ if (unicode_map !== undefined) return;
181
+ unicode_map = generateMap(_code_points || code_points);
182
+ };
183
+ /**
184
+ * Helper method for normalize a string
185
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize
186
+ * @param {string} str
187
+ * @param {string} form
188
+ */
189
+
190
+
191
+ const normalize = (str, form = 'NFKD') => str.normalize(form);
192
+ /**
193
+ * Compatibility Decomposition without reordering string
194
+ * calling str.normalize('NFKD') on \u{594}\u{595}\u{596} becomes \u{596}\u{594}\u{595}
195
+ * @param {string} str
196
+ */
197
+
198
+
199
+ const decompose = str => {
200
+ if (str.match(/[\u0f71-\u0f81]/)) {
201
+ return toArray(str).reduce(
202
+ /**
203
+ * @param {string} result
204
+ * @param {string} char
205
+ */
206
+ (result, char) => {
207
+ return result + normalize(char);
208
+ }, '');
209
+ }
210
+
211
+ return normalize(str);
212
+ };
213
+ /**
214
+ * Remove accents
215
+ * via https://github.com/krisk/Fuse/issues/133#issuecomment-318692703
216
+ * @param {string} str
217
+ * @return {string}
218
+ */
219
+
220
+
221
+ const asciifold = str => {
222
+ return decompose(str).toLowerCase().replace(convert_pat,
223
+ /** @type {string} */
224
+ char => {
225
+ return latin_convert[char] || '';
226
+ });
227
+ };
228
+ /**
229
+ * Generate a list of unicode variants from the list of code points
230
+ * @param {TCodePoints} code_points
231
+ * @yield {TCodePointObj}
232
+ */
233
+
234
+
235
+ function* generator(code_points) {
236
+ for (const [code_point_min, code_point_max] of code_points) {
237
+ for (let i = code_point_min; i <= code_point_max; i++) {
238
+ let composed = String.fromCharCode(i);
239
+ let folded = asciifold(composed);
240
+
241
+ if (folded == composed.toLowerCase()) {
242
+ continue;
243
+ } // skip when folded is a string longer than 3 characters long
244
+ // bc the resulting regex patterns will be long
245
+ // eg:
246
+ // folded صلى الله عليه وسلم length 18 code point 65018
247
+ // folded جل جلاله length 8 code point 65019
248
+
249
+
250
+ if (folded.length > max_char_length) {
251
+ continue;
252
+ }
253
+
254
+ if (folded.length == 0) {
255
+ continue;
256
+ }
257
+
258
+ let decomposed = normalize(composed);
259
+ let recomposed = normalize(decomposed, 'NFC');
260
+
261
+ if (recomposed === composed && folded === decomposed) {
262
+ continue;
263
+ }
264
+
265
+ yield {
266
+ folded: folded,
267
+ composed: composed,
268
+ code_point: i
269
+ };
270
+ }
271
+ }
272
+ }
273
+ /**
274
+ * Generate a unicode map from the list of code points
275
+ * @param {TCodePoints} code_points
276
+ * @return {TUnicodeSets}
277
+ */
278
+
279
+
280
+ const generateSets = code_points => {
281
+ /** @type {{[key:string]:Set<string>}} */
282
+ const unicode_sets = {};
283
+ /**
284
+ * @param {string} folded
285
+ * @param {string} to_add
286
+ */
287
+
288
+ const addMatching = (folded, to_add) => {
289
+ /** @type {Set<string>} */
290
+ const folded_set = unicode_sets[folded] || new Set();
291
+ const patt = new RegExp('^' + setToPattern(folded_set) + '$', 'iu');
292
+
293
+ if (to_add.match(patt)) {
294
+ return;
295
+ }
296
+
297
+ folded_set.add(escape_regex(to_add));
298
+ unicode_sets[folded] = folded_set;
299
+ };
300
+
301
+ for (let value of generator(code_points)) {
302
+ addMatching(value.folded, value.folded);
303
+ addMatching(value.folded, value.composed);
304
+ }
305
+
306
+ return unicode_sets;
307
+ };
308
+ /**
309
+ * Generate a unicode map from the list of code points
310
+ * ae => (?:(?:ae|Æ|Ǽ|Ǣ)|(?:A|Ⓐ|A...)(?:E|ɛ|Ⓔ...))
311
+ *
312
+ * @param {TCodePoints} code_points
313
+ * @return {TUnicodeMap}
314
+ */
315
+
316
+
317
+ const generateMap = code_points => {
318
+ /** @type {TUnicodeSets} */
319
+ const unicode_sets = generateSets(code_points);
320
+ /** @type {TUnicodeMap} */
321
+
322
+ const unicode_map = {};
323
+ /** @type {string[]} */
324
+
325
+ let multi_char = [];
326
+
327
+ for (let folded in unicode_sets) {
328
+ let set = unicode_sets[folded];
329
+
330
+ if (set) {
331
+ unicode_map[folded] = setToPattern(set);
332
+ }
333
+
334
+ if (folded.length > 1) {
335
+ multi_char.push(escape_regex(folded));
336
+ }
337
+ }
338
+
339
+ multi_char.sort((a, b) => b.length - a.length);
340
+ const multi_char_patt = arrayToPattern(multi_char);
341
+ multi_char_reg = new RegExp('^' + multi_char_patt, 'u');
342
+ return unicode_map;
343
+ };
344
+ /**
345
+ * Map each element of an array from it's folded value to all possible unicode matches
346
+ * @param {string[]} strings
347
+ * @param {number} min_replacement
348
+ * @return {string}
349
+ */
350
+
351
+
352
+ const mapSequence = (strings, min_replacement = 1) => {
353
+ let chars_replaced = 0;
354
+ strings = strings.map(str => {
355
+ if (unicode_map[str]) {
356
+ chars_replaced += str.length;
357
+ }
358
+
359
+ return unicode_map[str] || str;
360
+ });
361
+
362
+ if (chars_replaced >= min_replacement) {
363
+ return sequencePattern(strings);
364
+ }
365
+
366
+ return '';
367
+ };
368
+ /**
369
+ * Convert a short string and split it into all possible patterns
370
+ * Keep a pattern only if min_replacement is met
371
+ *
372
+ * 'abc'
373
+ * => [['abc'],['ab','c'],['a','bc'],['a','b','c']]
374
+ * => ['abc-pattern','ab-c-pattern'...]
375
+ *
376
+ *
377
+ * @param {string} str
378
+ * @param {number} min_replacement
379
+ * @return {string}
380
+ */
381
+
382
+
383
+ const substringsToPattern = (str, min_replacement = 1) => {
384
+ min_replacement = Math.max(min_replacement, str.length - 1);
385
+ return arrayToPattern(allSubstrings(str).map(sub_pat => {
386
+ return mapSequence(sub_pat, min_replacement);
387
+ }));
388
+ };
389
+ /**
390
+ * Convert an array of sequences into a pattern
391
+ * [{start:0,end:3,length:3,substr:'iii'}...] => (?:iii...)
392
+ *
393
+ * @param {Sequence[]} sequences
394
+ * @param {boolean} all
395
+ */
396
+
397
+
398
+ const sequencesToPattern = (sequences, all = true) => {
399
+ let min_replacement = sequences.length > 1 ? 1 : 0;
400
+ return arrayToPattern(sequences.map(sequence => {
401
+ let seq = [];
402
+ const len = all ? sequence.length() : sequence.length() - 1;
403
+
404
+ for (let j = 0; j < len; j++) {
405
+ seq.push(substringsToPattern(sequence.substrs[j] || '', min_replacement));
406
+ }
407
+
408
+ return sequencePattern(seq);
409
+ }));
410
+ };
411
+ /**
412
+ * Return true if the sequence is already in the sequences
413
+ * @param {Sequence} needle_seq
414
+ * @param {Sequence[]} sequences
415
+ */
416
+
417
+
418
+ const inSequences = (needle_seq, sequences) => {
419
+ for (const seq of sequences) {
420
+ if (seq.start != needle_seq.start || seq.end != needle_seq.end) {
421
+ continue;
422
+ }
423
+
424
+ if (seq.substrs.join('') !== needle_seq.substrs.join('')) {
425
+ continue;
426
+ }
427
+
428
+ let needle_parts = needle_seq.parts;
429
+ /**
430
+ * @param {TSequencePart} part
431
+ */
432
+
433
+ const filter = part => {
434
+ for (const needle_part of needle_parts) {
435
+ if (needle_part.start === part.start && needle_part.substr === part.substr) {
436
+ return false;
437
+ }
438
+
439
+ if (part.length == 1 || needle_part.length == 1) {
440
+ continue;
441
+ } // check for overlapping parts
442
+ // a = ['::=','==']
443
+ // b = ['::','===']
444
+ // a = ['r','sm']
445
+ // b = ['rs','m']
446
+
447
+
448
+ if (part.start < needle_part.start && part.end > needle_part.start) {
449
+ return true;
450
+ }
451
+
452
+ if (needle_part.start < part.start && needle_part.end > part.start) {
453
+ return true;
454
+ }
455
+ }
456
+
457
+ return false;
458
+ };
459
+
460
+ let filtered = seq.parts.filter(filter);
461
+
462
+ if (filtered.length > 0) {
463
+ continue;
464
+ }
465
+
466
+ return true;
467
+ }
468
+
469
+ return false;
470
+ };
471
+
472
+ class Sequence {
473
+ constructor() {
474
+ /** @type {TSequencePart[]} */
475
+ this.parts = [];
476
+ /** @type {string[]} */
477
+
478
+ this.substrs = [];
479
+ this.start = 0;
480
+ this.end = 0;
481
+ }
482
+ /**
483
+ * @param {TSequencePart|undefined} part
484
+ */
485
+
486
+
487
+ add(part) {
488
+ if (part) {
489
+ this.parts.push(part);
490
+ this.substrs.push(part.substr);
491
+ this.start = Math.min(part.start, this.start);
492
+ this.end = Math.max(part.end, this.end);
493
+ }
494
+ }
495
+
496
+ last() {
497
+ return this.parts[this.parts.length - 1];
498
+ }
499
+
500
+ length() {
501
+ return this.parts.length;
502
+ }
503
+ /**
504
+ * @param {number} position
505
+ * @param {TSequencePart} last_piece
506
+ */
507
+
508
+
509
+ clone(position, last_piece) {
510
+ let clone = new Sequence();
511
+ let parts = JSON.parse(JSON.stringify(this.parts));
512
+ let last_part = parts.pop();
513
+
514
+ for (const part of parts) {
515
+ clone.add(part);
516
+ }
517
+
518
+ let last_substr = last_piece.substr.substring(0, position - last_part.start);
519
+ let clone_last_len = last_substr.length;
520
+ clone.add({
521
+ start: last_part.start,
522
+ end: last_part.start + clone_last_len,
523
+ length: clone_last_len,
524
+ substr: last_substr
525
+ });
526
+ return clone;
527
+ }
528
+
529
+ }
530
+ /**
531
+ * Expand a regular expression pattern to include unicode variants
532
+ * eg /a/ becomes /aⓐaẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐɑAⒶAÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄȺⱯ/
533
+ *
534
+ * Issue:
535
+ * ﺊﺋ [ 'ﺊ = \\u{fe8a}', 'ﺋ = \\u{fe8b}' ]
536
+ * becomes: ئئ [ 'ي = \\u{64a}', 'ٔ = \\u{654}', 'ي = \\u{64a}', 'ٔ = \\u{654}' ]
537
+ *
538
+ * İIJ = IIJ = ⅡJ
539
+ *
540
+ * 1/2/4
541
+ *
542
+ * @param {string} str
543
+ * @return {string|undefined}
544
+ */
545
+
546
+
547
+ const getPattern = str => {
548
+ initialize();
549
+ str = asciifold(str);
550
+ let pattern = '';
551
+ let sequences = [new Sequence()];
552
+
553
+ for (let i = 0; i < str.length; i++) {
554
+ let substr = str.substring(i);
555
+ let match = substr.match(multi_char_reg);
556
+ const char = str.substring(i, i + 1);
557
+ const match_str = match ? match[0] : null; // loop through sequences
558
+ // add either the char or multi_match
559
+
560
+ let overlapping = [];
561
+ let added_types = new Set();
562
+
563
+ for (const sequence of sequences) {
564
+ const last_piece = sequence.last();
565
+
566
+ if (!last_piece || last_piece.length == 1 || last_piece.end <= i) {
567
+ // if we have a multi match
568
+ if (match_str) {
569
+ const len = match_str.length;
570
+ sequence.add({
571
+ start: i,
572
+ end: i + len,
573
+ length: len,
574
+ substr: match_str
575
+ });
576
+ added_types.add('1');
577
+ } else {
578
+ sequence.add({
579
+ start: i,
580
+ end: i + 1,
581
+ length: 1,
582
+ substr: char
583
+ });
584
+ added_types.add('2');
585
+ }
586
+ } else if (match_str) {
587
+ let clone = sequence.clone(i, last_piece);
588
+ const len = match_str.length;
589
+ clone.add({
590
+ start: i,
591
+ end: i + len,
592
+ length: len,
593
+ substr: match_str
594
+ });
595
+ overlapping.push(clone);
596
+ } else {
597
+ // don't add char
598
+ // adding would create invalid patterns: 234 => [2,34,4]
599
+ added_types.add('3');
600
+ }
601
+ } // if we have overlapping
602
+
603
+
604
+ if (overlapping.length > 0) {
605
+ // ['ii','iii'] before ['i','i','iii']
606
+ overlapping = overlapping.sort((a, b) => {
607
+ return a.length() - b.length();
608
+ });
609
+
610
+ for (let clone of overlapping) {
611
+ // don't add if we already have an equivalent sequence
612
+ if (inSequences(clone, sequences)) {
613
+ continue;
614
+ }
615
+
616
+ sequences.push(clone);
617
+ }
618
+
619
+ continue;
620
+ } // if we haven't done anything unique
621
+ // clean up the patterns
622
+ // helps keep patterns smaller
623
+ // if str = 'r₨㎧aarss', pattern will be 446 instead of 655
624
+
625
+
626
+ if (i > 0 && added_types.size == 1 && !added_types.has('3')) {
627
+ pattern += sequencesToPattern(sequences, false);
628
+ let new_seq = new Sequence();
629
+ const old_seq = sequences[0];
630
+
631
+ if (old_seq) {
632
+ new_seq.add(old_seq.last());
633
+ }
634
+
635
+ sequences = [new_seq];
636
+ }
637
+ }
638
+
639
+ pattern += sequencesToPattern(sequences, true);
640
+ return pattern;
641
+ };
642
+
643
+ /**
644
+ * A property getter resolving dot-notation
645
+ * @param {Object} obj The root object to fetch property on
646
+ * @param {String} name The optionally dotted property name to fetch
647
+ * @return {Object} The resolved property value
648
+ */
649
+ const getAttr = (obj, name) => {
650
+ if (!obj) return;
651
+ return obj[name];
652
+ };
653
+ /**
654
+ * A property getter resolving dot-notation
655
+ * @param {Object} obj The root object to fetch property on
656
+ * @param {String} name The optionally dotted property name to fetch
657
+ * @return {Object} The resolved property value
658
+ */
659
+
660
+ const getAttrNesting = (obj, name) => {
661
+ if (!obj) return;
662
+ var part,
663
+ names = name.split(".");
664
+
665
+ while ((part = names.shift()) && (obj = obj[part]));
666
+
667
+ return obj;
668
+ };
669
+ /**
670
+ * Calculates how close of a match the
671
+ * given value is against a search token.
672
+ *
673
+ */
674
+
675
+ const scoreValue = (value, token, weight) => {
676
+ var score, pos;
677
+ if (!value) return 0;
678
+ value = value + '';
679
+ if (token.regex == null) return 0;
680
+ pos = value.search(token.regex);
681
+ if (pos === -1) return 0;
682
+ score = token.string.length / value.length;
683
+ if (pos === 0) score += 0.5;
684
+ return score * weight;
685
+ };
686
+ /**
687
+ * Cast object property to an array if it exists and has a value
688
+ *
689
+ */
690
+
691
+ const propToArray = (obj, key) => {
692
+ var value = obj[key];
693
+ if (typeof value == 'function') return value;
694
+
695
+ if (value && !Array.isArray(value)) {
696
+ obj[key] = [value];
697
+ }
698
+ };
699
+ /**
700
+ * Iterates over arrays and hashes.
701
+ *
702
+ * ```
703
+ * iterate(this.items, function(item, id) {
704
+ * // invoked for each item
705
+ * });
706
+ * ```
707
+ *
708
+ */
709
+
710
+ const iterate = (object, callback) => {
711
+ if (Array.isArray(object)) {
712
+ object.forEach(callback);
713
+ } else {
714
+ for (var key in object) {
715
+ if (object.hasOwnProperty(key)) {
716
+ callback(object[key], key);
717
+ }
718
+ }
719
+ }
720
+ };
721
+ const cmp = (a, b) => {
722
+ if (typeof a === 'number' && typeof b === 'number') {
723
+ return a > b ? 1 : a < b ? -1 : 0;
724
+ }
725
+
726
+ a = asciifold(a + '').toLowerCase();
727
+ b = asciifold(b + '').toLowerCase();
728
+ if (a > b) return 1;
729
+ if (b > a) return -1;
730
+ return 0;
731
+ };
6
732
 
7
733
  /**
8
734
  * sifter.js
@@ -50,7 +776,7 @@ class Sifter {
50
776
  var field_regex;
51
777
 
52
778
  if (weights) {
53
- field_regex = new RegExp('^(' + Object.keys(weights).map(utils.escape_regex).join('|') + ')\:(.*)$');
779
+ field_regex = new RegExp('^(' + Object.keys(weights).map(escape_regex).join('|') + ')\:(.*)$');
54
780
  }
55
781
 
56
782
  words.forEach(word => {
@@ -65,12 +791,12 @@ class Sifter {
65
791
 
66
792
  if (word.length > 0) {
67
793
  if (this.settings.diacritics) {
68
- regex = diacritics.diacriticRegexPoints(word);
794
+ regex = getPattern(word) || null;
69
795
  } else {
70
- regex = utils.escape_regex(word);
796
+ regex = escape_regex(word);
71
797
  }
72
798
 
73
- if (respect_word_boundaries) regex = "\\b" + regex;
799
+ if (regex && respect_word_boundaries) regex = "\\b" + regex;
74
800
  }
75
801
 
76
802
  tokens.push({
@@ -88,12 +814,17 @@ class Sifter {
88
814
  * Good matches will have a higher score than poor matches.
89
815
  * If an item is not a match, 0 will be returned by the function.
90
816
  *
91
- * @returns {function}
817
+ * @returns {T.ScoreFn}
92
818
  */
93
819
  getScoreFunction(query, options) {
94
820
  var search = this.prepareSearch(query, options);
95
821
  return this._getScoreFunction(search);
96
822
  }
823
+ /**
824
+ * @returns {T.ScoreFn}
825
+ *
826
+ */
827
+
97
828
 
98
829
  _getScoreFunction(search) {
99
830
  const tokens = search.tokens,
@@ -126,7 +857,7 @@ class Sifter {
126
857
  if (field_count === 1) {
127
858
  return function (token, data) {
128
859
  const field = fields[0].field;
129
- return utils.scoreValue(getAttrFn(data, field), token, weights[field]);
860
+ return scoreValue(getAttrFn(data, field), token, weights[field] || 1);
130
861
  };
131
862
  }
132
863
 
@@ -139,11 +870,11 @@ class Sifter {
139
870
  if (!token.regex && value) {
140
871
  sum += 1 / field_count;
141
872
  } else {
142
- sum += utils.scoreValue(value, token, 1);
873
+ sum += scoreValue(value, token, 1);
143
874
  }
144
875
  } else {
145
- utils.iterate(weights, (weight, field) => {
146
- sum += utils.scoreValue(getAttrFn(data, field), token, weight);
876
+ iterate(weights, (weight, field) => {
877
+ sum += scoreValue(getAttrFn(data, field), token, weight);
147
878
  });
148
879
  }
149
880
 
@@ -159,12 +890,11 @@ class Sifter {
159
890
 
160
891
  if (search.options.conjunction === 'and') {
161
892
  return function (data) {
162
- var i = 0,
163
- score,
893
+ var score,
164
894
  sum = 0;
165
895
 
166
- for (; i < token_count; i++) {
167
- score = scoreObject(tokens[i], data);
896
+ for (let token of tokens) {
897
+ score = scoreObject(token, data);
168
898
  if (score <= 0) return 0;
169
899
  sum += score;
170
900
  }
@@ -174,7 +904,7 @@ class Sifter {
174
904
  } else {
175
905
  return function (data) {
176
906
  var sum = 0;
177
- utils.iterate(tokens, token => {
907
+ iterate(tokens, token => {
178
908
  sum += scoreObject(token, data);
179
909
  });
180
910
  return sum / token_count;
@@ -195,12 +925,11 @@ class Sifter {
195
925
  }
196
926
 
197
927
  _getSortFunction(search) {
198
- var i, n, implicit_score;
928
+ var implicit_score,
929
+ sort_flds = [];
199
930
  const self = this,
200
931
  options = search.options,
201
- sort = !search.query && options.sort_empty ? options.sort_empty : options.sort,
202
- sort_flds = [],
203
- multipliers = [];
932
+ sort = !search.query && options.sort_empty ? options.sort_empty : options.sort;
204
933
 
205
934
  if (typeof sort == 'function') {
206
935
  return sort.bind(this);
@@ -219,9 +948,9 @@ class Sifter {
219
948
 
220
949
 
221
950
  if (sort) {
222
- for (i = 0, n = sort.length; i < n; i++) {
223
- if (search.query || sort[i].field !== '$score') {
224
- sort_flds.push(sort[i]);
951
+ for (let s of sort) {
952
+ if (search.query || s.field !== '$score') {
953
+ sort_flds.push(s);
225
954
  }
226
955
  }
227
956
  } // the "$score" field is implied to be the primary
@@ -231,8 +960,8 @@ class Sifter {
231
960
  if (search.query) {
232
961
  implicit_score = true;
233
962
 
234
- for (i = 0, n = sort_flds.length; i < n; i++) {
235
- if (sort_flds[i].field === '$score') {
963
+ for (let fld of sort_flds) {
964
+ if (fld.field === '$score') {
236
965
  implicit_score = false;
237
966
  break;
238
967
  }
@@ -243,14 +972,10 @@ class Sifter {
243
972
  field: '$score',
244
973
  direction: 'desc'
245
974
  });
246
- }
975
+ } // without a search.query, all items will have the same score
976
+
247
977
  } else {
248
- for (i = 0, n = sort_flds.length; i < n; i++) {
249
- if (sort_flds[i].field === '$score') {
250
- sort_flds.splice(i, 1);
251
- break;
252
- }
253
- }
978
+ sort_flds = sort_flds.filter(fld => fld.field !== '$score');
254
979
  } // build function
255
980
 
256
981
 
@@ -261,17 +986,12 @@ class Sifter {
261
986
  }
262
987
 
263
988
  return function (a, b) {
264
- var i, result, field;
265
-
266
- for (i = 0; i < sort_flds_count; i++) {
267
- field = sort_flds[i].field;
268
- let multiplier = multipliers[i];
269
-
270
- if (multiplier == undefined) {
271
- multiplier = sort_flds[i].direction === 'desc' ? -1 : 1;
272
- }
989
+ var result, field;
273
990
 
274
- result = multiplier * utils.cmp(get_field(field, a), get_field(field, b));
991
+ for (let sort_fld of sort_flds) {
992
+ field = sort_fld.field;
993
+ let multiplier = sort_fld.direction === 'desc' ? -1 : 1;
994
+ result = multiplier * cmp(get_field(field, a), get_field(field, b));
275
995
  if (result) return result;
276
996
  }
277
997
 
@@ -288,11 +1008,11 @@ class Sifter {
288
1008
  prepareSearch(query, optsUser) {
289
1009
  const weights = {};
290
1010
  var options = Object.assign({}, optsUser);
291
- utils.propToArray(options, 'sort');
292
- utils.propToArray(options, 'sort_empty'); // convert fields to new format
1011
+ propToArray(options, 'sort');
1012
+ propToArray(options, 'sort_empty'); // convert fields to new format
293
1013
 
294
1014
  if (options.fields) {
295
- utils.propToArray(options, 'fields');
1015
+ propToArray(options, 'fields');
296
1016
  const fields = [];
297
1017
  options.fields.forEach(field => {
298
1018
  if (typeof field == 'string') {
@@ -315,7 +1035,7 @@ class Sifter {
315
1035
  total: 0,
316
1036
  items: [],
317
1037
  weights: weights,
318
- getAttrFn: options.nesting ? utils.getAttrNesting : utils.getAttr
1038
+ getAttrFn: options.nesting ? getAttrNesting : getAttr
319
1039
  };
320
1040
  }
321
1041
 
@@ -335,7 +1055,7 @@ class Sifter {
335
1055
 
336
1056
 
337
1057
  if (query.length) {
338
- utils.iterate(self.items, (item, id) => {
1058
+ iterate(self.items, (item, id) => {
339
1059
  score = fn_score(item);
340
1060
 
341
1061
  if (options.filter === false || score > 0) {
@@ -346,7 +1066,7 @@ class Sifter {
346
1066
  }
347
1067
  });
348
1068
  } else {
349
- utils.iterate(self.items, (_, id) => {
1069
+ iterate(self.items, (_, id) => {
350
1070
  search.items.push({
351
1071
  'score': 1,
352
1072
  'id': id
@@ -369,5 +1089,12 @@ class Sifter {
369
1089
 
370
1090
  }
371
1091
 
372
- module.exports = Sifter;
1092
+ exports.Sifter = Sifter;
1093
+ exports.cmp = cmp;
1094
+ exports.getAttr = getAttr;
1095
+ exports.getAttrNesting = getAttrNesting;
1096
+ exports.getPattern = getPattern;
1097
+ exports.iterate = iterate;
1098
+ exports.propToArray = propToArray;
1099
+ exports.scoreValue = scoreValue;
373
1100
  //# sourceMappingURL=sifter.js.map