Skip to content

Instantly share code, notes, and snippets.

@shepherdjerred
Last active May 5, 2024 02:44
Show Gist options
  • Save shepherdjerred/d0f57c99bfd69cf9eada43ca56ffc4e7 to your computer and use it in GitHub Desktop.
Save shepherdjerred/d0f57c99bfd69cf9eada43ca56ffc4e7 to your computer and use it in GitHub Desktop.
type State = {
song: string | undefined; // undefined represents that no song is playing. if you're less lucky, some might use an empty string, e.g. "", instead of undefined
position: number; // how many seconds into the song we're in
duration: number; // how many seconds long the song is
}
// take the state and seek to a particular position
function seek(state: State, position: number): State {
if (position > state.duration) {
throw Error
}
return {
...state,
position
}
}
// initial state
let state = {
song: "Hooked on a Feeling",
duration: 90,
position: 0,
}
// seek to some part of the song
state = seek(state, 10)
// stop the current song
let state = {
song: undefined
// we still have the fields "duration" and "position" on this object even though no song is playing
}
// this will cause an error!
seek(state, 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment