Skip to content

Commit

Permalink
Remove iterateNodeValues closure (#202)
Browse files Browse the repository at this point in the history
* Remove iterateNodeValues closure

* iterateNodeValues: Don't use filter for performance reason
  • Loading branch information
twoeths authored Oct 1, 2021
1 parent ceb636a commit b4463f8
Showing 1 changed file with 25 additions and 20 deletions.
45 changes: 25 additions & 20 deletions packages/persistent-ts/src/Vector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,16 +275,7 @@ export class PersistentVector<T> implements Iterable<T> {
*/
toArray(): T[] {
const values: T[] = [];
function iterateNodeValues(node: INode<T>, level: number): void {
if (level <= 0) {
values.push(...(node as ILeaf<T>).array.filter((i) => i != null));
} else {
for (const child of (node as IBranch<T>).array.filter((i) => i != null)) {
iterateNodeValues(child as INode<T>, level - BIT_WIDTH);
}
}
}
iterateNodeValues(this.root, this.shift);
iterateNodeValues(this.root, this.shift, values);
values.push(...this.tail.slice(0, this.getTailLength()));
return values;
}
Expand Down Expand Up @@ -542,16 +533,7 @@ export class TransientVector<T> implements Iterable<T> {
*/
toArray(): T[] {
const values: T[] = [];
function iterateNodeValues(node: INode<T>, level: number): void {
if (level <= 0) {
values.push(...(node as ILeaf<T>).array.filter((i) => i != null));
} else {
for (const child of (node as IBranch<T>).array.filter((i) => i != null)) {
iterateNodeValues(child as INode<T>, level - BIT_WIDTH);
}
}
}
iterateNodeValues(this.root, this.shift);
iterateNodeValues(this.root, this.shift, values);
values.push(...this.tail.slice(0, this.getTailLength()));
return values;
}
Expand All @@ -574,3 +556,26 @@ export class TransientVector<T> implements Iterable<T> {
return this.length < BRANCH_SIZE ? 0 : ((this.length - 1) >>> BIT_WIDTH) << BIT_WIDTH;
}
}

/**
* Recursively loop through the nodes and push node to values array.
*/
function iterateNodeValues<T>(node: INode<T>, level: number, values: T[]): void {
if (!node) {
return;
}

if (level <= 0) {
for (const t of (node as ILeaf<T>).array) {
if (t != null) {
values.push(t);
}
}
} else {
for (const child of (node as IBranch<T>).array) {
if (child !== null) {
iterateNodeValues(child as INode<T>, level - BIT_WIDTH, values);
}
}
}
}

0 comments on commit b4463f8

Please sign in to comment.