Last active
March 6, 2023 16:13
-
-
Save gordonbrander/7fb1cbb71273c5d843c22f986282c0f4 to your computer and use it in GitHub Desktop.
Mut.js - efficient DOM writing via mutation and version flag
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
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