From d2b9359fee924bbe07e78b6c83d575d0978836dc Mon Sep 17 00:00:00 2001 From: Christian Weimann Date: Sun, 9 Feb 2025 08:02:41 +0100 Subject: [PATCH] feat(helpers): add debounceFunction and distanceBetween --- utils/helpers.js | 51 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 utils/helpers.js diff --git a/utils/helpers.js b/utils/helpers.js new file mode 100644 index 0000000..f9d74c1 --- /dev/null +++ b/utils/helpers.js @@ -0,0 +1,51 @@ +// Load dependencies +const { TimerMgr } = require('../utils'); +const tm = new TimerMgr(); + +function debounceFunction(id, debounceTimeout, func, params) { + console.warn('debounce', id, debounceTimeout); + + timeout = time.ZonedDateTime.now().plusNanos(debounceTimeout * 1000000); + + if (tm.hasTimer(id) && tm.isActive(id)) { + log.info(`Skip evaluation of function with id ${id} as function is already running. Reschedule timer`); + tm.reschedule(id, timeout); + } else { + log.info(`Create timer to execute function ${id}`); + if (tm.hasTimer(id)) { + tm.cancel(id); + } + tm.create(id, timeout, func, params); + } +} + +function distanceBetween(locationA, locationB) { + const [lat1, lon1] = locationA.split(',').map(Number); + const [lat2, lon2] = locationB.split(',').map(Number); + + const toRadians = (degree) => degree * (Math.PI / 180); + + const radLat1 = toRadians(lat1); + const radLon1 = toRadians(lon1); + const radLat2 = toRadians(lat2); + const radLon2 = toRadians(lon2); + + if (lat1 === lat2 && lon1 === lon2) return '0 m'; + + const dlon = radLon2 - radLon1; + const dlat = radLat2 - radLat1; + + const a = Math.pow(Math.sin(dlat / 2), 2) + + Math.cos(radLat1) * Math.cos(radLat2) + * Math.pow(Math.sin(dlon / 2), 2); + + const c = 2 * Math.asin(Math.sqrt(a)); + const r = 6371000; // Radius of earth in meters + + return `${(c * r).toFixed()} m`; +} + +module.exports = { + debounceFunction, + distanceBetween +}; \ No newline at end of file