Skip to content

Instantly share code, notes, and snippets.

@habbes
Last active February 6, 2021 20:10
Show Gist options
  • Save habbes/ca34a84a7767dda2532b90018d5aec56 to your computer and use it in GitHub Desktop.
Save habbes/ca34a84a7767dda2532b90018d5aec56 to your computer and use it in GitHub Desktop.
Class that allows you to treat multiple arrays as if they were one huge array. Allows merging arrays without creating new copies
class MegaArray {
constructor() {
this._arrays = [];
this._size = 0;
}
push(item) {
const array = this._getActiveArray();
array.push(item);
this._size++;
}
merge(arrayToMerge) {
this._arrays.push(arrayToMerge);
this._size += arrayToMerge.length;
}
forEach(fn) {
let globalIndex = -1;
console.log('Here');
this._arrays.forEach((array) => {
for (let i = 0; i < array.length; i++) {
globalIndex++;
fn(array[i], globalIndex);
}
});
}
get(index) {
const [array, localIndex] = this._getArrayLocalIndex(index);
return array[localIndex];
}
set(index, value) {
const [array, localIndex] = this._getArrayLocalIndex(index);
return array[localIndex] = value;
}
get length() {
return this._size;
}
_getActiveArray() {
if (this._arrays.length == 0) {
this._arrays.push([]);
}
return this._arrays[this._arrays.length - 1];
}
_getArrayLocalIndex(globalIndex) {
// this can probably be optimized
// TODO: you should perform error-checking to ensure
// index is not out of bounds
let itemsSeen = 0
let array;
let offset = 0;
for (let a = 0; a < this._arrays.length; a++) {
offset = itemsSeen;
itemsSeen += this._arrays[a].length;
if (itemsSeen > globalIndex) {
array = this._arrays[a];
break;
}
}
const localIndex = globalIndex - offset;
return [array, localIndex];
}
}
const array = new MegaArray();
array.push(10);
array.push(20);
array.merge([1, 2, 3, 4]);
array.set(3, 15);
array.push(45);
array.merge([67, 89]);
console.log("Length", array.length);
console.log("Item at index 4", array.get(4));
console.log("Print all items");
array.forEach((item, index) =>
console.log("Element at ", index, "is", item));
// Should print 10, 20, 1, 15, 3, 4, 45, 67, 89
@grafitto
Copy link

grafitto commented Feb 6, 2021

Iyo _getArrayLocalIndex inado nini

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment