From c1729c0de63b0f817e374ff1bf69caae61a7573d Mon Sep 17 00:00:00 2001 From: Thomas Vargiu Date: Thu, 9 May 2024 17:04:24 +0200 Subject: [PATCH] improve glucose-get-last performance --- lib/glucose-get-last.js | 44 +++++++++++++++++++++++++---------------- 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/lib/glucose-get-last.js b/lib/glucose-get-last.js index bca3bfbc0..8f74654f3 100644 --- a/lib/glucose-get-last.js +++ b/lib/glucose-get-last.js @@ -1,20 +1,11 @@ + function getDateFromEntry(entry) { return entry.date || Date.parse(entry.display_time) || Date.parse(entry.dateString); } var getLastGlucose = function (data) { - data = data.filter(function(obj) { - return obj.glucose || obj.sgv; - }).map(function prepGlucose (obj) { - //Support the NS sgv field to avoid having to convert in a custom way - obj.glucose = obj.glucose || obj.sgv; - if ( obj.glucose !== null ) { - return obj; - } - }); - - var now = data[0]; - var now_date = getDateFromEntry(now); + var now = undefined; + var now_date = undefined; var change; var last_deltas = []; var short_deltas = []; @@ -22,15 +13,29 @@ var getLastGlucose = function (data) { var last_cal = 0; //console.error(now.glucose); - for (var i=1; i < data.length; i++) { + for (var i=0; i < data.length; i++) { // if we come across a cal record, don't process any older SGVs - if (typeof data[i] !== 'undefined' && data[i].type === "cal") { + var item = data[i]; + item.glucose = item.glucose || item.sgv; + if (!item.glucose) { + continue; + } + if (typeof now === 'undefined') { + now = item; + now_date = getDateFromEntry(item); + continue; + } + if (typeof now === 'undefined') { + continue; + } + if (item.type === "cal") { last_cal = i; break; } + // only use data from the same device as the most recent BG data point - if (typeof data[i] !== 'undefined' && data[i].glucose > 38 && data[i].device === now.device) { - var then = data[i]; + if (item.glucose > 38 && item.device === now.device) { + var then = item; var then_date = getDateFromEntry(then); var avgdelta = 0; var minutesago; @@ -39,7 +44,10 @@ var getLastGlucose = function (data) { // multiply by 5 to get the same units as delta, i.e. mg/dL/5m change = now.glucose - then.glucose; avgdelta = change/minutesago * 5; - } else { console.error("Error: date field not found: cannot calculate avgdelta"); } + } else { + console.error("Error: date field not found: cannot calculate avgdelta"); + continue; + } //if (i < 5) { //console.error(then.glucose, minutesago, avgdelta); //} @@ -60,6 +68,8 @@ var getLastGlucose = function (data) { // long_deltas are calculated from everything ~20-40 minutes ago } else if (17.5 < minutesago && minutesago < 42.5) { long_deltas.push(avgdelta); + } else if (minutesago > 42.5) { + break; } } }