From a219a8abad1110b3dcf9b7d95291b9a42f6f8880 Mon Sep 17 00:00:00 2001 From: Andrew Harvey Date: Wed, 5 May 2021 20:32:42 +1000 Subject: lib unitsToRanges --- lib/unitsToRanges.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 lib/unitsToRanges.js (limited to 'lib') diff --git a/lib/unitsToRanges.js b/lib/unitsToRanges.js new file mode 100644 index 0000000..8ffd7b0 --- /dev/null +++ b/lib/unitsToRanges.js @@ -0,0 +1,23 @@ +/** + * Convert a list of unit numbers into an addr:flats list. eg. converts 1,2,3,5 into 1-3;5 + * + * @param {Array} units + * + * @returns {string} addr:flats list + */ +module.exports = (units) => { + // adapted from https://stackoverflow.com/a/54973116/6702659 + const unitRanges = units + .slice() + .sort((a, b) => a - b) + .reduce((acc, cur, idx, src) => { + if ((idx > 0) && ((cur - src[idx - 1]) === 1)) { + acc[acc.length - 1][1] = cur + } else { + acc.push([cur]) + } + return acc + }, []) + .map(range => range.join('-')) + return unitRanges.length ? unitRanges.join(';') : null +} -- cgit v1.2.3