cujojs / jiff

JSON Patch and diff based on rfc6902
Other
627 stars 41 forks source link

Hash function doesn't appear to be working #39

Closed eatinasandwich closed 4 years ago

eatinasandwich commented 4 years ago

I can't seem to get the diff function to use the hash function that I'm passing in. I wanted to override the comparison of dates so that equivalent dates do not produce a patch. Below is the code that I've been trying.

var jiff = require('jiff');
var obj1 = {
    myDate: new Date('2019-1-1'),
    hello: 8
}
var obj2 = {
    myDate: new Date('2019-1-1'),
    hello: 9
}

const hashFunction = (x) => {
  if (x instanceof Date) {
    return x.getTime();
  } else if (Array.isArray(x) || typeof(x) === "object") {
    return JSON.stringify(x);
  } else {
    return x;
  }
}

console.log(jiff.diff(obj1, obj2, hashFunction ));

This always prints "myDate" as part of the patch and putting a break point inside the hash function never hits.

I've tried passing the hash function in this way and also in the options object with no luck. Am I misunderstanding the docs or what the hash function is being used for?

briancavalier commented 4 years ago

Hi @eatinasandwich. As the docs for diff mention, Jiff deals only with JSON values, and JS Date isn't a legal JSON value. So, essentially, the behavior of trying to diff values that aren't legal JSON is undefined.

Similarly to dealing with JS Date in other JSON contexts (such as HTTP request/response bodies), one option is to convert JS Date to an ISO8601 date string. Here's a stackoverflow with more info on using ISO8601 for JSON and JS Date.

I hope that helps!