From 92705b45454c75072417d383179d876833354c41 Mon Sep 17 00:00:00 2001 From: Roman Dvornov Date: Thu, 13 Jul 2017 01:03:03 +0300 Subject: [PATCH] refactoring of match result getTrace() method (25% performance boost) --- lib/lexer/trace.js | 31 ++++++++++++++++--------------- test/lexer.js | 2 +- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/lib/lexer/trace.js b/lib/lexer/trace.js index 89fb534e..c52dad66 100644 --- a/lib/lexer/trace.js +++ b/lib/lexer/trace.js @@ -2,10 +2,12 @@ function getTrace(node) { function hasMatch(matchNode) { if (matchNode.type === 'ASTNode') { if (matchNode.node === node) { + result = []; return true; } if (matchNode.childrenMatch) { + // use for-loop for better perfomance for (var i = 0; i < matchNode.childrenMatch.length; i++) { if (hasMatch(matchNode.childrenMatch[i])) { return true; @@ -13,30 +15,29 @@ function getTrace(node) { } } } else { - var addToStack = matchNode.syntax.type === 'Type' || - matchNode.syntax.type === 'Property' || - matchNode.syntax.type === 'Keyword'; - - if (addToStack) { - stack.push(matchNode.syntax); - } - + // use for-loop for better perfomance for (var i = 0; i < matchNode.match.length; i++) { - if (hasMatch(matchNode.match[i], node, stack)) { + if (hasMatch(matchNode.match[i])) { + if (matchNode.syntax.type === 'Type' || + matchNode.syntax.type === 'Property' || + matchNode.syntax.type === 'Keyword') { + result.unshift(matchNode.syntax); + } return true; } } - - if (addToStack) { - stack.pop(); - } } return false; } - var stack = []; - return this.matched !== null && hasMatch(this.matched) ? stack : null; + var result = null; + + if (this.matched !== null) { + hasMatch(this.matched); + } + + return result; } function testNode(match, node, fn) { diff --git a/test/lexer.js b/test/lexer.js index 2c668d02..21c6bafa 100644 --- a/test/lexer.js +++ b/test/lexer.js @@ -267,7 +267,7 @@ describe('lexer', function() { var match = syntax.lexer.matchProperty('background', ast); var mismatch = syntax.lexer.matchProperty('margin', ast); - it('getNodeTrace', function() { + it('getTrace', function() { assert.deepEqual(match.getTrace(testNode), [ { type: 'Type', name: 'final-bg-layer' }, { type: 'Property', name: 'background-color' },