Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/** @jsxImportSource https://esm.sh/react */
export function SparklineSVG({ strokeWidth, data, height, width, fill, stroke }) {
const padding = 2;
const xMargin = 25;
// Calculate the min and max values for x and y
const xValues = data.map((d, i) => i);
const yValues = data.map(d => d);
const xMin = Math.min(...xValues);
const xMax = Math.max(...xValues);
const yMin = Math.min(...yValues);
const yMax = Math.max(...yValues);
const yMid = (yMin + yMax) / 2;
// Scaling functions
const xScale = x => ((x - xMin) / (xMax - xMin)) * (width - 2 * padding) + padding + xMargin;
const yScale = y => height - padding - ((y - yMin) / (yMax - yMin)) * (height - 2 * padding);
return (
<svg width={width} height={height}>
{/* Y Axis Labels */}
{[yMin, yMid, yMax].map((y, index) => (
<text
key={index}
y={yScale(y)}
fontSize="10"
textAnchor="start"
dominantBaseline={index === 2 ? "hanging" : index === 0 ? "bottom" : "top"}
>
{Math.round(y / 100) / 10}s
</text>
))}
{/* Line Path */}
<polyline
fill={fill}
stroke={stroke}
strokeWidth={strokeWidth}
points={data.map((d, i) => `${xScale(i)},${yScale(d)}`).join(" ")}
/>
</svg>
);
}
June 11, 2024