Skip to content

Instantly share code, notes, and snippets.

@ChocolatMilka
Created January 4, 2022 14:45
Show Gist options
  • Select an option

  • Save ChocolatMilka/6c4f85770d780075c3726b9b7793dd42 to your computer and use it in GitHub Desktop.

Select an option

Save ChocolatMilka/6c4f85770d780075c3726b9b7793dd42 to your computer and use it in GitHub Desktop.
/**
* Permet de générer un nombre à virgule représentant
* la différence entre les valeurs (nombres) contenues entre les deux json.
*
* Plus la différence entre un nombre des deux jsons est importante,
* plus elle est intensifiée par une fonction exponentielle.
*
* Une valeur de sortie de 0.0 est retournée si les deux json sont identiques.
* Dans le cas contraire, une valeur de sortie supérieure à 1.0 est retournée,
* et elle n'a pas de valeur maximale.
*
* Si un json contient une valeur que l'autre ne contient pas,
* la valeur de sortie est intensifiée, mais moins importante.
*
* @type {exports}
*/
module.exports = class {
recurse (jsonA, jsonB) {
this.distance = 0;
this.absent = 0;
if (jsonA != null && jsonB != null) {
for (let x in jsonA) {
if (typeof jsonA[x] === 'object') {
if (typeof jsonB[x] === 'object') {
this.recurse(jsonA[x], jsonB[x]);
} else {
this.absent++;
}
continue;
}
if (!jsonB.hasOwnProperty(x)) {
this.absent++;
continue;
}
if (jsonA[x] === jsonB[x])
continue;
let diff = Math.abs(jsonA[x] - jsonB[x]);
this.distance += Math.pow(2, diff/100);
}
for (let x in jsonB) {
if (typeof jsonB[x] === 'object') {
if (typeof jsonA[x] !== 'object') {
this.absent++;
}
continue;
}
if (!jsonA.hasOwnProperty(x)) {
this.absent++;
}
}
}
return this.distance;
}
getDifference (jsonA, jsonB) {
this.recurse(jsonA, jsonB);
this.distance += (0.5*this.absent*Math.pow(2, 5/100)); // 5=neutral
return this.distance;
}
}
module.exports.getDifference = (jsonA, jsonB) => {
return new module.exports().getDifference(jsonA, jsonB);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment