Diff between two parts of code in JS skipping names

Viewed 111

I'm trying to find a diff in obfuscated code which means that names of variables/functions can be different for the same code. Here's an example:
Code A:

function A(a) {
  var b = a * 4;
  console.log(b);
}

Code B:

function B(b) {
  var c = b * 4 + 2;
  console.log(c);
}

So, the only diff I would like to find between these portions of code is just + 2 part and not diff in names of function and variables.

As mentioned by @blex in comment, variables/functions names don't matter but logic change does matter. So, here's another example:
Code A:

function A(a,b,c) {
  return a * b + c;
}

Code B:

function B(x,y,z) {
  return y * z + x
}

In this example I would like to see the difference: a * b + c => y * z + x.

Is this possible to do somehow?

2 Answers

You could use some minification library like Terser in order to produce a mangled output which should have the same function and variable names:

const { minify } = Terser;

const A = `function A(a) {
  var b = a * 4;
  console.log(b);
}`


const B = `function B(b) {
  var c = b * 4 + 2;
  console.log(c);
}`

Promise.all([A, B].map(x => minify(x, { mangle: { toplevel: true } })))
  .then(([A, B]) => console.log(`Calculate difference between ${A.code} and ${B.code}`));
<script src="https://cdn.jsdelivr.net/npm/terser/dist/bundle.min.js"></script>

I didn't write the string diffing part because it's a really big subject and there are whole libraries for that.

how about this

function A(b){
  var c = b * 4 + 2;
  return(c)
}
function B(b) {
  var c = b * 4;
  return(c);
}

console.log(B(10)-A(4))

this will solve your problem i guess

Related