Last active
October 15, 2021 01:40
-
-
Save mmyoji/3e3e5b451bbe7185721322b739dd74b5 to your computer and use it in GitHub Desktop.
Show string diff before / after style #nodejs
This file contains hidden or 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
import "colors"; | |
import * as Diff from "diff"; | |
const one = "こんにちは、きょうはいい天気ですね。"; | |
const other = "こんばんは。今日は良い天気だね。"; | |
const diff = Diff.diffChars(one, other); | |
function log(word) { | |
process.stderr.write(word); | |
} | |
function showDiffedString(diff, word, fn) { | |
let index = 0; | |
let current = word.slice(index); | |
for (const part of diff) { | |
if (current.length === 0) { | |
break; | |
} | |
if (current.startsWith(part.value)) { | |
fn(part); | |
current = current.slice(part.value.length); | |
} | |
} | |
} | |
log("Before: "); | |
showDiffedString(diff, one, (part) => { | |
if (part.removed) { | |
log(part.value["red"]); | |
} else { | |
log(part.value["grey"]); | |
} | |
}); | |
console.log(); | |
log("After: "); | |
showDiffedString(diff, other, (part) => { | |
if (part.added) { | |
log(part.value["green"]); | |
} else { | |
log(part.value["grey"]); | |
} | |
}); | |
console.log(); |
This file contains hidden or 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
{ | |
"name": "tmp", | |
"type": "module", | |
"dependencies": { | |
"colors": "^1.4.0", | |
"diff": "^5.0.0" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment