JSFiddle - React, Tailwind, and code Playground

by Johan Vandeplas

JavaScript

function process(a){
    var s=null, o= [];
    for (var i=0; i<a.length; i++) {
        if(s=== null) {
            if(a.length < i+1 || a[i+1] !== a[i]+1){
                o.push(a[i]);
            } else {
                s=a[i];
            }
        } else {
            if(a.length < i+1 || a[i+1] !== a[i]+1){
                o.push(s+ " to " + a[i]);
                s=null;            
            }
        }
    }
    return '{' + o.join(';') + '}';
}

var tests = [
    [1,2,3,4,5,6,7,9],
    [1,2,3,4,5,6,7,12,13,14,15,16,20],
    [1,2,3,4,5,6,7,12,13,14,15,16,20,21,22,23],
    [1,2,3,4,5,6,7,120,13,14,15,16,2890,21,22,23]
];

// setup
for (var i = 0; i < tests.length; i++) {
    console.log('Test ' + i + ' : ' + process(tests[i]));
}