jsdiff
Compares text tokens and creates or applies unified patches.
- Downloads / mo
- 735.9M
- Stars
- 9.2K
- Last release
- 9.0.0
- License
- BSD-3-Clause
Strengths
- Compares different text units. Choose character, word, or line comparisons.
- Creates reversible unified patches. Generate a structured patch and reverse it to undo changes.
Limitations
- Bounded comparisons can return undefined. Handle an aborted comparison when using timeout or maxEditLength.
- Patch context must still match. Deleted lines and insertion boundaries must match even with fuzzFactor.
Quickstart
const { diffChars } = require('diff'); console.log(diffChars('hello', 'hello world'));
jsdiff examples
export function getDiffStat( fileName: string, oldStr: string, aiStr: string, userStr: string, ): DiffStat { const getStats = (patch: Diff.StructuredPatch) => { let addedLines = 0; let removedLines = 0; let addedChars = 0; let removedChars = 0; patch.hunks.forEach((hunk: Diff.StructuredPatchHunk) => { hunk.lines.forEach((line: string) => { if (line.startsWith('+')) { addedLines++; addedChars += line.length - 1; } else if (line.startsWith('-')) { removedLines++; removedChars += line.length - 1; } }); }); return { addedLines, removedLines, addedChars, removedChars }; }; const modelPatch = Diff.structuredPatch( fileName, fileName, oldStr, aiStr, 'Current', 'Proposed', DEFAULT_STRUCTURED_PATCH_OPTS, ); const modelStats = getStats(modelPatch); const userPatch = Diff.structuredPatch( fileName, fileName, aiStr, userStr, 'Proposed', 'User', DEFAULT_STRUCTURED_PATCH_OPTS, ); const userStats = getStats(userPatch); return { model_added_lines: modelStats.addedLines, model_removed_lines: modelStats.removedLines, model_added_chars: modelStats.addedChars, model_removed_chars: modelStats.removedChars, user_added_lines: userStats.addedLines, user_removed_lines: userStats.removedLines, user_added_chars: userStats.addedChars, user_removed_chars: userStats.removedChars, }; }