Skip to content

Commit

Permalink
Optimise dict equality check on JavaScript
Browse files Browse the repository at this point in the history
  • Loading branch information
richard-viney committed Nov 13, 2024
1 parent 32f29ae commit b5ffd1f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 13 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
`trim_right` functions, which have been deprecated.
- The `result.nil_error` function has been deprecated in favour of
`result.replace_error`.
- Comparing two `Dict`s for equality has been optimised on the JavaScript
target.

## v0.41.0 - 2024-10-31

Expand Down
31 changes: 18 additions & 13 deletions src/dict.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -792,12 +792,12 @@ function withoutCollision(root, key) {
/**
* @template K,V
* @param {undefined | Node<K,V>} root
* @param {(value:V,key:K)=>void} fn
* @returns {void}
* @param {(value:V,key:K)=>boolean|void} fn
* @returns {boolean}
*/
function forEach(root, fn) {
if (root === undefined) {
return;
return true;
}
const items = root.array;
const size = items.length;
Expand All @@ -807,11 +807,16 @@ function forEach(root, fn) {
continue;
}
if (item.type === ENTRY) {
fn(item.v, item.k);
if (fn(item.v, item.k) === false) {
return false;
}
continue;
}
forEach(item, fn);
if (forEach(item, fn) === false) {
return false;
}
}
return true;
}
/**
* Extra wrapper to keep track of Dict size and clean up the API
Expand Down Expand Up @@ -923,15 +928,18 @@ export default class Dict {
}
/** @type [K,V][] */
const result = [];
this.forEach((v, k) => result.push([k, v]));
this.forEach((v, k) => {
result.push([k, v]);
});
return result;
}
/**
*
* @param {(val:V,key:K)=>void} fn
* @param {(val:V,key:K)=>boolean|void} fn
* @returns {boolean}
*/
forEach(fn) {
forEach(this.root, fn);
return forEach(this.root, fn);
}
hashCode() {
let h = 0;
Expand All @@ -948,10 +956,7 @@ export default class Dict {
if (!(o instanceof Dict) || this.size !== o.size) {
return false;
}
let equal = true;
this.forEach((v, k) => {
equal = equal && isEqual(o.get(k, !v), v);
});
return equal;

return this.forEach((v, k) => isEqual(o.get(k, !v), v));
}
}

0 comments on commit b5ffd1f

Please sign in to comment.