UNPKG

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