parser = ({
parse: function (data) {
return data.reduce((acc, d) => {
const cloned = Object.assign({}, d);
this.rules.forEach((rule) => {
if (d.type === rule.appliesTo) {
const args = rule.target.map((key) => d[key]);
if (d.center) {
}
if (args.every((arg) => arg !== null && arg !== undefined)) {
rule.target.forEach((key) => delete cloned[key]);
Object.assign(cloned, rule.callback(...args));
}
}
});
Object.keys(cloned).map((key) => {
const dashSeparated = camelToDash(key);
if (dashSeparated !== key) {
Object.assign(cloned, { [dashSeparated]: cloned[key] });
delete cloned[key];
}
});
acc.push(cloned);
return acc;
}, []);
},
rules: [
{
appliesTo: "line",
target: ["points"],
callback: function (points) {
return {
x1: points[0].x,
y1: points[0].y,
x2: points[1].x,
y2: points[1].y
};
}
},
{
appliesTo: "line",
target: ["from", "length", "slope"],
callback: function (from, length, slope) {
return {
x1: from.x,
y1: from.y,
x2: from.x + length * Math.cos(slope),
y2: from.y + length * Math.sin(slope)
};
}
},
{
appliesTo: "line",
target: ["from", "length", "angle"],
callback: function (from, length, angle) {
return {
x1: from.x,
y1: from.y,
x2: from.x + length * Math.cos((angle * Math.PI) / 180),
y2: from.y + length * Math.sin((angle * Math.PI) / 180)
};
}
},
{
appliesTo: "line",
target: ["center", "length", "slope"],
callback: function (center, length, slope) {
return {
x1: center.x - 0.5 * length * Math.cos(slope),
y1: center.y - 0.5 * length * Math.sin(slope),
x2: center.x + 0.5 * length * Math.cos(slope),
y2: center.y + 0.5 * length * Math.sin(slope)
};
}
},
{
appliesTo: "line",
target: ["center", "length", "angle"],
callback: function (center, length, angle) {
return {
x1: center.x - 0.5 * length * Math.cos((angle * Math.PI) / 180),
y1: center.y - 0.5 * length * Math.sin((angle * Math.PI) / 180),
x2: center.x + 0.5 * length * Math.cos((angle * Math.PI) / 180),
y2: center.y + 0.5 * length * Math.sin((angle * Math.PI) / 180)
};
}
},
{
appliesTo: "polygon",
target: ["points"],
callback: function (points) {
return {
points: points.map((p) => [p.x, p.y].join(",")).join(" ")
};
}
},
{
appliesTo: "text",
target: ["rotate", "x", "y"],
callback: function (rotate, x, y) {
return {
transform: `rotate(${rotate}, ${x}, ${y})`,
x,
y
};
}
},
{
appliesTo: "path",
target: ["points", "draw"],
callback: function (points, draw) {
return {
d: draw(d3.path(), points)
};
}
}
]
})