Imagine you have a network request with some incoming json:
type HeartRateDataType = {
timestamp: string;
medianBPM: number;
maxBPM: number;
minBPM: number;
}
// the JSON response will be an array; its type is heartRateDataType[]
This incoming JSON will be used to populate some charting software. It will need to be transformed in a way that makes it usable within the chart software API spec.
If the incoming JSON looks like this:
const heartRateData: HeartRateDataType[] = [{
timestamp: 'new Date()',
medianBPM: 80,
maxBPM: 120,
minBPM: 60,
},
{
timestamp: 'new Date()',
medianBPM: 70,
maxBPM: 110,
minBPM: 50,
}]
And we want to pass into the charting software a structure which looks like:
type MinMaxXYGraphObject = {
name: string;
x: string[];
y: number[];
}
const initialDataShape: MinMaxXYGraphObject[] = [
{ name: 'Median', x: [], y: [] },
{ name: 'Min', x: [], y: [] },
{ name: 'Max', x: [], y: [] },
]
We need to populate the above, with the corresponding data from the incoming JSON.
We want create a helper function that will populate the above like:
const populatedDataShape: MinMaxXYGraphObject[] = [
{
name: 'Median',
x: [
heartRateData[0].timestamp,
heartRateData[1].timestamp,
...etc
],
y: [
heartRateData[0].medianBPM,
heartRateData[1].medianBPM,
...etc
]
},
...etc
]
so we can start with initialDataShape and build upon it:
const populateMinMaxData = (measurements: HeartRateDataType[]): MinMaxXYGraphObject[] =>
measurements.reduce((acc: MinMaxXYGraphObject[], cur: HeartRateDataType) => {
acc[0].x.push(cur.timestamp);
acc[1].x.push(cur.timestamp);
acc[2].x.push(cur.timestamp);
acc[0].y.push(cur.medianBPM);
acc[1].y.push(cur.minBPM);
acc[2].y.push(cur.maxBPM);
return acc;
}, initialDataShape)