Skip to content

Commit

Permalink
avoid unnecessary iteration over array
Browse files Browse the repository at this point in the history
  • Loading branch information
jborkowski committed Apr 11, 2024
1 parent fe05d00 commit d9501ce
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions src/Specular/Internal/Incremental/MutableArray.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,20 @@ export function length(self) {

// iterate :: forall a. EffectFn2 (MutableArray a) (EffectFn1 a Unit) Unit
export function iterate(self, fn) {
var nullIndices = [];
for (var i = 0; i < self.length; i++) {
if (self[i] === null) {
nullIndices.push(i);
} else {
fn(self[i]);
let writeIndex = 0;

// Clean up array using in-place filtering technique
for (let i = 0; i < self.length; i++) {
const value = self[i];
if (value !== null) {
fn(value);
if (writeIndex !== i) {
self[writeIndex] = value; // Move non-null values to the left
}
writeIndex++;
}
}

for (var i = nullIndices.length - 1; i >= 0; i--) {
self.splice(nullIndices[i], 1);
}
// Trim the array to remove null values
self.length = writeIndex;
}

0 comments on commit d9501ce

Please sign in to comment.