From 47c234ae54ef78cbb81251e15e62c43491f6cf79 Mon Sep 17 00:00:00 2001 From: Dragon Fire Date: Tue, 9 Feb 2021 16:57:22 -0500 Subject: [PATCH] Use text-diff --- commands/games-sp/typing-test.js | 12 ++++++++++-- package.json | 1 + util/Util.js | 14 -------------- 3 files changed, 11 insertions(+), 16 deletions(-) diff --git a/commands/games-sp/typing-test.js b/commands/games-sp/typing-test.js index 9f2f2f8e..bf4f1379 100644 --- a/commands/games-sp/typing-test.js +++ b/commands/games-sp/typing-test.js @@ -1,8 +1,9 @@ const Command = require('../../structures/Command'); const { createCanvas, registerFont } = require('canvas'); const { stripIndents } = require('common-tags'); +const Diff = require('text-diff'); const path = require('path'); -const { textDiff, fetchHSUserDisplay } = require('../../util/Util'); +const { fetchHSUserDisplay } = require('../../util/Util'); const words = require('../../assets/json/word-list'); registerFont(path.join(__dirname, '..', '..', 'assets', 'fonts', 'Noto-Regular.ttf'), { family: 'Noto' }); @@ -39,9 +40,16 @@ module.exports = class TypingTestCommand extends Command { } if (!msgs.size) return msg.reply('Sorry! You lose!'); if (msgs.first().content.toLowerCase() !== sentence) { + const diff = new Diff(); + const textDiff = diff.main(msgs.first().content.toLowerCase(), sentence); + const formatted = diff.cleanupSemantic(textDiff).map(change => { + if (change[0] === 1) return `**${change[1]}**`; + if (change[0] === 0) return change[1]; + return ''; + }).join(''); return msg.reply(stripIndents` Sorry! You made a typo, so you lose! - ${textDiff(msgs.first().content.toLowerCase(), sentence)} + ${formatted} `); } const wpm = (sentence.length / 5) / ((newScore / 1000) / 60); diff --git a/package.json b/package.json index adfeecb2..49fdfb0b 100644 --- a/package.json +++ b/package.json @@ -70,6 +70,7 @@ "sherlockjs": "^1.4.0", "stackblur-canvas": "^2.4.0", "tesseract.js": "^2.1.4", + "text-diff": "^1.0.1", "tictactoe-minimax-ai": "^1.2.1", "valid-url": "^1.0.9", "winston": "^3.3.3" diff --git a/util/Util.js b/util/Util.js index ad57cc60..519c985f 100644 --- a/util/Util.js +++ b/util/Util.js @@ -181,20 +181,6 @@ module.exports = class Util { return ((r << 16) | (g << 8) | b).toString(16); } - static textDiff(oldText, newText) { - let changed = []; - return oldText.split('').map((char, i) => { - if (char === newText.charAt(i)) { - const chars = changed.length ? `**${changed.join('')}**${char}` : char; - if (changed.length) changed = []; - const extraText = newText.slice(oldText.length); - return i === oldText.length - 1 ? `${chars}${extraText.length ? `**${extraText}**` : ''}` : chars; - } - changed.push(newText.charAt(i)); - return i === oldText.length - 1 ? `**${changed.join('')}${newText.slice(oldText.length)}**` : ''; - }).join(''); - } - static magikToBuffer(magik) { return new Promise((res, rej) => { magik.toBuffer((err, buffer) => {