JSTools
Collection of stupid tools for my use
by Danielo Rodriguez
HTML
<div id="inputs">
<input id="left" type="text" />
<input id="right" type="text" />
</div>
<div id="controls">
<button id="execute">Compare</button>
</div>
<div id="reportArea">
<pre><code id="report"></code></pre>
</div>
CSS
#controls {
float: right;
}
#inputs {
float: left;
}
#reportArea {
clear:both;
padding-top: 5px;
}
#reportArea>pre {
border: 1px dotted #cecece;
}
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
Babel + JSX
const Left = $("#left");
const Right = $("#right");
const ComparisonType = $("#comparison");
const Report = $("#report");
$("#execute").on('click',compare);
restorePreviousValues();
function compare() {
saveCurrValues();
const lValue = JSON.parse(Left.val());
const rValue = JSON.parse(Right.val());
fillReport(arrComparer(lValue,rValue));
}
function saveCurrValues(){
localStorage.setItem('left',JSON.stringify(Left.val()));
localStorage.setItem('right',JSON.stringify(Right.val()));
}
function restorePreviousValues(){
Left.val(JSON.parse(localStorage.getItem('left')));
Right.val(JSON.parse(localStorage.getItem('right')));
}
function fillReport(values){
console.log(values);
Report.html(syntaxHighlight(JSON.stringify(values, null, 2)))
}
function arrComparer(a,b){
const result = {};
result['Exact match'] = (a.join() === b.join());
result['A size'] = a.length;
result['B size'] = b.length;
if(result['Exact match']){ return result};
result["Elements of A contained in B"] =
a.filter( val => b.indexOf(val) != -1 );
result["Elements of B contained in A"] =
b.filter( val => a.indexOf(val) != -1 );
return result;
}
function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}