Skip to content

Commit

Permalink
Refactored based on suggestions in PR
Browse files Browse the repository at this point in the history
Remove the use of `JSON.stringify` for comparing equality; instead use `Array.prototype.some` to check equality
  • Loading branch information
ptshih committed Jun 3, 2018
1 parent 2f4fe33 commit 942d983
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 29 deletions.
2 changes: 1 addition & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export const normalize = (input, schema) => {

const entities = {};
const addEntity = addEntities(entities);
const visitedEntities = {};
const visitedEntities = [];

const result = visit(input, input, null, schema, addEntity, visitedEntities);
return { entities, result };
Expand Down
30 changes: 2 additions & 28 deletions src/schemas/Entity.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,31 +33,6 @@ export default class EntitySchema {
return this._idAttribute;
}

stringifySafe(input) {
function replacer() {
const stack = [];
const keys = [];

return (key, value) => {
if (stack.length > 0) {
const thisPos = stack.indexOf(this);
~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
if (~stack.indexOf(value)) {
value =
stack[0] === value ? '[Circular ~]' : `[Circular ~.${keys.slice(0, stack.indexOf(value)).join('.')}]`;
}
} else {
stack.push(value);
}

return value;
};
}

return JSON.stringify(input, replacer());
}

define(definition) {
this.schema = Object.keys(definition).reduce((entitySchema, key) => {
const schema = definition[key];
Expand All @@ -74,11 +49,10 @@ export default class EntitySchema {
}

normalize(input, parent, key, visit, addEntity, visitedEntities) {
const stringifiedInput = this.stringifySafe(input);
if (visitedEntities[stringifiedInput]) {
if (visitedEntities.some((entity) => entity === input)) {
return this.getId(input, parent, key);
}
visitedEntities[stringifiedInput] = true;
visitedEntities.push(input);

const processedEntity = this._processStrategy(input, parent, key);
Object.keys(this.schema).forEach((key) => {
Expand Down

0 comments on commit 942d983

Please sign in to comment.