Skip to content

Instantly share code, notes, and snippets.

@Tanami
Last active February 12, 2020 08:53
Show Gist options
  • Save Tanami/1c8c02bc6f08e76959368bcbae88b3cb to your computer and use it in GitHub Desktop.
Save Tanami/1c8c02bc6f08e76959368bcbae88b3cb to your computer and use it in GitHub Desktop.
very fast text "highlighting" using substring and charCodeAt
const content = document.querySelector('#editor').value
const output = document.querySelector('#maze')
output.innerHTML = ''
if (content == '')
return
let t0 = performance.now()
let offsets = []
for (let word of this.db) {
let startIndex = 0, index
const len = word.length
const search = word.toLowerCase()
const str = content.toLowerCase()
while ((index = str.indexOf(search, startIndex)) > -1) {
let left = str.charCodeAt(index-1)
let right = str.charCodeAt(index+search.length)
// this might break in very surprising ways...
if ((index === 0 || left < 33) && (right < 33 || index+search.length === str.length))
offsets.push([index, search])
startIndex = index + len
}
}
if (offsets.length === 0) {
output.innerHTML = content
return
}
// console.log(JSON.stringify(offsets))
offsets = offsets.sort((a, b) => ((parseInt(a[0]) > parseInt(b[0])) ? 1 : -1))
output.appendChild(document.createTextNode(content.substring(0, offsets[0][0])))
let bound = offsets.length
for (let pair = 0; pair < bound; pair++) {
const word_start = offsets[pair][0]
const word_length = offsets[pair][0] + offsets[pair][1].length
const next_pair = offsets[parseInt(pair) + 1] ? offsets[parseInt(pair) + 1][0] : -1
let rem
const a = document.createElement("a")
a.appendChild(document.createTextNode(content.substring(word_start, word_length)))
a.href = '#/' + offsets[pair][1]
output.appendChild(a)
if (next_pair !== -1) {
rem = content.substring(word_length, next_pair)
}
else {
rem = content.substring(word_length)
}
output.appendChild(document.createTextNode(rem))
}
let t1 = performance.now()
console.log("took " + (t1 - t0) + " milliseconds.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment