I've a function for load OHCLV data from CSV, at the moment the function grabs all values, and return them, and that's works
What i would like is return only the last N
values.
For example of 1000 values i need only the last 100.
CSV appears like that:
date,open,high,low,close,volume
2013-03-25 16:00:00,76.31,77.5,76.31,77.5,117.65500211
2013-03-25 16:15:00,77.61,77.89,77.1,77.1,36.04786927
[...]
2022-12-22 17:15:00,16646.0,16649.0,16611.0,16623.0,37.57992574
2022-12-22 17:30:00,16626.0,16626.0,16585.0,16608.0,14.26339254
Here's the function
const getOHCLVData = async (path) => {
const res = await fetch(path);
const resp = await res.text();
const cdata = resp.split('\n').slice(1).map((row) => { // slice(1) skip the header
const [date, open, high, low, close, volume] = row.split(',');
return {
time: new Date(`${date}`).getTime() / 1000,
open: open,
high: high,
low: low,
close: close,
volume: volume,
};
});
return cdata;
};
// Call function
getOHCLVData(myfile.csv)
i should try add a new argument to function and do something like that: cdata.lenght - NumberValue
Any suggestion?
CodePudding user response:
This is an amendment to Randy Casburn's comment (new user = low rep = cannot comment).
"change .slice(1)
to .slice(-100)
- negative values pulls from the end of the array. – Randy Casburn
"
You will likely want to add a default variable to your function.
. . . = async (path, nValues=-1)
and alter your slice to be
. . . ('\n').slice(-nValues).map((row)
Note that the default of -1
is the same as .slice(1)
because we use -nValues
This should add the functionality you want without forcing the user to know how many lines they want. You do not want to needlessly limit your function.