Skip to content

Instantly share code, notes, and snippets.

@uhyo
Created July 16, 2020 04:29
Show Gist options
  • Save uhyo/e54a61726acca2af6d29b2150e082577 to your computer and use it in GitHub Desktop.
Save uhyo/e54a61726acca2af6d29b2150e082577 to your computer and use it in GitHub Desktop.
function offsetRange(arr) {
return (
arr.map(v => [v, v+1])
.join(",")
.replace(/(,\d+)\1/g, "-")
.replace(/(-+,)\d+/g, (_, s) => "-" + (s.length))
.replace(/(,\d+),\d+/g, (_, s) => `${s}-1`)
.split(",")
.map((v) => {
const [offset, range] = v.split("-");
return ({offset, range})
})
);
}
console.log(offsetRange([1, 2, 3, 5, 6, 9, 10]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment