UNPKG

2.55 kBJavaScriptView Raw
1(function() {
2 var basenameScore, stringScore;
3
4 stringScore = require('../vendor/stringscore');
5
6 basenameScore = function(string, query, score) {
7 var base, depth, index, lastCharacter, segmentCount, slashCount;
8 index = string.length - 1;
9 while (string[index] === '/') {
10 index--;
11 }
12 slashCount = 0;
13 lastCharacter = index;
14 base = null;
15 while (index >= 0) {
16 if (string[index] === '/') {
17 slashCount++;
18 if (base == null) {
19 base = string.substring(index + 1, lastCharacter + 1);
20 }
21 } else if (index === 0) {
22 if (lastCharacter < string.length - 1) {
23 if (base == null) {
24 base = string.substring(0, lastCharacter + 1);
25 }
26 } else {
27 if (base == null) {
28 base = string;
29 }
30 }
31 }
32 index--;
33 }
34 if (base === string) {
35 score *= 2;
36 } else if (base) {
37 score += stringScore(base, query);
38 }
39 segmentCount = slashCount + 1;
40 depth = Math.max(1, 10 - segmentCount);
41 score *= depth * 0.01;
42 return score;
43 };
44
45 module.exports = function(candidates, query, _arg) {
46 var candidate, key, maxResults, queryHasNoSlashes, score, scoredCandidate, scoredCandidates, string, _i, _len, _ref;
47 _ref = _arg != null ? _arg : {}, key = _ref.key, maxResults = _ref.maxResults;
48 if (query) {
49 queryHasNoSlashes = query.indexOf('/') === -1;
50 query = query.replace(/\ /g, '');
51 scoredCandidates = [];
52 for (_i = 0, _len = candidates.length; _i < _len; _i++) {
53 candidate = candidates[_i];
54 string = key != null ? candidate[key] : candidate;
55 if (!string) {
56 continue;
57 }
58 score = stringScore(string, query);
59 if (queryHasNoSlashes) {
60 score = basenameScore(string, query, score);
61 }
62 if (score > 0) {
63 scoredCandidates.push({
64 candidate: candidate,
65 score: score
66 });
67 }
68 }
69 scoredCandidates.sort(function(a, b) {
70 return b.score - a.score;
71 });
72 candidates = (function() {
73 var _j, _len1, _results;
74 _results = [];
75 for (_j = 0, _len1 = scoredCandidates.length; _j < _len1; _j++) {
76 scoredCandidate = scoredCandidates[_j];
77 _results.push(scoredCandidate.candidate);
78 }
79 return _results;
80 })();
81 }
82 if (maxResults != null) {
83 candidates = candidates.slice(0, maxResults);
84 }
85 return candidates;
86 };
87
88}).call(this);