diff options
author | Andrew Harvey <andrew@alantgeo.com.au> | 2021-05-05 20:32:42 +1000 |
---|---|---|
committer | Andrew Harvey <andrew@alantgeo.com.au> | 2021-05-05 20:32:42 +1000 |
commit | a219a8abad1110b3dcf9b7d95291b9a42f6f8880 (patch) | |
tree | 9f606f578e4a3adeef866d167ab9d25e7d34cecc /lib/unitsToRanges.js | |
parent | 71c5ec5950d9cf30cc1200ac0c22432dfd7ac1eb (diff) |
lib unitsToRanges
Diffstat (limited to 'lib/unitsToRanges.js')
-rw-r--r-- | lib/unitsToRanges.js | 23 |
1 files changed, 23 insertions, 0 deletions
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 +} |