Created
February 10, 2021 19:15
-
-
Save DogPawHat/1322e4d5ef8c843fc56982d300deed01 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
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
// Available variables: | |
// - Machine | |
// - interpret | |
// - assign | |
// - send | |
// - sendParent | |
// - spawn | |
// - raise | |
// - actions | |
// - XState (all XState exports) | |
class Interval { | |
constructor(startTime, endTime) { | |
this.startTime = startTime; | |
this.endTime = endTime; | |
} | |
isAfter(time) { | |
return time.valueOf() > this.endTime.valueOf(); | |
} | |
isBefore(time) { | |
return time.valueOf() < this.startTime.valueOf() | |
} | |
contains(time) { | |
return !this.isAfter(time) && !this.isBefore(time) | |
} | |
} | |
const startTime = new Date('2021-02-11T12:00:00.000Z') | |
const endTime = new Date("2021-02-11T11:30:00.000Z") | |
const now = new Date(); | |
const initInterval = new Interval(startTime, endTime); | |
console.log(endTime.toISOString()) | |
console.log(now.toISOString()) | |
console.log(initInterval.isAfter(now)) | |
const assigner = { | |
time: (ctx) => new Date() | |
} | |
const stateTransitions = [ | |
{ | |
target: 'before', | |
cond: { | |
type: 'isBefore', | |
}, | |
actions: assigner | |
}, | |
{ | |
target: 'live', | |
cond: { | |
type: 'contains', | |
}, | |
actions: assigner | |
}, | |
{ | |
target: 'after', | |
cond: { | |
type: 'isAfter', | |
}, | |
actions: assigner | |
}, | |
{ target: 'error' }, | |
]; | |
const timeState = { | |
after: { | |
LIVE_TIME_DELAY: stateTransitions, | |
}, | |
}; | |
const liveStateMachine = | |
Machine( | |
{ | |
id: 'liveState', | |
initial: 'unknown', | |
context: { | |
interval: initInterval, | |
time: now, | |
}, | |
states: { | |
unknown: { | |
on: { | |
'': stateTransitions, | |
}, | |
}, | |
before: { | |
...timeState, | |
}, | |
after: { | |
...timeState, | |
}, | |
live: { | |
...timeState, | |
}, | |
error: { | |
type: 'final', | |
}, | |
}, | |
}, | |
{ | |
delays: { LIVE_TIME_DELAY: 30000 }, | |
guards: { | |
isBefore: (ctx) => ctx.interval.isBefore(ctx.time), | |
isAfter: (ctx) => ctx.interval.isBefore(ctx.time), | |
contains: (ctx) => ctx.interval.contains(ctx.time), | |
}, | |
}, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment