encode = (array) => {
// crude array equality function
arrayEquals = (...arr) => {
return arr[0].map(x => {
return JSON.stringify(x);
}).every((x, _, a) => {
return x === a[0];
});
};
let result = [],
count = -1,
len = array.length;
array.reduce((acc, val, i) => {
if (!arrayEquals([acc, val])) {
// if current value differs from last
if (i !== len - 1) {
// push the count and data to the result
result.push([++count, acc]);
count = 0; // reset the count
} else { // last iteration
// push the (n - 1)th value
result.push([++count, acc]);
// now push the nth value
result.push([1, val]);
}
} else {
// if current value equals the last, increment counter and continue
count++;
if (i === len - 1) { // last iteration
// push regardless
count === 1 ? result.push([++count, val]) : result.push([count, val]);
}
}
return val;
}, array[0]);
return result;
};
console.log(encode([1, 1, 2, 2, 3, 3, 4]));
console.log(encode([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]
]));
console.log(encode([
[1, 2, 3],
[1, 2, 3],
[4, 5, 6]
]));
console.log(encode([
[0],
[0],
[1],
[2, 3],
[4, 5, 6],
[],
[]
]));