From 704f2dd73439d48de4e1abddb6f5f89a6e8e0d6f Mon Sep 17 00:00:00 2001 From: Raymond Hill Date: Tue, 12 Aug 2025 08:29:22 -0400 Subject: [PATCH] [mv3] Code review implementation of custom "console" Related commit: https://github.com/gorhill/uBlock/commit/28ea00fd11b1204f359c256d998c2e04328ec54b --- platform/mv3/extension/js/debug.js | 30 +++++++++++++----------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/platform/mv3/extension/js/debug.js b/platform/mv3/extension/js/debug.js index 8a299b6e7..2fe8e6e39 100644 --- a/platform/mv3/extension/js/debug.js +++ b/platform/mv3/extension/js/debug.js @@ -43,18 +43,21 @@ export const isSideloaded = (( ) => { const CONSOLE_MAX_LINES = 32; const consoleOutput = []; -let consoleWritePtr = 0; sessionRead('console').then(before => { if ( Array.isArray(before) === false ) { return; } - const current = getConsoleOutput(); - const merged = [ ...before, ...current ].slice(-CONSOLE_MAX_LINES); - for ( let i = 0; i < merged.length; i++ ) { - consoleOutput[i] = merged[i]; + for ( const s of before.reverse() ) { + consoleOutput.unshift(s); } - consoleWritePtr = merged.length % CONSOLE_MAX_LINES; + consoleTruncate(); }); +const consoleTruncate = ( ) => { + if ( consoleOutput.length <= CONSOLE_MAX_LINES ) { return; } + consoleOutput.copyWithin(0, -CONSOLE_MAX_LINES); + consoleOutput.length = CONSOLE_MAX_LINES; +}; + const consoleAdd = (...args) => { if ( args.length === 0 ) { return; } const now = new Date(); @@ -68,9 +71,10 @@ const consoleAdd = (...args) => { for ( let i = 0; i < args.length; i++ ) { const s = `[${time}]${args[i]}`; if ( Boolean(s) === false ) { continue; } - consoleOutput[consoleWritePtr++] = s; - consoleWritePtr %= CONSOLE_MAX_LINES; + if ( s === consoleOutput.at(-1) ) { continue; } + consoleOutput.push(s); } + consoleTruncate(); sessionWrite('console', getConsoleOutput()); } @@ -91,15 +95,7 @@ export const ubolErr = (...args) => { }; export const getConsoleOutput = ( ) => { - return [ - ...consoleOutput.slice(consoleWritePtr), - ...consoleOutput.slice(0, consoleWritePtr), - ].reduce((acc, val) => { - if ( val !== acc.at(-1) ) { - acc.push(val); - } - return acc; - }, []); + return consoleOutput.slice(); }; /******************************************************************************/