-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
77 lines (67 loc) · 1.86 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// @flow
var match = require('fuzzaldrin-plus').match
/*::
type SplitMatchesResult = Array<{|
isMatch: boolean,
str: string
|}>
*/
function splitMatches(
text /*: string */,
matches /*: number[] */
) /*: SplitMatchesResult */ {
var _matches = matches.slice(0)
var result = []
for (var i = 0; i < text.length; i += 1) {
var isMatch = i === _matches[0]
if (isMatch) {
_matches.shift()
}
var lastIndex = result.length - 1
if (lastIndex !== -1 && result[lastIndex].isMatch === isMatch) {
result[lastIndex].str += text[i]
} else {
result.push({ str: text[i], isMatch: isMatch })
}
}
return result
}
function highlightMatches /*:: <T> */(
text /*: string */,
matches /*: number[] */,
matchesWrapper /*: (s: string, index: number, array: SplitMatchesResult) => T */,
noMatchesWrapper /*: (s: string, index: number, array: SplitMatchesResult) => T */
) /*: Array<T> */ {
if (noMatchesWrapper == null) {
// $FlowFixMe
noMatchesWrapper = function(x) {
return x
}
}
if (matches.length === 0) {
// $FlowFixMe
return [noMatchesWrapper(text)]
}
var splitMatchesResult = splitMatches(text, matches)
var result = splitMatchesResult.map(function(r, i, a) {
return r.isMatch
? matchesWrapper(r.str, i, a)
: noMatchesWrapper(r.str, i, a)
})
return result
}
function highlightChars /*:: <T> */(
text /*: string */,
chars /*: string */,
matchesWrapper /*: (s: string, index: number, array: SplitMatchesResult) => T */,
noMatchesWrapper /*: (s: string, index: number, array: SplitMatchesResult) => T */
) /*: Array<T> */ {
var matches = match(text, chars)
var result = highlightMatches(text, matches, matchesWrapper, noMatchesWrapper)
return result
}
module.exports = {
splitMatches: splitMatches,
highlightMatches: highlightMatches,
highlightChars: highlightChars
}