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
30,100
opendigitaleducation/sijil.js
docs/libs/typescript.js
endNode
function endNode() { if (parent.children) { mergeChildren(parent.children); sortChildren(parent.children); } parent = parentsStack.pop(); }
javascript
function endNode() { if (parent.children) { mergeChildren(parent.children); sortChildren(parent.children); } parent = parentsStack.pop(); }
[ "function", "endNode", "(", ")", "{", "if", "(", "parent", ".", "children", ")", "{", "mergeChildren", "(", "parent", ".", "children", ")", ";", "sortChildren", "(", "parent", ".", "children", ")", ";", "}", "parent", "=", "parentsStack", ".", "pop", "...
Call after calling `startNode` and adding children to it.
[ "Call", "after", "calling", "startNode", "and", "adding", "children", "to", "it", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L47835-L47841
30,101
opendigitaleducation/sijil.js
docs/libs/typescript.js
mergeChildren
function mergeChildren(children) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { var decl = child.node; var name = decl.name && nodeText(decl.name); if (!name) { // Anonymous items are never merged. return true; } var itemsWithSameName = nameToItems[name]; if (!itemsWithSameName) { nameToItems[name] = child; return true; } if (itemsWithSameName instanceof Array) { for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { var itemWithSameName = itemsWithSameName_1[_i]; if (tryMerge(itemWithSameName, child)) { return false; } } itemsWithSameName.push(child); return true; } else { var itemWithSameName = itemsWithSameName; if (tryMerge(itemWithSameName, child)) { return false; } nameToItems[name] = [itemWithSameName, child]; return true; } function tryMerge(a, b) { if (shouldReallyMerge(a.node, b.node)) { merge(a, b); return true; } return false; } }); /** a and b have the same name, but they may not be mergeable. */ function shouldReallyMerge(a, b) { return a.kind === b.kind && (a.kind !== 225 /* ModuleDeclaration */ || areSameModule(a, b)); // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { if (a.body.kind !== b.body.kind) { return false; } if (a.body.kind !== 225 /* ModuleDeclaration */) { return true; } return areSameModule(a.body, b.body); } } /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { target.additionalNodes = target.additionalNodes || []; target.additionalNodes.push(source.node); if (source.additionalNodes) { (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); } target.children = ts.concatenate(target.children, source.children); if (target.children) { mergeChildren(target.children); sortChildren(target.children); } var _a; } }
javascript
function mergeChildren(children) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { var decl = child.node; var name = decl.name && nodeText(decl.name); if (!name) { // Anonymous items are never merged. return true; } var itemsWithSameName = nameToItems[name]; if (!itemsWithSameName) { nameToItems[name] = child; return true; } if (itemsWithSameName instanceof Array) { for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { var itemWithSameName = itemsWithSameName_1[_i]; if (tryMerge(itemWithSameName, child)) { return false; } } itemsWithSameName.push(child); return true; } else { var itemWithSameName = itemsWithSameName; if (tryMerge(itemWithSameName, child)) { return false; } nameToItems[name] = [itemWithSameName, child]; return true; } function tryMerge(a, b) { if (shouldReallyMerge(a.node, b.node)) { merge(a, b); return true; } return false; } }); /** a and b have the same name, but they may not be mergeable. */ function shouldReallyMerge(a, b) { return a.kind === b.kind && (a.kind !== 225 /* ModuleDeclaration */ || areSameModule(a, b)); // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { if (a.body.kind !== b.body.kind) { return false; } if (a.body.kind !== 225 /* ModuleDeclaration */) { return true; } return areSameModule(a.body, b.body); } } /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { target.additionalNodes = target.additionalNodes || []; target.additionalNodes.push(source.node); if (source.additionalNodes) { (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); } target.children = ts.concatenate(target.children, source.children); if (target.children) { mergeChildren(target.children); sortChildren(target.children); } var _a; } }
[ "function", "mergeChildren", "(", "children", ")", "{", "var", "nameToItems", "=", "ts", ".", "createMap", "(", ")", ";", "ts", ".", "filterMutate", "(", "children", ",", "function", "(", "child", ")", "{", "var", "decl", "=", "child", ".", "node", ";"...
Merge declarations of the same kind.
[ "Merge", "declarations", "of", "the", "same", "kind", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L47969-L48038
30,102
opendigitaleducation/sijil.js
docs/libs/typescript.js
shouldReallyMerge
function shouldReallyMerge(a, b) { return a.kind === b.kind && (a.kind !== 225 /* ModuleDeclaration */ || areSameModule(a, b)); // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { if (a.body.kind !== b.body.kind) { return false; } if (a.body.kind !== 225 /* ModuleDeclaration */) { return true; } return areSameModule(a.body, b.body); } }
javascript
function shouldReallyMerge(a, b) { return a.kind === b.kind && (a.kind !== 225 /* ModuleDeclaration */ || areSameModule(a, b)); // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { if (a.body.kind !== b.body.kind) { return false; } if (a.body.kind !== 225 /* ModuleDeclaration */) { return true; } return areSameModule(a.body, b.body); } }
[ "function", "shouldReallyMerge", "(", "a", ",", "b", ")", "{", "return", "a", ".", "kind", "===", "b", ".", "kind", "&&", "(", "a", ".", "kind", "!==", "225", "/* ModuleDeclaration */", "||", "areSameModule", "(", "a", ",", "b", ")", ")", ";", "// We...
a and b have the same name, but they may not be mergeable.
[ "a", "and", "b", "have", "the", "same", "name", "but", "they", "may", "not", "be", "mergeable", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L48010-L48023
30,103
opendigitaleducation/sijil.js
docs/libs/typescript.js
areSameModule
function areSameModule(a, b) { if (a.body.kind !== b.body.kind) { return false; } if (a.body.kind !== 225 /* ModuleDeclaration */) { return true; } return areSameModule(a.body, b.body); }
javascript
function areSameModule(a, b) { if (a.body.kind !== b.body.kind) { return false; } if (a.body.kind !== 225 /* ModuleDeclaration */) { return true; } return areSameModule(a.body, b.body); }
[ "function", "areSameModule", "(", "a", ",", "b", ")", "{", "if", "(", "a", ".", "body", ".", "kind", "!==", "b", ".", "body", ".", "kind", ")", "{", "return", "false", ";", "}", "if", "(", "a", ".", "body", ".", "kind", "!==", "225", "/* Module...
We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'!
[ "We", "use", "1", "NavNode", "to", "represent", "A", ".", "B", ".", "C", "but", "there", "are", "multiple", "source", "nodes", ".", "Only", "merge", "module", "nodes", "that", "have", "the", "same", "chain", ".", "Don", "t", "merge", "A", ".", "B", ...
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L48014-L48022
30,104
opendigitaleducation/sijil.js
docs/libs/typescript.js
merge
function merge(target, source) { target.additionalNodes = target.additionalNodes || []; target.additionalNodes.push(source.node); if (source.additionalNodes) { (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); } target.children = ts.concatenate(target.children, source.children); if (target.children) { mergeChildren(target.children); sortChildren(target.children); } var _a; }
javascript
function merge(target, source) { target.additionalNodes = target.additionalNodes || []; target.additionalNodes.push(source.node); if (source.additionalNodes) { (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); } target.children = ts.concatenate(target.children, source.children); if (target.children) { mergeChildren(target.children); sortChildren(target.children); } var _a; }
[ "function", "merge", "(", "target", ",", "source", ")", "{", "target", ".", "additionalNodes", "=", "target", ".", "additionalNodes", "||", "[", "]", ";", "target", ".", "additionalNodes", ".", "push", "(", "source", ".", "node", ")", ";", "if", "(", "...
Merge source into target. Source should be thrown away after this is called.
[ "Merge", "source", "into", "target", ".", "Source", "should", "be", "thrown", "away", "after", "this", "is", "called", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L48025-L48037
30,105
opendigitaleducation/sijil.js
docs/libs/typescript.js
topLevelItems
function topLevelItems(root) { var topLevel = []; function recur(item) { if (isTopLevel(item)) { topLevel.push(item); if (item.children) { for (var _i = 0, _a = item.children; _i < _a.length; _i++) { var child = _a[_i]; recur(child); } } } } recur(root); return topLevel; function isTopLevel(item) { switch (navigationBarNodeKind(item)) { case 221 /* ClassDeclaration */: case 192 /* ClassExpression */: case 224 /* EnumDeclaration */: case 222 /* InterfaceDeclaration */: case 225 /* ModuleDeclaration */: case 256 /* SourceFile */: case 223 /* TypeAliasDeclaration */: case 279 /* JSDocTypedefTag */: return true; case 148 /* Constructor */: case 147 /* MethodDeclaration */: case 149 /* GetAccessor */: case 150 /* SetAccessor */: return hasSomeImportantChild(item); case 180 /* ArrowFunction */: case 220 /* FunctionDeclaration */: case 179 /* FunctionExpression */: return isTopLevelFunctionDeclaration(item); default: return false; } function isTopLevelFunctionDeclaration(item) { if (!item.node.body) { return false; } switch (navigationBarNodeKind(item.parent)) { case 226 /* ModuleBlock */: case 256 /* SourceFile */: case 147 /* MethodDeclaration */: case 148 /* Constructor */: return true; default: return hasSomeImportantChild(item); } } function hasSomeImportantChild(item) { return ts.forEach(item.children, function (child) { var childKind = navigationBarNodeKind(child); return childKind !== 218 /* VariableDeclaration */ && childKind !== 169 /* BindingElement */; }); } } }
javascript
function topLevelItems(root) { var topLevel = []; function recur(item) { if (isTopLevel(item)) { topLevel.push(item); if (item.children) { for (var _i = 0, _a = item.children; _i < _a.length; _i++) { var child = _a[_i]; recur(child); } } } } recur(root); return topLevel; function isTopLevel(item) { switch (navigationBarNodeKind(item)) { case 221 /* ClassDeclaration */: case 192 /* ClassExpression */: case 224 /* EnumDeclaration */: case 222 /* InterfaceDeclaration */: case 225 /* ModuleDeclaration */: case 256 /* SourceFile */: case 223 /* TypeAliasDeclaration */: case 279 /* JSDocTypedefTag */: return true; case 148 /* Constructor */: case 147 /* MethodDeclaration */: case 149 /* GetAccessor */: case 150 /* SetAccessor */: return hasSomeImportantChild(item); case 180 /* ArrowFunction */: case 220 /* FunctionDeclaration */: case 179 /* FunctionExpression */: return isTopLevelFunctionDeclaration(item); default: return false; } function isTopLevelFunctionDeclaration(item) { if (!item.node.body) { return false; } switch (navigationBarNodeKind(item.parent)) { case 226 /* ModuleBlock */: case 256 /* SourceFile */: case 147 /* MethodDeclaration */: case 148 /* Constructor */: return true; default: return hasSomeImportantChild(item); } } function hasSomeImportantChild(item) { return ts.forEach(item.children, function (child) { var childKind = navigationBarNodeKind(child); return childKind !== 218 /* VariableDeclaration */ && childKind !== 169 /* BindingElement */; }); } } }
[ "function", "topLevelItems", "(", "root", ")", "{", "var", "topLevel", "=", "[", "]", ";", "function", "recur", "(", "item", ")", "{", "if", "(", "isTopLevel", "(", "item", ")", ")", "{", "topLevel", ".", "push", "(", "item", ")", ";", "if", "(", ...
Flattens the NavNode tree to a list, keeping only the top-level items.
[ "Flattens", "the", "NavNode", "tree", "to", "a", "list", "keeping", "only", "the", "top", "-", "level", "items", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L48154-L48213
30,106
opendigitaleducation/sijil.js
docs/libs/typescript.js
getArgumentIndexForTemplatePiece
function getArgumentIndexForTemplatePiece(spanIndex, node, position) { // Because the TemplateStringsArray is the first argument, we have to offset each substitution expression by 1. // There are three cases we can encounter: // 1. We are precisely in the template literal (argIndex = 0). // 2. We are in or to the right of the substitution expression (argIndex = spanIndex + 1). // 3. We are directly to the right of the template literal, but because we look for the token on the left, // not enough to put us in the substitution expression; we should consider ourselves part of // the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1). // // Example: f `# abcd $#{# 1 + 1# }# efghi ${ #"#hello"# } # ` // ^ ^ ^ ^ ^ ^ ^ ^ ^ // Case: 1 1 3 2 1 3 2 2 1 ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); if (ts.isTemplateLiteralKind(node.kind)) { if (ts.isInsideTemplateLiteral(node, position)) { return 0; } return spanIndex + 2; } return spanIndex + 1; }
javascript
function getArgumentIndexForTemplatePiece(spanIndex, node, position) { // Because the TemplateStringsArray is the first argument, we have to offset each substitution expression by 1. // There are three cases we can encounter: // 1. We are precisely in the template literal (argIndex = 0). // 2. We are in or to the right of the substitution expression (argIndex = spanIndex + 1). // 3. We are directly to the right of the template literal, but because we look for the token on the left, // not enough to put us in the substitution expression; we should consider ourselves part of // the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1). // // Example: f `# abcd $#{# 1 + 1# }# efghi ${ #"#hello"# } # ` // ^ ^ ^ ^ ^ ^ ^ ^ ^ // Case: 1 1 3 2 1 3 2 2 1 ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); if (ts.isTemplateLiteralKind(node.kind)) { if (ts.isInsideTemplateLiteral(node, position)) { return 0; } return spanIndex + 2; } return spanIndex + 1; }
[ "function", "getArgumentIndexForTemplatePiece", "(", "spanIndex", ",", "node", ",", "position", ")", "{", "// Because the TemplateStringsArray is the first argument, we have to offset each substitution expression by 1.", "// There are three cases we can encounter:", "// 1. We are precis...
spanIndex is either the index for a given template span. This does not give appropriate results for a NoSubstitutionTemplateLiteral
[ "spanIndex", "is", "either", "the", "index", "for", "a", "given", "template", "span", ".", "This", "does", "not", "give", "appropriate", "results", "for", "a", "NoSubstitutionTemplateLiteral" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L49218-L49238
30,107
opendigitaleducation/sijil.js
docs/libs/typescript.js
getTokenAtPosition
function getTokenAtPosition(sourceFile, position, includeJsDocComment) { if (includeJsDocComment === void 0) { includeJsDocComment = false; } return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includeItemAtEndPosition*/ undefined, includeJsDocComment); }
javascript
function getTokenAtPosition(sourceFile, position, includeJsDocComment) { if (includeJsDocComment === void 0) { includeJsDocComment = false; } return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includeItemAtEndPosition*/ undefined, includeJsDocComment); }
[ "function", "getTokenAtPosition", "(", "sourceFile", ",", "position", ",", "includeJsDocComment", ")", "{", "if", "(", "includeJsDocComment", "===", "void", "0", ")", "{", "includeJsDocComment", "=", "false", ";", "}", "return", "getTokenAtPositionWorker", "(", "s...
Returns a token if position is in [start-of-leading-trivia, end)
[ "Returns", "a", "token", "if", "position", "is", "in", "[", "start", "-", "of", "-", "leading", "-", "trivia", "end", ")" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L49657-L49660
30,108
opendigitaleducation/sijil.js
docs/libs/typescript.js
isInsideJsxElementOrAttribute
function isInsideJsxElementOrAttribute(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); if (!token) { return false; } if (token.kind === 244 /* JsxText */) { return true; } // <div>Hello |</div> if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 244 /* JsxText */) { return true; } // <div> { | </div> or <div a={| </div> if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 248 /* JsxExpression */) { return true; } // <div> { // | // } < /div> if (token && token.kind === 16 /* CloseBraceToken */ && token.parent.kind === 248 /* JsxExpression */) { return true; } // <div>|</div> if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 245 /* JsxClosingElement */) { return true; } return false; }
javascript
function isInsideJsxElementOrAttribute(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); if (!token) { return false; } if (token.kind === 244 /* JsxText */) { return true; } // <div>Hello |</div> if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 244 /* JsxText */) { return true; } // <div> { | </div> or <div a={| </div> if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 248 /* JsxExpression */) { return true; } // <div> { // | // } < /div> if (token && token.kind === 16 /* CloseBraceToken */ && token.parent.kind === 248 /* JsxExpression */) { return true; } // <div>|</div> if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 245 /* JsxClosingElement */) { return true; } return false; }
[ "function", "isInsideJsxElementOrAttribute", "(", "sourceFile", ",", "position", ")", "{", "var", "token", "=", "getTokenAtPosition", "(", "sourceFile", ",", "position", ")", ";", "if", "(", "!", "token", ")", "{", "return", "false", ";", "}", "if", "(", "...
returns true if the position is in between the open and close elements of an JSX expression.
[ "returns", "true", "if", "the", "position", "is", "in", "between", "the", "open", "and", "close", "elements", "of", "an", "JSX", "expression", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L49843-L49870
30,109
opendigitaleducation/sijil.js
docs/libs/typescript.js
isInCommentHelper
function isInCommentHelper(sourceFile, position, predicate) { var token = getTokenAtPosition(sourceFile, position); if (token && position <= token.getStart(sourceFile)) { var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); // The end marker of a single-line comment does not include the newline character. // In the following case, we are inside a comment (^ denotes the cursor position): // // // asdf ^\n // // But for multi-line comments, we don't want to be inside the comment in the following case: // // /* asdf */^ // // Internally, we represent the end of the comment at the newline and closing '/', respectively. return predicate ? ts.forEach(commentRanges, function (c) { return c.pos < position && (c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end) && predicate(c); }) : ts.forEach(commentRanges, function (c) { return c.pos < position && (c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end); }); } return false; }
javascript
function isInCommentHelper(sourceFile, position, predicate) { var token = getTokenAtPosition(sourceFile, position); if (token && position <= token.getStart(sourceFile)) { var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); // The end marker of a single-line comment does not include the newline character. // In the following case, we are inside a comment (^ denotes the cursor position): // // // asdf ^\n // // But for multi-line comments, we don't want to be inside the comment in the following case: // // /* asdf */^ // // Internally, we represent the end of the comment at the newline and closing '/', respectively. return predicate ? ts.forEach(commentRanges, function (c) { return c.pos < position && (c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end) && predicate(c); }) : ts.forEach(commentRanges, function (c) { return c.pos < position && (c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end); }); } return false; }
[ "function", "isInCommentHelper", "(", "sourceFile", ",", "position", ",", "predicate", ")", "{", "var", "token", "=", "getTokenAtPosition", "(", "sourceFile", ",", "position", ")", ";", "if", "(", "token", "&&", "position", "<=", "token", ".", "getStart", "(...
Returns true if the cursor at position in sourceFile is within a comment that additionally satisfies predicate, and false otherwise.
[ "Returns", "true", "if", "the", "cursor", "at", "position", "in", "sourceFile", "is", "within", "a", "comment", "that", "additionally", "satisfies", "predicate", "and", "false", "otherwise", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L49881-L49903
30,110
opendigitaleducation/sijil.js
docs/libs/typescript.js
mergeTypings
function mergeTypings(typingNames) { if (!typingNames) { return; } for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { var typing = typingNames_1[_i]; if (!(typing in inferredTypings)) { inferredTypings[typing] = undefined; } } }
javascript
function mergeTypings(typingNames) { if (!typingNames) { return; } for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { var typing = typingNames_1[_i]; if (!(typing in inferredTypings)) { inferredTypings[typing] = undefined; } } }
[ "function", "mergeTypings", "(", "typingNames", ")", "{", "if", "(", "!", "typingNames", ")", "{", "return", ";", "}", "for", "(", "var", "_i", "=", "0", ",", "typingNames_1", "=", "typingNames", ";", "_i", "<", "typingNames_1", ".", "length", ";", "_i...
Merge a given list of typingNames to the inferredTypings map
[ "Merge", "a", "given", "list", "of", "typingNames", "to", "the", "inferredTypings", "map" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L50444-L50454
30,111
opendigitaleducation/sijil.js
docs/libs/typescript.js
getTypingNamesFromJson
function getTypingNamesFromJson(jsonPath, filesToWatch) { if (host.fileExists(jsonPath)) { filesToWatch.push(jsonPath); } var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); if (result.config) { var jsonConfig = result.config; if (jsonConfig.dependencies) { mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); } if (jsonConfig.devDependencies) { mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); } if (jsonConfig.optionalDependencies) { mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); } if (jsonConfig.peerDependencies) { mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); } } }
javascript
function getTypingNamesFromJson(jsonPath, filesToWatch) { if (host.fileExists(jsonPath)) { filesToWatch.push(jsonPath); } var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); if (result.config) { var jsonConfig = result.config; if (jsonConfig.dependencies) { mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); } if (jsonConfig.devDependencies) { mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); } if (jsonConfig.optionalDependencies) { mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); } if (jsonConfig.peerDependencies) { mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); } } }
[ "function", "getTypingNamesFromJson", "(", "jsonPath", ",", "filesToWatch", ")", "{", "if", "(", "host", ".", "fileExists", "(", "jsonPath", ")", ")", "{", "filesToWatch", ".", "push", "(", "jsonPath", ")", ";", "}", "var", "result", "=", "ts", ".", "rea...
Get the typing info from common package manager json files like package.json or bower.json
[ "Get", "the", "typing", "info", "from", "common", "package", "manager", "json", "files", "like", "package", ".", "json", "or", "bower", ".", "json" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L50458-L50478
30,112
opendigitaleducation/sijil.js
docs/libs/typescript.js
getTypingNamesFromSourceFileNames
function getTypingNamesFromSourceFileNames(fileNames) { var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); if (safeList !== EmptySafeList) { mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); } var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2 /* JSX */; }); if (hasJsxFile) { mergeTypings(["react"]); } }
javascript
function getTypingNamesFromSourceFileNames(fileNames) { var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); if (safeList !== EmptySafeList) { mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); } var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2 /* JSX */; }); if (hasJsxFile) { mergeTypings(["react"]); } }
[ "function", "getTypingNamesFromSourceFileNames", "(", "fileNames", ")", "{", "var", "jsFileNames", "=", "ts", ".", "filter", "(", "fileNames", ",", "ts", ".", "hasJavaScriptFileExtension", ")", ";", "var", "inferredTypingNames", "=", "ts", ".", "map", "(", "jsFi...
Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred to the 'angular-route' typing name. @param fileNames are the names for source files in the project
[ "Infer", "typing", "names", "from", "given", "file", "names", ".", "For", "example", "the", "file", "name", "jquery", "-", "min", ".", "2", ".", "3", ".", "4", ".", "js", "should", "be", "inferred", "to", "the", "jquery", "typing", "name", ";", "and"...
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L50485-L50496
30,113
opendigitaleducation/sijil.js
docs/libs/typescript.js
getTypingNamesFromNodeModuleFolder
function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { // Todo: add support for ModuleResolutionHost too if (!host.directoryExists(nodeModulesPath)) { return; } var typingNames = []; var fileNames = host.readDirectory(nodeModulesPath, [".json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); if (ts.getBaseFileName(normalizedFileName) !== "package.json") { continue; } var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); if (!result.config) { continue; } var packageJson = result.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. if (packageJson._requiredBy && ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { continue; } // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used // to download d.ts files from DefinitelyTyped if (!packageJson.name) { continue; } if (packageJson.typings) { var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); inferredTypings[packageJson.name] = absolutePath; } else { typingNames.push(packageJson.name); } } mergeTypings(typingNames); }
javascript
function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { // Todo: add support for ModuleResolutionHost too if (!host.directoryExists(nodeModulesPath)) { return; } var typingNames = []; var fileNames = host.readDirectory(nodeModulesPath, [".json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); if (ts.getBaseFileName(normalizedFileName) !== "package.json") { continue; } var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); if (!result.config) { continue; } var packageJson = result.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. if (packageJson._requiredBy && ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { continue; } // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used // to download d.ts files from DefinitelyTyped if (!packageJson.name) { continue; } if (packageJson.typings) { var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); inferredTypings[packageJson.name] = absolutePath; } else { typingNames.push(packageJson.name); } } mergeTypings(typingNames); }
[ "function", "getTypingNamesFromNodeModuleFolder", "(", "nodeModulesPath", ")", "{", "// Todo: add support for ModuleResolutionHost too", "if", "(", "!", "host", ".", "directoryExists", "(", "nodeModulesPath", ")", ")", "{", "return", ";", "}", "var", "typingNames", "=",...
Infer typing names from node_module folder @param nodeModulesPath is the path to the "node_modules" folder
[ "Infer", "typing", "names", "from", "node_module", "folder" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L50501-L50540
30,114
opendigitaleducation/sijil.js
docs/libs/typescript.js
getScanStartPosition
function getScanStartPosition(enclosingNode, originalRange, sourceFile) { var start = enclosingNode.getStart(sourceFile); if (start === originalRange.pos && enclosingNode.end === originalRange.end) { return start; } var precedingToken = ts.findPrecedingToken(originalRange.pos, sourceFile); if (!precedingToken) { // no preceding token found - start from the beginning of enclosing node return enclosingNode.pos; } // preceding token ends after the start of original range (i.e when originalRange.pos falls in the middle of literal) // start from the beginning of enclosingNode to handle the entire 'originalRange' if (precedingToken.end >= originalRange.pos) { return enclosingNode.pos; } return precedingToken.end; }
javascript
function getScanStartPosition(enclosingNode, originalRange, sourceFile) { var start = enclosingNode.getStart(sourceFile); if (start === originalRange.pos && enclosingNode.end === originalRange.end) { return start; } var precedingToken = ts.findPrecedingToken(originalRange.pos, sourceFile); if (!precedingToken) { // no preceding token found - start from the beginning of enclosing node return enclosingNode.pos; } // preceding token ends after the start of original range (i.e when originalRange.pos falls in the middle of literal) // start from the beginning of enclosingNode to handle the entire 'originalRange' if (precedingToken.end >= originalRange.pos) { return enclosingNode.pos; } return precedingToken.end; }
[ "function", "getScanStartPosition", "(", "enclosingNode", ",", "originalRange", ",", "sourceFile", ")", "{", "var", "start", "=", "enclosingNode", ".", "getStart", "(", "sourceFile", ")", ";", "if", "(", "start", "===", "originalRange", ".", "pos", "&&", "encl...
Start of the original range might fall inside the comment - scanner will not yield appropriate results This function will look for token that is located before the start of target range and return its end as start position for the scanner.
[ "Start", "of", "the", "original", "range", "might", "fall", "inside", "the", "comment", "-", "scanner", "will", "not", "yield", "appropriate", "results", "This", "function", "will", "look", "for", "token", "that", "is", "located", "before", "the", "start", "...
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L52155-L52171
30,115
opendigitaleducation/sijil.js
docs/libs/typescript.js
tryComputeIndentationForListItem
function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) { if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) || ts.rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) { if (inheritedIndentation !== -1 /* Unknown */) { return inheritedIndentation; } } else { var startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line; var startLinePosition = ts.getLineStartPositionForPosition(startPos, sourceFile); var column = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options); if (startLine !== parentStartLine || startPos === column) { // Use the base indent size if it is greater than // the indentation of the inherited predecessor. var baseIndentSize = formatting.SmartIndenter.getBaseIndentation(options); return baseIndentSize > column ? baseIndentSize : column; } } return -1 /* Unknown */; }
javascript
function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) { if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) || ts.rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) { if (inheritedIndentation !== -1 /* Unknown */) { return inheritedIndentation; } } else { var startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line; var startLinePosition = ts.getLineStartPositionForPosition(startPos, sourceFile); var column = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options); if (startLine !== parentStartLine || startPos === column) { // Use the base indent size if it is greater than // the indentation of the inherited predecessor. var baseIndentSize = formatting.SmartIndenter.getBaseIndentation(options); return baseIndentSize > column ? baseIndentSize : column; } } return -1 /* Unknown */; }
[ "function", "tryComputeIndentationForListItem", "(", "startPos", ",", "endPos", ",", "parentStartLine", ",", "range", ",", "inheritedIndentation", ")", "{", "if", "(", "ts", ".", "rangeOverlapsWithStartEnd", "(", "range", ",", "startPos", ",", "endPos", ")", "||",...
local functions Tries to compute the indentation for a list element. If list element is not in range then function will pick its actual indentation so it can be pushed downstream as inherited indentation. If list element is in the range - its indentation will be equal to inherited indentation from its predecessors.
[ "local", "functions", "Tries", "to", "compute", "the", "indentation", "for", "a", "list", "element", ".", "If", "list", "element", "is", "not", "in", "range", "then", "function", "will", "pick", "its", "actual", "indentation", "so", "it", "can", "be", "pus...
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L52246-L52265
30,116
opendigitaleducation/sijil.js
docs/libs/typescript.js
trimTrailingWhitespacesForRemainingRange
function trimTrailingWhitespacesForRemainingRange() { var startPosition = previousRange ? previousRange.end : originalRange.pos; var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); }
javascript
function trimTrailingWhitespacesForRemainingRange() { var startPosition = previousRange ? previousRange.end : originalRange.pos; var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); }
[ "function", "trimTrailingWhitespacesForRemainingRange", "(", ")", "{", "var", "startPosition", "=", "previousRange", "?", "previousRange", ".", "end", ":", "originalRange", ".", "pos", ";", "var", "startLine", "=", "sourceFile", ".", "getLineAndCharacterOfPosition", "...
Trimming will be done for lines after the previous range
[ "Trimming", "will", "be", "done", "for", "lines", "after", "the", "previous", "range" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L52743-L52748
30,117
opendigitaleducation/sijil.js
docs/libs/typescript.js
getCompletionEntryDisplayNameForSymbol
function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, location) { var displayName = ts.getDeclaredName(program.getTypeChecker(), symbol, location); if (displayName) { var firstCharCode = displayName.charCodeAt(0); // First check of the displayName is not external module; if it is an external module, it is not valid entry if ((symbol.flags & 1920 /* Namespace */) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { // If the symbol is external module, don't show it in the completion list // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) return undefined; } } return getCompletionEntryDisplayName(displayName, target, performCharacterChecks); }
javascript
function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, location) { var displayName = ts.getDeclaredName(program.getTypeChecker(), symbol, location); if (displayName) { var firstCharCode = displayName.charCodeAt(0); // First check of the displayName is not external module; if it is an external module, it is not valid entry if ((symbol.flags & 1920 /* Namespace */) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { // If the symbol is external module, don't show it in the completion list // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) return undefined; } } return getCompletionEntryDisplayName(displayName, target, performCharacterChecks); }
[ "function", "getCompletionEntryDisplayNameForSymbol", "(", "symbol", ",", "target", ",", "performCharacterChecks", ",", "location", ")", "{", "var", "displayName", "=", "ts", ".", "getDeclaredName", "(", "program", ".", "getTypeChecker", "(", ")", ",", "symbol", "...
Get the name to be display in completion from a given symbol. @return undefined if the name is of external module otherwise a name with striped of any quote
[ "Get", "the", "name", "to", "be", "display", "in", "completion", "from", "a", "given", "symbol", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L55741-L55753
30,118
opendigitaleducation/sijil.js
docs/libs/typescript.js
getCompletionEntryDisplayName
function getCompletionEntryDisplayName(name, target, performCharacterChecks) { if (!name) { return undefined; } name = ts.stripQuotes(name); if (!name) { return undefined; } // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. if (performCharacterChecks) { if (!ts.isIdentifier(name, target)) { return undefined; } } return name; }
javascript
function getCompletionEntryDisplayName(name, target, performCharacterChecks) { if (!name) { return undefined; } name = ts.stripQuotes(name); if (!name) { return undefined; } // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. if (performCharacterChecks) { if (!ts.isIdentifier(name, target)) { return undefined; } } return name; }
[ "function", "getCompletionEntryDisplayName", "(", "name", ",", "target", ",", "performCharacterChecks", ")", "{", "if", "(", "!", "name", ")", "{", "return", "undefined", ";", "}", "name", "=", "ts", ".", "stripQuotes", "(", "name", ")", ";", "if", "(", ...
Get a displayName from a given for completion list, performing any necessary quotes stripping and checking whether the name is valid identifier name.
[ "Get", "a", "displayName", "from", "a", "given", "for", "completion", "list", "performing", "any", "necessary", "quotes", "stripping", "and", "checking", "whether", "the", "name", "is", "valid", "identifier", "name", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L55758-L55776
30,119
opendigitaleducation/sijil.js
docs/libs/typescript.js
tryGetObjectLikeCompletionSymbols
function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. isMemberCompletion = true; var typeForObject; var existingMembers; if (objectLikeContainer.kind === 171 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; // If the object literal is being assigned to something of type 'null | { hello: string }', // it clearly isn't trying to satisfy the 'null' type. So we grab the non-nullable type if possible. typeForObject = typeChecker.getContextualType(objectLikeContainer); typeForObject = typeForObject && typeForObject.getNonNullableType(); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 167 /* ObjectBindingPattern */) { // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); if (ts.isVariableLike(rootDeclaration)) { // We don't want to complete using the type acquired by the shape // of the binding pattern; we are only interested in types acquired // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); if (!canGetType && rootDeclaration.kind === 142 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } else if (rootDeclaration.parent.kind === 147 /* MethodDeclaration */ || rootDeclaration.parent.kind === 150 /* SetAccessor */) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } if (canGetType) { typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); existingMembers = objectLikeContainer.elements; } } else { ts.Debug.fail("Root declaration is not variable-like."); } } else { ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } if (!typeForObject) { return false; } var typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, existingMembers); } return true; }
javascript
function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. isMemberCompletion = true; var typeForObject; var existingMembers; if (objectLikeContainer.kind === 171 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; // If the object literal is being assigned to something of type 'null | { hello: string }', // it clearly isn't trying to satisfy the 'null' type. So we grab the non-nullable type if possible. typeForObject = typeChecker.getContextualType(objectLikeContainer); typeForObject = typeForObject && typeForObject.getNonNullableType(); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 167 /* ObjectBindingPattern */) { // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); if (ts.isVariableLike(rootDeclaration)) { // We don't want to complete using the type acquired by the shape // of the binding pattern; we are only interested in types acquired // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); if (!canGetType && rootDeclaration.kind === 142 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } else if (rootDeclaration.parent.kind === 147 /* MethodDeclaration */ || rootDeclaration.parent.kind === 150 /* SetAccessor */) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } if (canGetType) { typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); existingMembers = objectLikeContainer.elements; } } else { ts.Debug.fail("Root declaration is not variable-like."); } } else { ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } if (!typeForObject) { return false; } var typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, existingMembers); } return true; }
[ "function", "tryGetObjectLikeCompletionSymbols", "(", "objectLikeContainer", ")", "{", "// We're looking up possible property names from contextual/inferred/declared type.", "isMemberCompletion", "=", "true", ";", "var", "typeForObject", ";", "var", "existingMembers", ";", "if", ...
Aggregates relevant symbols for completion in object literals and object binding patterns. Relevant symbols are stored in the captured 'symbols' variable. @returns true if 'symbols' was successfully populated; false otherwise.
[ "Aggregates", "relevant", "symbols", "for", "completion", "in", "object", "literals", "and", "object", "binding", "patterns", ".", "Relevant", "symbols", "are", "stored", "in", "the", "captured", "symbols", "variable", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L56137-L56192
30,120
opendigitaleducation/sijil.js
docs/libs/typescript.js
tryGetObjectLikeCompletionContainer
function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { case 15 /* OpenBraceToken */: // const x = { | case 24 /* CommaToken */: var parent_19 = contextToken.parent; if (parent_19 && (parent_19.kind === 171 /* ObjectLiteralExpression */ || parent_19.kind === 167 /* ObjectBindingPattern */)) { return parent_19; } break; } } return undefined; }
javascript
function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { case 15 /* OpenBraceToken */: // const x = { | case 24 /* CommaToken */: var parent_19 = contextToken.parent; if (parent_19 && (parent_19.kind === 171 /* ObjectLiteralExpression */ || parent_19.kind === 167 /* ObjectBindingPattern */)) { return parent_19; } break; } } return undefined; }
[ "function", "tryGetObjectLikeCompletionContainer", "(", "contextToken", ")", "{", "if", "(", "contextToken", ")", "{", "switch", "(", "contextToken", ".", "kind", ")", "{", "case", "15", "/* OpenBraceToken */", ":", "// const x = { |", "case", "24", "/* CommaToken *...
Returns the immediate owning object literal or binding pattern of a context token, on the condition that one exists and that the context implies completion should be given.
[ "Returns", "the", "immediate", "owning", "object", "literal", "or", "binding", "pattern", "of", "a", "context", "token", "on", "the", "condition", "that", "one", "exists", "and", "that", "the", "context", "implies", "completion", "should", "be", "given", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L56231-L56244
30,121
opendigitaleducation/sijil.js
docs/libs/typescript.js
tryGetNamedImportsOrExportsForCompletion
function tryGetNamedImportsOrExportsForCompletion(contextToken) { if (contextToken) { switch (contextToken.kind) { case 15 /* OpenBraceToken */: // import { | case 24 /* CommaToken */: switch (contextToken.parent.kind) { case 233 /* NamedImports */: case 237 /* NamedExports */: return contextToken.parent; } } } return undefined; }
javascript
function tryGetNamedImportsOrExportsForCompletion(contextToken) { if (contextToken) { switch (contextToken.kind) { case 15 /* OpenBraceToken */: // import { | case 24 /* CommaToken */: switch (contextToken.parent.kind) { case 233 /* NamedImports */: case 237 /* NamedExports */: return contextToken.parent; } } } return undefined; }
[ "function", "tryGetNamedImportsOrExportsForCompletion", "(", "contextToken", ")", "{", "if", "(", "contextToken", ")", "{", "switch", "(", "contextToken", ".", "kind", ")", "{", "case", "15", "/* OpenBraceToken */", ":", "// import { |", "case", "24", "/* CommaToken...
Returns the containing list of named imports or exports of a context token, on the condition that one exists and that the context implies completion should be given.
[ "Returns", "the", "containing", "list", "of", "named", "imports", "or", "exports", "of", "a", "context", "token", "on", "the", "condition", "that", "one", "exists", "and", "that", "the", "context", "implies", "completion", "should", "be", "given", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L56249-L56262
30,122
opendigitaleducation/sijil.js
docs/libs/typescript.js
filterNamedImportOrExportCompletionItems
function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { var existingImportsOrExports = ts.createMap(); for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; // If this is the current item we are editing right now, do not filter it out if (element.getStart() <= position && position <= element.getEnd()) { continue; } var name_41 = element.propertyName || element.name; existingImportsOrExports[name_41.text] = true; } if (!ts.someProperties(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); } return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !existingImportsOrExports[e.name]; }); }
javascript
function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { var existingImportsOrExports = ts.createMap(); for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; // If this is the current item we are editing right now, do not filter it out if (element.getStart() <= position && position <= element.getEnd()) { continue; } var name_41 = element.propertyName || element.name; existingImportsOrExports[name_41.text] = true; } if (!ts.someProperties(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); } return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !existingImportsOrExports[e.name]; }); }
[ "function", "filterNamedImportOrExportCompletionItems", "(", "exportsOfModule", ",", "namedImportsOrExports", ")", "{", "var", "existingImportsOrExports", "=", "ts", ".", "createMap", "(", ")", ";", "for", "(", "var", "_i", "=", "0", ",", "namedImportsOrExports_1", ...
Filters out completion suggestions for named imports or exports. @param exportsOfModule The list of symbols which a module exposes. @param namedImportsOrExports The list of existing import/export specifiers in the import/export clause. @returns Symbols to be suggested at an import/export clause, barring those whose named imports/exports do not occur at the current position and have not otherwise been typed.
[ "Filters", "out", "completion", "suggestions", "for", "named", "imports", "or", "exports", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L56424-L56439
30,123
opendigitaleducation/sijil.js
docs/libs/typescript.js
getBaseDirectoriesFromRootDirs
function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { // Make all paths absolute/normalized if they are not already rootDirs = ts.map(rootDirs, function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); // Determine the path to the directory containing the script relative to the root directory it is contained within var relativeDirectory; for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { var rootDirectory = rootDirs_1[_i]; if (ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase)) { relativeDirectory = scriptPath.substr(rootDirectory.length); break; } } // Now find a path for each potential directory that is to be merged with the one containing the script return ts.deduplicate(ts.map(rootDirs, function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); })); }
javascript
function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { // Make all paths absolute/normalized if they are not already rootDirs = ts.map(rootDirs, function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); // Determine the path to the directory containing the script relative to the root directory it is contained within var relativeDirectory; for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { var rootDirectory = rootDirs_1[_i]; if (ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase)) { relativeDirectory = scriptPath.substr(rootDirectory.length); break; } } // Now find a path for each potential directory that is to be merged with the one containing the script return ts.deduplicate(ts.map(rootDirs, function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); })); }
[ "function", "getBaseDirectoriesFromRootDirs", "(", "rootDirs", ",", "basePath", ",", "scriptPath", ",", "ignoreCase", ")", "{", "// Make all paths absolute/normalized if they are not already", "rootDirs", "=", "ts", ".", "map", "(", "rootDirs", ",", "function", "(", "ro...
Takes a script path and returns paths for all potential folders that could be merged with its containing folder via the "rootDirs" compiler option
[ "Takes", "a", "script", "path", "and", "returns", "paths", "for", "all", "potential", "folders", "that", "could", "be", "merged", "with", "its", "containing", "folder", "via", "the", "rootDirs", "compiler", "option" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L56778-L56792
30,124
opendigitaleducation/sijil.js
docs/libs/typescript.js
getDirectoryFragmentTextSpan
function getDirectoryFragmentTextSpan(text, textStart) { var index = text.lastIndexOf(ts.directorySeparator); var offset = index !== -1 ? index + 1 : 0; return { start: textStart + offset, length: text.length - offset }; }
javascript
function getDirectoryFragmentTextSpan(text, textStart) { var index = text.lastIndexOf(ts.directorySeparator); var offset = index !== -1 ? index + 1 : 0; return { start: textStart + offset, length: text.length - offset }; }
[ "function", "getDirectoryFragmentTextSpan", "(", "text", ",", "textStart", ")", "{", "var", "index", "=", "text", ".", "lastIndexOf", "(", "ts", ".", "directorySeparator", ")", ";", "var", "offset", "=", "index", "!==", "-", "1", "?", "index", "+", "1", ...
Replace everything after the last directory seperator that appears
[ "Replace", "everything", "after", "the", "last", "directory", "seperator", "that", "appears" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L57124-L57128
30,125
opendigitaleducation/sijil.js
docs/libs/typescript.js
getSymbolScope
function getSymbolScope(symbol) { // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var valueDeclaration = symbol.valueDeclaration; if (valueDeclaration && (valueDeclaration.kind === 179 /* FunctionExpression */ || valueDeclaration.kind === 192 /* ClassExpression */)) { return valueDeclaration; } // If this is private property or method, the scope is the containing class if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 8 /* Private */) ? d : undefined; }); if (privateDeclaration) { return ts.getAncestor(privateDeclaration, 221 /* ClassDeclaration */); } } // If the symbol is an import we would like to find it if we are looking for what it imports. // So consider it visible outside its declaration scope. if (symbol.flags & 8388608 /* Alias */) { return undefined; } // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { return undefined; } // if this symbol is visible from its parent container, e.g. exported, then bail out // if symbol correspond to the union property - bail out if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) { return undefined; } var scope; var declarations = symbol.getDeclarations(); if (declarations) { for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { var declaration = declarations_9[_i]; var container = getContainerNode(declaration); if (!container) { return undefined; } if (scope && scope !== container) { // Different declarations have different containers, bail out return undefined; } if (container.kind === 256 /* SourceFile */ && !ts.isExternalModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; } // The search scope is the container node scope = container; } } return scope; }
javascript
function getSymbolScope(symbol) { // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var valueDeclaration = symbol.valueDeclaration; if (valueDeclaration && (valueDeclaration.kind === 179 /* FunctionExpression */ || valueDeclaration.kind === 192 /* ClassExpression */)) { return valueDeclaration; } // If this is private property or method, the scope is the containing class if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 8 /* Private */) ? d : undefined; }); if (privateDeclaration) { return ts.getAncestor(privateDeclaration, 221 /* ClassDeclaration */); } } // If the symbol is an import we would like to find it if we are looking for what it imports. // So consider it visible outside its declaration scope. if (symbol.flags & 8388608 /* Alias */) { return undefined; } // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { return undefined; } // if this symbol is visible from its parent container, e.g. exported, then bail out // if symbol correspond to the union property - bail out if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) { return undefined; } var scope; var declarations = symbol.getDeclarations(); if (declarations) { for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { var declaration = declarations_9[_i]; var container = getContainerNode(declaration); if (!container) { return undefined; } if (scope && scope !== container) { // Different declarations have different containers, bail out return undefined; } if (container.kind === 256 /* SourceFile */ && !ts.isExternalModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; } // The search scope is the container node scope = container; } } return scope; }
[ "function", "getSymbolScope", "(", "symbol", ")", "{", "// If this is the symbol of a named function expression or named class expression,", "// then named references are limited to its own scope.", "var", "valueDeclaration", "=", "symbol", ".", "valueDeclaration", ";", "if", "(", ...
Determines the smallest scope in which a symbol may have named references. Note that not every construct has been accounted for. This function can probably be improved. @returns undefined if the scope cannot be determined, implying that a reference to a symbol can occur anywhere.
[ "Determines", "the", "smallest", "scope", "in", "which", "a", "symbol", "may", "have", "named", "references", ".", "Note", "that", "not", "every", "construct", "has", "been", "accounted", "for", ".", "This", "function", "can", "probably", "be", "improved", "...
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L58682-L58734
30,126
opendigitaleducation/sijil.js
docs/libs/typescript.js
tryClassifyNode
function tryClassifyNode(node) { if (ts.isJSDocTag(node)) { return true; } if (ts.nodeIsMissing(node)) { return true; } var classifiedElementName = tryClassifyJsxElementName(node); if (!ts.isToken(node) && node.kind !== 244 /* JsxText */ && classifiedElementName === undefined) { return false; } var tokenStart = node.kind === 244 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); var tokenWidth = node.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { var type = classifiedElementName || classifyTokenType(node.kind, node); if (type) { pushClassification(tokenStart, tokenWidth, type); } } return true; }
javascript
function tryClassifyNode(node) { if (ts.isJSDocTag(node)) { return true; } if (ts.nodeIsMissing(node)) { return true; } var classifiedElementName = tryClassifyJsxElementName(node); if (!ts.isToken(node) && node.kind !== 244 /* JsxText */ && classifiedElementName === undefined) { return false; } var tokenStart = node.kind === 244 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); var tokenWidth = node.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { var type = classifiedElementName || classifyTokenType(node.kind, node); if (type) { pushClassification(tokenStart, tokenWidth, type); } } return true; }
[ "function", "tryClassifyNode", "(", "node", ")", "{", "if", "(", "ts", ".", "isJSDocTag", "(", "node", ")", ")", "{", "return", "true", ";", "}", "if", "(", "ts", ".", "nodeIsMissing", "(", "node", ")", ")", "{", "return", "true", ";", "}", "var", ...
Returns true if node should be treated as classified and no further processing is required. False will mean that node is not classified and traverse routine should recurse into node contents.
[ "Returns", "true", "if", "node", "should", "be", "treated", "as", "classified", "and", "no", "further", "processing", "is", "required", ".", "False", "will", "mean", "that", "node", "is", "not", "classified", "and", "traverse", "routine", "should", "recurse", ...
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L59869-L59890
30,127
opendigitaleducation/sijil.js
docs/libs/typescript.js
canFollow
function canFollow(keyword1, keyword2) { if (ts.isAccessibilityModifier(keyword1)) { if (keyword2 === 123 /* GetKeyword */ || keyword2 === 131 /* SetKeyword */ || keyword2 === 121 /* ConstructorKeyword */ || keyword2 === 113 /* StaticKeyword */) { // Allow things like "public get", "public constructor" and "public static". // These are all legal. return true; } // Any other keyword following "public" is actually an identifier an not a real // keyword. return false; } // Assume any other keyword combination is legal. This can be refined in the future // if there are more cases we want the classifier to be better at. return true; }
javascript
function canFollow(keyword1, keyword2) { if (ts.isAccessibilityModifier(keyword1)) { if (keyword2 === 123 /* GetKeyword */ || keyword2 === 131 /* SetKeyword */ || keyword2 === 121 /* ConstructorKeyword */ || keyword2 === 113 /* StaticKeyword */) { // Allow things like "public get", "public constructor" and "public static". // These are all legal. return true; } // Any other keyword following "public" is actually an identifier an not a real // keyword. return false; } // Assume any other keyword combination is legal. This can be refined in the future // if there are more cases we want the classifier to be better at. return true; }
[ "function", "canFollow", "(", "keyword1", ",", "keyword2", ")", "{", "if", "(", "ts", ".", "isAccessibilityModifier", "(", "keyword1", ")", ")", "{", "if", "(", "keyword2", "===", "123", "/* GetKeyword */", "||", "keyword2", "===", "131", "/* SetKeyword */", ...
Returns true if 'keyword2' can legally follow 'keyword1' in any language construct.
[ "Returns", "true", "if", "keyword2", "can", "legally", "follow", "keyword1", "in", "any", "language", "construct", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L60612-L60629
30,128
2do2go/node-twostep
lib/twoStep.js
chainStepsNoError
function chainStepsNoError() { var steps = slice.call(arguments).map(function(step) { return notHandlingError(step); }); return chainSteps.apply(null, steps); }
javascript
function chainStepsNoError() { var steps = slice.call(arguments).map(function(step) { return notHandlingError(step); }); return chainSteps.apply(null, steps); }
[ "function", "chainStepsNoError", "(", ")", "{", "var", "steps", "=", "slice", ".", "call", "(", "arguments", ")", ".", "map", "(", "function", "(", "step", ")", "{", "return", "notHandlingError", "(", "step", ")", ";", "}", ")", ";", "return", "chainSt...
Similar to `makeSteps` but the chaining continues only on successful execution of the previous step and breaks after the first error occured.
[ "Similar", "to", "makeSteps", "but", "the", "chaining", "continues", "only", "on", "successful", "execution", "of", "the", "previous", "step", "and", "breaks", "after", "the", "first", "error", "occured", "." ]
4a491b6982e26f6349c82072f04bed0ff2cc779c
https://github.com/2do2go/node-twostep/blob/4a491b6982e26f6349c82072f04bed0ff2cc779c/lib/twoStep.js#L138-L143
30,129
2do2go/node-twostep
lib/twoStep.js
chainAndCall
function chainAndCall(chainer) { return function(/*step1, step2, ...*/) { var steps = slice.call(arguments); var callback = steps.pop(); chainer.apply(null, steps)(callback); }; }
javascript
function chainAndCall(chainer) { return function(/*step1, step2, ...*/) { var steps = slice.call(arguments); var callback = steps.pop(); chainer.apply(null, steps)(callback); }; }
[ "function", "chainAndCall", "(", "chainer", ")", "{", "return", "function", "(", "/*step1, step2, ...*/", ")", "{", "var", "steps", "=", "slice", ".", "call", "(", "arguments", ")", ";", "var", "callback", "=", "steps", ".", "pop", "(", ")", ";", "chaine...
Chain and execute given steps immediately. The last step in chain will be the error- and result-handling callback.
[ "Chain", "and", "execute", "given", "steps", "immediately", ".", "The", "last", "step", "in", "chain", "will", "be", "the", "error", "-", "and", "result", "-", "handling", "callback", "." ]
4a491b6982e26f6349c82072f04bed0ff2cc779c
https://github.com/2do2go/node-twostep/blob/4a491b6982e26f6349c82072f04bed0ff2cc779c/lib/twoStep.js#L183-L189
30,130
apparatus/mu
packages/mu-router/index.js
route
function route (message, cb) { assert(message, 'route requries a valid message') assert(cb && (typeof cb === 'function'), 'route requires a valid callback handler') if (message.pattern) { return pattern(message, cb) } if (message.response) { return response(message, cb) } malformed(message, cb) }
javascript
function route (message, cb) { assert(message, 'route requries a valid message') assert(cb && (typeof cb === 'function'), 'route requires a valid callback handler') if (message.pattern) { return pattern(message, cb) } if (message.response) { return response(message, cb) } malformed(message, cb) }
[ "function", "route", "(", "message", ",", "cb", ")", "{", "assert", "(", "message", ",", "'route requries a valid message'", ")", "assert", "(", "cb", "&&", "(", "typeof", "cb", "===", "'function'", ")", ",", "'route requires a valid callback handler'", ")", "if...
main routing function
[ "main", "routing", "function" ]
c084ec60b5e3a7c163bead9aedbb59eefa1ea787
https://github.com/apparatus/mu/blob/c084ec60b5e3a7c163bead9aedbb59eefa1ea787/packages/mu-router/index.js#L66-L79
30,131
ericelliott/qconf
lib/make-config.js
get
function get(attr) { var val = dotty.get(attrs, attr); if (val === undefined) { this.emit('undefined', 'WARNING: Undefined environment variable: ' + attr, attr); } return val; }
javascript
function get(attr) { var val = dotty.get(attrs, attr); if (val === undefined) { this.emit('undefined', 'WARNING: Undefined environment variable: ' + attr, attr); } return val; }
[ "function", "get", "(", "attr", ")", "{", "var", "val", "=", "dotty", ".", "get", "(", "attrs", ",", "attr", ")", ";", "if", "(", "val", "===", "undefined", ")", "{", "this", ".", "emit", "(", "'undefined'", ",", "'WARNING: Undefined environment variable...
Return the value of the attribute requested. @param {String} attr The name of the attribute to return. @return {Any} The value of the requested attribute.
[ "Return", "the", "value", "of", "the", "attribute", "requested", "." ]
6969136ddfd3c4b688a26aba1bb7d0567158b7fb
https://github.com/ericelliott/qconf/blob/6969136ddfd3c4b688a26aba1bb7d0567158b7fb/lib/make-config.js#L22-L29
30,132
wokim/node-perforce
index.js
processZtagOutput
function processZtagOutput(output) { return output.split('\n').reduce(function(memo, line) { var match, key, value; match = ztagRegex.exec(line); if(match) { key = match[1]; value = match[2]; memo[key] = value; } return memo; }, {}); }
javascript
function processZtagOutput(output) { return output.split('\n').reduce(function(memo, line) { var match, key, value; match = ztagRegex.exec(line); if(match) { key = match[1]; value = match[2]; memo[key] = value; } return memo; }, {}); }
[ "function", "processZtagOutput", "(", "output", ")", "{", "return", "output", ".", "split", "(", "'\\n'", ")", ".", "reduce", "(", "function", "(", "memo", ",", "line", ")", "{", "var", "match", ",", "key", ",", "value", ";", "match", "=", "ztagRegex",...
process group of lines of output from a p4 command executed with -ztag
[ "process", "group", "of", "lines", "of", "output", "from", "a", "p4", "command", "executed", "with", "-", "ztag" ]
687e39b0177da0061f2980ed6b3c7e967259e263
https://github.com/wokim/node-perforce/blob/687e39b0177da0061f2980ed6b3c7e967259e263/index.js#L83-L94
30,133
af/JSnoX
jsnox.js
jsnox
function jsnox(React) { var client = function jsnoxClient(componentType, props, children) { // Special $renderIf prop allows you to conditionally render an element: //if (props && typeof props.$renderIf !== 'undefined') { if (props && typeof props === 'object' && props.hasOwnProperty('$renderIf')) { if (props.$renderIf) delete props.$renderIf // Don't pass down to components else return null } // Handle case where an array of children is given as the second argument: if (Array.isArray(props) || typeof props !== 'object') { children = props props = null } // Handle case where props object (second arg) is omitted var arg2IsReactElement = props && React.isValidElement(props) var finalProps = props if (typeof componentType === 'string' || !componentType) { // Parse the provided string into a hash of props // If componentType is invalid (undefined, empty string, etc), // parseTagSpec should throw. var spec = parseTagSpec(componentType) componentType = spec.tagName finalProps = arg2IsReactElement ? spec.props : extend(spec.props, props) } // If more than three args are given, assume args 3..n are ReactElement // children. You can also pass an array of children as the 3rd argument, // but in that case each child should have a unique key to avoid warnings. var args = protoSlice.call(arguments) if (args.length > 3 || arg2IsReactElement) { args[0] = componentType if (arg2IsReactElement) { args.splice(1, 0, finalProps || null) } else { args[1] = finalProps } return React.createElement.apply(React, args) } else { return React.createElement(componentType, finalProps, children) } } client.ParseError = ParseError return client }
javascript
function jsnox(React) { var client = function jsnoxClient(componentType, props, children) { // Special $renderIf prop allows you to conditionally render an element: //if (props && typeof props.$renderIf !== 'undefined') { if (props && typeof props === 'object' && props.hasOwnProperty('$renderIf')) { if (props.$renderIf) delete props.$renderIf // Don't pass down to components else return null } // Handle case where an array of children is given as the second argument: if (Array.isArray(props) || typeof props !== 'object') { children = props props = null } // Handle case where props object (second arg) is omitted var arg2IsReactElement = props && React.isValidElement(props) var finalProps = props if (typeof componentType === 'string' || !componentType) { // Parse the provided string into a hash of props // If componentType is invalid (undefined, empty string, etc), // parseTagSpec should throw. var spec = parseTagSpec(componentType) componentType = spec.tagName finalProps = arg2IsReactElement ? spec.props : extend(spec.props, props) } // If more than three args are given, assume args 3..n are ReactElement // children. You can also pass an array of children as the 3rd argument, // but in that case each child should have a unique key to avoid warnings. var args = protoSlice.call(arguments) if (args.length > 3 || arg2IsReactElement) { args[0] = componentType if (arg2IsReactElement) { args.splice(1, 0, finalProps || null) } else { args[1] = finalProps } return React.createElement.apply(React, args) } else { return React.createElement(componentType, finalProps, children) } } client.ParseError = ParseError return client }
[ "function", "jsnox", "(", "React", ")", "{", "var", "client", "=", "function", "jsnoxClient", "(", "componentType", ",", "props", ",", "children", ")", "{", "// Special $renderIf prop allows you to conditionally render an element:", "//if (props && typeof props.$renderIf !== ...
Main exported function. Returns a "client", which is a function that can be used to compose ReactElement trees directly.
[ "Main", "exported", "function", ".", "Returns", "a", "client", "which", "is", "a", "function", "that", "can", "be", "used", "to", "compose", "ReactElement", "trees", "directly", "." ]
95f26f9f5dc90fea3c55aa67a7d3f090b5cc430d
https://github.com/af/JSnoX/blob/95f26f9f5dc90fea3c55aa67a7d3f090b5cc430d/jsnox.js#L102-L148
30,134
tschortsch/gulp-bootlint
index.js
function(file, lint, isError, isWarning, errorLocation) { var lintId = (isError) ? colors.bgRed(colors.white(lint.id)) : colors.bgYellow(colors.white(lint.id)); var message = ''; if (errorLocation) { message = file.path + ':' + (errorLocation.line + 1) + ':' + (errorLocation.column + 1) + ' ' + lintId + ' ' + lint.message; } else { message = file.path + ': ' + lintId + ' ' + lint.message; } if (isError) { log.error(message); } else { log.warning(message); } }
javascript
function(file, lint, isError, isWarning, errorLocation) { var lintId = (isError) ? colors.bgRed(colors.white(lint.id)) : colors.bgYellow(colors.white(lint.id)); var message = ''; if (errorLocation) { message = file.path + ':' + (errorLocation.line + 1) + ':' + (errorLocation.column + 1) + ' ' + lintId + ' ' + lint.message; } else { message = file.path + ': ' + lintId + ' ' + lint.message; } if (isError) { log.error(message); } else { log.warning(message); } }
[ "function", "(", "file", ",", "lint", ",", "isError", ",", "isWarning", ",", "errorLocation", ")", "{", "var", "lintId", "=", "(", "isError", ")", "?", "colors", ".", "bgRed", "(", "colors", ".", "white", "(", "lint", ".", "id", ")", ")", ":", "col...
Reporter function for linting errors and warnings. @param file Current file object. @param lint Current linting error. @param isError True if this is an error. @param isWarning True if this is a warning. @param errorLocation Error location object.
[ "Reporter", "function", "for", "linting", "errors", "and", "warnings", "." ]
6469fd16a4624d6ef4218f1323283d238fea61e2
https://github.com/tschortsch/gulp-bootlint/blob/6469fd16a4624d6ef4218f1323283d238fea61e2/index.js#L34-L48
30,135
tschortsch/gulp-bootlint
index.js
function(file, errorCount, warningCount) { if (errorCount > 0 || warningCount > 0) { var message = ''; if (errorCount > 0) { message += colors.red(errorCount + ' lint ' + (errorCount === 1 ? 'error' : 'errors')); } if (warningCount > 0) { if (errorCount > 0) { message += ' and '; } message += colors.yellow(warningCount + ' lint ' + (warningCount === 1 ? 'warning' : 'warnings')); } message += ' found in file ' + file.path; log.notice(message); } else { log.info(colors.green(file.path + ' is lint free!')); } }
javascript
function(file, errorCount, warningCount) { if (errorCount > 0 || warningCount > 0) { var message = ''; if (errorCount > 0) { message += colors.red(errorCount + ' lint ' + (errorCount === 1 ? 'error' : 'errors')); } if (warningCount > 0) { if (errorCount > 0) { message += ' and '; } message += colors.yellow(warningCount + ' lint ' + (warningCount === 1 ? 'warning' : 'warnings')); } message += ' found in file ' + file.path; log.notice(message); } else { log.info(colors.green(file.path + ' is lint free!')); } }
[ "function", "(", "file", ",", "errorCount", ",", "warningCount", ")", "{", "if", "(", "errorCount", ">", "0", "||", "warningCount", ">", "0", ")", "{", "var", "message", "=", "''", ";", "if", "(", "errorCount", ">", "0", ")", "{", "message", "+=", ...
Reporter function for linting summary. @param file File which was linted. @param errorCount Total count of errors in file. @param warningCount Total count of warnings in file.
[ "Reporter", "function", "for", "linting", "summary", "." ]
6469fd16a4624d6ef4218f1323283d238fea61e2
https://github.com/tschortsch/gulp-bootlint/blob/6469fd16a4624d6ef4218f1323283d238fea61e2/index.js#L57-L75
30,136
cazala/mnist
src/mnist.js
shuffle
function shuffle(v) { for (var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x); return v; }
javascript
function shuffle(v) { for (var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x); return v; }
[ "function", "shuffle", "(", "v", ")", "{", "for", "(", "var", "j", ",", "x", ",", "i", "=", "v", ".", "length", ";", "i", ";", "j", "=", "parseInt", "(", "Math", ".", "random", "(", ")", "*", "i", ")", ",", "x", "=", "v", "[", "--", "i", ...
+ Jonas Raoni Soares Silva @ http://jsfromhell.com/array/shuffle [rev. #1]
[ "+", "Jonas", "Raoni", "Soares", "Silva" ]
76157793a26e2eed9313a6cde6ee60d8167a04fd
https://github.com/cazala/mnist/blob/76157793a26e2eed9313a6cde6ee60d8167a04fd/src/mnist.js#L190-L193
30,137
cssobj/cssobj
dist/cssobj.amd.js
_assign
function _assign (target, source) { var s, from, key; var to = Object(target); for (s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (key in from) { if (own(from, key)) { to[key] = from[key]; } } } return to }
javascript
function _assign (target, source) { var s, from, key; var to = Object(target); for (s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (key in from) { if (own(from, key)) { to[key] = from[key]; } } } return to }
[ "function", "_assign", "(", "target", ",", "source", ")", "{", "var", "s", ",", "from", ",", "key", ";", "var", "to", "=", "Object", "(", "target", ")", ";", "for", "(", "s", "=", "1", ";", "s", "<", "arguments", ".", "length", ";", "s", "++", ...
Object.assgin polyfill
[ "Object", ".", "assgin", "polyfill" ]
80f58c6fac72a0bbd9c1ba7c230d77be96909e1a
https://github.com/cssobj/cssobj/blob/80f58c6fac72a0bbd9c1ba7c230d77be96909e1a/dist/cssobj.amd.js#L45-L57
30,138
cssobj/cssobj
dist/cssobj.amd.js
splitSelector
function splitSelector (sel, splitter, inBracket) { if (sel.indexOf(splitter) < 0) return [sel] for (var c, i = 0, n = 0, instr = '', prev = 0, d = []; c = sel.charAt(i); i++) { if (instr) { if (c == instr && sel.charAt(i-1)!='\\') instr = ''; continue } if (c == '"' || c == '\'') instr = c; /* istanbul ignore if */ if(!inBracket){ if (c == '(' || c == '[') n++; if (c == ')' || c == ']') n--; } if (!n && c == splitter) d.push(sel.substring(prev, i)), prev = i + 1; } return d.concat(sel.substring(prev)) }
javascript
function splitSelector (sel, splitter, inBracket) { if (sel.indexOf(splitter) < 0) return [sel] for (var c, i = 0, n = 0, instr = '', prev = 0, d = []; c = sel.charAt(i); i++) { if (instr) { if (c == instr && sel.charAt(i-1)!='\\') instr = ''; continue } if (c == '"' || c == '\'') instr = c; /* istanbul ignore if */ if(!inBracket){ if (c == '(' || c == '[') n++; if (c == ')' || c == ']') n--; } if (!n && c == splitter) d.push(sel.substring(prev, i)), prev = i + 1; } return d.concat(sel.substring(prev)) }
[ "function", "splitSelector", "(", "sel", ",", "splitter", ",", "inBracket", ")", "{", "if", "(", "sel", ".", "indexOf", "(", "splitter", ")", "<", "0", ")", "return", "[", "sel", "]", "for", "(", "var", "c", ",", "i", "=", "0", ",", "n", "=", "...
split selector with splitter, aware of css attributes
[ "split", "selector", "with", "splitter", "aware", "of", "css", "attributes" ]
80f58c6fac72a0bbd9c1ba7c230d77be96909e1a
https://github.com/cssobj/cssobj/blob/80f58c6fac72a0bbd9c1ba7c230d77be96909e1a/dist/cssobj.amd.js#L162-L178
30,139
cssobj/cssobj
dist/cssobj.amd.js
isIterable
function isIterable (v) { return type.call(v) == OBJECT || type.call(v) == ARRAY }
javascript
function isIterable (v) { return type.call(v) == OBJECT || type.call(v) == ARRAY }
[ "function", "isIterable", "(", "v", ")", "{", "return", "type", ".", "call", "(", "v", ")", "==", "OBJECT", "||", "type", ".", "call", "(", "v", ")", "==", "ARRAY", "}" ]
only array, object now treated as iterable
[ "only", "array", "object", "now", "treated", "as", "iterable" ]
80f58c6fac72a0bbd9c1ba7c230d77be96909e1a
https://github.com/cssobj/cssobj/blob/80f58c6fac72a0bbd9c1ba7c230d77be96909e1a/dist/cssobj.amd.js#L202-L204
30,140
cssobj/cssobj
dist/cssobj.amd.js
createDOM
function createDOM (rootDoc, id, option) { var el = rootDoc.getElementById(id); var head = rootDoc.getElementsByTagName('head')[0]; if(el) { if(option.append) return el el.parentNode && el.parentNode.removeChild(el); } el = rootDoc.createElement('style'); head.appendChild(el); el.setAttribute('id', id); if (option.attrs) for (var i in option.attrs) { el.setAttribute(i, option.attrs[i]); } return el }
javascript
function createDOM (rootDoc, id, option) { var el = rootDoc.getElementById(id); var head = rootDoc.getElementsByTagName('head')[0]; if(el) { if(option.append) return el el.parentNode && el.parentNode.removeChild(el); } el = rootDoc.createElement('style'); head.appendChild(el); el.setAttribute('id', id); if (option.attrs) for (var i in option.attrs) { el.setAttribute(i, option.attrs[i]); } return el }
[ "function", "createDOM", "(", "rootDoc", ",", "id", ",", "option", ")", "{", "var", "el", "=", "rootDoc", ".", "getElementById", "(", "id", ")", ";", "var", "head", "=", "rootDoc", ".", "getElementsByTagName", "(", "'head'", ")", "[", "0", "]", ";", ...
plugin for cssobj
[ "plugin", "for", "cssobj" ]
80f58c6fac72a0bbd9c1ba7c230d77be96909e1a
https://github.com/cssobj/cssobj/blob/80f58c6fac72a0bbd9c1ba7c230d77be96909e1a/dist/cssobj.amd.js#L567-L582
30,141
cssobj/cssobj
dist/cssobj.amd.js
prefixProp
function prefixProp (name, inCSS) { // $prop will skip if(name[0]=='$') return '' // find name and cache the name for next time use var retName = cssProps[ name ] || ( cssProps[ name ] = vendorPropName( name ) || name); return inCSS // if hasPrefix in prop ? dashify(cssPrefixesReg.test(retName) ? capitalize(retName) : name=='float' && name || retName) // fix float in CSS, avoid return cssFloat : retName }
javascript
function prefixProp (name, inCSS) { // $prop will skip if(name[0]=='$') return '' // find name and cache the name for next time use var retName = cssProps[ name ] || ( cssProps[ name ] = vendorPropName( name ) || name); return inCSS // if hasPrefix in prop ? dashify(cssPrefixesReg.test(retName) ? capitalize(retName) : name=='float' && name || retName) // fix float in CSS, avoid return cssFloat : retName }
[ "function", "prefixProp", "(", "name", ",", "inCSS", ")", "{", "// $prop will skip", "if", "(", "name", "[", "0", "]", "==", "'$'", ")", "return", "''", "// find name and cache the name for next time use", "var", "retName", "=", "cssProps", "[", "name", "]", "...
apply prop to get right vendor prefix inCSS false=camelcase; true=dashed
[ "apply", "prop", "to", "get", "right", "vendor", "prefix", "inCSS", "false", "=", "camelcase", ";", "true", "=", "dashed" ]
80f58c6fac72a0bbd9c1ba7c230d77be96909e1a
https://github.com/cssobj/cssobj/blob/80f58c6fac72a0bbd9c1ba7c230d77be96909e1a/dist/cssobj.amd.js#L703-L712
30,142
cssobj/cssobj
dist/cssobj.amd.js
setCSSProperty
function setCSSProperty (styleObj, prop, val) { var value; var important = /^(.*)!(important)\s*$/i.exec(val); var propCamel = prefixProp(prop); var propDash = prefixProp(prop, true); if(important) { value = important[1]; important = important[2]; if(styleObj.setProperty) styleObj.setProperty(propDash, value, important); else { // for old IE, cssText is writable, and below is valid for contain !important // don't use styleObj.setAttribute since it's not set important // should do: delete styleObj[propCamel], but not affect result // only work on <= IE8: s.style['FONT-SIZE'] = '12px!important' styleObj[propDash.toUpperCase()] = val; // refresh cssText, the whole rule! styleObj.cssText = styleObj.cssText; } } else { styleObj[propCamel] = val; } }
javascript
function setCSSProperty (styleObj, prop, val) { var value; var important = /^(.*)!(important)\s*$/i.exec(val); var propCamel = prefixProp(prop); var propDash = prefixProp(prop, true); if(important) { value = important[1]; important = important[2]; if(styleObj.setProperty) styleObj.setProperty(propDash, value, important); else { // for old IE, cssText is writable, and below is valid for contain !important // don't use styleObj.setAttribute since it's not set important // should do: delete styleObj[propCamel], but not affect result // only work on <= IE8: s.style['FONT-SIZE'] = '12px!important' styleObj[propDash.toUpperCase()] = val; // refresh cssText, the whole rule! styleObj.cssText = styleObj.cssText; } } else { styleObj[propCamel] = val; } }
[ "function", "setCSSProperty", "(", "styleObj", ",", "prop", ",", "val", ")", "{", "var", "value", ";", "var", "important", "=", "/", "^(.*)!(important)\\s*$", "/", "i", ".", "exec", "(", "val", ")", ";", "var", "propCamel", "=", "prefixProp", "(", "prop"...
Get value and important flag from value str @param {CSSStyleRule} rule css style rule object @param {string} prop prop to set @param {string} val value string
[ "Get", "value", "and", "important", "flag", "from", "value", "str" ]
80f58c6fac72a0bbd9c1ba7c230d77be96909e1a
https://github.com/cssobj/cssobj/blob/80f58c6fac72a0bbd9c1ba7c230d77be96909e1a/dist/cssobj.amd.js#L720-L742
30,143
cssobj/cssobj
dist/cssobj.amd.js
function (node, selText, cssText) { if(!cssText) return // get parent to add var parent = getParent(node); var parentRule = node.parentRule; if (validParent(node)) return node.omRule = addCSSRule(parent, selText, cssText, node) else if (parentRule) { // for old IE not support @media, check mediaEnabled, add child nodes if (parentRule.mediaEnabled) { [].concat(node.omRule).forEach(removeOneRule); return node.omRule = addCSSRule(parent, selText, cssText, node) } else if (node.omRule) { node.omRule.forEach(removeOneRule); delete node.omRule; } } }
javascript
function (node, selText, cssText) { if(!cssText) return // get parent to add var parent = getParent(node); var parentRule = node.parentRule; if (validParent(node)) return node.omRule = addCSSRule(parent, selText, cssText, node) else if (parentRule) { // for old IE not support @media, check mediaEnabled, add child nodes if (parentRule.mediaEnabled) { [].concat(node.omRule).forEach(removeOneRule); return node.omRule = addCSSRule(parent, selText, cssText, node) } else if (node.omRule) { node.omRule.forEach(removeOneRule); delete node.omRule; } } }
[ "function", "(", "node", ",", "selText", ",", "cssText", ")", "{", "if", "(", "!", "cssText", ")", "return", "// get parent to add", "var", "parent", "=", "getParent", "(", "node", ")", ";", "var", "parentRule", "=", "node", ".", "parentRule", ";", "if",...
helper function for addNormalrule
[ "helper", "function", "for", "addNormalrule" ]
80f58c6fac72a0bbd9c1ba7c230d77be96909e1a
https://github.com/cssobj/cssobj/blob/80f58c6fac72a0bbd9c1ba7c230d77be96909e1a/dist/cssobj.amd.js#L825-L842
30,144
cssobj/cssobj
dist/cssobj.amd.js
cssobj$1
function cssobj$1 (obj, config, state) { config = config || {}; var local = config.local; config.local = !local ? {space: ''} : local && typeof local === 'object' ? local : {}; config.plugins = [].concat( config.plugins || [], cssobj_plugin_selector_localize(config.local), cssobj_plugin_post_cssom(config.cssom) ); return cssobj(config)(obj, state) }
javascript
function cssobj$1 (obj, config, state) { config = config || {}; var local = config.local; config.local = !local ? {space: ''} : local && typeof local === 'object' ? local : {}; config.plugins = [].concat( config.plugins || [], cssobj_plugin_selector_localize(config.local), cssobj_plugin_post_cssom(config.cssom) ); return cssobj(config)(obj, state) }
[ "function", "cssobj$1", "(", "obj", ",", "config", ",", "state", ")", "{", "config", "=", "config", "||", "{", "}", ";", "var", "local", "=", "config", ".", "local", ";", "config", ".", "local", "=", "!", "local", "?", "{", "space", ":", "''", "}...
cssobj is simply an intergration for cssobj-core, cssom
[ "cssobj", "is", "simply", "an", "intergration", "for", "cssobj", "-", "core", "cssom" ]
80f58c6fac72a0bbd9c1ba7c230d77be96909e1a
https://github.com/cssobj/cssobj/blob/80f58c6fac72a0bbd9c1ba7c230d77be96909e1a/dist/cssobj.amd.js#L1102-L1117
30,145
tnhu/jsface
jsface.pointcut.js
wrap
function wrap(fn, before, after, advisor) { var ignoredKeys = { prototype: 1 }; function wrapper() { var _before = wrapper[BEFORE], bLen = _before.length, _after = wrapper[AFTER], aLen = _after.length, _fn = wrapper[ORIGIN], ret, r; // Invoke before, if it returns { $skip: true } then skip fn() and after() and returns $data while (bLen--) { r = _before[bLen].apply(this, arguments); if (mapOrNil(r) && r.$skip === true) { return r.$data; } } // Invoke fn, save return value ret = _fn.apply(this, arguments); while (aLen--) { r = _after[aLen].apply(this, arguments); if (mapOrNil(r) && r.$skip === true) { return ret; } } return ret; } // wrapper exists? reuse it if (fn[WRAPPER] === fn) { fn[BEFORE].push(before); fn[AFTER].push(after); fn[ADVISOR].push(advisor); return fn; } // create a reusable wrapper structure extend(wrapper, fn, 0, true); if (classOrNil(fn)) { wrapper.prototype = fn.prototype; // this destroys the origin of wrapper[ORIGIN], in theory, prototype.constructor should point // to the class constructor itself, but it's no harm to not let that happen // wrapper.prototype.constructor = wrapper; } wrapper[BEFORE] = [ before ]; wrapper[AFTER] = [ after ]; wrapper[ORIGIN] = fn; wrapper[ADVISOR] = [ advisor ]; wrapper[WRAPPER] = wrapper; wrapper.$super = fn.$super; wrapper.$superp = fn.$superp; return wrapper; }
javascript
function wrap(fn, before, after, advisor) { var ignoredKeys = { prototype: 1 }; function wrapper() { var _before = wrapper[BEFORE], bLen = _before.length, _after = wrapper[AFTER], aLen = _after.length, _fn = wrapper[ORIGIN], ret, r; // Invoke before, if it returns { $skip: true } then skip fn() and after() and returns $data while (bLen--) { r = _before[bLen].apply(this, arguments); if (mapOrNil(r) && r.$skip === true) { return r.$data; } } // Invoke fn, save return value ret = _fn.apply(this, arguments); while (aLen--) { r = _after[aLen].apply(this, arguments); if (mapOrNil(r) && r.$skip === true) { return ret; } } return ret; } // wrapper exists? reuse it if (fn[WRAPPER] === fn) { fn[BEFORE].push(before); fn[AFTER].push(after); fn[ADVISOR].push(advisor); return fn; } // create a reusable wrapper structure extend(wrapper, fn, 0, true); if (classOrNil(fn)) { wrapper.prototype = fn.prototype; // this destroys the origin of wrapper[ORIGIN], in theory, prototype.constructor should point // to the class constructor itself, but it's no harm to not let that happen // wrapper.prototype.constructor = wrapper; } wrapper[BEFORE] = [ before ]; wrapper[AFTER] = [ after ]; wrapper[ORIGIN] = fn; wrapper[ADVISOR] = [ advisor ]; wrapper[WRAPPER] = wrapper; wrapper.$super = fn.$super; wrapper.$superp = fn.$superp; return wrapper; }
[ "function", "wrap", "(", "fn", ",", "before", ",", "after", ",", "advisor", ")", "{", "var", "ignoredKeys", "=", "{", "prototype", ":", "1", "}", ";", "function", "wrapper", "(", ")", "{", "var", "_before", "=", "wrapper", "[", "BEFORE", "]", ",", ...
Wrap a function with before & after.
[ "Wrap", "a", "function", "with", "before", "&", "after", "." ]
2949e282f01f5bcbe08dffb38044aef64413c24a
https://github.com/tnhu/jsface/blob/2949e282f01f5bcbe08dffb38044aef64413c24a/jsface.pointcut.js#L25-L82
30,146
tnhu/jsface
jsface.pointcut.js
restore
function restore(fn, advisor) { var origin, index, len; if (fn && fn === fn[WRAPPER]) { if ( !advisor) { origin = fn[ORIGIN]; delete fn[ORIGIN]; delete fn[ADVISOR]; delete fn[BEFORE]; delete fn[AFTER]; delete fn[WRAPPER]; } else { index = len = fn[ADVISOR].length; while (index--) { if (fn[ADVISOR][index] === advisor) { break; } } if (index >= 0) { if (len === 1) { return restore(fn); } fn[ADVISOR].splice(index, 1); fn[BEFORE].splice(index, 1); fn[AFTER].splice(index, 1); } } } return origin; }
javascript
function restore(fn, advisor) { var origin, index, len; if (fn && fn === fn[WRAPPER]) { if ( !advisor) { origin = fn[ORIGIN]; delete fn[ORIGIN]; delete fn[ADVISOR]; delete fn[BEFORE]; delete fn[AFTER]; delete fn[WRAPPER]; } else { index = len = fn[ADVISOR].length; while (index--) { if (fn[ADVISOR][index] === advisor) { break; } } if (index >= 0) { if (len === 1) { return restore(fn); } fn[ADVISOR].splice(index, 1); fn[BEFORE].splice(index, 1); fn[AFTER].splice(index, 1); } } } return origin; }
[ "function", "restore", "(", "fn", ",", "advisor", ")", "{", "var", "origin", ",", "index", ",", "len", ";", "if", "(", "fn", "&&", "fn", "===", "fn", "[", "WRAPPER", "]", ")", "{", "if", "(", "!", "advisor", ")", "{", "origin", "=", "fn", "[", ...
Restore a function to its origin state. @return function's origin state
[ "Restore", "a", "function", "to", "its", "origin", "state", "." ]
2949e282f01f5bcbe08dffb38044aef64413c24a
https://github.com/tnhu/jsface/blob/2949e282f01f5bcbe08dffb38044aef64413c24a/jsface.pointcut.js#L88-L113
30,147
tnhu/jsface
jsface.js
deepFreeze
function deepFreeze(object) { var prop, propKey; Object.freeze(object); // first freeze the object for (propKey in object) { prop = object[propKey]; if (!object.hasOwnProperty(propKey) || (typeof prop !== 'object') || Object.isFrozen(prop)) { // If the object is on the prototype, not an object, or is already frozen, // skip it. Note that this might leave an unfrozen reference somewhere in the // object if there is an already frozen object containing an unfrozen object. continue; } deepFreeze(prop); // recursively call deepFreeze } }
javascript
function deepFreeze(object) { var prop, propKey; Object.freeze(object); // first freeze the object for (propKey in object) { prop = object[propKey]; if (!object.hasOwnProperty(propKey) || (typeof prop !== 'object') || Object.isFrozen(prop)) { // If the object is on the prototype, not an object, or is already frozen, // skip it. Note that this might leave an unfrozen reference somewhere in the // object if there is an already frozen object containing an unfrozen object. continue; } deepFreeze(prop); // recursively call deepFreeze } }
[ "function", "deepFreeze", "(", "object", ")", "{", "var", "prop", ",", "propKey", ";", "Object", ".", "freeze", "(", "object", ")", ";", "// first freeze the object", "for", "(", "propKey", "in", "object", ")", "{", "prop", "=", "object", "[", "propKey", ...
To make object fully immutable, freeze each object inside it. @param object to deep freeze
[ "To", "make", "object", "fully", "immutable", "freeze", "each", "object", "inside", "it", "." ]
2949e282f01f5bcbe08dffb38044aef64413c24a
https://github.com/tnhu/jsface/blob/2949e282f01f5bcbe08dffb38044aef64413c24a/jsface.js#L89-L103
30,148
victorherraiz/cloud-config-client
index.js
getAuth
function getAuth (auth, url) { if (auth && auth.user && auth.pass) { return auth.user + ':' + auth.pass } return url.auth }
javascript
function getAuth (auth, url) { if (auth && auth.user && auth.pass) { return auth.user + ':' + auth.pass } return url.auth }
[ "function", "getAuth", "(", "auth", ",", "url", ")", "{", "if", "(", "auth", "&&", "auth", ".", "user", "&&", "auth", ".", "pass", ")", "{", "return", "auth", ".", "user", "+", "':'", "+", "auth", ".", "pass", "}", "return", "url", ".", "auth", ...
Handle load response @callback loadCallback @param {?Error} error - whether there was an error retrieving configurations @param {module:Config~Config} config - configuration object instance Retrieve basic auth from options Priority: 1. Defined in options 2. Coded as basic auth in url @param {module:CloudConfigClient~Auth} auth - auth configuration. @param {URL} url - endpoint. @returns {string} basic auth.
[ "Handle", "load", "response" ]
33d98bc419f014c94a49bd50abddc33aca858fc5
https://github.com/victorherraiz/cloud-config-client/blob/33d98bc419f014c94a49bd50abddc33aca858fc5/index.js#L55-L60
30,149
victorherraiz/cloud-config-client
index.js
getPath
function getPath (path, name, profiles, label) { const profilesStr = buildProfilesString(profiles) return (path.endsWith('/') ? path : path + '/') + encodeURIComponent(name) + '/' + encodeURIComponent(profilesStr) + (label ? '/' + encodeURIComponent(label) : '') }
javascript
function getPath (path, name, profiles, label) { const profilesStr = buildProfilesString(profiles) return (path.endsWith('/') ? path : path + '/') + encodeURIComponent(name) + '/' + encodeURIComponent(profilesStr) + (label ? '/' + encodeURIComponent(label) : '') }
[ "function", "getPath", "(", "path", ",", "name", ",", "profiles", ",", "label", ")", "{", "const", "profilesStr", "=", "buildProfilesString", "(", "profiles", ")", "return", "(", "path", ".", "endsWith", "(", "'/'", ")", "?", "path", ":", "path", "+", ...
Build spring config endpoint path @param {string} path - host base path @param {string} name - application name @param {(string|string[])} [profiles] - list of profiles, if none specified will use 'default' @param {string} [label] - environment id @returns {string} spring config endpoint
[ "Build", "spring", "config", "endpoint", "path" ]
33d98bc419f014c94a49bd50abddc33aca858fc5
https://github.com/victorherraiz/cloud-config-client/blob/33d98bc419f014c94a49bd50abddc33aca858fc5/index.js#L86-L93
30,150
victorherraiz/cloud-config-client
index.js
loadWithCallback
function loadWithCallback (options, callback) { const endpoint = options.endpoint ? URL.parse(options.endpoint) : DEFAULT_URL const name = options.name || options.application const context = options.context const client = endpoint.protocol === 'https:' ? https : http client.request({ protocol: endpoint.protocol, hostname: endpoint.hostname, port: endpoint.port, path: getPath(endpoint.path, name, options.profiles, options.label), auth: getAuth(options.auth, endpoint), rejectUnauthorized: options.rejectUnauthorized !== false, agent: options.agent }, (res) => { if (res.statusCode !== 200) { // OK res.resume() // it consumes response return callback(new Error('Invalid response: ' + res.statusCode)) } let response = '' res.setEncoding('utf8') res.on('data', (data) => { response += data }) res.on('end', () => { try { const body = JSON.parse(response) callback(null, new Config(body, context)) } catch (e) { callback(e) } }) }).on('error', callback).end() }
javascript
function loadWithCallback (options, callback) { const endpoint = options.endpoint ? URL.parse(options.endpoint) : DEFAULT_URL const name = options.name || options.application const context = options.context const client = endpoint.protocol === 'https:' ? https : http client.request({ protocol: endpoint.protocol, hostname: endpoint.hostname, port: endpoint.port, path: getPath(endpoint.path, name, options.profiles, options.label), auth: getAuth(options.auth, endpoint), rejectUnauthorized: options.rejectUnauthorized !== false, agent: options.agent }, (res) => { if (res.statusCode !== 200) { // OK res.resume() // it consumes response return callback(new Error('Invalid response: ' + res.statusCode)) } let response = '' res.setEncoding('utf8') res.on('data', (data) => { response += data }) res.on('end', () => { try { const body = JSON.parse(response) callback(null, new Config(body, context)) } catch (e) { callback(e) } }) }).on('error', callback).end() }
[ "function", "loadWithCallback", "(", "options", ",", "callback", ")", "{", "const", "endpoint", "=", "options", ".", "endpoint", "?", "URL", ".", "parse", "(", "options", ".", "endpoint", ")", ":", "DEFAULT_URL", "const", "name", "=", "options", ".", "name...
Load configuration with callback @param {module:CloudConfigClient~Options} options - spring client configuration options @param {module:CloudConfigClient~loadCallback} [callback] - load callback
[ "Load", "configuration", "with", "callback" ]
33d98bc419f014c94a49bd50abddc33aca858fc5
https://github.com/victorherraiz/cloud-config-client/blob/33d98bc419f014c94a49bd50abddc33aca858fc5/index.js#L101-L134
30,151
victorherraiz/cloud-config-client
index.js
loadWithPromise
function loadWithPromise (options) { return new Promise((resolve, reject) => { loadWithCallback(options, (error, config) => { if (error) { reject(error) } else { resolve(config) } }) }) }
javascript
function loadWithPromise (options) { return new Promise((resolve, reject) => { loadWithCallback(options, (error, config) => { if (error) { reject(error) } else { resolve(config) } }) }) }
[ "function", "loadWithPromise", "(", "options", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "loadWithCallback", "(", "options", ",", "(", "error", ",", "config", ")", "=>", "{", "if", "(", "error", ")", "{",...
Wrap loadWithCallback with Promise @param {module:CloudConfigClient~Options} options - spring client configuration options @returns {Promise<module:Config~Config, Error>} promise handler
[ "Wrap", "loadWithCallback", "with", "Promise" ]
33d98bc419f014c94a49bd50abddc33aca858fc5
https://github.com/victorherraiz/cloud-config-client/blob/33d98bc419f014c94a49bd50abddc33aca858fc5/index.js#L142-L152
30,152
SvSchmidt/linqjs
dist/linq.system.es5.js
_MinHeap
function _MinHeap(elements) { var comparator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultComparator; _classCallCheck(this, _MinHeap); __assertArray(elements); __assertFunction(comparator); // we do not wrap elements here since the heapify function does that the moment it encounters elements this.__elements = elements; // create comparator that works on heap elements (it also ensures equal elements remain in original order) this.__comparator = function (a, b) { var res = comparator(a.__value, b.__value); if (res !== 0) { return res; } return defaultComparator(a.__index, b.__index); }; // create heap ordering this.__createHeap(this.__elements, this.__comparator); }
javascript
function _MinHeap(elements) { var comparator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultComparator; _classCallCheck(this, _MinHeap); __assertArray(elements); __assertFunction(comparator); // we do not wrap elements here since the heapify function does that the moment it encounters elements this.__elements = elements; // create comparator that works on heap elements (it also ensures equal elements remain in original order) this.__comparator = function (a, b) { var res = comparator(a.__value, b.__value); if (res !== 0) { return res; } return defaultComparator(a.__index, b.__index); }; // create heap ordering this.__createHeap(this.__elements, this.__comparator); }
[ "function", "_MinHeap", "(", "elements", ")", "{", "var", "comparator", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "defaultComparator", ";", "_classCallCheck", "(",...
Creates the heap from the array of elements with the given comparator function. @param elements Array with elements to create the heap from. Will be modified in place for heap logic. @param comparator Comparator function (same as the one for Array.sort()).
[ "Creates", "the", "heap", "from", "the", "array", "of", "elements", "with", "the", "given", "comparator", "function", "." ]
e89561cd9c5d3f9f0b689711872d499b2b1a1e5a
https://github.com/SvSchmidt/linqjs/blob/e89561cd9c5d3f9f0b689711872d499b2b1a1e5a/dist/linq.system.es5.js#L2911-L2930
30,153
Bartvds/joi-assert
lib/index.js
assert
function assert(value, schema, message, vars) { return assertion(value, schema, message, vars, (internals.debug ? null : assert)); }
javascript
function assert(value, schema, message, vars) { return assertion(value, schema, message, vars, (internals.debug ? null : assert)); }
[ "function", "assert", "(", "value", ",", "schema", ",", "message", ",", "vars", ")", "{", "return", "assertion", "(", "value", ",", "schema", ",", "message", ",", "vars", ",", "(", "internals", ".", "debug", "?", "null", ":", "assert", ")", ")", ";",...
export API core assertion method
[ "export", "API", "core", "assertion", "method" ]
a4a920ad79a9b40ae38437244a5915e6cb76f3b3
https://github.com/Bartvds/joi-assert/blob/a4a920ad79a9b40ae38437244a5915e6cb76f3b3/lib/index.js#L8-L10
30,154
flohil/wdio-workflo
dist/lib/helpers.js
tolerancesToString
function tolerancesToString(values, tolerances) { let str = '{'; const props = []; if (typeof values !== 'object' && typeof values !== 'undefined') { if (typeof tolerances === 'undefined') { return values; } else if (typeof tolerances !== 'object') { const tolerance = Math.abs(tolerances); return `[${Math.max(values - tolerance, 0)}, ${Math.max(values + tolerance, 0)}]`; } } else { for (const p in values) { if (values.hasOwnProperty(p)) { const value = values[p]; let valueStr = ''; if (tolerances && typeof tolerances[p] !== 'undefined' && tolerances[p] !== 0) { const tolerance = Math.abs(tolerances[p]); valueStr = `[${Math.max(value - tolerance, 0)}, ${Math.max(value + tolerance, 0)}]`; } else { valueStr = `${value}`; } props.push(`${p}: ${valueStr}`); } } } str += props.join(', '); return `${str}}`; }
javascript
function tolerancesToString(values, tolerances) { let str = '{'; const props = []; if (typeof values !== 'object' && typeof values !== 'undefined') { if (typeof tolerances === 'undefined') { return values; } else if (typeof tolerances !== 'object') { const tolerance = Math.abs(tolerances); return `[${Math.max(values - tolerance, 0)}, ${Math.max(values + tolerance, 0)}]`; } } else { for (const p in values) { if (values.hasOwnProperty(p)) { const value = values[p]; let valueStr = ''; if (tolerances && typeof tolerances[p] !== 'undefined' && tolerances[p] !== 0) { const tolerance = Math.abs(tolerances[p]); valueStr = `[${Math.max(value - tolerance, 0)}, ${Math.max(value + tolerance, 0)}]`; } else { valueStr = `${value}`; } props.push(`${p}: ${valueStr}`); } } } str += props.join(', '); return `${str}}`; }
[ "function", "tolerancesToString", "(", "values", ",", "tolerances", ")", "{", "let", "str", "=", "'{'", ";", "const", "props", "=", "[", "]", ";", "if", "(", "typeof", "values", "!==", "'object'", "&&", "typeof", "values", "!==", "'undefined'", ")", "{",...
Prints values with tolerances as a string. @param values a number or an object with values of type number @param tolerances a number or an object with values of type number
[ "Prints", "values", "with", "tolerances", "as", "a", "string", "." ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/helpers.js#L9-L39
30,155
SvSchmidt/linqjs
dist/linq.es6.js
isKeyComparator
function isKeyComparator(arg) { let result = __getParameterCount(arg) === 2; const first = self.first(); try { const key = keySelector(first); // if this is a key comparator, it must return truthy values for equal values and falsy ones if they're different result = result && arg(key, key) && !arg(key, {}); } catch (err) { // if the function throws an error for values, it can't be a keyComparator result = false; } return result; }
javascript
function isKeyComparator(arg) { let result = __getParameterCount(arg) === 2; const first = self.first(); try { const key = keySelector(first); // if this is a key comparator, it must return truthy values for equal values and falsy ones if they're different result = result && arg(key, key) && !arg(key, {}); } catch (err) { // if the function throws an error for values, it can't be a keyComparator result = false; } return result; }
[ "function", "isKeyComparator", "(", "arg", ")", "{", "let", "result", "=", "__getParameterCount", "(", "arg", ")", "===", "2", ";", "const", "first", "=", "self", ".", "first", "(", ")", ";", "try", "{", "const", "key", "=", "keySelector", "(", "first"...
Checks whether or not a function is a key comparator. We need to differentiate between the key comparator and the result selector since both take two arguments. @param arg Function to be tested. @return If the given function is a key comparator.
[ "Checks", "whether", "or", "not", "a", "function", "is", "a", "key", "comparator", ".", "We", "need", "to", "differentiate", "between", "the", "key", "comparator", "and", "the", "result", "selector", "since", "both", "take", "two", "arguments", "." ]
e89561cd9c5d3f9f0b689711872d499b2b1a1e5a
https://github.com/SvSchmidt/linqjs/blob/e89561cd9c5d3f9f0b689711872d499b2b1a1e5a/dist/linq.es6.js#L559-L572
30,156
novacrazy/bluebird-co
src/yield_handler.js
processThunkArgs
function processThunkArgs( args ) { let length = args.length | 0; if( length >= 3 ) { let res = new Array( --length ); for( let i = 0; i < length; ) { res[i] = args[++i]; //It's a good thing this isn't undefined behavior in JavaScript } return res; } return args[1]; }
javascript
function processThunkArgs( args ) { let length = args.length | 0; if( length >= 3 ) { let res = new Array( --length ); for( let i = 0; i < length; ) { res[i] = args[++i]; //It's a good thing this isn't undefined behavior in JavaScript } return res; } return args[1]; }
[ "function", "processThunkArgs", "(", "args", ")", "{", "let", "length", "=", "args", ".", "length", "|", "0", ";", "if", "(", "length", ">=", "3", ")", "{", "let", "res", "=", "new", "Array", "(", "--", "length", ")", ";", "for", "(", "let", "i",...
This is separated out so it can be optimized independently to the calling function.
[ "This", "is", "separated", "out", "so", "it", "can", "be", "optimized", "independently", "to", "the", "calling", "function", "." ]
0f98755d326b99f8e3968308e4be43041ec5fde7
https://github.com/novacrazy/bluebird-co/blob/0f98755d326b99f8e3968308e4be43041ec5fde7/src/yield_handler.js#L174-L188
30,157
mikolalysenko/planar-graph-to-polyline
pg2pl.js
ccw
function ccw(c) { var n = c.length var area = [0] for(var j=0; j<n; ++j) { var a = positions[c[j]] var b = positions[c[(j+1)%n]] var t00 = twoProduct(-a[0], a[1]) var t01 = twoProduct(-a[0], b[1]) var t10 = twoProduct( b[0], a[1]) var t11 = twoProduct( b[0], b[1]) area = robustSum(area, robustSum(robustSum(t00, t01), robustSum(t10, t11))) } return area[area.length-1] > 0 }
javascript
function ccw(c) { var n = c.length var area = [0] for(var j=0; j<n; ++j) { var a = positions[c[j]] var b = positions[c[(j+1)%n]] var t00 = twoProduct(-a[0], a[1]) var t01 = twoProduct(-a[0], b[1]) var t10 = twoProduct( b[0], a[1]) var t11 = twoProduct( b[0], b[1]) area = robustSum(area, robustSum(robustSum(t00, t01), robustSum(t10, t11))) } return area[area.length-1] > 0 }
[ "function", "ccw", "(", "c", ")", "{", "var", "n", "=", "c", ".", "length", "var", "area", "=", "[", "0", "]", "for", "(", "var", "j", "=", "0", ";", "j", "<", "n", ";", "++", "j", ")", "{", "var", "a", "=", "positions", "[", "c", "[", ...
Check orientation of a polygon using exact arithmetic
[ "Check", "orientation", "of", "a", "polygon", "using", "exact", "arithmetic" ]
078192fd8c09bff5151a1db2c06a77c12cdc5554
https://github.com/mikolalysenko/planar-graph-to-polyline/blob/078192fd8c09bff5151a1db2c06a77c12cdc5554/pg2pl.js#L52-L65
30,158
ditesh/node-mbox
main.js
syncToTmp
function syncToTmp(tmpfd, msgnumber, cb) { // Pass the last msg if (msgnumber > messages.offsets.length) cb(); // Skip deleted messages else if (messages.offsets[msgnumber] === undefined) syncToTmp(tmpfd, msgnumber + 1, cb); else { var buffer = new Buffer(omessages.sizes[msgnumber]); fs.read(fd, buffer, 0, omessages.sizes[msgnumber], messages.offsets[msgnumber], function(err, bytesRead, buffer) { fs.write(tmpfd, buffer, 0, bytesRead, null, function(err, written, buffer) { syncToTmp(tmpfd, msgnumber + 1, cb); }); }); } }
javascript
function syncToTmp(tmpfd, msgnumber, cb) { // Pass the last msg if (msgnumber > messages.offsets.length) cb(); // Skip deleted messages else if (messages.offsets[msgnumber] === undefined) syncToTmp(tmpfd, msgnumber + 1, cb); else { var buffer = new Buffer(omessages.sizes[msgnumber]); fs.read(fd, buffer, 0, omessages.sizes[msgnumber], messages.offsets[msgnumber], function(err, bytesRead, buffer) { fs.write(tmpfd, buffer, 0, bytesRead, null, function(err, written, buffer) { syncToTmp(tmpfd, msgnumber + 1, cb); }); }); } }
[ "function", "syncToTmp", "(", "tmpfd", ",", "msgnumber", ",", "cb", ")", "{", "// Pass the last msg", "if", "(", "msgnumber", ">", "messages", ".", "offsets", ".", "length", ")", "cb", "(", ")", ";", "// Skip deleted messages", "else", "if", "(", "messages",...
Private methods follow Write modifications to temp file
[ "Private", "methods", "follow", "Write", "modifications", "to", "temp", "file" ]
85f6ad33e2f88fa55ffca6b47cc97e149d827a1e
https://github.com/ditesh/node-mbox/blob/85f6ad33e2f88fa55ffca6b47cc97e149d827a1e/main.js#L158-L178
30,159
flohil/wdio-workflo
dist/lib/page_objects/page_elements/PageElementGroup.js
isIElementNode
function isIElementNode(node) { return typeof node['getText'] === 'function' && typeof node.currently['hasText'] === 'function' && typeof node.currently['hasAnyText'] === 'function' && typeof node.currently['containsText'] === 'function' && typeof node.wait['hasText'] === 'function' && typeof node.wait['hasAnyText'] === 'function' && typeof node.wait['containsText'] === 'function' && typeof node.eventually['hasText'] === 'function' && typeof node.eventually['hasAnyText'] === 'function' && typeof node.eventually['containsText'] === 'function' && typeof node['getDirectText'] === 'function' && typeof node.currently['hasDirectText'] === 'function' && typeof node.currently['hasAnyDirectText'] === 'function' && typeof node.currently['containsDirectText'] === 'function' && typeof node.wait['hasDirectText'] === 'function' && typeof node.wait['hasAnyDirectText'] === 'function' && typeof node.wait['containsDirectText'] === 'function' && typeof node.eventually['hasDirectText'] === 'function' && typeof node.eventually['hasAnyDirectText'] === 'function' && typeof node.eventually['containsDirectText'] === 'function'; }
javascript
function isIElementNode(node) { return typeof node['getText'] === 'function' && typeof node.currently['hasText'] === 'function' && typeof node.currently['hasAnyText'] === 'function' && typeof node.currently['containsText'] === 'function' && typeof node.wait['hasText'] === 'function' && typeof node.wait['hasAnyText'] === 'function' && typeof node.wait['containsText'] === 'function' && typeof node.eventually['hasText'] === 'function' && typeof node.eventually['hasAnyText'] === 'function' && typeof node.eventually['containsText'] === 'function' && typeof node['getDirectText'] === 'function' && typeof node.currently['hasDirectText'] === 'function' && typeof node.currently['hasAnyDirectText'] === 'function' && typeof node.currently['containsDirectText'] === 'function' && typeof node.wait['hasDirectText'] === 'function' && typeof node.wait['hasAnyDirectText'] === 'function' && typeof node.wait['containsDirectText'] === 'function' && typeof node.eventually['hasDirectText'] === 'function' && typeof node.eventually['hasAnyDirectText'] === 'function' && typeof node.eventually['containsDirectText'] === 'function'; }
[ "function", "isIElementNode", "(", "node", ")", "{", "return", "typeof", "node", "[", "'getText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "currently", "[", "'hasText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "currently", "[", ...
type guards Returns true if the passed node supports all functions defined in IElementNode. @param node a PageNode
[ "type", "guards", "Returns", "true", "if", "the", "passed", "node", "supports", "all", "functions", "defined", "in", "IElementNode", "." ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/page_objects/page_elements/PageElementGroup.js#L1358-L1379
30,160
emmetio/markup-formatters
format/haml.js
updateFormatting
function updateFormatting(outNode, profile) { const node = outNode.node; if (!node.isTextOnly && node.value) { // node with text: put a space before single-line text outNode.beforeText = reNl.test(node.value) ? outNode.newline + outNode.indent + profile.indent(1) : ' '; } return outNode; }
javascript
function updateFormatting(outNode, profile) { const node = outNode.node; if (!node.isTextOnly && node.value) { // node with text: put a space before single-line text outNode.beforeText = reNl.test(node.value) ? outNode.newline + outNode.indent + profile.indent(1) : ' '; } return outNode; }
[ "function", "updateFormatting", "(", "outNode", ",", "profile", ")", "{", "const", "node", "=", "outNode", ".", "node", ";", "if", "(", "!", "node", ".", "isTextOnly", "&&", "node", ".", "value", ")", "{", "// node with text: put a space before single-line text"...
Updates formatting properties for given output node NB Unlike HTML, HAML is indent-based format so some formatting options from `profile` will not take effect, otherwise output will be broken @param {OutputNode} outNode Output wrapper of parsed abbreviation node @param {Profile} profile Output profile @return {OutputNode}
[ "Updates", "formatting", "properties", "for", "given", "output", "node", "NB", "Unlike", "HTML", "HAML", "is", "indent", "-", "based", "format", "so", "some", "formatting", "options", "from", "profile", "will", "not", "take", "effect", "otherwise", "output", "...
a9f93994fa5cb6aef6b0148b9ec485846fb4a338
https://github.com/emmetio/markup-formatters/blob/a9f93994fa5cb6aef6b0148b9ec485846fb4a338/format/haml.js#L58-L69
30,161
flohil/wdio-workflo
config/wdio.conf.js
function (commandName, args, result, error) { if (error) { if ( error.type ) { errorType = error.type } else if ( error.toString().indexOf("Error: An element could not be located on the page using the given search parameters") > -1 ) { errorType = true } try { const screenshot = browser.saveScreenshot() // returns base64 string buffer const screenshotFolder = path.join(process.env.WDIO_WORKFLO_RUN_PATH, 'allure-results') const screenshotFilename = `${screenshotFolder}/${global.screenshotId}.png` global.errorScreenshotFilename = screenshotFilename fs.writeFileSync(screenshotFilename, screenshot) } catch (err) { console.log(`Failed to take screenshot: ${err.message}`) console.log(err.stack) } } if (typeof workfloConf.afterCommand === 'function') { return workfloConf.afterCommand(commandName, args, result, error) } }
javascript
function (commandName, args, result, error) { if (error) { if ( error.type ) { errorType = error.type } else if ( error.toString().indexOf("Error: An element could not be located on the page using the given search parameters") > -1 ) { errorType = true } try { const screenshot = browser.saveScreenshot() // returns base64 string buffer const screenshotFolder = path.join(process.env.WDIO_WORKFLO_RUN_PATH, 'allure-results') const screenshotFilename = `${screenshotFolder}/${global.screenshotId}.png` global.errorScreenshotFilename = screenshotFilename fs.writeFileSync(screenshotFilename, screenshot) } catch (err) { console.log(`Failed to take screenshot: ${err.message}`) console.log(err.stack) } } if (typeof workfloConf.afterCommand === 'function') { return workfloConf.afterCommand(commandName, args, result, error) } }
[ "function", "(", "commandName", ",", "args", ",", "result", ",", "error", ")", "{", "if", "(", "error", ")", "{", "if", "(", "error", ".", "type", ")", "{", "errorType", "=", "error", ".", "type", "}", "else", "if", "(", "error", ".", "toString", ...
Runs after a WebdriverIO command gets executed
[ "Runs", "after", "a", "WebdriverIO", "command", "gets", "executed" ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/config/wdio.conf.js#L267-L293
30,162
canjs/worker-render
src/simple_extend.js
extend
function extend(a, b){ var p, type; for(p in b) { type = typeof b[p]; if(type !== "object" && type !== "function") { a[p] = b[p]; } } return a; }
javascript
function extend(a, b){ var p, type; for(p in b) { type = typeof b[p]; if(type !== "object" && type !== "function") { a[p] = b[p]; } } return a; }
[ "function", "extend", "(", "a", ",", "b", ")", "{", "var", "p", ",", "type", ";", "for", "(", "p", "in", "b", ")", "{", "type", "=", "typeof", "b", "[", "p", "]", ";", "if", "(", "type", "!==", "\"object\"", "&&", "type", "!==", "\"function\"",...
A simple extend that doesn't go deep
[ "A", "simple", "extend", "that", "doesn", "t", "go", "deep" ]
e36dbb886a8453bd9e4d4fc9f73a4bc84146d6e5
https://github.com/canjs/worker-render/blob/e36dbb886a8453bd9e4d4fc9f73a4bc84146d6e5/src/simple_extend.js#L4-L13
30,163
flohil/wdio-workflo
dist/lib/cli.js
completeSpecFiles
function completeSpecFiles(argv, _filters) { // if user manually defined an empty specFiles array, do not add specFiles from folder if (Object.keys(_filters.specFiles).length === 0 && !argv.specFiles) { io_1.getAllFiles(specsDir, '.spec.ts').forEach(specFile => _filters.specFiles[specFile] = true); return true; } else { let removeOnly = true; const removeSpecFiles = {}; for (const specFile in _filters.specFiles) { let remove = false; let matchStr = specFile; if (specFile.substr(0, 1) === '-') { remove = true; matchStr = specFile.substr(1, specFile.length - 1); } else { removeOnly = false; } if (remove) { delete _filters.specFiles[specFile]; removeSpecFiles[matchStr] = true; } } if (removeOnly) { io_1.getAllFiles(specsDir, '.spec.ts') .filter(specFile => !(specFile in removeSpecFiles)) .forEach(specFile => _filters.specFiles[specFile] = true); } } return false; }
javascript
function completeSpecFiles(argv, _filters) { // if user manually defined an empty specFiles array, do not add specFiles from folder if (Object.keys(_filters.specFiles).length === 0 && !argv.specFiles) { io_1.getAllFiles(specsDir, '.spec.ts').forEach(specFile => _filters.specFiles[specFile] = true); return true; } else { let removeOnly = true; const removeSpecFiles = {}; for (const specFile in _filters.specFiles) { let remove = false; let matchStr = specFile; if (specFile.substr(0, 1) === '-') { remove = true; matchStr = specFile.substr(1, specFile.length - 1); } else { removeOnly = false; } if (remove) { delete _filters.specFiles[specFile]; removeSpecFiles[matchStr] = true; } } if (removeOnly) { io_1.getAllFiles(specsDir, '.spec.ts') .filter(specFile => !(specFile in removeSpecFiles)) .forEach(specFile => _filters.specFiles[specFile] = true); } } return false; }
[ "function", "completeSpecFiles", "(", "argv", ",", "_filters", ")", "{", "// if user manually defined an empty specFiles array, do not add specFiles from folder", "if", "(", "Object", ".", "keys", "(", "_filters", ".", "specFiles", ")", ".", "length", "===", "0", "&&", ...
if no spec files are present in filters, use all spec files in specs folder
[ "if", "no", "spec", "files", "are", "present", "in", "filters", "use", "all", "spec", "files", "in", "specs", "folder" ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/cli.js#L735-L766
30,164
flohil/wdio-workflo
dist/lib/cli.js
mergeLists
function mergeLists(list, _filters) { if (list.specFiles) { list.specFiles.forEach(value => _filters.specFiles[value] = true); } if (list.testcaseFiles) { list.testcaseFiles.forEach(value => _filters.testcaseFiles[value] = true); } if (list.features) { list.features.forEach(value => _filters.features[value] = true); } if (list.specs) { list.specs.forEach(value => _filters.specs[value] = true); } if (list.testcases) { list.testcases.forEach(value => _filters.testcases[value] = true); } if (list.listFiles) { for (const listFile of list.listFiles) { // complete cli listFiles paths const listFilePath = path.join(listsDir, `${listFile}.list.ts`); if (!fs.existsSync(listFilePath)) { throw new Error(`List file could not be found: ${listFilePath}`); } else { const sublist = require(listFilePath).default; // recursively traverse sub list files mergeLists(sublist, _filters); } } } }
javascript
function mergeLists(list, _filters) { if (list.specFiles) { list.specFiles.forEach(value => _filters.specFiles[value] = true); } if (list.testcaseFiles) { list.testcaseFiles.forEach(value => _filters.testcaseFiles[value] = true); } if (list.features) { list.features.forEach(value => _filters.features[value] = true); } if (list.specs) { list.specs.forEach(value => _filters.specs[value] = true); } if (list.testcases) { list.testcases.forEach(value => _filters.testcases[value] = true); } if (list.listFiles) { for (const listFile of list.listFiles) { // complete cli listFiles paths const listFilePath = path.join(listsDir, `${listFile}.list.ts`); if (!fs.existsSync(listFilePath)) { throw new Error(`List file could not be found: ${listFilePath}`); } else { const sublist = require(listFilePath).default; // recursively traverse sub list files mergeLists(sublist, _filters); } } } }
[ "function", "mergeLists", "(", "list", ",", "_filters", ")", "{", "if", "(", "list", ".", "specFiles", ")", "{", "list", ".", "specFiles", ".", "forEach", "(", "value", "=>", "_filters", ".", "specFiles", "[", "value", "]", "=", "true", ")", ";", "}"...
Loads all specFiles, testcaseFiles, features, specs and testcases defined in lists and sublists of argv.listFiles @param argv
[ "Loads", "all", "specFiles", "testcaseFiles", "features", "specs", "and", "testcases", "defined", "in", "lists", "and", "sublists", "of", "argv", ".", "listFiles" ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/cli.js#L830-L860
30,165
flohil/wdio-workflo
dist/lib/cli.js
addFeatures
function addFeatures() { const features = {}; for (const spec in filters.specs) { features[parseResults.specs.specTable[spec].feature] = true; } filters.features = features; }
javascript
function addFeatures() { const features = {}; for (const spec in filters.specs) { features[parseResults.specs.specTable[spec].feature] = true; } filters.features = features; }
[ "function", "addFeatures", "(", ")", "{", "const", "features", "=", "{", "}", ";", "for", "(", "const", "spec", "in", "filters", ".", "specs", ")", "{", "features", "[", "parseResults", ".", "specs", ".", "specTable", "[", "spec", "]", ".", "feature", ...
adds features to filters based on current content of filters.specs
[ "adds", "features", "to", "filters", "based", "on", "current", "content", "of", "filters", ".", "specs" ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/cli.js#L1457-L1463
30,166
flohil/wdio-workflo
dist/lib/cli.js
addSpecFiles
function addSpecFiles() { const specFiles = {}; for (const spec in filters.specs) { specFiles[parseResults.specs.specTable[spec].specFile] = true; } filters.specFiles = specFiles; }
javascript
function addSpecFiles() { const specFiles = {}; for (const spec in filters.specs) { specFiles[parseResults.specs.specTable[spec].specFile] = true; } filters.specFiles = specFiles; }
[ "function", "addSpecFiles", "(", ")", "{", "const", "specFiles", "=", "{", "}", ";", "for", "(", "const", "spec", "in", "filters", ".", "specs", ")", "{", "specFiles", "[", "parseResults", ".", "specs", ".", "specTable", "[", "spec", "]", ".", "specFil...
adds spec files to filters based on current content of filters.specFiles
[ "adds", "spec", "files", "to", "filters", "based", "on", "current", "content", "of", "filters", ".", "specFiles" ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/cli.js#L1465-L1471
30,167
flohil/wdio-workflo
dist/lib/cli.js
cleanResultsStatus
function cleanResultsStatus() { // remove criterias and spec if no criteria in spec for (const spec in mergedResults.specs) { if (!(spec in parseResults.specs.specTable) || Object.keys(parseResults.specs.specTable[spec].criteria).length === 0) { delete mergedResults.specs[spec]; } else { const parsedCriteria = parseResults.specs.specTable[spec].criteria; const resultsCriteria = mergedResults.specs[spec]; for (const criteria in resultsCriteria) { if (!(criteria in parsedCriteria)) { delete mergedResults.specs[spec][criteria]; } } } } for (const testcase in mergedResults.testcases) { if (!(testcase in parseResults.testcases.testcaseTable)) { delete mergedResults.testcases[testcase]; } } // add criteria for (const spec in parseResults.specs.specTable) { if (!(spec in mergedResults.specs)) { mergedResults.specs[spec] = {}; } const parsedCriteria = parseResults.specs.specTable[spec].criteria; const resultsCriteria = mergedResults.specs[spec]; for (const criteria in parsedCriteria) { if (!(criteria in resultsCriteria)) { mergedResults.specs[spec][criteria] = { dateTime, status: 'unknown', resultsFolder: undefined, }; if (criteria in criteriaAnalysis.specs[spec].manual) { mergedResults.specs[spec][criteria].manual = true; } } } } for (const testcase in parseResults.testcases.testcaseTable) { if (!(testcase in mergedResults.testcases)) { mergedResults.testcases[testcase] = { dateTime, status: 'unknown', resultsFolder: undefined, }; } } fs.writeFileSync(mergedResultsPath, JSON.stringify(mergedResults), { encoding: 'utf8' }); }
javascript
function cleanResultsStatus() { // remove criterias and spec if no criteria in spec for (const spec in mergedResults.specs) { if (!(spec in parseResults.specs.specTable) || Object.keys(parseResults.specs.specTable[spec].criteria).length === 0) { delete mergedResults.specs[spec]; } else { const parsedCriteria = parseResults.specs.specTable[spec].criteria; const resultsCriteria = mergedResults.specs[spec]; for (const criteria in resultsCriteria) { if (!(criteria in parsedCriteria)) { delete mergedResults.specs[spec][criteria]; } } } } for (const testcase in mergedResults.testcases) { if (!(testcase in parseResults.testcases.testcaseTable)) { delete mergedResults.testcases[testcase]; } } // add criteria for (const spec in parseResults.specs.specTable) { if (!(spec in mergedResults.specs)) { mergedResults.specs[spec] = {}; } const parsedCriteria = parseResults.specs.specTable[spec].criteria; const resultsCriteria = mergedResults.specs[spec]; for (const criteria in parsedCriteria) { if (!(criteria in resultsCriteria)) { mergedResults.specs[spec][criteria] = { dateTime, status: 'unknown', resultsFolder: undefined, }; if (criteria in criteriaAnalysis.specs[spec].manual) { mergedResults.specs[spec][criteria].manual = true; } } } } for (const testcase in parseResults.testcases.testcaseTable) { if (!(testcase in mergedResults.testcases)) { mergedResults.testcases[testcase] = { dateTime, status: 'unknown', resultsFolder: undefined, }; } } fs.writeFileSync(mergedResultsPath, JSON.stringify(mergedResults), { encoding: 'utf8' }); }
[ "function", "cleanResultsStatus", "(", ")", "{", "// remove criterias and spec if no criteria in spec", "for", "(", "const", "spec", "in", "mergedResults", ".", "specs", ")", "{", "if", "(", "!", "(", "spec", "in", "parseResults", ".", "specs", ".", "specTable", ...
Removes specs and testcases from mergedResults that are no longer defined. Adds defined specs and testcases that have no status yet to mergedResults.
[ "Removes", "specs", "and", "testcases", "from", "mergedResults", "that", "are", "no", "longer", "defined", ".", "Adds", "defined", "specs", "and", "testcases", "that", "have", "no", "status", "yet", "to", "mergedResults", "." ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/cli.js#L1484-L1535
30,168
flohil/wdio-workflo
dist/lib/utility_functions/string.js
splitToObj
function splitToObj(str, delim) { if (!(_.isString(str))) { throw new Error(`Input must be a string: ${str}`); } else { return util_1.convertToObject(str.split(delim), () => true); } }
javascript
function splitToObj(str, delim) { if (!(_.isString(str))) { throw new Error(`Input must be a string: ${str}`); } else { return util_1.convertToObject(str.split(delim), () => true); } }
[ "function", "splitToObj", "(", "str", ",", "delim", ")", "{", "if", "(", "!", "(", "_", ".", "isString", "(", "str", ")", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "str", "}", "`", ")", ";", "}", "else", "{", "return", "util_1", ...
Splits a string at delim and returns an object with the split string parts as keys and the values set to true. @param str @param delim
[ "Splits", "a", "string", "at", "delim", "and", "returns", "an", "object", "with", "the", "split", "string", "parts", "as", "keys", "and", "the", "values", "set", "to", "true", "." ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/utility_functions/string.js#L12-L19
30,169
Bartvds/joi-assert
lib/assertion.js
assertion
function assertion(value, schema, message, vars, ssf) { return Joi.validate(value, schema, function(err, value) { // fast way if (!err) { return value; } // assemble message var msg = ''; // process message (if any) var mtype = typeof message; if (mtype === 'string') { if (vars && typeof vars === 'object') { // mini template message = message.replace(/\{([\w]+)\}/gi, function (match, key) { if (hasOwnProp.call(vars, key)) { return vars[key]; } }); } msg += message + ': '; } // append schema label msg += getLabel(schema.describe(), err); // append some of the errors var maxDetails = 4; msg += err.details.slice(0, maxDetails).map(function(det) { if (/^\w+\.\w/.test(det.path)) { return '[' + det.path + '] ' + det.message; } return det.message; }).join(', '); if (err.details.length > maxDetails) { var hidden = (err.details.length - maxDetails); msg += '... (showing ' + (err.details.length - hidden) + ' of ' + err.details.length + ')'; } // booya throw new AssertionError(msg, { details: err.details, value: value }, ssf); }); }
javascript
function assertion(value, schema, message, vars, ssf) { return Joi.validate(value, schema, function(err, value) { // fast way if (!err) { return value; } // assemble message var msg = ''; // process message (if any) var mtype = typeof message; if (mtype === 'string') { if (vars && typeof vars === 'object') { // mini template message = message.replace(/\{([\w]+)\}/gi, function (match, key) { if (hasOwnProp.call(vars, key)) { return vars[key]; } }); } msg += message + ': '; } // append schema label msg += getLabel(schema.describe(), err); // append some of the errors var maxDetails = 4; msg += err.details.slice(0, maxDetails).map(function(det) { if (/^\w+\.\w/.test(det.path)) { return '[' + det.path + '] ' + det.message; } return det.message; }).join(', '); if (err.details.length > maxDetails) { var hidden = (err.details.length - maxDetails); msg += '... (showing ' + (err.details.length - hidden) + ' of ' + err.details.length + ')'; } // booya throw new AssertionError(msg, { details: err.details, value: value }, ssf); }); }
[ "function", "assertion", "(", "value", ",", "schema", ",", "message", ",", "vars", ",", "ssf", ")", "{", "return", "Joi", ".", "validate", "(", "value", ",", "schema", ",", "function", "(", "err", ",", "value", ")", "{", "// fast way", "if", "(", "!"...
main assertino logic
[ "main", "assertino", "logic" ]
a4a920ad79a9b40ae38437244a5915e6cb76f3b3
https://github.com/Bartvds/joi-assert/blob/a4a920ad79a9b40ae38437244a5915e6cb76f3b3/lib/assertion.js#L25-L73
30,170
emmetio/markup-formatters
format/html.js
setFormatting
function setFormatting(outNode, profile) { const node = outNode.node; if (shouldFormatNode(node, profile)) { outNode.indent = profile.indent(getIndentLevel(node, profile)); outNode.newline = '\n'; const prefix = outNode.newline + outNode.indent; // do not format the very first node in output if (!isRoot(node.parent) || !isFirstChild(node)) { outNode.beforeOpen = prefix; if (node.isTextOnly) { outNode.beforeText = prefix; } } if (hasInnerFormatting(node, profile)) { if (!node.isTextOnly) { outNode.beforeText = prefix + profile.indent(1); } outNode.beforeClose = prefix; } } return outNode; }
javascript
function setFormatting(outNode, profile) { const node = outNode.node; if (shouldFormatNode(node, profile)) { outNode.indent = profile.indent(getIndentLevel(node, profile)); outNode.newline = '\n'; const prefix = outNode.newline + outNode.indent; // do not format the very first node in output if (!isRoot(node.parent) || !isFirstChild(node)) { outNode.beforeOpen = prefix; if (node.isTextOnly) { outNode.beforeText = prefix; } } if (hasInnerFormatting(node, profile)) { if (!node.isTextOnly) { outNode.beforeText = prefix + profile.indent(1); } outNode.beforeClose = prefix; } } return outNode; }
[ "function", "setFormatting", "(", "outNode", ",", "profile", ")", "{", "const", "node", "=", "outNode", ".", "node", ";", "if", "(", "shouldFormatNode", "(", "node", ",", "profile", ")", ")", "{", "outNode", ".", "indent", "=", "profile", ".", "indent", ...
Updates formatting properties for given output node @param {OutputNode} outNode Output wrapper of farsed abbreviation node @param {Profile} profile Output profile @return {OutputNode}
[ "Updates", "formatting", "properties", "for", "given", "output", "node" ]
a9f93994fa5cb6aef6b0148b9ec485846fb4a338
https://github.com/emmetio/markup-formatters/blob/a9f93994fa5cb6aef6b0148b9ec485846fb4a338/format/html.js#L70-L95
30,171
emmetio/markup-formatters
format/html.js
shouldFormatNode
function shouldFormatNode(node, profile) { if (!profile.get('format')) { return false; } if (node.parent.isTextOnly && node.parent.children.length === 1 && parseFields(node.parent.value).fields.length) { // Edge case: do not format the only child of text-only node, // but only if parent contains fields return false; } return isInline(node, profile) ? shouldFormatInline(node, profile) : true; }
javascript
function shouldFormatNode(node, profile) { if (!profile.get('format')) { return false; } if (node.parent.isTextOnly && node.parent.children.length === 1 && parseFields(node.parent.value).fields.length) { // Edge case: do not format the only child of text-only node, // but only if parent contains fields return false; } return isInline(node, profile) ? shouldFormatInline(node, profile) : true; }
[ "function", "shouldFormatNode", "(", "node", ",", "profile", ")", "{", "if", "(", "!", "profile", ".", "get", "(", "'format'", ")", ")", "{", "return", "false", ";", "}", "if", "(", "node", ".", "parent", ".", "isTextOnly", "&&", "node", ".", "parent...
Check if given node should be formatted @param {Node} node @param {Profile} profile @return {Boolean}
[ "Check", "if", "given", "node", "should", "be", "formatted" ]
a9f93994fa5cb6aef6b0148b9ec485846fb4a338
https://github.com/emmetio/markup-formatters/blob/a9f93994fa5cb6aef6b0148b9ec485846fb4a338/format/html.js#L103-L117
30,172
emmetio/markup-formatters
format/html.js
formatAttributes
function formatAttributes(outNode, profile) { const node = outNode.node; return node.attributes.map(attr => { if (attr.options.implied && attr.value == null) { return null; } const attrName = profile.attribute(attr.name); let attrValue = null; // handle boolean attributes if (attr.options.boolean || profile.get('booleanAttributes').indexOf(attrName.toLowerCase()) !== -1) { if (profile.get('compactBooleanAttributes') && attr.value == null) { return ` ${attrName}`; } else if (attr.value == null) { attrValue = attrName; } } if (attrValue == null) { attrValue = outNode.renderFields(attr.value); } return attr.options.before && attr.options.after ? ` ${attrName}=${attr.options.before+attrValue+attr.options.after}` : ` ${attrName}=${profile.quote(attrValue)}`; }).join(''); }
javascript
function formatAttributes(outNode, profile) { const node = outNode.node; return node.attributes.map(attr => { if (attr.options.implied && attr.value == null) { return null; } const attrName = profile.attribute(attr.name); let attrValue = null; // handle boolean attributes if (attr.options.boolean || profile.get('booleanAttributes').indexOf(attrName.toLowerCase()) !== -1) { if (profile.get('compactBooleanAttributes') && attr.value == null) { return ` ${attrName}`; } else if (attr.value == null) { attrValue = attrName; } } if (attrValue == null) { attrValue = outNode.renderFields(attr.value); } return attr.options.before && attr.options.after ? ` ${attrName}=${attr.options.before+attrValue+attr.options.after}` : ` ${attrName}=${profile.quote(attrValue)}`; }).join(''); }
[ "function", "formatAttributes", "(", "outNode", ",", "profile", ")", "{", "const", "node", "=", "outNode", ".", "node", ";", "return", "node", ".", "attributes", ".", "map", "(", "attr", "=>", "{", "if", "(", "attr", ".", "options", ".", "implied", "&&...
Outputs attributes of given abbreviation node as HTML attributes @param {OutputNode} outNode @param {Profile} profile @return {String}
[ "Outputs", "attributes", "of", "given", "abbreviation", "node", "as", "HTML", "attributes" ]
a9f93994fa5cb6aef6b0148b9ec485846fb4a338
https://github.com/emmetio/markup-formatters/blob/a9f93994fa5cb6aef6b0148b9ec485846fb4a338/format/html.js#L208-L236
30,173
emmetio/markup-formatters
format/html.js
getIndentLevel
function getIndentLevel(node, profile) { // Increase indent level IF NOT: // * parent is text-only node // * there’s a parent node with a name that is explicitly set to decrease level const skip = profile.get('formatSkip') || []; let level = node.parent.isTextOnly ? -2 : -1; let ctx = node; while (ctx = ctx.parent) { if (skip.indexOf( (ctx.name || '').toLowerCase() ) === -1) { level++; } } return level < 0 ? 0 : level; }
javascript
function getIndentLevel(node, profile) { // Increase indent level IF NOT: // * parent is text-only node // * there’s a parent node with a name that is explicitly set to decrease level const skip = profile.get('formatSkip') || []; let level = node.parent.isTextOnly ? -2 : -1; let ctx = node; while (ctx = ctx.parent) { if (skip.indexOf( (ctx.name || '').toLowerCase() ) === -1) { level++; } } return level < 0 ? 0 : level; }
[ "function", "getIndentLevel", "(", "node", ",", "profile", ")", "{", "// Increase indent level IF NOT:", "// * parent is text-only node", "// * there’s a parent node with a name that is explicitly set to decrease level", "const", "skip", "=", "profile", ".", "get", "(", "'formatS...
Computes indent level for given node @param {Node} node @param {Profile} profile @param {Number} level @return {Number}
[ "Computes", "indent", "level", "for", "given", "node" ]
a9f93994fa5cb6aef6b0148b9ec485846fb4a338
https://github.com/emmetio/markup-formatters/blob/a9f93994fa5cb6aef6b0148b9ec485846fb4a338/format/html.js#L266-L280
30,174
emmetio/markup-formatters
format/html.js
commentNode
function commentNode(outNode, options) { const node = outNode.node; if (!options.enabled || !options.trigger || !node.name) { return; } const attrs = outNode.node.attributes.reduce((out, attr) => { if (attr.name && attr.value != null) { out[attr.name.toUpperCase().replace(/-/g, '_')] = attr.value; } return out; }, {}); // add comment only if attribute trigger is present for (let i = 0, il = options.trigger.length; i < il; i++) { if (options.trigger[i].toUpperCase() in attrs) { outNode.open = template(options.before, attrs) + outNode.open; if (outNode.close) { outNode.close += template(options.after, attrs); } break; } } }
javascript
function commentNode(outNode, options) { const node = outNode.node; if (!options.enabled || !options.trigger || !node.name) { return; } const attrs = outNode.node.attributes.reduce((out, attr) => { if (attr.name && attr.value != null) { out[attr.name.toUpperCase().replace(/-/g, '_')] = attr.value; } return out; }, {}); // add comment only if attribute trigger is present for (let i = 0, il = options.trigger.length; i < il; i++) { if (options.trigger[i].toUpperCase() in attrs) { outNode.open = template(options.before, attrs) + outNode.open; if (outNode.close) { outNode.close += template(options.after, attrs); } break; } } }
[ "function", "commentNode", "(", "outNode", ",", "options", ")", "{", "const", "node", "=", "outNode", ".", "node", ";", "if", "(", "!", "options", ".", "enabled", "||", "!", "options", ".", "trigger", "||", "!", "node", ".", "name", ")", "{", "return...
Comments given output node, if required @param {OutputNode} outNode @param {Object} options
[ "Comments", "given", "output", "node", "if", "required" ]
a9f93994fa5cb6aef6b0148b9ec485846fb4a338
https://github.com/emmetio/markup-formatters/blob/a9f93994fa5cb6aef6b0148b9ec485846fb4a338/format/html.js#L287-L312
30,175
flohil/wdio-workflo
dist/lib/page_objects/page_elements/ValuePageElementGroup.js
isIValueElementNode
function isIValueElementNode(node) { return typeof node['getValue'] === 'function' && typeof node['setValue'] === 'function' && typeof node.currently['getValue'] === 'function' && typeof node.currently['hasValue'] === 'function' && typeof node.currently['hasAnyValue'] === 'function' && typeof node.currently['containsValue'] === 'function' && typeof node.wait['hasValue'] === 'function' && typeof node.wait['hasAnyValue'] === 'function' && typeof node.wait['containsValue'] === 'function' && typeof node.eventually['hasValue'] === 'function' && typeof node.eventually['hasAnyValue'] === 'function' && typeof node.eventually['containsValue'] === 'function'; }
javascript
function isIValueElementNode(node) { return typeof node['getValue'] === 'function' && typeof node['setValue'] === 'function' && typeof node.currently['getValue'] === 'function' && typeof node.currently['hasValue'] === 'function' && typeof node.currently['hasAnyValue'] === 'function' && typeof node.currently['containsValue'] === 'function' && typeof node.wait['hasValue'] === 'function' && typeof node.wait['hasAnyValue'] === 'function' && typeof node.wait['containsValue'] === 'function' && typeof node.eventually['hasValue'] === 'function' && typeof node.eventually['hasAnyValue'] === 'function' && typeof node.eventually['containsValue'] === 'function'; }
[ "function", "isIValueElementNode", "(", "node", ")", "{", "return", "typeof", "node", "[", "'getValue'", "]", "===", "'function'", "&&", "typeof", "node", "[", "'setValue'", "]", "===", "'function'", "&&", "typeof", "node", ".", "currently", "[", "'getValue'",...
type guards Returns true if the passed node supports all functions defined in IValueElementNode. @param node a PageNode
[ "type", "guards", "Returns", "true", "if", "the", "passed", "node", "supports", "all", "functions", "defined", "in", "IValueElementNode", "." ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/page_objects/page_elements/ValuePageElementGroup.js#L432-L445
30,176
flohil/wdio-workflo
dist/lib/jasmineMatchers.js
prettifyDiffObj
function prettifyDiffObj(diff) { const obj = { kind: undefined, path: undefined, expect: undefined, actual: undefined, index: undefined, item: undefined, }; if (diff.kind) { switch (diff.kind) { case 'N': obj.kind = 'New'; break; case 'D': obj.kind = 'Missing'; break; case 'E': obj.kind = 'Changed'; break; case 'A': obj.kind = 'Array Canged'; break; } } if (diff.path) { let path = diff.path[0]; for (let i = 1; i < diff.path.length; i++) { path += `/${diff.path[i]}`; } obj.path = path; } if (typeof diff.lhs !== 'undefined') { obj.expect = diff.lhs; } if (typeof diff.rhs !== 'undefined') { obj.actual = diff.rhs; } if (diff.index) { obj.index = diff.index; } if (diff.item) { obj.item = prettifyDiffObj(diff.item); } return obj; }
javascript
function prettifyDiffObj(diff) { const obj = { kind: undefined, path: undefined, expect: undefined, actual: undefined, index: undefined, item: undefined, }; if (diff.kind) { switch (diff.kind) { case 'N': obj.kind = 'New'; break; case 'D': obj.kind = 'Missing'; break; case 'E': obj.kind = 'Changed'; break; case 'A': obj.kind = 'Array Canged'; break; } } if (diff.path) { let path = diff.path[0]; for (let i = 1; i < diff.path.length; i++) { path += `/${diff.path[i]}`; } obj.path = path; } if (typeof diff.lhs !== 'undefined') { obj.expect = diff.lhs; } if (typeof diff.rhs !== 'undefined') { obj.actual = diff.rhs; } if (diff.index) { obj.index = diff.index; } if (diff.item) { obj.item = prettifyDiffObj(diff.item); } return obj; }
[ "function", "prettifyDiffObj", "(", "diff", ")", "{", "const", "obj", "=", "{", "kind", ":", "undefined", ",", "path", ":", "undefined", ",", "expect", ":", "undefined", ",", "actual", ":", "undefined", ",", "index", ":", "undefined", ",", "item", ":", ...
DEFINE INTERNAL UTILITY FUNCTIONS BELOW makes output of a single diff more readable
[ "DEFINE", "INTERNAL", "UTILITY", "FUNCTIONS", "BELOW", "makes", "output", "of", "a", "single", "diff", "more", "readable" ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/jasmineMatchers.js#L120-L165
30,177
flohil/wdio-workflo
dist/lib/jasmineMatchers.js
prettifyDiffOutput
function prettifyDiffOutput(diffArr) { const res = []; for (const diff of diffArr) { res.push(prettifyDiffObj(diff)); } return res; }
javascript
function prettifyDiffOutput(diffArr) { const res = []; for (const diff of diffArr) { res.push(prettifyDiffObj(diff)); } return res; }
[ "function", "prettifyDiffOutput", "(", "diffArr", ")", "{", "const", "res", "=", "[", "]", ";", "for", "(", "const", "diff", "of", "diffArr", ")", "{", "res", ".", "push", "(", "prettifyDiffObj", "(", "diff", ")", ")", ";", "}", "return", "res", ";",...
makes output of a diff object array more readable
[ "makes", "output", "of", "a", "diff", "object", "array", "more", "readable" ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/jasmineMatchers.js#L167-L173
30,178
telehash/e3x-js
e3x.js
cleanup
function cleanup() { if(chan.timer) clearTimeout(chan.timer); chan.timer = setTimeout(function(){ chan.state = "gone"; // in case an app has a reference x.channels[chan.id] = {state:"gone"}; // remove our reference for gc }, chan.timeout); }
javascript
function cleanup() { if(chan.timer) clearTimeout(chan.timer); chan.timer = setTimeout(function(){ chan.state = "gone"; // in case an app has a reference x.channels[chan.id] = {state:"gone"}; // remove our reference for gc }, chan.timeout); }
[ "function", "cleanup", "(", ")", "{", "if", "(", "chan", ".", "timer", ")", "clearTimeout", "(", "chan", ".", "timer", ")", ";", "chan", ".", "timer", "=", "setTimeout", "(", "function", "(", ")", "{", "chan", ".", "state", "=", "\"gone\"", ";", "/...
track all active channels to route incoming packets called to do eventual cleanup
[ "track", "all", "active", "channels", "to", "route", "incoming", "packets", "called", "to", "do", "eventual", "cleanup" ]
0f96c0e57c85c81f340dba79df1ce6fd411fb0d6
https://github.com/telehash/e3x-js/blob/0f96c0e57c85c81f340dba79df1ce6fd411fb0d6/e3x.js#L313-L320
30,179
flohil/wdio-workflo
dist/lib/steps.js
proxifySteps
function proxifySteps(stepDefinitions) { return new Proxy(stepDefinitions, { get: (target, name, receiver) => stepsGetter(target, name, receiver), set: (target, name, value) => stepsSetter(target, name, value), }); }
javascript
function proxifySteps(stepDefinitions) { return new Proxy(stepDefinitions, { get: (target, name, receiver) => stepsGetter(target, name, receiver), set: (target, name, value) => stepsSetter(target, name, value), }); }
[ "function", "proxifySteps", "(", "stepDefinitions", ")", "{", "return", "new", "Proxy", "(", "stepDefinitions", ",", "{", "get", ":", "(", "target", ",", "name", ",", "receiver", ")", "=>", "stepsGetter", "(", "target", ",", "name", ",", "receiver", ")", ...
Creates a Proxy that adds custom getters and setters to the merged step definitions. Steps in wdio-workflo can only function properly if this proxy is used to interact with them. @param stepDefinitions the merged step definitions @returns the proxified steps
[ "Creates", "a", "Proxy", "that", "adds", "custom", "getters", "and", "setters", "to", "the", "merged", "step", "definitions", ".", "Steps", "in", "wdio", "-", "workflo", "can", "only", "function", "properly", "if", "this", "proxy", "is", "used", "to", "int...
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/steps.js#L57-L62
30,180
flohil/wdio-workflo
dist/lib/utility_functions/array.js
mapToObject
function mapToObject(input, mapFunc) { const obj = {}; for (const element of input) { obj[element] = mapFunc(element); } return obj; }
javascript
function mapToObject(input, mapFunc) { const obj = {}; for (const element of input) { obj[element] = mapFunc(element); } return obj; }
[ "function", "mapToObject", "(", "input", ",", "mapFunc", ")", "{", "const", "obj", "=", "{", "}", ";", "for", "(", "const", "element", "of", "input", ")", "{", "obj", "[", "element", "]", "=", "mapFunc", "(", "element", ")", ";", "}", "return", "ob...
Gets an input array and maps it to an object where the property keys correspond to the array elements and the property values are defiend by mapFunc. @param input @param mapFunc
[ "Gets", "an", "input", "array", "and", "maps", "it", "to", "an", "object", "where", "the", "property", "keys", "correspond", "to", "the", "array", "elements", "and", "the", "property", "values", "are", "defiend", "by", "mapFunc", "." ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/utility_functions/array.js#L11-L17
30,181
igocreate/igo
cli/i18n.js
function(args, callback) { if (!config.i18n.spreadsheet_id) { return callback('Missing config.i18n.spreadsheet_id'); } const path = 'https://spreadsheets.google.com/feeds/list/' + config.i18n.spreadsheet_id + '/default/public/values?alt=json'; // request json data request(path, (err, res, body) => { if (err) { return callback(err); } const json = JSON.parse(body); //console.dir(json); const translations = {}; // parse json.feed.entry.forEach(entry => { // const key = _.get(entry, 'gsx$key.$t'); config.i18n.whitelist.forEach((lang) => { const value = _.get(entry, 'gsx$' + lang + '.$t'); if (value) { _.setWith(translations, lang + '.' + key, value, Object); } }); }); // write translation files config.i18n.whitelist.forEach((lang) => { const dir = `./locales/${lang}`; if (!fs.existsSync(dir)) { console.warn('Missing directory: ' + dir); return; } translations[lang]._meta = { generated_at: new Date(), lang }; const data = JSON.stringify(translations[lang], null, 2); const filename = `${dir}/translation.json`; console.log('Writing ' + filename); fs.writeFileSync(filename, data ); }); callback(); }); }
javascript
function(args, callback) { if (!config.i18n.spreadsheet_id) { return callback('Missing config.i18n.spreadsheet_id'); } const path = 'https://spreadsheets.google.com/feeds/list/' + config.i18n.spreadsheet_id + '/default/public/values?alt=json'; // request json data request(path, (err, res, body) => { if (err) { return callback(err); } const json = JSON.parse(body); //console.dir(json); const translations = {}; // parse json.feed.entry.forEach(entry => { // const key = _.get(entry, 'gsx$key.$t'); config.i18n.whitelist.forEach((lang) => { const value = _.get(entry, 'gsx$' + lang + '.$t'); if (value) { _.setWith(translations, lang + '.' + key, value, Object); } }); }); // write translation files config.i18n.whitelist.forEach((lang) => { const dir = `./locales/${lang}`; if (!fs.existsSync(dir)) { console.warn('Missing directory: ' + dir); return; } translations[lang]._meta = { generated_at: new Date(), lang }; const data = JSON.stringify(translations[lang], null, 2); const filename = `${dir}/translation.json`; console.log('Writing ' + filename); fs.writeFileSync(filename, data ); }); callback(); }); }
[ "function", "(", "args", ",", "callback", ")", "{", "if", "(", "!", "config", ".", "i18n", ".", "spreadsheet_id", ")", "{", "return", "callback", "(", "'Missing config.i18n.spreadsheet_id'", ")", ";", "}", "const", "path", "=", "'https://spreadsheets.google.com/...
igo i18n update
[ "igo", "i18n", "update" ]
fab4409260c648cad55f7b00b7a93ab2d9d8124c
https://github.com/igocreate/igo/blob/fab4409260c648cad55f7b00b7a93ab2d9d8124c/cli/i18n.js#L11-L60
30,182
flohil/wdio-workflo
dist/lib/matchers.js
convertDiffToMessages
function convertDiffToMessages(diff, actualOnly = false, includeTimeouts = false, timeout = undefined, comparisonLines = [], paths = []) { if (diff.tree && Object.keys(diff.tree).length > 0) { const keys = Object.keys(diff.tree); keys.forEach(key => { const _paths = [...paths]; _paths.push(key); convertDiffToMessages(diff.tree[key], actualOnly, includeTimeouts, timeout, comparisonLines, _paths); }); } else { let _paths = paths.join(''); if (_paths.charAt(0) === '.') { _paths = _paths.substring(1); } const _actual = printValue(diff.actual); const _expected = printValue(diff.expected); let compareStr = ''; if (actualOnly) { compareStr = (typeof diff.actual === 'undefined') ? '' : `{actual: <${_actual}>}\n`; } else { compareStr = (typeof diff.actual === 'undefined' && typeof diff.expected === 'undefined') ? '' : `{actual: <${_actual}>, expected: <${_expected}>}\n`; } const timeoutStr = (includeTimeouts) ? ` within ${timeout || diff.timeout}ms` : ''; comparisonLines.push(`${diff.constructorName} at path '${_paths}'${timeoutStr}\n${compareStr}( ${diff.selector} )`); } return comparisonLines; }
javascript
function convertDiffToMessages(diff, actualOnly = false, includeTimeouts = false, timeout = undefined, comparisonLines = [], paths = []) { if (diff.tree && Object.keys(diff.tree).length > 0) { const keys = Object.keys(diff.tree); keys.forEach(key => { const _paths = [...paths]; _paths.push(key); convertDiffToMessages(diff.tree[key], actualOnly, includeTimeouts, timeout, comparisonLines, _paths); }); } else { let _paths = paths.join(''); if (_paths.charAt(0) === '.') { _paths = _paths.substring(1); } const _actual = printValue(diff.actual); const _expected = printValue(diff.expected); let compareStr = ''; if (actualOnly) { compareStr = (typeof diff.actual === 'undefined') ? '' : `{actual: <${_actual}>}\n`; } else { compareStr = (typeof diff.actual === 'undefined' && typeof diff.expected === 'undefined') ? '' : `{actual: <${_actual}>, expected: <${_expected}>}\n`; } const timeoutStr = (includeTimeouts) ? ` within ${timeout || diff.timeout}ms` : ''; comparisonLines.push(`${diff.constructorName} at path '${_paths}'${timeoutStr}\n${compareStr}( ${diff.selector} )`); } return comparisonLines; }
[ "function", "convertDiffToMessages", "(", "diff", ",", "actualOnly", "=", "false", ",", "includeTimeouts", "=", "false", ",", "timeout", "=", "undefined", ",", "comparisonLines", "=", "[", "]", ",", "paths", "=", "[", "]", ")", "{", "if", "(", "diff", "....
ERROR TEXT FUNCTIONS
[ "ERROR", "TEXT", "FUNCTIONS" ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/matchers.js#L281-L310
30,183
flohil/wdio-workflo
dist/lib/utility_functions/util.js
convertToObject
function convertToObject(unknownTypedInput, valueFunc = undefined) { let obj = {}; if (typeof unknownTypedInput !== 'undefined') { if (typeof unknownTypedInput === 'string') { unknownTypedInput = [unknownTypedInput]; } if (_.isArray(unknownTypedInput)) { for (const element of unknownTypedInput) { let value; if (typeof valueFunc !== 'undefined') { value = valueFunc(element); } else { value = undefined; } obj[element] = value; } } else { obj = _.cloneDeep(unknownTypedInput); } } return obj; }
javascript
function convertToObject(unknownTypedInput, valueFunc = undefined) { let obj = {}; if (typeof unknownTypedInput !== 'undefined') { if (typeof unknownTypedInput === 'string') { unknownTypedInput = [unknownTypedInput]; } if (_.isArray(unknownTypedInput)) { for (const element of unknownTypedInput) { let value; if (typeof valueFunc !== 'undefined') { value = valueFunc(element); } else { value = undefined; } obj[element] = value; } } else { obj = _.cloneDeep(unknownTypedInput); } } return obj; }
[ "function", "convertToObject", "(", "unknownTypedInput", ",", "valueFunc", "=", "undefined", ")", "{", "let", "obj", "=", "{", "}", ";", "if", "(", "typeof", "unknownTypedInput", "!==", "'undefined'", ")", "{", "if", "(", "typeof", "unknownTypedInput", "===", ...
Converts strings, arrays and objects into objects. If input is string, output is an object with one entry where the key is the string. If input is array, output is an object where each key represents one element in the array. If input is object, output is a clone of the input object. For strings and arrays, valueFunc is used to calculate the resulting object's property values. For objects, valueFunc has no effect -> original property values will be preserved! @param unknownTypedInput @param valueFunc
[ "Converts", "strings", "arrays", "and", "objects", "into", "objects", "." ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/utility_functions/util.js#L20-L43
30,184
flohil/wdio-workflo
dist/lib/utility_functions/util.js
compare
function compare(var1, var2, operator) { switch (operator) { case Workflo.Comparator.equalTo || Workflo.Comparator.eq: return var1 === var2; case Workflo.Comparator.notEqualTo || Workflo.Comparator.ne: return var1 !== var2; case Workflo.Comparator.greaterThan || Workflo.Comparator.gt: return var1 > var2; case Workflo.Comparator.lessThan || Workflo.Comparator.lt: return var1 < var2; } }
javascript
function compare(var1, var2, operator) { switch (operator) { case Workflo.Comparator.equalTo || Workflo.Comparator.eq: return var1 === var2; case Workflo.Comparator.notEqualTo || Workflo.Comparator.ne: return var1 !== var2; case Workflo.Comparator.greaterThan || Workflo.Comparator.gt: return var1 > var2; case Workflo.Comparator.lessThan || Workflo.Comparator.lt: return var1 < var2; } }
[ "function", "compare", "(", "var1", ",", "var2", ",", "operator", ")", "{", "switch", "(", "operator", ")", "{", "case", "Workflo", ".", "Comparator", ".", "equalTo", "||", "Workflo", ".", "Comparator", ".", "eq", ":", "return", "var1", "===", "var2", ...
This function compares the values of two passed variables with a compare method defined in `operator`. The following compare methods are supported: - equals - not equals - less than - greater than @template Type the type of the compared variables @param var1 the first variable to be compared @param var2 the second variable to be compared @param operator defines the method to be used for the comparison (===, !==, <, >) @returns the result of the comparison
[ "This", "function", "compares", "the", "values", "of", "two", "passed", "variables", "with", "a", "compare", "method", "defined", "in", "operator", "." ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/utility_functions/util.js#L61-L72
30,185
uber-archive/thriftify
compiler/spec.js
Types
function Types() { this.binary = specs.ABinary; this.string = specs.AString; this.bool = specs.ABoolean; this.byte = specs.AByte; this.i16 = specs.AInt16; this.i32 = specs.AInt32; this.i64 = specs.AInt64; this.double = specs.ADouble; }
javascript
function Types() { this.binary = specs.ABinary; this.string = specs.AString; this.bool = specs.ABoolean; this.byte = specs.AByte; this.i16 = specs.AInt16; this.i32 = specs.AInt32; this.i64 = specs.AInt64; this.double = specs.ADouble; }
[ "function", "Types", "(", ")", "{", "this", ".", "binary", "=", "specs", ".", "ABinary", ";", "this", ".", "string", "=", "specs", ".", "AString", ";", "this", ".", "bool", "=", "specs", ".", "ABoolean", ";", "this", ".", "byte", "=", "specs", ".",...
The types structure starts with the default types, and devolves into a dictionary of type declarations.
[ "The", "types", "structure", "starts", "with", "the", "default", "types", "and", "devolves", "into", "a", "dictionary", "of", "type", "declarations", "." ]
f54e97e02dd22190a779a4b316b15f0c81087ebf
https://github.com/uber-archive/thriftify/blob/f54e97e02dd22190a779a4b316b15f0c81087ebf/compiler/spec.js#L37-L46
30,186
jhudson8/react-mixin-manager
react-mixin-manager.js
get
function get(values, index, initiatedOnce, rtn) { /** * add the named mixin and all un-added dependencies to the return array * @param the mixin name */ function addTo(name) { var indexName = name, match = name.match(/^([^\(]*)\s*\(([^\)]*)\)\s*/), params = match && match[2]; name = match && match[1] || name; if (!index[indexName]) { if (params) { // there can be no function calls here because of the regex match /*jshint evil: true */ params = eval('[' + params + ']'); } var mixin = _mixins[name], checkAgain = false, skip = false; if (mixin) { if (typeof mixin === 'function') { if (_initiatedOnce[name]) { if (!initiatedOnce[name]) { initiatedOnce[name] = []; // add the placeholder so the mixin ends up in the right place // we will replace all names with the appropriate mixins at the end // (so we have all of the appropriate arguments) mixin = name; } else { // but we only want to add it a single time skip = true; } if (params) { initiatedOnce[name].push(params); } } else { mixin = mixin.apply(this, params || []); checkAgain = true; } } else if (params) { throw new Error('the mixin "' + name + '" does not support parameters'); } get(_dependsOn[name], index, initiatedOnce, rtn); get(_dependsInjected[name], index, initiatedOnce, rtn); index[indexName] = true; if (checkAgain) { get([mixin], index, initiatedOnce, rtn); } else if (!skip) { checkForInlineMixins(mixin, rtn); rtn.push(mixin); } } else { throw new Error('invalid mixin "' + name + '"'); } } } // if the mixin has a "mixins" attribute, clone and add those dependencies first function checkForInlineMixins(mixin, rtn) { if (mixin.mixins) { get(mixin.mixins, index, initiatedOnce, rtn); } } function handleMixin(mixin) { if (mixin) { if (Array.isArray(mixin)) { // flatten it out get(mixin, index, initiatedOnce, rtn); } else if (typeof mixin === 'string') { // add the named mixin and all of it's dependencies addTo(mixin); } else { checkForInlineMixins(mixin, rtn); // just add the mixin normally rtn.push(mixin); } } } if (Array.isArray(values)) { for (var i = 0; i < values.length; i++) { handleMixin(values[i]); } } else { handleMixin(values); } }
javascript
function get(values, index, initiatedOnce, rtn) { /** * add the named mixin and all un-added dependencies to the return array * @param the mixin name */ function addTo(name) { var indexName = name, match = name.match(/^([^\(]*)\s*\(([^\)]*)\)\s*/), params = match && match[2]; name = match && match[1] || name; if (!index[indexName]) { if (params) { // there can be no function calls here because of the regex match /*jshint evil: true */ params = eval('[' + params + ']'); } var mixin = _mixins[name], checkAgain = false, skip = false; if (mixin) { if (typeof mixin === 'function') { if (_initiatedOnce[name]) { if (!initiatedOnce[name]) { initiatedOnce[name] = []; // add the placeholder so the mixin ends up in the right place // we will replace all names with the appropriate mixins at the end // (so we have all of the appropriate arguments) mixin = name; } else { // but we only want to add it a single time skip = true; } if (params) { initiatedOnce[name].push(params); } } else { mixin = mixin.apply(this, params || []); checkAgain = true; } } else if (params) { throw new Error('the mixin "' + name + '" does not support parameters'); } get(_dependsOn[name], index, initiatedOnce, rtn); get(_dependsInjected[name], index, initiatedOnce, rtn); index[indexName] = true; if (checkAgain) { get([mixin], index, initiatedOnce, rtn); } else if (!skip) { checkForInlineMixins(mixin, rtn); rtn.push(mixin); } } else { throw new Error('invalid mixin "' + name + '"'); } } } // if the mixin has a "mixins" attribute, clone and add those dependencies first function checkForInlineMixins(mixin, rtn) { if (mixin.mixins) { get(mixin.mixins, index, initiatedOnce, rtn); } } function handleMixin(mixin) { if (mixin) { if (Array.isArray(mixin)) { // flatten it out get(mixin, index, initiatedOnce, rtn); } else if (typeof mixin === 'string') { // add the named mixin and all of it's dependencies addTo(mixin); } else { checkForInlineMixins(mixin, rtn); // just add the mixin normally rtn.push(mixin); } } } if (Array.isArray(values)) { for (var i = 0; i < values.length; i++) { handleMixin(values[i]); } } else { handleMixin(values); } }
[ "function", "get", "(", "values", ",", "index", ",", "initiatedOnce", ",", "rtn", ")", "{", "/**\n * add the named mixin and all un-added dependencies to the return array\n * @param the mixin name\n */", "function", "addTo", "(", "name", ")", "{", "var",...
return the normalized mixin list @param values {Array} list of mixin entries @param index {Object} hash which contains a truthy value for all named mixins that have been added @param initiatedOnce {Object} hash which collects mixins and their parameters that should be initiated once @param rtn {Array} the normalized return array
[ "return", "the", "normalized", "mixin", "list" ]
a2ea6d1ed6cbb7aaa6f15e90352fbec746842430
https://github.com/jhudson8/react-mixin-manager/blob/a2ea6d1ed6cbb7aaa6f15e90352fbec746842430/react-mixin-manager.js#L88-L180
30,187
jhudson8/react-mixin-manager
react-mixin-manager.js
addTo
function addTo(name) { var indexName = name, match = name.match(/^([^\(]*)\s*\(([^\)]*)\)\s*/), params = match && match[2]; name = match && match[1] || name; if (!index[indexName]) { if (params) { // there can be no function calls here because of the regex match /*jshint evil: true */ params = eval('[' + params + ']'); } var mixin = _mixins[name], checkAgain = false, skip = false; if (mixin) { if (typeof mixin === 'function') { if (_initiatedOnce[name]) { if (!initiatedOnce[name]) { initiatedOnce[name] = []; // add the placeholder so the mixin ends up in the right place // we will replace all names with the appropriate mixins at the end // (so we have all of the appropriate arguments) mixin = name; } else { // but we only want to add it a single time skip = true; } if (params) { initiatedOnce[name].push(params); } } else { mixin = mixin.apply(this, params || []); checkAgain = true; } } else if (params) { throw new Error('the mixin "' + name + '" does not support parameters'); } get(_dependsOn[name], index, initiatedOnce, rtn); get(_dependsInjected[name], index, initiatedOnce, rtn); index[indexName] = true; if (checkAgain) { get([mixin], index, initiatedOnce, rtn); } else if (!skip) { checkForInlineMixins(mixin, rtn); rtn.push(mixin); } } else { throw new Error('invalid mixin "' + name + '"'); } } }
javascript
function addTo(name) { var indexName = name, match = name.match(/^([^\(]*)\s*\(([^\)]*)\)\s*/), params = match && match[2]; name = match && match[1] || name; if (!index[indexName]) { if (params) { // there can be no function calls here because of the regex match /*jshint evil: true */ params = eval('[' + params + ']'); } var mixin = _mixins[name], checkAgain = false, skip = false; if (mixin) { if (typeof mixin === 'function') { if (_initiatedOnce[name]) { if (!initiatedOnce[name]) { initiatedOnce[name] = []; // add the placeholder so the mixin ends up in the right place // we will replace all names with the appropriate mixins at the end // (so we have all of the appropriate arguments) mixin = name; } else { // but we only want to add it a single time skip = true; } if (params) { initiatedOnce[name].push(params); } } else { mixin = mixin.apply(this, params || []); checkAgain = true; } } else if (params) { throw new Error('the mixin "' + name + '" does not support parameters'); } get(_dependsOn[name], index, initiatedOnce, rtn); get(_dependsInjected[name], index, initiatedOnce, rtn); index[indexName] = true; if (checkAgain) { get([mixin], index, initiatedOnce, rtn); } else if (!skip) { checkForInlineMixins(mixin, rtn); rtn.push(mixin); } } else { throw new Error('invalid mixin "' + name + '"'); } } }
[ "function", "addTo", "(", "name", ")", "{", "var", "indexName", "=", "name", ",", "match", "=", "name", ".", "match", "(", "/", "^([^\\(]*)\\s*\\(([^\\)]*)\\)\\s*", "/", ")", ",", "params", "=", "match", "&&", "match", "[", "2", "]", ";", "name", "=", ...
add the named mixin and all un-added dependencies to the return array @param the mixin name
[ "add", "the", "named", "mixin", "and", "all", "un", "-", "added", "dependencies", "to", "the", "return", "array" ]
a2ea6d1ed6cbb7aaa6f15e90352fbec746842430
https://github.com/jhudson8/react-mixin-manager/blob/a2ea6d1ed6cbb7aaa6f15e90352fbec746842430/react-mixin-manager.js#L93-L147
30,188
jhudson8/react-mixin-manager
react-mixin-manager.js
checkForInlineMixins
function checkForInlineMixins(mixin, rtn) { if (mixin.mixins) { get(mixin.mixins, index, initiatedOnce, rtn); } }
javascript
function checkForInlineMixins(mixin, rtn) { if (mixin.mixins) { get(mixin.mixins, index, initiatedOnce, rtn); } }
[ "function", "checkForInlineMixins", "(", "mixin", ",", "rtn", ")", "{", "if", "(", "mixin", ".", "mixins", ")", "{", "get", "(", "mixin", ".", "mixins", ",", "index", ",", "initiatedOnce", ",", "rtn", ")", ";", "}", "}" ]
if the mixin has a "mixins" attribute, clone and add those dependencies first
[ "if", "the", "mixin", "has", "a", "mixins", "attribute", "clone", "and", "add", "those", "dependencies", "first" ]
a2ea6d1ed6cbb7aaa6f15e90352fbec746842430
https://github.com/jhudson8/react-mixin-manager/blob/a2ea6d1ed6cbb7aaa6f15e90352fbec746842430/react-mixin-manager.js#L150-L154
30,189
jhudson8/react-mixin-manager
react-mixin-manager.js
applyInitiatedOnceArgs
function applyInitiatedOnceArgs(mixins, rtn) { /** * added once initiated mixins to return array */ function addInitiatedOnce(name, mixin, params) { mixin = mixin.call(this, params || []); // find the name placeholder in the return arr and replace it with the mixin var index = rtn.indexOf(name); rtn.splice(index, 1, mixin); } for (var m in mixins) { if (mixins.hasOwnProperty(m)) { addInitiatedOnce(m, _mixins[m], mixins[m]); } } }
javascript
function applyInitiatedOnceArgs(mixins, rtn) { /** * added once initiated mixins to return array */ function addInitiatedOnce(name, mixin, params) { mixin = mixin.call(this, params || []); // find the name placeholder in the return arr and replace it with the mixin var index = rtn.indexOf(name); rtn.splice(index, 1, mixin); } for (var m in mixins) { if (mixins.hasOwnProperty(m)) { addInitiatedOnce(m, _mixins[m], mixins[m]); } } }
[ "function", "applyInitiatedOnceArgs", "(", "mixins", ",", "rtn", ")", "{", "/**\n * added once initiated mixins to return array\n */", "function", "addInitiatedOnce", "(", "name", ",", "mixin", ",", "params", ")", "{", "mixin", "=", "mixin", ".", "call",...
add the mixins that should be once initiated to the normalized mixin list @param mixins {Object} hash of mixins keys and list of its parameters @param rtn {Array} the normalized return array
[ "add", "the", "mixins", "that", "should", "be", "once", "initiated", "to", "the", "normalized", "mixin", "list" ]
a2ea6d1ed6cbb7aaa6f15e90352fbec746842430
https://github.com/jhudson8/react-mixin-manager/blob/a2ea6d1ed6cbb7aaa6f15e90352fbec746842430/react-mixin-manager.js#L187-L204
30,190
jhudson8/react-mixin-manager
react-mixin-manager.js
addInitiatedOnce
function addInitiatedOnce(name, mixin, params) { mixin = mixin.call(this, params || []); // find the name placeholder in the return arr and replace it with the mixin var index = rtn.indexOf(name); rtn.splice(index, 1, mixin); }
javascript
function addInitiatedOnce(name, mixin, params) { mixin = mixin.call(this, params || []); // find the name placeholder in the return arr and replace it with the mixin var index = rtn.indexOf(name); rtn.splice(index, 1, mixin); }
[ "function", "addInitiatedOnce", "(", "name", ",", "mixin", ",", "params", ")", "{", "mixin", "=", "mixin", ".", "call", "(", "this", ",", "params", "||", "[", "]", ")", ";", "// find the name placeholder in the return arr and replace it with the mixin", "var", "in...
added once initiated mixins to return array
[ "added", "once", "initiated", "mixins", "to", "return", "array" ]
a2ea6d1ed6cbb7aaa6f15e90352fbec746842430
https://github.com/jhudson8/react-mixin-manager/blob/a2ea6d1ed6cbb7aaa6f15e90352fbec746842430/react-mixin-manager.js#L192-L197
30,191
jhudson8/react-mixin-manager
react-mixin-manager.js
function(name) { var l = _dependsInjected[name]; if (!l) { l = _dependsInjected[name] = []; } l.push(Array.prototype.slice.call(arguments, 1)); }
javascript
function(name) { var l = _dependsInjected[name]; if (!l) { l = _dependsInjected[name] = []; } l.push(Array.prototype.slice.call(arguments, 1)); }
[ "function", "(", "name", ")", "{", "var", "l", "=", "_dependsInjected", "[", "name", "]", ";", "if", "(", "!", "l", ")", "{", "l", "=", "_dependsInjected", "[", "name", "]", "=", "[", "]", ";", "}", "l", ".", "push", "(", "Array", ".", "prototy...
Inject dependencies that were not originally defined when a mixin was registered @param name {string} the main mixin name @param (any additional) {string} dependencies that should be registered against the mixin
[ "Inject", "dependencies", "that", "were", "not", "originally", "defined", "when", "a", "mixin", "was", "registered" ]
a2ea6d1ed6cbb7aaa6f15e90352fbec746842430
https://github.com/jhudson8/react-mixin-manager/blob/a2ea6d1ed6cbb7aaa6f15e90352fbec746842430/react-mixin-manager.js#L301-L307
30,192
igocreate/igo
src/connect/errorhandler.js
function(err, req, res) { console.log('handle error:'); console.dir(err); // uri error if (err instanceof URIError) { return res.status(404).render('errors/404'); } logger.error(req.method + ' ' + getURL(req) + ' : ' + err); logger.error(err.stack); if (!res._headerSent) { // show error if (config.showerrstack) { // const stacktrace = [ '<h1>', req.originalUrl, '</h1>', '<pre>', err.stack, '</pre>' ].join(''); res.status(500).send(stacktrace); } else { res.status(500).render('errors/500'); } } if (config.mailcrashto) { mailer.send('crash', { to: config.mailcrashto, subject: [ config.appname, 'Crash:', err ].join(' '), body: formatMessage(req, err) }) } }
javascript
function(err, req, res) { console.log('handle error:'); console.dir(err); // uri error if (err instanceof URIError) { return res.status(404).render('errors/404'); } logger.error(req.method + ' ' + getURL(req) + ' : ' + err); logger.error(err.stack); if (!res._headerSent) { // show error if (config.showerrstack) { // const stacktrace = [ '<h1>', req.originalUrl, '</h1>', '<pre>', err.stack, '</pre>' ].join(''); res.status(500).send(stacktrace); } else { res.status(500).render('errors/500'); } } if (config.mailcrashto) { mailer.send('crash', { to: config.mailcrashto, subject: [ config.appname, 'Crash:', err ].join(' '), body: formatMessage(req, err) }) } }
[ "function", "(", "err", ",", "req", ",", "res", ")", "{", "console", ".", "log", "(", "'handle error:'", ")", ";", "console", ".", "dir", "(", "err", ")", ";", "// uri error", "if", "(", "err", "instanceof", "URIError", ")", "{", "return", "res", "."...
log and show error
[ "log", "and", "show", "error" ]
fab4409260c648cad55f7b00b7a93ab2d9d8124c
https://github.com/igocreate/igo/blob/fab4409260c648cad55f7b00b7a93ab2d9d8124c/src/connect/errorhandler.js#L37-L71
30,193
flohil/wdio-workflo
dist/lib/utility_functions/object.js
mapProperties
function mapProperties(obj, func) { if (_.isArray(obj)) { throw new Error(`Input must be an object: ${obj}`); } else { const resultObj = Object.create(Object.prototype); for (const key in obj) { if (obj.hasOwnProperty(key)) { resultObj[key] = func(obj[key], key); } } return resultObj; } }
javascript
function mapProperties(obj, func) { if (_.isArray(obj)) { throw new Error(`Input must be an object: ${obj}`); } else { const resultObj = Object.create(Object.prototype); for (const key in obj) { if (obj.hasOwnProperty(key)) { resultObj[key] = func(obj[key], key); } } return resultObj; } }
[ "function", "mapProperties", "(", "obj", ",", "func", ")", "{", "if", "(", "_", ".", "isArray", "(", "obj", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "obj", "}", "`", ")", ";", "}", "else", "{", "const", "resultObj", "=", "Object", ...
Iterates over all properties in an object and executes func on each. Returns a new object with the same keys as the input object and the values as result of the func. @param obj an object for which a func should be executed on each property @param func the function to be executed on each property of the passed object
[ "Iterates", "over", "all", "properties", "in", "an", "object", "and", "executes", "func", "on", "each", "." ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/utility_functions/object.js#L14-L27
30,194
syntax-tree/unist-util-modify-children
index.js
iteratorFactory
function iteratorFactory(callback) { return iterator function iterator(parent) { var children = parent && parent.children if (!children) { throw new Error('Missing children in `parent` for `modifier`') } return iterate(children, callback, parent) } }
javascript
function iteratorFactory(callback) { return iterator function iterator(parent) { var children = parent && parent.children if (!children) { throw new Error('Missing children in `parent` for `modifier`') } return iterate(children, callback, parent) } }
[ "function", "iteratorFactory", "(", "callback", ")", "{", "return", "iterator", "function", "iterator", "(", "parent", ")", "{", "var", "children", "=", "parent", "&&", "parent", ".", "children", "if", "(", "!", "children", ")", "{", "throw", "new", "Error...
Turn `callback` into a `iterator' accepting a parent.
[ "Turn", "callback", "into", "a", "iterator", "accepting", "a", "parent", "." ]
ff6dd063db36a5df30f4585c27d74a58eb1e27fa
https://github.com/syntax-tree/unist-util-modify-children/blob/ff6dd063db36a5df30f4585c27d74a58eb1e27fa/index.js#L14-L26
30,195
canjs/worker-render
src/worker/handlers/initial.js
setIfPresent
function setIfPresent(docEl, nodeName){ var node = getBaseElement(docEl, nodeName); if(node) { document[nodeName] = node; } }
javascript
function setIfPresent(docEl, nodeName){ var node = getBaseElement(docEl, nodeName); if(node) { document[nodeName] = node; } }
[ "function", "setIfPresent", "(", "docEl", ",", "nodeName", ")", "{", "var", "node", "=", "getBaseElement", "(", "docEl", ",", "nodeName", ")", ";", "if", "(", "node", ")", "{", "document", "[", "nodeName", "]", "=", "node", ";", "}", "}" ]
Set the document.body and document.head properties.
[ "Set", "the", "document", ".", "body", "and", "document", ".", "head", "properties", "." ]
e36dbb886a8453bd9e4d4fc9f73a4bc84146d6e5
https://github.com/canjs/worker-render/blob/e36dbb886a8453bd9e4d4fc9f73a4bc84146d6e5/src/worker/handlers/initial.js#L40-L46
30,196
emmetio/markup-formatters
format/slim.js
updateFormatting
function updateFormatting(outNode, profile) { const node = outNode.node; const parent = node.parent; // Edge case: a single inline-level child inside node without text: // allow it to be inlined if (profile.get('inlineBreak') === 0 && isInline(node, profile) && !isRoot(parent) && parent.value == null && parent.children.length === 1) { outNode.beforeOpen = ': '; } if (!node.isTextOnly && node.value) { // node with text: put a space before single-line text outNode.beforeText = reNl.test(node.value) ? outNode.newline + outNode.indent + profile.indent(1) : ' '; } return outNode; }
javascript
function updateFormatting(outNode, profile) { const node = outNode.node; const parent = node.parent; // Edge case: a single inline-level child inside node without text: // allow it to be inlined if (profile.get('inlineBreak') === 0 && isInline(node, profile) && !isRoot(parent) && parent.value == null && parent.children.length === 1) { outNode.beforeOpen = ': '; } if (!node.isTextOnly && node.value) { // node with text: put a space before single-line text outNode.beforeText = reNl.test(node.value) ? outNode.newline + outNode.indent + profile.indent(1) : ' '; } return outNode; }
[ "function", "updateFormatting", "(", "outNode", ",", "profile", ")", "{", "const", "node", "=", "outNode", ".", "node", ";", "const", "parent", "=", "node", ".", "parent", ";", "// Edge case: a single inline-level child inside node without text:", "// allow it to be inl...
Updates formatting properties for given output node NB Unlike HTML, Slim is indent-based format so some formatting options from `profile` will not take effect, otherwise output will be broken @param {OutputNode} outNode Output wrapper of farsed abbreviation node @param {Profile} profile Output profile @return {OutputNode}
[ "Updates", "formatting", "properties", "for", "given", "output", "node", "NB", "Unlike", "HTML", "Slim", "is", "indent", "-", "based", "format", "so", "some", "formatting", "options", "from", "profile", "will", "not", "take", "effect", "otherwise", "output", "...
a9f93994fa5cb6aef6b0148b9ec485846fb4a338
https://github.com/emmetio/markup-formatters/blob/a9f93994fa5cb6aef6b0148b9ec485846fb4a338/format/slim.js#L72-L91
30,197
novacrazy/bluebird-co
benchmark/co/index.js
next
function next( ret ) { if( ret.done ) { return resolve( ret.value ); } var value = toPromise.call( ctx, ret.value ); if( value && isPromise( value ) ) { return value.then( onFulfilled, onRejected ); } return onRejected( new TypeError( 'You may only yield a function, promise, generator, array, or object, ' + 'but the following object was passed: "' + String( ret.value ) + '"' ) ); }
javascript
function next( ret ) { if( ret.done ) { return resolve( ret.value ); } var value = toPromise.call( ctx, ret.value ); if( value && isPromise( value ) ) { return value.then( onFulfilled, onRejected ); } return onRejected( new TypeError( 'You may only yield a function, promise, generator, array, or object, ' + 'but the following object was passed: "' + String( ret.value ) + '"' ) ); }
[ "function", "next", "(", "ret", ")", "{", "if", "(", "ret", ".", "done", ")", "{", "return", "resolve", "(", "ret", ".", "value", ")", ";", "}", "var", "value", "=", "toPromise", ".", "call", "(", "ctx", ",", "ret", ".", "value", ")", ";", "if"...
Get the next value in the generator, return a promise. @param {Object} ret @return {Promise} @api private
[ "Get", "the", "next", "value", "in", "the", "generator", "return", "a", "promise", "." ]
0f98755d326b99f8e3968308e4be43041ec5fde7
https://github.com/novacrazy/bluebird-co/blob/0f98755d326b99f8e3968308e4be43041ec5fde7/benchmark/co/index.js#L106-L117
30,198
novacrazy/bluebird-co
benchmark/co/index.js
toPromise
function toPromise( obj ) { if( !obj ) { return obj; } if( isPromise( obj ) ) { return obj; } if( isGeneratorFunction( obj ) || isGenerator( obj ) ) { return co.call( this, obj ); } if( 'function' == typeof obj ) { return thunkToPromise.call( this, obj ); } if( Array.isArray( obj ) ) { return arrayToPromise.call( this, obj ); } if( isObject( obj ) ) { return objectToPromise.call( this, obj ); } return obj; }
javascript
function toPromise( obj ) { if( !obj ) { return obj; } if( isPromise( obj ) ) { return obj; } if( isGeneratorFunction( obj ) || isGenerator( obj ) ) { return co.call( this, obj ); } if( 'function' == typeof obj ) { return thunkToPromise.call( this, obj ); } if( Array.isArray( obj ) ) { return arrayToPromise.call( this, obj ); } if( isObject( obj ) ) { return objectToPromise.call( this, obj ); } return obj; }
[ "function", "toPromise", "(", "obj", ")", "{", "if", "(", "!", "obj", ")", "{", "return", "obj", ";", "}", "if", "(", "isPromise", "(", "obj", ")", ")", "{", "return", "obj", ";", "}", "if", "(", "isGeneratorFunction", "(", "obj", ")", "||", "isG...
Convert a `yield`ed value into a promise. @param {Mixed} obj @return {Promise} @api private
[ "Convert", "a", "yield", "ed", "value", "into", "a", "promise", "." ]
0f98755d326b99f8e3968308e4be43041ec5fde7
https://github.com/novacrazy/bluebird-co/blob/0f98755d326b99f8e3968308e4be43041ec5fde7/benchmark/co/index.js#L129-L149
30,199
Jam3/ae-to-json
src/getEaseForKeyFrame.js
getEaseType
function getEaseType(type){ switch(type) { case KeyframeInterpolationType.BEZIER: return EASE_TYPE.BEZIER; break; case KeyframeInterpolationType.LINEAR: return EASE_TYPE.LINEAR; break; case KeyframeInterpolationType.HOLD: return EASE_TYPE.HOLD; break; default: throw new Error('unknown ease type'); break; } }
javascript
function getEaseType(type){ switch(type) { case KeyframeInterpolationType.BEZIER: return EASE_TYPE.BEZIER; break; case KeyframeInterpolationType.LINEAR: return EASE_TYPE.LINEAR; break; case KeyframeInterpolationType.HOLD: return EASE_TYPE.HOLD; break; default: throw new Error('unknown ease type'); break; } }
[ "function", "getEaseType", "(", "type", ")", "{", "switch", "(", "type", ")", "{", "case", "KeyframeInterpolationType", ".", "BEZIER", ":", "return", "EASE_TYPE", ".", "BEZIER", ";", "break", ";", "case", "KeyframeInterpolationType", ".", "LINEAR", ":", "retur...
get ease type
[ "get", "ease", "type" ]
9c7cf53287c90b9d3d7c72c302a076badf589758
https://github.com/Jam3/ae-to-json/blob/9c7cf53287c90b9d3d7c72c302a076badf589758/src/getEaseForKeyFrame.js#L30-L48