Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Returns a sorted string of numbers, grouping consecutive numbers
- * of at least [range] _as_ a range of numbers, e.g. "8-11"
- * @param {Iterable<number>} collection Numbers to sort and group into ranges
- * @param {number} [range=2] min number of consecutive ints that form a range
- * @return {string}
- */
- function getSortedWithRanges(collection, range = 2) {
- // Roughly assert that we have an iterable
- // note: this doesn't validate the elements
- if (!(collection && typeof collection[Symbol.iterator] === 'function')) {
- throw new TypeError(
- `Expected [collection] to be an iterable,` +
- ` saw type "${Object.prototype.toString.call(collection)}"`
- );
- }
- // Assert that the range is a finite number greater than 1
- if (!(Number.isFinite(range) && range > 1)) {
- throw new TypeError(
- `Expected [range] to be a finite number` +
- ` greater than 1, saw "${range}" of type "${typeof range}"`
- );
- }
- const sorted = Array.from(collection).sort((a, b) => a - b);
- // Bail early if we don't have enough elements to create ranges
- if (sorted.length < range) {
- return sorted.join();
- }
- for (let i = 0; i < sorted.length; i++) {
- const n = sorted[i];
- // Count of consecutive numbers found
- // offset by 1 so we skip checking the
- // current number
- let cursor = 1;
- // Scan forward for said consecutive numbers
- while (sorted[i + cursor] === n + cursor) cursor++;
- // If we found consective numbers that satisfy the min range,
- // splice it into the result and remove the elements that make
- // up the range
- if (cursor >= range) {
- sorted.splice(
- // Insertion index
- i,
- // Number of elements to be replaced with the range
- cursor,
- // Range to insert
- `${n}-${n + cursor - 1}`
- );
- } else if (cursor !== 1) {
- // Advance the index by however many consecutive
- // elements were found. We know we can't create a
- // range from them so it's safe to step over
- i += cursor - 1;
- }
- }
- return sorted.join();
- }
- // doit
- // const numbers = new Set([1, 2, 5, 9, 8, 7, 3, 4, 100]);
- // console.log(getSortedWithRanges(numbers, 4));
Add Comment
Please, Sign In to add comment