forked from rsmelo92/bob-ross-highlight-html
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmethods.js
71 lines (68 loc) · 1.88 KB
/
methods.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
const stringManipulation = (trimmedText, wordToBeHighlighted) => {
// Set regex to be found
const regex = wordToBeHighlighted
.replace(/\s/gi, "")
.split("")
.map((letter, index, array) => {
if (array.length === index + 1) {
return letter;
}
if (letter.match(/[^A-Z0-9 ]/gi)) {
return `${letter}*_*?`
.normalize("NFD")
.replace(/[\u0300-\u036f]/gi, "");
}
return `${letter}_*`;
})
.join("");
// Find regex
const pattern = new RegExp(regex, "gi");
// Get final and init position for the underline terms
const termsLength = [];
trimmedText.replace(pattern, item => {
const regexExec = trimmedText.match(item);
termsLength.push({
initPosition: regexExec.index,
finalPosition: regexExec.index + item.length
});
return item;
});
return termsLength;
};
const fuzzy = (trimmedText, wordToBeHighlighted) => {
// import Fuzzy package
const stringSimilarity = require("string-similarity");
let similarity;
let higherSimilarity = 0.00000001;
const similars = [];
// Test similarities and get second higher one
trimmedText.split("").reduce((a, b) => {
similarity = stringSimilarity.compareTwoStrings(
wordToBeHighlighted.normalize("NFD").replace(/[\u0300-\u036f]/gi, ""),
a
);
if (similarity >= higherSimilarity) {
higherSimilarity = similarity;
similars.unshift(a);
}
if (a.length === wordToBeHighlighted.length) {
return a.substr(1) + b;
}
return a + b;
});
// Get final and init position for the underline terms
return getPositions(trimmedText, similars[1]);
};
const getPositions = (trimmedText, regex) => {
const regexExec = trimmedText.indexOf(regex);
return [
{
initPosition: regexExec,
finalPosition: regexExec + regex.length
}
];
};
module.exports = {
fuzzy,
stringManipulation
};