Skip to content

Instantly share code, notes, and snippets.

@nathanhammond
Created August 27, 2010 21:55
Show Gist options
  • Save nathanhammond/554269 to your computer and use it in GitHub Desktop.
Save nathanhammond/554269 to your computer and use it in GitHub Desktop.
Simple textarea diff functionality.
/*
* Textarea Diff
* Simple textarea diff functionality.
*
* Copyright 2010, Nathan Hammond
* Released under the MIT License
*/
function diff(oldtext, newtext) {
// Only one difference. Guaranteed contiguous.
// Protect the special case of inserting or deleting an adjacent repeating token.
for (var beginning = 0; oldtext[beginning] === newtext[beginning]; beginning++) {}
var endmax = Math.max(newtext.length - beginning, oldtext.length - beginning);
for (var end = 0; oldtext[oldtext.length-end] === newtext[newtext.length-end], end < endmax; end++) {}
var content = newtext.substring(beginning, (newtext.length-end+1));
return { beginning: beginning, end: end, content: content};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment