json-deep-compare
Version:
A powerful library for comparing JSON objects with support for deep comparison, regex validation, and customizable options
1 lines • 2.24 kB
JavaScript
class FastComparator{static fastCompare(e,t){return e===t?{matchPercentage:100,totalKeys:0,matched:0,unmatched:0}:typeof e!=typeof t?{matchPercentage:0,totalKeys:1,matched:0,unmatched:1}:null==e||null==t||"object"!=typeof e?{matchPercentage:e===t?100:0,totalKeys:1,matched:e===t?1:0,unmatched:e===t?0:1}:Array.isArray(e)&&Array.isArray(t)?this.fastCompareArrays(e,t):"object"==typeof e&&"object"==typeof t?this.fastCompareObjects(e,t):{matchPercentage:0,totalKeys:1,matched:0,unmatched:1}}static fastCompareArrays(e,t){const a=e.length,c=t.length;if(a!==c)return{matchPercentage:0,totalKeys:Math.max(a,c),matched:0,unmatched:Math.max(a,c)};if(0===a)return{matchPercentage:100,totalKeys:0,matched:0,unmatched:0};let r=0,s=0;for(let c=0;c<a;c++)if(e[c]===t[c])r++;else{const n=e[c],h=t[c];if(null==n&&null==h){if(n===h)r++;else if(s++,s>a/2)return{matchPercentage:0,totalKeys:a,matched:r,unmatched:a-r}}else{if(100===this.fastCompare(n,h).matchPercentage)r++;else if(s++,s>a/2)return{matchPercentage:0,totalKeys:a,matched:r,unmatched:a-r}}}const n=r+s;return{matchPercentage:n>0?r/n*100:100,totalKeys:n,matched:r,unmatched:s}}static fastCompareObjects(e,t){if(Object.getPrototypeOf(e)!==Object.prototype||Object.getPrototypeOf(t)!==Object.prototype)return{matchPercentage:0,totalKeys:1,matched:0,unmatched:1};const a=Object.keys(e),c=Object.keys(t),r=a.length,s=c.length;if(s<r)return{matchPercentage:0,totalKeys:r,matched:0,unmatched:r-s};if(0===r)return{matchPercentage:100,totalKeys:0,matched:0,unmatched:0};let n=0,h=0;for(let c=0;c<r;c++){const s=a[c];if(s in t)if(e[s]===t[s])n++;else{const a=e[s],c=t[s];if(null==a&&null==c){if(a===c)n++;else if(h++,h>r/2)return{matchPercentage:0,totalKeys:r,matched:n,unmatched:r-n}}else{if(100===this.fastCompare(a,c).matchPercentage)n++;else if(h++,h>r/2)return{matchPercentage:0,totalKeys:r,matched:n,unmatched:r-n}}}else h++}const m=n+h;return{matchPercentage:m>0?n/m*100:100,totalKeys:m,matched:n,unmatched:h}}static shouldUseFastMode(e){return!(e.regexChecks&&0!==Object.keys(e.regexChecks).length||e.equivalentValues&&0!==Object.keys(e.equivalentValues).length||!0!==e.strictTypes||e.ignoredKeys&&0!==e.ignoredKeys.length||!0!==e.ignoreExtraKeys||e.matchKeysByName)}}module.exports=FastComparator;