Last active
August 13, 2020 09:39
-
-
Save montogeek/dd51382ecc1d57a9ae9f6bad4c0b47df to your computer and use it in GitHub Desktop.
xState states to TypeScript Enums
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
enum Events = { | |
START, | |
END | |
} | |
type EventMap<T> = { | |
[K in keyof T]: { | |
type: K; | |
}; | |
}; | |
type TrainingEvents = EventMap<typeof Events>[keyof EventMap<typeof Events>]; | |
// { type: START } | { type: END } |
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 enum States { | |
DASHBOARD = 'DASHBOARD', | |
OVERVIEW = 'OVERVIEW' | |
} | |
type StatesMap<T> = { | |
[K in keyof T]: { | |
value: K, | |
context: never | |
} | |
} | |
export type TrainingStates = StatesMap<typeof States>[keyof StatesMap<typeof States>]; | |
// { type: DASHBOARD; context: never } | { type: OVERVIEW; context: never } |
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
function getStates(states) { | |
return Object.keys(states).reduce((acc, key) => { | |
if ('states' in states[key]) { | |
const internalStates = states[key].states; | |
return acc.concat( | |
Object.keys(internalStates) | |
.map((internalKey) => { | |
if ('on' in internalStates[internalKey]) { | |
return Object.keys(internalStates[internalKey].on); | |
} | |
return []; | |
}) | |
.filter((e) => e.length !== 0) | |
.concat(getStates(internalStates)) | |
); | |
} else { | |
return []; | |
} | |
}, []); | |
} | |
const states = Array.from( | |
new Set(getStates(trainingMachineConfiguration.states).flat()) | |
); | |
console.log( | |
states.reduce((str, state) => { | |
return `${str} \n ${state} = '${state}',`; | |
}, '') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment