Created
November 14, 2022 06:31
-
-
Save pfftdammitchris/c530059463d2e0ff943068c6b4f7dc43 to your computer and use it in GitHub Desktop.
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
let state = { backgroundColor: 'white', profiles: [] } | |
let subscribers = [] | |
function notifySubscribers(...args) { | |
subscribers.forEach((fn) => fn(...args)) | |
} | |
function setBackgroundColor(color) { | |
setState((prevState) => ({ | |
...prevState, | |
backgroundColor: color, | |
})) | |
} | |
function setState(newState) { | |
let prevState = state | |
state = | |
typeof newState === 'function' | |
? newState(prevState) | |
: { ...prevState, ...newState } | |
notifySubscribers(prevState, state) | |
} | |
function subscribe(callback) { | |
subscribers.push(callback) | |
} | |
function addProfile(profile) { | |
setState((prevState) => ({ | |
...prevState, | |
profiles: prevState.profiles.concat(profile), | |
})) | |
} | |
subscribe( | |
(function () { | |
function getColor(length) { | |
if (length >= 5 && length <= 8) return 'blue' // Average | |
if (length > 8 && length < 10) return 'orange' // Reaching limit | |
if (length > 10) return 'red' // Limit reached | |
return 'white' // Default | |
} | |
return (prevState, newState) => { | |
const prevProfiles = prevState?.profiles || [] | |
const newProfiles = newState?.profiles || [] | |
if (prevProfiles.length !== newProfiles.length) { | |
setBackgroundColor(getColor(newProfiles.length)) | |
} | |
} | |
})(), | |
) | |
console.log(state.backgroundColor) // 'white' | |
addProfile({ id: 0, name: 'george', gender: 'male' }) | |
addProfile({ id: 1, name: 'sally', gender: 'female' }) | |
addProfile({ id: 2, name: 'kelly', gender: 'female' }) | |
console.log(state.backgroundColor) // 'white' | |
addProfile({ id: 3, name: 'mike', gender: 'male' }) | |
addProfile({ id: 4, name: 'bob', gender: 'male' }) | |
console.log(state.backgroundColor) // 'blue' | |
addProfile({ id: 5, name: 'kevin', gender: 'male' }) | |
addProfile({ id: 6, name: 'henry', gender: 'male' }) | |
console.log(state.backgroundColor) // 'blue' | |
addProfile({ name: 'ronald', gender: 'male' }) | |
addProfile({ name: 'chris', gender: 'male' }) | |
addProfile({ name: 'andy', gender: 'male' }) | |
addProfile({ name: 'luke', gender: 'male' }) | |
console.log(state.backgroundColor) // 'red' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment