2 * @fileoverview Define utility functions for token store.
3 * @author Toru Nagashima
7 //------------------------------------------------------------------------------
9 //------------------------------------------------------------------------------
12 * Gets `token.range[0]` from the given token.
13 * @param {Node|Token|Comment} token The token to get.
14 * @returns {number} The start location.
17 function getStartLocation(token) {
18 return token.range[0];
21 //------------------------------------------------------------------------------
23 //------------------------------------------------------------------------------
26 * Finds the index of the first token which is after the given location.
27 * If it was not found, this returns `tokens.length`.
28 * @param {(Token|Comment)[]} tokens It searches the token in this list.
29 * @param {number} location The location to search.
30 * @returns {number} The found index or `tokens.length`.
32 exports.search = function search(tokens, location) {
33 const index = tokens.findIndex(el => location <= getStartLocation(el));
35 return index === -1 ? tokens.length : index;
39 * Gets the index of the `startLoc` in `tokens`.
40 * `startLoc` can be the value of `node.range[1]`, so this checks about `startLoc - 1` as well.
41 * @param {(Token|Comment)[]} tokens The tokens to find an index.
42 * @param {Object} indexMap The map from locations to indices.
43 * @param {number} startLoc The location to get an index.
44 * @returns {number} The index.
46 exports.getFirstIndex = function getFirstIndex(tokens, indexMap, startLoc) {
47 if (startLoc in indexMap) {
48 return indexMap[startLoc];
50 if ((startLoc - 1) in indexMap) {
51 const index = indexMap[startLoc - 1];
52 const token = (index >= 0 && index < tokens.length) ? tokens[index] : null;
55 * For the map of "comment's location -> token's index", it points the next token of a comment.
56 * In that case, +1 is unnecessary.
58 if (token && token.range[0] >= startLoc) {
67 * Gets the index of the `endLoc` in `tokens`.
68 * The information of end locations are recorded at `endLoc - 1` in `indexMap`, so this checks about `endLoc - 1` as well.
69 * @param {(Token|Comment)[]} tokens The tokens to find an index.
70 * @param {Object} indexMap The map from locations to indices.
71 * @param {number} endLoc The location to get an index.
72 * @returns {number} The index.
74 exports.getLastIndex = function getLastIndex(tokens, indexMap, endLoc) {
75 if (endLoc in indexMap) {
76 return indexMap[endLoc] - 1;
78 if ((endLoc - 1) in indexMap) {
79 const index = indexMap[endLoc - 1];
80 const token = (index >= 0 && index < tokens.length) ? tokens[index] : null;
83 * For the map of "comment's location -> token's index", it points the next token of a comment.
84 * In that case, -1 is necessary.
86 if (token && token.range[1] > endLoc) {
91 return tokens.length - 1;