Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Last active March 6, 2023 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gordonbrander/7fb1cbb71273c5d843c22f986282c0f4 to your computer and use it in GitHub Desktop.
Save gordonbrander/7fb1cbb71273c5d843c22f986282c0f4 to your computer and use it in GitHub Desktop.
Mut.js - efficient DOM writing via mutation and version flag
const $version = Symbol('version')
export const version = state => {
if state[$version] == null {
return 0
}
return state[$version]
}
export const markSynced = (following, leading) => {
following[$version] = version(leading)
}
// Bump the state version
export const bump = state => {
let next = version(state) + 1
state[$version] = next
return next
}
// Mutate state with a set function.
// If set function returns true, then state is marked dirty.
export const mut = (set, state, value) => {
let isDirty = !!set(state, value)
if (isDirty) {
bump(state)
}
return isDirty
}
// Write if dirty, using a `write` function.
export const patch = (
write,
element,
state,
send
) => {
if (state[$version] === element[$version]) {
return
}
write(element, state, send)
markSynced(element, state)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment