UNPKG

2.5 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 {
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 scoredCandidates = [];
51 for (_i = 0, _len = candidates.length; _i < _len; _i++) {
52 candidate = candidates[_i];
53 string = key != null ? candidate[key] : candidate;
54 if (!string) {
55 continue;
56 }
57 score = stringScore(string, query);
58 if (queryHasNoSlashes) {
59 score = basenameScore(string, query, score);
60 }
61 if (score > 0) {
62 scoredCandidates.push({
63 candidate: candidate,
64 score: score
65 });
66 }
67 }
68 scoredCandidates.sort(function(a, b) {
69 return b.score - a.score;
70 });
71 candidates = (function() {
72 var _j, _len1, _results;
73 _results = [];
74 for (_j = 0, _len1 = scoredCandidates.length; _j < _len1; _j++) {
75 scoredCandidate = scoredCandidates[_j];
76 _results.push(scoredCandidate.candidate);
77 }
78 return _results;
79 })();
80 }
81 if (maxResults != null) {
82 candidates = candidates.slice(0, maxResults);
83 }
84 return candidates;
85 };
86
87}).call(this);