Monday, June 16, 2008

JavaScript Diff Function Implementation

Since I have not ever done it before, I have found it was not obvious to me how to create a lists diff function in JavaScript, so I feel like should public the solution.

function diff(first, second) {
var diff = [], start_k = 0;

// calculating the diff
for (var i=0; i < first.length; i++) {
var same_found = false;
var pluses = [];
for (var k=start_k; k < second.length; k++) {
if (first[i] == second[k]) {
same_found = second[k];
start_k = k+1;
break;
} else {
pluses.push(second[k]);
}
}
if (same_found) {
for (var j=0; j < pluses.length; j++) {
diff.push({plus: pluses[j]});
}
diff.push({same: same_found});
} else {
diff.push({minus: first[i]});
}
}

// pushing down the trailing elements
for (var k=start_k; k < second.length; k++) {
diff.push({plus: second[k]});
}

return diff;
};

this function will return a sequention of hashes with keys 'minus', 'plus', 'same' which represents the differences and similarities between the two incomming arrays

No comments: