-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Performance: Improve method for removing items from the mutable array (…
…#98)
- Loading branch information
1 parent
ffa7889
commit 44c06fa
Showing
2 changed files
with
23 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,29 +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.splice(index, 1); | ||
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) { | ||
for (var i = 0; i < self.length; i++) { | ||
fn(self[i]); | ||
let writeIndex = 0; | ||
|
||
// Clean up array using in-place filtering technique | ||
for (let i = 0; i < self.array.length; i++) { | ||
const value = self.array[i]; | ||
if (value !== null) { | ||
fn(value); | ||
if (writeIndex !== i) { | ||
self.array[writeIndex] = value; // Move non-null values to the left | ||
} | ||
writeIndex++; | ||
} | ||
} | ||
|
||
// Trim the array to remove null values | ||
self.array.length = writeIndex; | ||
self.nullCnt = 0; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters