Skip to content
This repository has been archived by the owner on Mar 23, 2024. It is now read-only.

Commit

Permalink
Add "iterateTokenByValue" method
Browse files Browse the repository at this point in the history
Closes gh-597
  • Loading branch information
markelog committed Aug 28, 2014
1 parent ba562c4 commit 430e0fd
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
20 changes: 20 additions & 0 deletions lib/js-file.js
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,26 @@ JsFile.prototype = {
}
});
},
/**
* Iterates token by value from the token array.
* Calls passed function for every matched token.
*
* @param {String|String[]} name
* @param {Function} cb
*/
iterateTokenByValue: function(name, cb) {
var names = (typeof name === 'string') ? [name] : name;
var nameIndex = {};
names.forEach(function(type) {
nameIndex[type] = true;
});

this.getTokens().forEach(function(token, index, tokens) {
if (nameIndex[token.value]) {
cb(token, index, tokens);
}
});
},
/**
* Returns string representing contents of the file.
*
Expand Down
31 changes: 31 additions & 0 deletions test/js-file.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,4 +134,35 @@ describe('modules/js-file', function() {
assert(ifToken.type === 'Keyword');
assert(ifToken.value === 'if');
});

it('should find token by value', function() {
var str = 'if (true);';
var file = new JsFile(null, str, esprima.parse(str, {loc: true, range: true, tokens: true}));

file.iterateTokenByValue(')', function(token, index, tokens) {
assert(token.value === ')');
assert(index === 3);
assert(Array.isArray(tokens));
});
});

it('should find tokens by value', function() {
var str = 'if (true);';
var file = new JsFile(null, str, esprima.parse(str, {loc: true, range: true, tokens: true}));

file.iterateTokenByValue([')', '('], function(token, index, tokens) {
assert(token.value === ')' || token.value === '(');
assert(index === 3 || index === 1);
assert(Array.isArray(tokens));
});
});

it('should not find string value', function() {
var str = '"("';
var file = new JsFile(null, str, esprima.parse(str, {loc: true, range: true, tokens: true}));

file.iterateTokenByValue('(', function(token, index, tokens) {
assert(false);
});
});
});

0 comments on commit 430e0fd

Please sign in to comment.