'use strict'; const LatLon = require('geodesy').LatLonSpherical; /** * Compare date2 and date2 * * @param {*} date1 * @param {*} date2 * @returns value > 0: date2 > date1 */ function dateDiff(date1, date2) { return date2.getTime() - date1.getTime(); } function last(array) { return array && array.length ? array[array.length - 1] : null; } function isEmpty(obj) { for (let x in obj) { if (Object.prototype.hasOwnProperty.call(obj, x)) { return false; } else { return true; } } return true; } function isDateTime(obj) { return (Object.prototype.toString.call(obj) === '[object Date]'); } /** * Copy an Original Array or an Object without impacting on original data * Ref: https://stackoverflow.com/questions/36124363/deep-copying-objects-in-angular */ function clone(data) { let node; if (Array.isArray(data)) { node = data.length > 0 ? data.slice(0) : []; node.forEach((e, i) => { if ((typeof e === 'object' && e != {}) || (Array.isArray(e) && e.length > 0)) node[i] = clone(e); }); } else if (data && typeof data === 'object') { node = data instanceof Date ? new Date(data.valueOf()) : Object.assign({}, data); Object.keys(node).forEach((key) => { if ((typeof node[key] === 'object' && node[key] != {}) || (Array.isArray(node[key]) && node[key].length > 0)) node[key] = clone(node[key]); }); } else node = data; return node; } /** * Distance between 2 latlong points * @param {*} latLng fisrt point [lat, lon] * @param {*} latLng2 second point [lat, lon] */ function distance(latLng, latLng2) { if (!(latLng && latLng.length) || !(latLng2 && latLng2.length)) return 0; return (new LatLon(latLng[0], latLng[1])).distanceTo(new LatLon(latLng2[0], latLng2[1])); } module.exports = { dateDiff, last, isEmpty, isDateTime, clone, distance };