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

Commit

Permalink
Merge abffc7e into ba562c4
Browse files Browse the repository at this point in the history
  • Loading branch information
markelog committed Aug 27, 2014
2 parents ba562c4 + abffc7e commit d14e2e1
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
21 changes: 21 additions & 0 deletions lib/js-file.js
Expand Up @@ -275,6 +275,27 @@ 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
22 changes: 22 additions & 0 deletions test/js-file.js
Expand Up @@ -134,4 +134,26 @@ 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));
});
});
});

0 comments on commit d14e2e1

Please sign in to comment.