Skip to content

Instantly share code, notes, and snippets.

@vaaas
Last active July 8, 2024 08:04
Show Gist options
  • Save vaaas/db7c4686919bc1f90bd920248df5f49e to your computer and use it in GitHub Desktop.
Save vaaas/db7c4686919bc1f90bd920248df5f49e to your computer and use it in GitHub Desktop.
list search
const $ = x => document.querySelector(x)
const $$ = x => [...document.querySelectorAll(x)]
const nonempty = x => x.length > 0
const lower_case = x => x.toLowerCase()
const includes = y => x => x.includes(y)
const multiple_included = xs => x => xs.some(includes(x))
const show = x => x.style.display = ""
const hide = x => x.style.display = "none"
const head = x => x[0]
const last = x => x[x.length - 1]
const to_words = x => x.replace(/\W/g, " ")
.split(" ")
.filter(nonempty)
.map(lower_case)
let words = $$("li").map(x => [x, to_words(x.innerText)])
let shown = words
let previous_input = ""
function* search_generator(query, words)
{ for (let x of words)
if (query.every (multiple_included (last (x))))
yield x }
function on_input(e)
{ if (!this.value)
{ words.forEach(x => show(head(x)))
shown = words
previous_input = this.value
return }
shown.forEach(x => hide(head(x)))
let new_shown = []
for (let x of search_generator(to_words(this.value), shown))
{ show(head(x))
new_shown.push(x) }
shown = new_shown }
function main()
{ const current = $("input")
const clone = current.cloneNode()
current.parentElement.replaceChild(clone, current)
clone.oninput = on_input }
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment