Created
August 8, 2019 22:32
-
-
Save GoodNovember/c09fa2052ab8fd06addf47a6bbc630d0 to your computer and use it in GitHub Desktop.
Kinda useful getter setter and subscriber all in one.
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
| export const makeGetSet = ({ initialValue, skipInitialCall = false }) => { | |
| let value = initialValue | |
| let subscribers = new Set() | |
| const getValue = () => value | |
| const setValue = newValue => { | |
| value = newValue | |
| subscribers.forEach(sub => { sub(newValue) }) | |
| } | |
| const subscribe = callback => { | |
| if (subscribers.has(callback) === false) { | |
| subscribers.add(callback) | |
| if (skipInitialCall === false) { | |
| callback(initialValue) | |
| } | |
| } | |
| return () => { | |
| subscribers.delete(callback) | |
| } | |
| } | |
| return [getValue, setValue, subscribe] | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment