UNPKG

@hyperbytes/wappler-codediff

Version:

Compare two texts for differences

47 lines (40 loc) 1.68 kB
// JavaScript Document const diff = require('diff'); exports.textdiff = async function (options, name) { const oldText = this.parseRequired(options.text1, "*", "No old text sent"); const newText = this.parseRequired(options.text2, "*", "No new text sent"); const multiline = this.parseOptional(options.multiline, "*", false); const usebr = this.parseOptional(options.usebr, "*", false); return analyzeTextChange(oldText, newText) function analyzeTextChange(oldText, newText) { const changes = diff.diffWords(oldText, newText); let changedWords = 0; let totalWords = 0; let addedChars = 0; let removedChars = 0; let changeDetails = []; let multidelim = usebr ? "<br>" : "/n"; changes.forEach(part => { const trimmed = part.value.trim(); const wordCount = trimmed.split(/\s+/).filter(Boolean).length; totalWords += wordCount; if (part.added) { changedWords += wordCount; addedChars += trimmed.length; changeDetails.push(`change: "Added: ${trimmed}"`); } else if (part.removed) { changedWords += wordCount; removedChars += trimmed.length; changeDetails.push(`change: "Removed: ${trimmed}"`); } }); if (multiline) { changeDetails = changeDetails.join(multidelim) } const changeScore = totalWords === 0 ? 0 : Math.round((changedWords / totalWords) * 100); return { changes: changeDetails, changeScore, addedChars, removedChars }; } }