Skip to content

Instantly share code, notes, and snippets.

@elclanrs
Last active August 29, 2015 13:57
Show Gist options
  • Save elclanrs/9641497 to your computer and use it in GitHub Desktop.
Save elclanrs/9641497 to your computer and use it in GitHub Desktop.
Minimal library for functional DOM manipulation
queryDoc \ul
|> children
|> parent
|> mapQ (.textContent)

query body, 'li a'
|> parents
|> siblings
|> mapQ (.style)
{map, unique, flatten} = require \prelude-ls
# Helpers
#
joinF = (f, g) -->
->
(f ...) ++ g ...
maybe = (pred, f, x) -->
| pred x => f x
| _ => x
isArrayLike = (x) ->
typeof x is \object and x.length
toArray = (x) ->
Array::slice.call x
# Query
#
# query :: Node -> String -> [Node]
query = (el, sel) -->
toArray el.querySelectorAll sel
queryDoc = query document
# mapQ :: (Node -> Node) -> [Node] -> [Node]
mapQ = (f, xs) -->
xs |> map (maybe isArrayLike, toArray) . f
|> flatten
|> unique
# iter :: String -> Node -> [Node]
iter = (prop, x) -->
res = []
while x = x[prop]
res.push x
res
# slice :: Number -> Number -> [Node]
slice = (i, j, xs) -->
xs.slice i, j ? xs.length
parent = mapQ (.parentNode)
parents = mapQ iter (.parentNode)
children = mapQ (.children)
next = mapQ (.nextElementSibling)
prev = mapQ (.previousElementSibling)
nextAll = mapQ iter \nextElementSibling
prevAll = mapQ iter \previousElementSibling
siblings = (xs) ->
prev = iter \previousElementSibling
next = iter \nextElementSibling
xs |> mapQ joinF prev, next
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment