Skip to content

Commit

Permalink
Use swapRemove
Browse files Browse the repository at this point in the history
  • Loading branch information
jborkowski committed Apr 11, 2024
1 parent d9501ce commit ec9b42b
Showing 1 changed file with 11 additions and 15 deletions.
26 changes: 11 additions & 15 deletions src/Specular/Internal/Incremental/MutableArray.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,17 @@ export function push(self, x) {
// remove :: forall a. EffectFn2 (MutableArray a) a Unit
export function remove(self, x) {
var index = self.indexOf(x);

// The removed element is replaced by the last element of the array.
// This does not preserve ordering, but is *O*(1).
if (index !== -1) {
self[index] = null;
var lastIdx = self.length - 1;

if (index !== lastIdx) {
self[index] = self[lastIdx];
}

self.length = lastIdx;
}
}

Expand All @@ -23,20 +32,7 @@ export function length(self) {

// iterate :: forall a. EffectFn2 (MutableArray a) (EffectFn1 a Unit) Unit
export function iterate(self, fn) {
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++;
}
fn(self[i]);
}

// Trim the array to remove null values
self.length = writeIndex;
}

0 comments on commit ec9b42b

Please sign in to comment.