Skip to content

Commit

Permalink
Move arrayEquals to utils.js
Browse files Browse the repository at this point in the history
  • Loading branch information
willeastcott committed Jun 16, 2024
1 parent 4873da5 commit b27079b
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 26 deletions.
27 changes: 1 addition & 26 deletions src/observer.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,5 @@
import Events from './events.js';

// The Observer implementation assumed this array equality function
// was a member of Array prototype (called 'equals'). This has now
// been moved here instead.
const arrayEquals = (a, b) => {
if (!a || !b) {
return false;
}

const l = a.length;

if (l !== b.length) {
return false;
}

for (let i = 0; i < l; i++) {
if (a[i] instanceof Array && b[i] instanceof Array) {
if (!arrayEquals(a[i], b[i])) {
return false;
}
} else if (a[i] !== b[i]) {
return false;
}
}
return true;
};
import { arrayEquals } from './utils.js';

/**
* The Observer class is used to observe and manage changes to an object. It allows for tracking
Expand Down
41 changes: 41 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* Determines whether two arrays are deeply equal. Two arrays are considered equal if they have the
* same length and corresponding elements are equal. This function also supports nested arrays,
* comparing them recursively.
*
* @param {Array} a - The first array to compare.
* @param {Array} b - The second array to compare.
* @returns {boolean} - Returns `true` if the arrays are deeply equal, otherwise `false`.
*
* @example
* arrayEquals([1, 2, 3], [1, 2, 3]); // true
* arrayEquals([1, 2, 3], [3, 2, 1]); // false
* arrayEquals([1, [2, 3]], [1, [2, 3]]); // true
* arrayEquals([1, [2, 3]], [1, [3, 2]]); // false
* arrayEquals([1, 2, 3], null); // false
* arrayEquals(null, null); // false
*/
const arrayEquals = (a, b) => {
if (!a || !b) {
return false;
}

const l = a.length;

if (l !== b.length) {
return false;
}

for (let i = 0; i < l; i++) {
if (a[i] instanceof Array && b[i] instanceof Array) {
if (!arrayEquals(a[i], b[i])) {
return false;
}
} else if (a[i] !== b[i]) {
return false;
}
}
return true;
};

export { arrayEquals };

0 comments on commit b27079b

Please sign in to comment.