Skip to content

Commit

Permalink
Add deepEqual utility function for comparing (#96)
Browse files Browse the repository at this point in the history
objects
  • Loading branch information
iPurpl3x authored Nov 15, 2023
1 parent ea4621a commit 78c4b21
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
6 changes: 5 additions & 1 deletion js/src/forum/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import ComposerState from 'flarum/forum/states/ComposerState';
import fillRelationship from './utils/fillRelationship';
import DraftsListState from './states/DraftsListState';
import app from 'flarum/forum/app';
import deepEqual from './utils/deepEqual';

export * from './components';
export * from './models';
Expand Down Expand Up @@ -61,7 +62,10 @@ app.initializers.add('fof-drafts', () => {
const getData = (field) => (field === 'content' ? this.fields.content() : data[field]) || '';

for (const field of fields) {
if ((!draft && getData(field)) || (draft && getData(field) != draft.data.attributes[field])) {
const fieldValue = getData(field);
const draftFieldValue = draft && draft.data.attributes[field];

if ((!draft && fieldValue) || (draft && !deepEqual(fieldValue, draftFieldValue))) {
return true;
}
}
Expand Down
20 changes: 20 additions & 0 deletions js/src/forum/utils/deepEqual.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Deep comparison function
export default function deepEqual(obj1, obj2) {
if (obj1 === obj2) {
return true;
}
if (typeof obj1 !== 'object' || typeof obj2 !== 'object' || obj1 == null || obj2 == null) {
return false;
}
let keys1 = Object.keys(obj1);
let keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) {
return false;
}
for (let key of keys1) {
if (!keys2.includes(key) || !deepEqual(obj1[key], obj2[key])) {
return false;
}
}
return true;
}

0 comments on commit 78c4b21

Please sign in to comment.