Created
July 7, 2017 22:27
-
-
Save nick-brown/ebea410466c3f5d920847b911b9c0b28 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function subMatches(string, subs) { | |
return [] | |
.concat.apply([], subs.map(sub => matchIndexes(string, sub))) | |
.reduce((acc, idx) => { | |
acc[idx] = true; | |
return acc; | |
}, Array.from(string).fill(false)); | |
} | |
function matchIndexes(string, sub, startIndex=0, matches=[]) { | |
if((startIndex + sub.length) > string.length) { | |
return matches; | |
} | |
if(sub === string.substr(startIndex, sub.length)) { | |
return matchIndexes(string, sub, startIndex + 1, matches.concat(range(startIndex, sub.length))); | |
} else { | |
return matchIndexes(string, sub, startIndex + 1, matches); | |
} | |
} | |
function range(start, count) { | |
return Array.from(new Array(count), (n, i) => i + start); | |
} | |
function wrapSubs(string, subs) { | |
const matches = subMatches(string, subs); | |
let open = false; | |
return string.split('').map((c, idx) => { | |
let ret = ''; | |
if(matches[idx] && !open) { | |
open = !open; | |
ret += '<b>'; | |
} else if(!matches[idx] && open) { | |
open = !open; | |
ret += '</b>'; | |
} | |
ret += c; | |
if(idx === string.length - 1 && open) { | |
ret += '</b>'; | |
} | |
return ret; | |
}).join(''); | |
} | |
console.log(wrapSubs('abcdxyzzzxzz', ['ab', 'bcd', 'z'])); | |
console.log(wrapSubs('abcdefcd', ['cd'])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment