Skip to content

Instantly share code, notes, and snippets.

@montogeek
Last active August 13, 2020 09:39
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 montogeek/dd51382ecc1d57a9ae9f6bad4c0b47df to your computer and use it in GitHub Desktop.
Save montogeek/dd51382ecc1d57a9ae9f6bad4c0b47df to your computer and use it in GitHub Desktop.
xState states to TypeScript Enums
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 }
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 }
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