Skip to content

Commit

Permalink
Return number of non empty items
Browse files Browse the repository at this point in the history
  • Loading branch information
jborkowski committed Apr 11, 2024
1 parent 25c754c commit 2bbd3f8
Showing 1 changed file with 12 additions and 9 deletions.
21 changes: 12 additions & 9 deletions src/Specular/Internal/Incremental/MutableArray.js
Original file line number Diff line number Diff line change
@@ -1,42 +1,45 @@
// empty :: forall a. Effect (MutableArray a)
export function empty() {
return [];
return { array: [], nullCnt: 0 };
}

// push :: forall a. EffectFn2 (MutableArray a) a Unit
export function push(self, x) {
self.push(x);
self.array.push(x);
}

// remove :: forall a. EffectFn2 (MutableArray a) a Unit
export function remove(self, x) {
var index = self.indexOf(x);
var index = self.array.indexOf(x);

if (index !== -1) {
self[index] = null;
self.array[index] = null;
self.nullCnt++;
}
}

// length :: forall a. EffectFn1 (MutableArray a) Int
export function length(self) {
return self.length;
return self.array.length - self.nullCnt;
}

// 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];
for (let i = 0; i < self.array.length; i++) {
const value = self.array[i];
if (value !== null) {
fn(value);
if (writeIndex !== i) {
self[writeIndex] = value; // Move non-null values to the left
self.array[writeIndex] = value; // Move non-null values to the left
}
writeIndex++;
}
}

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

0 comments on commit 2bbd3f8

Please sign in to comment.