Skip to content

Instantly share code, notes, and snippets.

@chapmanjacobd

chapmanjacobd/swimming.ts

Last active Aug 13, 2020
Embed
What would you like to do?
swimlanes.io to XState FSM
swimlaneToXState(`
idle -> loading: fetch
loading -> success: resolve
loading -> failure: reject
failure -> loading: retry
`);
export function swimlaneToXState(swimlane: string) {
const initial = swimlane.split("->")[0].trim();
const states = swimlane
.trim()
.split("\n")
.reduce((n, l) => {
const from = l.split("->")[0].trim();
const to = l.split("->")[1].split(":")[0].trim();
const path = l
.split("->")[1]
.split(":")[1]
.trim()
.toUpperCase()
.replace(/\s/g, "_")
.replace(/\-/g, "_")
.replace(/\./g, "_")
.replace(/\,/g, "_")
.replace(/\//g, "_")
.replace(/\(/g, "_")
.replace(/\)/g, "_");
if (n[from])
return {
...n,
[from]: {
on: {
...n[from].on,
[path]: to,
},
},
...(!n[to] && { [to]: {} }),
};
return {
...n,
[from]: {
on: {
[path]: to,
},
},
...(!n[to] && { [to]: {} }),
};
}, {});
const o = `
Machine({
initial: "${initial}",
states:
${strObj(states)},
});
`;
console.log(o);
return o;
}
const strObj = (obj_from_json) => {
// In case of an array we'll stringify all objects.
if (Array.isArray(obj_from_json)) {
return `[${obj_from_json.map((obj) => `${strObj(obj)}`).join(",")}]`;
}
// not an object, stringify using native function
if (
typeof obj_from_json !== "object" ||
obj_from_json instanceof Date ||
obj_from_json === null
) {
return JSON.stringify(obj_from_json);
}
// Implements recursive object serialization according to JSON spec
// but without quotes around the keys.
return `{
${Object.keys(obj_from_json)
.map((key) => ` ${key}: ${strObj(obj_from_json[key])}`)
.join(",")}
}`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment