Created
August 11, 2017 18:09
-
-
Save mngyuan/6b506dd6414dc11119044f933c4aa081 to your computer and use it in GitHub Desktop.
Single Line Diff tool
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// paste into https://facebook.github.io/react/ to use | |
class DiffInput extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = {text1: 'hello', text2: 'henlo world', diff:[]}; | |
this.onChange1 = this.onChange1.bind(this); | |
this.onChange2 = this.onChange2.bind(this); | |
} | |
onChange1(e) { | |
const text1 = e.target.value; | |
this.setState({text1, diff: this.computeDiff(text1, this.state.text2)}); | |
} | |
onChange2(e) { | |
const text2 = e.target.value; | |
this.setState({text2, diff: this.computeDiff(this.state.text1, text2)}); | |
} | |
computeDiff(a, b) { | |
const totallen = a.length + b.length; | |
let result = []; | |
let j = 0; | |
for (let i = 0; i+j<totallen; i++) { | |
if (a[i] == b[j]) { | |
result = result.concat({char: a[i]}); | |
j++; | |
} else { | |
result = result.concat({char: a[i], removal: true}); | |
while (a[i] != b[j] && j < b.length) { | |
result = result.concat({char: b[j], addition: true}); | |
j++; | |
} | |
} | |
} | |
return result; | |
} | |
displayDiff(diff) { | |
let result = []; | |
diff.map(function(c) { | |
result = result.concat( | |
c.removal | |
? <span style={{background:"red"}}>{c.char}</span> | |
: (c.addition ? <span style={{background:"green"}}>{c.char}</span> | |
: <span>{c.char}</span>) | |
); | |
}); | |
console.log(result); | |
return ( | |
<div> | |
{result} | |
</div> | |
); | |
} | |
render() { | |
return ( | |
<div> | |
<input value={this.state.text1} onChange={this.onChange1} /> | |
<input value={this.state.text2} onChange={this.onChange2} /> | |
<div>{this.displayDiff(this.state.diff)}</div> | |
</div> | |
); | |
} | |
} | |
ReactDOM.render(<DiffInput name="John" />, mountNode); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment