So, I have this function which performs some calculations and returns 6 values in an object. But on page A, I only want it to calculate and return the first 3 values. On page B, I want it to return all the values.
I want to avoid using the string comparison and wanted to make use of currying.
The values being calculated are dependent on each other. For example, value3 uses value2 to calculate. value4 uses value1 to calculate.
export const transformMeasurementStats = (data: Data[]) => {
const result = data.map((item) => {
if (item.measurementSamples) {
//All these calculations are dependent on one another.
// e.g. value3 uses value2 to calculate and so on.
const value1 = //some calculation
const value2 = //some calculation
const value3 = //some calculation
const value4 = //some calculation
const value5 = //some calculation
const value6 = //some calculation
return { value1, value2, value3, value4, value5, value6};
}
});
return result;
};
If you're sure you want to implement it using currying, below could be one way of making it work:
const transformMeasurementStats = (num) => (data) => {
const result = data.map((item) => {
if (item.measurementSamples) {
//All these calculations are dependent on one another.
// e.g. value3 uses value2 to calculate and so on.
const value1 = "1";
const value2 = "2";
const value3 = "3";
const value4 = "4";
const value5 = "5";
const value6 = "6";
return num === 3
? { value1, value2, value3 }
: { value1, value2, value3, value4, value5, value6 };
}
});
return result;
};
const data = [{ measurementSamples: true }];
console.log(transformMeasurementStats(3)(data));
console.log(transformMeasurementStats()(data));
Dynamically returning a certain number of values (or all, if no value of num provided):
Could use Map instead of array if keys matter.
const transformMeasurementStats = (num) => (data) => {
const result = data.map((item) => {
if (item.measurementSamples) {
//All these calculations are dependent on one another.
// e.g. value3 uses value2 to calculate and so on.
const values = [];
values[0] = "1";
values[1] = "2";
values[2] = "3";
values[3] = "4";
values[4] = "5";
values[5] = "6";
const resultValues = {};
num = num ? num : values.length - 1;
for (let i = 1; i <= num; i++) {
resultValues[`value${i}`] = values[i];
}
return resultValues;
}
});
return result;
};
const data = [{ measurementSamples: true }];
// return all 6 values
console.log(transformMeasurementStats()(data));
// return
const getFirst3Values = transformMeasurementStats(3);
console.log(getFirst3Values(data));
Hope it helps.