Skip to content

Instantly share code, notes, and snippets.

@rlamacraft
Created December 26, 2023 11:31
Show Gist options
  • Save rlamacraft/49359fec6c44c8e645db29db1abea3c9 to your computer and use it in GitHub Desktop.
Save rlamacraft/49359fec6c44c8e645db29db1abea3c9 to your computer and use it in GitHub Desktop.
Slices of arrays in JavaScript
function* makeSlices(delim, array) {
let offset = 0;
let length = 0;
for(let x of array) {
if (x === delim) {
yield {
offset,
length,
get: (i) => {
if (i < 0 || i > length) { throw "OutOfBounds"; }
return array[offset + i];
},
set: (i, newValue) => {
if (i < 0 || i > length) { throw "OutOfBounds"; }
array[offset + i] = newValue;
}
};
offset = offset + length + 1;
length = 0;
} else {
length++;
}
}
yield {
offset,
length,
get: (i) => {
if (i < 0 || i > length) { throw "OutOfBounds"; }
return array[offset + i];
},
set: (i, newValue) => {
if (i < 0 || i > length) { throw "OutOfBounds"; }
array[offset + i] = newValue;
}
};
}
// increment every number the follows a 0
const array = [1, 0, 1, 2, 0, 3];
const iterator = makeSlices(0, array);
iterator.next();
for(let x of iterator) {
x.set(0, x.get(0) + 1);
}
console.log(array);
// capitalise the first letter of each word
const string = "hello world".split("");
for(let substr of makeSlices(" ", string)) {
substr.set(0, substr.get(0).toUpperCase());
}
console.log(string.join(""));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment