id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
23,900
ota-meshi/eslint-plugin-lodash-template
lib/service/MicroTemplateService.js
parseSelector
function parseSelector(rawSelector) { const parsedSelector = tryParseSelector(rawSelector) return { rawSelector, isExit: rawSelector.endsWith(":exit"), parsedSelector, } }
javascript
function parseSelector(rawSelector) { const parsedSelector = tryParseSelector(rawSelector) return { rawSelector, isExit: rawSelector.endsWith(":exit"), parsedSelector, } }
[ "function", "parseSelector", "(", "rawSelector", ")", "{", "const", "parsedSelector", "=", "tryParseSelector", "(", "rawSelector", ")", "return", "{", "rawSelector", ",", "isExit", ":", "rawSelector", ".", "endsWith", "(", "\":exit\"", ")", ",", "parsedSelector", ",", "}", "}" ]
Parses a raw selector string, and returns the parsed selector along with specificity and type information. @param {string} rawSelector A raw AST selector @returns {ASTSelector} A selector descriptor
[ "Parses", "a", "raw", "selector", "string", "and", "returns", "the", "parsed", "selector", "along", "with", "specificity", "and", "type", "information", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/service/MicroTemplateService.js#L36-L44
23,901
ota-meshi/eslint-plugin-lodash-template
lib/service/MicroTemplateService.js
traverse
function traverse(tokens, options) { const traverser = new Traverser() const nodes = Array.isArray(tokens) ? tokens : [tokens] for (const node of nodes) { traverser.traverse(node, options) if (traverser.isBroken()) { return } } }
javascript
function traverse(tokens, options) { const traverser = new Traverser() const nodes = Array.isArray(tokens) ? tokens : [tokens] for (const node of nodes) { traverser.traverse(node, options) if (traverser.isBroken()) { return } } }
[ "function", "traverse", "(", "tokens", ",", "options", ")", "{", "const", "traverser", "=", "new", "Traverser", "(", ")", "const", "nodes", "=", "Array", ".", "isArray", "(", "tokens", ")", "?", "tokens", ":", "[", "tokens", "]", "for", "(", "const", "node", "of", "nodes", ")", "{", "traverser", ".", "traverse", "(", "node", ",", "options", ")", "if", "(", "traverser", ".", "isBroken", "(", ")", ")", "{", "return", "}", "}", "}" ]
Traverse the given tokens. @param {Token|Token[]} tokens tokens. @param {object} options The option object. @returns {void}
[ "Traverse", "the", "given", "tokens", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/service/MicroTemplateService.js#L133-L142
23,902
ota-meshi/eslint-plugin-lodash-template
lib/service/MicroTemplateService.js
traverseNodes
function traverseNodes(nodes, visitor) { const ne = new NodeEventGenerator(visitor) traverse(nodes, { enter(child) { ne.enterNode(child) }, leave(child) { ne.leaveNode(child) }, }) }
javascript
function traverseNodes(nodes, visitor) { const ne = new NodeEventGenerator(visitor) traverse(nodes, { enter(child) { ne.enterNode(child) }, leave(child) { ne.leaveNode(child) }, }) }
[ "function", "traverseNodes", "(", "nodes", ",", "visitor", ")", "{", "const", "ne", "=", "new", "NodeEventGenerator", "(", "visitor", ")", "traverse", "(", "nodes", ",", "{", "enter", "(", "child", ")", "{", "ne", ".", "enterNode", "(", "child", ")", "}", ",", "leave", "(", "child", ")", "{", "ne", ".", "leaveNode", "(", "child", ")", "}", ",", "}", ")", "}" ]
Traverse the given AST tree. @param {object} nodes Root node to traverse. @param {object} visitor Visitor. @returns {void}
[ "Traverse", "the", "given", "AST", "tree", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/service/MicroTemplateService.js#L150-L161
23,903
ota-meshi/eslint-plugin-lodash-template
lib/service/MicroTemplateService.js
findToken
function findToken(node, test) { let find = null traverse(node, { enter(child) { if (test(child)) { find = child this.break() } }, }) return find }
javascript
function findToken(node, test) { let find = null traverse(node, { enter(child) { if (test(child)) { find = child this.break() } }, }) return find }
[ "function", "findToken", "(", "node", ",", "test", ")", "{", "let", "find", "=", "null", "traverse", "(", "node", ",", "{", "enter", "(", "child", ")", "{", "if", "(", "test", "(", "child", ")", ")", "{", "find", "=", "child", "this", ".", "break", "(", ")", "}", "}", ",", "}", ")", "return", "find", "}" ]
Find for the token that hit on the given test. @param {object} node Root node to traverse. @param {function} test test. @returns {Token|null} The token that hit on the given test
[ "Find", "for", "the", "token", "that", "hit", "on", "the", "given", "test", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/service/MicroTemplateService.js#L169-L180
23,904
ota-meshi/eslint-plugin-lodash-template
lib/service/MicroTemplateService.js
inToken
function inToken(loc, token) { if (typeof loc === "number") { return token.range[0] <= loc && loc < token.range[1] } return locationInRangeLoc(loc, token.loc.start, token.loc.end) }
javascript
function inToken(loc, token) { if (typeof loc === "number") { return token.range[0] <= loc && loc < token.range[1] } return locationInRangeLoc(loc, token.loc.start, token.loc.end) }
[ "function", "inToken", "(", "loc", ",", "token", ")", "{", "if", "(", "typeof", "loc", "===", "\"number\"", ")", "{", "return", "token", ".", "range", "[", "0", "]", "<=", "loc", "&&", "loc", "<", "token", ".", "range", "[", "1", "]", "}", "return", "locationInRangeLoc", "(", "loc", ",", "token", ".", "loc", ".", "start", ",", "token", ".", "loc", ".", "end", ")", "}" ]
Check whether the location is in token. @param {object|number} loc The location or index. @param {object} token The token. @returns {boolean} `true` if the location is in token.
[ "Check", "whether", "the", "location", "is", "in", "token", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/service/MicroTemplateService.js#L212-L217
23,905
ota-meshi/eslint-plugin-lodash-template
lib/service/MicroTemplateService.js
findExpressionStatement
function findExpressionStatement(start, end) { let target = sourceCode.getNodeByRangeIndex(start) while ( target && target.range[1] <= end && start <= target.range[0] ) { if ( target.type === "ExpressionStatement" && start === target.range[0] && target.range[1] === end ) { return target } target = target.parent } return null }
javascript
function findExpressionStatement(start, end) { let target = sourceCode.getNodeByRangeIndex(start) while ( target && target.range[1] <= end && start <= target.range[0] ) { if ( target.type === "ExpressionStatement" && start === target.range[0] && target.range[1] === end ) { return target } target = target.parent } return null }
[ "function", "findExpressionStatement", "(", "start", ",", "end", ")", "{", "let", "target", "=", "sourceCode", ".", "getNodeByRangeIndex", "(", "start", ")", "while", "(", "target", "&&", "target", ".", "range", "[", "1", "]", "<=", "end", "&&", "start", "<=", "target", ".", "range", "[", "0", "]", ")", "{", "if", "(", "target", ".", "type", "===", "\"ExpressionStatement\"", "&&", "start", "===", "target", ".", "range", "[", "0", "]", "&&", "target", ".", "range", "[", "1", "]", "===", "end", ")", "{", "return", "target", "}", "target", "=", "target", ".", "parent", "}", "return", "null", "}" ]
Find the ExpressionStatement of range. @param {number} start - The start of range. @param {numnber} end - The end of range. @returns {ExpressionStatement} The expression statement.
[ "Find", "the", "ExpressionStatement", "of", "range", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/service/MicroTemplateService.js#L537-L554
23,906
ota-meshi/eslint-plugin-lodash-template
lib/rules/html-indent.js
equalsLocation
function equalsLocation(a, b) { return a.range[0] === b.range[0] && a.range[1] === b.range[1] }
javascript
function equalsLocation(a, b) { return a.range[0] === b.range[0] && a.range[1] === b.range[1] }
[ "function", "equalsLocation", "(", "a", ",", "b", ")", "{", "return", "a", ".", "range", "[", "0", "]", "===", "b", ".", "range", "[", "0", "]", "&&", "a", ".", "range", "[", "1", "]", "===", "b", ".", "range", "[", "1", "]", "}" ]
Check whether the given tokens is a equals range. @param {Token} a The token @param {Token} b The token @returns {boolean} `true` if the given tokens is a equals range.
[ "Check", "whether", "the", "given", "tokens", "is", "a", "equals", "range", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/html-indent.js#L113-L115
23,907
ota-meshi/eslint-plugin-lodash-template
lib/rules/html-indent.js
isLineStart
function isLineStart(loc) { const actualText = getActualLineIndentText(loc.line) return actualText.length === loc.column }
javascript
function isLineStart(loc) { const actualText = getActualLineIndentText(loc.line) return actualText.length === loc.column }
[ "function", "isLineStart", "(", "loc", ")", "{", "const", "actualText", "=", "getActualLineIndentText", "(", "loc", ".", "line", ")", "return", "actualText", ".", "length", "===", "loc", ".", "column", "}" ]
Check whether the given location is a line start location. @param {Location} loc The location to check. @returns {boolean} `true` if the location is a line start location.
[ "Check", "whether", "the", "given", "location", "is", "a", "line", "start", "location", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/html-indent.js#L197-L200
23,908
ota-meshi/eslint-plugin-lodash-template
lib/rules/html-indent.js
setOffsetToLoc
function setOffsetToLoc(loc, offset, baseline) { if (baseline >= loc.line) { return } const actualText = getActualLineIndentText(loc.line) if (actualText.length !== loc.column) { return } offsets.set(loc.line, { actualText, baseline, offset, expectedIndent: undefined, }) }
javascript
function setOffsetToLoc(loc, offset, baseline) { if (baseline >= loc.line) { return } const actualText = getActualLineIndentText(loc.line) if (actualText.length !== loc.column) { return } offsets.set(loc.line, { actualText, baseline, offset, expectedIndent: undefined, }) }
[ "function", "setOffsetToLoc", "(", "loc", ",", "offset", ",", "baseline", ")", "{", "if", "(", "baseline", ">=", "loc", ".", "line", ")", "{", "return", "}", "const", "actualText", "=", "getActualLineIndentText", "(", "loc", ".", "line", ")", "if", "(", "actualText", ".", "length", "!==", "loc", ".", "column", ")", "{", "return", "}", "offsets", ".", "set", "(", "loc", ".", "line", ",", "{", "actualText", ",", "baseline", ",", "offset", ",", "expectedIndent", ":", "undefined", ",", "}", ")", "}" ]
Set offset to the given location. @param {Location} loc The start index to set. @param {number} offset The offset of the tokens. @param {number} baseline The line of the base offset. @returns {void}
[ "Set", "offset", "to", "the", "given", "location", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/html-indent.js#L209-L223
23,909
ota-meshi/eslint-plugin-lodash-template
lib/rules/html-indent.js
setOffsetToIndex
function setOffsetToIndex(startIndex, offset, baseline) { const loc = sourceCode.getLocFromIndex(startIndex) setOffsetToLoc(loc, offset, baseline) }
javascript
function setOffsetToIndex(startIndex, offset, baseline) { const loc = sourceCode.getLocFromIndex(startIndex) setOffsetToLoc(loc, offset, baseline) }
[ "function", "setOffsetToIndex", "(", "startIndex", ",", "offset", ",", "baseline", ")", "{", "const", "loc", "=", "sourceCode", ".", "getLocFromIndex", "(", "startIndex", ")", "setOffsetToLoc", "(", "loc", ",", "offset", ",", "baseline", ")", "}" ]
Set offset to the given index. @param {number} startIndex The start index to set. @param {number} offset The offset of the tokens. @param {number} baseline The line of the base offset. @returns {void}
[ "Set", "offset", "to", "the", "given", "index", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/html-indent.js#L232-L235
23,910
ota-meshi/eslint-plugin-lodash-template
lib/rules/html-indent.js
setOffsetToLine
function setOffsetToLine(line, offset, baseline) { if (baseline >= line) { return } const actualText = getActualLineIndentText(line) offsets.set(line, { actualText, baseline, offset, expectedIndent: undefined, }) }
javascript
function setOffsetToLine(line, offset, baseline) { if (baseline >= line) { return } const actualText = getActualLineIndentText(line) offsets.set(line, { actualText, baseline, offset, expectedIndent: undefined, }) }
[ "function", "setOffsetToLine", "(", "line", ",", "offset", ",", "baseline", ")", "{", "if", "(", "baseline", ">=", "line", ")", "{", "return", "}", "const", "actualText", "=", "getActualLineIndentText", "(", "line", ")", "offsets", ".", "set", "(", "line", ",", "{", "actualText", ",", "baseline", ",", "offset", ",", "expectedIndent", ":", "undefined", ",", "}", ")", "}" ]
Set offset to the given line. @param {number} line The line to set. @param {number} offset The offset of the tokens. @param {number} baseline The line of the base offset. @returns {void}
[ "Set", "offset", "to", "the", "given", "line", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/html-indent.js#L261-L273
23,911
ota-meshi/eslint-plugin-lodash-template
lib/rules/html-indent.js
setOffsetRootToIndex
function setOffsetRootToIndex(startIndex) { const loc = sourceCode.getLocFromIndex(startIndex) if (!offsets.has(loc.line)) { setOffsetToLoc(loc, 0, -1) } }
javascript
function setOffsetRootToIndex(startIndex) { const loc = sourceCode.getLocFromIndex(startIndex) if (!offsets.has(loc.line)) { setOffsetToLoc(loc, 0, -1) } }
[ "function", "setOffsetRootToIndex", "(", "startIndex", ")", "{", "const", "loc", "=", "sourceCode", ".", "getLocFromIndex", "(", "startIndex", ")", "if", "(", "!", "offsets", ".", "has", "(", "loc", ".", "line", ")", ")", "{", "setOffsetToLoc", "(", "loc", ",", "0", ",", "-", "1", ")", "}", "}" ]
Set root line offset to the given index. @param {number} startIndex The start index to set. @returns {void}
[ "Set", "root", "line", "offset", "to", "the", "given", "index", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/html-indent.js#L280-L286
23,912
ota-meshi/eslint-plugin-lodash-template
lib/rules/html-indent.js
isDummyElement
function isDummyElement(node) { return ( !node.startTag && (node.name === "body" || node.name === "head" || node.name === "html") ) }
javascript
function isDummyElement(node) { return ( !node.startTag && (node.name === "body" || node.name === "head" || node.name === "html") ) }
[ "function", "isDummyElement", "(", "node", ")", "{", "return", "(", "!", "node", ".", "startTag", "&&", "(", "node", ".", "name", "===", "\"body\"", "||", "node", ".", "name", "===", "\"head\"", "||", "node", ".", "name", "===", "\"html\"", ")", ")", "}" ]
Check whether the given token is a dummy element. @param {Token} node The token to check. @returns {boolean} `true` if the token is a dummy element.
[ "Check", "whether", "the", "given", "token", "is", "a", "dummy", "element", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/html-indent.js#L345-L352
23,913
ota-meshi/eslint-plugin-lodash-template
lib/rules/html-indent.js
getStartToken
function getStartToken(elementNode) { if (!elementNode) { return null } if (elementNode.type !== "HTMLElement") { return null } if (isDummyElement(elementNode)) { return null } return elementNode.startTag || elementNode }
javascript
function getStartToken(elementNode) { if (!elementNode) { return null } if (elementNode.type !== "HTMLElement") { return null } if (isDummyElement(elementNode)) { return null } return elementNode.startTag || elementNode }
[ "function", "getStartToken", "(", "elementNode", ")", "{", "if", "(", "!", "elementNode", ")", "{", "return", "null", "}", "if", "(", "elementNode", ".", "type", "!==", "\"HTMLElement\"", ")", "{", "return", "null", "}", "if", "(", "isDummyElement", "(", "elementNode", ")", ")", "{", "return", "null", "}", "return", "elementNode", ".", "startTag", "||", "elementNode", "}" ]
Get the start token of Element @param {Node} elementNode The element node @returns {Token} The start token
[ "Get", "the", "start", "token", "of", "Element" ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/html-indent.js#L359-L370
23,914
ota-meshi/eslint-plugin-lodash-template
lib/rules/html-indent.js
findIndentationStartPunctuator
function findIndentationStartPunctuator(evaluate) { const searchIndex = evaluate.code.search(/(\S)\s*$/u) if (searchIndex < 0) { return null } const charIndex = evaluate.expressionStart.range[1] + searchIndex const node = sourceCode.getNodeByRangeIndex(charIndex) if (!node) { // comment only return null } const tokens = sourceCode .getTokens(node) .filter( t => t.range[0] <= evaluate.range[1] && t.range[1] >= evaluate.range[0] ) let targetToken = tokens.find( t => t.range[0] <= charIndex && charIndex < t.range[1] ) if (!targetToken) { targetToken = tokens .reverse() .find(t => t.range[1] <= charIndex) } let token = targetToken while (token) { if ( token.range[0] > evaluate.range[1] || token.range[1] < evaluate.range[0] ) { return null } if (isIndentationStartPunctuator(token)) { return token } if (isIndentationEndPunctuator(token)) { // skip const next = findPairOpenPunctuator(token) token = sourceCode.getTokenBefore(next) continue } token = sourceCode.getTokenBefore(token) } return null }
javascript
function findIndentationStartPunctuator(evaluate) { const searchIndex = evaluate.code.search(/(\S)\s*$/u) if (searchIndex < 0) { return null } const charIndex = evaluate.expressionStart.range[1] + searchIndex const node = sourceCode.getNodeByRangeIndex(charIndex) if (!node) { // comment only return null } const tokens = sourceCode .getTokens(node) .filter( t => t.range[0] <= evaluate.range[1] && t.range[1] >= evaluate.range[0] ) let targetToken = tokens.find( t => t.range[0] <= charIndex && charIndex < t.range[1] ) if (!targetToken) { targetToken = tokens .reverse() .find(t => t.range[1] <= charIndex) } let token = targetToken while (token) { if ( token.range[0] > evaluate.range[1] || token.range[1] < evaluate.range[0] ) { return null } if (isIndentationStartPunctuator(token)) { return token } if (isIndentationEndPunctuator(token)) { // skip const next = findPairOpenPunctuator(token) token = sourceCode.getTokenBefore(next) continue } token = sourceCode.getTokenBefore(token) } return null }
[ "function", "findIndentationStartPunctuator", "(", "evaluate", ")", "{", "const", "searchIndex", "=", "evaluate", ".", "code", ".", "search", "(", "/", "(\\S)\\s*$", "/", "u", ")", "if", "(", "searchIndex", "<", "0", ")", "{", "return", "null", "}", "const", "charIndex", "=", "evaluate", ".", "expressionStart", ".", "range", "[", "1", "]", "+", "searchIndex", "const", "node", "=", "sourceCode", ".", "getNodeByRangeIndex", "(", "charIndex", ")", "if", "(", "!", "node", ")", "{", "// comment only", "return", "null", "}", "const", "tokens", "=", "sourceCode", ".", "getTokens", "(", "node", ")", ".", "filter", "(", "t", "=>", "t", ".", "range", "[", "0", "]", "<=", "evaluate", ".", "range", "[", "1", "]", "&&", "t", ".", "range", "[", "1", "]", ">=", "evaluate", ".", "range", "[", "0", "]", ")", "let", "targetToken", "=", "tokens", ".", "find", "(", "t", "=>", "t", ".", "range", "[", "0", "]", "<=", "charIndex", "&&", "charIndex", "<", "t", ".", "range", "[", "1", "]", ")", "if", "(", "!", "targetToken", ")", "{", "targetToken", "=", "tokens", ".", "reverse", "(", ")", ".", "find", "(", "t", "=>", "t", ".", "range", "[", "1", "]", "<=", "charIndex", ")", "}", "let", "token", "=", "targetToken", "while", "(", "token", ")", "{", "if", "(", "token", ".", "range", "[", "0", "]", ">", "evaluate", ".", "range", "[", "1", "]", "||", "token", ".", "range", "[", "1", "]", "<", "evaluate", ".", "range", "[", "0", "]", ")", "{", "return", "null", "}", "if", "(", "isIndentationStartPunctuator", "(", "token", ")", ")", "{", "return", "token", "}", "if", "(", "isIndentationEndPunctuator", "(", "token", ")", ")", "{", "// skip", "const", "next", "=", "findPairOpenPunctuator", "(", "token", ")", "token", "=", "sourceCode", ".", "getTokenBefore", "(", "next", ")", "continue", "}", "token", "=", "sourceCode", ".", "getTokenBefore", "(", "token", ")", "}", "return", "null", "}" ]
Find indentation-start punctuator token, within micro-template evaluate. @param {Node} evaluate The micro-template evaluate to set @returns {Token} The indentation-start punctuator token.
[ "Find", "indentation", "-", "start", "punctuator", "token", "within", "micro", "-", "template", "evaluate", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/html-indent.js#L553-L603
23,915
ota-meshi/eslint-plugin-lodash-template
lib/rules/html-indent.js
findPairOpenPunctuator
function findPairOpenPunctuator(closeToken) { const closePunctuatorText = closeToken.value const isPairOpenPunctuator = closePunctuatorText === ")" ? isLeftParen : closePunctuatorText === "}" ? isLeftBrace : isLeftBracket let token = sourceCode.getTokenBefore(closeToken) while (token) { if (isPairOpenPunctuator(token)) { return token } if (isIndentationEndPunctuator(token)) { // skip const next = findPairOpenPunctuator(token) token = sourceCode.getTokenBefore(next) continue } token = sourceCode.getTokenBefore(token) } return null }
javascript
function findPairOpenPunctuator(closeToken) { const closePunctuatorText = closeToken.value const isPairOpenPunctuator = closePunctuatorText === ")" ? isLeftParen : closePunctuatorText === "}" ? isLeftBrace : isLeftBracket let token = sourceCode.getTokenBefore(closeToken) while (token) { if (isPairOpenPunctuator(token)) { return token } if (isIndentationEndPunctuator(token)) { // skip const next = findPairOpenPunctuator(token) token = sourceCode.getTokenBefore(next) continue } token = sourceCode.getTokenBefore(token) } return null }
[ "function", "findPairOpenPunctuator", "(", "closeToken", ")", "{", "const", "closePunctuatorText", "=", "closeToken", ".", "value", "const", "isPairOpenPunctuator", "=", "closePunctuatorText", "===", "\")\"", "?", "isLeftParen", ":", "closePunctuatorText", "===", "\"}\"", "?", "isLeftBrace", ":", "isLeftBracket", "let", "token", "=", "sourceCode", ".", "getTokenBefore", "(", "closeToken", ")", "while", "(", "token", ")", "{", "if", "(", "isPairOpenPunctuator", "(", "token", ")", ")", "{", "return", "token", "}", "if", "(", "isIndentationEndPunctuator", "(", "token", ")", ")", "{", "// skip", "const", "next", "=", "findPairOpenPunctuator", "(", "token", ")", "token", "=", "sourceCode", ".", "getTokenBefore", "(", "next", ")", "continue", "}", "token", "=", "sourceCode", ".", "getTokenBefore", "(", "token", ")", "}", "return", "null", "}" ]
Find pair open punctuator token. @param {Node} closeToken The close punctuator token @returns {Token} The indentation-start punctuator token.
[ "Find", "pair", "open", "punctuator", "token", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/html-indent.js#L610-L634
23,916
ota-meshi/eslint-plugin-lodash-template
lib/rules/html-indent.js
findPairClosePunctuator
function findPairClosePunctuator(openToken) { const openPunctuatorText = openToken.value const isPairClosePunctuator = openPunctuatorText === "(" ? isRightParen : openPunctuatorText === "{" ? isRightBrace : isRightBracket let token = sourceCode.getTokenAfter(openToken) while (token) { if (isPairClosePunctuator(token)) { return token } if (isIndentationStartPunctuator(token)) { // skip const next = findPairClosePunctuator(token) token = sourceCode.getTokenAfter(next) continue } token = sourceCode.getTokenAfter(token) } return null }
javascript
function findPairClosePunctuator(openToken) { const openPunctuatorText = openToken.value const isPairClosePunctuator = openPunctuatorText === "(" ? isRightParen : openPunctuatorText === "{" ? isRightBrace : isRightBracket let token = sourceCode.getTokenAfter(openToken) while (token) { if (isPairClosePunctuator(token)) { return token } if (isIndentationStartPunctuator(token)) { // skip const next = findPairClosePunctuator(token) token = sourceCode.getTokenAfter(next) continue } token = sourceCode.getTokenAfter(token) } return null }
[ "function", "findPairClosePunctuator", "(", "openToken", ")", "{", "const", "openPunctuatorText", "=", "openToken", ".", "value", "const", "isPairClosePunctuator", "=", "openPunctuatorText", "===", "\"(\"", "?", "isRightParen", ":", "openPunctuatorText", "===", "\"{\"", "?", "isRightBrace", ":", "isRightBracket", "let", "token", "=", "sourceCode", ".", "getTokenAfter", "(", "openToken", ")", "while", "(", "token", ")", "{", "if", "(", "isPairClosePunctuator", "(", "token", ")", ")", "{", "return", "token", "}", "if", "(", "isIndentationStartPunctuator", "(", "token", ")", ")", "{", "// skip", "const", "next", "=", "findPairClosePunctuator", "(", "token", ")", "token", "=", "sourceCode", ".", "getTokenAfter", "(", "next", ")", "continue", "}", "token", "=", "sourceCode", ".", "getTokenAfter", "(", "token", ")", "}", "return", "null", "}" ]
Find pair close punctuator token. @param {Node} openToken The open punctuator token @returns {Token} The indentation-end punctuator token.
[ "Find", "pair", "close", "punctuator", "token", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/html-indent.js#L641-L665
23,917
ota-meshi/eslint-plugin-lodash-template
lib/rules/html-indent.js
findSwitchCaseBodyInfoAtLineStart
function findSwitchCaseBodyInfoAtLineStart(line) { const index = sourceCode.getIndexFromLoc({ line, column: 0, }) let switchCaseNode = sourceCode.getNodeByRangeIndex(index) if ( !switchCaseNode || switchCaseNode.type === "SwitchStatement" ) { switchCaseNode = switchStatementNode.cases.find( (_token, i) => { const next = switchStatementNode.cases[i + 1] if (!next || index < next.range[0]) { return true } return false } ) } if ( !switchCaseNode || switchCaseNode.type !== "SwitchCase" ) { // not SwitchCase return null } if (switchCaseNode.test) { if (index < switchCaseNode.test.range[1]) { // not body return null } } else { // default: const fToken = sourceCode.getFirstToken(switchCaseNode) const colon = sourceCode.getTokenAfter( fToken, t => t.type === "Punctuator" && t.value === ":" ) if (index < colon.range[1]) { // not body return null } } if ( !equalsLocation( switchCaseNode.parent, switchStatementNode ) ) { // not target return null } const casesIndex = switchStatementNode.cases.findIndex(c => equalsLocation(c, switchCaseNode) ) const evaluate = evaluates.find( e => e.range[0] <= switchCaseNode.range[0] && switchCaseNode.range[0] < e.range[1] ) return { evaluate, casesIndex, node: switchCaseNode, } }
javascript
function findSwitchCaseBodyInfoAtLineStart(line) { const index = sourceCode.getIndexFromLoc({ line, column: 0, }) let switchCaseNode = sourceCode.getNodeByRangeIndex(index) if ( !switchCaseNode || switchCaseNode.type === "SwitchStatement" ) { switchCaseNode = switchStatementNode.cases.find( (_token, i) => { const next = switchStatementNode.cases[i + 1] if (!next || index < next.range[0]) { return true } return false } ) } if ( !switchCaseNode || switchCaseNode.type !== "SwitchCase" ) { // not SwitchCase return null } if (switchCaseNode.test) { if (index < switchCaseNode.test.range[1]) { // not body return null } } else { // default: const fToken = sourceCode.getFirstToken(switchCaseNode) const colon = sourceCode.getTokenAfter( fToken, t => t.type === "Punctuator" && t.value === ":" ) if (index < colon.range[1]) { // not body return null } } if ( !equalsLocation( switchCaseNode.parent, switchStatementNode ) ) { // not target return null } const casesIndex = switchStatementNode.cases.findIndex(c => equalsLocation(c, switchCaseNode) ) const evaluate = evaluates.find( e => e.range[0] <= switchCaseNode.range[0] && switchCaseNode.range[0] < e.range[1] ) return { evaluate, casesIndex, node: switchCaseNode, } }
[ "function", "findSwitchCaseBodyInfoAtLineStart", "(", "line", ")", "{", "const", "index", "=", "sourceCode", ".", "getIndexFromLoc", "(", "{", "line", ",", "column", ":", "0", ",", "}", ")", "let", "switchCaseNode", "=", "sourceCode", ".", "getNodeByRangeIndex", "(", "index", ")", "if", "(", "!", "switchCaseNode", "||", "switchCaseNode", ".", "type", "===", "\"SwitchStatement\"", ")", "{", "switchCaseNode", "=", "switchStatementNode", ".", "cases", ".", "find", "(", "(", "_token", ",", "i", ")", "=>", "{", "const", "next", "=", "switchStatementNode", ".", "cases", "[", "i", "+", "1", "]", "if", "(", "!", "next", "||", "index", "<", "next", ".", "range", "[", "0", "]", ")", "{", "return", "true", "}", "return", "false", "}", ")", "}", "if", "(", "!", "switchCaseNode", "||", "switchCaseNode", ".", "type", "!==", "\"SwitchCase\"", ")", "{", "// not SwitchCase", "return", "null", "}", "if", "(", "switchCaseNode", ".", "test", ")", "{", "if", "(", "index", "<", "switchCaseNode", ".", "test", ".", "range", "[", "1", "]", ")", "{", "// not body", "return", "null", "}", "}", "else", "{", "// default:", "const", "fToken", "=", "sourceCode", ".", "getFirstToken", "(", "switchCaseNode", ")", "const", "colon", "=", "sourceCode", ".", "getTokenAfter", "(", "fToken", ",", "t", "=>", "t", ".", "type", "===", "\"Punctuator\"", "&&", "t", ".", "value", "===", "\":\"", ")", "if", "(", "index", "<", "colon", ".", "range", "[", "1", "]", ")", "{", "// not body", "return", "null", "}", "}", "if", "(", "!", "equalsLocation", "(", "switchCaseNode", ".", "parent", ",", "switchStatementNode", ")", ")", "{", "// not target", "return", "null", "}", "const", "casesIndex", "=", "switchStatementNode", ".", "cases", ".", "findIndex", "(", "c", "=>", "equalsLocation", "(", "c", ",", "switchCaseNode", ")", ")", "const", "evaluate", "=", "evaluates", ".", "find", "(", "e", "=>", "e", ".", "range", "[", "0", "]", "<=", "switchCaseNode", ".", "range", "[", "0", "]", "&&", "switchCaseNode", ".", "range", "[", "0", "]", "<", "e", ".", "range", "[", "1", "]", ")", "return", "{", "evaluate", ",", "casesIndex", ",", "node", ":", "switchCaseNode", ",", "}", "}" ]
Find evaluate token of SwitchCase body from the given line. @param {number} line The line no to set. @returns {Token} The evaluate token of SwitchCase.
[ "Find", "evaluate", "token", "of", "SwitchCase", "body", "from", "the", "given", "line", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/html-indent.js#L705-L773
23,918
ota-meshi/eslint-plugin-lodash-template
lib/rules/html-indent.js
inIgnore
function inIgnore(line) { const index = sourceCode.getIndexFromLoc({ line, column: 0, }) return ignoreRanges.find( range => range[0] <= index && index < range[1] ) }
javascript
function inIgnore(line) { const index = sourceCode.getIndexFromLoc({ line, column: 0, }) return ignoreRanges.find( range => range[0] <= index && index < range[1] ) }
[ "function", "inIgnore", "(", "line", ")", "{", "const", "index", "=", "sourceCode", ".", "getIndexFromLoc", "(", "{", "line", ",", "column", ":", "0", ",", "}", ")", "return", "ignoreRanges", ".", "find", "(", "range", "=>", "range", "[", "0", "]", "<=", "index", "&&", "index", "<", "range", "[", "1", "]", ")", "}" ]
Check whether the line start is in ignore range. @param {number} line The line. @returns {boolean} `true` if the line start is in ignore range.
[ "Check", "whether", "the", "line", "start", "is", "in", "ignore", "range", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/html-indent.js#L895-L903
23,919
ota-meshi/eslint-plugin-lodash-template
lib/rules/template-tag-spacing.js
equalLine
function equalLine(index1, index2) { return ( sourceCode.getLocFromIndex(index1).line === sourceCode.getLocFromIndex(index2).line ) }
javascript
function equalLine(index1, index2) { return ( sourceCode.getLocFromIndex(index1).line === sourceCode.getLocFromIndex(index2).line ) }
[ "function", "equalLine", "(", "index1", ",", "index2", ")", "{", "return", "(", "sourceCode", ".", "getLocFromIndex", "(", "index1", ")", ".", "line", "===", "sourceCode", ".", "getLocFromIndex", "(", "index2", ")", ".", "line", ")", "}" ]
Check whether the line numbers in the given indices are equal. @param {number} index1 The index @param {number} index2 The index @returns {boolean} `true` if the line numbers in the indices are equal.
[ "Check", "whether", "the", "line", "numbers", "in", "the", "given", "indices", "are", "equal", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/template-tag-spacing.js#L91-L96
23,920
ota-meshi/eslint-plugin-lodash-template
lib/parser/micro-template-eslint-parser.js
getDelimitersFinalMeans
function getDelimitersFinalMeans(text, innerCode) { const codeStart = text.indexOf(innerCode) const codeEnd = codeStart + innerCode.length return [text.slice(0, codeStart), text.slice(codeEnd)] }
javascript
function getDelimitersFinalMeans(text, innerCode) { const codeStart = text.indexOf(innerCode) const codeEnd = codeStart + innerCode.length return [text.slice(0, codeStart), text.slice(codeEnd)] }
[ "function", "getDelimitersFinalMeans", "(", "text", ",", "innerCode", ")", "{", "const", "codeStart", "=", "text", ".", "indexOf", "(", "innerCode", ")", "const", "codeEnd", "=", "codeStart", "+", "innerCode", ".", "length", "return", "[", "text", ".", "slice", "(", "0", ",", "codeStart", ")", ",", "text", ".", "slice", "(", "codeEnd", ")", "]", "}" ]
Get delimiters from the given text and inner text. @param {string} text The hit text. @param {string} innerCode The hit inner text. @returns {Array} The delimiters result.
[ "Get", "delimiters", "from", "the", "given", "text", "and", "inner", "text", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/parser/micro-template-eslint-parser.js#L21-L25
23,921
ota-meshi/eslint-plugin-lodash-template
lib/parser/micro-template-eslint-parser.js
settingToRegExpInfo
function settingToRegExpInfo(val, defaultDelimiters) { if (!val) { return { pattern: `${defaultDelimiters[0]}([\\s\\S]*?)${ defaultDelimiters[1] }`, getDelimiters: () => defaultDelimiters, } } if (Array.isArray(val)) { return { pattern: `${escapeRegExp(val[0])}([\\s\\S]*?)${escapeRegExp( val[1] )}`, getDelimiters: () => val, } } const source = val instanceof RegExp ? val.source : `${val}` const pattern = source.indexOf("([\\s\\S]+?)") >= 0 ? source.replace("([\\s\\S]+?)", "([\\s\\S]*?)") : source.indexOf("([\\S\\s]+?)") >= 0 ? source.replace("([\\S\\s]+?)", "([\\s\\S]*?)") : source let getDelimiters = undefined const delmPattern = pattern.split("([\\s\\S]*?)") if (delmPattern.length === 2) { const re = new RegExp( delmPattern.map(s => `(${s})`).join("([\\s\\S]*?)"), "u" ) getDelimiters = (text, innerCode) => { const r = text.match(re) if (r) { return [r[1], r[3]] } return getDelimitersFinalMeans(text, innerCode) } } else { getDelimiters = getDelimitersFinalMeans } return { pattern, getDelimiters, } }
javascript
function settingToRegExpInfo(val, defaultDelimiters) { if (!val) { return { pattern: `${defaultDelimiters[0]}([\\s\\S]*?)${ defaultDelimiters[1] }`, getDelimiters: () => defaultDelimiters, } } if (Array.isArray(val)) { return { pattern: `${escapeRegExp(val[0])}([\\s\\S]*?)${escapeRegExp( val[1] )}`, getDelimiters: () => val, } } const source = val instanceof RegExp ? val.source : `${val}` const pattern = source.indexOf("([\\s\\S]+?)") >= 0 ? source.replace("([\\s\\S]+?)", "([\\s\\S]*?)") : source.indexOf("([\\S\\s]+?)") >= 0 ? source.replace("([\\S\\s]+?)", "([\\s\\S]*?)") : source let getDelimiters = undefined const delmPattern = pattern.split("([\\s\\S]*?)") if (delmPattern.length === 2) { const re = new RegExp( delmPattern.map(s => `(${s})`).join("([\\s\\S]*?)"), "u" ) getDelimiters = (text, innerCode) => { const r = text.match(re) if (r) { return [r[1], r[3]] } return getDelimitersFinalMeans(text, innerCode) } } else { getDelimiters = getDelimitersFinalMeans } return { pattern, getDelimiters, } }
[ "function", "settingToRegExpInfo", "(", "val", ",", "defaultDelimiters", ")", "{", "if", "(", "!", "val", ")", "{", "return", "{", "pattern", ":", "`", "${", "defaultDelimiters", "[", "0", "]", "}", "\\\\", "\\\\", "${", "defaultDelimiters", "[", "1", "]", "}", "`", ",", "getDelimiters", ":", "(", ")", "=>", "defaultDelimiters", ",", "}", "}", "if", "(", "Array", ".", "isArray", "(", "val", ")", ")", "{", "return", "{", "pattern", ":", "`", "${", "escapeRegExp", "(", "val", "[", "0", "]", ")", "}", "\\\\", "\\\\", "${", "escapeRegExp", "(", "val", "[", "1", "]", ")", "}", "`", ",", "getDelimiters", ":", "(", ")", "=>", "val", ",", "}", "}", "const", "source", "=", "val", "instanceof", "RegExp", "?", "val", ".", "source", ":", "`", "${", "val", "}", "`", "const", "pattern", "=", "source", ".", "indexOf", "(", "\"([\\\\s\\\\S]+?)\"", ")", ">=", "0", "?", "source", ".", "replace", "(", "\"([\\\\s\\\\S]+?)\"", ",", "\"([\\\\s\\\\S]*?)\"", ")", ":", "source", ".", "indexOf", "(", "\"([\\\\S\\\\s]+?)\"", ")", ">=", "0", "?", "source", ".", "replace", "(", "\"([\\\\S\\\\s]+?)\"", ",", "\"([\\\\s\\\\S]*?)\"", ")", ":", "source", "let", "getDelimiters", "=", "undefined", "const", "delmPattern", "=", "pattern", ".", "split", "(", "\"([\\\\s\\\\S]*?)\"", ")", "if", "(", "delmPattern", ".", "length", "===", "2", ")", "{", "const", "re", "=", "new", "RegExp", "(", "delmPattern", ".", "map", "(", "s", "=>", "`", "${", "s", "}", "`", ")", ".", "join", "(", "\"([\\\\s\\\\S]*?)\"", ")", ",", "\"u\"", ")", "getDelimiters", "=", "(", "text", ",", "innerCode", ")", "=>", "{", "const", "r", "=", "text", ".", "match", "(", "re", ")", "if", "(", "r", ")", "{", "return", "[", "r", "[", "1", "]", ",", "r", "[", "3", "]", "]", "}", "return", "getDelimitersFinalMeans", "(", "text", ",", "innerCode", ")", "}", "}", "else", "{", "getDelimiters", "=", "getDelimitersFinalMeans", "}", "return", "{", "pattern", ",", "getDelimiters", ",", "}", "}" ]
Delimiters setting to RegExp source @param {*} val The delimiter settings. @param {Array} defaultDelimiters The default delimiters. @returns {string} The delimiters RegExp source.
[ "Delimiters", "setting", "to", "RegExp", "source" ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/parser/micro-template-eslint-parser.js#L43-L90
23,922
ota-meshi/eslint-plugin-lodash-template
lib/parser/micro-template-eslint-parser.js
parseTemplate
function parseTemplate(code, parserOptions) { const sourceCodeStore = new SourceCodeStore(code) // 文字位置をそのままにしてscriptとhtmlを分解 let script = "" let pre = 0 let template = "" const microTemplateTokens = [] // テンプレートTokens for (const token of genMicroTemplateTokens( code, parserOptions, sourceCodeStore )) { microTemplateTokens.push(token) const start = token.start const end = token.end const part = code.slice(pre, start) script += replaceToWhitespace(part) template += part const scriptBeforeBase = token.expressionStart.chars const scriptAfterBase = token.expressionEnd.chars const scriptBefore = replaceToWhitespace(scriptBeforeBase) let scriptAfter = replaceToWhitespace(scriptAfterBase) if (token.type !== "MicroTemplateEvaluate") { scriptAfter = scriptAfter.replace(/ /u, ";") } script += `${scriptBefore}${token.code}${scriptAfter}` template += replaceToWhitespace(code.slice(start, end)) pre = end } const part = code.slice(pre, code.length) script += replaceToWhitespace(part) template += part const scriptResult = parseScript(script, parserOptions) sourceCodeStore.template = template sourceCodeStore.script = script const service = new MicroTemplateService({ code, template, script, microTemplateTokens, sourceCodeStore, ast: scriptResult.ast, }) container.addService(parserOptions.filePath, service) scriptResult.services = Object.assign(scriptResult.services || {}, { getMicroTemplateService() { return service }, }) return scriptResult }
javascript
function parseTemplate(code, parserOptions) { const sourceCodeStore = new SourceCodeStore(code) // 文字位置をそのままにしてscriptとhtmlを分解 let script = "" let pre = 0 let template = "" const microTemplateTokens = [] // テンプレートTokens for (const token of genMicroTemplateTokens( code, parserOptions, sourceCodeStore )) { microTemplateTokens.push(token) const start = token.start const end = token.end const part = code.slice(pre, start) script += replaceToWhitespace(part) template += part const scriptBeforeBase = token.expressionStart.chars const scriptAfterBase = token.expressionEnd.chars const scriptBefore = replaceToWhitespace(scriptBeforeBase) let scriptAfter = replaceToWhitespace(scriptAfterBase) if (token.type !== "MicroTemplateEvaluate") { scriptAfter = scriptAfter.replace(/ /u, ";") } script += `${scriptBefore}${token.code}${scriptAfter}` template += replaceToWhitespace(code.slice(start, end)) pre = end } const part = code.slice(pre, code.length) script += replaceToWhitespace(part) template += part const scriptResult = parseScript(script, parserOptions) sourceCodeStore.template = template sourceCodeStore.script = script const service = new MicroTemplateService({ code, template, script, microTemplateTokens, sourceCodeStore, ast: scriptResult.ast, }) container.addService(parserOptions.filePath, service) scriptResult.services = Object.assign(scriptResult.services || {}, { getMicroTemplateService() { return service }, }) return scriptResult }
[ "function", "parseTemplate", "(", "code", ",", "parserOptions", ")", "{", "const", "sourceCodeStore", "=", "new", "SourceCodeStore", "(", "code", ")", "// 文字位置をそのままにしてscriptとhtmlを分解", "let", "script", "=", "\"\"", "let", "pre", "=", "0", "let", "template", "=", "\"\"", "const", "microTemplateTokens", "=", "[", "]", "// テンプレートTokens", "for", "(", "const", "token", "of", "genMicroTemplateTokens", "(", "code", ",", "parserOptions", ",", "sourceCodeStore", ")", ")", "{", "microTemplateTokens", ".", "push", "(", "token", ")", "const", "start", "=", "token", ".", "start", "const", "end", "=", "token", ".", "end", "const", "part", "=", "code", ".", "slice", "(", "pre", ",", "start", ")", "script", "+=", "replaceToWhitespace", "(", "part", ")", "template", "+=", "part", "const", "scriptBeforeBase", "=", "token", ".", "expressionStart", ".", "chars", "const", "scriptAfterBase", "=", "token", ".", "expressionEnd", ".", "chars", "const", "scriptBefore", "=", "replaceToWhitespace", "(", "scriptBeforeBase", ")", "let", "scriptAfter", "=", "replaceToWhitespace", "(", "scriptAfterBase", ")", "if", "(", "token", ".", "type", "!==", "\"MicroTemplateEvaluate\"", ")", "{", "scriptAfter", "=", "scriptAfter", ".", "replace", "(", "/", " ", "/", "u", ",", "\";\"", ")", "}", "script", "+=", "`", "${", "scriptBefore", "}", "${", "token", ".", "code", "}", "${", "scriptAfter", "}", "`", "template", "+=", "replaceToWhitespace", "(", "code", ".", "slice", "(", "start", ",", "end", ")", ")", "pre", "=", "end", "}", "const", "part", "=", "code", ".", "slice", "(", "pre", ",", "code", ".", "length", ")", "script", "+=", "replaceToWhitespace", "(", "part", ")", "template", "+=", "part", "const", "scriptResult", "=", "parseScript", "(", "script", ",", "parserOptions", ")", "sourceCodeStore", ".", "template", "=", "template", "sourceCodeStore", ".", "script", "=", "script", "const", "service", "=", "new", "MicroTemplateService", "(", "{", "code", ",", "template", ",", "script", ",", "microTemplateTokens", ",", "sourceCodeStore", ",", "ast", ":", "scriptResult", ".", "ast", ",", "}", ")", "container", ".", "addService", "(", "parserOptions", ".", "filePath", ",", "service", ")", "scriptResult", ".", "services", "=", "Object", ".", "assign", "(", "scriptResult", ".", "services", "||", "{", "}", ",", "{", "getMicroTemplateService", "(", ")", "{", "return", "service", "}", ",", "}", ")", "return", "scriptResult", "}" ]
Parse the given template. @param {string} code The template to parse. @param {object} parserOptions The parser options. @returns {object} The parsing result.
[ "Parse", "the", "given", "template", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/parser/micro-template-eslint-parser.js#L184-L242
23,923
ota-meshi/eslint-plugin-lodash-template
lib/parser/micro-template-eslint-parser.js
parseScript
function parseScript(code, parserOptions) { const parser = parserOptions.parser === "espree" || !parserOptions.parser ? require("espree") // eslint-disable-line @mysticatea/node/no-extraneous-require : require(parserOptions.parser) const scriptParserOptions = Object.assign({}, parserOptions) delete scriptParserOptions.parser const result = typeof parser.parseForESLint === "function" ? parser.parseForESLint(code, scriptParserOptions) : parser.parse(code, scriptParserOptions) if (result.ast) { return result } return { ast: result, } }
javascript
function parseScript(code, parserOptions) { const parser = parserOptions.parser === "espree" || !parserOptions.parser ? require("espree") // eslint-disable-line @mysticatea/node/no-extraneous-require : require(parserOptions.parser) const scriptParserOptions = Object.assign({}, parserOptions) delete scriptParserOptions.parser const result = typeof parser.parseForESLint === "function" ? parser.parseForESLint(code, scriptParserOptions) : parser.parse(code, scriptParserOptions) if (result.ast) { return result } return { ast: result, } }
[ "function", "parseScript", "(", "code", ",", "parserOptions", ")", "{", "const", "parser", "=", "parserOptions", ".", "parser", "===", "\"espree\"", "||", "!", "parserOptions", ".", "parser", "?", "require", "(", "\"espree\"", ")", "// eslint-disable-line @mysticatea/node/no-extraneous-require", ":", "require", "(", "parserOptions", ".", "parser", ")", "const", "scriptParserOptions", "=", "Object", ".", "assign", "(", "{", "}", ",", "parserOptions", ")", "delete", "scriptParserOptions", ".", "parser", "const", "result", "=", "typeof", "parser", ".", "parseForESLint", "===", "\"function\"", "?", "parser", ".", "parseForESLint", "(", "code", ",", "scriptParserOptions", ")", ":", "parser", ".", "parse", "(", "code", ",", "scriptParserOptions", ")", "if", "(", "result", ".", "ast", ")", "{", "return", "result", "}", "return", "{", "ast", ":", "result", ",", "}", "}" ]
Parse the given script source code. @param {string} code The script source code to parse. @param {object} parserOptions The parser options. @returns {object} The parsing result.
[ "Parse", "the", "given", "script", "source", "code", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/parser/micro-template-eslint-parser.js#L250-L267
23,924
ota-meshi/eslint-plugin-lodash-template
lib/parser/micro-template-eslint-parser.js
isHtmlFile
function isHtmlFile(code, options) { const filePath = typeof options.filePath === "string" ? options.filePath : "unknown.js" for (const ext of container.targetExtensions) { if (filePath.endsWith(ext)) { return true } } if (filePath.endsWith(".vue")) { return false } return /^\s*</u.test(code) }
javascript
function isHtmlFile(code, options) { const filePath = typeof options.filePath === "string" ? options.filePath : "unknown.js" for (const ext of container.targetExtensions) { if (filePath.endsWith(ext)) { return true } } if (filePath.endsWith(".vue")) { return false } return /^\s*</u.test(code) }
[ "function", "isHtmlFile", "(", "code", ",", "options", ")", "{", "const", "filePath", "=", "typeof", "options", ".", "filePath", "===", "\"string\"", "?", "options", ".", "filePath", ":", "\"unknown.js\"", "for", "(", "const", "ext", "of", "container", ".", "targetExtensions", ")", "{", "if", "(", "filePath", ".", "endsWith", "(", "ext", ")", ")", "{", "return", "true", "}", "}", "if", "(", "filePath", ".", "endsWith", "(", "\".vue\"", ")", ")", "{", "return", "false", "}", "return", "/", "^\\s*<", "/", "u", ".", "test", "(", "code", ")", "}" ]
Check whether the code is a HTML. @param {string} code The source code to check. @param {object} options The parser options. @returns {boolean} `true` if the source code is a HTML.
[ "Check", "whether", "the", "code", "is", "a", "HTML", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/parser/micro-template-eslint-parser.js#L275-L287
23,925
ota-meshi/eslint-plugin-lodash-template
lib/parser/micro-template-eslint-parser.js
parseForESLint
function parseForESLint(code, options) { const opts = options || {} if (!isHtmlFile(code, opts)) { return parseScript(code, opts) } return parseTemplate(code, opts) }
javascript
function parseForESLint(code, options) { const opts = options || {} if (!isHtmlFile(code, opts)) { return parseScript(code, opts) } return parseTemplate(code, opts) }
[ "function", "parseForESLint", "(", "code", ",", "options", ")", "{", "const", "opts", "=", "options", "||", "{", "}", "if", "(", "!", "isHtmlFile", "(", "code", ",", "opts", ")", ")", "{", "return", "parseScript", "(", "code", ",", "opts", ")", "}", "return", "parseTemplate", "(", "code", ",", "opts", ")", "}" ]
Parse the given source code. @param {string} code The source code to parse. @param {object} options The parser options. @returns {object} The parsing result.
[ "Parse", "the", "given", "source", "code", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/parser/micro-template-eslint-parser.js#L295-L301
23,926
ota-meshi/eslint-plugin-lodash-template
lib/rules/no-irregular-whitespace.js
getStartTagIgnoreTokens
function getStartTagIgnoreTokens(startTag) { if (!skipAttrValues) { return [] } const tokens = [] for (const attr of startTag.attributes) { tokens.push(attr.valueToken) } for (const attr of startTag.ignoredAttributes) { tokens.push(attr.valueToken) } return tokens.filter(t => Boolean(t)) }
javascript
function getStartTagIgnoreTokens(startTag) { if (!skipAttrValues) { return [] } const tokens = [] for (const attr of startTag.attributes) { tokens.push(attr.valueToken) } for (const attr of startTag.ignoredAttributes) { tokens.push(attr.valueToken) } return tokens.filter(t => Boolean(t)) }
[ "function", "getStartTagIgnoreTokens", "(", "startTag", ")", "{", "if", "(", "!", "skipAttrValues", ")", "{", "return", "[", "]", "}", "const", "tokens", "=", "[", "]", "for", "(", "const", "attr", "of", "startTag", ".", "attributes", ")", "{", "tokens", ".", "push", "(", "attr", ".", "valueToken", ")", "}", "for", "(", "const", "attr", "of", "startTag", ".", "ignoredAttributes", ")", "{", "tokens", ".", "push", "(", "attr", ".", "valueToken", ")", "}", "return", "tokens", ".", "filter", "(", "t", "=>", "Boolean", "(", "t", ")", ")", "}" ]
Get the start tag ignore tokens array @param {HTMLStartTag} startTag The start tag @returns {Array} Then tokens
[ "Get", "the", "start", "tag", "ignore", "tokens", "array" ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/no-irregular-whitespace.js#L93-L107
23,927
ota-meshi/eslint-plugin-lodash-template
lib/rules/no-irregular-whitespace.js
checkForIrregularWhitespace
function checkForIrregularWhitespace(node, ignoreTokens) { const text = sourceCode.text.slice(node.range[0], node.range[1]) let match = undefined /** * Check whether the index is in ignore location. * @param {number} index The index. * @returns {boolean} `true` if the index is in ignore location. */ function isIgnoreLocation(index) { return ( ignoreTokens.find( t => t.range[0] <= index && index < t.range[1] ) || templateTokens.find( t => t.range[0] <= index && index < t.range[1] ) ) } while ((match = IRREGULAR_WHITESPACE.exec(text)) !== null) { const index = node.range[0] + match.index if (isIgnoreLocation(index)) { continue } const code = `0000${sourceCode.text[index] .charCodeAt(0) .toString(16)}` .slice(-4) .toUpperCase() context.report({ loc: sourceCode.getLocFromIndex(index), messageId: "unexpected", data: { code }, fix: defineWhitespaceFix(index), }) } while ((match = IRREGULAR_LINE_TERMINATORS.exec(text)) !== null) { const index = node.range[0] + match.index if (isIgnoreLocation(index)) { continue } const code = `0000${sourceCode.text[index] .charCodeAt(0) .toString(16)}` .slice(-4) .toUpperCase() context.report({ loc: sourceCode.getLocFromIndex(index), messageId: "unexpected", data: { code }, fix: defineLineTerminatorsFix(index), }) } }
javascript
function checkForIrregularWhitespace(node, ignoreTokens) { const text = sourceCode.text.slice(node.range[0], node.range[1]) let match = undefined /** * Check whether the index is in ignore location. * @param {number} index The index. * @returns {boolean} `true` if the index is in ignore location. */ function isIgnoreLocation(index) { return ( ignoreTokens.find( t => t.range[0] <= index && index < t.range[1] ) || templateTokens.find( t => t.range[0] <= index && index < t.range[1] ) ) } while ((match = IRREGULAR_WHITESPACE.exec(text)) !== null) { const index = node.range[0] + match.index if (isIgnoreLocation(index)) { continue } const code = `0000${sourceCode.text[index] .charCodeAt(0) .toString(16)}` .slice(-4) .toUpperCase() context.report({ loc: sourceCode.getLocFromIndex(index), messageId: "unexpected", data: { code }, fix: defineWhitespaceFix(index), }) } while ((match = IRREGULAR_LINE_TERMINATORS.exec(text)) !== null) { const index = node.range[0] + match.index if (isIgnoreLocation(index)) { continue } const code = `0000${sourceCode.text[index] .charCodeAt(0) .toString(16)}` .slice(-4) .toUpperCase() context.report({ loc: sourceCode.getLocFromIndex(index), messageId: "unexpected", data: { code }, fix: defineLineTerminatorsFix(index), }) } }
[ "function", "checkForIrregularWhitespace", "(", "node", ",", "ignoreTokens", ")", "{", "const", "text", "=", "sourceCode", ".", "text", ".", "slice", "(", "node", ".", "range", "[", "0", "]", ",", "node", ".", "range", "[", "1", "]", ")", "let", "match", "=", "undefined", "/**\n * Check whether the index is in ignore location.\n * @param {number} index The index.\n * @returns {boolean} `true` if the index is in ignore location.\n */", "function", "isIgnoreLocation", "(", "index", ")", "{", "return", "(", "ignoreTokens", ".", "find", "(", "t", "=>", "t", ".", "range", "[", "0", "]", "<=", "index", "&&", "index", "<", "t", ".", "range", "[", "1", "]", ")", "||", "templateTokens", ".", "find", "(", "t", "=>", "t", ".", "range", "[", "0", "]", "<=", "index", "&&", "index", "<", "t", ".", "range", "[", "1", "]", ")", ")", "}", "while", "(", "(", "match", "=", "IRREGULAR_WHITESPACE", ".", "exec", "(", "text", ")", ")", "!==", "null", ")", "{", "const", "index", "=", "node", ".", "range", "[", "0", "]", "+", "match", ".", "index", "if", "(", "isIgnoreLocation", "(", "index", ")", ")", "{", "continue", "}", "const", "code", "=", "`", "${", "sourceCode", ".", "text", "[", "index", "]", ".", "charCodeAt", "(", "0", ")", ".", "toString", "(", "16", ")", "}", "`", ".", "slice", "(", "-", "4", ")", ".", "toUpperCase", "(", ")", "context", ".", "report", "(", "{", "loc", ":", "sourceCode", ".", "getLocFromIndex", "(", "index", ")", ",", "messageId", ":", "\"unexpected\"", ",", "data", ":", "{", "code", "}", ",", "fix", ":", "defineWhitespaceFix", "(", "index", ")", ",", "}", ")", "}", "while", "(", "(", "match", "=", "IRREGULAR_LINE_TERMINATORS", ".", "exec", "(", "text", ")", ")", "!==", "null", ")", "{", "const", "index", "=", "node", ".", "range", "[", "0", "]", "+", "match", ".", "index", "if", "(", "isIgnoreLocation", "(", "index", ")", ")", "{", "continue", "}", "const", "code", "=", "`", "${", "sourceCode", ".", "text", "[", "index", "]", ".", "charCodeAt", "(", "0", ")", ".", "toString", "(", "16", ")", "}", "`", ".", "slice", "(", "-", "4", ")", ".", "toUpperCase", "(", ")", "context", ".", "report", "(", "{", "loc", ":", "sourceCode", ".", "getLocFromIndex", "(", "index", ")", ",", "messageId", ":", "\"unexpected\"", ",", "data", ":", "{", "code", "}", ",", "fix", ":", "defineLineTerminatorsFix", "(", "index", ")", ",", "}", ")", "}", "}" ]
Checks the source for irregular whitespace @param {ASTNode} node The tag node @param {Token[]} ignoreTokens The ignore location tokens @returns {void}
[ "Checks", "the", "source", "for", "irregular", "whitespace" ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/no-irregular-whitespace.js#L133-L192
23,928
ota-meshi/eslint-plugin-lodash-template
lib/rules/no-irregular-whitespace.js
isIgnoreLocation
function isIgnoreLocation(index) { return ( ignoreTokens.find( t => t.range[0] <= index && index < t.range[1] ) || templateTokens.find( t => t.range[0] <= index && index < t.range[1] ) ) }
javascript
function isIgnoreLocation(index) { return ( ignoreTokens.find( t => t.range[0] <= index && index < t.range[1] ) || templateTokens.find( t => t.range[0] <= index && index < t.range[1] ) ) }
[ "function", "isIgnoreLocation", "(", "index", ")", "{", "return", "(", "ignoreTokens", ".", "find", "(", "t", "=>", "t", ".", "range", "[", "0", "]", "<=", "index", "&&", "index", "<", "t", ".", "range", "[", "1", "]", ")", "||", "templateTokens", ".", "find", "(", "t", "=>", "t", ".", "range", "[", "0", "]", "<=", "index", "&&", "index", "<", "t", ".", "range", "[", "1", "]", ")", ")", "}" ]
Check whether the index is in ignore location. @param {number} index The index. @returns {boolean} `true` if the index is in ignore location.
[ "Check", "whether", "the", "index", "is", "in", "ignore", "location", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/no-irregular-whitespace.js#L142-L151
23,929
ota-meshi/eslint-plugin-lodash-template
lib/utils/rules.js
collectRules
function collectRules(category) { return rules.reduce((obj, rule) => { if (!category || rule.meta.docs.category === category) { obj[rule.meta.docs.ruleId] = "error" } return obj }, {}) }
javascript
function collectRules(category) { return rules.reduce((obj, rule) => { if (!category || rule.meta.docs.category === category) { obj[rule.meta.docs.ruleId] = "error" } return obj }, {}) }
[ "function", "collectRules", "(", "category", ")", "{", "return", "rules", ".", "reduce", "(", "(", "obj", ",", "rule", ")", "=>", "{", "if", "(", "!", "category", "||", "rule", ".", "meta", ".", "docs", ".", "category", "===", "category", ")", "{", "obj", "[", "rule", ".", "meta", ".", "docs", ".", "ruleId", "]", "=", "\"error\"", "}", "return", "obj", "}", ",", "{", "}", ")", "}" ]
Collect the rules @param {string} category category @returns {Array} rules
[ "Collect", "the", "rules" ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/utils/rules.js#L143-L150
23,930
ota-meshi/eslint-plugin-lodash-template
lib/service/html-parser.js
buildChildTokens
function buildChildTokens(node, parentToken, html, sourceCodeStore, lastIndex) { return node.childNodes.map(child => { const token = parse5NodeToToken( child, parentToken, html, sourceCodeStore, lastIndex ) token.parent = parentToken return token }) }
javascript
function buildChildTokens(node, parentToken, html, sourceCodeStore, lastIndex) { return node.childNodes.map(child => { const token = parse5NodeToToken( child, parentToken, html, sourceCodeStore, lastIndex ) token.parent = parentToken return token }) }
[ "function", "buildChildTokens", "(", "node", ",", "parentToken", ",", "html", ",", "sourceCodeStore", ",", "lastIndex", ")", "{", "return", "node", ".", "childNodes", ".", "map", "(", "child", "=>", "{", "const", "token", "=", "parse5NodeToToken", "(", "child", ",", "parentToken", ",", "html", ",", "sourceCodeStore", ",", "lastIndex", ")", "token", ".", "parent", "=", "parentToken", "return", "token", "}", ")", "}" ]
Create child tokens from Node childNodes @param {object} node The node from parse5. @param {object} parentToken The parent token. @param {string} html The html source code to parse. @param {SourceCodeStore} sourceCodeStore The sourceCodeStore. @param {number} lastIndex The last index. @returns {Array} The child tokens.
[ "Create", "child", "tokens", "from", "Node", "childNodes" ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/service/html-parser.js#L33-L45
23,931
ota-meshi/eslint-plugin-lodash-template
lib/service/html-parser.js
defineRootTokenBuilder
function defineRootTokenBuilder(Type) { return (node, _parentToken, html, sourceCodeStore, lastIndex) => { const token = new Type(html, 0, lastIndex, sourceCodeStore) token.children = buildChildTokens( node, token, html, sourceCodeStore, lastIndex ) return token } }
javascript
function defineRootTokenBuilder(Type) { return (node, _parentToken, html, sourceCodeStore, lastIndex) => { const token = new Type(html, 0, lastIndex, sourceCodeStore) token.children = buildChildTokens( node, token, html, sourceCodeStore, lastIndex ) return token } }
[ "function", "defineRootTokenBuilder", "(", "Type", ")", "{", "return", "(", "node", ",", "_parentToken", ",", "html", ",", "sourceCodeStore", ",", "lastIndex", ")", "=>", "{", "const", "token", "=", "new", "Type", "(", "html", ",", "0", ",", "lastIndex", ",", "sourceCodeStore", ")", "token", ".", "children", "=", "buildChildTokens", "(", "node", ",", "token", ",", "html", ",", "sourceCodeStore", ",", "lastIndex", ")", "return", "token", "}", "}" ]
Define root token builder @param {Class} Type The token type. @returns {function} The token builder.
[ "Define", "root", "token", "builder" ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/service/html-parser.js#L52-L64
23,932
ota-meshi/eslint-plugin-lodash-template
lib/service/html-parser.js
parse5NodeToToken
function parse5NodeToToken( node, parentToken, html, sourceCodeStore, lastIndex ) { const type = NODENAME_TO_TYPE_MAP[node.nodeName] ? NODENAME_TO_TYPE_MAP[node.nodeName] : "HTMLElement" return TOKEN_BUILDERS[type]( node, parentToken, html, sourceCodeStore, lastIndex ) }
javascript
function parse5NodeToToken( node, parentToken, html, sourceCodeStore, lastIndex ) { const type = NODENAME_TO_TYPE_MAP[node.nodeName] ? NODENAME_TO_TYPE_MAP[node.nodeName] : "HTMLElement" return TOKEN_BUILDERS[type]( node, parentToken, html, sourceCodeStore, lastIndex ) }
[ "function", "parse5NodeToToken", "(", "node", ",", "parentToken", ",", "html", ",", "sourceCodeStore", ",", "lastIndex", ")", "{", "const", "type", "=", "NODENAME_TO_TYPE_MAP", "[", "node", ".", "nodeName", "]", "?", "NODENAME_TO_TYPE_MAP", "[", "node", ".", "nodeName", "]", ":", "\"HTMLElement\"", "return", "TOKEN_BUILDERS", "[", "type", "]", "(", "node", ",", "parentToken", ",", "html", ",", "sourceCodeStore", ",", "lastIndex", ")", "}" ]
Node to ESLint token. @param {object} node The node from parse5. @param {object} parentToken The parent token. @param {string} html The html source code to parse. @param {SourceCodeStore} sourceCodeStore The sourceCodeStore. @param {number} lastIndex The last index. @returns {object} The ESLint token.
[ "Node", "to", "ESLint", "token", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/service/html-parser.js#L210-L228
23,933
ota-meshi/eslint-plugin-lodash-template
lib/service/html-parser.js
parseHtml
function parseHtml(html, sourceCodeStore) { const isFragment = !/^\s*<(!doctype|html|head|body|!--)/iu.test(html) const document = (isFragment ? parse5.parseFragment : parse5.parse)(html, { sourceCodeLocationInfo: true, }) return parse5NodeToToken(document, null, html, sourceCodeStore, html.length) }
javascript
function parseHtml(html, sourceCodeStore) { const isFragment = !/^\s*<(!doctype|html|head|body|!--)/iu.test(html) const document = (isFragment ? parse5.parseFragment : parse5.parse)(html, { sourceCodeLocationInfo: true, }) return parse5NodeToToken(document, null, html, sourceCodeStore, html.length) }
[ "function", "parseHtml", "(", "html", ",", "sourceCodeStore", ")", "{", "const", "isFragment", "=", "!", "/", "^\\s*<(!doctype|html|head|body|!--)", "/", "iu", ".", "test", "(", "html", ")", "const", "document", "=", "(", "isFragment", "?", "parse5", ".", "parseFragment", ":", "parse5", ".", "parse", ")", "(", "html", ",", "{", "sourceCodeLocationInfo", ":", "true", ",", "}", ")", "return", "parse5NodeToToken", "(", "document", ",", "null", ",", "html", ",", "sourceCodeStore", ",", "html", ".", "length", ")", "}" ]
Parse the given html. @param {string} html The html source code to parse. @param {SourceCodeStore} sourceCodeStore The sourceCodeStore. @returns {object} The parsing result.
[ "Parse", "the", "given", "html", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/service/html-parser.js#L236-L243
23,934
ota-meshi/eslint-plugin-lodash-template
lib/rules/max-attributes-per-line.js
isSingleLine
function isSingleLine(node) { return node.loc.start.line === node.loc.end.line }
javascript
function isSingleLine(node) { return node.loc.start.line === node.loc.end.line }
[ "function", "isSingleLine", "(", "node", ")", "{", "return", "node", ".", "loc", ".", "start", ".", "line", "===", "node", ".", "loc", ".", "end", ".", "line", "}" ]
Check whether the node is declared in a single line or not. @param {ASTNode} node The startTag node @returns {boolean} `true` if the node is declared in a single line
[ "Check", "whether", "the", "node", "is", "declared", "in", "a", "single", "line", "or", "not", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/max-attributes-per-line.js#L47-L49
23,935
ota-meshi/eslint-plugin-lodash-template
lib/rules/max-attributes-per-line.js
report
function report(attributes) { attributes.forEach((prop, i) => { context.report({ node: prop, loc: prop.loc, messageId: "missingNewLine", data: { name: prop.key, }, fix: i === 0 ? fixer => fixer.insertTextBefore(prop, "\n") : undefined, }) }) }
javascript
function report(attributes) { attributes.forEach((prop, i) => { context.report({ node: prop, loc: prop.loc, messageId: "missingNewLine", data: { name: prop.key, }, fix: i === 0 ? fixer => fixer.insertTextBefore(prop, "\n") : undefined, }) }) }
[ "function", "report", "(", "attributes", ")", "{", "attributes", ".", "forEach", "(", "(", "prop", ",", "i", ")", "=>", "{", "context", ".", "report", "(", "{", "node", ":", "prop", ",", "loc", ":", "prop", ".", "loc", ",", "messageId", ":", "\"missingNewLine\"", ",", "data", ":", "{", "name", ":", "prop", ".", "key", ",", "}", ",", "fix", ":", "i", "===", "0", "?", "fixer", "=>", "fixer", ".", "insertTextBefore", "(", "prop", ",", "\"\\n\"", ")", ":", "undefined", ",", "}", ")", "}", ")", "}" ]
Report warning the given attribute nodes. @param {Array} attributes The attribute nodes @returns {void}
[ "Report", "warning", "the", "given", "attribute", "nodes", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/max-attributes-per-line.js#L168-L183
23,936
ota-meshi/eslint-plugin-lodash-template
lib/rules/max-attributes-per-line.js
groupAttrsByLine
function groupAttrsByLine(attributes) { const propsPerLine = [[attributes[0]]] attributes.reduce((previous, current) => { if (previous.loc.end.line === current.loc.start.line) { propsPerLine[propsPerLine.length - 1].push(current) } else { propsPerLine.push([current]) } return current }) return propsPerLine }
javascript
function groupAttrsByLine(attributes) { const propsPerLine = [[attributes[0]]] attributes.reduce((previous, current) => { if (previous.loc.end.line === current.loc.start.line) { propsPerLine[propsPerLine.length - 1].push(current) } else { propsPerLine.push([current]) } return current }) return propsPerLine }
[ "function", "groupAttrsByLine", "(", "attributes", ")", "{", "const", "propsPerLine", "=", "[", "[", "attributes", "[", "0", "]", "]", "]", "attributes", ".", "reduce", "(", "(", "previous", ",", "current", ")", "=>", "{", "if", "(", "previous", ".", "loc", ".", "end", ".", "line", "===", "current", ".", "loc", ".", "start", ".", "line", ")", "{", "propsPerLine", "[", "propsPerLine", ".", "length", "-", "1", "]", ".", "push", "(", "current", ")", "}", "else", "{", "propsPerLine", ".", "push", "(", "[", "current", "]", ")", "}", "return", "current", "}", ")", "return", "propsPerLine", "}" ]
Grouping attribute lists line by line @param {Array} attributes The attribute nodes @returns {Array} The group attribute nodes
[ "Grouping", "attribute", "lists", "line", "by", "line" ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/max-attributes-per-line.js#L190-L203
23,937
ota-meshi/eslint-plugin-lodash-template
lib/rules/html-content-newline.js
isMultiline
function isMultiline(node, contentFirstLoc, contentLastLoc) { if ( node.startTag.loc.start.line !== node.startTag.loc.end.line || node.endTag.loc.start.line !== node.endTag.loc.end.line ) { // multiline tag return true } if (contentFirstLoc.line < contentLastLoc.line) { // multiline contents return true } return false }
javascript
function isMultiline(node, contentFirstLoc, contentLastLoc) { if ( node.startTag.loc.start.line !== node.startTag.loc.end.line || node.endTag.loc.start.line !== node.endTag.loc.end.line ) { // multiline tag return true } if (contentFirstLoc.line < contentLastLoc.line) { // multiline contents return true } return false }
[ "function", "isMultiline", "(", "node", ",", "contentFirstLoc", ",", "contentLastLoc", ")", "{", "if", "(", "node", ".", "startTag", ".", "loc", ".", "start", ".", "line", "!==", "node", ".", "startTag", ".", "loc", ".", "end", ".", "line", "||", "node", ".", "endTag", ".", "loc", ".", "start", ".", "line", "!==", "node", ".", "endTag", ".", "loc", ".", "end", ".", "line", ")", "{", "// multiline tag", "return", "true", "}", "if", "(", "contentFirstLoc", ".", "line", "<", "contentLastLoc", ".", "line", ")", "{", "// multiline contents", "return", "true", "}", "return", "false", "}" ]
Check whether the given node is a multiline @param {ASTNode} node The element node. @param {object} contentFirstLoc The content first location. @param {object} contentLastLoc The content last location. @returns {boolean} `true` if the node is a multiline.
[ "Check", "whether", "the", "given", "node", "is", "a", "multiline" ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/html-content-newline.js#L10-L23
23,938
ota-meshi/eslint-plugin-lodash-template
lib/rules/html-content-newline.js
isIgnore
function isIgnore(node) { let target = node while (target.type === "HTMLElement") { if (options.ignoreNames.indexOf(target.name) >= 0) { // ignore element name return true } target = target.parent } return false }
javascript
function isIgnore(node) { let target = node while (target.type === "HTMLElement") { if (options.ignoreNames.indexOf(target.name) >= 0) { // ignore element name return true } target = target.parent } return false }
[ "function", "isIgnore", "(", "node", ")", "{", "let", "target", "=", "node", "while", "(", "target", ".", "type", "===", "\"HTMLElement\"", ")", "{", "if", "(", "options", ".", "ignoreNames", ".", "indexOf", "(", "target", ".", "name", ")", ">=", "0", ")", "{", "// ignore element name", "return", "true", "}", "target", "=", "target", ".", "parent", "}", "return", "false", "}" ]
Check whether the given node is in ignore. @param {ASTNode} node The element node. @returns {boolean} `true` if the given node is in ignore.
[ "Check", "whether", "the", "given", "node", "is", "in", "ignore", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/html-content-newline.js#L141-L151
23,939
ota-meshi/eslint-plugin-lodash-template
lib/rules/html-content-newline.js
getContentLocatuons
function getContentLocatuons(node) { const contentStartIndex = node.startTag.range[1] const contentEndIndex = node.endTag.range[0] const contentText = sourceCode.text.slice( contentStartIndex, contentEndIndex ) const contentFirstIndex = (() => { const index = contentText.search(/\S/u) if (index >= 0) { return index + contentStartIndex } return contentEndIndex })() const contentLastIndex = (() => { const index = contentText.search(/\S\s*$/gu) if (index >= 0) { return index + contentStartIndex + 1 } return contentStartIndex })() return { first: { index: contentFirstIndex, loc: sourceCode.getLocFromIndex(contentFirstIndex), }, last: { index: contentLastIndex, loc: sourceCode.getLocFromIndex(contentLastIndex), }, } }
javascript
function getContentLocatuons(node) { const contentStartIndex = node.startTag.range[1] const contentEndIndex = node.endTag.range[0] const contentText = sourceCode.text.slice( contentStartIndex, contentEndIndex ) const contentFirstIndex = (() => { const index = contentText.search(/\S/u) if (index >= 0) { return index + contentStartIndex } return contentEndIndex })() const contentLastIndex = (() => { const index = contentText.search(/\S\s*$/gu) if (index >= 0) { return index + contentStartIndex + 1 } return contentStartIndex })() return { first: { index: contentFirstIndex, loc: sourceCode.getLocFromIndex(contentFirstIndex), }, last: { index: contentLastIndex, loc: sourceCode.getLocFromIndex(contentLastIndex), }, } }
[ "function", "getContentLocatuons", "(", "node", ")", "{", "const", "contentStartIndex", "=", "node", ".", "startTag", ".", "range", "[", "1", "]", "const", "contentEndIndex", "=", "node", ".", "endTag", ".", "range", "[", "0", "]", "const", "contentText", "=", "sourceCode", ".", "text", ".", "slice", "(", "contentStartIndex", ",", "contentEndIndex", ")", "const", "contentFirstIndex", "=", "(", "(", ")", "=>", "{", "const", "index", "=", "contentText", ".", "search", "(", "/", "\\S", "/", "u", ")", "if", "(", "index", ">=", "0", ")", "{", "return", "index", "+", "contentStartIndex", "}", "return", "contentEndIndex", "}", ")", "(", ")", "const", "contentLastIndex", "=", "(", "(", ")", "=>", "{", "const", "index", "=", "contentText", ".", "search", "(", "/", "\\S\\s*$", "/", "gu", ")", "if", "(", "index", ">=", "0", ")", "{", "return", "index", "+", "contentStartIndex", "+", "1", "}", "return", "contentStartIndex", "}", ")", "(", ")", "return", "{", "first", ":", "{", "index", ":", "contentFirstIndex", ",", "loc", ":", "sourceCode", ".", "getLocFromIndex", "(", "contentFirstIndex", ")", ",", "}", ",", "last", ":", "{", "index", ":", "contentLastIndex", ",", "loc", ":", "sourceCode", ".", "getLocFromIndex", "(", "contentLastIndex", ")", ",", "}", ",", "}", "}" ]
Get the contents locations. @param {ASTNode} node The element node. @returns {object} The contents locations.
[ "Get", "the", "contents", "locations", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/html-content-newline.js#L158-L190
23,940
ota-meshi/eslint-plugin-lodash-template
lib/service/BranchedHTMLStore.js
traverseAst
function traverseAst(sourceCode, node, parent, visitor) { if (visitor[node.type]) { visitor[node.type](node, parent) } const keys = sourceCode.visitorKeys[node.type] for (const key of keys) { const child = node[key] if (Array.isArray(child)) { for (const c of child) { if (c) { traverseAst(sourceCode, c, node, visitor) } } } else if (child) { traverseAst(sourceCode, child, node, visitor) } } }
javascript
function traverseAst(sourceCode, node, parent, visitor) { if (visitor[node.type]) { visitor[node.type](node, parent) } const keys = sourceCode.visitorKeys[node.type] for (const key of keys) { const child = node[key] if (Array.isArray(child)) { for (const c of child) { if (c) { traverseAst(sourceCode, c, node, visitor) } } } else if (child) { traverseAst(sourceCode, child, node, visitor) } } }
[ "function", "traverseAst", "(", "sourceCode", ",", "node", ",", "parent", ",", "visitor", ")", "{", "if", "(", "visitor", "[", "node", ".", "type", "]", ")", "{", "visitor", "[", "node", ".", "type", "]", "(", "node", ",", "parent", ")", "}", "const", "keys", "=", "sourceCode", ".", "visitorKeys", "[", "node", ".", "type", "]", "for", "(", "const", "key", "of", "keys", ")", "{", "const", "child", "=", "node", "[", "key", "]", "if", "(", "Array", ".", "isArray", "(", "child", ")", ")", "{", "for", "(", "const", "c", "of", "child", ")", "{", "if", "(", "c", ")", "{", "traverseAst", "(", "sourceCode", ",", "c", ",", "node", ",", "visitor", ")", "}", "}", "}", "else", "if", "(", "child", ")", "{", "traverseAst", "(", "sourceCode", ",", "child", ",", "node", ",", "visitor", ")", "}", "}", "}" ]
Traverse the given node. @param {SourceCode} sourceCode The source code. @param {object} node The node to traverse. @param {object} parent The parent node. @param {object} visitor Visitor. @returns {void}
[ "Traverse", "the", "given", "node", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/service/BranchedHTMLStore.js#L11-L30
23,941
ota-meshi/eslint-plugin-lodash-template
lib/service/BranchedHTMLStore.js
createBranchedHTML
function createBranchedHTML(service, branchStatements, targetNode) { let template = service.template const stripedRanges = [] /** * Strip template of range. * @param {number} start The start index of range. * @param {number} end The end index of range. * @returns {void} */ function strip(start, end) { const before = template.slice(0, start) const target = template.slice(start, end) const after = template.slice(end) template = before + target.replace(/\S/gu, " ") + after stripedRanges.push([start, end]) } const visitor = { IfStatement(node) { if ( node.alternate.range[0] <= targetNode.range[0] && targetNode.range[0] < node.alternate.range[1] ) { strip(node.consequent.range[0], node.consequent.range[1]) } else { strip(node.alternate.range[0], node.alternate.range[1]) } }, SwitchStatement(node) { let nodeCaseIndex = node.cases.findIndex((cur, index) => { const next = node.cases[index + 1] const endIndex = next ? next.range[0] : node.range[1] return ( cur.range[0] <= targetNode.range[0] && targetNode.range[0] < endIndex ) }) if (nodeCaseIndex < 0) { nodeCaseIndex = 0 } node.cases.forEach((cur, index) => { if (index === nodeCaseIndex) { return } const next = node.cases[index + 1] const endIndex = next ? next.range[0] : node.range[1] strip(cur.range[0], endIndex) }) }, } for (const node of branchStatements) { visitor[node.type](node) } return new BranchedHTML( template, service.parseHtml(template), stripedRanges ) }
javascript
function createBranchedHTML(service, branchStatements, targetNode) { let template = service.template const stripedRanges = [] /** * Strip template of range. * @param {number} start The start index of range. * @param {number} end The end index of range. * @returns {void} */ function strip(start, end) { const before = template.slice(0, start) const target = template.slice(start, end) const after = template.slice(end) template = before + target.replace(/\S/gu, " ") + after stripedRanges.push([start, end]) } const visitor = { IfStatement(node) { if ( node.alternate.range[0] <= targetNode.range[0] && targetNode.range[0] < node.alternate.range[1] ) { strip(node.consequent.range[0], node.consequent.range[1]) } else { strip(node.alternate.range[0], node.alternate.range[1]) } }, SwitchStatement(node) { let nodeCaseIndex = node.cases.findIndex((cur, index) => { const next = node.cases[index + 1] const endIndex = next ? next.range[0] : node.range[1] return ( cur.range[0] <= targetNode.range[0] && targetNode.range[0] < endIndex ) }) if (nodeCaseIndex < 0) { nodeCaseIndex = 0 } node.cases.forEach((cur, index) => { if (index === nodeCaseIndex) { return } const next = node.cases[index + 1] const endIndex = next ? next.range[0] : node.range[1] strip(cur.range[0], endIndex) }) }, } for (const node of branchStatements) { visitor[node.type](node) } return new BranchedHTML( template, service.parseHtml(template), stripedRanges ) }
[ "function", "createBranchedHTML", "(", "service", ",", "branchStatements", ",", "targetNode", ")", "{", "let", "template", "=", "service", ".", "template", "const", "stripedRanges", "=", "[", "]", "/**\n * Strip template of range.\n * @param {number} start The start index of range.\n * @param {number} end The end index of range.\n * @returns {void}\n */", "function", "strip", "(", "start", ",", "end", ")", "{", "const", "before", "=", "template", ".", "slice", "(", "0", ",", "start", ")", "const", "target", "=", "template", ".", "slice", "(", "start", ",", "end", ")", "const", "after", "=", "template", ".", "slice", "(", "end", ")", "template", "=", "before", "+", "target", ".", "replace", "(", "/", "\\S", "/", "gu", ",", "\" \"", ")", "+", "after", "stripedRanges", ".", "push", "(", "[", "start", ",", "end", "]", ")", "}", "const", "visitor", "=", "{", "IfStatement", "(", "node", ")", "{", "if", "(", "node", ".", "alternate", ".", "range", "[", "0", "]", "<=", "targetNode", ".", "range", "[", "0", "]", "&&", "targetNode", ".", "range", "[", "0", "]", "<", "node", ".", "alternate", ".", "range", "[", "1", "]", ")", "{", "strip", "(", "node", ".", "consequent", ".", "range", "[", "0", "]", ",", "node", ".", "consequent", ".", "range", "[", "1", "]", ")", "}", "else", "{", "strip", "(", "node", ".", "alternate", ".", "range", "[", "0", "]", ",", "node", ".", "alternate", ".", "range", "[", "1", "]", ")", "}", "}", ",", "SwitchStatement", "(", "node", ")", "{", "let", "nodeCaseIndex", "=", "node", ".", "cases", ".", "findIndex", "(", "(", "cur", ",", "index", ")", "=>", "{", "const", "next", "=", "node", ".", "cases", "[", "index", "+", "1", "]", "const", "endIndex", "=", "next", "?", "next", ".", "range", "[", "0", "]", ":", "node", ".", "range", "[", "1", "]", "return", "(", "cur", ".", "range", "[", "0", "]", "<=", "targetNode", ".", "range", "[", "0", "]", "&&", "targetNode", ".", "range", "[", "0", "]", "<", "endIndex", ")", "}", ")", "if", "(", "nodeCaseIndex", "<", "0", ")", "{", "nodeCaseIndex", "=", "0", "}", "node", ".", "cases", ".", "forEach", "(", "(", "cur", ",", "index", ")", "=>", "{", "if", "(", "index", "===", "nodeCaseIndex", ")", "{", "return", "}", "const", "next", "=", "node", ".", "cases", "[", "index", "+", "1", "]", "const", "endIndex", "=", "next", "?", "next", ".", "range", "[", "0", "]", ":", "node", ".", "range", "[", "1", "]", "strip", "(", "cur", ".", "range", "[", "0", "]", ",", "endIndex", ")", "}", ")", "}", ",", "}", "for", "(", "const", "node", "of", "branchStatements", ")", "{", "visitor", "[", "node", ".", "type", "]", "(", "node", ")", "}", "return", "new", "BranchedHTML", "(", "template", ",", "service", ".", "parseHtml", "(", "template", ")", ",", "stripedRanges", ")", "}" ]
Get HTML with alternate statements striped. @param {MicroTemplateService} service The MicroTemplateService @param {Array} branchStatements The branch statements @param {ASTNode} targetNode The target node. @returns {BranchedHTML} Branch-processed HTML
[ "Get", "HTML", "with", "alternate", "statements", "striped", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/service/BranchedHTMLStore.js#L73-L133
23,942
ota-meshi/eslint-plugin-lodash-template
lib/service/BranchedHTMLStore.js
strip
function strip(start, end) { const before = template.slice(0, start) const target = template.slice(start, end) const after = template.slice(end) template = before + target.replace(/\S/gu, " ") + after stripedRanges.push([start, end]) }
javascript
function strip(start, end) { const before = template.slice(0, start) const target = template.slice(start, end) const after = template.slice(end) template = before + target.replace(/\S/gu, " ") + after stripedRanges.push([start, end]) }
[ "function", "strip", "(", "start", ",", "end", ")", "{", "const", "before", "=", "template", ".", "slice", "(", "0", ",", "start", ")", "const", "target", "=", "template", ".", "slice", "(", "start", ",", "end", ")", "const", "after", "=", "template", ".", "slice", "(", "end", ")", "template", "=", "before", "+", "target", ".", "replace", "(", "/", "\\S", "/", "gu", ",", "\" \"", ")", "+", "after", "stripedRanges", ".", "push", "(", "[", "start", ",", "end", "]", ")", "}" ]
Strip template of range. @param {number} start The start index of range. @param {number} end The end index of range. @returns {void}
[ "Strip", "template", "of", "range", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/service/BranchedHTMLStore.js#L83-L89
23,943
ota-meshi/eslint-plugin-lodash-template
lib/rules/no-template-tag-in-start-tag.js
getTemplateTags
function getTemplateTags(start, end) { const results = [] for (const token of microTemplateService.getMicroTemplateTokens()) { if (token.range[1] <= start) { continue } if (end <= token.range[0]) { break } results.push(token) } return results }
javascript
function getTemplateTags(start, end) { const results = [] for (const token of microTemplateService.getMicroTemplateTokens()) { if (token.range[1] <= start) { continue } if (end <= token.range[0]) { break } results.push(token) } return results }
[ "function", "getTemplateTags", "(", "start", ",", "end", ")", "{", "const", "results", "=", "[", "]", "for", "(", "const", "token", "of", "microTemplateService", ".", "getMicroTemplateTokens", "(", ")", ")", "{", "if", "(", "token", ".", "range", "[", "1", "]", "<=", "start", ")", "{", "continue", "}", "if", "(", "end", "<=", "token", ".", "range", "[", "0", "]", ")", "{", "break", "}", "results", ".", "push", "(", "token", ")", "}", "return", "results", "}" ]
Gets all interpolation tokens that are contained to the given range. @param {number} start - The start of range. @param {number} end - The end of range. @returns {Token[]} Array of objects representing tokens.
[ "Gets", "all", "interpolation", "tokens", "that", "are", "contained", "to", "the", "given", "range", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/no-template-tag-in-start-tag.js#L46-L58
23,944
ota-meshi/eslint-plugin-lodash-template
lib/rules/no-template-tag-in-start-tag.js
validate
function validate(templateTags, attrs) { const valueTokens = attrs .map(attr => attr.valueToken) .filter(t => Boolean(t)) for (const templateTag of templateTags) { if ( valueTokens.some( valueToken => valueToken.range[0] <= templateTag.range[0] && templateTag.range[1] <= valueToken.range[1] ) ) { continue } const isInterpolate = templateTag.type === "MicroTemplateInterpolate" || templateTag.type === "MicroTemplateEscape" if (isInterpolate ? arrowInterpolateTag : arrowEvaluateTag) { continue } context.report({ node: templateTag, messageId: isInterpolate ? "unexpectedInterpolate" : "unexpectedEvaluate", }) } }
javascript
function validate(templateTags, attrs) { const valueTokens = attrs .map(attr => attr.valueToken) .filter(t => Boolean(t)) for (const templateTag of templateTags) { if ( valueTokens.some( valueToken => valueToken.range[0] <= templateTag.range[0] && templateTag.range[1] <= valueToken.range[1] ) ) { continue } const isInterpolate = templateTag.type === "MicroTemplateInterpolate" || templateTag.type === "MicroTemplateEscape" if (isInterpolate ? arrowInterpolateTag : arrowEvaluateTag) { continue } context.report({ node: templateTag, messageId: isInterpolate ? "unexpectedInterpolate" : "unexpectedEvaluate", }) } }
[ "function", "validate", "(", "templateTags", ",", "attrs", ")", "{", "const", "valueTokens", "=", "attrs", ".", "map", "(", "attr", "=>", "attr", ".", "valueToken", ")", ".", "filter", "(", "t", "=>", "Boolean", "(", "t", ")", ")", "for", "(", "const", "templateTag", "of", "templateTags", ")", "{", "if", "(", "valueTokens", ".", "some", "(", "valueToken", "=>", "valueToken", ".", "range", "[", "0", "]", "<=", "templateTag", ".", "range", "[", "0", "]", "&&", "templateTag", ".", "range", "[", "1", "]", "<=", "valueToken", ".", "range", "[", "1", "]", ")", ")", "{", "continue", "}", "const", "isInterpolate", "=", "templateTag", ".", "type", "===", "\"MicroTemplateInterpolate\"", "||", "templateTag", ".", "type", "===", "\"MicroTemplateEscape\"", "if", "(", "isInterpolate", "?", "arrowInterpolateTag", ":", "arrowEvaluateTag", ")", "{", "continue", "}", "context", ".", "report", "(", "{", "node", ":", "templateTag", ",", "messageId", ":", "isInterpolate", "?", "\"unexpectedInterpolate\"", ":", "\"unexpectedEvaluate\"", ",", "}", ")", "}", "}" ]
Validate template tags. @param {Array} templateTags The template tags. @param {Array} attrs The attibutes nodes. @returns {void}
[ "Validate", "template", "tags", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/no-template-tag-in-start-tag.js#L66-L93
23,945
swhite24/hover-api
index.js
createARecord
function createARecord (domain, subdomain, ip, cb) { var body = { name: subdomain, type: 'A', content: ip }; _hoverRequest('POST', '/domains/' + domain + '/dns', body, cb); }
javascript
function createARecord (domain, subdomain, ip, cb) { var body = { name: subdomain, type: 'A', content: ip }; _hoverRequest('POST', '/domains/' + domain + '/dns', body, cb); }
[ "function", "createARecord", "(", "domain", ",", "subdomain", ",", "ip", ",", "cb", ")", "{", "var", "body", "=", "{", "name", ":", "subdomain", ",", "type", ":", "'A'", ",", "content", ":", "ip", "}", ";", "_hoverRequest", "(", "'POST'", ",", "'/domains/'", "+", "domain", "+", "'/dns'", ",", "body", ",", "cb", ")", ";", "}" ]
Create a new A record under the specified domain @param {String} domain Domain identifier @param {String} subdomain Subdomain of record @param {String} ip IP Address of record @param {Function} cb @api public
[ "Create", "a", "new", "A", "record", "under", "the", "specified", "domain" ]
0720a4b1566eb501dc64c5f8747fc19d1f5a9e31
https://github.com/swhite24/hover-api/blob/0720a4b1566eb501dc64c5f8747fc19d1f5a9e31/index.js#L80-L87
23,946
swhite24/hover-api
index.js
createMXRecord
function createMXRecord (domain, subdomain, priority, ip, cb) { var body = { name: subdomain, type: 'MX', content: [priority, ip].join(' ') }; _hoverRequest('POST', '/domains/' + domain + '/dns', body, cb); }
javascript
function createMXRecord (domain, subdomain, priority, ip, cb) { var body = { name: subdomain, type: 'MX', content: [priority, ip].join(' ') }; _hoverRequest('POST', '/domains/' + domain + '/dns', body, cb); }
[ "function", "createMXRecord", "(", "domain", ",", "subdomain", ",", "priority", ",", "ip", ",", "cb", ")", "{", "var", "body", "=", "{", "name", ":", "subdomain", ",", "type", ":", "'MX'", ",", "content", ":", "[", "priority", ",", "ip", "]", ".", "join", "(", "' '", ")", "}", ";", "_hoverRequest", "(", "'POST'", ",", "'/domains/'", "+", "domain", "+", "'/dns'", ",", "body", ",", "cb", ")", ";", "}" ]
Create a new MX record under the specified domain @param {String} domain Domain identifier @param {String} subdomain Subdomain of record @param {String} priority Priority of record @param {String} ip IP Address of record @param {Function} cb @api public
[ "Create", "a", "new", "MX", "record", "under", "the", "specified", "domain" ]
0720a4b1566eb501dc64c5f8747fc19d1f5a9e31
https://github.com/swhite24/hover-api/blob/0720a4b1566eb501dc64c5f8747fc19d1f5a9e31/index.js#L99-L106
23,947
swhite24/hover-api
index.js
updateDomainDns
function updateDomainDns (dns, ip, cb) { var body = { content: ip }; _hoverRequest('PUT', '/dns/' + dns, body, cb); }
javascript
function updateDomainDns (dns, ip, cb) { var body = { content: ip }; _hoverRequest('PUT', '/dns/' + dns, body, cb); }
[ "function", "updateDomainDns", "(", "dns", ",", "ip", ",", "cb", ")", "{", "var", "body", "=", "{", "content", ":", "ip", "}", ";", "_hoverRequest", "(", "'PUT'", ",", "'/dns/'", "+", "dns", ",", "body", ",", "cb", ")", ";", "}" ]
Update an existing domain record @param {String} dns DNS identifier @param {String} ip New IP Address of record @param {Function} cb @api public
[ "Update", "an", "existing", "domain", "record" ]
0720a4b1566eb501dc64c5f8747fc19d1f5a9e31
https://github.com/swhite24/hover-api/blob/0720a4b1566eb501dc64c5f8747fc19d1f5a9e31/index.js#L116-L121
23,948
swhite24/hover-api
index.js
_hoverRequest
function _hoverRequest (method, path, body, cb) { // Check if previously logged in if (_loggedin) return _hoverApiRequest(method, path, body, cb); // Issue login request with provided username / password r({ uri: baseUrl + '/login', body: 'username=' + username + '&password=' + password, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }, _rCallback(function (err) { if (err) return cb(err); // Note logged in / forward request _loggedin = true; _hoverApiRequest(method, path, body, cb); })); }
javascript
function _hoverRequest (method, path, body, cb) { // Check if previously logged in if (_loggedin) return _hoverApiRequest(method, path, body, cb); // Issue login request with provided username / password r({ uri: baseUrl + '/login', body: 'username=' + username + '&password=' + password, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }, _rCallback(function (err) { if (err) return cb(err); // Note logged in / forward request _loggedin = true; _hoverApiRequest(method, path, body, cb); })); }
[ "function", "_hoverRequest", "(", "method", ",", "path", ",", "body", ",", "cb", ")", "{", "// Check if previously logged in", "if", "(", "_loggedin", ")", "return", "_hoverApiRequest", "(", "method", ",", "path", ",", "body", ",", "cb", ")", ";", "// Issue login request with provided username / password", "r", "(", "{", "uri", ":", "baseUrl", "+", "'/login'", ",", "body", ":", "'username='", "+", "username", "+", "'&password='", "+", "password", ",", "headers", ":", "{", "'Content-Type'", ":", "'application/x-www-form-urlencoded'", "}", "}", ",", "_rCallback", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "// Note logged in / forward request", "_loggedin", "=", "true", ";", "_hoverApiRequest", "(", "method", ",", "path", ",", "body", ",", "cb", ")", ";", "}", ")", ")", ";", "}" ]
Proxy request to hover API. Will issue login request if not previously generated. @param {String} method @param {String} path @param {Function} cb @api private
[ "Proxy", "request", "to", "hover", "API", ".", "Will", "issue", "login", "request", "if", "not", "previously", "generated", "." ]
0720a4b1566eb501dc64c5f8747fc19d1f5a9e31
https://github.com/swhite24/hover-api/blob/0720a4b1566eb501dc64c5f8747fc19d1f5a9e31/index.js#L143-L161
23,949
swhite24/hover-api
index.js
_hoverApiRequest
function _hoverApiRequest (method, path, body, cb) { // Check body provided if (typeof body === 'function') { cb = body; body = null; } // Default options var options = { method: method, uri: baseUrl + path }; // Add body if provided if (body) options.body = body; // Issue request r(options, _rCallback(function (err, data) { if (err) return cb(err); // Pull out property name var key = _.without(_.keys(data), 'succeeded'); cb(null, data[key]); })); }
javascript
function _hoverApiRequest (method, path, body, cb) { // Check body provided if (typeof body === 'function') { cb = body; body = null; } // Default options var options = { method: method, uri: baseUrl + path }; // Add body if provided if (body) options.body = body; // Issue request r(options, _rCallback(function (err, data) { if (err) return cb(err); // Pull out property name var key = _.without(_.keys(data), 'succeeded'); cb(null, data[key]); })); }
[ "function", "_hoverApiRequest", "(", "method", ",", "path", ",", "body", ",", "cb", ")", "{", "// Check body provided", "if", "(", "typeof", "body", "===", "'function'", ")", "{", "cb", "=", "body", ";", "body", "=", "null", ";", "}", "// Default options", "var", "options", "=", "{", "method", ":", "method", ",", "uri", ":", "baseUrl", "+", "path", "}", ";", "// Add body if provided", "if", "(", "body", ")", "options", ".", "body", "=", "body", ";", "// Issue request", "r", "(", "options", ",", "_rCallback", "(", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "// Pull out property name", "var", "key", "=", "_", ".", "without", "(", "_", ".", "keys", "(", "data", ")", ",", "'succeeded'", ")", ";", "cb", "(", "null", ",", "data", "[", "key", "]", ")", ";", "}", ")", ")", ";", "}" ]
Issue request to hover api. @param {String} method @param {String} path @param {Object} [body] @param {Function} cb @api private
[ "Issue", "request", "to", "hover", "api", "." ]
0720a4b1566eb501dc64c5f8747fc19d1f5a9e31
https://github.com/swhite24/hover-api/blob/0720a4b1566eb501dc64c5f8747fc19d1f5a9e31/index.js#L172-L196
23,950
swhite24/hover-api
index.js
_rCallback
function _rCallback (cb) { return function (err, res, data) { if (err) return cb(err); if (!res || res.statusCode > 400) return cb(data); cb(null, data); }; }
javascript
function _rCallback (cb) { return function (err, res, data) { if (err) return cb(err); if (!res || res.statusCode > 400) return cb(data); cb(null, data); }; }
[ "function", "_rCallback", "(", "cb", ")", "{", "return", "function", "(", "err", ",", "res", ",", "data", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "if", "(", "!", "res", "||", "res", ".", "statusCode", ">", "400", ")", "return", "cb", "(", "data", ")", ";", "cb", "(", "null", ",", "data", ")", ";", "}", ";", "}" ]
Request callback abstraction to deliver http or connection error. @param {Function} cb @return {Function} @api private
[ "Request", "callback", "abstraction", "to", "deliver", "http", "or", "connection", "error", "." ]
0720a4b1566eb501dc64c5f8747fc19d1f5a9e31
https://github.com/swhite24/hover-api/blob/0720a4b1566eb501dc64c5f8747fc19d1f5a9e31/index.js#L205-L212
23,951
ota-meshi/eslint-plugin-lodash-template
lib/rules/attribute-value-quote.js
calcValueInfo
function calcValueInfo(valueToken) { const text = valueToken.htmlValue const firstChar = text[0] const quote = firstChar === "'" || firstChar === '"' ? firstChar : undefined const content = quote ? text.slice(1, -1) : text return { quote, content, } }
javascript
function calcValueInfo(valueToken) { const text = valueToken.htmlValue const firstChar = text[0] const quote = firstChar === "'" || firstChar === '"' ? firstChar : undefined const content = quote ? text.slice(1, -1) : text return { quote, content, } }
[ "function", "calcValueInfo", "(", "valueToken", ")", "{", "const", "text", "=", "valueToken", ".", "htmlValue", "const", "firstChar", "=", "text", "[", "0", "]", "const", "quote", "=", "firstChar", "===", "\"'\"", "||", "firstChar", "===", "'\"'", "?", "firstChar", ":", "undefined", "const", "content", "=", "quote", "?", "text", ".", "slice", "(", "1", ",", "-", "1", ")", ":", "text", "return", "{", "quote", ",", "content", ",", "}", "}" ]
get the value info. @param {Token} valueToken The value token. @returns {object} the value info.
[ "get", "the", "value", "info", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/attribute-value-quote.js#L8-L17
23,952
ota-meshi/eslint-plugin-lodash-template
lib/rules/no-multi-spaces-in-script.js
formatReportedCommentValue
function formatReportedCommentValue(token) { const valueLines = token.value.split("\n") const value = valueLines[0] const formattedValue = `${value.slice(0, 12)}...` return valueLines.length === 1 && value.length <= 12 ? value : formattedValue }
javascript
function formatReportedCommentValue(token) { const valueLines = token.value.split("\n") const value = valueLines[0] const formattedValue = `${value.slice(0, 12)}...` return valueLines.length === 1 && value.length <= 12 ? value : formattedValue }
[ "function", "formatReportedCommentValue", "(", "token", ")", "{", "const", "valueLines", "=", "token", ".", "value", ".", "split", "(", "\"\\n\"", ")", "const", "value", "=", "valueLines", "[", "0", "]", "const", "formattedValue", "=", "`", "${", "value", ".", "slice", "(", "0", ",", "12", ")", "}", "`", "return", "valueLines", ".", "length", "===", "1", "&&", "value", ".", "length", "<=", "12", "?", "value", ":", "formattedValue", "}" ]
Formats value of given comment token for error message by truncating its length. @param {Token} token comment token @returns {string} formatted value @private
[ "Formats", "value", "of", "given", "comment", "token", "for", "error", "message", "by", "truncating", "its", "length", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/no-multi-spaces-in-script.js#L59-L67
23,953
ota-meshi/eslint-plugin-lodash-template
lib/rules/no-multi-spaces-in-script.js
getTemplateTagByToken
function getTemplateTagByToken(token) { return microTemplateService .getMicroTemplateTokens() .find( t => t.expressionStart.range[1] <= token.range[0] && token.range[0] < t.expressionEnd.range[0] ) }
javascript
function getTemplateTagByToken(token) { return microTemplateService .getMicroTemplateTokens() .find( t => t.expressionStart.range[1] <= token.range[0] && token.range[0] < t.expressionEnd.range[0] ) }
[ "function", "getTemplateTagByToken", "(", "token", ")", "{", "return", "microTemplateService", ".", "getMicroTemplateTokens", "(", ")", ".", "find", "(", "t", "=>", "t", ".", "expressionStart", ".", "range", "[", "1", "]", "<=", "token", ".", "range", "[", "0", "]", "&&", "token", ".", "range", "[", "0", "]", "<", "t", ".", "expressionEnd", ".", "range", "[", "0", "]", ")", "}" ]
Get the template tag token containing a script. @param {Token} token The script token. @returns {Token} The token if found or null if not found.
[ "Get", "the", "template", "tag", "token", "containing", "a", "script", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/no-multi-spaces-in-script.js#L74-L82
23,954
ota-meshi/eslint-plugin-lodash-template
lib/rules/no-multi-spaces-in-script.js
isIgnores
function isIgnores(leftToken, leftIndex, rightToken) { const tokensAndComments = sourceCode.tokensAndComments const leftTemplateTag = getTemplateTagByToken(leftToken) const rightTemplateTag = getTemplateTagByToken(rightToken) if (!leftTemplateTag || !rightTemplateTag) { return true } // Ignore if token is the first token of the template tag script if ( !sourceCode.text .slice( rightTemplateTag.expressionStart.range[1], rightToken.range[0] ) .trim() ) { return true } // Ignore comments that are the last token on their line if `ignoreEOLComments` is active. if ( ignoreEOLComments && isCommentToken(rightToken) && (leftIndex === tokensAndComments.length - 2 || rightToken.loc.end.line < tokensAndComments[leftIndex + 2].loc.start.line) ) { return true } // Ignore tokens that are in a node in the "exceptions" object if (hasExceptions) { const parentNode = sourceCode.getNodeByRangeIndex( rightToken.range[0] - 1 ) if (parentNode && exceptions[parentNode.type]) { return true } } return false }
javascript
function isIgnores(leftToken, leftIndex, rightToken) { const tokensAndComments = sourceCode.tokensAndComments const leftTemplateTag = getTemplateTagByToken(leftToken) const rightTemplateTag = getTemplateTagByToken(rightToken) if (!leftTemplateTag || !rightTemplateTag) { return true } // Ignore if token is the first token of the template tag script if ( !sourceCode.text .slice( rightTemplateTag.expressionStart.range[1], rightToken.range[0] ) .trim() ) { return true } // Ignore comments that are the last token on their line if `ignoreEOLComments` is active. if ( ignoreEOLComments && isCommentToken(rightToken) && (leftIndex === tokensAndComments.length - 2 || rightToken.loc.end.line < tokensAndComments[leftIndex + 2].loc.start.line) ) { return true } // Ignore tokens that are in a node in the "exceptions" object if (hasExceptions) { const parentNode = sourceCode.getNodeByRangeIndex( rightToken.range[0] - 1 ) if (parentNode && exceptions[parentNode.type]) { return true } } return false }
[ "function", "isIgnores", "(", "leftToken", ",", "leftIndex", ",", "rightToken", ")", "{", "const", "tokensAndComments", "=", "sourceCode", ".", "tokensAndComments", "const", "leftTemplateTag", "=", "getTemplateTagByToken", "(", "leftToken", ")", "const", "rightTemplateTag", "=", "getTemplateTagByToken", "(", "rightToken", ")", "if", "(", "!", "leftTemplateTag", "||", "!", "rightTemplateTag", ")", "{", "return", "true", "}", "// Ignore if token is the first token of the template tag script", "if", "(", "!", "sourceCode", ".", "text", ".", "slice", "(", "rightTemplateTag", ".", "expressionStart", ".", "range", "[", "1", "]", ",", "rightToken", ".", "range", "[", "0", "]", ")", ".", "trim", "(", ")", ")", "{", "return", "true", "}", "// Ignore comments that are the last token on their line if `ignoreEOLComments` is active.", "if", "(", "ignoreEOLComments", "&&", "isCommentToken", "(", "rightToken", ")", "&&", "(", "leftIndex", "===", "tokensAndComments", ".", "length", "-", "2", "||", "rightToken", ".", "loc", ".", "end", ".", "line", "<", "tokensAndComments", "[", "leftIndex", "+", "2", "]", ".", "loc", ".", "start", ".", "line", ")", ")", "{", "return", "true", "}", "// Ignore tokens that are in a node in the \"exceptions\" object", "if", "(", "hasExceptions", ")", "{", "const", "parentNode", "=", "sourceCode", ".", "getNodeByRangeIndex", "(", "rightToken", ".", "range", "[", "0", "]", "-", "1", ")", "if", "(", "parentNode", "&&", "exceptions", "[", "parentNode", ".", "type", "]", ")", "{", "return", "true", "}", "}", "return", "false", "}" ]
Checks if the given token is ignore or not. @param {Token} leftToken - The token to check. @param {number} leftIndex - The index of left token. @param {Token} rightToken - The token to check. @returns {boolean} `true` if the token is ignore.
[ "Checks", "if", "the", "given", "token", "is", "ignore", "or", "not", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/no-multi-spaces-in-script.js#L106-L148
23,955
ota-meshi/eslint-plugin-lodash-template
docs/.vuepress/components/state/serialize.js
getEnabledRules
function getEnabledRules(allRules) { return Object.keys(allRules).reduce((map, id) => { if (allRules[id] === "error") { map[id] = 2 } return map }, {}) }
javascript
function getEnabledRules(allRules) { return Object.keys(allRules).reduce((map, id) => { if (allRules[id] === "error") { map[id] = 2 } return map }, {}) }
[ "function", "getEnabledRules", "(", "allRules", ")", "{", "return", "Object", ".", "keys", "(", "allRules", ")", ".", "reduce", "(", "(", "map", ",", "id", ")", "=>", "{", "if", "(", "allRules", "[", "id", "]", "===", "\"error\"", ")", "{", "map", "[", "id", "]", "=", "2", "}", "return", "map", "}", ",", "{", "}", ")", "}" ]
Get only enabled rules to make the serialized data smaller. @param {object} allRules The rule settings. @returns {object} The rule settings for the enabled rules.
[ "Get", "only", "enabled", "rules", "to", "make", "the", "serialized", "data", "smaller", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/docs/.vuepress/components/state/serialize.js#L8-L15
23,956
ota-meshi/eslint-plugin-lodash-template
tools/lib/load-rules.js
readRules
function readRules() { const rulesRoot = path.resolve(__dirname, "../../lib/rules") const result = fs.readdirSync(rulesRoot) const rules = [] for (const name of result) { const ruleName = name.replace(/\.js$/u, "") const ruleId = `lodash-template/${ruleName}` const rule = require(path.join(rulesRoot, name)) rule.meta.docs.ruleId = ruleId rule.meta.docs.ruleName = ruleName rules.push(rule) } return rules }
javascript
function readRules() { const rulesRoot = path.resolve(__dirname, "../../lib/rules") const result = fs.readdirSync(rulesRoot) const rules = [] for (const name of result) { const ruleName = name.replace(/\.js$/u, "") const ruleId = `lodash-template/${ruleName}` const rule = require(path.join(rulesRoot, name)) rule.meta.docs.ruleId = ruleId rule.meta.docs.ruleName = ruleName rules.push(rule) } return rules }
[ "function", "readRules", "(", ")", "{", "const", "rulesRoot", "=", "path", ".", "resolve", "(", "__dirname", ",", "\"../../lib/rules\"", ")", "const", "result", "=", "fs", ".", "readdirSync", "(", "rulesRoot", ")", "const", "rules", "=", "[", "]", "for", "(", "const", "name", "of", "result", ")", "{", "const", "ruleName", "=", "name", ".", "replace", "(", "/", "\\.js$", "/", "u", ",", "\"\"", ")", "const", "ruleId", "=", "`", "${", "ruleName", "}", "`", "const", "rule", "=", "require", "(", "path", ".", "join", "(", "rulesRoot", ",", "name", ")", ")", "rule", ".", "meta", ".", "docs", ".", "ruleId", "=", "ruleId", "rule", ".", "meta", ".", "docs", ".", "ruleName", "=", "ruleName", "rules", ".", "push", "(", "rule", ")", "}", "return", "rules", "}" ]
Get the all rules @returns {Array} The all rules
[ "Get", "the", "all", "rules" ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/tools/lib/load-rules.js#L10-L24
23,957
ota-meshi/eslint-plugin-lodash-template
lib/rules/html-comment-content-newline.js
getCommentLocatuons
function getCommentLocatuons(node) { const contentStartIndex = node.commentOpen.range[1] const contentEndIndex = node.commentClose.range[0] const contentText = sourceCode.text.slice( contentStartIndex, contentEndIndex ) const contentFirstIndex = (() => { const index = contentText.search(/\S/u) if (index >= 0) { return index + contentStartIndex } return contentEndIndex })() const contentLastIndex = (() => { const index = contentText.search(/\S\s*$/gu) if (index >= 0) { return index + contentStartIndex + 1 } return contentStartIndex })() return { first: { index: contentFirstIndex, loc: sourceCode.getLocFromIndex(contentFirstIndex), }, last: { index: contentLastIndex, loc: sourceCode.getLocFromIndex(contentLastIndex), }, } }
javascript
function getCommentLocatuons(node) { const contentStartIndex = node.commentOpen.range[1] const contentEndIndex = node.commentClose.range[0] const contentText = sourceCode.text.slice( contentStartIndex, contentEndIndex ) const contentFirstIndex = (() => { const index = contentText.search(/\S/u) if (index >= 0) { return index + contentStartIndex } return contentEndIndex })() const contentLastIndex = (() => { const index = contentText.search(/\S\s*$/gu) if (index >= 0) { return index + contentStartIndex + 1 } return contentStartIndex })() return { first: { index: contentFirstIndex, loc: sourceCode.getLocFromIndex(contentFirstIndex), }, last: { index: contentLastIndex, loc: sourceCode.getLocFromIndex(contentLastIndex), }, } }
[ "function", "getCommentLocatuons", "(", "node", ")", "{", "const", "contentStartIndex", "=", "node", ".", "commentOpen", ".", "range", "[", "1", "]", "const", "contentEndIndex", "=", "node", ".", "commentClose", ".", "range", "[", "0", "]", "const", "contentText", "=", "sourceCode", ".", "text", ".", "slice", "(", "contentStartIndex", ",", "contentEndIndex", ")", "const", "contentFirstIndex", "=", "(", "(", ")", "=>", "{", "const", "index", "=", "contentText", ".", "search", "(", "/", "\\S", "/", "u", ")", "if", "(", "index", ">=", "0", ")", "{", "return", "index", "+", "contentStartIndex", "}", "return", "contentEndIndex", "}", ")", "(", ")", "const", "contentLastIndex", "=", "(", "(", ")", "=>", "{", "const", "index", "=", "contentText", ".", "search", "(", "/", "\\S\\s*$", "/", "gu", ")", "if", "(", "index", ">=", "0", ")", "{", "return", "index", "+", "contentStartIndex", "+", "1", "}", "return", "contentStartIndex", "}", ")", "(", ")", "return", "{", "first", ":", "{", "index", ":", "contentFirstIndex", ",", "loc", ":", "sourceCode", ".", "getLocFromIndex", "(", "contentFirstIndex", ")", ",", "}", ",", "last", ":", "{", "index", ":", "contentLastIndex", ",", "loc", ":", "sourceCode", ".", "getLocFromIndex", "(", "contentLastIndex", ")", ",", "}", ",", "}", "}" ]
Get the comments locations. @param {ASTNode} node The HTML comment. @returns {object} The comments locations.
[ "Get", "the", "comments", "locations", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/html-comment-content-newline.js#L126-L158
23,958
ota-meshi/eslint-plugin-lodash-template
lib/rules/no-multi-spaces-in-html-tag.js
startTagToTokens
function startTagToTokens(startTag) { const tokens = [startTag.tagOpen] for (const attr of startTag.attributes) { tokens.push(attr) } tokens.push(startTag.tagClose) return tokens .filter(t => Boolean(t)) .sort((a, b) => a.range[0] - b.range[0]) }
javascript
function startTagToTokens(startTag) { const tokens = [startTag.tagOpen] for (const attr of startTag.attributes) { tokens.push(attr) } tokens.push(startTag.tagClose) return tokens .filter(t => Boolean(t)) .sort((a, b) => a.range[0] - b.range[0]) }
[ "function", "startTagToTokens", "(", "startTag", ")", "{", "const", "tokens", "=", "[", "startTag", ".", "tagOpen", "]", "for", "(", "const", "attr", "of", "startTag", ".", "attributes", ")", "{", "tokens", ".", "push", "(", "attr", ")", "}", "tokens", ".", "push", "(", "startTag", ".", "tagClose", ")", "return", "tokens", ".", "filter", "(", "t", "=>", "Boolean", "(", "t", ")", ")", ".", "sort", "(", "(", "a", ",", "b", ")", "=>", "a", ".", "range", "[", "0", "]", "-", "b", ".", "range", "[", "0", "]", ")", "}" ]
Convert start tag to Tokens array @param {HTMLStartTag} startTag The start tag @returns {Array} Then tokens
[ "Convert", "start", "tag", "to", "Tokens", "array" ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/no-multi-spaces-in-html-tag.js#L32-L44
23,959
ota-meshi/eslint-plugin-lodash-template
lib/rules/no-multi-spaces-in-html-tag.js
endTagToTokens
function endTagToTokens(endTag) { const tokens = [endTag.tagOpen, endTag.tagClose] return tokens .filter(t => Boolean(t)) .sort((a, b) => a.range[0] - b.range[0]) }
javascript
function endTagToTokens(endTag) { const tokens = [endTag.tagOpen, endTag.tagClose] return tokens .filter(t => Boolean(t)) .sort((a, b) => a.range[0] - b.range[0]) }
[ "function", "endTagToTokens", "(", "endTag", ")", "{", "const", "tokens", "=", "[", "endTag", ".", "tagOpen", ",", "endTag", ".", "tagClose", "]", "return", "tokens", ".", "filter", "(", "t", "=>", "Boolean", "(", "t", ")", ")", ".", "sort", "(", "(", "a", ",", "b", ")", "=>", "a", ".", "range", "[", "0", "]", "-", "b", ".", "range", "[", "0", "]", ")", "}" ]
Convert end tag to Tokens array @param {HTMLEndTag} endTag The end tag @returns {Array} Then tokens
[ "Convert", "end", "tag", "to", "Tokens", "array" ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/no-multi-spaces-in-html-tag.js#L51-L57
23,960
ota-meshi/eslint-plugin-lodash-template
lib/rules/no-multi-spaces-in-html-tag.js
getIntersectionTemplateTags
function getIntersectionTemplateTags(start, end) { return microTemplateService .getMicroTemplateTokens() .filter( token => Math.max(start, token.range[0]) <= Math.min(end, token.range[1]) ) .sort((a, b) => a.range[0] - b.range[0]) }
javascript
function getIntersectionTemplateTags(start, end) { return microTemplateService .getMicroTemplateTokens() .filter( token => Math.max(start, token.range[0]) <= Math.min(end, token.range[1]) ) .sort((a, b) => a.range[0] - b.range[0]) }
[ "function", "getIntersectionTemplateTags", "(", "start", ",", "end", ")", "{", "return", "microTemplateService", ".", "getMicroTemplateTokens", "(", ")", ".", "filter", "(", "token", "=>", "Math", ".", "max", "(", "start", ",", "token", ".", "range", "[", "0", "]", ")", "<=", "Math", ".", "min", "(", "end", ",", "token", ".", "range", "[", "1", "]", ")", ")", ".", "sort", "(", "(", "a", ",", "b", ")", "=>", "a", ".", "range", "[", "0", "]", "-", "b", ".", "range", "[", "0", "]", ")", "}" ]
Get the location intersection in template tags. @param {number} start The location start. @param {number} end The location end. @returns {Array} the location intersection in template tags.
[ "Get", "the", "location", "intersection", "in", "template", "tags", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/no-multi-spaces-in-html-tag.js#L75-L84
23,961
ota-meshi/eslint-plugin-lodash-template
lib/rules/no-multi-spaces-in-html-tag.js
processTokens
function processTokens(tokens) { for (const tokenInfo of genTargetTokens(tokens)) { const prevToken = tokenInfo.prevToken const token = tokenInfo.token const start = prevToken.range[1] const end = token.range[0] const spaces = end - start if ( spaces > 1 && token.loc.start.line === prevToken.loc.start.line && !sourceCode.text.slice(start, end).trim() ) { context.report({ node: token, loc: { start: prevToken.loc.end, end: token.loc.start, }, messageId: "unexpected", fix: defineFix(start, end), data: { displayValue: formatReportedHTMLToken(token), }, }) } } }
javascript
function processTokens(tokens) { for (const tokenInfo of genTargetTokens(tokens)) { const prevToken = tokenInfo.prevToken const token = tokenInfo.token const start = prevToken.range[1] const end = token.range[0] const spaces = end - start if ( spaces > 1 && token.loc.start.line === prevToken.loc.start.line && !sourceCode.text.slice(start, end).trim() ) { context.report({ node: token, loc: { start: prevToken.loc.end, end: token.loc.start, }, messageId: "unexpected", fix: defineFix(start, end), data: { displayValue: formatReportedHTMLToken(token), }, }) } } }
[ "function", "processTokens", "(", "tokens", ")", "{", "for", "(", "const", "tokenInfo", "of", "genTargetTokens", "(", "tokens", ")", ")", "{", "const", "prevToken", "=", "tokenInfo", ".", "prevToken", "const", "token", "=", "tokenInfo", ".", "token", "const", "start", "=", "prevToken", ".", "range", "[", "1", "]", "const", "end", "=", "token", ".", "range", "[", "0", "]", "const", "spaces", "=", "end", "-", "start", "if", "(", "spaces", ">", "1", "&&", "token", ".", "loc", ".", "start", ".", "line", "===", "prevToken", ".", "loc", ".", "start", ".", "line", "&&", "!", "sourceCode", ".", "text", ".", "slice", "(", "start", ",", "end", ")", ".", "trim", "(", ")", ")", "{", "context", ".", "report", "(", "{", "node", ":", "token", ",", "loc", ":", "{", "start", ":", "prevToken", ".", "loc", ".", "end", ",", "end", ":", "token", ".", "loc", ".", "start", ",", "}", ",", "messageId", ":", "\"unexpected\"", ",", "fix", ":", "defineFix", "(", "start", ",", "end", ")", ",", "data", ":", "{", "displayValue", ":", "formatReportedHTMLToken", "(", "token", ")", ",", "}", ",", "}", ")", "}", "}", "}" ]
Process tokens. @param {Array} tokens The tokens. @returns {void}
[ "Process", "tokens", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/no-multi-spaces-in-html-tag.js#L117-L144
23,962
ota-meshi/eslint-plugin-lodash-template
lib/rules/no-multi-spaces-in-html-tag.js
formatReportedHTMLToken
function formatReportedHTMLToken(token) { const valueLines = sourceCode.getText(token).split("\n") const value = valueLines[0] return value }
javascript
function formatReportedHTMLToken(token) { const valueLines = sourceCode.getText(token).split("\n") const value = valueLines[0] return value }
[ "function", "formatReportedHTMLToken", "(", "token", ")", "{", "const", "valueLines", "=", "sourceCode", ".", "getText", "(", "token", ")", ".", "split", "(", "\"\\n\"", ")", "const", "value", "=", "valueLines", "[", "0", "]", "return", "value", "}" ]
Formats value of given token for error message by first line. @param {Token} token The token @returns {string} formatted value @private
[ "Formats", "value", "of", "given", "token", "for", "error", "message", "by", "first", "line", "." ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/rules/no-multi-spaces-in-html-tag.js#L152-L156
23,963
ota-meshi/eslint-plugin-lodash-template
lib/service/SourceCodeStore.js
sortedLastIndexForNum
function sortedLastIndexForNum(array, value) { let low = 0 let high = array == null ? low : array.length while (low < high) { const mid = (low + high) >>> 1 const computed = array[mid] if (computed <= value) { low = mid + 1 } else { high = mid } } return high }
javascript
function sortedLastIndexForNum(array, value) { let low = 0 let high = array == null ? low : array.length while (low < high) { const mid = (low + high) >>> 1 const computed = array[mid] if (computed <= value) { low = mid + 1 } else { high = mid } } return high }
[ "function", "sortedLastIndexForNum", "(", "array", ",", "value", ")", "{", "let", "low", "=", "0", "let", "high", "=", "array", "==", "null", "?", "low", ":", "array", ".", "length", "while", "(", "low", "<", "high", ")", "{", "const", "mid", "=", "(", "low", "+", "high", ")", ">>>", "1", "const", "computed", "=", "array", "[", "mid", "]", "if", "(", "computed", "<=", "value", ")", "{", "low", "=", "mid", "+", "1", "}", "else", "{", "high", "=", "mid", "}", "}", "return", "high", "}" ]
_.sortedLastIndex @param {Array} array The sorted array to inspect. @param {*} value The value to evaluate. @returns {number} Returns the index at which `value` should be inserted into `array`.
[ "_", ".", "sortedLastIndex" ]
9ff820d58da1eea47f12a87939e62a23cc07561d
https://github.com/ota-meshi/eslint-plugin-lodash-template/blob/9ff820d58da1eea47f12a87939e62a23cc07561d/lib/service/SourceCodeStore.js#L11-L25
23,964
anvaka/query-state
lib/windowHistory.js
init
function init() { var stateFromHash = getStateFromHash(); var stateChanged = false; if (typeof defaults === 'object' && defaults) { Object.keys(defaults).forEach(function(key) { if (key in stateFromHash) return; stateFromHash[key] = defaults[key] stateChanged = true; }); } if (stateChanged) set(stateFromHash); }
javascript
function init() { var stateFromHash = getStateFromHash(); var stateChanged = false; if (typeof defaults === 'object' && defaults) { Object.keys(defaults).forEach(function(key) { if (key in stateFromHash) return; stateFromHash[key] = defaults[key] stateChanged = true; }); } if (stateChanged) set(stateFromHash); }
[ "function", "init", "(", ")", "{", "var", "stateFromHash", "=", "getStateFromHash", "(", ")", ";", "var", "stateChanged", "=", "false", ";", "if", "(", "typeof", "defaults", "===", "'object'", "&&", "defaults", ")", "{", "Object", ".", "keys", "(", "defaults", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "key", "in", "stateFromHash", ")", "return", ";", "stateFromHash", "[", "key", "]", "=", "defaults", "[", "key", "]", "stateChanged", "=", "true", ";", "}", ")", ";", "}", "if", "(", "stateChanged", ")", "set", "(", "stateFromHash", ")", ";", "}" ]
Public API is over. You can ignore this part.
[ "Public", "API", "is", "over", ".", "You", "can", "ignore", "this", "part", "." ]
99b19b10f75dc3afae75b20f33960adc4f57b92b
https://github.com/anvaka/query-state/blob/99b19b10f75dc3afae75b20f33960adc4f57b92b/lib/windowHistory.js#L66-L80
23,965
anvaka/query-state
index.js
queryState
function queryState(defaults, options) { options = options || {}; var history = options.history || windowHistory(defaults, options); validateHistoryAPI(history); history.onChanged(updateQuery) var query = history.get() || Object.create(null); var api = { /** * Gets current state. * * @param {string?} keyName if present then value for this key is returned. * Otherwise the entire app state is returned. */ get: getValue, /** * Merges current app state with new key/value. * * @param {string} key name * @param {string|number|date} value */ set: setValue, /** * Removes value from the query string */ unset: unsetValue, /** * Similar to `set()`, but only sets value if it was not set before. * * @param {string} key name * @param {string|number|date} value */ setIfEmpty: setIfEmpty, /** * Releases all resources acquired by query state. After calling this method * no hash monitoring will happen and no more events will be fired. */ dispose: dispose, onChange: onChange, offChange: offChange, getHistoryObject: getHistoryObject, } var eventBus = eventify({}); return api; function onChange(callback, ctx) { eventBus.on('change', callback, ctx); } function offChange(callback, ctx) { eventBus.off('change', callback, ctx) } function getHistoryObject() { return history; } function dispose() { // dispose all history listeners history.dispose(); // And remove our own listeners eventBus.off(); } function getValue(keyName) { if (keyName === undefined) return query; return query[keyName]; } function setValue(keyName, value) { var keyNameType = typeof keyName; if (keyNameType === 'object') { Object.keys(keyName).forEach(function(key) { query[key] = keyName[key]; }); } else if (keyNameType === 'string') { query[keyName] = value; } history.set(query); return api; } function unsetValue(keyName) { if (!(keyName in query)) return; // nothing to do delete query[keyName]; history.set(query); return api; } function updateQuery(newAppState) { query = newAppState; eventBus.fire('change', query); } function setIfEmpty(keyName, value) { if (typeof keyName === 'object') { Object.keys(keyName).forEach(function(key) { // TODO: Can I remove code duplication? The main reason why I don't // want recursion here is to avoid spamming `history.set()` if (key in query) return; // key name is not empty query[key] = keyName[key]; }); } if (keyName in query) return; // key name is not empty query[keyName] = value; history.set(query); return api; } }
javascript
function queryState(defaults, options) { options = options || {}; var history = options.history || windowHistory(defaults, options); validateHistoryAPI(history); history.onChanged(updateQuery) var query = history.get() || Object.create(null); var api = { /** * Gets current state. * * @param {string?} keyName if present then value for this key is returned. * Otherwise the entire app state is returned. */ get: getValue, /** * Merges current app state with new key/value. * * @param {string} key name * @param {string|number|date} value */ set: setValue, /** * Removes value from the query string */ unset: unsetValue, /** * Similar to `set()`, but only sets value if it was not set before. * * @param {string} key name * @param {string|number|date} value */ setIfEmpty: setIfEmpty, /** * Releases all resources acquired by query state. After calling this method * no hash monitoring will happen and no more events will be fired. */ dispose: dispose, onChange: onChange, offChange: offChange, getHistoryObject: getHistoryObject, } var eventBus = eventify({}); return api; function onChange(callback, ctx) { eventBus.on('change', callback, ctx); } function offChange(callback, ctx) { eventBus.off('change', callback, ctx) } function getHistoryObject() { return history; } function dispose() { // dispose all history listeners history.dispose(); // And remove our own listeners eventBus.off(); } function getValue(keyName) { if (keyName === undefined) return query; return query[keyName]; } function setValue(keyName, value) { var keyNameType = typeof keyName; if (keyNameType === 'object') { Object.keys(keyName).forEach(function(key) { query[key] = keyName[key]; }); } else if (keyNameType === 'string') { query[keyName] = value; } history.set(query); return api; } function unsetValue(keyName) { if (!(keyName in query)) return; // nothing to do delete query[keyName]; history.set(query); return api; } function updateQuery(newAppState) { query = newAppState; eventBus.fire('change', query); } function setIfEmpty(keyName, value) { if (typeof keyName === 'object') { Object.keys(keyName).forEach(function(key) { // TODO: Can I remove code duplication? The main reason why I don't // want recursion here is to avoid spamming `history.set()` if (key in query) return; // key name is not empty query[key] = keyName[key]; }); } if (keyName in query) return; // key name is not empty query[keyName] = value; history.set(query); return api; } }
[ "function", "queryState", "(", "defaults", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "history", "=", "options", ".", "history", "||", "windowHistory", "(", "defaults", ",", "options", ")", ";", "validateHistoryAPI", "(", "history", ")", ";", "history", ".", "onChanged", "(", "updateQuery", ")", "var", "query", "=", "history", ".", "get", "(", ")", "||", "Object", ".", "create", "(", "null", ")", ";", "var", "api", "=", "{", "/**\n * Gets current state.\n *\n * @param {string?} keyName if present then value for this key is returned.\n * Otherwise the entire app state is returned.\n */", "get", ":", "getValue", ",", "/**\n * Merges current app state with new key/value.\n *\n * @param {string} key name\n * @param {string|number|date} value\n */", "set", ":", "setValue", ",", "/**\n * Removes value from the query string\n */", "unset", ":", "unsetValue", ",", "/**\n * Similar to `set()`, but only sets value if it was not set before.\n *\n * @param {string} key name\n * @param {string|number|date} value\n */", "setIfEmpty", ":", "setIfEmpty", ",", "/**\n * Releases all resources acquired by query state. After calling this method\n * no hash monitoring will happen and no more events will be fired.\n */", "dispose", ":", "dispose", ",", "onChange", ":", "onChange", ",", "offChange", ":", "offChange", ",", "getHistoryObject", ":", "getHistoryObject", ",", "}", "var", "eventBus", "=", "eventify", "(", "{", "}", ")", ";", "return", "api", ";", "function", "onChange", "(", "callback", ",", "ctx", ")", "{", "eventBus", ".", "on", "(", "'change'", ",", "callback", ",", "ctx", ")", ";", "}", "function", "offChange", "(", "callback", ",", "ctx", ")", "{", "eventBus", ".", "off", "(", "'change'", ",", "callback", ",", "ctx", ")", "}", "function", "getHistoryObject", "(", ")", "{", "return", "history", ";", "}", "function", "dispose", "(", ")", "{", "// dispose all history listeners", "history", ".", "dispose", "(", ")", ";", "// And remove our own listeners", "eventBus", ".", "off", "(", ")", ";", "}", "function", "getValue", "(", "keyName", ")", "{", "if", "(", "keyName", "===", "undefined", ")", "return", "query", ";", "return", "query", "[", "keyName", "]", ";", "}", "function", "setValue", "(", "keyName", ",", "value", ")", "{", "var", "keyNameType", "=", "typeof", "keyName", ";", "if", "(", "keyNameType", "===", "'object'", ")", "{", "Object", ".", "keys", "(", "keyName", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "query", "[", "key", "]", "=", "keyName", "[", "key", "]", ";", "}", ")", ";", "}", "else", "if", "(", "keyNameType", "===", "'string'", ")", "{", "query", "[", "keyName", "]", "=", "value", ";", "}", "history", ".", "set", "(", "query", ")", ";", "return", "api", ";", "}", "function", "unsetValue", "(", "keyName", ")", "{", "if", "(", "!", "(", "keyName", "in", "query", ")", ")", "return", ";", "// nothing to do", "delete", "query", "[", "keyName", "]", ";", "history", ".", "set", "(", "query", ")", ";", "return", "api", ";", "}", "function", "updateQuery", "(", "newAppState", ")", "{", "query", "=", "newAppState", ";", "eventBus", ".", "fire", "(", "'change'", ",", "query", ")", ";", "}", "function", "setIfEmpty", "(", "keyName", ",", "value", ")", "{", "if", "(", "typeof", "keyName", "===", "'object'", ")", "{", "Object", ".", "keys", "(", "keyName", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "// TODO: Can I remove code duplication? The main reason why I don't", "// want recursion here is to avoid spamming `history.set()`", "if", "(", "key", "in", "query", ")", "return", ";", "// key name is not empty", "query", "[", "key", "]", "=", "keyName", "[", "key", "]", ";", "}", ")", ";", "}", "if", "(", "keyName", "in", "query", ")", "return", ";", "// key name is not empty", "query", "[", "keyName", "]", "=", "value", ";", "history", ".", "set", "(", "query", ")", ";", "return", "api", ";", "}", "}" ]
Creates new instance of the query state.
[ "Creates", "new", "instance", "of", "the", "query", "state", "." ]
99b19b10f75dc3afae75b20f33960adc4f57b92b
https://github.com/anvaka/query-state/blob/99b19b10f75dc3afae75b20f33960adc4f57b92b/index.js#L20-L150
23,966
anvaka/query-state
index.js
instance
function instance(defaults, options) { if (!singletonQS) { singletonQS = queryState(defaults, options); } else if (defaults) { singletonQS.setIfEmpty(defaults); } return singletonQS; }
javascript
function instance(defaults, options) { if (!singletonQS) { singletonQS = queryState(defaults, options); } else if (defaults) { singletonQS.setIfEmpty(defaults); } return singletonQS; }
[ "function", "instance", "(", "defaults", ",", "options", ")", "{", "if", "(", "!", "singletonQS", ")", "{", "singletonQS", "=", "queryState", "(", "defaults", ",", "options", ")", ";", "}", "else", "if", "(", "defaults", ")", "{", "singletonQS", ".", "setIfEmpty", "(", "defaults", ")", ";", "}", "return", "singletonQS", ";", "}" ]
Returns singleton instance of the query state. @param {Object} defaults - if present, then it is passed to the current instance of the query state. Defaults are applied only if they were not present before.
[ "Returns", "singleton", "instance", "of", "the", "query", "state", "." ]
99b19b10f75dc3afae75b20f33960adc4f57b92b
https://github.com/anvaka/query-state/blob/99b19b10f75dc3afae75b20f33960adc4f57b92b/index.js#L158-L166
23,967
nighca/universal-diff
dist/diff.js
function(seq1, seq2, stepMap){ // get contrast arrays (src & target) by analyze step by step var l1 = seq1.length, l2 = seq2.length, src = [], target = []; for(var i = l1,j = l2; i > 0 || j > 0;){ switch(stepMap[i][j]){ case STEP_NOCHANGE: src.unshift(seq1[i-1]); target.unshift(MARK_SAME); i -= 1; j -= 1; break; case STEP_REPLACE: src.unshift(seq1[i-1]); target.unshift(seq2[j-1]); i -= 1; j -= 1; break; case STEP_REMOVE: src.unshift(seq1[i-1]); target.unshift(MARK_EMPTY); i -= 1; j -= 0; break; case STEP_INSERT: src.unshift(MARK_EMPTY); target.unshift(seq2[j-1]); i -= 0; j -= 1; break; } } return { src: src, target: target }; }
javascript
function(seq1, seq2, stepMap){ // get contrast arrays (src & target) by analyze step by step var l1 = seq1.length, l2 = seq2.length, src = [], target = []; for(var i = l1,j = l2; i > 0 || j > 0;){ switch(stepMap[i][j]){ case STEP_NOCHANGE: src.unshift(seq1[i-1]); target.unshift(MARK_SAME); i -= 1; j -= 1; break; case STEP_REPLACE: src.unshift(seq1[i-1]); target.unshift(seq2[j-1]); i -= 1; j -= 1; break; case STEP_REMOVE: src.unshift(seq1[i-1]); target.unshift(MARK_EMPTY); i -= 1; j -= 0; break; case STEP_INSERT: src.unshift(MARK_EMPTY); target.unshift(seq2[j-1]); i -= 0; j -= 1; break; } } return { src: src, target: target }; }
[ "function", "(", "seq1", ",", "seq2", ",", "stepMap", ")", "{", "// get contrast arrays (src & target) by analyze step by step", "var", "l1", "=", "seq1", ".", "length", ",", "l2", "=", "seq2", ".", "length", ",", "src", "=", "[", "]", ",", "target", "=", "[", "]", ";", "for", "(", "var", "i", "=", "l1", ",", "j", "=", "l2", ";", "i", ">", "0", "||", "j", ">", "0", ";", ")", "{", "switch", "(", "stepMap", "[", "i", "]", "[", "j", "]", ")", "{", "case", "STEP_NOCHANGE", ":", "src", ".", "unshift", "(", "seq1", "[", "i", "-", "1", "]", ")", ";", "target", ".", "unshift", "(", "MARK_SAME", ")", ";", "i", "-=", "1", ";", "j", "-=", "1", ";", "break", ";", "case", "STEP_REPLACE", ":", "src", ".", "unshift", "(", "seq1", "[", "i", "-", "1", "]", ")", ";", "target", ".", "unshift", "(", "seq2", "[", "j", "-", "1", "]", ")", ";", "i", "-=", "1", ";", "j", "-=", "1", ";", "break", ";", "case", "STEP_REMOVE", ":", "src", ".", "unshift", "(", "seq1", "[", "i", "-", "1", "]", ")", ";", "target", ".", "unshift", "(", "MARK_EMPTY", ")", ";", "i", "-=", "1", ";", "j", "-=", "0", ";", "break", ";", "case", "STEP_INSERT", ":", "src", ".", "unshift", "(", "MARK_EMPTY", ")", ";", "target", ".", "unshift", "(", "seq2", "[", "j", "-", "1", "]", ")", ";", "i", "-=", "0", ";", "j", "-=", "1", ";", "break", ";", "}", "}", "return", "{", "src", ":", "src", ",", "target", ":", "target", "}", ";", "}" ]
stepMap to contrast array
[ "stepMap", "to", "contrast", "array" ]
41ae67d209e0d238d1ceb07e6025d6d9e91f6ed7
https://github.com/nighca/universal-diff/blob/41ae67d209e0d238d1ceb07e6025d6d9e91f6ed7/dist/diff.js#L122-L166
23,968
nighca/universal-diff
dist/diff.js
function(seq1, seq2, eq){ // do compare var stepMap = coreCompare(seq1, seq2, eq); // transform stepMap var contrast = transformStepMap(seq1, seq2, stepMap), src = contrast.src, target = contrast.target; // convert contrast arrays to edit script var l = target.length, start, len, to, notEmpty = function(s){return s !== MARK_EMPTY;}, script = [], i, j; for(i = l - 1; i >= 0;){ // join continuous diffs for(j = i; target[j] !== MARK_SAME && j >= 0; j--){} if(j < i){ start = src.slice(0, j + 1).filter(notEmpty).length; // start pos of diffs (on src) len = src.slice(j + 1, i + 1).filter(notEmpty).length; // length should be replaced (on src) to = target.slice(j + 1, i + 1).filter(notEmpty); // new content script.unshift( to.length ? [start, len, to] : // replace [start, len] // remove ); } i = j - 1; } return script; }
javascript
function(seq1, seq2, eq){ // do compare var stepMap = coreCompare(seq1, seq2, eq); // transform stepMap var contrast = transformStepMap(seq1, seq2, stepMap), src = contrast.src, target = contrast.target; // convert contrast arrays to edit script var l = target.length, start, len, to, notEmpty = function(s){return s !== MARK_EMPTY;}, script = [], i, j; for(i = l - 1; i >= 0;){ // join continuous diffs for(j = i; target[j] !== MARK_SAME && j >= 0; j--){} if(j < i){ start = src.slice(0, j + 1).filter(notEmpty).length; // start pos of diffs (on src) len = src.slice(j + 1, i + 1).filter(notEmpty).length; // length should be replaced (on src) to = target.slice(j + 1, i + 1).filter(notEmpty); // new content script.unshift( to.length ? [start, len, to] : // replace [start, len] // remove ); } i = j - 1; } return script; }
[ "function", "(", "seq1", ",", "seq2", ",", "eq", ")", "{", "// do compare", "var", "stepMap", "=", "coreCompare", "(", "seq1", ",", "seq2", ",", "eq", ")", ";", "// transform stepMap", "var", "contrast", "=", "transformStepMap", "(", "seq1", ",", "seq2", ",", "stepMap", ")", ",", "src", "=", "contrast", ".", "src", ",", "target", "=", "contrast", ".", "target", ";", "// convert contrast arrays to edit script", "var", "l", "=", "target", ".", "length", ",", "start", ",", "len", ",", "to", ",", "notEmpty", "=", "function", "(", "s", ")", "{", "return", "s", "!==", "MARK_EMPTY", ";", "}", ",", "script", "=", "[", "]", ",", "i", ",", "j", ";", "for", "(", "i", "=", "l", "-", "1", ";", "i", ">=", "0", ";", ")", "{", "// join continuous diffs", "for", "(", "j", "=", "i", ";", "target", "[", "j", "]", "!==", "MARK_SAME", "&&", "j", ">=", "0", ";", "j", "--", ")", "{", "}", "if", "(", "j", "<", "i", ")", "{", "start", "=", "src", ".", "slice", "(", "0", ",", "j", "+", "1", ")", ".", "filter", "(", "notEmpty", ")", ".", "length", ";", "// start pos of diffs (on src)", "len", "=", "src", ".", "slice", "(", "j", "+", "1", ",", "i", "+", "1", ")", ".", "filter", "(", "notEmpty", ")", ".", "length", ";", "// length should be replaced (on src)", "to", "=", "target", ".", "slice", "(", "j", "+", "1", ",", "i", "+", "1", ")", ".", "filter", "(", "notEmpty", ")", ";", "// new content", "script", ".", "unshift", "(", "to", ".", "length", "?", "[", "start", ",", "len", ",", "to", "]", ":", "// replace", "[", "start", ",", "len", "]", "// remove", ")", ";", "}", "i", "=", "j", "-", "1", ";", "}", "return", "script", ";", "}" ]
get edit script
[ "get", "edit", "script" ]
41ae67d209e0d238d1ceb07e6025d6d9e91f6ed7
https://github.com/nighca/universal-diff/blob/41ae67d209e0d238d1ceb07e6025d6d9e91f6ed7/dist/diff.js#L169-L206
23,969
anvaka/query-state
lib/query.js
decodeValue
function decodeValue(value) { value = decodeURIComponent(value); if (value === "") return value; if (!isNaN(value)) return parseFloat(value); if (isBolean(value)) return value === 'true'; if (isISODateString(value)) return new Date(value); return value; }
javascript
function decodeValue(value) { value = decodeURIComponent(value); if (value === "") return value; if (!isNaN(value)) return parseFloat(value); if (isBolean(value)) return value === 'true'; if (isISODateString(value)) return new Date(value); return value; }
[ "function", "decodeValue", "(", "value", ")", "{", "value", "=", "decodeURIComponent", "(", "value", ")", ";", "if", "(", "value", "===", "\"\"", ")", "return", "value", ";", "if", "(", "!", "isNaN", "(", "value", ")", ")", "return", "parseFloat", "(", "value", ")", ";", "if", "(", "isBolean", "(", "value", ")", ")", "return", "value", "===", "'true'", ";", "if", "(", "isISODateString", "(", "value", ")", ")", "return", "new", "Date", "(", "value", ")", ";", "return", "value", ";", "}" ]
This method returns typed value from string
[ "This", "method", "returns", "typed", "value", "from", "string" ]
99b19b10f75dc3afae75b20f33960adc4f57b92b
https://github.com/anvaka/query-state/blob/99b19b10f75dc3afae75b20f33960adc4f57b92b/lib/query.js#L76-L85
23,970
angular-ui/ui-tinymce
src/tinymce.js
function() { var UITinymceService = function() { var ID_ATTR = 'ui-tinymce'; // uniqueId keeps track of the latest assigned ID var uniqueId = 0; // getUniqueId returns a unique ID var getUniqueId = function() { uniqueId ++; return ID_ATTR + '-' + uniqueId; }; // return the function as a public method of the service return { getUniqueId: getUniqueId }; }; // return a new instance of the service return new UITinymceService(); }
javascript
function() { var UITinymceService = function() { var ID_ATTR = 'ui-tinymce'; // uniqueId keeps track of the latest assigned ID var uniqueId = 0; // getUniqueId returns a unique ID var getUniqueId = function() { uniqueId ++; return ID_ATTR + '-' + uniqueId; }; // return the function as a public method of the service return { getUniqueId: getUniqueId }; }; // return a new instance of the service return new UITinymceService(); }
[ "function", "(", ")", "{", "var", "UITinymceService", "=", "function", "(", ")", "{", "var", "ID_ATTR", "=", "'ui-tinymce'", ";", "// uniqueId keeps track of the latest assigned ID", "var", "uniqueId", "=", "0", ";", "// getUniqueId returns a unique ID", "var", "getUniqueId", "=", "function", "(", ")", "{", "uniqueId", "++", ";", "return", "ID_ATTR", "+", "'-'", "+", "uniqueId", ";", "}", ";", "// return the function as a public method of the service", "return", "{", "getUniqueId", ":", "getUniqueId", "}", ";", "}", ";", "// return a new instance of the service", "return", "new", "UITinymceService", "(", ")", ";", "}" ]
A service is used to create unique ID's, this prevents duplicate ID's if there are multiple editors on screen.
[ "A", "service", "is", "used", "to", "create", "unique", "ID", "s", "this", "prevents", "duplicate", "ID", "s", "if", "there", "are", "multiple", "editors", "on", "screen", "." ]
30434e227768c47cdcf97b552cdbc4f12fad86da
https://github.com/angular-ui/ui-tinymce/blob/30434e227768c47cdcf97b552cdbc4f12fad86da/src/tinymce.js#L217-L234
23,971
aurelia/router
dist/es2015/aurelia-router.js
inspect
function inspect(val, router) { if (ignoreResult || shouldContinue(val, router)) { return iterate(); } return next.cancel(val); }
javascript
function inspect(val, router) { if (ignoreResult || shouldContinue(val, router)) { return iterate(); } return next.cancel(val); }
[ "function", "inspect", "(", "val", ",", "router", ")", "{", "if", "(", "ignoreResult", "||", "shouldContinue", "(", "val", ",", "router", ")", ")", "{", "return", "iterate", "(", ")", ";", "}", "return", "next", ".", "cancel", "(", "val", ")", ";", "}" ]
query from top down
[ "query", "from", "top", "down" ]
893b768f01aea842ee57db4222e66aa572f24404
https://github.com/aurelia/router/blob/893b768f01aea842ee57db4222e66aa572f24404/dist/es2015/aurelia-router.js#L1614-L1619
23,972
aurelia/router
dist/amd/aurelia-router.js
function (navigationInstruction, callbackName, next, ignoreResult) { var plan = navigationInstruction.plan; var infos = findDeactivatable(plan, callbackName); var i = infos.length; // query from inside out function inspect(val) { if (ignoreResult || shouldContinue(val)) { return iterate(); } return next.cancel(val); } function iterate() { if (i--) { try { var viewModel = infos[i]; var result = viewModel[callbackName](navigationInstruction); return processPotential(result, inspect, next.cancel); } catch (error) { return next.cancel(error); } } navigationInstruction.router.couldDeactivate = true; return next(); } return iterate(); }
javascript
function (navigationInstruction, callbackName, next, ignoreResult) { var plan = navigationInstruction.plan; var infos = findDeactivatable(plan, callbackName); var i = infos.length; // query from inside out function inspect(val) { if (ignoreResult || shouldContinue(val)) { return iterate(); } return next.cancel(val); } function iterate() { if (i--) { try { var viewModel = infos[i]; var result = viewModel[callbackName](navigationInstruction); return processPotential(result, inspect, next.cancel); } catch (error) { return next.cancel(error); } } navigationInstruction.router.couldDeactivate = true; return next(); } return iterate(); }
[ "function", "(", "navigationInstruction", ",", "callbackName", ",", "next", ",", "ignoreResult", ")", "{", "var", "plan", "=", "navigationInstruction", ".", "plan", ";", "var", "infos", "=", "findDeactivatable", "(", "plan", ",", "callbackName", ")", ";", "var", "i", "=", "infos", ".", "length", ";", "// query from inside out\r", "function", "inspect", "(", "val", ")", "{", "if", "(", "ignoreResult", "||", "shouldContinue", "(", "val", ")", ")", "{", "return", "iterate", "(", ")", ";", "}", "return", "next", ".", "cancel", "(", "val", ")", ";", "}", "function", "iterate", "(", ")", "{", "if", "(", "i", "--", ")", "{", "try", "{", "var", "viewModel", "=", "infos", "[", "i", "]", ";", "var", "result", "=", "viewModel", "[", "callbackName", "]", "(", "navigationInstruction", ")", ";", "return", "processPotential", "(", "result", ",", "inspect", ",", "next", ".", "cancel", ")", ";", "}", "catch", "(", "error", ")", "{", "return", "next", ".", "cancel", "(", "error", ")", ";", "}", "}", "navigationInstruction", ".", "router", ".", "couldDeactivate", "=", "true", ";", "return", "next", "(", ")", ";", "}", "return", "iterate", "(", ")", ";", "}" ]
Recursively find list of deactivate-able view models and invoke the either 'canDeactivate' or 'deactivate' on each @internal exported for unit testing
[ "Recursively", "find", "list", "of", "deactivate", "-", "able", "view", "models", "and", "invoke", "the", "either", "canDeactivate", "or", "deactivate", "on", "each" ]
893b768f01aea842ee57db4222e66aa572f24404
https://github.com/aurelia/router/blob/893b768f01aea842ee57db4222e66aa572f24404/dist/amd/aurelia-router.js#L1609-L1634
23,973
aurelia/router
dist/amd/aurelia-router.js
function (plan, callbackName, list) { if (list === void 0) { list = []; } for (var viewPortName in plan) { var viewPortPlan = plan[viewPortName]; var prevComponent = viewPortPlan.prevComponent; if ((viewPortPlan.strategy === activationStrategy.invokeLifecycle || viewPortPlan.strategy === activationStrategy.replace) && prevComponent) { var viewModel = prevComponent.viewModel; if (callbackName in viewModel) { list.push(viewModel); } } if (viewPortPlan.strategy === activationStrategy.replace && prevComponent) { addPreviousDeactivatable(prevComponent, callbackName, list); } else if (viewPortPlan.childNavigationInstruction) { findDeactivatable(viewPortPlan.childNavigationInstruction.plan, callbackName, list); } } return list; }
javascript
function (plan, callbackName, list) { if (list === void 0) { list = []; } for (var viewPortName in plan) { var viewPortPlan = plan[viewPortName]; var prevComponent = viewPortPlan.prevComponent; if ((viewPortPlan.strategy === activationStrategy.invokeLifecycle || viewPortPlan.strategy === activationStrategy.replace) && prevComponent) { var viewModel = prevComponent.viewModel; if (callbackName in viewModel) { list.push(viewModel); } } if (viewPortPlan.strategy === activationStrategy.replace && prevComponent) { addPreviousDeactivatable(prevComponent, callbackName, list); } else if (viewPortPlan.childNavigationInstruction) { findDeactivatable(viewPortPlan.childNavigationInstruction.plan, callbackName, list); } } return list; }
[ "function", "(", "plan", ",", "callbackName", ",", "list", ")", "{", "if", "(", "list", "===", "void", "0", ")", "{", "list", "=", "[", "]", ";", "}", "for", "(", "var", "viewPortName", "in", "plan", ")", "{", "var", "viewPortPlan", "=", "plan", "[", "viewPortName", "]", ";", "var", "prevComponent", "=", "viewPortPlan", ".", "prevComponent", ";", "if", "(", "(", "viewPortPlan", ".", "strategy", "===", "activationStrategy", ".", "invokeLifecycle", "||", "viewPortPlan", ".", "strategy", "===", "activationStrategy", ".", "replace", ")", "&&", "prevComponent", ")", "{", "var", "viewModel", "=", "prevComponent", ".", "viewModel", ";", "if", "(", "callbackName", "in", "viewModel", ")", "{", "list", ".", "push", "(", "viewModel", ")", ";", "}", "}", "if", "(", "viewPortPlan", ".", "strategy", "===", "activationStrategy", ".", "replace", "&&", "prevComponent", ")", "{", "addPreviousDeactivatable", "(", "prevComponent", ",", "callbackName", ",", "list", ")", ";", "}", "else", "if", "(", "viewPortPlan", ".", "childNavigationInstruction", ")", "{", "findDeactivatable", "(", "viewPortPlan", ".", "childNavigationInstruction", ".", "plan", ",", "callbackName", ",", "list", ")", ";", "}", "}", "return", "list", ";", "}" ]
Recursively find and returns a list of deactivate-able view models @internal exported for unit testing
[ "Recursively", "find", "and", "returns", "a", "list", "of", "deactivate", "-", "able", "view", "models" ]
893b768f01aea842ee57db4222e66aa572f24404
https://github.com/aurelia/router/blob/893b768f01aea842ee57db4222e66aa572f24404/dist/amd/aurelia-router.js#L1639-L1659
23,974
aurelia/router
dist/commonjs/aurelia-router.js
function (routeLoader, navigationInstruction, config) { var router = navigationInstruction.router; var lifecycleArgs = navigationInstruction.lifecycleArgs; return Promise.resolve() .then(function () { return routeLoader.loadRoute(router, config, navigationInstruction); }) .then( /** * @param component an object carrying information about loaded route * typically contains information about view model, childContainer, view and router */ function (component) { var viewModel = component.viewModel, childContainer = component.childContainer; component.router = router; component.config = config; if ('configureRouter' in viewModel) { var childRouter_1 = childContainer.getChildRouter(); component.childRouter = childRouter_1; return childRouter_1 .configure(function (c) { return viewModel.configureRouter(c, childRouter_1, lifecycleArgs[0], lifecycleArgs[1], lifecycleArgs[2]); }) .then(function () { return component; }); } return component; }); }
javascript
function (routeLoader, navigationInstruction, config) { var router = navigationInstruction.router; var lifecycleArgs = navigationInstruction.lifecycleArgs; return Promise.resolve() .then(function () { return routeLoader.loadRoute(router, config, navigationInstruction); }) .then( /** * @param component an object carrying information about loaded route * typically contains information about view model, childContainer, view and router */ function (component) { var viewModel = component.viewModel, childContainer = component.childContainer; component.router = router; component.config = config; if ('configureRouter' in viewModel) { var childRouter_1 = childContainer.getChildRouter(); component.childRouter = childRouter_1; return childRouter_1 .configure(function (c) { return viewModel.configureRouter(c, childRouter_1, lifecycleArgs[0], lifecycleArgs[1], lifecycleArgs[2]); }) .then(function () { return component; }); } return component; }); }
[ "function", "(", "routeLoader", ",", "navigationInstruction", ",", "config", ")", "{", "var", "router", "=", "navigationInstruction", ".", "router", ";", "var", "lifecycleArgs", "=", "navigationInstruction", ".", "lifecycleArgs", ";", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "function", "(", ")", "{", "return", "routeLoader", ".", "loadRoute", "(", "router", ",", "config", ",", "navigationInstruction", ")", ";", "}", ")", ".", "then", "(", "/**\r\n * @param component an object carrying information about loaded route\r\n * typically contains information about view model, childContainer, view and router\r\n */", "function", "(", "component", ")", "{", "var", "viewModel", "=", "component", ".", "viewModel", ",", "childContainer", "=", "component", ".", "childContainer", ";", "component", ".", "router", "=", "router", ";", "component", ".", "config", "=", "config", ";", "if", "(", "'configureRouter'", "in", "viewModel", ")", "{", "var", "childRouter_1", "=", "childContainer", ".", "getChildRouter", "(", ")", ";", "component", ".", "childRouter", "=", "childRouter_1", ";", "return", "childRouter_1", ".", "configure", "(", "function", "(", "c", ")", "{", "return", "viewModel", ".", "configureRouter", "(", "c", ",", "childRouter_1", ",", "lifecycleArgs", "[", "0", "]", ",", "lifecycleArgs", "[", "1", "]", ",", "lifecycleArgs", "[", "2", "]", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "component", ";", "}", ")", ";", "}", "return", "component", ";", "}", ")", ";", "}" ]
Load a routed-component based on navigation instruction and route config @internal exported for unit testing only
[ "Load", "a", "routed", "-", "component", "based", "on", "navigation", "instruction", "and", "route", "config" ]
893b768f01aea842ee57db4222e66aa572f24404
https://github.com/aurelia/router/blob/893b768f01aea842ee57db4222e66aa572f24404/dist/commonjs/aurelia-router.js#L1504-L1527
23,975
ionic-team/ionic-plugin-keyboard
src/blackberry10/index.js
function (success, fail, args, env) { var result = new PluginResult(args, env); result.ok(keyboard.getInstance().startService(), false); }
javascript
function (success, fail, args, env) { var result = new PluginResult(args, env); result.ok(keyboard.getInstance().startService(), false); }
[ "function", "(", "success", ",", "fail", ",", "args", ",", "env", ")", "{", "var", "result", "=", "new", "PluginResult", "(", "args", ",", "env", ")", ";", "result", ".", "ok", "(", "keyboard", ".", "getInstance", "(", ")", ".", "startService", "(", ")", ",", "false", ")", ";", "}" ]
These methods call into JNEXT.Keyboard which handles the communication through the JNEXT plugin to keyboard_js.cpp
[ "These", "methods", "call", "into", "JNEXT", ".", "Keyboard", "which", "handles", "the", "communication", "through", "the", "JNEXT", "plugin", "to", "keyboard_js", ".", "cpp" ]
93024cf825aade60859ee71af3ad46dda008e6bf
https://github.com/ionic-team/ionic-plugin-keyboard/blob/93024cf825aade60859ee71af3ad46dda008e6bf/src/blackberry10/index.js#L16-L20
23,976
fuzhenn/chinese_coordinate_conversion
chncrs.js
function (wgsLon, wgsLat) { if (this.outOfChina(wgsLat, wgsLon)) return [wgsLon, wgsLat]; var d = this.delta(wgsLat, wgsLon); return [wgsLon + d.lon, wgsLat + d.lat]; }
javascript
function (wgsLon, wgsLat) { if (this.outOfChina(wgsLat, wgsLon)) return [wgsLon, wgsLat]; var d = this.delta(wgsLat, wgsLon); return [wgsLon + d.lon, wgsLat + d.lat]; }
[ "function", "(", "wgsLon", ",", "wgsLat", ")", "{", "if", "(", "this", ".", "outOfChina", "(", "wgsLat", ",", "wgsLon", ")", ")", "return", "[", "wgsLon", ",", "wgsLat", "]", ";", "var", "d", "=", "this", ".", "delta", "(", "wgsLat", ",", "wgsLon", ")", ";", "return", "[", "wgsLon", "+", "d", ".", "lon", ",", "wgsLat", "+", "d", ".", "lat", "]", ";", "}" ]
WGS-84 to GCJ-02
[ "WGS", "-", "84", "to", "GCJ", "-", "02" ]
448e4e4ad4b4a84422305d7263c74d44e72dbb6a
https://github.com/fuzhenn/chinese_coordinate_conversion/blob/448e4e4ad4b4a84422305d7263c74d44e72dbb6a/chncrs.js#L34-L40
23,977
fuzhenn/chinese_coordinate_conversion
chncrs.js
function (gcjLon, gcjLat) { if (this.outOfChina(gcjLat, gcjLon)) return [gcjLon, gcjLat]; var d = this.delta(gcjLat, gcjLon); return [gcjLon - d.lon, gcjLat - d.lat]; }
javascript
function (gcjLon, gcjLat) { if (this.outOfChina(gcjLat, gcjLon)) return [gcjLon, gcjLat]; var d = this.delta(gcjLat, gcjLon); return [gcjLon - d.lon, gcjLat - d.lat]; }
[ "function", "(", "gcjLon", ",", "gcjLat", ")", "{", "if", "(", "this", ".", "outOfChina", "(", "gcjLat", ",", "gcjLon", ")", ")", "return", "[", "gcjLon", ",", "gcjLat", "]", ";", "var", "d", "=", "this", ".", "delta", "(", "gcjLat", ",", "gcjLon", ")", ";", "return", "[", "gcjLon", "-", "d", ".", "lon", ",", "gcjLat", "-", "d", ".", "lat", "]", ";", "}" ]
GCJ-02 to WGS-84
[ "GCJ", "-", "02", "to", "WGS", "-", "84" ]
448e4e4ad4b4a84422305d7263c74d44e72dbb6a
https://github.com/fuzhenn/chinese_coordinate_conversion/blob/448e4e4ad4b4a84422305d7263c74d44e72dbb6a/chncrs.js#L42-L48
23,978
fuzhenn/chinese_coordinate_conversion
chncrs.js
function (gcjLon, gcjLat) { var initDelta = 0.01; var threshold = 0.000000001; var dLat = initDelta, dLon = initDelta; var mLat = gcjLat - dLat, mLon = gcjLon - dLon; var pLat = gcjLat + dLat, pLon = gcjLon + dLon; var wgsLat, wgsLon, i = 0; while (1) { wgsLat = (mLat + pLat) / 2; wgsLon = (mLon + pLon) / 2; var tmp = this.gcj_encrypt(wgsLat, wgsLon) dLat = tmp.lat - gcjLat; dLon = tmp.lon - gcjLon; if ((Math.abs(dLat) < threshold) && (Math.abs(dLon) < threshold)) break; if (dLat > 0) pLat = wgsLat; else mLat = wgsLat; if (dLon > 0) pLon = wgsLon; else mLon = wgsLon; if (++i > 10000) break; } return [wgsLon, wgsLat]; }
javascript
function (gcjLon, gcjLat) { var initDelta = 0.01; var threshold = 0.000000001; var dLat = initDelta, dLon = initDelta; var mLat = gcjLat - dLat, mLon = gcjLon - dLon; var pLat = gcjLat + dLat, pLon = gcjLon + dLon; var wgsLat, wgsLon, i = 0; while (1) { wgsLat = (mLat + pLat) / 2; wgsLon = (mLon + pLon) / 2; var tmp = this.gcj_encrypt(wgsLat, wgsLon) dLat = tmp.lat - gcjLat; dLon = tmp.lon - gcjLon; if ((Math.abs(dLat) < threshold) && (Math.abs(dLon) < threshold)) break; if (dLat > 0) pLat = wgsLat; else mLat = wgsLat; if (dLon > 0) pLon = wgsLon; else mLon = wgsLon; if (++i > 10000) break; } return [wgsLon, wgsLat]; }
[ "function", "(", "gcjLon", ",", "gcjLat", ")", "{", "var", "initDelta", "=", "0.01", ";", "var", "threshold", "=", "0.000000001", ";", "var", "dLat", "=", "initDelta", ",", "dLon", "=", "initDelta", ";", "var", "mLat", "=", "gcjLat", "-", "dLat", ",", "mLon", "=", "gcjLon", "-", "dLon", ";", "var", "pLat", "=", "gcjLat", "+", "dLat", ",", "pLon", "=", "gcjLon", "+", "dLon", ";", "var", "wgsLat", ",", "wgsLon", ",", "i", "=", "0", ";", "while", "(", "1", ")", "{", "wgsLat", "=", "(", "mLat", "+", "pLat", ")", "/", "2", ";", "wgsLon", "=", "(", "mLon", "+", "pLon", ")", "/", "2", ";", "var", "tmp", "=", "this", ".", "gcj_encrypt", "(", "wgsLat", ",", "wgsLon", ")", "dLat", "=", "tmp", ".", "lat", "-", "gcjLat", ";", "dLon", "=", "tmp", ".", "lon", "-", "gcjLon", ";", "if", "(", "(", "Math", ".", "abs", "(", "dLat", ")", "<", "threshold", ")", "&&", "(", "Math", ".", "abs", "(", "dLon", ")", "<", "threshold", ")", ")", "break", ";", "if", "(", "dLat", ">", "0", ")", "pLat", "=", "wgsLat", ";", "else", "mLat", "=", "wgsLat", ";", "if", "(", "dLon", ">", "0", ")", "pLon", "=", "wgsLon", ";", "else", "mLon", "=", "wgsLon", ";", "if", "(", "++", "i", ">", "10000", ")", "break", ";", "}", "return", "[", "wgsLon", ",", "wgsLat", "]", ";", "}" ]
GCJ-02 to WGS-84 exactly
[ "GCJ", "-", "02", "to", "WGS", "-", "84", "exactly" ]
448e4e4ad4b4a84422305d7263c74d44e72dbb6a
https://github.com/fuzhenn/chinese_coordinate_conversion/blob/448e4e4ad4b4a84422305d7263c74d44e72dbb6a/chncrs.js#L50-L72
23,979
fuzhenn/chinese_coordinate_conversion
chncrs.js
function (gcjLon, gcjLat) { var x = gcjLon, y = gcjLat; var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * this.x_pi); var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * this.x_pi); var bdLon = z * Math.cos(theta) + 0.0065; var bdLat = z * Math.sin(theta) + 0.006; return [bdLon, bdLat]; }
javascript
function (gcjLon, gcjLat) { var x = gcjLon, y = gcjLat; var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * this.x_pi); var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * this.x_pi); var bdLon = z * Math.cos(theta) + 0.0065; var bdLat = z * Math.sin(theta) + 0.006; return [bdLon, bdLat]; }
[ "function", "(", "gcjLon", ",", "gcjLat", ")", "{", "var", "x", "=", "gcjLon", ",", "y", "=", "gcjLat", ";", "var", "z", "=", "Math", ".", "sqrt", "(", "x", "*", "x", "+", "y", "*", "y", ")", "+", "0.00002", "*", "Math", ".", "sin", "(", "y", "*", "this", ".", "x_pi", ")", ";", "var", "theta", "=", "Math", ".", "atan2", "(", "y", ",", "x", ")", "+", "0.000003", "*", "Math", ".", "cos", "(", "x", "*", "this", ".", "x_pi", ")", ";", "var", "bdLon", "=", "z", "*", "Math", ".", "cos", "(", "theta", ")", "+", "0.0065", ";", "var", "bdLat", "=", "z", "*", "Math", ".", "sin", "(", "theta", ")", "+", "0.006", ";", "return", "[", "bdLon", ",", "bdLat", "]", ";", "}" ]
GCJ-02 to BD-09
[ "GCJ", "-", "02", "to", "BD", "-", "09" ]
448e4e4ad4b4a84422305d7263c74d44e72dbb6a
https://github.com/fuzhenn/chinese_coordinate_conversion/blob/448e4e4ad4b4a84422305d7263c74d44e72dbb6a/chncrs.js#L74-L81
23,980
fuzhenn/chinese_coordinate_conversion
chncrs.js
function(source, fromCRS, toCRS) { if (!source) { return null; } if (!fromCRS || !toCRS) { throw new Error('must provide a valid fromCRS and toCRS.'); } if (this._isCoord(source)) { return this._transformCoordinate(source, fromCRS, toCRS); } else if (this._isArray(source)) { var result = []; for (var i = 0; i < source.length; i++) { result.push(this.transform(source[i], fromCRS, toCRS)); } return result; } return this._transformGeoJSON(source, fromCRS, toCRS); }
javascript
function(source, fromCRS, toCRS) { if (!source) { return null; } if (!fromCRS || !toCRS) { throw new Error('must provide a valid fromCRS and toCRS.'); } if (this._isCoord(source)) { return this._transformCoordinate(source, fromCRS, toCRS); } else if (this._isArray(source)) { var result = []; for (var i = 0; i < source.length; i++) { result.push(this.transform(source[i], fromCRS, toCRS)); } return result; } return this._transformGeoJSON(source, fromCRS, toCRS); }
[ "function", "(", "source", ",", "fromCRS", ",", "toCRS", ")", "{", "if", "(", "!", "source", ")", "{", "return", "null", ";", "}", "if", "(", "!", "fromCRS", "||", "!", "toCRS", ")", "{", "throw", "new", "Error", "(", "'must provide a valid fromCRS and toCRS.'", ")", ";", "}", "if", "(", "this", ".", "_isCoord", "(", "source", ")", ")", "{", "return", "this", ".", "_transformCoordinate", "(", "source", ",", "fromCRS", ",", "toCRS", ")", ";", "}", "else", "if", "(", "this", ".", "_isArray", "(", "source", ")", ")", "{", "var", "result", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "source", ".", "length", ";", "i", "++", ")", "{", "result", ".", "push", "(", "this", ".", "transform", "(", "source", "[", "i", "]", ",", "fromCRS", ",", "toCRS", ")", ")", ";", "}", "return", "result", ";", "}", "return", "this", ".", "_transformGeoJSON", "(", "source", ",", "fromCRS", ",", "toCRS", ")", ";", "}" ]
transform geojson's coordinates @param {Object | Array} source a coordinate [x,y] or a geoJSON object to convert @param {String | CRS Object} fromCRS crs converted from @param {String | CRS Object} toCRS crs converted to @return {Object} result geoJSON object
[ "transform", "geojson", "s", "coordinates" ]
448e4e4ad4b4a84422305d7263c74d44e72dbb6a
https://github.com/fuzhenn/chinese_coordinate_conversion/blob/448e4e4ad4b4a84422305d7263c74d44e72dbb6a/chncrs.js#L139-L156
23,981
aurelia/validation
dist/amd/aurelia-validation.js
getTargetDOMElement
function getTargetDOMElement(binding, view) { var target = binding.target; // DOM element if (target instanceof Element) { return target; } // custom element or custom attribute // tslint:disable-next-line:prefer-const for (var i = 0, ii = view.controllers.length; i < ii; i++) { var controller = view.controllers[i]; if (controller.viewModel === target) { var element = controller.container.get(aureliaPal.DOM.Element); if (element) { return element; } throw new Error("Unable to locate target element for \"" + binding.sourceExpression + "\"."); } } throw new Error("Unable to locate target element for \"" + binding.sourceExpression + "\"."); }
javascript
function getTargetDOMElement(binding, view) { var target = binding.target; // DOM element if (target instanceof Element) { return target; } // custom element or custom attribute // tslint:disable-next-line:prefer-const for (var i = 0, ii = view.controllers.length; i < ii; i++) { var controller = view.controllers[i]; if (controller.viewModel === target) { var element = controller.container.get(aureliaPal.DOM.Element); if (element) { return element; } throw new Error("Unable to locate target element for \"" + binding.sourceExpression + "\"."); } } throw new Error("Unable to locate target element for \"" + binding.sourceExpression + "\"."); }
[ "function", "getTargetDOMElement", "(", "binding", ",", "view", ")", "{", "var", "target", "=", "binding", ".", "target", ";", "// DOM element\r", "if", "(", "target", "instanceof", "Element", ")", "{", "return", "target", ";", "}", "// custom element or custom attribute\r", "// tslint:disable-next-line:prefer-const\r", "for", "(", "var", "i", "=", "0", ",", "ii", "=", "view", ".", "controllers", ".", "length", ";", "i", "<", "ii", ";", "i", "++", ")", "{", "var", "controller", "=", "view", ".", "controllers", "[", "i", "]", ";", "if", "(", "controller", ".", "viewModel", "===", "target", ")", "{", "var", "element", "=", "controller", ".", "container", ".", "get", "(", "aureliaPal", ".", "DOM", ".", "Element", ")", ";", "if", "(", "element", ")", "{", "return", "element", ";", "}", "throw", "new", "Error", "(", "\"Unable to locate target element for \\\"\"", "+", "binding", ".", "sourceExpression", "+", "\"\\\".\"", ")", ";", "}", "}", "throw", "new", "Error", "(", "\"Unable to locate target element for \\\"\"", "+", "binding", ".", "sourceExpression", "+", "\"\\\".\"", ")", ";", "}" ]
Gets the DOM element associated with the data-binding. Most of the time it's the binding.target but sometimes binding.target is an aurelia custom element, or custom attribute which is a javascript "class" instance, so we need to use the controller's container to retrieve the actual DOM element.
[ "Gets", "the", "DOM", "element", "associated", "with", "the", "data", "-", "binding", ".", "Most", "of", "the", "time", "it", "s", "the", "binding", ".", "target", "but", "sometimes", "binding", ".", "target", "is", "an", "aurelia", "custom", "element", "or", "custom", "attribute", "which", "is", "a", "javascript", "class", "instance", "so", "we", "need", "to", "use", "the", "controller", "s", "container", "to", "retrieve", "the", "actual", "DOM", "element", "." ]
ecc1dc2f0b522d6e1ff7ff1c7ba2c0973afe3b2d
https://github.com/aurelia/validation/blob/ecc1dc2f0b522d6e1ff7ff1c7ba2c0973afe3b2d/dist/amd/aurelia-validation.js#L9-L28
23,982
aurelia/validation
dist/amd/aurelia-validation.js
getPropertyInfo
function getPropertyInfo(expression, source) { var originalExpression = expression; while (expression instanceof aureliaBinding.BindingBehavior || expression instanceof aureliaBinding.ValueConverter) { expression = expression.expression; } var object; var propertyName; if (expression instanceof aureliaBinding.AccessScope) { object = aureliaBinding.getContextFor(expression.name, source, expression.ancestor); propertyName = expression.name; } else if (expression instanceof aureliaBinding.AccessMember) { object = getObject(originalExpression, expression.object, source); propertyName = expression.name; } else if (expression instanceof aureliaBinding.AccessKeyed) { object = getObject(originalExpression, expression.object, source); propertyName = expression.key.evaluate(source); } else { throw new Error("Expression '" + originalExpression + "' is not compatible with the validate binding-behavior."); } if (object === null || object === undefined) { return null; } return { object: object, propertyName: propertyName }; }
javascript
function getPropertyInfo(expression, source) { var originalExpression = expression; while (expression instanceof aureliaBinding.BindingBehavior || expression instanceof aureliaBinding.ValueConverter) { expression = expression.expression; } var object; var propertyName; if (expression instanceof aureliaBinding.AccessScope) { object = aureliaBinding.getContextFor(expression.name, source, expression.ancestor); propertyName = expression.name; } else if (expression instanceof aureliaBinding.AccessMember) { object = getObject(originalExpression, expression.object, source); propertyName = expression.name; } else if (expression instanceof aureliaBinding.AccessKeyed) { object = getObject(originalExpression, expression.object, source); propertyName = expression.key.evaluate(source); } else { throw new Error("Expression '" + originalExpression + "' is not compatible with the validate binding-behavior."); } if (object === null || object === undefined) { return null; } return { object: object, propertyName: propertyName }; }
[ "function", "getPropertyInfo", "(", "expression", ",", "source", ")", "{", "var", "originalExpression", "=", "expression", ";", "while", "(", "expression", "instanceof", "aureliaBinding", ".", "BindingBehavior", "||", "expression", "instanceof", "aureliaBinding", ".", "ValueConverter", ")", "{", "expression", "=", "expression", ".", "expression", ";", "}", "var", "object", ";", "var", "propertyName", ";", "if", "(", "expression", "instanceof", "aureliaBinding", ".", "AccessScope", ")", "{", "object", "=", "aureliaBinding", ".", "getContextFor", "(", "expression", ".", "name", ",", "source", ",", "expression", ".", "ancestor", ")", ";", "propertyName", "=", "expression", ".", "name", ";", "}", "else", "if", "(", "expression", "instanceof", "aureliaBinding", ".", "AccessMember", ")", "{", "object", "=", "getObject", "(", "originalExpression", ",", "expression", ".", "object", ",", "source", ")", ";", "propertyName", "=", "expression", ".", "name", ";", "}", "else", "if", "(", "expression", "instanceof", "aureliaBinding", ".", "AccessKeyed", ")", "{", "object", "=", "getObject", "(", "originalExpression", ",", "expression", ".", "object", ",", "source", ")", ";", "propertyName", "=", "expression", ".", "key", ".", "evaluate", "(", "source", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"Expression '\"", "+", "originalExpression", "+", "\"' is not compatible with the validate binding-behavior.\"", ")", ";", "}", "if", "(", "object", "===", "null", "||", "object", "===", "undefined", ")", "{", "return", "null", ";", "}", "return", "{", "object", ":", "object", ",", "propertyName", ":", "propertyName", "}", ";", "}" ]
Retrieves the object and property name for the specified expression. @param expression The expression @param source The scope
[ "Retrieves", "the", "object", "and", "property", "name", "for", "the", "specified", "expression", "." ]
ecc1dc2f0b522d6e1ff7ff1c7ba2c0973afe3b2d
https://github.com/aurelia/validation/blob/ecc1dc2f0b522d6e1ff7ff1c7ba2c0973afe3b2d/dist/amd/aurelia-validation.js#L43-L69
23,983
aurelia/validation
dist/es2017/aurelia-validation.js
configure
function configure( // tslint:disable-next-line:ban-types frameworkConfig, callback) { // the fluent rule definition API needs the parser to translate messages // to interpolation expressions. const messageParser = frameworkConfig.container.get(ValidationMessageParser); const propertyParser = frameworkConfig.container.get(PropertyAccessorParser); ValidationRules.initialize(messageParser, propertyParser); // configure... const config = new AureliaValidationConfiguration(); if (callback instanceof Function) { callback(config); } config.apply(frameworkConfig.container); // globalize the behaviors. if (frameworkConfig.globalResources) { frameworkConfig.globalResources(ValidateBindingBehavior, ValidateManuallyBindingBehavior, ValidateOnBlurBindingBehavior, ValidateOnChangeBindingBehavior, ValidateOnChangeOrBlurBindingBehavior, ValidationErrorsCustomAttribute, ValidationRendererCustomAttribute); } }
javascript
function configure( // tslint:disable-next-line:ban-types frameworkConfig, callback) { // the fluent rule definition API needs the parser to translate messages // to interpolation expressions. const messageParser = frameworkConfig.container.get(ValidationMessageParser); const propertyParser = frameworkConfig.container.get(PropertyAccessorParser); ValidationRules.initialize(messageParser, propertyParser); // configure... const config = new AureliaValidationConfiguration(); if (callback instanceof Function) { callback(config); } config.apply(frameworkConfig.container); // globalize the behaviors. if (frameworkConfig.globalResources) { frameworkConfig.globalResources(ValidateBindingBehavior, ValidateManuallyBindingBehavior, ValidateOnBlurBindingBehavior, ValidateOnChangeBindingBehavior, ValidateOnChangeOrBlurBindingBehavior, ValidationErrorsCustomAttribute, ValidationRendererCustomAttribute); } }
[ "function", "configure", "(", "// tslint:disable-next-line:ban-types\r", "frameworkConfig", ",", "callback", ")", "{", "// the fluent rule definition API needs the parser to translate messages\r", "// to interpolation expressions.\r", "const", "messageParser", "=", "frameworkConfig", ".", "container", ".", "get", "(", "ValidationMessageParser", ")", ";", "const", "propertyParser", "=", "frameworkConfig", ".", "container", ".", "get", "(", "PropertyAccessorParser", ")", ";", "ValidationRules", ".", "initialize", "(", "messageParser", ",", "propertyParser", ")", ";", "// configure...\r", "const", "config", "=", "new", "AureliaValidationConfiguration", "(", ")", ";", "if", "(", "callback", "instanceof", "Function", ")", "{", "callback", "(", "config", ")", ";", "}", "config", ".", "apply", "(", "frameworkConfig", ".", "container", ")", ";", "// globalize the behaviors.\r", "if", "(", "frameworkConfig", ".", "globalResources", ")", "{", "frameworkConfig", ".", "globalResources", "(", "ValidateBindingBehavior", ",", "ValidateManuallyBindingBehavior", ",", "ValidateOnBlurBindingBehavior", ",", "ValidateOnChangeBindingBehavior", ",", "ValidateOnChangeOrBlurBindingBehavior", ",", "ValidationErrorsCustomAttribute", ",", "ValidationRendererCustomAttribute", ")", ";", "}", "}" ]
Configures the plugin.
[ "Configures", "the", "plugin", "." ]
ecc1dc2f0b522d6e1ff7ff1c7ba2c0973afe3b2d
https://github.com/aurelia/validation/blob/ecc1dc2f0b522d6e1ff7ff1c7ba2c0973afe3b2d/dist/es2017/aurelia-validation.js#L1713-L1731
23,984
brandly/angular-youtube-embed
src/angular-youtube-embed.js
applyBroadcast
function applyBroadcast () { var args = Array.prototype.slice.call(arguments); scope.$apply(function () { scope.$emit.apply(scope, args); }); }
javascript
function applyBroadcast () { var args = Array.prototype.slice.call(arguments); scope.$apply(function () { scope.$emit.apply(scope, args); }); }
[ "function", "applyBroadcast", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "scope", ".", "$apply", "(", "function", "(", ")", "{", "scope", ".", "$emit", ".", "apply", "(", "scope", ",", "args", ")", ";", "}", ")", ";", "}" ]
YT calls callbacks outside of digest cycle
[ "YT", "calls", "callbacks", "outside", "of", "digest", "cycle" ]
23ecdd8c94d2f676a6894e21d447ee1a616a9698
https://github.com/brandly/angular-youtube-embed/blob/23ecdd8c94d2f676a6894e21d447ee1a616a9698/src/angular-youtube-embed.js#L149-L154
23,985
jaredhanson/passport-http
lib/passport-http/strategies/digest.js
DigestStrategy
function DigestStrategy(options, secret, validate) { if (typeof options == 'function') { validate = secret; secret = options; options = {}; } if (!secret) throw new Error('HTTP Digest authentication strategy requires a secret function'); passport.Strategy.call(this); this.name = 'digest'; this._secret = secret; this._validate = validate; this._realm = options.realm || 'Users'; if (options.domain) { this._domain = (Array.isArray(options.domain)) ? options.domain : [ options.domain ]; } this._opaque = options.opaque; this._algorithm = options.algorithm; if (options.qop) { this._qop = (Array.isArray(options.qop)) ? options.qop : [ options.qop ]; } }
javascript
function DigestStrategy(options, secret, validate) { if (typeof options == 'function') { validate = secret; secret = options; options = {}; } if (!secret) throw new Error('HTTP Digest authentication strategy requires a secret function'); passport.Strategy.call(this); this.name = 'digest'; this._secret = secret; this._validate = validate; this._realm = options.realm || 'Users'; if (options.domain) { this._domain = (Array.isArray(options.domain)) ? options.domain : [ options.domain ]; } this._opaque = options.opaque; this._algorithm = options.algorithm; if (options.qop) { this._qop = (Array.isArray(options.qop)) ? options.qop : [ options.qop ]; } }
[ "function", "DigestStrategy", "(", "options", ",", "secret", ",", "validate", ")", "{", "if", "(", "typeof", "options", "==", "'function'", ")", "{", "validate", "=", "secret", ";", "secret", "=", "options", ";", "options", "=", "{", "}", ";", "}", "if", "(", "!", "secret", ")", "throw", "new", "Error", "(", "'HTTP Digest authentication strategy requires a secret function'", ")", ";", "passport", ".", "Strategy", ".", "call", "(", "this", ")", ";", "this", ".", "name", "=", "'digest'", ";", "this", ".", "_secret", "=", "secret", ";", "this", ".", "_validate", "=", "validate", ";", "this", ".", "_realm", "=", "options", ".", "realm", "||", "'Users'", ";", "if", "(", "options", ".", "domain", ")", "{", "this", ".", "_domain", "=", "(", "Array", ".", "isArray", "(", "options", ".", "domain", ")", ")", "?", "options", ".", "domain", ":", "[", "options", ".", "domain", "]", ";", "}", "this", ".", "_opaque", "=", "options", ".", "opaque", ";", "this", ".", "_algorithm", "=", "options", ".", "algorithm", ";", "if", "(", "options", ".", "qop", ")", "{", "this", ".", "_qop", "=", "(", "Array", ".", "isArray", "(", "options", ".", "qop", ")", ")", "?", "options", ".", "qop", ":", "[", "options", ".", "qop", "]", ";", "}", "}" ]
`DigestStrategy` constructor. The HTTP Digest authentication strategy authenticates requests based on username and digest credentials contained in the `Authorization` header field. Applications must supply a `secret` callback, which is used to look up the user and corresponding password (aka shared secret) known to both the server and the client, supplying them to the `done` callback as `user` and `password`, respectively. The strategy will use the password to compute the response hash, failing authentication if it does not match that found in the request. If the username is not valid, `user` should be set to false. If an exception occured, `err` should be set. An optional `validate` callback can be supplied, which receives `params` containing nonces that the server may want to track and validate. Options: - `realm` authentication realm, defaults to "Users" - `domain` list of URIs that define the protection space - `algorithm` algorithm used to produce the digest (MD5 | MD5-sess) - `qop` list of quality of protection values support by the server (auth | auth-int) (recommended: auth) `validate` params: - `nonce` unique string value specified by the server - `cnonce` opaque string value provided by the client - `nc` count of the number of requests (including the current request) that the client has sent with the nonce value - `opaque` string of data, specified by the server, which should be returned by the client in subsequent requests Examples: passport.use(new DigestStrategy({ qop: 'auth' }, function(username, done) { // secret callback User.findOne({ username: username }, function (err, user) { if (err) { return done(err); } return done(null, user, user.password); }); }, function(params, done) { // validate callback, check nonces in params... done(err, true); } )); For further details on HTTP Basic authentication, refer to [RFC 2617: HTTP Authentication: Basic and Digest Access Authentication](http://tools.ietf.org/html/rfc2617) @param {Object} options @param {Function} secret @param {Function} validate @api public
[ "DigestStrategy", "constructor", "." ]
aa3f9554488b6830c64e6267558997a131dccd1f
https://github.com/jaredhanson/passport-http/blob/aa3f9554488b6830c64e6267558997a131dccd1f/lib/passport-http/strategies/digest.js#L62-L83
23,986
jaredhanson/passport-http
lib/passport-http/strategies/digest.js
parse
function parse(params) { var opts = {}; var tokens = params.split(/,(?=(?:[^"]|"[^"]*")*$)/); for (var i = 0, len = tokens.length; i < len; i++) { var param = /(\w+)=["]?([^"]+)["]?$/.exec(tokens[i]) if (param) { opts[param[1]] = param[2]; } } return opts; }
javascript
function parse(params) { var opts = {}; var tokens = params.split(/,(?=(?:[^"]|"[^"]*")*$)/); for (var i = 0, len = tokens.length; i < len; i++) { var param = /(\w+)=["]?([^"]+)["]?$/.exec(tokens[i]) if (param) { opts[param[1]] = param[2]; } } return opts; }
[ "function", "parse", "(", "params", ")", "{", "var", "opts", "=", "{", "}", ";", "var", "tokens", "=", "params", ".", "split", "(", "/", ",(?=(?:[^\"]|\"[^\"]*\")*$)", "/", ")", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "tokens", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "param", "=", "/", "(\\w+)=[\"]?([^\"]+)[\"]?$", "/", ".", "exec", "(", "tokens", "[", "i", "]", ")", "if", "(", "param", ")", "{", "opts", "[", "param", "[", "1", "]", "]", "=", "param", "[", "2", "]", ";", "}", "}", "return", "opts", ";", "}" ]
Parse authentication response. @api private
[ "Parse", "authentication", "response", "." ]
aa3f9554488b6830c64e6267558997a131dccd1f
https://github.com/jaredhanson/passport-http/blob/aa3f9554488b6830c64e6267558997a131dccd1f/lib/passport-http/strategies/digest.js#L234-L244
23,987
jaredhanson/passport-http
lib/passport-http/strategies/digest.js
nonce
function nonce(len) { var buf = [] , chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' , charlen = chars.length; for (var i = 0; i < len; ++i) { buf.push(chars[Math.random() * charlen | 0]); } return buf.join(''); }
javascript
function nonce(len) { var buf = [] , chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' , charlen = chars.length; for (var i = 0; i < len; ++i) { buf.push(chars[Math.random() * charlen | 0]); } return buf.join(''); }
[ "function", "nonce", "(", "len", ")", "{", "var", "buf", "=", "[", "]", ",", "chars", "=", "'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'", ",", "charlen", "=", "chars", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "++", "i", ")", "{", "buf", ".", "push", "(", "chars", "[", "Math", ".", "random", "(", ")", "*", "charlen", "|", "0", "]", ")", ";", "}", "return", "buf", ".", "join", "(", "''", ")", ";", "}" ]
Return a unique nonce with the given `len`. utils.uid(10); // => "FDaS435D2z" CREDIT: Connect -- utils.uid https://github.com/senchalabs/connect/blob/1.7.1/lib/utils.js @param {Number} len @return {String} @api private
[ "Return", "a", "unique", "nonce", "with", "the", "given", "len", "." ]
aa3f9554488b6830c64e6267558997a131dccd1f
https://github.com/jaredhanson/passport-http/blob/aa3f9554488b6830c64e6267558997a131dccd1f/lib/passport-http/strategies/digest.js#L259-L269
23,988
jaredhanson/passport-http
lib/passport-http/strategies/basic.js
BasicStrategy
function BasicStrategy(options, verify) { if (typeof options == 'function') { verify = options; options = {}; } if (!verify) throw new Error('HTTP Basic authentication strategy requires a verify function'); passport.Strategy.call(this); this.name = 'basic'; this._verify = verify; this._realm = options.realm || 'Users'; this._passReqToCallback = options.passReqToCallback; }
javascript
function BasicStrategy(options, verify) { if (typeof options == 'function') { verify = options; options = {}; } if (!verify) throw new Error('HTTP Basic authentication strategy requires a verify function'); passport.Strategy.call(this); this.name = 'basic'; this._verify = verify; this._realm = options.realm || 'Users'; this._passReqToCallback = options.passReqToCallback; }
[ "function", "BasicStrategy", "(", "options", ",", "verify", ")", "{", "if", "(", "typeof", "options", "==", "'function'", ")", "{", "verify", "=", "options", ";", "options", "=", "{", "}", ";", "}", "if", "(", "!", "verify", ")", "throw", "new", "Error", "(", "'HTTP Basic authentication strategy requires a verify function'", ")", ";", "passport", ".", "Strategy", ".", "call", "(", "this", ")", ";", "this", ".", "name", "=", "'basic'", ";", "this", ".", "_verify", "=", "verify", ";", "this", ".", "_realm", "=", "options", ".", "realm", "||", "'Users'", ";", "this", ".", "_passReqToCallback", "=", "options", ".", "passReqToCallback", ";", "}" ]
`BasicStrategy` constructor. The HTTP Basic authentication strategy authenticates requests based on userid and password credentials contained in the `Authorization` header field. Applications must supply a `verify` callback which accepts `userid` and `password` credentials, and then calls the `done` callback supplying a `user`, which should be set to `false` if the credentials are not valid. If an exception occured, `err` should be set. Optionally, `options` can be used to change the authentication realm. Options: - `realm` authentication realm, defaults to "Users" Examples: passport.use(new BasicStrategy( function(userid, password, done) { User.findOne({ username: userid, password: password }, function (err, user) { done(err, user); }); } )); For further details on HTTP Basic authentication, refer to [RFC 2617: HTTP Authentication: Basic and Digest Access Authentication](http://tools.ietf.org/html/rfc2617) @param {Object} options @param {Function} verify @api public
[ "BasicStrategy", "constructor", "." ]
aa3f9554488b6830c64e6267558997a131dccd1f
https://github.com/jaredhanson/passport-http/blob/aa3f9554488b6830c64e6267558997a131dccd1f/lib/passport-http/strategies/basic.js#L41-L53
23,989
thenikso/angular-inview
angular-inview.spec.js
scrollTo
function scrollTo(element, position, useTimeout) { if (!angular.isDefined(position)) { position = element; element = window; } if (!angular.isArray(position)) { position = [0, position]; } // Prepare promise resolution var deferred = $q.defer(), timeout; var scrollOnceHandler = function () { var check = (element === window) ? [element.scrollX, element.scrollY] : [element.scrollLeft, element.scrollTop]; if (check[0] != position[0] || check[1] != position[1]) { return; } if (timeout) { clearTimeout(timeout); timeout = null; } angular.element(element).off('scroll', scrollOnceHandler); deferred.resolve(); $rootScope.$digest(); }; angular.element(element).on('scroll', scrollOnceHandler); // Actual scrolling if (element === window) { element.scrollTo.apply(element, position); } else { element.scrollLeft = position[0]; element.scrollTop = position[1]; } // Backup resolver if (useTimeout) timeout = setTimeout(function () { angular.element(element).off('scroll', scrollOnceHandler); var check = (element === window) ? [element.scrollX, element.scrollY] : [element.scrollLeft, element.scrollTop]; if (check[0] != position[0] || check[1] != position[1]) { deferred.reject(); } else { deferred.resolve(); } $rootScope.$digest(); }, 100); return deferred.promise; }
javascript
function scrollTo(element, position, useTimeout) { if (!angular.isDefined(position)) { position = element; element = window; } if (!angular.isArray(position)) { position = [0, position]; } // Prepare promise resolution var deferred = $q.defer(), timeout; var scrollOnceHandler = function () { var check = (element === window) ? [element.scrollX, element.scrollY] : [element.scrollLeft, element.scrollTop]; if (check[0] != position[0] || check[1] != position[1]) { return; } if (timeout) { clearTimeout(timeout); timeout = null; } angular.element(element).off('scroll', scrollOnceHandler); deferred.resolve(); $rootScope.$digest(); }; angular.element(element).on('scroll', scrollOnceHandler); // Actual scrolling if (element === window) { element.scrollTo.apply(element, position); } else { element.scrollLeft = position[0]; element.scrollTop = position[1]; } // Backup resolver if (useTimeout) timeout = setTimeout(function () { angular.element(element).off('scroll', scrollOnceHandler); var check = (element === window) ? [element.scrollX, element.scrollY] : [element.scrollLeft, element.scrollTop]; if (check[0] != position[0] || check[1] != position[1]) { deferred.reject(); } else { deferred.resolve(); } $rootScope.$digest(); }, 100); return deferred.promise; }
[ "function", "scrollTo", "(", "element", ",", "position", ",", "useTimeout", ")", "{", "if", "(", "!", "angular", ".", "isDefined", "(", "position", ")", ")", "{", "position", "=", "element", ";", "element", "=", "window", ";", "}", "if", "(", "!", "angular", ".", "isArray", "(", "position", ")", ")", "{", "position", "=", "[", "0", ",", "position", "]", ";", "}", "// Prepare promise resolution", "var", "deferred", "=", "$q", ".", "defer", "(", ")", ",", "timeout", ";", "var", "scrollOnceHandler", "=", "function", "(", ")", "{", "var", "check", "=", "(", "element", "===", "window", ")", "?", "[", "element", ".", "scrollX", ",", "element", ".", "scrollY", "]", ":", "[", "element", ".", "scrollLeft", ",", "element", ".", "scrollTop", "]", ";", "if", "(", "check", "[", "0", "]", "!=", "position", "[", "0", "]", "||", "check", "[", "1", "]", "!=", "position", "[", "1", "]", ")", "{", "return", ";", "}", "if", "(", "timeout", ")", "{", "clearTimeout", "(", "timeout", ")", ";", "timeout", "=", "null", ";", "}", "angular", ".", "element", "(", "element", ")", ".", "off", "(", "'scroll'", ",", "scrollOnceHandler", ")", ";", "deferred", ".", "resolve", "(", ")", ";", "$rootScope", ".", "$digest", "(", ")", ";", "}", ";", "angular", ".", "element", "(", "element", ")", ".", "on", "(", "'scroll'", ",", "scrollOnceHandler", ")", ";", "// Actual scrolling", "if", "(", "element", "===", "window", ")", "{", "element", ".", "scrollTo", ".", "apply", "(", "element", ",", "position", ")", ";", "}", "else", "{", "element", ".", "scrollLeft", "=", "position", "[", "0", "]", ";", "element", ".", "scrollTop", "=", "position", "[", "1", "]", ";", "}", "// Backup resolver", "if", "(", "useTimeout", ")", "timeout", "=", "setTimeout", "(", "function", "(", ")", "{", "angular", ".", "element", "(", "element", ")", ".", "off", "(", "'scroll'", ",", "scrollOnceHandler", ")", ";", "var", "check", "=", "(", "element", "===", "window", ")", "?", "[", "element", ".", "scrollX", ",", "element", ".", "scrollY", "]", ":", "[", "element", ".", "scrollLeft", ",", "element", ".", "scrollTop", "]", ";", "if", "(", "check", "[", "0", "]", "!=", "position", "[", "0", "]", "||", "check", "[", "1", "]", "!=", "position", "[", "1", "]", ")", "{", "deferred", ".", "reject", "(", ")", ";", "}", "else", "{", "deferred", ".", "resolve", "(", ")", ";", "}", "$rootScope", ".", "$digest", "(", ")", ";", "}", ",", "100", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Scrolls the element to the given x, y position and waits a bit before resolving the returned promise.
[ "Scrolls", "the", "element", "to", "the", "given", "x", "y", "position", "and", "waits", "a", "bit", "before", "resolving", "the", "returned", "promise", "." ]
5cc859115f222510eac44b9ed5f5b86aa4843338
https://github.com/thenikso/angular-inview/blob/5cc859115f222510eac44b9ed5f5b86aa4843338/angular-inview.spec.js#L349-L398
23,990
thenikso/angular-inview
angular-inview.js
signalFromEvent
function signalFromEvent (target, event) { return new QuickSignal(function (subscriber) { var handler = function (e) { subscriber(e); }; var el = angular.element(target); event.split(' ').map(function (e) { el[0].addEventListener(e, handler, true); }); subscriber.$dispose = function () { event.split(' ').map(function (e) { el[0].removeEventListener(e, handler, true); }); }; }); }
javascript
function signalFromEvent (target, event) { return new QuickSignal(function (subscriber) { var handler = function (e) { subscriber(e); }; var el = angular.element(target); event.split(' ').map(function (e) { el[0].addEventListener(e, handler, true); }); subscriber.$dispose = function () { event.split(' ').map(function (e) { el[0].removeEventListener(e, handler, true); }); }; }); }
[ "function", "signalFromEvent", "(", "target", ",", "event", ")", "{", "return", "new", "QuickSignal", "(", "function", "(", "subscriber", ")", "{", "var", "handler", "=", "function", "(", "e", ")", "{", "subscriber", "(", "e", ")", ";", "}", ";", "var", "el", "=", "angular", ".", "element", "(", "target", ")", ";", "event", ".", "split", "(", "' '", ")", ".", "map", "(", "function", "(", "e", ")", "{", "el", "[", "0", "]", ".", "addEventListener", "(", "e", ",", "handler", ",", "true", ")", ";", "}", ")", ";", "subscriber", ".", "$dispose", "=", "function", "(", ")", "{", "event", ".", "split", "(", "' '", ")", ".", "map", "(", "function", "(", "e", ")", "{", "el", "[", "0", "]", ".", "removeEventListener", "(", "e", ",", "handler", ",", "true", ")", ";", "}", ")", ";", "}", ";", "}", ")", ";", "}" ]
Returns a signal from DOM events of a target.
[ "Returns", "a", "signal", "from", "DOM", "events", "of", "a", "target", "." ]
5cc859115f222510eac44b9ed5f5b86aa4843338
https://github.com/thenikso/angular-inview/blob/5cc859115f222510eac44b9ed5f5b86aa4843338/angular-inview.js#L357-L372
23,991
restify/errors
lib/helpers.js
errNameFromDesc
function errNameFromDesc(desc) { assert.string(desc, 'desc'); // takes an error description, split on spaces, camel case it correctly, // then append 'Error' at the end of it. // e.g., the passed in description is 'Internal Server Error' // the output is 'InternalServerError' var pieces = desc.split(/\s+/); var name = _.reduce(pieces, function(acc, piece) { // lowercase all, then capitalize it. var normalizedPiece = _.capitalize(piece.toLowerCase()); return acc + normalizedPiece; }, ''); // strip all non word characters name = name.replace(/\W+/g, ''); // append 'Error' at the end of it only if it doesn't already end with it. if (!_.endsWith(name, 'Error')) { name += 'Error'; } return name; }
javascript
function errNameFromDesc(desc) { assert.string(desc, 'desc'); // takes an error description, split on spaces, camel case it correctly, // then append 'Error' at the end of it. // e.g., the passed in description is 'Internal Server Error' // the output is 'InternalServerError' var pieces = desc.split(/\s+/); var name = _.reduce(pieces, function(acc, piece) { // lowercase all, then capitalize it. var normalizedPiece = _.capitalize(piece.toLowerCase()); return acc + normalizedPiece; }, ''); // strip all non word characters name = name.replace(/\W+/g, ''); // append 'Error' at the end of it only if it doesn't already end with it. if (!_.endsWith(name, 'Error')) { name += 'Error'; } return name; }
[ "function", "errNameFromDesc", "(", "desc", ")", "{", "assert", ".", "string", "(", "desc", ",", "'desc'", ")", ";", "// takes an error description, split on spaces, camel case it correctly,", "// then append 'Error' at the end of it.", "// e.g., the passed in description is 'Internal Server Error'", "// the output is 'InternalServerError'", "var", "pieces", "=", "desc", ".", "split", "(", "/", "\\s+", "/", ")", ";", "var", "name", "=", "_", ".", "reduce", "(", "pieces", ",", "function", "(", "acc", ",", "piece", ")", "{", "// lowercase all, then capitalize it.", "var", "normalizedPiece", "=", "_", ".", "capitalize", "(", "piece", ".", "toLowerCase", "(", ")", ")", ";", "return", "acc", "+", "normalizedPiece", ";", "}", ",", "''", ")", ";", "// strip all non word characters", "name", "=", "name", ".", "replace", "(", "/", "\\W+", "/", "g", ",", "''", ")", ";", "// append 'Error' at the end of it only if it doesn't already end with it.", "if", "(", "!", "_", ".", "endsWith", "(", "name", ",", "'Error'", ")", ")", "{", "name", "+=", "'Error'", ";", "}", "return", "name", ";", "}" ]
used to programatically create http error code names, using the underlying status codes names exposed via the http module. @private @function errNameFromDesc @param {String} desc a description of the error, e.g., 'Not Found' @returns {String}
[ "used", "to", "programatically", "create", "http", "error", "code", "names", "using", "the", "underlying", "status", "codes", "names", "exposed", "via", "the", "http", "module", "." ]
af5cb0c1a72b7a47886b77a56f56d766806b3c1e
https://github.com/restify/errors/blob/af5cb0c1a72b7a47886b77a56f56d766806b3c1e/lib/helpers.js#L103-L127
23,992
restify/errors
lib/index.js
makeErrFromCode
function makeErrFromCode(statusCode) { // assert! assert.number(statusCode, 'statusCode'); assert.equal(statusCode >= 400, true); // drop the first arg var args = _.drop(_.toArray(arguments)); var name = helpers.errNameFromCode(statusCode); var ErrCtor = httpErrors[name]; // assert constructor was found assert.func(ErrCtor); // pass every other arg down to constructor return makeInstance(ErrCtor, makeErrFromCode, args); }
javascript
function makeErrFromCode(statusCode) { // assert! assert.number(statusCode, 'statusCode'); assert.equal(statusCode >= 400, true); // drop the first arg var args = _.drop(_.toArray(arguments)); var name = helpers.errNameFromCode(statusCode); var ErrCtor = httpErrors[name]; // assert constructor was found assert.func(ErrCtor); // pass every other arg down to constructor return makeInstance(ErrCtor, makeErrFromCode, args); }
[ "function", "makeErrFromCode", "(", "statusCode", ")", "{", "// assert!", "assert", ".", "number", "(", "statusCode", ",", "'statusCode'", ")", ";", "assert", ".", "equal", "(", "statusCode", ">=", "400", ",", "true", ")", ";", "// drop the first arg", "var", "args", "=", "_", ".", "drop", "(", "_", ".", "toArray", "(", "arguments", ")", ")", ";", "var", "name", "=", "helpers", ".", "errNameFromCode", "(", "statusCode", ")", ";", "var", "ErrCtor", "=", "httpErrors", "[", "name", "]", ";", "// assert constructor was found", "assert", ".", "func", "(", "ErrCtor", ")", ";", "// pass every other arg down to constructor", "return", "makeInstance", "(", "ErrCtor", ",", "makeErrFromCode", ",", "args", ")", ";", "}" ]
create an error object from an http status code. first arg is status code, all subsequent args passed on to the constructor. only works for regular HttpErrors, not RestErrors. @public @function makeErrFromCode @param {Number} statusCode the http status code @returns {Error} an error instance
[ "create", "an", "error", "object", "from", "an", "http", "status", "code", ".", "first", "arg", "is", "status", "code", "all", "subsequent", "args", "passed", "on", "to", "the", "constructor", ".", "only", "works", "for", "regular", "HttpErrors", "not", "RestErrors", "." ]
af5cb0c1a72b7a47886b77a56f56d766806b3c1e
https://github.com/restify/errors/blob/af5cb0c1a72b7a47886b77a56f56d766806b3c1e/lib/index.js#L26-L42
23,993
restify/errors
lib/index.js
makeInstance
function makeInstance(constructor, constructorOpt, args) { // pass args to the constructor function F() { // eslint-disable-line require-jsdoc return constructor.apply(this, args); } F.prototype = constructor.prototype; // new up an instance, and capture stack trace from the // passed in constructorOpt var errInstance = new F(); Error.captureStackTrace(errInstance, constructorOpt); // return the error instance return errInstance; }
javascript
function makeInstance(constructor, constructorOpt, args) { // pass args to the constructor function F() { // eslint-disable-line require-jsdoc return constructor.apply(this, args); } F.prototype = constructor.prototype; // new up an instance, and capture stack trace from the // passed in constructorOpt var errInstance = new F(); Error.captureStackTrace(errInstance, constructorOpt); // return the error instance return errInstance; }
[ "function", "makeInstance", "(", "constructor", ",", "constructorOpt", ",", "args", ")", "{", "// pass args to the constructor", "function", "F", "(", ")", "{", "// eslint-disable-line require-jsdoc", "return", "constructor", ".", "apply", "(", "this", ",", "args", ")", ";", "}", "F", ".", "prototype", "=", "constructor", ".", "prototype", ";", "// new up an instance, and capture stack trace from the", "// passed in constructorOpt", "var", "errInstance", "=", "new", "F", "(", ")", ";", "Error", ".", "captureStackTrace", "(", "errInstance", ",", "constructorOpt", ")", ";", "// return the error instance", "return", "errInstance", ";", "}" ]
helper function to dynamically apply args to a dynamic constructor. magicks. @private @function makeInstance @param {Function} constructor the constructor function @param {Function} constructorOpt where to start the error stack trace @param {Array} args array of arguments to apply to ctor @returns {Object} instance of the ctor
[ "helper", "function", "to", "dynamically", "apply", "args", "to", "a", "dynamic", "constructor", ".", "magicks", "." ]
af5cb0c1a72b7a47886b77a56f56d766806b3c1e
https://github.com/restify/errors/blob/af5cb0c1a72b7a47886b77a56f56d766806b3c1e/lib/index.js#L55-L69
23,994
restify/errors
lib/makeConstructor.js
makeConstructor
function makeConstructor(name, defaults) { assert.string(name, 'name'); assert.optionalObject(defaults, 'defaults'); // code property doesn't have 'Error' in it. remove it. var defaultCode = name.replace(new RegExp('[Ee]rror$'), ''); var prototypeDefaults = _.assign({}, { name: name, code: (defaults && defaults.code) || defaultCode, restCode: _.get(defaults, 'restCode', defaultCode) }, defaults); // assert that this constructor doesn't already exist. assert.equal( typeof module.exports[name], 'undefined', 'Constructor already exists!' ); // dynamically create a constructor. // must be anonymous fn. var ErrCtor = function() { // eslint-disable-line require-jsdoc, func-style // call super RestError.apply(this, arguments); this.name = name; }; util.inherits(ErrCtor, RestError); // copy over all options to prototype _.assign(ErrCtor.prototype, prototypeDefaults); // assign display name ErrCtor.displayName = name; // return constructor to user, they can choose how to store and manage it. return ErrCtor; }
javascript
function makeConstructor(name, defaults) { assert.string(name, 'name'); assert.optionalObject(defaults, 'defaults'); // code property doesn't have 'Error' in it. remove it. var defaultCode = name.replace(new RegExp('[Ee]rror$'), ''); var prototypeDefaults = _.assign({}, { name: name, code: (defaults && defaults.code) || defaultCode, restCode: _.get(defaults, 'restCode', defaultCode) }, defaults); // assert that this constructor doesn't already exist. assert.equal( typeof module.exports[name], 'undefined', 'Constructor already exists!' ); // dynamically create a constructor. // must be anonymous fn. var ErrCtor = function() { // eslint-disable-line require-jsdoc, func-style // call super RestError.apply(this, arguments); this.name = name; }; util.inherits(ErrCtor, RestError); // copy over all options to prototype _.assign(ErrCtor.prototype, prototypeDefaults); // assign display name ErrCtor.displayName = name; // return constructor to user, they can choose how to store and manage it. return ErrCtor; }
[ "function", "makeConstructor", "(", "name", ",", "defaults", ")", "{", "assert", ".", "string", "(", "name", ",", "'name'", ")", ";", "assert", ".", "optionalObject", "(", "defaults", ",", "'defaults'", ")", ";", "// code property doesn't have 'Error' in it. remove it.", "var", "defaultCode", "=", "name", ".", "replace", "(", "new", "RegExp", "(", "'[Ee]rror$'", ")", ",", "''", ")", ";", "var", "prototypeDefaults", "=", "_", ".", "assign", "(", "{", "}", ",", "{", "name", ":", "name", ",", "code", ":", "(", "defaults", "&&", "defaults", ".", "code", ")", "||", "defaultCode", ",", "restCode", ":", "_", ".", "get", "(", "defaults", ",", "'restCode'", ",", "defaultCode", ")", "}", ",", "defaults", ")", ";", "// assert that this constructor doesn't already exist.", "assert", ".", "equal", "(", "typeof", "module", ".", "exports", "[", "name", "]", ",", "'undefined'", ",", "'Constructor already exists!'", ")", ";", "// dynamically create a constructor.", "// must be anonymous fn.", "var", "ErrCtor", "=", "function", "(", ")", "{", "// eslint-disable-line require-jsdoc, func-style", "// call super", "RestError", ".", "apply", "(", "this", ",", "arguments", ")", ";", "this", ".", "name", "=", "name", ";", "}", ";", "util", ".", "inherits", "(", "ErrCtor", ",", "RestError", ")", ";", "// copy over all options to prototype", "_", ".", "assign", "(", "ErrCtor", ".", "prototype", ",", "prototypeDefaults", ")", ";", "// assign display name", "ErrCtor", ".", "displayName", "=", "name", ";", "// return constructor to user, they can choose how to store and manage it.", "return", "ErrCtor", ";", "}" ]
create RestError subclasses for users. takes a string, creates a constructor for them. magicks, again. @public @function makeConstructor @param {String} name the name of the error class to create @param {Number} defaults optional status code @return {Function} a constructor function
[ "create", "RestError", "subclasses", "for", "users", ".", "takes", "a", "string", "creates", "a", "constructor", "for", "them", ".", "magicks", "again", "." ]
af5cb0c1a72b7a47886b77a56f56d766806b3c1e
https://github.com/restify/errors/blob/af5cb0c1a72b7a47886b77a56f56d766806b3c1e/lib/makeConstructor.js#L24-L61
23,995
restify/errors
lib/serializer.js
factory
function factory(options) { assert.optionalObject(options, 'options'); var opts = _.assign({ topLevelFields: false }, options); var serializer = new ErrorSerializer(opts); // rebind the serialize function since this will be lost when we export it // as a POJO serializer.serialize = serializer.serialize.bind(serializer); return serializer; }
javascript
function factory(options) { assert.optionalObject(options, 'options'); var opts = _.assign({ topLevelFields: false }, options); var serializer = new ErrorSerializer(opts); // rebind the serialize function since this will be lost when we export it // as a POJO serializer.serialize = serializer.serialize.bind(serializer); return serializer; }
[ "function", "factory", "(", "options", ")", "{", "assert", ".", "optionalObject", "(", "options", ",", "'options'", ")", ";", "var", "opts", "=", "_", ".", "assign", "(", "{", "topLevelFields", ":", "false", "}", ",", "options", ")", ";", "var", "serializer", "=", "new", "ErrorSerializer", "(", "opts", ")", ";", "// rebind the serialize function since this will be lost when we export it", "// as a POJO", "serializer", ".", "serialize", "=", "serializer", ".", "serialize", ".", "bind", "(", "serializer", ")", ";", "return", "serializer", ";", "}" ]
factory function to create customized serializers. @public @param {Object} options an options object @return {Function} serializer function
[ "factory", "function", "to", "create", "customized", "serializers", "." ]
af5cb0c1a72b7a47886b77a56f56d766806b3c1e
https://github.com/restify/errors/blob/af5cb0c1a72b7a47886b77a56f56d766806b3c1e/lib/serializer.js#L265-L278
23,996
camunda/camunda-bpm-sdk-js
lib/forms/camunda-form.js
CamundaForm
function CamundaForm(options) { if(!options) { throw new Error('CamundaForm need to be initialized with options.'); } var done = options.done = options.done || function(err) { if(err) throw err; }; if (options.client) { this.client = options.client; } else { this.client = new CamSDK.Client(options.clientConfig || {}); } if (!options.taskId && !options.processDefinitionId && !options.processDefinitionKey) { return done(new Error('Cannot initialize Taskform: either \'taskId\' or \'processDefinitionId\' or \'processDefinitionKey\' must be provided')); } this.taskId = options.taskId; if(this.taskId) { this.taskBasePath = this.client.baseUrl + '/task/' + this.taskId; } this.processDefinitionId = options.processDefinitionId; this.processDefinitionKey = options.processDefinitionKey; this.formElement = options.formElement; this.containerElement = options.containerElement; this.formUrl = options.formUrl; if(!this.formElement && !this.containerElement) { return done(new Error('CamundaForm needs to be initilized with either \'formElement\' or \'containerElement\'')); } if(!this.formElement && !this.formUrl) { return done(new Error('Camunda form needs to be intialized with either \'formElement\' or \'formUrl\'')); } /** * A VariableManager instance * @type {VariableManager} */ this.variableManager = new VariableManager({ client: this.client }); /** * An array of FormFieldHandlers * @type {FormFieldHandlers[]} */ this.formFieldHandlers = options.formFieldHandlers || [ InputFieldHandler, ChoicesFieldHandler, FileDownloadHandler ]; this.businessKey = null; this.fields = []; this.scripts = []; this.options = options; // init event support Events.attach(this); this.initialize(done); }
javascript
function CamundaForm(options) { if(!options) { throw new Error('CamundaForm need to be initialized with options.'); } var done = options.done = options.done || function(err) { if(err) throw err; }; if (options.client) { this.client = options.client; } else { this.client = new CamSDK.Client(options.clientConfig || {}); } if (!options.taskId && !options.processDefinitionId && !options.processDefinitionKey) { return done(new Error('Cannot initialize Taskform: either \'taskId\' or \'processDefinitionId\' or \'processDefinitionKey\' must be provided')); } this.taskId = options.taskId; if(this.taskId) { this.taskBasePath = this.client.baseUrl + '/task/' + this.taskId; } this.processDefinitionId = options.processDefinitionId; this.processDefinitionKey = options.processDefinitionKey; this.formElement = options.formElement; this.containerElement = options.containerElement; this.formUrl = options.formUrl; if(!this.formElement && !this.containerElement) { return done(new Error('CamundaForm needs to be initilized with either \'formElement\' or \'containerElement\'')); } if(!this.formElement && !this.formUrl) { return done(new Error('Camunda form needs to be intialized with either \'formElement\' or \'formUrl\'')); } /** * A VariableManager instance * @type {VariableManager} */ this.variableManager = new VariableManager({ client: this.client }); /** * An array of FormFieldHandlers * @type {FormFieldHandlers[]} */ this.formFieldHandlers = options.formFieldHandlers || [ InputFieldHandler, ChoicesFieldHandler, FileDownloadHandler ]; this.businessKey = null; this.fields = []; this.scripts = []; this.options = options; // init event support Events.attach(this); this.initialize(done); }
[ "function", "CamundaForm", "(", "options", ")", "{", "if", "(", "!", "options", ")", "{", "throw", "new", "Error", "(", "'CamundaForm need to be initialized with options.'", ")", ";", "}", "var", "done", "=", "options", ".", "done", "=", "options", ".", "done", "||", "function", "(", "err", ")", "{", "if", "(", "err", ")", "throw", "err", ";", "}", ";", "if", "(", "options", ".", "client", ")", "{", "this", ".", "client", "=", "options", ".", "client", ";", "}", "else", "{", "this", ".", "client", "=", "new", "CamSDK", ".", "Client", "(", "options", ".", "clientConfig", "||", "{", "}", ")", ";", "}", "if", "(", "!", "options", ".", "taskId", "&&", "!", "options", ".", "processDefinitionId", "&&", "!", "options", ".", "processDefinitionKey", ")", "{", "return", "done", "(", "new", "Error", "(", "'Cannot initialize Taskform: either \\'taskId\\' or \\'processDefinitionId\\' or \\'processDefinitionKey\\' must be provided'", ")", ")", ";", "}", "this", ".", "taskId", "=", "options", ".", "taskId", ";", "if", "(", "this", ".", "taskId", ")", "{", "this", ".", "taskBasePath", "=", "this", ".", "client", ".", "baseUrl", "+", "'/task/'", "+", "this", ".", "taskId", ";", "}", "this", ".", "processDefinitionId", "=", "options", ".", "processDefinitionId", ";", "this", ".", "processDefinitionKey", "=", "options", ".", "processDefinitionKey", ";", "this", ".", "formElement", "=", "options", ".", "formElement", ";", "this", ".", "containerElement", "=", "options", ".", "containerElement", ";", "this", ".", "formUrl", "=", "options", ".", "formUrl", ";", "if", "(", "!", "this", ".", "formElement", "&&", "!", "this", ".", "containerElement", ")", "{", "return", "done", "(", "new", "Error", "(", "'CamundaForm needs to be initilized with either \\'formElement\\' or \\'containerElement\\''", ")", ")", ";", "}", "if", "(", "!", "this", ".", "formElement", "&&", "!", "this", ".", "formUrl", ")", "{", "return", "done", "(", "new", "Error", "(", "'Camunda form needs to be intialized with either \\'formElement\\' or \\'formUrl\\''", ")", ")", ";", "}", "/**\n * A VariableManager instance\n * @type {VariableManager}\n */", "this", ".", "variableManager", "=", "new", "VariableManager", "(", "{", "client", ":", "this", ".", "client", "}", ")", ";", "/**\n * An array of FormFieldHandlers\n * @type {FormFieldHandlers[]}\n */", "this", ".", "formFieldHandlers", "=", "options", ".", "formFieldHandlers", "||", "[", "InputFieldHandler", ",", "ChoicesFieldHandler", ",", "FileDownloadHandler", "]", ";", "this", ".", "businessKey", "=", "null", ";", "this", ".", "fields", "=", "[", "]", ";", "this", ".", "scripts", "=", "[", "]", ";", "this", ".", "options", "=", "options", ";", "// init event support", "Events", ".", "attach", "(", "this", ")", ";", "this", ".", "initialize", "(", "done", ")", ";", "}" ]
A class to help handling embedded forms @class @memberof CamSDk.form @param {Object.<String,*>} options @param {Cam} options.client @param {String} [options.taskId] @param {String} [options.processDefinitionId] @param {String} [options.processDefinitionKey] @param {Element} [options.formContainer] @param {Element} [options.formElement] @param {Object} [options.urlParams] @param {String} [options.formUrl]
[ "A", "class", "to", "help", "handling", "embedded", "forms" ]
4ad43b41b501c31024ee017f5dc95a933258b0f0
https://github.com/camunda/camunda-bpm-sdk-js/blob/4ad43b41b501c31024ee017f5dc95a933258b0f0/lib/forms/camunda-form.js#L69-L136
23,997
camunda/camunda-bpm-sdk-js
lib/events.js
toArray
function toArray(obj) { var a, arr = []; for (a in obj) { arr.push(obj[a]); } return arr; }
javascript
function toArray(obj) { var a, arr = []; for (a in obj) { arr.push(obj[a]); } return arr; }
[ "function", "toArray", "(", "obj", ")", "{", "var", "a", ",", "arr", "=", "[", "]", ";", "for", "(", "a", "in", "obj", ")", "{", "arr", ".", "push", "(", "obj", "[", "a", "]", ")", ";", "}", "return", "arr", ";", "}" ]
Converts an object into array @param {*} obj @return {Array}
[ "Converts", "an", "object", "into", "array" ]
4ad43b41b501c31024ee017f5dc95a933258b0f0
https://github.com/camunda/camunda-bpm-sdk-js/blob/4ad43b41b501c31024ee017f5dc95a933258b0f0/lib/events.js#L45-L51
23,998
camunda/camunda-bpm-sdk-js
lib/events.js
ensureEvents
function ensureEvents(obj, name) { obj._events = obj._events || {}; obj._events[name] = obj._events[name] || []; }
javascript
function ensureEvents(obj, name) { obj._events = obj._events || {}; obj._events[name] = obj._events[name] || []; }
[ "function", "ensureEvents", "(", "obj", ",", "name", ")", "{", "obj", ".", "_events", "=", "obj", ".", "_events", "||", "{", "}", ";", "obj", ".", "_events", "[", "name", "]", "=", "obj", ".", "_events", "[", "name", "]", "||", "[", "]", ";", "}" ]
Ensure an object to have the needed _events property @param {*} obj @param {String} name
[ "Ensure", "an", "object", "to", "have", "the", "needed", "_events", "property" ]
4ad43b41b501c31024ee017f5dc95a933258b0f0
https://github.com/camunda/camunda-bpm-sdk-js/blob/4ad43b41b501c31024ee017f5dc95a933258b0f0/lib/events.js#L76-L79
23,999
camunda/camunda-bpm-sdk-js
lib/forms/controls/abstract-form-field.js
AbstractFormField
function AbstractFormField(element, variableManager) { this.element = $( element ); this.variableManager = variableManager; this.variableName = null; this.initialize(); }
javascript
function AbstractFormField(element, variableManager) { this.element = $( element ); this.variableManager = variableManager; this.variableName = null; this.initialize(); }
[ "function", "AbstractFormField", "(", "element", ",", "variableManager", ")", "{", "this", ".", "element", "=", "$", "(", "element", ")", ";", "this", ".", "variableManager", "=", "variableManager", ";", "this", ".", "variableName", "=", "null", ";", "this", ".", "initialize", "(", ")", ";", "}" ]
An abstract class for the form field controls @class AbstractFormField @abstract @memberof CamSDK.form
[ "An", "abstract", "class", "for", "the", "form", "field", "controls" ]
4ad43b41b501c31024ee017f5dc95a933258b0f0
https://github.com/camunda/camunda-bpm-sdk-js/blob/4ad43b41b501c31024ee017f5dc95a933258b0f0/lib/forms/controls/abstract-form-field.js#L33-L40