Skip to content

Instantly share code, notes, and snippets.

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 pfftdammitchris/40d92e2ec1e73bd504b9c70ec09df499 to your computer and use it in GitHub Desktop.
Save pfftdammitchris/40d92e2ec1e73bd504b9c70ec09df499 to your computer and use it in GitHub Desktop.
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