Forked from calebporzio/reactive-switchboard-utility.js
Last active
April 3, 2023 15:29
-
-
Save AlexVipond/4fd4591deebc643b7e3bd9a5a9194599 to your computer and use it in GitHub Desktop.
This file contains 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
import { reactive, effectScope, watchEffect } from 'vue' | |
function switchboard(value) { | |
let lookup = {} | |
let scope = effectScope() | |
let current | |
let get = () => current | |
let set = (newValue) => { | |
if (newValue === current) return | |
if (current !== undefined) lookup[current].state = false | |
current = newValue | |
if (lookup[newValue] === undefined) { | |
scope.run(() => { | |
lookup[newValue] = reactive({ state: true }) | |
}) | |
} else { | |
lookup[newValue].state = true | |
} | |
} | |
let is = (comparisonValue) => { | |
if (lookup[comparisonValue] === undefined) { | |
scope.run(() => { | |
lookup[comparisonValue] = reactive({ state: false }) | |
}) | |
return lookup[comparisonValue].state | |
} | |
return !! lookup[comparisonValue].state | |
} | |
value === undefined || set(value) | |
let scopedWatchEffect = (...params) => { | |
scope.run(() => { | |
watchEffect(...params) | |
}) | |
} | |
return { get, set, is, watchEffect: scopedWatchEffect, stop: scope.stop } | |
} | |
function switchboardSet(value) { | |
let lookup = {} | |
let scope = effectScope() | |
let current = [] | |
let all = () => current | |
let add = (newValue) => { | |
if (current.includes(newValue)) return | |
current.push(newValue) | |
if (lookup[newValue] === undefined) { | |
scope.run(() => { | |
lookup[newValue] = reactive({ state: true }) | |
}) | |
} else { | |
lookup[newValue].state = true | |
} | |
} | |
let remove = (newValue) => { | |
if (! current.includes(newValue)) return | |
current = current.filter(i => i !== newValue) | |
if (lookup[newValue] === undefined) { | |
scope.run(() => { | |
lookup[newValue] = reactive({ state: false }) | |
}) | |
} else { | |
lookup[newValue].state = false | |
} | |
} | |
let has = (comparisonValue) => { | |
if (lookup[comparisonValue] === undefined) { | |
scope.run(() => { | |
lookup[comparisonValue] = reactive({ state: false }) | |
}) | |
return false | |
} | |
return !! lookup[comparisonValue].state | |
} | |
let clear = () => { | |
for (let i = 0; i < current.length; i++) { | |
let key = current[i] | |
delete current[i] | |
lookup[key].state = false | |
} | |
current = current.filter(i => i) | |
} | |
let scopedWatchEffect = (...params) => { | |
scope.run(() => { | |
watchEffect(...params) | |
}) | |
}s | |
value === undefined || value.forEach(i => add(i)) | |
return { all, add, remove, has, clear, watchEffect: scopedWatchEffect, stop: scope.stop } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment