MCPcopy Index your code
hub / github.com/github/docs / groupTokens

Function groupTokens

script/helpers/get-liquid-conditionals.js:73–113  ·  view source on GitHub ↗
(tokens, tagName, endTagName, newArray = [])

Source from the content-addressed store, hash-verified

71}
72
73function groupTokens(tokens, tagName, endTagName, newArray = []) {
74 const startIndex = tokens.findIndex((token) => token.conditional === tagName)
75 // The end tag name is currently in a separate token, but we want to group it with the start tag and content.
76 const endIndex = tokens.findIndex(
77 (token, index) => token.conditional === endTagName && index > startIndex
78 )
79 // Once all tags are grouped and removed from `tokens`, this findIndex will not find anything,
80 // so we can return the grouped result at this point.
81 if (startIndex === -1) return newArray
82
83 const condBlockArr = tokens.slice(startIndex, endIndex + 1)
84 if (!condBlockArr.length) return newArray
85
86 const [newBlockArr, newEndIndex] = handleNestedTags(
87 condBlockArr,
88 endIndex,
89 tagName,
90 endTagName,
91 tokens
92 )
93
94 // Combine the text of the groups so it's all together.
95 const condBlock = newBlockArr.map((t) => t.text).join('')
96
97 const startToken = tokens[startIndex]
98 const endToken = tokens[endIndex]
99 newArray.push({
100 conditional: startToken.text,
101 text: condBlock,
102 endIfText: endToken.text,
103 positionStart: startToken.position,
104 positionEnd: endToken.position,
105 })
106
107 // Remove the already-processed tokens.
108 const numberOfItemsToRemove = newEndIndex + 1 - startIndex
109 tokens.splice(startIndex, numberOfItemsToRemove)
110
111 // Run recursively until we reach the end of the tokens.
112 return groupTokens(tokens, tagName, endTagName, newArray)
113}
114
115function handleNestedTags(condBlockArr, endIndex, tagName, endTagName, tokens) {
116 // Return early if there are no nested tags to be handled.

Callers 1

Calls 1

handleNestedTagsFunction · 0.85

Tested by

no test coverage detected