SampleLookup
by whelkaholism
HTML
<script src="https://cdn.cfront-cloud.co.uk/scripts/7/cf.app.linq.js"></script>
JavaScript
(function() {
var d;
_init();
function SampleLookup(dataset)
{
var _this = this;
this.ds = dataset;
this.raw = {};
this.fields = dataset.Fields;
this.fieldIndexes = {};
this.sampleLength = dataset.Data[0].w;
this.valuesPerSample = dataset.Fields.length;
var tlist = [];
var tmap = {};
//
this.fields.forEach(function(x, i) { _this.fieldIndexes[x] = i; });
dataset.Data.forEach(function(x) {
var sts = x.dt.dt;
var ts = new Date(sts).getTime();
tlist.push(ts);
tmap[ts] = sts;
_this.raw[sts] = x.vals || x.val;
});
this.createEmptySample = function()
{
var res = [];
for(var i = 0; i < _this.valuesPerSample; i++)
res.push(null);
return res;
};
this.find = function(ts)
{
ts = new Date(ts).getTime();
var res = null;
var lenms = this.sampleLength * 1000;
if(ts > tlist[0] - lenms && ts <= tlist[tlist.length - 1])
{
var match = tlist.where(function(x) {
return (ts > (x - lenms)) && (ts <= x);
}).first();
res = match ? _this.raw[tmap[match]] : null;
}
return res;
};
this.get = function(ts)
{
return this.find(ts) || this.createEmptySample();
};
this.createSampleSet = function(tsstart, tsend)
{
var res = {
times: [],
samples: []
};
this.doEvery(tsstart, tsend, this.sampleLength * 1000, function(t, sample) {
sample = sample || _this.createEmptySample();
res.times.push(t);
res.samples.push(sample);
});
return res;
};
this.doEvery = function(tsstart, tsend, secs, cb)
{
tsstart = new Date(tsstart).getTime();
tsend = new Date(tsend).getTime();
for(var t = tsstart; t <= tsend; t += secs)
{
cb(t,...