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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
57,400
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
function() { return { textNode: this.textNode, offset: this.offset, character: this.textNode ? this.textNode.getText().charAt( this.offset ) : null, hitMatchBoundary: this._.matchBoundary }; }
javascript
function() { return { textNode: this.textNode, offset: this.offset, character: this.textNode ? this.textNode.getText().charAt( this.offset ) : null, hitMatchBoundary: this._.matchBoundary }; }
[ "function", "(", ")", "{", "return", "{", "textNode", ":", "this", ".", "textNode", ",", "offset", ":", "this", ".", "offset", ",", "character", ":", "this", ".", "textNode", "?", "this", ".", "textNode", ".", "getText", "(", ")", ".", "charAt", "(", "this", ".", "offset", ")", ":", "null", ",", "hitMatchBoundary", ":", "this", ".", "_", ".", "matchBoundary", "}", ";", "}" ]
Get the cursor object which represent both current character and it's dom position thing.
[ "Get", "the", "cursor", "object", "which", "represent", "both", "current", "character", "and", "it", "s", "dom", "position", "thing", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L20-L27
57,401
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
syncFieldsBetweenTabs
function syncFieldsBetweenTabs( currentPageId ) { var sourceIndex, targetIndex, sourceField, targetField; sourceIndex = currentPageId === 'find' ? 1 : 0; targetIndex = 1 - sourceIndex; var i, l = fieldsMapping.length; for ( i = 0; i < l; i++ ) { sourceField = this.getContentElement( pages[ sourceIndex ], fieldsMapping[ i ][ sourceIndex ] ); targetField = this.getContentElement( pages[ targetIndex ], fieldsMapping[ i ][ targetIndex ] ); targetField.setValue( sourceField.getValue() ); } }
javascript
function syncFieldsBetweenTabs( currentPageId ) { var sourceIndex, targetIndex, sourceField, targetField; sourceIndex = currentPageId === 'find' ? 1 : 0; targetIndex = 1 - sourceIndex; var i, l = fieldsMapping.length; for ( i = 0; i < l; i++ ) { sourceField = this.getContentElement( pages[ sourceIndex ], fieldsMapping[ i ][ sourceIndex ] ); targetField = this.getContentElement( pages[ targetIndex ], fieldsMapping[ i ][ targetIndex ] ); targetField.setValue( sourceField.getValue() ); } }
[ "function", "syncFieldsBetweenTabs", "(", "currentPageId", ")", "{", "var", "sourceIndex", ",", "targetIndex", ",", "sourceField", ",", "targetField", ";", "sourceIndex", "=", "currentPageId", "===", "'find'", "?", "1", ":", "0", ";", "targetIndex", "=", "1", "-", "sourceIndex", ";", "var", "i", ",", "l", "=", "fieldsMapping", ".", "length", ";", "for", "(", "i", "=", "0", ";", "i", "<", "l", ";", "i", "++", ")", "{", "sourceField", "=", "this", ".", "getContentElement", "(", "pages", "[", "sourceIndex", "]", ",", "fieldsMapping", "[", "i", "]", "[", "sourceIndex", "]", ")", ";", "targetField", "=", "this", ".", "getContentElement", "(", "pages", "[", "targetIndex", "]", ",", "fieldsMapping", "[", "i", "]", "[", "targetIndex", "]", ")", ";", "targetField", ".", "setValue", "(", "sourceField", ".", "getValue", "(", ")", ")", ";", "}", "}" ]
Synchronize corresponding filed values between 'replace' and 'find' pages. @param {String} currentPageId The page id which receive values.
[ "Synchronize", "corresponding", "filed", "values", "between", "replace", "and", "find", "pages", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L38-L51
57,402
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
function( range, matchWord ) { var self = this; var walker = new CKEDITOR.dom.walker( range ); walker.guard = matchWord ? nonCharactersBoundary : function( node ) { !nonCharactersBoundary( node ) && ( self._.matchBoundary = true ); }; walker[ 'evaluator' ] = findEvaluator; walker.breakOnFalse = 1; if ( range.startContainer.type == CKEDITOR.NODE_TEXT ) { this.textNode = range.startContainer; this.offset = range.startOffset - 1; } this._ = { matchWord: matchWord, walker: walker, matchBoundary: false }; }
javascript
function( range, matchWord ) { var self = this; var walker = new CKEDITOR.dom.walker( range ); walker.guard = matchWord ? nonCharactersBoundary : function( node ) { !nonCharactersBoundary( node ) && ( self._.matchBoundary = true ); }; walker[ 'evaluator' ] = findEvaluator; walker.breakOnFalse = 1; if ( range.startContainer.type == CKEDITOR.NODE_TEXT ) { this.textNode = range.startContainer; this.offset = range.startOffset - 1; } this._ = { matchWord: matchWord, walker: walker, matchBoundary: false }; }
[ "function", "(", "range", ",", "matchWord", ")", "{", "var", "self", "=", "this", ";", "var", "walker", "=", "new", "CKEDITOR", ".", "dom", ".", "walker", "(", "range", ")", ";", "walker", ".", "guard", "=", "matchWord", "?", "nonCharactersBoundary", ":", "function", "(", "node", ")", "{", "!", "nonCharactersBoundary", "(", "node", ")", "&&", "(", "self", ".", "_", ".", "matchBoundary", "=", "true", ")", ";", "}", ";", "walker", "[", "'evaluator'", "]", "=", "findEvaluator", ";", "walker", ".", "breakOnFalse", "=", "1", ";", "if", "(", "range", ".", "startContainer", ".", "type", "==", "CKEDITOR", ".", "NODE_TEXT", ")", "{", "this", ".", "textNode", "=", "range", ".", "startContainer", ";", "this", ".", "offset", "=", "range", ".", "startOffset", "-", "1", ";", "}", "this", ".", "_", "=", "{", "matchWord", ":", "matchWord", ",", "walker", ":", "walker", ",", "matchBoundary", ":", "false", "}", ";", "}" ]
Iterator which walk through the specified range char by char. By default the walking will not stop at the character boundaries, until the end of the range is encountered. @param { CKEDITOR.dom.range } range @param {Boolean} matchWord Whether the walking will stop at character boundary.
[ "Iterator", "which", "walk", "through", "the", "specified", "range", "char", "by", "char", ".", "By", "default", "the", "walking", "will", "not", "stop", "at", "the", "character", "boundaries", "until", "the", "end", "of", "the", "range", "is", "encountered", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L68-L87
57,403
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
function( characterWalker, rangeLength ) { this._ = { walker: characterWalker, cursors: [], rangeLength: rangeLength, highlightRange: null, isMatched: 0 }; }
javascript
function( characterWalker, rangeLength ) { this._ = { walker: characterWalker, cursors: [], rangeLength: rangeLength, highlightRange: null, isMatched: 0 }; }
[ "function", "(", "characterWalker", ",", "rangeLength", ")", "{", "this", ".", "_", "=", "{", "walker", ":", "characterWalker", ",", "cursors", ":", "[", "]", ",", "rangeLength", ":", "rangeLength", ",", "highlightRange", ":", "null", ",", "isMatched", ":", "0", "}", ";", "}" ]
A range of cursors which represent a trunk of characters which try to match, it has the same length as the pattern string. **Note:** This class isn't accessible from global scope. @private @class CKEDITOR.plugins.find.characterRange @constructor Creates a characterRange class instance.
[ "A", "range", "of", "cursors", "which", "represent", "a", "trunk", "of", "characters", "which", "try", "to", "match", "it", "has", "the", "same", "length", "as", "the", "pattern", "string", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L147-L155
57,404
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
function( domRange ) { var cursor, walker = new characterWalker( domRange ); this._.cursors = []; do { cursor = walker.next(); if ( cursor.character ) this._.cursors.push( cursor ); } while ( cursor.character ); this._.rangeLength = this._.cursors.length; }
javascript
function( domRange ) { var cursor, walker = new characterWalker( domRange ); this._.cursors = []; do { cursor = walker.next(); if ( cursor.character ) this._.cursors.push( cursor ); } while ( cursor.character ); this._.rangeLength = this._.cursors.length; }
[ "function", "(", "domRange", ")", "{", "var", "cursor", ",", "walker", "=", "new", "characterWalker", "(", "domRange", ")", ";", "this", ".", "_", ".", "cursors", "=", "[", "]", ";", "do", "{", "cursor", "=", "walker", ".", "next", "(", ")", ";", "if", "(", "cursor", ".", "character", ")", "this", ".", "_", ".", "cursors", ".", "push", "(", "cursor", ")", ";", "}", "while", "(", "cursor", ".", "character", ")", ";", "this", ".", "_", ".", "rangeLength", "=", "this", ".", "_", ".", "cursors", ".", "length", ";", "}" ]
Reflect the latest changes from dom range.
[ "Reflect", "the", "latest", "changes", "from", "dom", "range", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L184-L194
57,405
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
function() { // Do not apply if nothing is found. if ( this._.cursors.length < 1 ) return; // Remove the previous highlight if there's one. if ( this._.highlightRange ) this.removeHighlight(); // Apply the highlight. var range = this.toDomRange(), bookmark = range.createBookmark(); highlightStyle.applyToRange( range, editor ); range.moveToBookmark( bookmark ); this._.highlightRange = range; // Scroll the editor to the highlighted area. var element = range.startContainer; if ( element.type != CKEDITOR.NODE_ELEMENT ) element = element.getParent(); element.scrollIntoView(); // Update the character cursors. this.updateFromDomRange( range ); }
javascript
function() { // Do not apply if nothing is found. if ( this._.cursors.length < 1 ) return; // Remove the previous highlight if there's one. if ( this._.highlightRange ) this.removeHighlight(); // Apply the highlight. var range = this.toDomRange(), bookmark = range.createBookmark(); highlightStyle.applyToRange( range, editor ); range.moveToBookmark( bookmark ); this._.highlightRange = range; // Scroll the editor to the highlighted area. var element = range.startContainer; if ( element.type != CKEDITOR.NODE_ELEMENT ) element = element.getParent(); element.scrollIntoView(); // Update the character cursors. this.updateFromDomRange( range ); }
[ "function", "(", ")", "{", "// Do not apply if nothing is found.\r", "if", "(", "this", ".", "_", ".", "cursors", ".", "length", "<", "1", ")", "return", ";", "// Remove the previous highlight if there's one.\r", "if", "(", "this", ".", "_", ".", "highlightRange", ")", "this", ".", "removeHighlight", "(", ")", ";", "// Apply the highlight.\r", "var", "range", "=", "this", ".", "toDomRange", "(", ")", ",", "bookmark", "=", "range", ".", "createBookmark", "(", ")", ";", "highlightStyle", ".", "applyToRange", "(", "range", ",", "editor", ")", ";", "range", ".", "moveToBookmark", "(", "bookmark", ")", ";", "this", ".", "_", ".", "highlightRange", "=", "range", ";", "// Scroll the editor to the highlighted area.\r", "var", "element", "=", "range", ".", "startContainer", ";", "if", "(", "element", ".", "type", "!=", "CKEDITOR", ".", "NODE_ELEMENT", ")", "element", "=", "element", ".", "getParent", "(", ")", ";", "element", ".", "scrollIntoView", "(", ")", ";", "// Update the character cursors.\r", "this", ".", "updateFromDomRange", "(", "range", ")", ";", "}" ]
Hightlight the current matched chunk of text.
[ "Hightlight", "the", "current", "matched", "chunk", "of", "text", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L211-L235
57,406
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
function() { if ( !this._.highlightRange ) return; var bookmark = this._.highlightRange.createBookmark(); highlightStyle.removeFromRange( this._.highlightRange, editor ); this._.highlightRange.moveToBookmark( bookmark ); this.updateFromDomRange( this._.highlightRange ); this._.highlightRange = null; }
javascript
function() { if ( !this._.highlightRange ) return; var bookmark = this._.highlightRange.createBookmark(); highlightStyle.removeFromRange( this._.highlightRange, editor ); this._.highlightRange.moveToBookmark( bookmark ); this.updateFromDomRange( this._.highlightRange ); this._.highlightRange = null; }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "_", ".", "highlightRange", ")", "return", ";", "var", "bookmark", "=", "this", ".", "_", ".", "highlightRange", ".", "createBookmark", "(", ")", ";", "highlightStyle", ".", "removeFromRange", "(", "this", ".", "_", ".", "highlightRange", ",", "editor", ")", ";", "this", ".", "_", ".", "highlightRange", ".", "moveToBookmark", "(", "bookmark", ")", ";", "this", ".", "updateFromDomRange", "(", "this", ".", "_", ".", "highlightRange", ")", ";", "this", ".", "_", ".", "highlightRange", "=", "null", ";", "}" ]
Remove highlighted find result.
[ "Remove", "highlighted", "find", "result", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L240-L249
57,407
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
getRangeAfterCursor
function getRangeAfterCursor( cursor, inclusive ) { var range = editor.createRange(); range.setStart( cursor.textNode, ( inclusive ? cursor.offset : cursor.offset + 1 ) ); range.setEndAt( editor.editable(), CKEDITOR.POSITION_BEFORE_END ); return range; }
javascript
function getRangeAfterCursor( cursor, inclusive ) { var range = editor.createRange(); range.setStart( cursor.textNode, ( inclusive ? cursor.offset : cursor.offset + 1 ) ); range.setEndAt( editor.editable(), CKEDITOR.POSITION_BEFORE_END ); return range; }
[ "function", "getRangeAfterCursor", "(", "cursor", ",", "inclusive", ")", "{", "var", "range", "=", "editor", ".", "createRange", "(", ")", ";", "range", ".", "setStart", "(", "cursor", ".", "textNode", ",", "(", "inclusive", "?", "cursor", ".", "offset", ":", "cursor", ".", "offset", "+", "1", ")", ")", ";", "range", ".", "setEndAt", "(", "editor", ".", "editable", "(", ")", ",", "CKEDITOR", ".", "POSITION_BEFORE_END", ")", ";", "return", "range", ";", "}" ]
The remaining document range after the character cursor.
[ "The", "remaining", "document", "range", "after", "the", "character", "cursor", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L315-L320
57,408
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
getRangeBeforeCursor
function getRangeBeforeCursor( cursor ) { var range = editor.createRange(); range.setStartAt( editor.editable(), CKEDITOR.POSITION_AFTER_START ); range.setEnd( cursor.textNode, cursor.offset ); return range; }
javascript
function getRangeBeforeCursor( cursor ) { var range = editor.createRange(); range.setStartAt( editor.editable(), CKEDITOR.POSITION_AFTER_START ); range.setEnd( cursor.textNode, cursor.offset ); return range; }
[ "function", "getRangeBeforeCursor", "(", "cursor", ")", "{", "var", "range", "=", "editor", ".", "createRange", "(", ")", ";", "range", ".", "setStartAt", "(", "editor", ".", "editable", "(", ")", ",", "CKEDITOR", ".", "POSITION_AFTER_START", ")", ";", "range", ".", "setEnd", "(", "cursor", ".", "textNode", ",", "cursor", ".", "offset", ")", ";", "return", "range", ";", "}" ]
The document range before the character cursor.
[ "The", "document", "range", "before", "the", "character", "cursor", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L323-L328
57,409
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
function( pattern, ignoreCase ) { var overlap = [ -1 ]; if ( ignoreCase ) pattern = pattern.toLowerCase(); for ( var i = 0; i < pattern.length; i++ ) { overlap.push( overlap[ i ] + 1 ); while ( overlap[ i + 1 ] > 0 && pattern.charAt( i ) != pattern.charAt( overlap[ i + 1 ] - 1 ) ) overlap[ i + 1 ] = overlap[ overlap[ i + 1 ] - 1 ] + 1; } this._ = { overlap: overlap, state: 0, ignoreCase: !!ignoreCase, pattern: pattern }; }
javascript
function( pattern, ignoreCase ) { var overlap = [ -1 ]; if ( ignoreCase ) pattern = pattern.toLowerCase(); for ( var i = 0; i < pattern.length; i++ ) { overlap.push( overlap[ i ] + 1 ); while ( overlap[ i + 1 ] > 0 && pattern.charAt( i ) != pattern.charAt( overlap[ i + 1 ] - 1 ) ) overlap[ i + 1 ] = overlap[ overlap[ i + 1 ] - 1 ] + 1; } this._ = { overlap: overlap, state: 0, ignoreCase: !!ignoreCase, pattern: pattern }; }
[ "function", "(", "pattern", ",", "ignoreCase", ")", "{", "var", "overlap", "=", "[", "-", "1", "]", ";", "if", "(", "ignoreCase", ")", "pattern", "=", "pattern", ".", "toLowerCase", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "pattern", ".", "length", ";", "i", "++", ")", "{", "overlap", ".", "push", "(", "overlap", "[", "i", "]", "+", "1", ")", ";", "while", "(", "overlap", "[", "i", "+", "1", "]", ">", "0", "&&", "pattern", ".", "charAt", "(", "i", ")", "!=", "pattern", ".", "charAt", "(", "overlap", "[", "i", "+", "1", "]", "-", "1", ")", ")", "overlap", "[", "i", "+", "1", "]", "=", "overlap", "[", "overlap", "[", "i", "+", "1", "]", "-", "1", "]", "+", "1", ";", "}", "this", ".", "_", "=", "{", "overlap", ":", "overlap", ",", "state", ":", "0", ",", "ignoreCase", ":", "!", "!", "ignoreCase", ",", "pattern", ":", "pattern", "}", ";", "}" ]
Examination the occurrence of a word which implement KMP algorithm.
[ "Examination", "the", "occurrence", "of", "a", "word", "which", "implement", "KMP", "algorithm", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L335-L351
57,410
ultraq/dumb-query-selector
dumb-query-selector.js
function(query, scope) { return Array.prototype.slice.call((scope || document).querySelectorAll(query)); }
javascript
function(query, scope) { return Array.prototype.slice.call((scope || document).querySelectorAll(query)); }
[ "function", "(", "query", ",", "scope", ")", "{", "return", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "(", "scope", "||", "document", ")", ".", "querySelectorAll", "(", "query", ")", ")", ";", "}" ]
An element list selector, returning an array of elements because `NodeList`s are dumb. @param {String} query @param {Node} [scope=document] The scope to limit the search to for non-ID queries. Defaults to `document` scope. @return {Array} The list of matching elements.
[ "An", "element", "list", "selector", "returning", "an", "array", "of", "elements", "because", "NodeList", "s", "are", "dumb", "." ]
f4af7d4d7e5ef364ea455ad538c4ae1acde24bba
https://github.com/ultraq/dumb-query-selector/blob/f4af7d4d7e5ef364ea455ad538c4ae1acde24bba/dumb-query-selector.js#L62-L64
57,411
mairatma/es6-imports-renamer
lib/ES6ImportsRenamer.js
ES6ImportsRenamer
function ES6ImportsRenamer(config, callback) { config = config || {}; this._basePath = config.basePath; this._renameDependencies = config.renameDependencies; this._renameFn = config.renameFn; this._callback = callback; this._addedMap = {}; this._initStack(config.sources || []); this._renameNextAst(); }
javascript
function ES6ImportsRenamer(config, callback) { config = config || {}; this._basePath = config.basePath; this._renameDependencies = config.renameDependencies; this._renameFn = config.renameFn; this._callback = callback; this._addedMap = {}; this._initStack(config.sources || []); this._renameNextAst(); }
[ "function", "ES6ImportsRenamer", "(", "config", ",", "callback", ")", "{", "config", "=", "config", "||", "{", "}", ";", "this", ".", "_basePath", "=", "config", ".", "basePath", ";", "this", ".", "_renameDependencies", "=", "config", ".", "renameDependencies", ";", "this", ".", "_renameFn", "=", "config", ".", "renameFn", ";", "this", ".", "_callback", "=", "callback", ";", "this", ".", "_addedMap", "=", "{", "}", ";", "this", ".", "_initStack", "(", "config", ".", "sources", "||", "[", "]", ")", ";", "this", ".", "_renameNextAst", "(", ")", ";", "}" ]
Class responsible for renaming import paths present in both the given source files and their dependencies, according to the given rename function. @param {{sources: !Array<{ast: !Object, path: string}>, basePath: ?string}} config @param {function(Error, Array)} callback Function to be called when the renaming is done. @constructor
[ "Class", "responsible", "for", "renaming", "import", "paths", "present", "in", "both", "the", "given", "source", "files", "and", "their", "dependencies", "according", "to", "the", "given", "rename", "function", "." ]
ad03988f485ad4b116ce2fcad54200aca3edb67e
https://github.com/mairatma/es6-imports-renamer/blob/ad03988f485ad4b116ce2fcad54200aca3edb67e/lib/ES6ImportsRenamer.js#L17-L28
57,412
jamestalmage/firebase-copy
index.js
createRequireFunc
function createRequireFunc(customResolver) { return function (requestedPath) { var resolvedPath = null; try { resolvedPath = resolve.sync(requestedPath, {basedir: FIRBASE_DIR}); } catch (e) {} return customResolver(requestedPath, resolvedPath); }; }
javascript
function createRequireFunc(customResolver) { return function (requestedPath) { var resolvedPath = null; try { resolvedPath = resolve.sync(requestedPath, {basedir: FIRBASE_DIR}); } catch (e) {} return customResolver(requestedPath, resolvedPath); }; }
[ "function", "createRequireFunc", "(", "customResolver", ")", "{", "return", "function", "(", "requestedPath", ")", "{", "var", "resolvedPath", "=", "null", ";", "try", "{", "resolvedPath", "=", "resolve", ".", "sync", "(", "requestedPath", ",", "{", "basedir", ":", "FIRBASE_DIR", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "return", "customResolver", "(", "requestedPath", ",", "resolvedPath", ")", ";", "}", ";", "}" ]
eslint-disable-line no-new-func
[ "eslint", "-", "disable", "-", "line", "no", "-", "new", "-", "func" ]
e876693afa6d5ec0c40a95c4314a113e3432aa75
https://github.com/jamestalmage/firebase-copy/blob/e876693afa6d5ec0c40a95c4314a113e3432aa75/index.js#L9-L17
57,413
dennismckinnon/tmsp-server
lib/server.js
runNextRequest
function runNextRequest(){ var self = this; var req = parser.read() if (req){ var res = new Response(req); res.assignSocket(socket) //No matter how the response object gets closed this //will trigger the next one if there is one. res.once('close', function(){ //Check if there is work. if(self.work){ runNextRequest.call(self) } else { //Let the system know that you have stopped working self.working = false; } }); this.emit('request', req, res); } }
javascript
function runNextRequest(){ var self = this; var req = parser.read() if (req){ var res = new Response(req); res.assignSocket(socket) //No matter how the response object gets closed this //will trigger the next one if there is one. res.once('close', function(){ //Check if there is work. if(self.work){ runNextRequest.call(self) } else { //Let the system know that you have stopped working self.working = false; } }); this.emit('request', req, res); } }
[ "function", "runNextRequest", "(", ")", "{", "var", "self", "=", "this", ";", "var", "req", "=", "parser", ".", "read", "(", ")", "if", "(", "req", ")", "{", "var", "res", "=", "new", "Response", "(", "req", ")", ";", "res", ".", "assignSocket", "(", "socket", ")", "//No matter how the response object gets closed this", "//will trigger the next one if there is one.", "res", ".", "once", "(", "'close'", ",", "function", "(", ")", "{", "//Check if there is work.", "if", "(", "self", ".", "work", ")", "{", "runNextRequest", ".", "call", "(", "self", ")", "}", "else", "{", "//Let the system know that you have stopped working", "self", ".", "working", "=", "false", ";", "}", "}", ")", ";", "this", ".", "emit", "(", "'request'", ",", "req", ",", "res", ")", ";", "}", "}" ]
This is the request processor loop using events to trigger the next request in the Queue.
[ "This", "is", "the", "request", "processor", "loop", "using", "events", "to", "trigger", "the", "next", "request", "in", "the", "Queue", "." ]
24d054c5a3eeacc6552645a2e3a7ed353112b171
https://github.com/dennismckinnon/tmsp-server/blob/24d054c5a3eeacc6552645a2e3a7ed353112b171/lib/server.js#L85-L107
57,414
leowang721/k-core
util.js
rand16Num
function rand16Num(len) { let result = []; for (let i = 0; i < len; i++) { result.push('0123456789abcdef'.charAt( Math.floor(Math.random() * 16)) ); } return result.join(''); }
javascript
function rand16Num(len) { let result = []; for (let i = 0; i < len; i++) { result.push('0123456789abcdef'.charAt( Math.floor(Math.random() * 16)) ); } return result.join(''); }
[ "function", "rand16Num", "(", "len", ")", "{", "let", "result", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "result", ".", "push", "(", "'0123456789abcdef'", ".", "charAt", "(", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "16", ")", ")", ")", ";", "}", "return", "result", ".", "join", "(", "''", ")", ";", "}" ]
Generates a random GUID legal string of the given length. @param {number} len 要生成串的长度 @return {string} 指定长度的16进制数随机串
[ "Generates", "a", "random", "GUID", "legal", "string", "of", "the", "given", "length", "." ]
582a526b43856d8e0312dd5fe1e617b19db4861d
https://github.com/leowang721/k-core/blob/582a526b43856d8e0312dd5fe1e617b19db4861d/util.js#L16-L24
57,415
valerii-zinchenko/class-wrapper
lib/ClassBuilder.js
ClassBuilder
function ClassBuilder(InstanceBuilder, Parent, Constructor, props) { // Last input argument is an object of properties for a new class props = arguments[arguments.length - 1]; // Second last input argument is a constructor function Constructor = arguments[arguments.length - 2]; // Set default Parent class if it is not provided if (arguments.length === 3) { Parent = Object; } // Validate input arguments // -------------------------------------------------- if (arguments.length < 3 || typeof InstanceBuilder !== 'function' || Object.prototype.toString.call(Parent) !== '[object Function]' || (Constructor !== null && typeof Constructor !== 'function') || Object.prototype.toString.call(props) !== '[object Object]') { throw new Error('Incorrect input arguments. It should be: ClassBuilder(Function, [Function], Function | null, Object)'); } // -------------------------------------------------- // Extract class name if defined // -------------------------------------------------- var className = ''; if (typeof props.__name === 'string' && props.__name) { className = props.__name; } delete props.__name; // -------------------------------------------------- // Prepare an array of what is going to be encapsulated into a new class // -------------------------------------------------- var encapsulations = []; // Collect objects properties and methods if (props.Encapsulate) { if (Object.prototype.toString.call(props.Encapsulate) === '[object Array]') { encapsulations = encapsulations.concat(props.Encapsulate); } else { encapsulations.push(props.Encapsulate); } // Remove "Encapsulate" property, because it is not need to be encapsulated delete props.Encapsulate; } // Put parent's defaults into an encapsulation stack if (Parent.prototype.__defaults) { encapsulations.unshift(Parent.prototype.__defaults); } // Put properties and methods for a new class into the encapsulation stack encapsulations.push(props); // Validate what is going to be encapsulated if (encapsulations.some(function(item) { var type = Object.prototype.toString.call(item); return type !== '[object Function]' && type !== '[object Object]'; })) { throw new Error('Some of the items for encapsulation is incorrect. An item can be: Object, Function, Class'); } // -------------------------------------------------- // Clone class constructor function to prevent a sharing of instance builder function // -------------------------------------------------- var Class; var declaration = className ? 'var ' + className + '; Class = ' + className + ' = ' : 'Class = '; eval(declaration + InstanceBuilder.toString()); // -------------------------------------------------- // Inheritance chain // -------------------------------------------------- // Derive a new class from a Parent class Class.prototype = Object.create(Parent.prototype); // Revert back the reference to the instance builder function Class.prototype.constructor = Class; // Store the reference to the constructor function if (Constructor) { Class.prototype.__constructor = Constructor; } // Create a storage for default properties Class.prototype.__defaults = {}; // Store a reference to a parent's prototype object for internal usage Class.__parent = Parent.prototype; // -------------------------------------------------- // Encapsulate properties and methods // -------------------------------------------------- for (var n = 0, N = encapsulations.length; n < N; n++) { ClassBuilder.encapsulate(encapsulations[n], Class); } // -------------------------------------------------- return Class; }
javascript
function ClassBuilder(InstanceBuilder, Parent, Constructor, props) { // Last input argument is an object of properties for a new class props = arguments[arguments.length - 1]; // Second last input argument is a constructor function Constructor = arguments[arguments.length - 2]; // Set default Parent class if it is not provided if (arguments.length === 3) { Parent = Object; } // Validate input arguments // -------------------------------------------------- if (arguments.length < 3 || typeof InstanceBuilder !== 'function' || Object.prototype.toString.call(Parent) !== '[object Function]' || (Constructor !== null && typeof Constructor !== 'function') || Object.prototype.toString.call(props) !== '[object Object]') { throw new Error('Incorrect input arguments. It should be: ClassBuilder(Function, [Function], Function | null, Object)'); } // -------------------------------------------------- // Extract class name if defined // -------------------------------------------------- var className = ''; if (typeof props.__name === 'string' && props.__name) { className = props.__name; } delete props.__name; // -------------------------------------------------- // Prepare an array of what is going to be encapsulated into a new class // -------------------------------------------------- var encapsulations = []; // Collect objects properties and methods if (props.Encapsulate) { if (Object.prototype.toString.call(props.Encapsulate) === '[object Array]') { encapsulations = encapsulations.concat(props.Encapsulate); } else { encapsulations.push(props.Encapsulate); } // Remove "Encapsulate" property, because it is not need to be encapsulated delete props.Encapsulate; } // Put parent's defaults into an encapsulation stack if (Parent.prototype.__defaults) { encapsulations.unshift(Parent.prototype.__defaults); } // Put properties and methods for a new class into the encapsulation stack encapsulations.push(props); // Validate what is going to be encapsulated if (encapsulations.some(function(item) { var type = Object.prototype.toString.call(item); return type !== '[object Function]' && type !== '[object Object]'; })) { throw new Error('Some of the items for encapsulation is incorrect. An item can be: Object, Function, Class'); } // -------------------------------------------------- // Clone class constructor function to prevent a sharing of instance builder function // -------------------------------------------------- var Class; var declaration = className ? 'var ' + className + '; Class = ' + className + ' = ' : 'Class = '; eval(declaration + InstanceBuilder.toString()); // -------------------------------------------------- // Inheritance chain // -------------------------------------------------- // Derive a new class from a Parent class Class.prototype = Object.create(Parent.prototype); // Revert back the reference to the instance builder function Class.prototype.constructor = Class; // Store the reference to the constructor function if (Constructor) { Class.prototype.__constructor = Constructor; } // Create a storage for default properties Class.prototype.__defaults = {}; // Store a reference to a parent's prototype object for internal usage Class.__parent = Parent.prototype; // -------------------------------------------------- // Encapsulate properties and methods // -------------------------------------------------- for (var n = 0, N = encapsulations.length; n < N; n++) { ClassBuilder.encapsulate(encapsulations[n], Class); } // -------------------------------------------------- return Class; }
[ "function", "ClassBuilder", "(", "InstanceBuilder", ",", "Parent", ",", "Constructor", ",", "props", ")", "{", "// Last input argument is an object of properties for a new class", "props", "=", "arguments", "[", "arguments", ".", "length", "-", "1", "]", ";", "// Second last input argument is a constructor function", "Constructor", "=", "arguments", "[", "arguments", ".", "length", "-", "2", "]", ";", "// Set default Parent class if it is not provided", "if", "(", "arguments", ".", "length", "===", "3", ")", "{", "Parent", "=", "Object", ";", "}", "// Validate input arguments", "// --------------------------------------------------", "if", "(", "arguments", ".", "length", "<", "3", "||", "typeof", "InstanceBuilder", "!==", "'function'", "||", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "Parent", ")", "!==", "'[object Function]'", "||", "(", "Constructor", "!==", "null", "&&", "typeof", "Constructor", "!==", "'function'", ")", "||", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "props", ")", "!==", "'[object Object]'", ")", "{", "throw", "new", "Error", "(", "'Incorrect input arguments. It should be: ClassBuilder(Function, [Function], Function | null, Object)'", ")", ";", "}", "// --------------------------------------------------", "// Extract class name if defined", "// --------------------------------------------------", "var", "className", "=", "''", ";", "if", "(", "typeof", "props", ".", "__name", "===", "'string'", "&&", "props", ".", "__name", ")", "{", "className", "=", "props", ".", "__name", ";", "}", "delete", "props", ".", "__name", ";", "// --------------------------------------------------", "// Prepare an array of what is going to be encapsulated into a new class", "// --------------------------------------------------", "var", "encapsulations", "=", "[", "]", ";", "// Collect objects properties and methods", "if", "(", "props", ".", "Encapsulate", ")", "{", "if", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "props", ".", "Encapsulate", ")", "===", "'[object Array]'", ")", "{", "encapsulations", "=", "encapsulations", ".", "concat", "(", "props", ".", "Encapsulate", ")", ";", "}", "else", "{", "encapsulations", ".", "push", "(", "props", ".", "Encapsulate", ")", ";", "}", "// Remove \"Encapsulate\" property, because it is not need to be encapsulated", "delete", "props", ".", "Encapsulate", ";", "}", "// Put parent's defaults into an encapsulation stack", "if", "(", "Parent", ".", "prototype", ".", "__defaults", ")", "{", "encapsulations", ".", "unshift", "(", "Parent", ".", "prototype", ".", "__defaults", ")", ";", "}", "// Put properties and methods for a new class into the encapsulation stack", "encapsulations", ".", "push", "(", "props", ")", ";", "// Validate what is going to be encapsulated", "if", "(", "encapsulations", ".", "some", "(", "function", "(", "item", ")", "{", "var", "type", "=", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "item", ")", ";", "return", "type", "!==", "'[object Function]'", "&&", "type", "!==", "'[object Object]'", ";", "}", ")", ")", "{", "throw", "new", "Error", "(", "'Some of the items for encapsulation is incorrect. An item can be: Object, Function, Class'", ")", ";", "}", "// --------------------------------------------------", "// Clone class constructor function to prevent a sharing of instance builder function", "// --------------------------------------------------", "var", "Class", ";", "var", "declaration", "=", "className", "?", "'var '", "+", "className", "+", "'; Class = '", "+", "className", "+", "' = '", ":", "'Class = '", ";", "eval", "(", "declaration", "+", "InstanceBuilder", ".", "toString", "(", ")", ")", ";", "// --------------------------------------------------", "// Inheritance chain", "// --------------------------------------------------", "// Derive a new class from a Parent class", "Class", ".", "prototype", "=", "Object", ".", "create", "(", "Parent", ".", "prototype", ")", ";", "// Revert back the reference to the instance builder function", "Class", ".", "prototype", ".", "constructor", "=", "Class", ";", "// Store the reference to the constructor function", "if", "(", "Constructor", ")", "{", "Class", ".", "prototype", ".", "__constructor", "=", "Constructor", ";", "}", "// Create a storage for default properties", "Class", ".", "prototype", ".", "__defaults", "=", "{", "}", ";", "// Store a reference to a parent's prototype object for internal usage", "Class", ".", "__parent", "=", "Parent", ".", "prototype", ";", "// --------------------------------------------------", "// Encapsulate properties and methods", "// --------------------------------------------------", "for", "(", "var", "n", "=", "0", ",", "N", "=", "encapsulations", ".", "length", ";", "n", "<", "N", ";", "n", "++", ")", "{", "ClassBuilder", ".", "encapsulate", "(", "encapsulations", "[", "n", "]", ",", "Class", ")", ";", "}", "// --------------------------------------------------", "return", "Class", ";", "}" ]
Main class builder. It takes the constructor function and wraps it to add few automated processes for constructing a new class. Properties and features: - set the parent class - save the inheritance chain - define the classes/functions/objects that are going to be encapsulated into the resulting class. The last encapsulated object will have a precedence over the previous objects, even parent class. Only the own properties of the new class will have the highest precedence - the reference to the parent class is stored in 'parent' property - inherited methods are stored in class prototype object - store default class properties in '__default' object where the objects will be copied, not shared @see {@link Class} @see {@link SingletonClass} @throws {Error} Incorrect input arguments. It should be: ClassBuilder(Function, [Function], Function | null, Object) @throws {Error} Some of the items for encapsulation is incorrect. An item can be: Object, Function, Class @param {Function} InstanceBuilder - Function that defines how instances will be created, how constructor(s) will be executed @param {Function} [Parent = Object] - Parent class @param {Function | null} Constructor - Constructor function @param {Object} props - Object of properties and methods for a new class. Property names that are used internally and will be ignored by encapsulation: - __constructor - __parent If some of the object has "__defaults" object, then all of it's properties will be treated as an object of default properties that a new class should have. @param {Object | Function | Class | Array} [props.Encapsulate] - Define which object/function/class or an array of objects/functions/classes should be encapsulated into the new class @param {String} [props.__name = "Class"] - Specify the class name what will be visible near the variables during the debugging. @returns {Function} Class
[ "Main", "class", "builder", ".", "It", "takes", "the", "constructor", "function", "and", "wraps", "it", "to", "add", "few", "automated", "processes", "for", "constructing", "a", "new", "class", "." ]
b9f71c5a64eb023abca6d9d8f80c0c713d85e15d
https://github.com/valerii-zinchenko/class-wrapper/blob/b9f71c5a64eb023abca6d9d8f80c0c713d85e15d/lib/ClassBuilder.js#L50-L156
57,416
hmapjs/hmap-parser
index.js
function() { var block = this.emptyBlock(0); while ('eos' != this.peek().type) { if ('newline' == this.peek().type) { this.advance(); } else if ('text-html' == this.peek().type) { block.nodes = block.nodes.concat(this.parseTextHtml()); } else { var expr = this.parseExpr(); if (expr) block.nodes.push(expr); } } return block; }
javascript
function() { var block = this.emptyBlock(0); while ('eos' != this.peek().type) { if ('newline' == this.peek().type) { this.advance(); } else if ('text-html' == this.peek().type) { block.nodes = block.nodes.concat(this.parseTextHtml()); } else { var expr = this.parseExpr(); if (expr) block.nodes.push(expr); } } return block; }
[ "function", "(", ")", "{", "var", "block", "=", "this", ".", "emptyBlock", "(", "0", ")", ";", "while", "(", "'eos'", "!=", "this", ".", "peek", "(", ")", ".", "type", ")", "{", "if", "(", "'newline'", "==", "this", ".", "peek", "(", ")", ".", "type", ")", "{", "this", ".", "advance", "(", ")", ";", "}", "else", "if", "(", "'text-html'", "==", "this", ".", "peek", "(", ")", ".", "type", ")", "{", "block", ".", "nodes", "=", "block", ".", "nodes", ".", "concat", "(", "this", ".", "parseTextHtml", "(", ")", ")", ";", "}", "else", "{", "var", "expr", "=", "this", ".", "parseExpr", "(", ")", ";", "if", "(", "expr", ")", "block", ".", "nodes", ".", "push", "(", "expr", ")", ";", "}", "}", "return", "block", ";", "}" ]
Parse input returning a string of js for evaluation. @return {String} @api public
[ "Parse", "input", "returning", "a", "string", "of", "js", "for", "evaluation", "." ]
6d7f38dc66d95246c1f8f271ab88e858f17bd1f5
https://github.com/hmapjs/hmap-parser/blob/6d7f38dc66d95246c1f8f271ab88e858f17bd1f5/index.js#L103-L119
57,417
hmapjs/hmap-parser
index.js
function() { var tok = this.expect('filter'); var block, attrs = []; if (this.peek().type === 'start-attributes') { attrs = this.attrs(); } if (this.peek().type === 'text') { var textToken = this.advance(); block = this.initBlock(textToken.line, [ { type: 'Text', val: textToken.val, line: textToken.line, filename: this.filename } ]); } else if (this.peek().type === 'filter') { block = this.initBlock(tok.line, [this.parseFilter()]); } else { block = this.parseTextBlock() || this.emptyBlock(tok.line); } return { type: 'Filter', name: tok.val, block: block, attrs: attrs, line: tok.line, filename: this.filename }; }
javascript
function() { var tok = this.expect('filter'); var block, attrs = []; if (this.peek().type === 'start-attributes') { attrs = this.attrs(); } if (this.peek().type === 'text') { var textToken = this.advance(); block = this.initBlock(textToken.line, [ { type: 'Text', val: textToken.val, line: textToken.line, filename: this.filename } ]); } else if (this.peek().type === 'filter') { block = this.initBlock(tok.line, [this.parseFilter()]); } else { block = this.parseTextBlock() || this.emptyBlock(tok.line); } return { type: 'Filter', name: tok.val, block: block, attrs: attrs, line: tok.line, filename: this.filename }; }
[ "function", "(", ")", "{", "var", "tok", "=", "this", ".", "expect", "(", "'filter'", ")", ";", "var", "block", ",", "attrs", "=", "[", "]", ";", "if", "(", "this", ".", "peek", "(", ")", ".", "type", "===", "'start-attributes'", ")", "{", "attrs", "=", "this", ".", "attrs", "(", ")", ";", "}", "if", "(", "this", ".", "peek", "(", ")", ".", "type", "===", "'text'", ")", "{", "var", "textToken", "=", "this", ".", "advance", "(", ")", ";", "block", "=", "this", ".", "initBlock", "(", "textToken", ".", "line", ",", "[", "{", "type", ":", "'Text'", ",", "val", ":", "textToken", ".", "val", ",", "line", ":", "textToken", ".", "line", ",", "filename", ":", "this", ".", "filename", "}", "]", ")", ";", "}", "else", "if", "(", "this", ".", "peek", "(", ")", ".", "type", "===", "'filter'", ")", "{", "block", "=", "this", ".", "initBlock", "(", "tok", ".", "line", ",", "[", "this", ".", "parseFilter", "(", ")", "]", ")", ";", "}", "else", "{", "block", "=", "this", ".", "parseTextBlock", "(", ")", "||", "this", ".", "emptyBlock", "(", "tok", ".", "line", ")", ";", "}", "return", "{", "type", ":", "'Filter'", ",", "name", ":", "tok", ".", "val", ",", "block", ":", "block", ",", "attrs", ":", "attrs", ",", "line", ":", "tok", ".", "line", ",", "filename", ":", "this", ".", "filename", "}", ";", "}" ]
filter attrs? text-block
[ "filter", "attrs?", "text", "-", "block" ]
6d7f38dc66d95246c1f8f271ab88e858f17bd1f5
https://github.com/hmapjs/hmap-parser/blob/6d7f38dc66d95246c1f8f271ab88e858f17bd1f5/index.js#L645-L678
57,418
hmapjs/hmap-parser
index.js
function() { var tok = this.expect('block'); var node = 'indent' == this.peek().type ? this.block() : this.emptyBlock(tok.line); node.type = 'NamedBlock'; node.name = tok.val.trim(); node.mode = tok.mode; node.line = tok.line; return node; }
javascript
function() { var tok = this.expect('block'); var node = 'indent' == this.peek().type ? this.block() : this.emptyBlock(tok.line); node.type = 'NamedBlock'; node.name = tok.val.trim(); node.mode = tok.mode; node.line = tok.line; return node; }
[ "function", "(", ")", "{", "var", "tok", "=", "this", ".", "expect", "(", "'block'", ")", ";", "var", "node", "=", "'indent'", "==", "this", ".", "peek", "(", ")", ".", "type", "?", "this", ".", "block", "(", ")", ":", "this", ".", "emptyBlock", "(", "tok", ".", "line", ")", ";", "node", ".", "type", "=", "'NamedBlock'", ";", "node", ".", "name", "=", "tok", ".", "val", ".", "trim", "(", ")", ";", "node", ".", "mode", "=", "tok", ".", "mode", ";", "node", ".", "line", "=", "tok", ".", "line", ";", "return", "node", ";", "}" ]
'block' name block
[ "block", "name", "block" ]
6d7f38dc66d95246c1f8f271ab88e858f17bd1f5
https://github.com/hmapjs/hmap-parser/blob/6d7f38dc66d95246c1f8f271ab88e858f17bd1f5/index.js#L726-L738
57,419
fabioricali/stringme
index.js
Stringme
function Stringme(val, opt) { if (val === undefined) { val = '"undefined"'; } else if (val === null) { val = '"null"'; } else { var replace = opt && opt.replace ? opt.replace : null; var space = opt && opt.space ? opt.space : null; val = JSON.stringify(val, replace, space); } if (opt && opt.quotes === false && !/(^{|\[).*?([}\]])$/gm.test(val)) val = val.slice(1, val.length - 1); return val; }
javascript
function Stringme(val, opt) { if (val === undefined) { val = '"undefined"'; } else if (val === null) { val = '"null"'; } else { var replace = opt && opt.replace ? opt.replace : null; var space = opt && opt.space ? opt.space : null; val = JSON.stringify(val, replace, space); } if (opt && opt.quotes === false && !/(^{|\[).*?([}\]])$/gm.test(val)) val = val.slice(1, val.length - 1); return val; }
[ "function", "Stringme", "(", "val", ",", "opt", ")", "{", "if", "(", "val", "===", "undefined", ")", "{", "val", "=", "'\"undefined\"'", ";", "}", "else", "if", "(", "val", "===", "null", ")", "{", "val", "=", "'\"null\"'", ";", "}", "else", "{", "var", "replace", "=", "opt", "&&", "opt", ".", "replace", "?", "opt", ".", "replace", ":", "null", ";", "var", "space", "=", "opt", "&&", "opt", ".", "space", "?", "opt", ".", "space", ":", "null", ";", "val", "=", "JSON", ".", "stringify", "(", "val", ",", "replace", ",", "space", ")", ";", "}", "if", "(", "opt", "&&", "opt", ".", "quotes", "===", "false", "&&", "!", "/", "(^{|\\[).*?([}\\]])$", "/", "gm", ".", "test", "(", "val", ")", ")", "val", "=", "val", ".", "slice", "(", "1", ",", "val", ".", "length", "-", "1", ")", ";", "return", "val", ";", "}" ]
Convert also undefined and null to string @param {*} val Anything you want stringify @param {object} [opt] Options @param {boolean} [opt.quotes=true] If false remove quotes @param {function|array|string|number} [opt.replace=null] Replace (JSON.stringify 2# param) @param {number|string} [opt.space=0] Space (JSON.stringify 3# param) @link https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify @returns {string} @constructor
[ "Convert", "also", "undefined", "and", "null", "to", "string" ]
d14d51cdb4aa5f821e26ac29feeba7fc1e4ae868
https://github.com/fabioricali/stringme/blob/d14d51cdb4aa5f821e26ac29feeba7fc1e4ae868/index.js#L12-L28
57,420
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/filebrowser/plugin.js
ucFirst
function ucFirst( str ) { str += ''; var f = str.charAt( 0 ).toUpperCase(); return f + str.substr( 1 ); }
javascript
function ucFirst( str ) { str += ''; var f = str.charAt( 0 ).toUpperCase(); return f + str.substr( 1 ); }
[ "function", "ucFirst", "(", "str", ")", "{", "str", "+=", "''", ";", "var", "f", "=", "str", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", ";", "return", "f", "+", "str", ".", "substr", "(", "1", ")", ";", "}" ]
Make a string's first character uppercase. @param {String} str String.
[ "Make", "a", "string", "s", "first", "character", "uppercase", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/filebrowser/plugin.js#L140-L144
57,421
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/filebrowser/plugin.js
browseServer
function browseServer( evt ) { var dialog = this.getDialog(); var editor = dialog.getParentEditor(); editor._.filebrowserSe = this; var width = editor.config[ 'filebrowser' + ucFirst( dialog.getName() ) + 'WindowWidth' ] || editor.config.filebrowserWindowWidth || '80%'; var height = editor.config[ 'filebrowser' + ucFirst( dialog.getName() ) + 'WindowHeight' ] || editor.config.filebrowserWindowHeight || '70%'; var params = this.filebrowser.params || {}; params.CKEditor = editor.name; params.CKEditorFuncNum = editor._.filebrowserFn; if ( !params.langCode ) params.langCode = editor.langCode; var url = addQueryString( this.filebrowser.url, params ); // TODO: V4: Remove backward compatibility (#8163). editor.popup( url, width, height, editor.config.filebrowserWindowFeatures || editor.config.fileBrowserWindowFeatures ); }
javascript
function browseServer( evt ) { var dialog = this.getDialog(); var editor = dialog.getParentEditor(); editor._.filebrowserSe = this; var width = editor.config[ 'filebrowser' + ucFirst( dialog.getName() ) + 'WindowWidth' ] || editor.config.filebrowserWindowWidth || '80%'; var height = editor.config[ 'filebrowser' + ucFirst( dialog.getName() ) + 'WindowHeight' ] || editor.config.filebrowserWindowHeight || '70%'; var params = this.filebrowser.params || {}; params.CKEditor = editor.name; params.CKEditorFuncNum = editor._.filebrowserFn; if ( !params.langCode ) params.langCode = editor.langCode; var url = addQueryString( this.filebrowser.url, params ); // TODO: V4: Remove backward compatibility (#8163). editor.popup( url, width, height, editor.config.filebrowserWindowFeatures || editor.config.fileBrowserWindowFeatures ); }
[ "function", "browseServer", "(", "evt", ")", "{", "var", "dialog", "=", "this", ".", "getDialog", "(", ")", ";", "var", "editor", "=", "dialog", ".", "getParentEditor", "(", ")", ";", "editor", ".", "_", ".", "filebrowserSe", "=", "this", ";", "var", "width", "=", "editor", ".", "config", "[", "'filebrowser'", "+", "ucFirst", "(", "dialog", ".", "getName", "(", ")", ")", "+", "'WindowWidth'", "]", "||", "editor", ".", "config", ".", "filebrowserWindowWidth", "||", "'80%'", ";", "var", "height", "=", "editor", ".", "config", "[", "'filebrowser'", "+", "ucFirst", "(", "dialog", ".", "getName", "(", ")", ")", "+", "'WindowHeight'", "]", "||", "editor", ".", "config", ".", "filebrowserWindowHeight", "||", "'70%'", ";", "var", "params", "=", "this", ".", "filebrowser", ".", "params", "||", "{", "}", ";", "params", ".", "CKEditor", "=", "editor", ".", "name", ";", "params", ".", "CKEditorFuncNum", "=", "editor", ".", "_", ".", "filebrowserFn", ";", "if", "(", "!", "params", ".", "langCode", ")", "params", ".", "langCode", "=", "editor", ".", "langCode", ";", "var", "url", "=", "addQueryString", "(", "this", ".", "filebrowser", ".", "url", ",", "params", ")", ";", "// TODO: V4: Remove backward compatibility (#8163).\r", "editor", ".", "popup", "(", "url", ",", "width", ",", "height", ",", "editor", ".", "config", ".", "filebrowserWindowFeatures", "||", "editor", ".", "config", ".", "fileBrowserWindowFeatures", ")", ";", "}" ]
The onlick function assigned to the 'Browse Server' button. Opens the file browser and updates target field when file is selected. @param {CKEDITOR.event} evt The event object.
[ "The", "onlick", "function", "assigned", "to", "the", "Browse", "Server", "button", ".", "Opens", "the", "file", "browser", "and", "updates", "target", "field", "when", "file", "is", "selected", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/filebrowser/plugin.js#L151-L169
57,422
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/filebrowser/plugin.js
uploadFile
function uploadFile( evt ) { var dialog = this.getDialog(); var editor = dialog.getParentEditor(); editor._.filebrowserSe = this; // If user didn't select the file, stop the upload. if ( !dialog.getContentElement( this[ 'for' ][ 0 ], this[ 'for' ][ 1 ] ).getInputElement().$.value ) return false; if ( !dialog.getContentElement( this[ 'for' ][ 0 ], this[ 'for' ][ 1 ] ).getAction() ) return false; return true; }
javascript
function uploadFile( evt ) { var dialog = this.getDialog(); var editor = dialog.getParentEditor(); editor._.filebrowserSe = this; // If user didn't select the file, stop the upload. if ( !dialog.getContentElement( this[ 'for' ][ 0 ], this[ 'for' ][ 1 ] ).getInputElement().$.value ) return false; if ( !dialog.getContentElement( this[ 'for' ][ 0 ], this[ 'for' ][ 1 ] ).getAction() ) return false; return true; }
[ "function", "uploadFile", "(", "evt", ")", "{", "var", "dialog", "=", "this", ".", "getDialog", "(", ")", ";", "var", "editor", "=", "dialog", ".", "getParentEditor", "(", ")", ";", "editor", ".", "_", ".", "filebrowserSe", "=", "this", ";", "// If user didn't select the file, stop the upload.\r", "if", "(", "!", "dialog", ".", "getContentElement", "(", "this", "[", "'for'", "]", "[", "0", "]", ",", "this", "[", "'for'", "]", "[", "1", "]", ")", ".", "getInputElement", "(", ")", ".", "$", ".", "value", ")", "return", "false", ";", "if", "(", "!", "dialog", ".", "getContentElement", "(", "this", "[", "'for'", "]", "[", "0", "]", ",", "this", "[", "'for'", "]", "[", "1", "]", ")", ".", "getAction", "(", ")", ")", "return", "false", ";", "return", "true", ";", "}" ]
The onlick function assigned to the 'Upload' button. Makes the final decision whether form is really submitted and updates target field when file is uploaded. @param {CKEDITOR.event} evt The event object.
[ "The", "onlick", "function", "assigned", "to", "the", "Upload", "button", ".", "Makes", "the", "final", "decision", "whether", "form", "is", "really", "submitted", "and", "updates", "target", "field", "when", "file", "is", "uploaded", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/filebrowser/plugin.js#L177-L191
57,423
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/filebrowser/plugin.js
setupFileElement
function setupFileElement( editor, fileInput, filebrowser ) { var params = filebrowser.params || {}; params.CKEditor = editor.name; params.CKEditorFuncNum = editor._.filebrowserFn; if ( !params.langCode ) params.langCode = editor.langCode; fileInput.action = addQueryString( filebrowser.url, params ); fileInput.filebrowser = filebrowser; }
javascript
function setupFileElement( editor, fileInput, filebrowser ) { var params = filebrowser.params || {}; params.CKEditor = editor.name; params.CKEditorFuncNum = editor._.filebrowserFn; if ( !params.langCode ) params.langCode = editor.langCode; fileInput.action = addQueryString( filebrowser.url, params ); fileInput.filebrowser = filebrowser; }
[ "function", "setupFileElement", "(", "editor", ",", "fileInput", ",", "filebrowser", ")", "{", "var", "params", "=", "filebrowser", ".", "params", "||", "{", "}", ";", "params", ".", "CKEditor", "=", "editor", ".", "name", ";", "params", ".", "CKEditorFuncNum", "=", "editor", ".", "_", ".", "filebrowserFn", ";", "if", "(", "!", "params", ".", "langCode", ")", "params", ".", "langCode", "=", "editor", ".", "langCode", ";", "fileInput", ".", "action", "=", "addQueryString", "(", "filebrowser", ".", "url", ",", "params", ")", ";", "fileInput", ".", "filebrowser", "=", "filebrowser", ";", "}" ]
Setups the file element. @param {CKEDITOR.ui.dialog.file} fileInput The file element used during file upload. @param {Object} filebrowser Object containing filebrowser settings assigned to the fileButton associated with this file element.
[ "Setups", "the", "file", "element", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/filebrowser/plugin.js#L200-L209
57,424
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/filebrowser/plugin.js
attachFileBrowser
function attachFileBrowser( editor, dialogName, definition, elements ) { if ( !elements || !elements.length ) return; var element, fileInput; for ( var i = elements.length; i--; ) { element = elements[ i ]; if ( element.type == 'hbox' || element.type == 'vbox' || element.type == 'fieldset' ) attachFileBrowser( editor, dialogName, definition, element.children ); if ( !element.filebrowser ) continue; if ( typeof element.filebrowser == 'string' ) { var fb = { action: ( element.type == 'fileButton' ) ? 'QuickUpload' : 'Browse', target: element.filebrowser }; element.filebrowser = fb; } if ( element.filebrowser.action == 'Browse' ) { var url = element.filebrowser.url; if ( url === undefined ) { url = editor.config[ 'filebrowser' + ucFirst( dialogName ) + 'BrowseUrl' ]; if ( url === undefined ) url = editor.config.filebrowserBrowseUrl; } if ( url ) { element.onClick = browseServer; element.filebrowser.url = url; element.hidden = false; } } else if ( element.filebrowser.action == 'QuickUpload' && element[ 'for' ] ) { url = element.filebrowser.url; if ( url === undefined ) { url = editor.config[ 'filebrowser' + ucFirst( dialogName ) + 'UploadUrl' ]; if ( url === undefined ) url = editor.config.filebrowserUploadUrl; } if ( url ) { var onClick = element.onClick; element.onClick = function( evt ) { // "element" here means the definition object, so we need to find the correct // button to scope the event call var sender = evt.sender; if ( onClick && onClick.call( sender, evt ) === false ) return false; return uploadFile.call( sender, evt ); }; element.filebrowser.url = url; element.hidden = false; setupFileElement( editor, definition.getContents( element[ 'for' ][ 0 ] ).get( element[ 'for' ][ 1 ] ), element.filebrowser ); } } } }
javascript
function attachFileBrowser( editor, dialogName, definition, elements ) { if ( !elements || !elements.length ) return; var element, fileInput; for ( var i = elements.length; i--; ) { element = elements[ i ]; if ( element.type == 'hbox' || element.type == 'vbox' || element.type == 'fieldset' ) attachFileBrowser( editor, dialogName, definition, element.children ); if ( !element.filebrowser ) continue; if ( typeof element.filebrowser == 'string' ) { var fb = { action: ( element.type == 'fileButton' ) ? 'QuickUpload' : 'Browse', target: element.filebrowser }; element.filebrowser = fb; } if ( element.filebrowser.action == 'Browse' ) { var url = element.filebrowser.url; if ( url === undefined ) { url = editor.config[ 'filebrowser' + ucFirst( dialogName ) + 'BrowseUrl' ]; if ( url === undefined ) url = editor.config.filebrowserBrowseUrl; } if ( url ) { element.onClick = browseServer; element.filebrowser.url = url; element.hidden = false; } } else if ( element.filebrowser.action == 'QuickUpload' && element[ 'for' ] ) { url = element.filebrowser.url; if ( url === undefined ) { url = editor.config[ 'filebrowser' + ucFirst( dialogName ) + 'UploadUrl' ]; if ( url === undefined ) url = editor.config.filebrowserUploadUrl; } if ( url ) { var onClick = element.onClick; element.onClick = function( evt ) { // "element" here means the definition object, so we need to find the correct // button to scope the event call var sender = evt.sender; if ( onClick && onClick.call( sender, evt ) === false ) return false; return uploadFile.call( sender, evt ); }; element.filebrowser.url = url; element.hidden = false; setupFileElement( editor, definition.getContents( element[ 'for' ][ 0 ] ).get( element[ 'for' ][ 1 ] ), element.filebrowser ); } } } }
[ "function", "attachFileBrowser", "(", "editor", ",", "dialogName", ",", "definition", ",", "elements", ")", "{", "if", "(", "!", "elements", "||", "!", "elements", ".", "length", ")", "return", ";", "var", "element", ",", "fileInput", ";", "for", "(", "var", "i", "=", "elements", ".", "length", ";", "i", "--", ";", ")", "{", "element", "=", "elements", "[", "i", "]", ";", "if", "(", "element", ".", "type", "==", "'hbox'", "||", "element", ".", "type", "==", "'vbox'", "||", "element", ".", "type", "==", "'fieldset'", ")", "attachFileBrowser", "(", "editor", ",", "dialogName", ",", "definition", ",", "element", ".", "children", ")", ";", "if", "(", "!", "element", ".", "filebrowser", ")", "continue", ";", "if", "(", "typeof", "element", ".", "filebrowser", "==", "'string'", ")", "{", "var", "fb", "=", "{", "action", ":", "(", "element", ".", "type", "==", "'fileButton'", ")", "?", "'QuickUpload'", ":", "'Browse'", ",", "target", ":", "element", ".", "filebrowser", "}", ";", "element", ".", "filebrowser", "=", "fb", ";", "}", "if", "(", "element", ".", "filebrowser", ".", "action", "==", "'Browse'", ")", "{", "var", "url", "=", "element", ".", "filebrowser", ".", "url", ";", "if", "(", "url", "===", "undefined", ")", "{", "url", "=", "editor", ".", "config", "[", "'filebrowser'", "+", "ucFirst", "(", "dialogName", ")", "+", "'BrowseUrl'", "]", ";", "if", "(", "url", "===", "undefined", ")", "url", "=", "editor", ".", "config", ".", "filebrowserBrowseUrl", ";", "}", "if", "(", "url", ")", "{", "element", ".", "onClick", "=", "browseServer", ";", "element", ".", "filebrowser", ".", "url", "=", "url", ";", "element", ".", "hidden", "=", "false", ";", "}", "}", "else", "if", "(", "element", ".", "filebrowser", ".", "action", "==", "'QuickUpload'", "&&", "element", "[", "'for'", "]", ")", "{", "url", "=", "element", ".", "filebrowser", ".", "url", ";", "if", "(", "url", "===", "undefined", ")", "{", "url", "=", "editor", ".", "config", "[", "'filebrowser'", "+", "ucFirst", "(", "dialogName", ")", "+", "'UploadUrl'", "]", ";", "if", "(", "url", "===", "undefined", ")", "url", "=", "editor", ".", "config", ".", "filebrowserUploadUrl", ";", "}", "if", "(", "url", ")", "{", "var", "onClick", "=", "element", ".", "onClick", ";", "element", ".", "onClick", "=", "function", "(", "evt", ")", "{", "// \"element\" here means the definition object, so we need to find the correct\r", "// button to scope the event call\r", "var", "sender", "=", "evt", ".", "sender", ";", "if", "(", "onClick", "&&", "onClick", ".", "call", "(", "sender", ",", "evt", ")", "===", "false", ")", "return", "false", ";", "return", "uploadFile", ".", "call", "(", "sender", ",", "evt", ")", ";", "}", ";", "element", ".", "filebrowser", ".", "url", "=", "url", ";", "element", ".", "hidden", "=", "false", ";", "setupFileElement", "(", "editor", ",", "definition", ".", "getContents", "(", "element", "[", "'for'", "]", "[", "0", "]", ")", ".", "get", "(", "element", "[", "'for'", "]", "[", "1", "]", ")", ",", "element", ".", "filebrowser", ")", ";", "}", "}", "}", "}" ]
Traverse through the content definition and attach filebrowser to elements with 'filebrowser' attribute. @param String dialogName Dialog name. @param {CKEDITOR.dialog.definitionObject} definition Dialog definition. @param {Array} elements Array of {@link CKEDITOR.dialog.definition.content} objects.
[ "Traverse", "through", "the", "content", "definition", "and", "attach", "filebrowser", "to", "elements", "with", "filebrowser", "attribute", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/filebrowser/plugin.js#L221-L283
57,425
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/filebrowser/plugin.js
isConfigured
function isConfigured( definition, tabId, elementId ) { if ( elementId.indexOf( ";" ) !== -1 ) { var ids = elementId.split( ";" ); for ( var i = 0; i < ids.length; i++ ) { if ( isConfigured( definition, tabId, ids[ i ] ) ) return true; } return false; } var elementFileBrowser = definition.getContents( tabId ).get( elementId ).filebrowser; return ( elementFileBrowser && elementFileBrowser.url ); }
javascript
function isConfigured( definition, tabId, elementId ) { if ( elementId.indexOf( ";" ) !== -1 ) { var ids = elementId.split( ";" ); for ( var i = 0; i < ids.length; i++ ) { if ( isConfigured( definition, tabId, ids[ i ] ) ) return true; } return false; } var elementFileBrowser = definition.getContents( tabId ).get( elementId ).filebrowser; return ( elementFileBrowser && elementFileBrowser.url ); }
[ "function", "isConfigured", "(", "definition", ",", "tabId", ",", "elementId", ")", "{", "if", "(", "elementId", ".", "indexOf", "(", "\";\"", ")", "!==", "-", "1", ")", "{", "var", "ids", "=", "elementId", ".", "split", "(", "\";\"", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "ids", ".", "length", ";", "i", "++", ")", "{", "if", "(", "isConfigured", "(", "definition", ",", "tabId", ",", "ids", "[", "i", "]", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}", "var", "elementFileBrowser", "=", "definition", ".", "getContents", "(", "tabId", ")", ".", "get", "(", "elementId", ")", ".", "filebrowser", ";", "return", "(", "elementFileBrowser", "&&", "elementFileBrowser", ".", "url", ")", ";", "}" ]
Returns true if filebrowser is configured in one of the elements. @param {CKEDITOR.dialog.definitionObject} definition Dialog definition. @param String tabId The tab id where element(s) can be found. @param String elementId The element id (or ids, separated with a semicolon) to check.
[ "Returns", "true", "if", "filebrowser", "is", "configured", "in", "one", "of", "the", "elements", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/filebrowser/plugin.js#L312-L324
57,426
pvorb/node-confdir
confdir.js
findDirRec
function findDirRec(dir, callback) { var result = path.resolve(dir, dirmod); fs.stat(result, function stat(err, stat) { if (err || !stat.isDirectory()) { if (lastResult == result) { callback(new Error('No configuration directory found.')); return; } lastResult = result; findDirRec(path.resolve(dir, '..'), callback); } else { callback(null, result); } }); }
javascript
function findDirRec(dir, callback) { var result = path.resolve(dir, dirmod); fs.stat(result, function stat(err, stat) { if (err || !stat.isDirectory()) { if (lastResult == result) { callback(new Error('No configuration directory found.')); return; } lastResult = result; findDirRec(path.resolve(dir, '..'), callback); } else { callback(null, result); } }); }
[ "function", "findDirRec", "(", "dir", ",", "callback", ")", "{", "var", "result", "=", "path", ".", "resolve", "(", "dir", ",", "dirmod", ")", ";", "fs", ".", "stat", "(", "result", ",", "function", "stat", "(", "err", ",", "stat", ")", "{", "if", "(", "err", "||", "!", "stat", ".", "isDirectory", "(", ")", ")", "{", "if", "(", "lastResult", "==", "result", ")", "{", "callback", "(", "new", "Error", "(", "'No configuration directory found.'", ")", ")", ";", "return", ";", "}", "lastResult", "=", "result", ";", "findDirRec", "(", "path", ".", "resolve", "(", "dir", ",", "'..'", ")", ",", "callback", ")", ";", "}", "else", "{", "callback", "(", "null", ",", "result", ")", ";", "}", "}", ")", ";", "}" ]
find dirname by recursively walking up the path hierarchy
[ "find", "dirname", "by", "recursively", "walking", "up", "the", "path", "hierarchy" ]
11464820356ea1878b63733f80e923edc7db9d72
https://github.com/pvorb/node-confdir/blob/11464820356ea1878b63733f80e923edc7db9d72/confdir.js#L16-L30
57,427
airbrite/muni
mongo.js
function(obj) { _.forEach(obj, function(val, key) { if (_.isString(val)) { if (Mixins.isObjectId(val)) { obj[key] = Mixins.newObjectId(val); } else if (Mixins.isValidISO8601String(val)) { obj[key] = new Date(val); } } else if (_.isDate(val)) { obj[key] = val; } else if (_.isObject(val)) { if (val['$oid']) { obj[key] = val['$oid']; } else { obj[key] = this.cast(val); } } }.bind(this)); return obj; }
javascript
function(obj) { _.forEach(obj, function(val, key) { if (_.isString(val)) { if (Mixins.isObjectId(val)) { obj[key] = Mixins.newObjectId(val); } else if (Mixins.isValidISO8601String(val)) { obj[key] = new Date(val); } } else if (_.isDate(val)) { obj[key] = val; } else if (_.isObject(val)) { if (val['$oid']) { obj[key] = val['$oid']; } else { obj[key] = this.cast(val); } } }.bind(this)); return obj; }
[ "function", "(", "obj", ")", "{", "_", ".", "forEach", "(", "obj", ",", "function", "(", "val", ",", "key", ")", "{", "if", "(", "_", ".", "isString", "(", "val", ")", ")", "{", "if", "(", "Mixins", ".", "isObjectId", "(", "val", ")", ")", "{", "obj", "[", "key", "]", "=", "Mixins", ".", "newObjectId", "(", "val", ")", ";", "}", "else", "if", "(", "Mixins", ".", "isValidISO8601String", "(", "val", ")", ")", "{", "obj", "[", "key", "]", "=", "new", "Date", "(", "val", ")", ";", "}", "}", "else", "if", "(", "_", ".", "isDate", "(", "val", ")", ")", "{", "obj", "[", "key", "]", "=", "val", ";", "}", "else", "if", "(", "_", ".", "isObject", "(", "val", ")", ")", "{", "if", "(", "val", "[", "'$oid'", "]", ")", "{", "obj", "[", "key", "]", "=", "val", "[", "'$oid'", "]", ";", "}", "else", "{", "obj", "[", "key", "]", "=", "this", ".", "cast", "(", "val", ")", ";", "}", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "return", "obj", ";", "}" ]
Automatically cast to HexString to ObjectId Automatically cast ISO8601 date strings to Javascript Date Will mutate the original object obj can be an object or an array
[ "Automatically", "cast", "to", "HexString", "to", "ObjectId", "Automatically", "cast", "ISO8601", "date", "strings", "to", "Javascript", "Date", "Will", "mutate", "the", "original", "object", "obj", "can", "be", "an", "object", "or", "an", "array" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/mongo.js#L117-L137
57,428
airbrite/muni
mongo.js
function(obj) { _.forEach(obj, function(val, key) { if (val && _.isFunction(val.toHexString)) { obj[key] = val.toHexString(); } else if (_.isDate(val)) { obj[key] = val; } else if (_.isObject(val)) { if (val['$oid']) { obj[key] = val['$oid']; } else { obj[key] = this.uncast(val); } } }.bind(this)); return obj; }
javascript
function(obj) { _.forEach(obj, function(val, key) { if (val && _.isFunction(val.toHexString)) { obj[key] = val.toHexString(); } else if (_.isDate(val)) { obj[key] = val; } else if (_.isObject(val)) { if (val['$oid']) { obj[key] = val['$oid']; } else { obj[key] = this.uncast(val); } } }.bind(this)); return obj; }
[ "function", "(", "obj", ")", "{", "_", ".", "forEach", "(", "obj", ",", "function", "(", "val", ",", "key", ")", "{", "if", "(", "val", "&&", "_", ".", "isFunction", "(", "val", ".", "toHexString", ")", ")", "{", "obj", "[", "key", "]", "=", "val", ".", "toHexString", "(", ")", ";", "}", "else", "if", "(", "_", ".", "isDate", "(", "val", ")", ")", "{", "obj", "[", "key", "]", "=", "val", ";", "}", "else", "if", "(", "_", ".", "isObject", "(", "val", ")", ")", "{", "if", "(", "val", "[", "'$oid'", "]", ")", "{", "obj", "[", "key", "]", "=", "val", "[", "'$oid'", "]", ";", "}", "else", "{", "obj", "[", "key", "]", "=", "this", ".", "uncast", "(", "val", ")", ";", "}", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "return", "obj", ";", "}" ]
Automatically uncast ObjectId to HexString Will mutate the original object obj can be an object or an array
[ "Automatically", "uncast", "ObjectId", "to", "HexString", "Will", "mutate", "the", "original", "object", "obj", "can", "be", "an", "object", "or", "an", "array" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/mongo.js#L142-L158
57,429
bocallaghan/JADS
objects/jads_directory.js
function (requestURL, filename, fileType) { if (gc.coreFunctions.getReqestExtension(filename) == '.ipa'){ // The template of an entry as well as the indicator variable for a file or dir. // This is used for IPA files that need to be installed on iOS devices so .manifest is appended to search for the appropriate manifest. var listingEntry = '<tr><td>{itemType}</td><td><a href="itms-services://?action=download-manifest&url={hrefLink}.plist">{itemName}</a></td></tr>\n'; // Populate the template now using the placeholders as text to be replaced. listingEntry = listingEntry.replace('{itemType}', "iOS"); listingEntry = listingEntry.replace('{hrefLink}', gc.coreFunctions.joinPaths(requestURL, filename)); listingEntry = listingEntry.replace('{itemName}', filename); } else { // The template of an entry as well as the indicator variable for a file or dir. var listingEntry = '<tr><td>{itemType}</td><td><a href="{hrefLink}">{itemName}</a></td></tr>\n'; // Populate the template now using the placeholders as text to be replaced. listingEntry = listingEntry.replace('{itemType}', fileType); listingEntry = listingEntry.replace('{hrefLink}', gc.coreFunctions.joinPaths(requestURL, filename)); listingEntry = listingEntry.replace('{itemName}', filename); } // Return the entry. return listingEntry; }
javascript
function (requestURL, filename, fileType) { if (gc.coreFunctions.getReqestExtension(filename) == '.ipa'){ // The template of an entry as well as the indicator variable for a file or dir. // This is used for IPA files that need to be installed on iOS devices so .manifest is appended to search for the appropriate manifest. var listingEntry = '<tr><td>{itemType}</td><td><a href="itms-services://?action=download-manifest&url={hrefLink}.plist">{itemName}</a></td></tr>\n'; // Populate the template now using the placeholders as text to be replaced. listingEntry = listingEntry.replace('{itemType}', "iOS"); listingEntry = listingEntry.replace('{hrefLink}', gc.coreFunctions.joinPaths(requestURL, filename)); listingEntry = listingEntry.replace('{itemName}', filename); } else { // The template of an entry as well as the indicator variable for a file or dir. var listingEntry = '<tr><td>{itemType}</td><td><a href="{hrefLink}">{itemName}</a></td></tr>\n'; // Populate the template now using the placeholders as text to be replaced. listingEntry = listingEntry.replace('{itemType}', fileType); listingEntry = listingEntry.replace('{hrefLink}', gc.coreFunctions.joinPaths(requestURL, filename)); listingEntry = listingEntry.replace('{itemName}', filename); } // Return the entry. return listingEntry; }
[ "function", "(", "requestURL", ",", "filename", ",", "fileType", ")", "{", "if", "(", "gc", ".", "coreFunctions", ".", "getReqestExtension", "(", "filename", ")", "==", "'.ipa'", ")", "{", "// The template of an entry as well as the indicator variable for a file or dir.", "// This is used for IPA files that need to be installed on iOS devices so .manifest is appended to search for the appropriate manifest.", "var", "listingEntry", "=", "'<tr><td>{itemType}</td><td><a href=\"itms-services://?action=download-manifest&url={hrefLink}.plist\">{itemName}</a></td></tr>\\n'", ";", "// Populate the template now using the placeholders as text to be replaced.", "listingEntry", "=", "listingEntry", ".", "replace", "(", "'{itemType}'", ",", "\"iOS\"", ")", ";", "listingEntry", "=", "listingEntry", ".", "replace", "(", "'{hrefLink}'", ",", "gc", ".", "coreFunctions", ".", "joinPaths", "(", "requestURL", ",", "filename", ")", ")", ";", "listingEntry", "=", "listingEntry", ".", "replace", "(", "'{itemName}'", ",", "filename", ")", ";", "}", "else", "{", "// The template of an entry as well as the indicator variable for a file or dir.", "var", "listingEntry", "=", "'<tr><td>{itemType}</td><td><a href=\"{hrefLink}\">{itemName}</a></td></tr>\\n'", ";", "// Populate the template now using the placeholders as text to be replaced.", "listingEntry", "=", "listingEntry", ".", "replace", "(", "'{itemType}'", ",", "fileType", ")", ";", "listingEntry", "=", "listingEntry", ".", "replace", "(", "'{hrefLink}'", ",", "gc", ".", "coreFunctions", ".", "joinPaths", "(", "requestURL", ",", "filename", ")", ")", ";", "listingEntry", "=", "listingEntry", ".", "replace", "(", "'{itemName}'", ",", "filename", ")", ";", "}", "// Return the entry.", "return", "listingEntry", ";", "}" ]
Node file system object. Formats an entry for the directory listing based on whether its a file or dir.
[ "Node", "file", "system", "object", ".", "Formats", "an", "entry", "for", "the", "directory", "listing", "based", "on", "whether", "its", "a", "file", "or", "dir", "." ]
fb022d86138998d9d7fd22bb2148989e6ec7b981
https://github.com/bocallaghan/JADS/blob/fb022d86138998d9d7fd22bb2148989e6ec7b981/objects/jads_directory.js#L6-L30
57,430
welefen/thinkit
src/index.js
Class
function Class(superCtor, props){ let cls = function (...args) { if (!(this instanceof cls)) { throw new Error('Class constructors cannot be invoked without \'new\''); } //extend prototype data to instance //avoid instance change data to pullte prototype cls.extend(cls.__props__, this); if(isFunction(this.init)){ this.__initReturn = this.init(...args); } }; cls.__props__ = {}; cls.extend = function(props, target){ target = target || cls.prototype; let name, value; for(name in props){ value = props[name]; if (isArray(value)) { cls.__props__[name] = target[name] = extend([], value); }else if(isObject(value)){ cls.__props__[name] = target[name] = extend({}, value); }else{ target[name] = value; } } return cls; }; cls.inherits = function(superCtor){ cls.super_ = superCtor; //if superCtor.prototype is not enumerable if(Object.keys(superCtor.prototype).length === 0){ cls.prototype = Object.create(superCtor.prototype, { constructor: { value: cls, enumerable: false, writable: true, configurable: true } }); }else{ extend(cls.prototype, superCtor.prototype); } return cls; }; if (!isFunction(superCtor)) { props = superCtor; }else if (isFunction(superCtor)) { cls.inherits(superCtor); } if (props) { cls.extend(props); } /** * invoke super class method * @param {String} name [] * @param {Mixed} data [] * @return {Mixed} [] */ cls.prototype.super = function(name, data){ if (!this[name]) { this.super_c = null; return; } let super_ = this.super_c ? this.super_c.super_ : this.constructor.super_; if (!super_ || !isFunction(super_.prototype[name])) { this.super_c = null; return; } while(this[name] === super_.prototype[name] && super_.super_){ super_ = super_.super_; } this.super_c = super_; if (!this.super_t) { this.super_t = 1; } if (!isArray(data) && !isArguments(data)) { data = arguments.length === 1 ? [] : [data]; } let t = ++this.super_t, ret, method = super_.prototype[name]; ret = method.apply(this, data); if (t === this.super_t) { this.super_c = null; this.super_t = 0; } return ret; }; return cls; }
javascript
function Class(superCtor, props){ let cls = function (...args) { if (!(this instanceof cls)) { throw new Error('Class constructors cannot be invoked without \'new\''); } //extend prototype data to instance //avoid instance change data to pullte prototype cls.extend(cls.__props__, this); if(isFunction(this.init)){ this.__initReturn = this.init(...args); } }; cls.__props__ = {}; cls.extend = function(props, target){ target = target || cls.prototype; let name, value; for(name in props){ value = props[name]; if (isArray(value)) { cls.__props__[name] = target[name] = extend([], value); }else if(isObject(value)){ cls.__props__[name] = target[name] = extend({}, value); }else{ target[name] = value; } } return cls; }; cls.inherits = function(superCtor){ cls.super_ = superCtor; //if superCtor.prototype is not enumerable if(Object.keys(superCtor.prototype).length === 0){ cls.prototype = Object.create(superCtor.prototype, { constructor: { value: cls, enumerable: false, writable: true, configurable: true } }); }else{ extend(cls.prototype, superCtor.prototype); } return cls; }; if (!isFunction(superCtor)) { props = superCtor; }else if (isFunction(superCtor)) { cls.inherits(superCtor); } if (props) { cls.extend(props); } /** * invoke super class method * @param {String} name [] * @param {Mixed} data [] * @return {Mixed} [] */ cls.prototype.super = function(name, data){ if (!this[name]) { this.super_c = null; return; } let super_ = this.super_c ? this.super_c.super_ : this.constructor.super_; if (!super_ || !isFunction(super_.prototype[name])) { this.super_c = null; return; } while(this[name] === super_.prototype[name] && super_.super_){ super_ = super_.super_; } this.super_c = super_; if (!this.super_t) { this.super_t = 1; } if (!isArray(data) && !isArguments(data)) { data = arguments.length === 1 ? [] : [data]; } let t = ++this.super_t, ret, method = super_.prototype[name]; ret = method.apply(this, data); if (t === this.super_t) { this.super_c = null; this.super_t = 0; } return ret; }; return cls; }
[ "function", "Class", "(", "superCtor", ",", "props", ")", "{", "let", "cls", "=", "function", "(", "...", "args", ")", "{", "if", "(", "!", "(", "this", "instanceof", "cls", ")", ")", "{", "throw", "new", "Error", "(", "'Class constructors cannot be invoked without \\'new\\''", ")", ";", "}", "//extend prototype data to instance", "//avoid instance change data to pullte prototype", "cls", ".", "extend", "(", "cls", ".", "__props__", ",", "this", ")", ";", "if", "(", "isFunction", "(", "this", ".", "init", ")", ")", "{", "this", ".", "__initReturn", "=", "this", ".", "init", "(", "...", "args", ")", ";", "}", "}", ";", "cls", ".", "__props__", "=", "{", "}", ";", "cls", ".", "extend", "=", "function", "(", "props", ",", "target", ")", "{", "target", "=", "target", "||", "cls", ".", "prototype", ";", "let", "name", ",", "value", ";", "for", "(", "name", "in", "props", ")", "{", "value", "=", "props", "[", "name", "]", ";", "if", "(", "isArray", "(", "value", ")", ")", "{", "cls", ".", "__props__", "[", "name", "]", "=", "target", "[", "name", "]", "=", "extend", "(", "[", "]", ",", "value", ")", ";", "}", "else", "if", "(", "isObject", "(", "value", ")", ")", "{", "cls", ".", "__props__", "[", "name", "]", "=", "target", "[", "name", "]", "=", "extend", "(", "{", "}", ",", "value", ")", ";", "}", "else", "{", "target", "[", "name", "]", "=", "value", ";", "}", "}", "return", "cls", ";", "}", ";", "cls", ".", "inherits", "=", "function", "(", "superCtor", ")", "{", "cls", ".", "super_", "=", "superCtor", ";", "//if superCtor.prototype is not enumerable", "if", "(", "Object", ".", "keys", "(", "superCtor", ".", "prototype", ")", ".", "length", "===", "0", ")", "{", "cls", ".", "prototype", "=", "Object", ".", "create", "(", "superCtor", ".", "prototype", ",", "{", "constructor", ":", "{", "value", ":", "cls", ",", "enumerable", ":", "false", ",", "writable", ":", "true", ",", "configurable", ":", "true", "}", "}", ")", ";", "}", "else", "{", "extend", "(", "cls", ".", "prototype", ",", "superCtor", ".", "prototype", ")", ";", "}", "return", "cls", ";", "}", ";", "if", "(", "!", "isFunction", "(", "superCtor", ")", ")", "{", "props", "=", "superCtor", ";", "}", "else", "if", "(", "isFunction", "(", "superCtor", ")", ")", "{", "cls", ".", "inherits", "(", "superCtor", ")", ";", "}", "if", "(", "props", ")", "{", "cls", ".", "extend", "(", "props", ")", ";", "}", "/**\n * invoke super class method\n * @param {String} name []\n * @param {Mixed} data []\n * @return {Mixed} []\n */", "cls", ".", "prototype", ".", "super", "=", "function", "(", "name", ",", "data", ")", "{", "if", "(", "!", "this", "[", "name", "]", ")", "{", "this", ".", "super_c", "=", "null", ";", "return", ";", "}", "let", "super_", "=", "this", ".", "super_c", "?", "this", ".", "super_c", ".", "super_", ":", "this", ".", "constructor", ".", "super_", ";", "if", "(", "!", "super_", "||", "!", "isFunction", "(", "super_", ".", "prototype", "[", "name", "]", ")", ")", "{", "this", ".", "super_c", "=", "null", ";", "return", ";", "}", "while", "(", "this", "[", "name", "]", "===", "super_", ".", "prototype", "[", "name", "]", "&&", "super_", ".", "super_", ")", "{", "super_", "=", "super_", ".", "super_", ";", "}", "this", ".", "super_c", "=", "super_", ";", "if", "(", "!", "this", ".", "super_t", ")", "{", "this", ".", "super_t", "=", "1", ";", "}", "if", "(", "!", "isArray", "(", "data", ")", "&&", "!", "isArguments", "(", "data", ")", ")", "{", "data", "=", "arguments", ".", "length", "===", "1", "?", "[", "]", ":", "[", "data", "]", ";", "}", "let", "t", "=", "++", "this", ".", "super_t", ",", "ret", ",", "method", "=", "super_", ".", "prototype", "[", "name", "]", ";", "ret", "=", "method", ".", "apply", "(", "this", ",", "data", ")", ";", "if", "(", "t", "===", "this", ".", "super_t", ")", "{", "this", ".", "super_c", "=", "null", ";", "this", ".", "super_t", "=", "0", ";", "}", "return", "ret", ";", "}", ";", "return", "cls", ";", "}" ]
create Class in javascript @param {Function} superCtor [super constructor] @param {Object} props []
[ "create", "Class", "in", "javascript" ]
7f4096c7ae744eadb055daba9d9a6b0312bc6177
https://github.com/welefen/thinkit/blob/7f4096c7ae744eadb055daba9d9a6b0312bc6177/src/index.js#L55-L143
57,431
byu-oit/fully-typed
bin/array.js
TypedArray
function TypedArray (config) { const array = this; // validate min items if (config.hasOwnProperty('minItems') && (!util.isInteger(config.minItems) || config.minItems < 0)) { throw Error('Invalid configuration value for property: minItems. Must be an integer that is greater than or equal to zero. Received: ' + config.minItems); } const minItems = config.hasOwnProperty('minItems') ? config.minItems : 0; // validate max items if (config.hasOwnProperty('maxItems') && (!util.isInteger(config.maxItems) || config.maxItems < minItems)) { throw Error('Invalid configuration value for property: maxItems. Must be an integer that is greater than or equal to the minItems. Received: ' + config.maxItems); } // validate schema if (config.hasOwnProperty('schema')) config.schema = FullyTyped(config.schema); // define properties Object.defineProperties(array, { maxItems: { /** * @property * @name TypedArray#maxItems * @type {number} */ value: Math.round(config.maxItems), writable: false }, minItems: { /** * @property * @name TypedArray#minItems * @type {number} */ value: Math.round(config.minItems), writable: false }, schema: { /** * @property * @name TypedArray#schema * @type {object} */ value: config.schema, writable: false }, uniqueItems: { /** * @property * @name TypedArray#uniqueItems * @type {boolean} */ value: !!config.uniqueItems, writable: false } }); return array; }
javascript
function TypedArray (config) { const array = this; // validate min items if (config.hasOwnProperty('minItems') && (!util.isInteger(config.minItems) || config.minItems < 0)) { throw Error('Invalid configuration value for property: minItems. Must be an integer that is greater than or equal to zero. Received: ' + config.minItems); } const minItems = config.hasOwnProperty('minItems') ? config.minItems : 0; // validate max items if (config.hasOwnProperty('maxItems') && (!util.isInteger(config.maxItems) || config.maxItems < minItems)) { throw Error('Invalid configuration value for property: maxItems. Must be an integer that is greater than or equal to the minItems. Received: ' + config.maxItems); } // validate schema if (config.hasOwnProperty('schema')) config.schema = FullyTyped(config.schema); // define properties Object.defineProperties(array, { maxItems: { /** * @property * @name TypedArray#maxItems * @type {number} */ value: Math.round(config.maxItems), writable: false }, minItems: { /** * @property * @name TypedArray#minItems * @type {number} */ value: Math.round(config.minItems), writable: false }, schema: { /** * @property * @name TypedArray#schema * @type {object} */ value: config.schema, writable: false }, uniqueItems: { /** * @property * @name TypedArray#uniqueItems * @type {boolean} */ value: !!config.uniqueItems, writable: false } }); return array; }
[ "function", "TypedArray", "(", "config", ")", "{", "const", "array", "=", "this", ";", "// validate min items", "if", "(", "config", ".", "hasOwnProperty", "(", "'minItems'", ")", "&&", "(", "!", "util", ".", "isInteger", "(", "config", ".", "minItems", ")", "||", "config", ".", "minItems", "<", "0", ")", ")", "{", "throw", "Error", "(", "'Invalid configuration value for property: minItems. Must be an integer that is greater than or equal to zero. Received: '", "+", "config", ".", "minItems", ")", ";", "}", "const", "minItems", "=", "config", ".", "hasOwnProperty", "(", "'minItems'", ")", "?", "config", ".", "minItems", ":", "0", ";", "// validate max items", "if", "(", "config", ".", "hasOwnProperty", "(", "'maxItems'", ")", "&&", "(", "!", "util", ".", "isInteger", "(", "config", ".", "maxItems", ")", "||", "config", ".", "maxItems", "<", "minItems", ")", ")", "{", "throw", "Error", "(", "'Invalid configuration value for property: maxItems. Must be an integer that is greater than or equal to the minItems. Received: '", "+", "config", ".", "maxItems", ")", ";", "}", "// validate schema", "if", "(", "config", ".", "hasOwnProperty", "(", "'schema'", ")", ")", "config", ".", "schema", "=", "FullyTyped", "(", "config", ".", "schema", ")", ";", "// define properties", "Object", ".", "defineProperties", "(", "array", ",", "{", "maxItems", ":", "{", "/**\n * @property\n * @name TypedArray#maxItems\n * @type {number}\n */", "value", ":", "Math", ".", "round", "(", "config", ".", "maxItems", ")", ",", "writable", ":", "false", "}", ",", "minItems", ":", "{", "/**\n * @property\n * @name TypedArray#minItems\n * @type {number}\n */", "value", ":", "Math", ".", "round", "(", "config", ".", "minItems", ")", ",", "writable", ":", "false", "}", ",", "schema", ":", "{", "/**\n * @property\n * @name TypedArray#schema\n * @type {object}\n */", "value", ":", "config", ".", "schema", ",", "writable", ":", "false", "}", ",", "uniqueItems", ":", "{", "/**\n * @property\n * @name TypedArray#uniqueItems\n * @type {boolean}\n */", "value", ":", "!", "!", "config", ".", "uniqueItems", ",", "writable", ":", "false", "}", "}", ")", ";", "return", "array", ";", "}" ]
Create a TypedArray instance. @param {object} config @returns {TypedArray} @augments Typed @constructor
[ "Create", "a", "TypedArray", "instance", "." ]
ed6b3ed88ffc72990acffb765232eaaee261afef
https://github.com/byu-oit/fully-typed/blob/ed6b3ed88ffc72990acffb765232eaaee261afef/bin/array.js#L30-L93
57,432
jurca/szn-options
szn-options.js
registerOptionsObserver
function registerOptionsObserver(instance) { if (!instance._mounted || !instance._options) { return } instance._observer.observe(instance._options, { childList: true, attributes: true, characterData: true, subtree: true, attributeFilter: ['disabled', 'label', 'selected', 'title', 'multiple'], }) }
javascript
function registerOptionsObserver(instance) { if (!instance._mounted || !instance._options) { return } instance._observer.observe(instance._options, { childList: true, attributes: true, characterData: true, subtree: true, attributeFilter: ['disabled', 'label', 'selected', 'title', 'multiple'], }) }
[ "function", "registerOptionsObserver", "(", "instance", ")", "{", "if", "(", "!", "instance", ".", "_mounted", "||", "!", "instance", ".", "_options", ")", "{", "return", "}", "instance", ".", "_observer", ".", "observe", "(", "instance", ".", "_options", ",", "{", "childList", ":", "true", ",", "attributes", ":", "true", ",", "characterData", ":", "true", ",", "subtree", ":", "true", ",", "attributeFilter", ":", "[", "'disabled'", ",", "'label'", ",", "'selected'", ",", "'title'", ",", "'multiple'", "]", ",", "}", ")", "}" ]
Registers the provided szn-options element's DOM mutation observer to observe the related options for changes. @param {SznElements.SznOptions} instance The szn-options element instance.
[ "Registers", "the", "provided", "szn", "-", "options", "element", "s", "DOM", "mutation", "observer", "to", "observe", "the", "related", "options", "for", "changes", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L157-L169
57,433
jurca/szn-options
szn-options.js
addEventListeners
function addEventListeners(instance) { if (!instance._mounted || !instance._options) { return } instance._options.addEventListener('change', instance._onSelectionChange) instance._root.addEventListener('mouseover', instance._onItemHovered) instance._root.addEventListener('mousedown', instance._onItemSelectionStart) instance._root.addEventListener('mouseup', instance._onItemClicked) addEventListener('mouseup', instance._onSelectionEnd) }
javascript
function addEventListeners(instance) { if (!instance._mounted || !instance._options) { return } instance._options.addEventListener('change', instance._onSelectionChange) instance._root.addEventListener('mouseover', instance._onItemHovered) instance._root.addEventListener('mousedown', instance._onItemSelectionStart) instance._root.addEventListener('mouseup', instance._onItemClicked) addEventListener('mouseup', instance._onSelectionEnd) }
[ "function", "addEventListeners", "(", "instance", ")", "{", "if", "(", "!", "instance", ".", "_mounted", "||", "!", "instance", ".", "_options", ")", "{", "return", "}", "instance", ".", "_options", ".", "addEventListener", "(", "'change'", ",", "instance", ".", "_onSelectionChange", ")", "instance", ".", "_root", ".", "addEventListener", "(", "'mouseover'", ",", "instance", ".", "_onItemHovered", ")", "instance", ".", "_root", ".", "addEventListener", "(", "'mousedown'", ",", "instance", ".", "_onItemSelectionStart", ")", "instance", ".", "_root", ".", "addEventListener", "(", "'mouseup'", ",", "instance", ".", "_onItemClicked", ")", "addEventListener", "(", "'mouseup'", ",", "instance", ".", "_onSelectionEnd", ")", "}" ]
Registers event listeners that the provided szn-options instance requires to function correctly. The function has no effect if the provided szn-options element is not mounted into the document or has not been provided with its options yet. @param {SznElements.SznOptions} instance The szn-options element instance.
[ "Registers", "event", "listeners", "that", "the", "provided", "szn", "-", "options", "instance", "requires", "to", "function", "correctly", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L179-L189
57,434
jurca/szn-options
szn-options.js
removeEventListeners
function removeEventListeners(instance) { if (instance._options) { instance._options.removeEventListener('change', instance._onSelectionChange) } instance._root.removeEventListener('mouseover', instance._onItemHovered) instance._root.removeEventListener('mousedown', instance._onItemSelectionStart) instance._root.removeEventListener('mouseup', instance._onItemClicked) removeEventListener('mouseup', instance._onSelectionEnd) }
javascript
function removeEventListeners(instance) { if (instance._options) { instance._options.removeEventListener('change', instance._onSelectionChange) } instance._root.removeEventListener('mouseover', instance._onItemHovered) instance._root.removeEventListener('mousedown', instance._onItemSelectionStart) instance._root.removeEventListener('mouseup', instance._onItemClicked) removeEventListener('mouseup', instance._onSelectionEnd) }
[ "function", "removeEventListeners", "(", "instance", ")", "{", "if", "(", "instance", ".", "_options", ")", "{", "instance", ".", "_options", ".", "removeEventListener", "(", "'change'", ",", "instance", ".", "_onSelectionChange", ")", "}", "instance", ".", "_root", ".", "removeEventListener", "(", "'mouseover'", ",", "instance", ".", "_onItemHovered", ")", "instance", ".", "_root", ".", "removeEventListener", "(", "'mousedown'", ",", "instance", ".", "_onItemSelectionStart", ")", "instance", ".", "_root", ".", "removeEventListener", "(", "'mouseup'", ",", "instance", ".", "_onItemClicked", ")", "removeEventListener", "(", "'mouseup'", ",", "instance", ".", "_onSelectionEnd", ")", "}" ]
Deregisters all event listeners used by the provided szn-options element. @param {SznElements.SznOptions} instance The szn-options element instance.
[ "Deregisters", "all", "event", "listeners", "used", "by", "the", "provided", "szn", "-", "options", "element", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L196-L204
57,435
jurca/szn-options
szn-options.js
onItemHovered
function onItemHovered(instance, itemUi) { if (instance._options.disabled || !isEnabledOptionUi(itemUi)) { return } if (instance._options.multiple) { if (instance._dragSelectionStartOption) { updateMultiSelection(instance, itemUi) } return } instance._root.setAttribute('data-szn-options--highlighting', '') const previouslyHighlighted = instance._root.querySelector('[data-szn-options--highlighted]') if (previouslyHighlighted) { previouslyHighlighted.removeAttribute('data-szn-options--highlighted') } itemUi.setAttribute('data-szn-options--highlighted', '') }
javascript
function onItemHovered(instance, itemUi) { if (instance._options.disabled || !isEnabledOptionUi(itemUi)) { return } if (instance._options.multiple) { if (instance._dragSelectionStartOption) { updateMultiSelection(instance, itemUi) } return } instance._root.setAttribute('data-szn-options--highlighting', '') const previouslyHighlighted = instance._root.querySelector('[data-szn-options--highlighted]') if (previouslyHighlighted) { previouslyHighlighted.removeAttribute('data-szn-options--highlighted') } itemUi.setAttribute('data-szn-options--highlighted', '') }
[ "function", "onItemHovered", "(", "instance", ",", "itemUi", ")", "{", "if", "(", "instance", ".", "_options", ".", "disabled", "||", "!", "isEnabledOptionUi", "(", "itemUi", ")", ")", "{", "return", "}", "if", "(", "instance", ".", "_options", ".", "multiple", ")", "{", "if", "(", "instance", ".", "_dragSelectionStartOption", ")", "{", "updateMultiSelection", "(", "instance", ",", "itemUi", ")", "}", "return", "}", "instance", ".", "_root", ".", "setAttribute", "(", "'data-szn-options--highlighting'", ",", "''", ")", "const", "previouslyHighlighted", "=", "instance", ".", "_root", ".", "querySelector", "(", "'[data-szn-options--highlighted]'", ")", "if", "(", "previouslyHighlighted", ")", "{", "previouslyHighlighted", ".", "removeAttribute", "(", "'data-szn-options--highlighted'", ")", "}", "itemUi", ".", "setAttribute", "(", "'data-szn-options--highlighted'", ",", "''", ")", "}" ]
Handles the user moving the mouse pointer over an option in the szn-options element's UI. The function updates the current multiple-items selection if the element represents a multi-select, or updates the currently highlighted item in the UI of a single-select. @param {SznElements.SznOptions} instance The szn-options element instance. @param {Element} itemUi The element which's area the mouse pointer entered.
[ "Handles", "the", "user", "moving", "the", "mouse", "pointer", "over", "an", "option", "in", "the", "szn", "-", "options", "element", "s", "UI", ".", "The", "function", "updates", "the", "current", "multiple", "-", "items", "selection", "if", "the", "element", "represents", "a", "multi", "-", "select", "or", "updates", "the", "currently", "highlighted", "item", "in", "the", "UI", "of", "a", "single", "-", "select", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L214-L232
57,436
jurca/szn-options
szn-options.js
onItemClicked
function onItemClicked(instance, itemUi) { if (instance._dragSelectionStartOption) { // multi-select instance._dragSelectionStartOption = null return } if (instance._options.disabled || !isEnabledOptionUi(itemUi)) { return } instance._root.removeAttribute('data-szn-options--highlighting') instance._options.selectedIndex = itemUi._option.index instance._options.dispatchEvent(new CustomEvent('change', {bubbles: true, cancelable: true})) }
javascript
function onItemClicked(instance, itemUi) { if (instance._dragSelectionStartOption) { // multi-select instance._dragSelectionStartOption = null return } if (instance._options.disabled || !isEnabledOptionUi(itemUi)) { return } instance._root.removeAttribute('data-szn-options--highlighting') instance._options.selectedIndex = itemUi._option.index instance._options.dispatchEvent(new CustomEvent('change', {bubbles: true, cancelable: true})) }
[ "function", "onItemClicked", "(", "instance", ",", "itemUi", ")", "{", "if", "(", "instance", ".", "_dragSelectionStartOption", ")", "{", "// multi-select", "instance", ".", "_dragSelectionStartOption", "=", "null", "return", "}", "if", "(", "instance", ".", "_options", ".", "disabled", "||", "!", "isEnabledOptionUi", "(", "itemUi", ")", ")", "{", "return", "}", "instance", ".", "_root", ".", "removeAttribute", "(", "'data-szn-options--highlighting'", ")", "instance", ".", "_options", ".", "selectedIndex", "=", "itemUi", ".", "_option", ".", "index", "instance", ".", "_options", ".", "dispatchEvent", "(", "new", "CustomEvent", "(", "'change'", ",", "{", "bubbles", ":", "true", ",", "cancelable", ":", "true", "}", ")", ")", "}" ]
Handles the user releasing the primary mouse button over an element representing an item. The function ends multiple-items selection for multi-selects, ends options highlighting and marks the the selected option for single-selects. @param {SznElements.SznOptions} instance The szn-options element instance. @param {Element} itemUi The element at which the user released the primary mouse button.
[ "Handles", "the", "user", "releasing", "the", "primary", "mouse", "button", "over", "an", "element", "representing", "an", "item", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L243-L256
57,437
jurca/szn-options
szn-options.js
onItemSelectionStart
function onItemSelectionStart(instance, itemUi, event) { if (instance._options.disabled || !instance._options.multiple || !isEnabledOptionUi(itemUi)) { return } const options = instance._options.options if (event.shiftKey && instance._previousSelectionStartIndex > -1) { instance._dragSelectionStartOption = options.item(instance._previousSelectionStartIndex) } else { if (event.ctrlKey) { instance._additionalSelectedIndexes = [] for (let i = 0, length = options.length; i < length; i++) { if (options.item(i).selected) { instance._additionalSelectedIndexes.push(i) } } instance._invertSelection = itemUi._option.selected } else { instance._invertSelection = false } instance._dragSelectionStartOption = itemUi._option } instance._previousSelectionStartIndex = instance._dragSelectionStartOption.index updateMultiSelection(instance, itemUi) }
javascript
function onItemSelectionStart(instance, itemUi, event) { if (instance._options.disabled || !instance._options.multiple || !isEnabledOptionUi(itemUi)) { return } const options = instance._options.options if (event.shiftKey && instance._previousSelectionStartIndex > -1) { instance._dragSelectionStartOption = options.item(instance._previousSelectionStartIndex) } else { if (event.ctrlKey) { instance._additionalSelectedIndexes = [] for (let i = 0, length = options.length; i < length; i++) { if (options.item(i).selected) { instance._additionalSelectedIndexes.push(i) } } instance._invertSelection = itemUi._option.selected } else { instance._invertSelection = false } instance._dragSelectionStartOption = itemUi._option } instance._previousSelectionStartIndex = instance._dragSelectionStartOption.index updateMultiSelection(instance, itemUi) }
[ "function", "onItemSelectionStart", "(", "instance", ",", "itemUi", ",", "event", ")", "{", "if", "(", "instance", ".", "_options", ".", "disabled", "||", "!", "instance", ".", "_options", ".", "multiple", "||", "!", "isEnabledOptionUi", "(", "itemUi", ")", ")", "{", "return", "}", "const", "options", "=", "instance", ".", "_options", ".", "options", "if", "(", "event", ".", "shiftKey", "&&", "instance", ".", "_previousSelectionStartIndex", ">", "-", "1", ")", "{", "instance", ".", "_dragSelectionStartOption", "=", "options", ".", "item", "(", "instance", ".", "_previousSelectionStartIndex", ")", "}", "else", "{", "if", "(", "event", ".", "ctrlKey", ")", "{", "instance", ".", "_additionalSelectedIndexes", "=", "[", "]", "for", "(", "let", "i", "=", "0", ",", "length", "=", "options", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "{", "if", "(", "options", ".", "item", "(", "i", ")", ".", "selected", ")", "{", "instance", ".", "_additionalSelectedIndexes", ".", "push", "(", "i", ")", "}", "}", "instance", ".", "_invertSelection", "=", "itemUi", ".", "_option", ".", "selected", "}", "else", "{", "instance", ".", "_invertSelection", "=", "false", "}", "instance", ".", "_dragSelectionStartOption", "=", "itemUi", ".", "_option", "}", "instance", ".", "_previousSelectionStartIndex", "=", "instance", ".", "_dragSelectionStartOption", ".", "index", "updateMultiSelection", "(", "instance", ",", "itemUi", ")", "}" ]
Handles start of the user dragging the mouse pointer over the UI of a multi-selection szn-options element. The function marks the starting item. The function marks the starting item used previously as the current starting item if the Shift key is pressed. The function marks the indexes of the currently selected items if the Ctrl key is pressed and the Shift key is not. Also, if the Ctrl key pressed, the Shift key is not, and the user starts at an already selected item, the function will mark this as inverted selection. The function has no effect for single-selects. @param {SznElements.SznOptions} instance The szn-options element instance. @param {Element} itemUi The element at which the user pressed the primary mouse button down. @param {MouseEvent} event The mouse event representing the user's action.
[ "Handles", "start", "of", "the", "user", "dragging", "the", "mouse", "pointer", "over", "the", "UI", "of", "a", "multi", "-", "selection", "szn", "-", "options", "element", ".", "The", "function", "marks", "the", "starting", "item", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L273-L297
57,438
jurca/szn-options
szn-options.js
scrollToSelection
function scrollToSelection(instance, selectionStartIndex, selectionEndIndex) { const lastSelectionIndexes = instance._lastSelectionIndexes if ( selectionStartIndex !== -1 && (selectionStartIndex !== lastSelectionIndexes.start || selectionEndIndex !== lastSelectionIndexes.end) ) { const changedIndex = selectionStartIndex !== lastSelectionIndexes.start ? selectionStartIndex : selectionEndIndex scrollToOption(instance, changedIndex) } lastSelectionIndexes.start = selectionStartIndex lastSelectionIndexes.end = selectionEndIndex }
javascript
function scrollToSelection(instance, selectionStartIndex, selectionEndIndex) { const lastSelectionIndexes = instance._lastSelectionIndexes if ( selectionStartIndex !== -1 && (selectionStartIndex !== lastSelectionIndexes.start || selectionEndIndex !== lastSelectionIndexes.end) ) { const changedIndex = selectionStartIndex !== lastSelectionIndexes.start ? selectionStartIndex : selectionEndIndex scrollToOption(instance, changedIndex) } lastSelectionIndexes.start = selectionStartIndex lastSelectionIndexes.end = selectionEndIndex }
[ "function", "scrollToSelection", "(", "instance", ",", "selectionStartIndex", ",", "selectionEndIndex", ")", "{", "const", "lastSelectionIndexes", "=", "instance", ".", "_lastSelectionIndexes", "if", "(", "selectionStartIndex", "!==", "-", "1", "&&", "(", "selectionStartIndex", "!==", "lastSelectionIndexes", ".", "start", "||", "selectionEndIndex", "!==", "lastSelectionIndexes", ".", "end", ")", ")", "{", "const", "changedIndex", "=", "selectionStartIndex", "!==", "lastSelectionIndexes", ".", "start", "?", "selectionStartIndex", ":", "selectionEndIndex", "scrollToOption", "(", "instance", ",", "changedIndex", ")", "}", "lastSelectionIndexes", ".", "start", "=", "selectionStartIndex", "lastSelectionIndexes", ".", "end", "=", "selectionEndIndex", "}" ]
Scrolls, only if necessary, the UI of the provided szn-options element to make the last selected option visible. Which option is the last selected one is determined by comparing the provided index with the indexes passed to the previous call of this function. @param {SznElements.SznOptions} instance The szn-options element instance. @param {number} selectionStartIndex The index of the first selected option. The index must be a non-negative integer and cannot be greater that the total number of options; or set to <code>-1</code> if there is no option currently selected. @param {number} selectionEndIndex The index of the last selected option. The index must be a non-negative integer, cannot be greater than the total number of options and must not be lower than the <code>selectionStartIndex</code>; or set to <code>-1</code> if there is no option currently selected.
[ "Scrolls", "only", "if", "necessary", "the", "UI", "of", "the", "provided", "szn", "-", "options", "element", "to", "make", "the", "last", "selected", "option", "visible", ".", "Which", "option", "is", "the", "last", "selected", "one", "is", "determined", "by", "comparing", "the", "provided", "index", "with", "the", "indexes", "passed", "to", "the", "previous", "call", "of", "this", "function", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L312-L324
57,439
jurca/szn-options
szn-options.js
scrollToOption
function scrollToOption(instance, optionIndex) { const ui = instance._root if (ui.clientHeight >= ui.scrollHeight) { return } const uiBounds = ui.getBoundingClientRect() const options = instance._root.querySelectorAll('[data-szn-options--option]') const optionBounds = options[optionIndex].getBoundingClientRect() if (optionBounds.top >= uiBounds.top && optionBounds.bottom <= uiBounds.bottom) { return } const delta = optionBounds.top < uiBounds.top ? optionBounds.top - uiBounds.top : optionBounds.bottom - uiBounds.bottom ui.scrollTop += delta }
javascript
function scrollToOption(instance, optionIndex) { const ui = instance._root if (ui.clientHeight >= ui.scrollHeight) { return } const uiBounds = ui.getBoundingClientRect() const options = instance._root.querySelectorAll('[data-szn-options--option]') const optionBounds = options[optionIndex].getBoundingClientRect() if (optionBounds.top >= uiBounds.top && optionBounds.bottom <= uiBounds.bottom) { return } const delta = optionBounds.top < uiBounds.top ? optionBounds.top - uiBounds.top : optionBounds.bottom - uiBounds.bottom ui.scrollTop += delta }
[ "function", "scrollToOption", "(", "instance", ",", "optionIndex", ")", "{", "const", "ui", "=", "instance", ".", "_root", "if", "(", "ui", ".", "clientHeight", ">=", "ui", ".", "scrollHeight", ")", "{", "return", "}", "const", "uiBounds", "=", "ui", ".", "getBoundingClientRect", "(", ")", "const", "options", "=", "instance", ".", "_root", ".", "querySelectorAll", "(", "'[data-szn-options--option]'", ")", "const", "optionBounds", "=", "options", "[", "optionIndex", "]", ".", "getBoundingClientRect", "(", ")", "if", "(", "optionBounds", ".", "top", ">=", "uiBounds", ".", "top", "&&", "optionBounds", ".", "bottom", "<=", "uiBounds", ".", "bottom", ")", "{", "return", "}", "const", "delta", "=", "optionBounds", ".", "top", "<", "uiBounds", ".", "top", "?", "optionBounds", ".", "top", "-", "uiBounds", ".", "top", ":", "optionBounds", ".", "bottom", "-", "uiBounds", ".", "bottom", "ui", ".", "scrollTop", "+=", "delta", "}" ]
Scrolls, only if necessary, the UI of the provided szn-options element to make the option at the specified index fully visible. @param {SznElements.SznOptions} instance The szn-options element instance. @param {number} optionIndex The index of the option to select. The index must be a non-negative integer and cannot be greater than the total number of options.
[ "Scrolls", "only", "if", "necessary", "the", "UI", "of", "the", "provided", "szn", "-", "options", "element", "to", "make", "the", "option", "at", "the", "specified", "index", "fully", "visible", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L334-L352
57,440
jurca/szn-options
szn-options.js
updateMultiSelection
function updateMultiSelection(instance, lastHoveredItem) { const startIndex = instance._dragSelectionStartOption.index const lastIndex = lastHoveredItem._option.index const minIndex = Math.min(startIndex, lastIndex) const maxIndex = Math.max(startIndex, lastIndex) const options = instance._options.options const additionalIndexes = instance._additionalSelectedIndexes for (let i = 0, length = options.length; i < length; i++) { const option = options.item(i) if (isOptionEnabled(option)) { let isOptionSelected = additionalIndexes.indexOf(i) > -1 if (i >= minIndex && i <= maxIndex) { isOptionSelected = !instance._invertSelection } option.selected = isOptionSelected } } instance._options.dispatchEvent(new CustomEvent('change', {bubbles: true, cancelable: true})) }
javascript
function updateMultiSelection(instance, lastHoveredItem) { const startIndex = instance._dragSelectionStartOption.index const lastIndex = lastHoveredItem._option.index const minIndex = Math.min(startIndex, lastIndex) const maxIndex = Math.max(startIndex, lastIndex) const options = instance._options.options const additionalIndexes = instance._additionalSelectedIndexes for (let i = 0, length = options.length; i < length; i++) { const option = options.item(i) if (isOptionEnabled(option)) { let isOptionSelected = additionalIndexes.indexOf(i) > -1 if (i >= minIndex && i <= maxIndex) { isOptionSelected = !instance._invertSelection } option.selected = isOptionSelected } } instance._options.dispatchEvent(new CustomEvent('change', {bubbles: true, cancelable: true})) }
[ "function", "updateMultiSelection", "(", "instance", ",", "lastHoveredItem", ")", "{", "const", "startIndex", "=", "instance", ".", "_dragSelectionStartOption", ".", "index", "const", "lastIndex", "=", "lastHoveredItem", ".", "_option", ".", "index", "const", "minIndex", "=", "Math", ".", "min", "(", "startIndex", ",", "lastIndex", ")", "const", "maxIndex", "=", "Math", ".", "max", "(", "startIndex", ",", "lastIndex", ")", "const", "options", "=", "instance", ".", "_options", ".", "options", "const", "additionalIndexes", "=", "instance", ".", "_additionalSelectedIndexes", "for", "(", "let", "i", "=", "0", ",", "length", "=", "options", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "{", "const", "option", "=", "options", ".", "item", "(", "i", ")", "if", "(", "isOptionEnabled", "(", "option", ")", ")", "{", "let", "isOptionSelected", "=", "additionalIndexes", ".", "indexOf", "(", "i", ")", ">", "-", "1", "if", "(", "i", ">=", "minIndex", "&&", "i", "<=", "maxIndex", ")", "{", "isOptionSelected", "=", "!", "instance", ".", "_invertSelection", "}", "option", ".", "selected", "=", "isOptionSelected", "}", "}", "instance", ".", "_options", ".", "dispatchEvent", "(", "new", "CustomEvent", "(", "'change'", ",", "{", "bubbles", ":", "true", ",", "cancelable", ":", "true", "}", ")", ")", "}" ]
Updates the multiple-items selection. This function is meant to be used with multi-selects when the user is selecting multiple items by dragging the mouse pointer over them. Any item which's index is in the provided instance's list of additionally selected items will be marked as selected as well. @param {SznElements.SznOptions} instance The szn-options element instance. @param {Element} lastHoveredItem The element representing the UI of the last option the user has hovered using their mouse pointer.
[ "Updates", "the", "multiple", "-", "items", "selection", ".", "This", "function", "is", "meant", "to", "be", "used", "with", "multi", "-", "selects", "when", "the", "user", "is", "selecting", "multiple", "items", "by", "dragging", "the", "mouse", "pointer", "over", "them", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L365-L385
57,441
jurca/szn-options
szn-options.js
updateUi
function updateUi(instance) { if (!instance._options) { return } if (instance._options.disabled) { instance._root.setAttribute('disabled', '') } else { instance._root.removeAttribute('disabled') } if (instance._options.multiple) { instance._root.setAttribute('data-szn-options--multiple', '') } else { instance._root.removeAttribute('data-szn-options--multiple') } updateGroupUi(instance._root, instance._options) if (instance._mounted) { const options = instance._options.options let lastSelectedIndex = -1 for (let i = options.length - 1; i >= 0; i--) { if (options.item(i).selected) { lastSelectedIndex = i break } } scrollToSelection(instance, instance._options.selectedIndex, lastSelectedIndex) } }
javascript
function updateUi(instance) { if (!instance._options) { return } if (instance._options.disabled) { instance._root.setAttribute('disabled', '') } else { instance._root.removeAttribute('disabled') } if (instance._options.multiple) { instance._root.setAttribute('data-szn-options--multiple', '') } else { instance._root.removeAttribute('data-szn-options--multiple') } updateGroupUi(instance._root, instance._options) if (instance._mounted) { const options = instance._options.options let lastSelectedIndex = -1 for (let i = options.length - 1; i >= 0; i--) { if (options.item(i).selected) { lastSelectedIndex = i break } } scrollToSelection(instance, instance._options.selectedIndex, lastSelectedIndex) } }
[ "function", "updateUi", "(", "instance", ")", "{", "if", "(", "!", "instance", ".", "_options", ")", "{", "return", "}", "if", "(", "instance", ".", "_options", ".", "disabled", ")", "{", "instance", ".", "_root", ".", "setAttribute", "(", "'disabled'", ",", "''", ")", "}", "else", "{", "instance", ".", "_root", ".", "removeAttribute", "(", "'disabled'", ")", "}", "if", "(", "instance", ".", "_options", ".", "multiple", ")", "{", "instance", ".", "_root", ".", "setAttribute", "(", "'data-szn-options--multiple'", ",", "''", ")", "}", "else", "{", "instance", ".", "_root", ".", "removeAttribute", "(", "'data-szn-options--multiple'", ")", "}", "updateGroupUi", "(", "instance", ".", "_root", ",", "instance", ".", "_options", ")", "if", "(", "instance", ".", "_mounted", ")", "{", "const", "options", "=", "instance", ".", "_options", ".", "options", "let", "lastSelectedIndex", "=", "-", "1", "for", "(", "let", "i", "=", "options", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "options", ".", "item", "(", "i", ")", ".", "selected", ")", "{", "lastSelectedIndex", "=", "i", "break", "}", "}", "scrollToSelection", "(", "instance", ",", "instance", ".", "_options", ".", "selectedIndex", ",", "lastSelectedIndex", ")", "}", "}" ]
Updates the UI, if the provided szn-options element has already been provided with the options to display. The functions synchronizes the displayed UI to reflect the available options, their status, and scrolls to the last selected option if it is not visible. @param {SznElements.SznOptions} instance The szn-options element's instance.
[ "Updates", "the", "UI", "if", "the", "provided", "szn", "-", "options", "element", "has", "already", "been", "provided", "with", "the", "options", "to", "display", ".", "The", "functions", "synchronizes", "the", "displayed", "UI", "to", "reflect", "the", "available", "options", "their", "status", "and", "scrolls", "to", "the", "last", "selected", "option", "if", "it", "is", "not", "visible", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L422-L450
57,442
jurca/szn-options
szn-options.js
updateGroupUi
function updateGroupUi(uiContainer, optionsGroup) { removeRemovedItems(uiContainer, optionsGroup) updateExistingItems(uiContainer) addMissingItems(uiContainer, optionsGroup) }
javascript
function updateGroupUi(uiContainer, optionsGroup) { removeRemovedItems(uiContainer, optionsGroup) updateExistingItems(uiContainer) addMissingItems(uiContainer, optionsGroup) }
[ "function", "updateGroupUi", "(", "uiContainer", ",", "optionsGroup", ")", "{", "removeRemovedItems", "(", "uiContainer", ",", "optionsGroup", ")", "updateExistingItems", "(", "uiContainer", ")", "addMissingItems", "(", "uiContainer", ",", "optionsGroup", ")", "}" ]
Updates the contents of the provided UI to reflect the options in the provided options container. The function removes removed options from the UI, updates the existing and adds the missing ones. @param {Element} uiContainer The element containing the constructed UI reflecting the provided options. @param {HTMLElement} optionsGroup The element containing the options to be reflected in the UI.
[ "Updates", "the", "contents", "of", "the", "provided", "UI", "to", "reflect", "the", "options", "in", "the", "provided", "options", "container", ".", "The", "function", "removes", "removed", "options", "from", "the", "UI", "updates", "the", "existing", "and", "adds", "the", "missing", "ones", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L459-L463
57,443
jurca/szn-options
szn-options.js
removeRemovedItems
function removeRemovedItems(uiContainer, optionsGroup) { const options = Array.prototype.slice.call(optionsGroup.children) let currentItemUi = uiContainer.firstElementChild while (currentItemUi) { if (options.indexOf(currentItemUi._option) > -1) { currentItemUi = currentItemUi.nextElementSibling continue } const itemToRemove = currentItemUi currentItemUi = currentItemUi.nextElementSibling uiContainer.removeChild(itemToRemove) } }
javascript
function removeRemovedItems(uiContainer, optionsGroup) { const options = Array.prototype.slice.call(optionsGroup.children) let currentItemUi = uiContainer.firstElementChild while (currentItemUi) { if (options.indexOf(currentItemUi._option) > -1) { currentItemUi = currentItemUi.nextElementSibling continue } const itemToRemove = currentItemUi currentItemUi = currentItemUi.nextElementSibling uiContainer.removeChild(itemToRemove) } }
[ "function", "removeRemovedItems", "(", "uiContainer", ",", "optionsGroup", ")", "{", "const", "options", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "optionsGroup", ".", "children", ")", "let", "currentItemUi", "=", "uiContainer", ".", "firstElementChild", "while", "(", "currentItemUi", ")", "{", "if", "(", "options", ".", "indexOf", "(", "currentItemUi", ".", "_option", ")", ">", "-", "1", ")", "{", "currentItemUi", "=", "currentItemUi", ".", "nextElementSibling", "continue", "}", "const", "itemToRemove", "=", "currentItemUi", "currentItemUi", "=", "currentItemUi", ".", "nextElementSibling", "uiContainer", ".", "removeChild", "(", "itemToRemove", ")", "}", "}" ]
Removes UI items from the UI that have been representing the options and option groups that have been removed from the provided container of options. @param {Element} uiContainer The element containing the elements reflecting the provided options and providing the UI for the options. @param {HTMLElement} optionsGroup The element containing the options for which this szn-options element is providing the UI.
[ "Removes", "UI", "items", "from", "the", "UI", "that", "have", "been", "representing", "the", "options", "and", "option", "groups", "that", "have", "been", "removed", "from", "the", "provided", "container", "of", "options", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L474-L487
57,444
jurca/szn-options
szn-options.js
updateExistingItems
function updateExistingItems(groupUi) { let itemUi = groupUi.firstElementChild while (itemUi) { updateItem(itemUi) itemUi = itemUi.nextElementSibling } }
javascript
function updateExistingItems(groupUi) { let itemUi = groupUi.firstElementChild while (itemUi) { updateItem(itemUi) itemUi = itemUi.nextElementSibling } }
[ "function", "updateExistingItems", "(", "groupUi", ")", "{", "let", "itemUi", "=", "groupUi", ".", "firstElementChild", "while", "(", "itemUi", ")", "{", "updateItem", "(", "itemUi", ")", "itemUi", "=", "itemUi", ".", "nextElementSibling", "}", "}" ]
Updates all items in the provided UI container to reflect the current state of their associated options. @param {Element} groupUi The element containing the elements representing the UIs of the options.
[ "Updates", "all", "items", "in", "the", "provided", "UI", "container", "to", "reflect", "the", "current", "state", "of", "their", "associated", "options", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L494-L500
57,445
jurca/szn-options
szn-options.js
addMissingItems
function addMissingItems(groupUi, options) { let nextItemUi = groupUi.firstElementChild let nextOption = options.firstElementChild while (nextOption) { if (!nextItemUi || nextItemUi._option !== nextOption) { const newItemUi = document.createElement('szn-') newItemUi._option = nextOption newItemUi.setAttribute('data-szn-options--' + (nextOption.tagName === 'OPTGROUP' ? 'optgroup' : 'option'), '') updateItem(newItemUi) groupUi.insertBefore(newItemUi, nextItemUi) } else { nextItemUi = nextItemUi && nextItemUi.nextElementSibling } nextOption = nextOption.nextElementSibling } }
javascript
function addMissingItems(groupUi, options) { let nextItemUi = groupUi.firstElementChild let nextOption = options.firstElementChild while (nextOption) { if (!nextItemUi || nextItemUi._option !== nextOption) { const newItemUi = document.createElement('szn-') newItemUi._option = nextOption newItemUi.setAttribute('data-szn-options--' + (nextOption.tagName === 'OPTGROUP' ? 'optgroup' : 'option'), '') updateItem(newItemUi) groupUi.insertBefore(newItemUi, nextItemUi) } else { nextItemUi = nextItemUi && nextItemUi.nextElementSibling } nextOption = nextOption.nextElementSibling } }
[ "function", "addMissingItems", "(", "groupUi", ",", "options", ")", "{", "let", "nextItemUi", "=", "groupUi", ".", "firstElementChild", "let", "nextOption", "=", "options", ".", "firstElementChild", "while", "(", "nextOption", ")", "{", "if", "(", "!", "nextItemUi", "||", "nextItemUi", ".", "_option", "!==", "nextOption", ")", "{", "const", "newItemUi", "=", "document", ".", "createElement", "(", "'szn-'", ")", "newItemUi", ".", "_option", "=", "nextOption", "newItemUi", ".", "setAttribute", "(", "'data-szn-options--'", "+", "(", "nextOption", ".", "tagName", "===", "'OPTGROUP'", "?", "'optgroup'", ":", "'option'", ")", ",", "''", ")", "updateItem", "(", "newItemUi", ")", "groupUi", ".", "insertBefore", "(", "newItemUi", ",", "nextItemUi", ")", "}", "else", "{", "nextItemUi", "=", "nextItemUi", "&&", "nextItemUi", ".", "nextElementSibling", "}", "nextOption", "=", "nextOption", ".", "nextElementSibling", "}", "}" ]
Adds the options present in the options container missing the UI into the UI, while preserving the order of the options. Option groups are added recursively. @param {Element} groupUi The element containing the UIs of the options. The new options will be inserted into this element's children. @param {HTMLElement} options An element containing the <code>option</code> and <code>optgroup</code> elements that the UI reflects.
[ "Adds", "the", "options", "present", "in", "the", "options", "container", "missing", "the", "UI", "into", "the", "UI", "while", "preserving", "the", "order", "of", "the", "options", ".", "Option", "groups", "are", "added", "recursively", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L548-L564
57,446
iAdramelk/css-url-edit
lib/css-url-edit.js
_collectURLs
function _collectURLs ( token ) { var elem, isArrayElem; if ( Array.isArray( token ) ) { for ( var i = 0; i < token.length; i++ ) { elem = token[ i ]; isArrayElem = Array.isArray( elem ); if ( isArrayElem && ( elem[ 0 ] === 'uri' ) ) { urls.push( elem ); } else if ( isArrayElem ) { _collectURLs( elem ); } } } }
javascript
function _collectURLs ( token ) { var elem, isArrayElem; if ( Array.isArray( token ) ) { for ( var i = 0; i < token.length; i++ ) { elem = token[ i ]; isArrayElem = Array.isArray( elem ); if ( isArrayElem && ( elem[ 0 ] === 'uri' ) ) { urls.push( elem ); } else if ( isArrayElem ) { _collectURLs( elem ); } } } }
[ "function", "_collectURLs", "(", "token", ")", "{", "var", "elem", ",", "isArrayElem", ";", "if", "(", "Array", ".", "isArray", "(", "token", ")", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "token", ".", "length", ";", "i", "++", ")", "{", "elem", "=", "token", "[", "i", "]", ";", "isArrayElem", "=", "Array", ".", "isArray", "(", "elem", ")", ";", "if", "(", "isArrayElem", "&&", "(", "elem", "[", "0", "]", "===", "'uri'", ")", ")", "{", "urls", ".", "push", "(", "elem", ")", ";", "}", "else", "if", "(", "isArrayElem", ")", "{", "_collectURLs", "(", "elem", ")", ";", "}", "}", "}", "}" ]
collection of urls to work with Generates initial document tree. @private
[ "collection", "of", "urls", "to", "work", "with", "Generates", "initial", "document", "tree", "." ]
7cbff3b449db5e343a0fe071df138f95468fa60d
https://github.com/iAdramelk/css-url-edit/blob/7cbff3b449db5e343a0fe071df138f95468fa60d/lib/css-url-edit.js#L35-L60
57,447
iAdramelk/css-url-edit
lib/css-url-edit.js
function ( mask ) { if ( mask && ( mask instanceof RegExp ) !== true ) { throw { type: 'getURLs', message: 'First argument must be RegExp' }; } return urls.map( function ( value ) { return _getURLValue( value ); } ).filter( function ( value, pos, self ) { var unique = self.indexOf( value ) === pos; if ( mask && unique ) { return mask.test( value ); } else { return unique; } } ); }
javascript
function ( mask ) { if ( mask && ( mask instanceof RegExp ) !== true ) { throw { type: 'getURLs', message: 'First argument must be RegExp' }; } return urls.map( function ( value ) { return _getURLValue( value ); } ).filter( function ( value, pos, self ) { var unique = self.indexOf( value ) === pos; if ( mask && unique ) { return mask.test( value ); } else { return unique; } } ); }
[ "function", "(", "mask", ")", "{", "if", "(", "mask", "&&", "(", "mask", "instanceof", "RegExp", ")", "!==", "true", ")", "{", "throw", "{", "type", ":", "'getURLs'", ",", "message", ":", "'First argument must be RegExp'", "}", ";", "}", "return", "urls", ".", "map", "(", "function", "(", "value", ")", "{", "return", "_getURLValue", "(", "value", ")", ";", "}", ")", ".", "filter", "(", "function", "(", "value", ",", "pos", ",", "self", ")", "{", "var", "unique", "=", "self", ".", "indexOf", "(", "value", ")", "===", "pos", ";", "if", "(", "mask", "&&", "unique", ")", "{", "return", "mask", ".", "test", "(", "value", ")", ";", "}", "else", "{", "return", "unique", ";", "}", "}", ")", ";", "}" ]
Returns list of unique URLs in css document. @param {regexp} mask RegExp to test URLs against. @return {array} Array of matchet URLs.
[ "Returns", "list", "of", "unique", "URLs", "in", "css", "document", "." ]
7cbff3b449db5e343a0fe071df138f95468fa60d
https://github.com/iAdramelk/css-url-edit/blob/7cbff3b449db5e343a0fe071df138f95468fa60d/lib/css-url-edit.js#L105-L133
57,448
iAdramelk/css-url-edit
lib/css-url-edit.js
function ( from_value, to_value ) { var type; if ( from_value instanceof RegExp ) { type = 'RegExp'; } else if ( typeof from_value === 'string' ) { type = 'String'; } else { throw { type: 'changeURLContent', message: 'First argument must be RegExp of String' }; } if ( to_value === undefined ) { to_value = ""; } else if( typeof to_value !== 'string' ) { throw { type: 'changeURLContent', message: 'Second argument must be String' }; } urls.filter( function ( value ) { if ( type === "RegExp" ) { return from_value.test( _getURLValue( value ) ); } else { return _getURLValue( value ).indexOf( from_value ) !== -1; } } ).forEach( function ( value ) { var new_value = _getURLValue( value ).replace( from_value, to_value ); _setURLValue( value, new_value ); } ); }
javascript
function ( from_value, to_value ) { var type; if ( from_value instanceof RegExp ) { type = 'RegExp'; } else if ( typeof from_value === 'string' ) { type = 'String'; } else { throw { type: 'changeURLContent', message: 'First argument must be RegExp of String' }; } if ( to_value === undefined ) { to_value = ""; } else if( typeof to_value !== 'string' ) { throw { type: 'changeURLContent', message: 'Second argument must be String' }; } urls.filter( function ( value ) { if ( type === "RegExp" ) { return from_value.test( _getURLValue( value ) ); } else { return _getURLValue( value ).indexOf( from_value ) !== -1; } } ).forEach( function ( value ) { var new_value = _getURLValue( value ).replace( from_value, to_value ); _setURLValue( value, new_value ); } ); }
[ "function", "(", "from_value", ",", "to_value", ")", "{", "var", "type", ";", "if", "(", "from_value", "instanceof", "RegExp", ")", "{", "type", "=", "'RegExp'", ";", "}", "else", "if", "(", "typeof", "from_value", "===", "'string'", ")", "{", "type", "=", "'String'", ";", "}", "else", "{", "throw", "{", "type", ":", "'changeURLContent'", ",", "message", ":", "'First argument must be RegExp of String'", "}", ";", "}", "if", "(", "to_value", "===", "undefined", ")", "{", "to_value", "=", "\"\"", ";", "}", "else", "if", "(", "typeof", "to_value", "!==", "'string'", ")", "{", "throw", "{", "type", ":", "'changeURLContent'", ",", "message", ":", "'Second argument must be String'", "}", ";", "}", "urls", ".", "filter", "(", "function", "(", "value", ")", "{", "if", "(", "type", "===", "\"RegExp\"", ")", "{", "return", "from_value", ".", "test", "(", "_getURLValue", "(", "value", ")", ")", ";", "}", "else", "{", "return", "_getURLValue", "(", "value", ")", ".", "indexOf", "(", "from_value", ")", "!==", "-", "1", ";", "}", "}", ")", ".", "forEach", "(", "function", "(", "value", ")", "{", "var", "new_value", "=", "_getURLValue", "(", "value", ")", ".", "replace", "(", "from_value", ",", "to_value", ")", ";", "_setURLValue", "(", "value", ",", "new_value", ")", ";", "}", ")", ";", "}" ]
Replace content of every URL matching RegExp with new content. @param {regexp|string} or from_value Mask to select urls with. @param {string} to_value Rule to apply on found items.
[ "Replace", "content", "of", "every", "URL", "matching", "RegExp", "with", "new", "content", "." ]
7cbff3b449db5e343a0fe071df138f95468fa60d
https://github.com/iAdramelk/css-url-edit/blob/7cbff3b449db5e343a0fe071df138f95468fa60d/lib/css-url-edit.js#L179-L226
57,449
sydneystockholm/blog.md
lib/blog.js
Blog
function Blog(loader, options) { this.slugs = {}; this.ids = {}; this.posts = []; this.length = 0; options = options || {}; if (typeof loader === 'string') { loader = new FileSystemLoader(loader, options); } else if (Array.isArray(loader)) { loader = new ArrayLoader(loader); } var self = this; loader.on('error', function (err) { self.emit('error', err); }); loader.on('load', this.onLoad.bind(this)); loader.on('new_post', this.onNewPost.bind(this)); loader.on('updated_post', this.onUpdatedPost.bind(this)); loader.on('removed_post', this.onRemovedPost.bind(this)); }
javascript
function Blog(loader, options) { this.slugs = {}; this.ids = {}; this.posts = []; this.length = 0; options = options || {}; if (typeof loader === 'string') { loader = new FileSystemLoader(loader, options); } else if (Array.isArray(loader)) { loader = new ArrayLoader(loader); } var self = this; loader.on('error', function (err) { self.emit('error', err); }); loader.on('load', this.onLoad.bind(this)); loader.on('new_post', this.onNewPost.bind(this)); loader.on('updated_post', this.onUpdatedPost.bind(this)); loader.on('removed_post', this.onRemovedPost.bind(this)); }
[ "function", "Blog", "(", "loader", ",", "options", ")", "{", "this", ".", "slugs", "=", "{", "}", ";", "this", ".", "ids", "=", "{", "}", ";", "this", ".", "posts", "=", "[", "]", ";", "this", ".", "length", "=", "0", ";", "options", "=", "options", "||", "{", "}", ";", "if", "(", "typeof", "loader", "===", "'string'", ")", "{", "loader", "=", "new", "FileSystemLoader", "(", "loader", ",", "options", ")", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "loader", ")", ")", "{", "loader", "=", "new", "ArrayLoader", "(", "loader", ")", ";", "}", "var", "self", "=", "this", ";", "loader", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "self", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", ")", ";", "loader", ".", "on", "(", "'load'", ",", "this", ".", "onLoad", ".", "bind", "(", "this", ")", ")", ";", "loader", ".", "on", "(", "'new_post'", ",", "this", ".", "onNewPost", ".", "bind", "(", "this", ")", ")", ";", "loader", ".", "on", "(", "'updated_post'", ",", "this", ".", "onUpdatedPost", ".", "bind", "(", "this", ")", ")", ";", "loader", ".", "on", "(", "'removed_post'", ",", "this", ".", "onRemovedPost", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Create a new blog. @param {Loader|Array|String} loader @param {Object} options (optional)
[ "Create", "a", "new", "blog", "." ]
0b145fa1620cbe8b7296eb242241ee93223db9f9
https://github.com/sydneystockholm/blog.md/blob/0b145fa1620cbe8b7296eb242241ee93223db9f9/lib/blog.js#L16-L35
57,450
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/text.js
function( offset ) { // Saved the children count and text length beforehand. var parent = this.$.parentNode, count = parent.childNodes.length, length = this.getLength(); var doc = this.getDocument(); var retval = new CKEDITOR.dom.text( this.$.splitText( offset ), doc ); if ( parent.childNodes.length == count ) { // If the offset is after the last char, IE creates the text node // on split, but don't include it into the DOM. So, we have to do // that manually here. if ( offset >= length ) { retval = doc.createText( '' ); retval.insertAfter( this ); } else { // IE BUG: IE8+ does not update the childNodes array in DOM after splitText(), // we need to make some DOM changes to make it update. (#3436) var workaround = doc.createText( '' ); workaround.insertAfter( retval ); workaround.remove(); } } return retval; }
javascript
function( offset ) { // Saved the children count and text length beforehand. var parent = this.$.parentNode, count = parent.childNodes.length, length = this.getLength(); var doc = this.getDocument(); var retval = new CKEDITOR.dom.text( this.$.splitText( offset ), doc ); if ( parent.childNodes.length == count ) { // If the offset is after the last char, IE creates the text node // on split, but don't include it into the DOM. So, we have to do // that manually here. if ( offset >= length ) { retval = doc.createText( '' ); retval.insertAfter( this ); } else { // IE BUG: IE8+ does not update the childNodes array in DOM after splitText(), // we need to make some DOM changes to make it update. (#3436) var workaround = doc.createText( '' ); workaround.insertAfter( retval ); workaround.remove(); } } return retval; }
[ "function", "(", "offset", ")", "{", "// Saved the children count and text length beforehand.", "var", "parent", "=", "this", ".", "$", ".", "parentNode", ",", "count", "=", "parent", ".", "childNodes", ".", "length", ",", "length", "=", "this", ".", "getLength", "(", ")", ";", "var", "doc", "=", "this", ".", "getDocument", "(", ")", ";", "var", "retval", "=", "new", "CKEDITOR", ".", "dom", ".", "text", "(", "this", ".", "$", ".", "splitText", "(", "offset", ")", ",", "doc", ")", ";", "if", "(", "parent", ".", "childNodes", ".", "length", "==", "count", ")", "{", "// If the offset is after the last char, IE creates the text node", "// on split, but don't include it into the DOM. So, we have to do", "// that manually here.", "if", "(", "offset", ">=", "length", ")", "{", "retval", "=", "doc", ".", "createText", "(", "''", ")", ";", "retval", ".", "insertAfter", "(", "this", ")", ";", "}", "else", "{", "// IE BUG: IE8+ does not update the childNodes array in DOM after splitText(),", "// we need to make some DOM changes to make it update. (#3436)", "var", "workaround", "=", "doc", ".", "createText", "(", "''", ")", ";", "workaround", ".", "insertAfter", "(", "retval", ")", ";", "workaround", ".", "remove", "(", ")", ";", "}", "}", "return", "retval", ";", "}" ]
Breaks this text node into two nodes at the specified offset, keeping both in the tree as siblings. This node then only contains all the content up to the offset point. A new text node, which is inserted as the next sibling of this node, contains all the content at and after the offset point. When the offset is equal to the length of this node, the new node has no data. @param {Number} The position at which to split, starting from zero. @returns {CKEDITOR.dom.text} The new text node.
[ "Breaks", "this", "text", "node", "into", "two", "nodes", "at", "the", "specified", "offset", "keeping", "both", "in", "the", "tree", "as", "siblings", ".", "This", "node", "then", "only", "contains", "all", "the", "content", "up", "to", "the", "offset", "point", ".", "A", "new", "text", "node", "which", "is", "inserted", "as", "the", "next", "sibling", "of", "this", "node", "contains", "all", "the", "content", "at", "and", "after", "the", "offset", "point", ".", "When", "the", "offset", "is", "equal", "to", "the", "length", "of", "this", "node", "the", "new", "node", "has", "no", "data", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/text.js#L90-L121
57,451
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/text.js
function( indexA, indexB ) { // We need the following check due to a Firefox bug // https://bugzilla.mozilla.org/show_bug.cgi?id=458886 if ( typeof indexB != 'number' ) return this.$.nodeValue.substr( indexA ); else return this.$.nodeValue.substring( indexA, indexB ); }
javascript
function( indexA, indexB ) { // We need the following check due to a Firefox bug // https://bugzilla.mozilla.org/show_bug.cgi?id=458886 if ( typeof indexB != 'number' ) return this.$.nodeValue.substr( indexA ); else return this.$.nodeValue.substring( indexA, indexB ); }
[ "function", "(", "indexA", ",", "indexB", ")", "{", "// We need the following check due to a Firefox bug", "// https://bugzilla.mozilla.org/show_bug.cgi?id=458886", "if", "(", "typeof", "indexB", "!=", "'number'", ")", "return", "this", ".", "$", ".", "nodeValue", ".", "substr", "(", "indexA", ")", ";", "else", "return", "this", ".", "$", ".", "nodeValue", ".", "substring", "(", "indexA", ",", "indexB", ")", ";", "}" ]
Extracts characters from indexA up to but not including `indexB`. @param {Number} indexA An integer between `0` and one less than the length of the text. @param {Number} [indexB] An integer between `0` and the length of the string. If omitted, extracts characters to the end of the text.
[ "Extracts", "characters", "from", "indexA", "up", "to", "but", "not", "including", "indexB", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/text.js#L131-L138
57,452
zeustrismegistus/dformat
dformat.js
setTypeValueFromInstance
function setTypeValueFromInstance(node) { var val = node.instance; if(val === undefined) { node.type = "undefined"; node.value = "undefined"; } else if(val === null) { node.type = "null"; node.value = "null"; } else { var valType = typeof val; if(valType === "boolean") { node.type = "boolean"; node.value = val.toString(); } else if (valType === "number") { node.type = "number"; node.value = val.toString(); } else if (valType === "string") { node.type = "string"; node.value = val; } else if (valType === "symbol") { node.type = "symbol"; node.value = val.toString(); } else if(valType === "function") { node.type = "function"; node.value = val.toString(); } else if(val instanceof Date) { node.type = "date"; node.value = val.getTime().toString(); } else if(val instanceof Array) { node.type = "array"; } else if(jsmeta.isEmpty(val)) { node.type = "empty"; node.value = "empty"; } else { node.type = "object"; } } }
javascript
function setTypeValueFromInstance(node) { var val = node.instance; if(val === undefined) { node.type = "undefined"; node.value = "undefined"; } else if(val === null) { node.type = "null"; node.value = "null"; } else { var valType = typeof val; if(valType === "boolean") { node.type = "boolean"; node.value = val.toString(); } else if (valType === "number") { node.type = "number"; node.value = val.toString(); } else if (valType === "string") { node.type = "string"; node.value = val; } else if (valType === "symbol") { node.type = "symbol"; node.value = val.toString(); } else if(valType === "function") { node.type = "function"; node.value = val.toString(); } else if(val instanceof Date) { node.type = "date"; node.value = val.getTime().toString(); } else if(val instanceof Array) { node.type = "array"; } else if(jsmeta.isEmpty(val)) { node.type = "empty"; node.value = "empty"; } else { node.type = "object"; } } }
[ "function", "setTypeValueFromInstance", "(", "node", ")", "{", "var", "val", "=", "node", ".", "instance", ";", "if", "(", "val", "===", "undefined", ")", "{", "node", ".", "type", "=", "\"undefined\"", ";", "node", ".", "value", "=", "\"undefined\"", ";", "}", "else", "if", "(", "val", "===", "null", ")", "{", "node", ".", "type", "=", "\"null\"", ";", "node", ".", "value", "=", "\"null\"", ";", "}", "else", "{", "var", "valType", "=", "typeof", "val", ";", "if", "(", "valType", "===", "\"boolean\"", ")", "{", "node", ".", "type", "=", "\"boolean\"", ";", "node", ".", "value", "=", "val", ".", "toString", "(", ")", ";", "}", "else", "if", "(", "valType", "===", "\"number\"", ")", "{", "node", ".", "type", "=", "\"number\"", ";", "node", ".", "value", "=", "val", ".", "toString", "(", ")", ";", "}", "else", "if", "(", "valType", "===", "\"string\"", ")", "{", "node", ".", "type", "=", "\"string\"", ";", "node", ".", "value", "=", "val", ";", "}", "else", "if", "(", "valType", "===", "\"symbol\"", ")", "{", "node", ".", "type", "=", "\"symbol\"", ";", "node", ".", "value", "=", "val", ".", "toString", "(", ")", ";", "}", "else", "if", "(", "valType", "===", "\"function\"", ")", "{", "node", ".", "type", "=", "\"function\"", ";", "node", ".", "value", "=", "val", ".", "toString", "(", ")", ";", "}", "else", "if", "(", "val", "instanceof", "Date", ")", "{", "node", ".", "type", "=", "\"date\"", ";", "node", ".", "value", "=", "val", ".", "getTime", "(", ")", ".", "toString", "(", ")", ";", "}", "else", "if", "(", "val", "instanceof", "Array", ")", "{", "node", ".", "type", "=", "\"array\"", ";", "}", "else", "if", "(", "jsmeta", ".", "isEmpty", "(", "val", ")", ")", "{", "node", ".", "type", "=", "\"empty\"", ";", "node", ".", "value", "=", "\"empty\"", ";", "}", "else", "{", "node", ".", "type", "=", "\"object\"", ";", "}", "}", "}" ]
hydrates type and value properties from a value
[ "hydrates", "type", "and", "value", "properties", "from", "a", "value" ]
8f2b90a3dfd4ae440530f695558f7dfd51cd54c4
https://github.com/zeustrismegistus/dformat/blob/8f2b90a3dfd4ae440530f695558f7dfd51cd54c4/dformat.js#L221-L282
57,453
zeustrismegistus/dformat
dformat.js
setInstanceFromTypeValue
function setInstanceFromTypeValue(node) { if(node.type == "undefined") { node.instance = undefined; } else if(node.type === "boolean") { node.instance = Boolean(node.value); } else if (node.type === "number") { node.instance = Number(node.value); } else if (node.type === "string") { node.instance = node.value; } else if (node.type === "symbol") { node.instance = Symbol(node.value); } else if(node.type === "function") { var fn; eval("fn = " + node.value); node.instance = fn; } else if(node.type === "null") { node.instance = null; } else if(node.type === "date") { node.instance = new Date(Number(node.value)) } else if(node.type === "array") { node.instance = []; } else if(node.type === "empty") { node.instance = {}; } else { /* $lab:coverage:off$ */ if(node.type !== "object") throw new Error("object expected"); /* $lab:coverage:on$ */ node.instance = {}; } }
javascript
function setInstanceFromTypeValue(node) { if(node.type == "undefined") { node.instance = undefined; } else if(node.type === "boolean") { node.instance = Boolean(node.value); } else if (node.type === "number") { node.instance = Number(node.value); } else if (node.type === "string") { node.instance = node.value; } else if (node.type === "symbol") { node.instance = Symbol(node.value); } else if(node.type === "function") { var fn; eval("fn = " + node.value); node.instance = fn; } else if(node.type === "null") { node.instance = null; } else if(node.type === "date") { node.instance = new Date(Number(node.value)) } else if(node.type === "array") { node.instance = []; } else if(node.type === "empty") { node.instance = {}; } else { /* $lab:coverage:off$ */ if(node.type !== "object") throw new Error("object expected"); /* $lab:coverage:on$ */ node.instance = {}; } }
[ "function", "setInstanceFromTypeValue", "(", "node", ")", "{", "if", "(", "node", ".", "type", "==", "\"undefined\"", ")", "{", "node", ".", "instance", "=", "undefined", ";", "}", "else", "if", "(", "node", ".", "type", "===", "\"boolean\"", ")", "{", "node", ".", "instance", "=", "Boolean", "(", "node", ".", "value", ")", ";", "}", "else", "if", "(", "node", ".", "type", "===", "\"number\"", ")", "{", "node", ".", "instance", "=", "Number", "(", "node", ".", "value", ")", ";", "}", "else", "if", "(", "node", ".", "type", "===", "\"string\"", ")", "{", "node", ".", "instance", "=", "node", ".", "value", ";", "}", "else", "if", "(", "node", ".", "type", "===", "\"symbol\"", ")", "{", "node", ".", "instance", "=", "Symbol", "(", "node", ".", "value", ")", ";", "}", "else", "if", "(", "node", ".", "type", "===", "\"function\"", ")", "{", "var", "fn", ";", "eval", "(", "\"fn = \"", "+", "node", ".", "value", ")", ";", "node", ".", "instance", "=", "fn", ";", "}", "else", "if", "(", "node", ".", "type", "===", "\"null\"", ")", "{", "node", ".", "instance", "=", "null", ";", "}", "else", "if", "(", "node", ".", "type", "===", "\"date\"", ")", "{", "node", ".", "instance", "=", "new", "Date", "(", "Number", "(", "node", ".", "value", ")", ")", "}", "else", "if", "(", "node", ".", "type", "===", "\"array\"", ")", "{", "node", ".", "instance", "=", "[", "]", ";", "}", "else", "if", "(", "node", ".", "type", "===", "\"empty\"", ")", "{", "node", ".", "instance", "=", "{", "}", ";", "}", "else", "{", "/* $lab:coverage:off$ */", "if", "(", "node", ".", "type", "!==", "\"object\"", ")", "throw", "new", "Error", "(", "\"object expected\"", ")", ";", "/* $lab:coverage:on$ */", "node", ".", "instance", "=", "{", "}", ";", "}", "}" ]
does the reverse of setTypeValue
[ "does", "the", "reverse", "of", "setTypeValue" ]
8f2b90a3dfd4ae440530f695558f7dfd51cd54c4
https://github.com/zeustrismegistus/dformat/blob/8f2b90a3dfd4ae440530f695558f7dfd51cd54c4/dformat.js#L285-L339
57,454
saebekassebil/erroneous
lib/erroneous.js
ErroneousError
function ErroneousError(e, additional) { additional = additional || {}; this.line = e.lineno || e.lineNumber || additional.lineno; this.file = e.filename || e.fileName || additional.filename; this.msg = e.message || additional.message; this.time = e.timestamp || additional.timestamp || Date.now(); this.type = (this.parseMessage(this.msg) || e.type || e.name).toLowerCase(); // If it's a DOM node, let's figure out which if (e.target) { this.target = this.getTargetIdentifier(e.target); if (e.target.nodeName) { this.type = 'resource'; if (e.target.href) { this.file = e.target.href; } else if (e.target.src) { this.file = e.target.src; } } } // Parse the stack if any this.stack = e.stack; this.parseStack(e.stack); }
javascript
function ErroneousError(e, additional) { additional = additional || {}; this.line = e.lineno || e.lineNumber || additional.lineno; this.file = e.filename || e.fileName || additional.filename; this.msg = e.message || additional.message; this.time = e.timestamp || additional.timestamp || Date.now(); this.type = (this.parseMessage(this.msg) || e.type || e.name).toLowerCase(); // If it's a DOM node, let's figure out which if (e.target) { this.target = this.getTargetIdentifier(e.target); if (e.target.nodeName) { this.type = 'resource'; if (e.target.href) { this.file = e.target.href; } else if (e.target.src) { this.file = e.target.src; } } } // Parse the stack if any this.stack = e.stack; this.parseStack(e.stack); }
[ "function", "ErroneousError", "(", "e", ",", "additional", ")", "{", "additional", "=", "additional", "||", "{", "}", ";", "this", ".", "line", "=", "e", ".", "lineno", "||", "e", ".", "lineNumber", "||", "additional", ".", "lineno", ";", "this", ".", "file", "=", "e", ".", "filename", "||", "e", ".", "fileName", "||", "additional", ".", "filename", ";", "this", ".", "msg", "=", "e", ".", "message", "||", "additional", ".", "message", ";", "this", ".", "time", "=", "e", ".", "timestamp", "||", "additional", ".", "timestamp", "||", "Date", ".", "now", "(", ")", ";", "this", ".", "type", "=", "(", "this", ".", "parseMessage", "(", "this", ".", "msg", ")", "||", "e", ".", "type", "||", "e", ".", "name", ")", ".", "toLowerCase", "(", ")", ";", "// If it's a DOM node, let's figure out which", "if", "(", "e", ".", "target", ")", "{", "this", ".", "target", "=", "this", ".", "getTargetIdentifier", "(", "e", ".", "target", ")", ";", "if", "(", "e", ".", "target", ".", "nodeName", ")", "{", "this", ".", "type", "=", "'resource'", ";", "if", "(", "e", ".", "target", ".", "href", ")", "{", "this", ".", "file", "=", "e", ".", "target", ".", "href", ";", "}", "else", "if", "(", "e", ".", "target", ".", "src", ")", "{", "this", ".", "file", "=", "e", ".", "target", ".", "src", ";", "}", "}", "}", "// Parse the stack if any", "this", ".", "stack", "=", "e", ".", "stack", ";", "this", ".", "parseStack", "(", "e", ".", "stack", ")", ";", "}" ]
Object for storing error details Only used internally
[ "Object", "for", "storing", "error", "details", "Only", "used", "internally" ]
05a104db15373bd302202ec544e65a4d8bd5ce02
https://github.com/saebekassebil/erroneous/blob/05a104db15373bd302202ec544e65a4d8bd5ce02/lib/erroneous.js#L13-L38
57,455
Pocketbrain/native-ads-web-ad-library
src/ads/adBuilder.js
_replaceMacros
function _replaceMacros(s, macros, obj) { var regex = null; for (var i = 0; i < macros.length; i++) { var macro = macros[i]; regex = new RegExp(macro.macro, "g"); s = s.replace(regex, obj[macro.prop]); } return s; }
javascript
function _replaceMacros(s, macros, obj) { var regex = null; for (var i = 0; i < macros.length; i++) { var macro = macros[i]; regex = new RegExp(macro.macro, "g"); s = s.replace(regex, obj[macro.prop]); } return s; }
[ "function", "_replaceMacros", "(", "s", ",", "macros", ",", "obj", ")", "{", "var", "regex", "=", "null", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "macros", ".", "length", ";", "i", "++", ")", "{", "var", "macro", "=", "macros", "[", "i", "]", ";", "regex", "=", "new", "RegExp", "(", "macro", ".", "macro", ",", "\"g\"", ")", ";", "s", "=", "s", ".", "replace", "(", "regex", ",", "obj", "[", "macro", ".", "prop", "]", ")", ";", "}", "return", "s", ";", "}" ]
Replaces macros in a string with the properties of an object @param s The string to replace the macros in @param macros The macros to replace the string with @param obj the object to get the macro properties from @returns {String} - The string with the macros replaced @private
[ "Replaces", "macros", "in", "a", "string", "with", "the", "properties", "of", "an", "object" ]
aafee1c42e0569ee77f334fc2c4eb71eb146957e
https://github.com/Pocketbrain/native-ads-web-ad-library/blob/aafee1c42e0569ee77f334fc2c4eb71eb146957e/src/ads/adBuilder.js#L70-L80
57,456
AndiDittrich/Node.async-magic
lib/series.js
series
async function series(resolvers){ // buffer const results = []; // run resolvers in series for (const r of resolvers){ results.push(await r.resolve()); } // return results return results; }
javascript
async function series(resolvers){ // buffer const results = []; // run resolvers in series for (const r of resolvers){ results.push(await r.resolve()); } // return results return results; }
[ "async", "function", "series", "(", "resolvers", ")", "{", "// buffer", "const", "results", "=", "[", "]", ";", "// run resolvers in series", "for", "(", "const", "r", "of", "resolvers", ")", "{", "results", ".", "push", "(", "await", "r", ".", "resolve", "(", ")", ")", ";", "}", "// return results", "return", "results", ";", "}" ]
resolves multiple promises in series
[ "resolves", "multiple", "promises", "in", "series" ]
0c41dd27d8f7539bb24034bc23ce870f5f8a10b3
https://github.com/AndiDittrich/Node.async-magic/blob/0c41dd27d8f7539bb24034bc23ce870f5f8a10b3/lib/series.js#L2-L13
57,457
ikondrat/franky
src/etc/components.js
function (componentDescription) { var i = components.length, app; // Old-school declaration // > franky.Component.extend({ // id: 'hello', // init: function () { // console.log('hello'); // } // }); if (franky.isObject(componentDescription)) { app = franky.beget(franky.ComponentBase, componentDescription); // Short form declaration // > franky.Component.extend('hello', function () { // console.log('hello'); // }); } else if (franky.isString(componentDescription) && franky.isFunction(arguments[1])) { app = franky.beget(franky.ComponentBase, { id: componentDescription, init: arguments[1] }); // Dependencies injection form declaration // > franky.Component.extend('hello', ['$logger', function ($logger) { // $logger.say('hello'); // }]); } else if (franky.isString(componentDescription) && franky.isArray(arguments[1])) { var args = arguments[1]; app = franky.beget(franky.ComponentBase, { id: componentDescription, init: function () { var deps = franky.filter(args, function (item) { return franky.isString(item); }); deps = franky.map(deps, function (serviceName) { if (!services[serviceName]) { throw new Error('Service ' + serviceName + ' hasnt defined'); } return services[serviceName](); }); var defs = franky.filter(args, function (item) { return franky.isFunction(item); }); if (defs.length > 1) { throw new Error('Too much declaration functions'); } defs[0].apply(this, deps); } }); } else { throw new Error('Unknown definition structure, try to use extend("yourName", function() { ... init code ... })'); } if (!app.id) { franky.error('extend method expects id field in description object'); } components.push(app); // fill index componentsIndex[app.id] = i; return components[i]; }
javascript
function (componentDescription) { var i = components.length, app; // Old-school declaration // > franky.Component.extend({ // id: 'hello', // init: function () { // console.log('hello'); // } // }); if (franky.isObject(componentDescription)) { app = franky.beget(franky.ComponentBase, componentDescription); // Short form declaration // > franky.Component.extend('hello', function () { // console.log('hello'); // }); } else if (franky.isString(componentDescription) && franky.isFunction(arguments[1])) { app = franky.beget(franky.ComponentBase, { id: componentDescription, init: arguments[1] }); // Dependencies injection form declaration // > franky.Component.extend('hello', ['$logger', function ($logger) { // $logger.say('hello'); // }]); } else if (franky.isString(componentDescription) && franky.isArray(arguments[1])) { var args = arguments[1]; app = franky.beget(franky.ComponentBase, { id: componentDescription, init: function () { var deps = franky.filter(args, function (item) { return franky.isString(item); }); deps = franky.map(deps, function (serviceName) { if (!services[serviceName]) { throw new Error('Service ' + serviceName + ' hasnt defined'); } return services[serviceName](); }); var defs = franky.filter(args, function (item) { return franky.isFunction(item); }); if (defs.length > 1) { throw new Error('Too much declaration functions'); } defs[0].apply(this, deps); } }); } else { throw new Error('Unknown definition structure, try to use extend("yourName", function() { ... init code ... })'); } if (!app.id) { franky.error('extend method expects id field in description object'); } components.push(app); // fill index componentsIndex[app.id] = i; return components[i]; }
[ "function", "(", "componentDescription", ")", "{", "var", "i", "=", "components", ".", "length", ",", "app", ";", "// Old-school declaration", "// > franky.Component.extend({", "// id: 'hello',", "// init: function () {", "// console.log('hello');", "// }", "// });", "if", "(", "franky", ".", "isObject", "(", "componentDescription", ")", ")", "{", "app", "=", "franky", ".", "beget", "(", "franky", ".", "ComponentBase", ",", "componentDescription", ")", ";", "// Short form declaration", "// > franky.Component.extend('hello', function () {", "// console.log('hello');", "// });", "}", "else", "if", "(", "franky", ".", "isString", "(", "componentDescription", ")", "&&", "franky", ".", "isFunction", "(", "arguments", "[", "1", "]", ")", ")", "{", "app", "=", "franky", ".", "beget", "(", "franky", ".", "ComponentBase", ",", "{", "id", ":", "componentDescription", ",", "init", ":", "arguments", "[", "1", "]", "}", ")", ";", "// Dependencies injection form declaration", "// > franky.Component.extend('hello', ['$logger', function ($logger) {", "// $logger.say('hello');", "// }]);", "}", "else", "if", "(", "franky", ".", "isString", "(", "componentDescription", ")", "&&", "franky", ".", "isArray", "(", "arguments", "[", "1", "]", ")", ")", "{", "var", "args", "=", "arguments", "[", "1", "]", ";", "app", "=", "franky", ".", "beget", "(", "franky", ".", "ComponentBase", ",", "{", "id", ":", "componentDescription", ",", "init", ":", "function", "(", ")", "{", "var", "deps", "=", "franky", ".", "filter", "(", "args", ",", "function", "(", "item", ")", "{", "return", "franky", ".", "isString", "(", "item", ")", ";", "}", ")", ";", "deps", "=", "franky", ".", "map", "(", "deps", ",", "function", "(", "serviceName", ")", "{", "if", "(", "!", "services", "[", "serviceName", "]", ")", "{", "throw", "new", "Error", "(", "'Service '", "+", "serviceName", "+", "' hasnt defined'", ")", ";", "}", "return", "services", "[", "serviceName", "]", "(", ")", ";", "}", ")", ";", "var", "defs", "=", "franky", ".", "filter", "(", "args", ",", "function", "(", "item", ")", "{", "return", "franky", ".", "isFunction", "(", "item", ")", ";", "}", ")", ";", "if", "(", "defs", ".", "length", ">", "1", ")", "{", "throw", "new", "Error", "(", "'Too much declaration functions'", ")", ";", "}", "defs", "[", "0", "]", ".", "apply", "(", "this", ",", "deps", ")", ";", "}", "}", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Unknown definition structure, try to use extend(\"yourName\", function() { ... init code ... })'", ")", ";", "}", "if", "(", "!", "app", ".", "id", ")", "{", "franky", ".", "error", "(", "'extend method expects id field in description object'", ")", ";", "}", "components", ".", "push", "(", "app", ")", ";", "// fill index", "componentsIndex", "[", "app", ".", "id", "]", "=", "i", ";", "return", "components", "[", "i", "]", ";", "}" ]
Cornerstone of Component moodule - method for creating new components
[ "Cornerstone", "of", "Component", "moodule", "-", "method", "for", "creating", "new", "components" ]
6a7368891f39620a225e37c4a56d2bf99644c3e7
https://github.com/ikondrat/franky/blob/6a7368891f39620a225e37c4a56d2bf99644c3e7/src/etc/components.js#L37-L100
57,458
craiglonsdale/repohelper
lib/pullRequests.js
getPRsForRepo
function getPRsForRepo(repo) { print(['Fetching PRs for ', clc.yellow.bold(`${repo.owner.login}/${repo.name}`)], debug); return new Promise((resolve, reject) => { github.pullRequests.getAll({ user: repo.owner.login, repo: repo.name, state: 'open' }, (err, prs) => { if (err) { return reject(err); } return resolve(prs.filter((pr) => { return pr && pr.head; })); }); }); }
javascript
function getPRsForRepo(repo) { print(['Fetching PRs for ', clc.yellow.bold(`${repo.owner.login}/${repo.name}`)], debug); return new Promise((resolve, reject) => { github.pullRequests.getAll({ user: repo.owner.login, repo: repo.name, state: 'open' }, (err, prs) => { if (err) { return reject(err); } return resolve(prs.filter((pr) => { return pr && pr.head; })); }); }); }
[ "function", "getPRsForRepo", "(", "repo", ")", "{", "print", "(", "[", "'Fetching PRs for '", ",", "clc", ".", "yellow", ".", "bold", "(", "`", "${", "repo", ".", "owner", ".", "login", "}", "${", "repo", ".", "name", "}", "`", ")", "]", ",", "debug", ")", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "github", ".", "pullRequests", ".", "getAll", "(", "{", "user", ":", "repo", ".", "owner", ".", "login", ",", "repo", ":", "repo", ".", "name", ",", "state", ":", "'open'", "}", ",", "(", "err", ",", "prs", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "reject", "(", "err", ")", ";", "}", "return", "resolve", "(", "prs", ".", "filter", "(", "(", "pr", ")", "=>", "{", "return", "pr", "&&", "pr", ".", "head", ";", "}", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Fetch open pull requests for a single repository @param {Object} repo Repository metadata @return {Promise} Resolves to a list of pull requests
[ "Fetch", "open", "pull", "requests", "for", "a", "single", "repository" ]
9685a71e0d2cfc78df76280b9b1a8e66d0001587
https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/pullRequests.js#L71-L87
57,459
craiglonsdale/repohelper
lib/pullRequests.js
populateLabelsForPR
function populateLabelsForPR(pr) { print(['Get labels for PR ', clc.yellow.bold(`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`)], debug); return new Promise((resolve) => { github.issues.getIssueLabels({ user: pr.base.user.login, repo: pr.base.repo.name, number: pr.number }, function (err, labels) { if (err && debug) { print(['Error fetching labels for PR ', clc.red.bold`${pr.base.user.login}/${pr.base.repo.name}#${pr.number}`], debug); } if (labels && labels.length > 0) { pr.labels = labels.map((label) => { return { name: label.name, color: label.color }; }); } return resolve(pr); }); }); }
javascript
function populateLabelsForPR(pr) { print(['Get labels for PR ', clc.yellow.bold(`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`)], debug); return new Promise((resolve) => { github.issues.getIssueLabels({ user: pr.base.user.login, repo: pr.base.repo.name, number: pr.number }, function (err, labels) { if (err && debug) { print(['Error fetching labels for PR ', clc.red.bold`${pr.base.user.login}/${pr.base.repo.name}#${pr.number}`], debug); } if (labels && labels.length > 0) { pr.labels = labels.map((label) => { return { name: label.name, color: label.color }; }); } return resolve(pr); }); }); }
[ "function", "populateLabelsForPR", "(", "pr", ")", "{", "print", "(", "[", "'Get labels for PR '", ",", "clc", ".", "yellow", ".", "bold", "(", "`", "${", "pr", ".", "head", ".", "user", ".", "login", "}", "${", "pr", ".", "head", ".", "repo", ".", "name", "}", "${", "pr", ".", "number", "}", "`", ")", "]", ",", "debug", ")", ";", "return", "new", "Promise", "(", "(", "resolve", ")", "=>", "{", "github", ".", "issues", ".", "getIssueLabels", "(", "{", "user", ":", "pr", ".", "base", ".", "user", ".", "login", ",", "repo", ":", "pr", ".", "base", ".", "repo", ".", "name", ",", "number", ":", "pr", ".", "number", "}", ",", "function", "(", "err", ",", "labels", ")", "{", "if", "(", "err", "&&", "debug", ")", "{", "print", "(", "[", "'Error fetching labels for PR '", ",", "clc", ".", "red", ".", "bold", "`", "${", "pr", ".", "base", ".", "user", ".", "login", "}", "${", "pr", ".", "base", ".", "repo", ".", "name", "}", "${", "pr", ".", "number", "}", "`", "]", ",", "debug", ")", ";", "}", "if", "(", "labels", "&&", "labels", ".", "length", ">", "0", ")", "{", "pr", ".", "labels", "=", "labels", ".", "map", "(", "(", "label", ")", "=>", "{", "return", "{", "name", ":", "label", ".", "name", ",", "color", ":", "label", ".", "color", "}", ";", "}", ")", ";", "}", "return", "resolve", "(", "pr", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Fetch a list of labels for a single pull-request @param {Object} pr Pull-request metadata @return {Promise} Resolves to an array of labels
[ "Fetch", "a", "list", "of", "labels", "for", "a", "single", "pull", "-", "request" ]
9685a71e0d2cfc78df76280b9b1a8e66d0001587
https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/pullRequests.js#L94-L116
57,460
craiglonsdale/repohelper
lib/pullRequests.js
getLabels
function getLabels(prs) { return Promise.all(prs.reduce((flattenedPRs, pr) => { if (pr) { return flattenedPRs.concat(pr); } }, []).map(populateLabelsForPR)); }
javascript
function getLabels(prs) { return Promise.all(prs.reduce((flattenedPRs, pr) => { if (pr) { return flattenedPRs.concat(pr); } }, []).map(populateLabelsForPR)); }
[ "function", "getLabels", "(", "prs", ")", "{", "return", "Promise", ".", "all", "(", "prs", ".", "reduce", "(", "(", "flattenedPRs", ",", "pr", ")", "=>", "{", "if", "(", "pr", ")", "{", "return", "flattenedPRs", ".", "concat", "(", "pr", ")", ";", "}", "}", ",", "[", "]", ")", ".", "map", "(", "populateLabelsForPR", ")", ")", ";", "}" ]
Fetch labels for a list of pull-requests @param {Array} repos List of pull-requests @return {Promise} Resolves to an array of PRs containing labels
[ "Fetch", "labels", "for", "a", "list", "of", "pull", "-", "requests" ]
9685a71e0d2cfc78df76280b9b1a8e66d0001587
https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/pullRequests.js#L123-L129
57,461
craiglonsdale/repohelper
lib/pullRequests.js
analyzePatch
function analyzePatch(patch) { const patchLines = patch.split('\n').reduce((reducedPatch, currentLine) => { if (currentLine.match(/^[-+]/)) { return reducedPatch.concat(currentLine.replace(/^[-+]+\s*/, '')); } return reducedPatch; }, []); return { lines: patchLines.length, chars: patchLines.join('').length }; }
javascript
function analyzePatch(patch) { const patchLines = patch.split('\n').reduce((reducedPatch, currentLine) => { if (currentLine.match(/^[-+]/)) { return reducedPatch.concat(currentLine.replace(/^[-+]+\s*/, '')); } return reducedPatch; }, []); return { lines: patchLines.length, chars: patchLines.join('').length }; }
[ "function", "analyzePatch", "(", "patch", ")", "{", "const", "patchLines", "=", "patch", ".", "split", "(", "'\\n'", ")", ".", "reduce", "(", "(", "reducedPatch", ",", "currentLine", ")", "=>", "{", "if", "(", "currentLine", ".", "match", "(", "/", "^[-+]", "/", ")", ")", "{", "return", "reducedPatch", ".", "concat", "(", "currentLine", ".", "replace", "(", "/", "^[-+]+\\s*", "/", ",", "''", ")", ")", ";", "}", "return", "reducedPatch", ";", "}", ",", "[", "]", ")", ";", "return", "{", "lines", ":", "patchLines", ".", "length", ",", "chars", ":", "patchLines", ".", "join", "(", "''", ")", ".", "length", "}", ";", "}" ]
Reduce a patch down to just changed lines @param {String} patch The complete patch with surrounding context @return {Object} Stats about the changed lines
[ "Reduce", "a", "patch", "down", "to", "just", "changed", "lines" ]
9685a71e0d2cfc78df76280b9b1a8e66d0001587
https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/pullRequests.js#L148-L159
57,462
craiglonsdale/repohelper
lib/pullRequests.js
extractDiffData
function extractDiffData(diff) { print(['Extract diff for ', clc.yellow.bold(`${diff.user}/${diff.repo}#${diff.number}`), clc.white.italic(` (${diff.title})`)], debug); return { user: diff.user, repo: diff.repo, title: diff.title, number: diff.number, link: diff.link, createdAt: diff.createdAt, updatedAt: diff.updatedAt, labels: diff.labels, aheadBy: diff.ahead_by, behindBy: diff.behind_by, status: diff.status, totalCommits: diff.total_commits, author: { login: diff.merge_base_commit.author ? diff.merge_base_commit.author.login : 'Unknown', avatarUrl: diff.merge_base_commit.author ? diff.merge_base_commit.author.avatar_url : '', }, files: diff.files.map((file) => { return { filename: file.filename, status: file.status, additions: file.additions, deletions: file.deletions, changes: file.changes, patch: analyzePatch(file.patch || '') }; }) }; }
javascript
function extractDiffData(diff) { print(['Extract diff for ', clc.yellow.bold(`${diff.user}/${diff.repo}#${diff.number}`), clc.white.italic(` (${diff.title})`)], debug); return { user: diff.user, repo: diff.repo, title: diff.title, number: diff.number, link: diff.link, createdAt: diff.createdAt, updatedAt: diff.updatedAt, labels: diff.labels, aheadBy: diff.ahead_by, behindBy: diff.behind_by, status: diff.status, totalCommits: diff.total_commits, author: { login: diff.merge_base_commit.author ? diff.merge_base_commit.author.login : 'Unknown', avatarUrl: diff.merge_base_commit.author ? diff.merge_base_commit.author.avatar_url : '', }, files: diff.files.map((file) => { return { filename: file.filename, status: file.status, additions: file.additions, deletions: file.deletions, changes: file.changes, patch: analyzePatch(file.patch || '') }; }) }; }
[ "function", "extractDiffData", "(", "diff", ")", "{", "print", "(", "[", "'Extract diff for '", ",", "clc", ".", "yellow", ".", "bold", "(", "`", "${", "diff", ".", "user", "}", "${", "diff", ".", "repo", "}", "${", "diff", ".", "number", "}", "`", ")", ",", "clc", ".", "white", ".", "italic", "(", "`", "${", "diff", ".", "title", "}", "`", ")", "]", ",", "debug", ")", ";", "return", "{", "user", ":", "diff", ".", "user", ",", "repo", ":", "diff", ".", "repo", ",", "title", ":", "diff", ".", "title", ",", "number", ":", "diff", ".", "number", ",", "link", ":", "diff", ".", "link", ",", "createdAt", ":", "diff", ".", "createdAt", ",", "updatedAt", ":", "diff", ".", "updatedAt", ",", "labels", ":", "diff", ".", "labels", ",", "aheadBy", ":", "diff", ".", "ahead_by", ",", "behindBy", ":", "diff", ".", "behind_by", ",", "status", ":", "diff", ".", "status", ",", "totalCommits", ":", "diff", ".", "total_commits", ",", "author", ":", "{", "login", ":", "diff", ".", "merge_base_commit", ".", "author", "?", "diff", ".", "merge_base_commit", ".", "author", ".", "login", ":", "'Unknown'", ",", "avatarUrl", ":", "diff", ".", "merge_base_commit", ".", "author", "?", "diff", ".", "merge_base_commit", ".", "author", ".", "avatar_url", ":", "''", ",", "}", ",", "files", ":", "diff", ".", "files", ".", "map", "(", "(", "file", ")", "=>", "{", "return", "{", "filename", ":", "file", ".", "filename", ",", "status", ":", "file", ".", "status", ",", "additions", ":", "file", ".", "additions", ",", "deletions", ":", "file", ".", "deletions", ",", "changes", ":", "file", ".", "changes", ",", "patch", ":", "analyzePatch", "(", "file", ".", "patch", "||", "''", ")", "}", ";", "}", ")", "}", ";", "}" ]
Refine a complete diff down to its useful information @param {Object} diff Too much information about a diff @return {Object} Just enough information about a diff
[ "Refine", "a", "complete", "diff", "down", "to", "its", "useful", "information" ]
9685a71e0d2cfc78df76280b9b1a8e66d0001587
https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/pullRequests.js#L166-L196
57,463
craiglonsdale/repohelper
lib/pullRequests.js
getDiffForPR
function getDiffForPR(pr) { print(['Get diff for PR ', clc.yellow.bold(`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`)], debug); return new Promise((resolve) => { github.repos.compareCommits({ user: pr.head.user.login, repo: pr.head.repo.name, head: pr.head.ref, base: pr.base.ref }, (err, diff) => { if (err && debug) { print(['Error fetching diffs for PR ', clc.red.bold`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`], debug); } diff.user = pr.head.user.login; diff.repo = pr.head.repo.name; diff.title = pr.title; diff.number = pr.number; diff.link = pr._links.html.href; diff.createdAt = pr.created_at; diff.createdAt = pr.updated_at; diff.labels = pr.labels; return resolve(extractDiffData(diff)); }); }); }
javascript
function getDiffForPR(pr) { print(['Get diff for PR ', clc.yellow.bold(`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`)], debug); return new Promise((resolve) => { github.repos.compareCommits({ user: pr.head.user.login, repo: pr.head.repo.name, head: pr.head.ref, base: pr.base.ref }, (err, diff) => { if (err && debug) { print(['Error fetching diffs for PR ', clc.red.bold`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`], debug); } diff.user = pr.head.user.login; diff.repo = pr.head.repo.name; diff.title = pr.title; diff.number = pr.number; diff.link = pr._links.html.href; diff.createdAt = pr.created_at; diff.createdAt = pr.updated_at; diff.labels = pr.labels; return resolve(extractDiffData(diff)); }); }); }
[ "function", "getDiffForPR", "(", "pr", ")", "{", "print", "(", "[", "'Get diff for PR '", ",", "clc", ".", "yellow", ".", "bold", "(", "`", "${", "pr", ".", "head", ".", "user", ".", "login", "}", "${", "pr", ".", "head", ".", "repo", ".", "name", "}", "${", "pr", ".", "number", "}", "`", ")", "]", ",", "debug", ")", ";", "return", "new", "Promise", "(", "(", "resolve", ")", "=>", "{", "github", ".", "repos", ".", "compareCommits", "(", "{", "user", ":", "pr", ".", "head", ".", "user", ".", "login", ",", "repo", ":", "pr", ".", "head", ".", "repo", ".", "name", ",", "head", ":", "pr", ".", "head", ".", "ref", ",", "base", ":", "pr", ".", "base", ".", "ref", "}", ",", "(", "err", ",", "diff", ")", "=>", "{", "if", "(", "err", "&&", "debug", ")", "{", "print", "(", "[", "'Error fetching diffs for PR '", ",", "clc", ".", "red", ".", "bold", "`", "${", "pr", ".", "head", ".", "user", ".", "login", "}", "${", "pr", ".", "head", ".", "repo", ".", "name", "}", "${", "pr", ".", "number", "}", "`", "]", ",", "debug", ")", ";", "}", "diff", ".", "user", "=", "pr", ".", "head", ".", "user", ".", "login", ";", "diff", ".", "repo", "=", "pr", ".", "head", ".", "repo", ".", "name", ";", "diff", ".", "title", "=", "pr", ".", "title", ";", "diff", ".", "number", "=", "pr", ".", "number", ";", "diff", ".", "link", "=", "pr", ".", "_links", ".", "html", ".", "href", ";", "diff", ".", "createdAt", "=", "pr", ".", "created_at", ";", "diff", ".", "createdAt", "=", "pr", ".", "updated_at", ";", "diff", ".", "labels", "=", "pr", ".", "labels", ";", "return", "resolve", "(", "extractDiffData", "(", "diff", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Fetch the diff for a single pull-request @param {Object} pr Pull-request metadata @return {Promise} Resolves to an array of labels
[ "Fetch", "the", "diff", "for", "a", "single", "pull", "-", "request" ]
9685a71e0d2cfc78df76280b9b1a8e66d0001587
https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/pullRequests.js#L203-L226
57,464
craiglonsdale/repohelper
lib/pullRequests.js
getDiffs
function getDiffs(prs) { print('Fetching diffs', debug); return Promise.all(prs.reduce((flattenedPRs, pr) => { if (pr) { return flattenedPRs.concat(pr); } }, []).map(getDiffForPR)); }
javascript
function getDiffs(prs) { print('Fetching diffs', debug); return Promise.all(prs.reduce((flattenedPRs, pr) => { if (pr) { return flattenedPRs.concat(pr); } }, []).map(getDiffForPR)); }
[ "function", "getDiffs", "(", "prs", ")", "{", "print", "(", "'Fetching diffs'", ",", "debug", ")", ";", "return", "Promise", ".", "all", "(", "prs", ".", "reduce", "(", "(", "flattenedPRs", ",", "pr", ")", "=>", "{", "if", "(", "pr", ")", "{", "return", "flattenedPRs", ".", "concat", "(", "pr", ")", ";", "}", "}", ",", "[", "]", ")", ".", "map", "(", "getDiffForPR", ")", ")", ";", "}" ]
Fetch diffs for a list of pull-requests @param {Array} repos List of pull-requests @return {Promise} Resolves to an array of PRs containing diff infomation
[ "Fetch", "diffs", "for", "a", "list", "of", "pull", "-", "requests" ]
9685a71e0d2cfc78df76280b9b1a8e66d0001587
https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/pullRequests.js#L233-L240
57,465
craiglonsdale/repohelper
lib/pullRequests.js
getOpenPRs
function getOpenPRs(auth, repo, debugEnabled) { setDebugMode(debugEnabled); return authenticate(auth) .then(function () { return getPRsForRepo(repo) .then(getLabels, handleError('getPRs')) .then(getDiffs, handleError('getLabels')); }, handleError('authenticate')); }
javascript
function getOpenPRs(auth, repo, debugEnabled) { setDebugMode(debugEnabled); return authenticate(auth) .then(function () { return getPRsForRepo(repo) .then(getLabels, handleError('getPRs')) .then(getDiffs, handleError('getLabels')); }, handleError('authenticate')); }
[ "function", "getOpenPRs", "(", "auth", ",", "repo", ",", "debugEnabled", ")", "{", "setDebugMode", "(", "debugEnabled", ")", ";", "return", "authenticate", "(", "auth", ")", ".", "then", "(", "function", "(", ")", "{", "return", "getPRsForRepo", "(", "repo", ")", ".", "then", "(", "getLabels", ",", "handleError", "(", "'getPRs'", ")", ")", ".", "then", "(", "getDiffs", ",", "handleError", "(", "'getLabels'", ")", ")", ";", "}", ",", "handleError", "(", "'authenticate'", ")", ")", ";", "}" ]
Get a list of all open pull requests. @param {Object} auth Credentials containing an auth token @param {Object} repo The repo from which to get the Open PRs @param {Boolean} debugEnabled Set the debug state @return {Promise} Resolves to a list of all open pull-requests
[ "Get", "a", "list", "of", "all", "open", "pull", "requests", "." ]
9685a71e0d2cfc78df76280b9b1a8e66d0001587
https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/pullRequests.js#L249-L257
57,466
IonicaBizau/double-last
lib/index.js
DoubleLast
function DoubleLast(input, letters) { var last = LastChar(input); if (!letters || ~letters.indexOf(last)) { return input + last; } return input; }
javascript
function DoubleLast(input, letters) { var last = LastChar(input); if (!letters || ~letters.indexOf(last)) { return input + last; } return input; }
[ "function", "DoubleLast", "(", "input", ",", "letters", ")", "{", "var", "last", "=", "LastChar", "(", "input", ")", ";", "if", "(", "!", "letters", "||", "~", "letters", ".", "indexOf", "(", "last", ")", ")", "{", "return", "input", "+", "last", ";", "}", "return", "input", ";", "}" ]
DoubleLast Doubles the last letter. @name DoubleLast @function @param {String} input The input string. @param {Array} letters An array of letters: if the last letter of the input is not found in this list, it will *not* be doubled. @return {String} The modified string.
[ "DoubleLast", "Doubles", "the", "last", "letter", "." ]
e3de121d5c71dbfe075077797b2361efd00dd24e
https://github.com/IonicaBizau/double-last/blob/e3de121d5c71dbfe075077797b2361efd00dd24e/lib/index.js#L15-L21
57,467
rranauro/boxspringjs
backbone.boxspring.js
function(err, data, response) { // call the 'response' callback, if provided using 'node' style callback pattern if (options.complete) { options.complete.call(model, err, data, response, options); } // trigger any event listeners for "complete" model.trigger('complete', err, data, response, options); }
javascript
function(err, data, response) { // call the 'response' callback, if provided using 'node' style callback pattern if (options.complete) { options.complete.call(model, err, data, response, options); } // trigger any event listeners for "complete" model.trigger('complete', err, data, response, options); }
[ "function", "(", "err", ",", "data", ",", "response", ")", "{", "// call the 'response' callback, if provided using 'node' style callback pattern", "if", "(", "options", ".", "complete", ")", "{", "options", ".", "complete", ".", "call", "(", "model", ",", "err", ",", "data", ",", "response", ",", "options", ")", ";", "}", "// trigger any event listeners for \"complete\"", "model", ".", "trigger", "(", "'complete'", ",", "err", ",", "data", ",", "response", ",", "options", ")", ";", "}" ]
complete call back
[ "complete", "call", "back" ]
43fd13ae45ba5b16ba9144084b96748a1cd8c0ea
https://github.com/rranauro/boxspringjs/blob/43fd13ae45ba5b16ba9144084b96748a1cd8c0ea/backbone.boxspring.js#L34-L43
57,468
Industryswarm/isnode-mod-data
lib/mongodb/mongodb/lib/bulk/common.js
handleMongoWriteConcernError
function handleMongoWriteConcernError(batch, bulkResult, ordered, err, callback) { mergeBatchResults(ordered, batch, bulkResult, null, err.result); const wrappedWriteConcernError = new WriteConcernError({ errmsg: err.result.writeConcernError.errmsg, code: err.result.writeConcernError.result }); return handleCallback( callback, new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)), null ); }
javascript
function handleMongoWriteConcernError(batch, bulkResult, ordered, err, callback) { mergeBatchResults(ordered, batch, bulkResult, null, err.result); const wrappedWriteConcernError = new WriteConcernError({ errmsg: err.result.writeConcernError.errmsg, code: err.result.writeConcernError.result }); return handleCallback( callback, new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)), null ); }
[ "function", "handleMongoWriteConcernError", "(", "batch", ",", "bulkResult", ",", "ordered", ",", "err", ",", "callback", ")", "{", "mergeBatchResults", "(", "ordered", ",", "batch", ",", "bulkResult", ",", "null", ",", "err", ".", "result", ")", ";", "const", "wrappedWriteConcernError", "=", "new", "WriteConcernError", "(", "{", "errmsg", ":", "err", ".", "result", ".", "writeConcernError", ".", "errmsg", ",", "code", ":", "err", ".", "result", ".", "writeConcernError", ".", "result", "}", ")", ";", "return", "handleCallback", "(", "callback", ",", "new", "BulkWriteError", "(", "toError", "(", "wrappedWriteConcernError", ")", ",", "new", "BulkWriteResult", "(", "bulkResult", ")", ")", ",", "null", ")", ";", "}" ]
handles write concern error @param {object} batch @param {object} bulkResult @param {boolean} ordered @param {WriteConcernError} err @param {function} callback
[ "handles", "write", "concern", "error" ]
5adc639b88a0d72cbeef23a6b5df7f4540745089
https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb/lib/bulk/common.js#L496-L508
57,469
huafu/ember-dev-fixtures
private/utils/dev-fixtures/fixtures.js
recordCursor
function recordCursor(records, id) { var record; id = coerceId(id); for (var i = 0, len = records.length; i < len; i++) { record = records[i]; if (coerceId(record.id) === id) { return {record: record, index: i}; } } }
javascript
function recordCursor(records, id) { var record; id = coerceId(id); for (var i = 0, len = records.length; i < len; i++) { record = records[i]; if (coerceId(record.id) === id) { return {record: record, index: i}; } } }
[ "function", "recordCursor", "(", "records", ",", "id", ")", "{", "var", "record", ";", "id", "=", "coerceId", "(", "id", ")", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "records", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "record", "=", "records", "[", "i", "]", ";", "if", "(", "coerceId", "(", "record", ".", "id", ")", "===", "id", ")", "{", "return", "{", "record", ":", "record", ",", "index", ":", "i", "}", ";", "}", "}", "}" ]
Get the cursor of a record for a given ID @function recordCursor @param {Array} records @param {string|number} id @return {{record: Object, index: number}}
[ "Get", "the", "cursor", "of", "a", "record", "for", "a", "given", "ID" ]
811ed4d339c2dc840d5b297b5b244726cf1339ca
https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/utils/dev-fixtures/fixtures.js#L38-L47
57,470
huafu/ember-dev-fixtures
private/utils/dev-fixtures/fixtures.js
function (overlayName, modelName) { var key = (overlayName || BASE_OVERLAY) + '#' + modelName; if (!this.instances[key]) { this.instances[key] = DevFixturesFixtures.create({ modelName: modelName, overlayName: overlayName }); } return this.instances[key]; }
javascript
function (overlayName, modelName) { var key = (overlayName || BASE_OVERLAY) + '#' + modelName; if (!this.instances[key]) { this.instances[key] = DevFixturesFixtures.create({ modelName: modelName, overlayName: overlayName }); } return this.instances[key]; }
[ "function", "(", "overlayName", ",", "modelName", ")", "{", "var", "key", "=", "(", "overlayName", "||", "BASE_OVERLAY", ")", "+", "'#'", "+", "modelName", ";", "if", "(", "!", "this", ".", "instances", "[", "key", "]", ")", "{", "this", ".", "instances", "[", "key", "]", "=", "DevFixturesFixtures", ".", "create", "(", "{", "modelName", ":", "modelName", ",", "overlayName", ":", "overlayName", "}", ")", ";", "}", "return", "this", ".", "instances", "[", "key", "]", ";", "}" ]
Get the instance for given overlay name and model name @method for @param {string} overlayName @param {string} modelName @return {DevFixturesFixtures}
[ "Get", "the", "instance", "for", "given", "overlay", "name", "and", "model", "name" ]
811ed4d339c2dc840d5b297b5b244726cf1339ca
https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/utils/dev-fixtures/fixtures.js#L263-L272
57,471
AndreasMadsen/drugged
drugged.js
Router
function Router(HandleConstructor) { if (!(this instanceof Router)) return new Router(HandleConstructor); this.Handle = DefaultHandle; this.router = new HttpHash(); this.collections = new Map(); this.attachMethods = []; }
javascript
function Router(HandleConstructor) { if (!(this instanceof Router)) return new Router(HandleConstructor); this.Handle = DefaultHandle; this.router = new HttpHash(); this.collections = new Map(); this.attachMethods = []; }
[ "function", "Router", "(", "HandleConstructor", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Router", ")", ")", "return", "new", "Router", "(", "HandleConstructor", ")", ";", "this", ".", "Handle", "=", "DefaultHandle", ";", "this", ".", "router", "=", "new", "HttpHash", "(", ")", ";", "this", ".", "collections", "=", "new", "Map", "(", ")", ";", "this", ".", "attachMethods", "=", "[", "]", ";", "}" ]
API for creating routes and dispatching requests
[ "API", "for", "creating", "routes", "and", "dispatching", "requests" ]
2ba5e9a9e87dd43a6754f711a125da13c58da68b
https://github.com/AndreasMadsen/drugged/blob/2ba5e9a9e87dd43a6754f711a125da13c58da68b/drugged.js#L50-L57
57,472
AndreasMadsen/drugged
drugged.js
done
function done(err) { if (err) return handle.error(err); // Evaluate all the attach methods for (const attachMethod of self.attachMethods) { attachMethod.call(handle); } // No match found, send 404 if (match.handler === null) { err = new Error('Not Found'); err.statusCode = 404; return handle.error(err); } // match found, relay to HandlerCollection match.handler(req.method, handle, match.params, match.splat); }
javascript
function done(err) { if (err) return handle.error(err); // Evaluate all the attach methods for (const attachMethod of self.attachMethods) { attachMethod.call(handle); } // No match found, send 404 if (match.handler === null) { err = new Error('Not Found'); err.statusCode = 404; return handle.error(err); } // match found, relay to HandlerCollection match.handler(req.method, handle, match.params, match.splat); }
[ "function", "done", "(", "err", ")", "{", "if", "(", "err", ")", "return", "handle", ".", "error", "(", "err", ")", ";", "// Evaluate all the attach methods", "for", "(", "const", "attachMethod", "of", "self", ".", "attachMethods", ")", "{", "attachMethod", ".", "call", "(", "handle", ")", ";", "}", "// No match found, send 404", "if", "(", "match", ".", "handler", "===", "null", ")", "{", "err", "=", "new", "Error", "(", "'Not Found'", ")", ";", "err", ".", "statusCode", "=", "404", ";", "return", "handle", ".", "error", "(", "err", ")", ";", "}", "// match found, relay to HandlerCollection", "match", ".", "handler", "(", "req", ".", "method", ",", "handle", ",", "match", ".", "params", ",", "match", ".", "splat", ")", ";", "}" ]
The handle constructor is done
[ "The", "handle", "constructor", "is", "done" ]
2ba5e9a9e87dd43a6754f711a125da13c58da68b
https://github.com/AndreasMadsen/drugged/blob/2ba5e9a9e87dd43a6754f711a125da13c58da68b/drugged.js#L139-L156
57,473
skazska/marking-codes
v0-hash.js
vsHash
function vsHash(text) { let codes = []; let pos = 0; let partPos = 0; for (let i = 0; i < text.length; i++) { if (!codes[pos]) codes[pos]=[]; let code = decodeCharCode2Int36(text.charCodeAt(i)); if (code !== null) { codes[pos][partPos] = code; partPos += 1; } if (partPos === LEN) { partPos = 0; pos += 1; } } if (partPos) { for (let i = 0; i < LEN - partPos; i++) { codes[pos].push(0); } } return [codes.reduce((result, code) => { result = result ^ code.reduce((r, v, i) => { return r + v * Math.pow(36, i); }, 0); return result; }, 0)]; }
javascript
function vsHash(text) { let codes = []; let pos = 0; let partPos = 0; for (let i = 0; i < text.length; i++) { if (!codes[pos]) codes[pos]=[]; let code = decodeCharCode2Int36(text.charCodeAt(i)); if (code !== null) { codes[pos][partPos] = code; partPos += 1; } if (partPos === LEN) { partPos = 0; pos += 1; } } if (partPos) { for (let i = 0; i < LEN - partPos; i++) { codes[pos].push(0); } } return [codes.reduce((result, code) => { result = result ^ code.reduce((r, v, i) => { return r + v * Math.pow(36, i); }, 0); return result; }, 0)]; }
[ "function", "vsHash", "(", "text", ")", "{", "let", "codes", "=", "[", "]", ";", "let", "pos", "=", "0", ";", "let", "partPos", "=", "0", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "text", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "codes", "[", "pos", "]", ")", "codes", "[", "pos", "]", "=", "[", "]", ";", "let", "code", "=", "decodeCharCode2Int36", "(", "text", ".", "charCodeAt", "(", "i", ")", ")", ";", "if", "(", "code", "!==", "null", ")", "{", "codes", "[", "pos", "]", "[", "partPos", "]", "=", "code", ";", "partPos", "+=", "1", ";", "}", "if", "(", "partPos", "===", "LEN", ")", "{", "partPos", "=", "0", ";", "pos", "+=", "1", ";", "}", "}", "if", "(", "partPos", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "LEN", "-", "partPos", ";", "i", "++", ")", "{", "codes", "[", "pos", "]", ".", "push", "(", "0", ")", ";", "}", "}", "return", "[", "codes", ".", "reduce", "(", "(", "result", ",", "code", ")", "=>", "{", "result", "=", "result", "^", "code", ".", "reduce", "(", "(", "r", ",", "v", ",", "i", ")", "=>", "{", "return", "r", "+", "v", "*", "Math", ".", "pow", "(", "36", ",", "i", ")", ";", "}", ",", "0", ")", ";", "return", "result", ";", "}", ",", "0", ")", "]", ";", "}" ]
hashes string value @param text @returns {Array}
[ "hashes", "string", "value" ]
64c81c39db3dd8a8b17b0bf5e66e4da04d13a846
https://github.com/skazska/marking-codes/blob/64c81c39db3dd8a8b17b0bf5e66e4da04d13a846/v0-hash.js#L73-L102
57,474
fvanwijk/jasmine-mox-matchers
src/jasmine-mox-matchers.js
getResult
function getResult(matcherName, pass, ...messageWithPlaceholderValues) { const formattedMessage = format.apply(this, messageWithPlaceholderValues); messages[matcherName] = formattedMessage; // Save {not} message for later use return { pass, message: formattedMessage.replace(' {not}', pass ? ' not' : '') }; }
javascript
function getResult(matcherName, pass, ...messageWithPlaceholderValues) { const formattedMessage = format.apply(this, messageWithPlaceholderValues); messages[matcherName] = formattedMessage; // Save {not} message for later use return { pass, message: formattedMessage.replace(' {not}', pass ? ' not' : '') }; }
[ "function", "getResult", "(", "matcherName", ",", "pass", ",", "...", "messageWithPlaceholderValues", ")", "{", "const", "formattedMessage", "=", "format", ".", "apply", "(", "this", ",", "messageWithPlaceholderValues", ")", ";", "messages", "[", "matcherName", "]", "=", "formattedMessage", ";", "// Save {not} message for later use", "return", "{", "pass", ",", "message", ":", "formattedMessage", ".", "replace", "(", "' {not}'", ",", "pass", "?", "' not'", ":", "''", ")", "}", ";", "}" ]
Create a jasmine 2 matcher result @param {string} matcherName @param {Boolean} pass @param {...string} message @returns {{pass: boolean, message: string}}
[ "Create", "a", "jasmine", "2", "matcher", "result" ]
99230a8665deef2ffbb69f013bedbcc80fa59a8e
https://github.com/fvanwijk/jasmine-mox-matchers/blob/99230a8665deef2ffbb69f013bedbcc80fa59a8e/src/jasmine-mox-matchers.js#L37-L44
57,475
fvanwijk/jasmine-mox-matchers
src/jasmine-mox-matchers.js
createPromiseWith
function createPromiseWith(actual, expected, verb) { assertPromise(actual); const success = jasmine.createSpy('Promise success callback'); const failure = jasmine.createSpy('Promise failure callback'); actual.then(success, failure); createScope().$digest(); const spy = verb === 'resolved' ? success : failure; let pass = false; let message = `Expected promise to have been ${verb} with ${jasmine.pp(expected)} but it was not ${verb} at all`; if (isJasmine2 ? spy.calls.any() : spy.calls.length) { const actualResult = isJasmine2 ? spy.calls.mostRecent().args[0] : spy.mostRecentCall.args[0]; if (angular.isFunction(expected)) { expected(actualResult); pass = true; } else { pass = angular.equals(actualResult, expected); } message = `Expected promise {not} to have been ${verb} with ${jasmine.pp(expected)} but was ${verb} with \ ${jasmine.pp(actualResult)}`; } return getResult(`to${verb === 'resolved' ? 'Resolve' : 'Reject'}With`, pass, message); }
javascript
function createPromiseWith(actual, expected, verb) { assertPromise(actual); const success = jasmine.createSpy('Promise success callback'); const failure = jasmine.createSpy('Promise failure callback'); actual.then(success, failure); createScope().$digest(); const spy = verb === 'resolved' ? success : failure; let pass = false; let message = `Expected promise to have been ${verb} with ${jasmine.pp(expected)} but it was not ${verb} at all`; if (isJasmine2 ? spy.calls.any() : spy.calls.length) { const actualResult = isJasmine2 ? spy.calls.mostRecent().args[0] : spy.mostRecentCall.args[0]; if (angular.isFunction(expected)) { expected(actualResult); pass = true; } else { pass = angular.equals(actualResult, expected); } message = `Expected promise {not} to have been ${verb} with ${jasmine.pp(expected)} but was ${verb} with \ ${jasmine.pp(actualResult)}`; } return getResult(`to${verb === 'resolved' ? 'Resolve' : 'Reject'}With`, pass, message); }
[ "function", "createPromiseWith", "(", "actual", ",", "expected", ",", "verb", ")", "{", "assertPromise", "(", "actual", ")", ";", "const", "success", "=", "jasmine", ".", "createSpy", "(", "'Promise success callback'", ")", ";", "const", "failure", "=", "jasmine", ".", "createSpy", "(", "'Promise failure callback'", ")", ";", "actual", ".", "then", "(", "success", ",", "failure", ")", ";", "createScope", "(", ")", ".", "$digest", "(", ")", ";", "const", "spy", "=", "verb", "===", "'resolved'", "?", "success", ":", "failure", ";", "let", "pass", "=", "false", ";", "let", "message", "=", "`", "${", "verb", "}", "${", "jasmine", ".", "pp", "(", "expected", ")", "}", "${", "verb", "}", "`", ";", "if", "(", "isJasmine2", "?", "spy", ".", "calls", ".", "any", "(", ")", ":", "spy", ".", "calls", ".", "length", ")", "{", "const", "actualResult", "=", "isJasmine2", "?", "spy", ".", "calls", ".", "mostRecent", "(", ")", ".", "args", "[", "0", "]", ":", "spy", ".", "mostRecentCall", ".", "args", "[", "0", "]", ";", "if", "(", "angular", ".", "isFunction", "(", "expected", ")", ")", "{", "expected", "(", "actualResult", ")", ";", "pass", "=", "true", ";", "}", "else", "{", "pass", "=", "angular", ".", "equals", "(", "actualResult", ",", "expected", ")", ";", "}", "message", "=", "`", "${", "verb", "}", "${", "jasmine", ".", "pp", "(", "expected", ")", "}", "${", "verb", "}", "\\\n", "${", "jasmine", ".", "pp", "(", "actualResult", ")", "}", "`", ";", "}", "return", "getResult", "(", "`", "${", "verb", "===", "'resolved'", "?", "'Resolve'", ":", "'Reject'", "}", "`", ",", "pass", ",", "message", ")", ";", "}" ]
Helper function to create returns for to...With matchers @param {*} actual the test subject @param {*} expected value to match against @param {string} verb 'rejected' or 'resolved' @returns {boolean}
[ "Helper", "function", "to", "create", "returns", "for", "to", "...", "With", "matchers" ]
99230a8665deef2ffbb69f013bedbcc80fa59a8e
https://github.com/fvanwijk/jasmine-mox-matchers/blob/99230a8665deef2ffbb69f013bedbcc80fa59a8e/src/jasmine-mox-matchers.js#L78-L104
57,476
jeremyckahn/bezierizer
dist/bezierizer.js
Bezierizer
function Bezierizer (container) { this.$el = $(container); this.$el.append($(HTML_TEMPLATE)); this._$canvasContainer = this.$el.find('.bezierizer-canvas-container'); this._$canvas = this._$canvasContainer.find('canvas'); this._$handleContainer = this.$el.find('.bezierizer-handle-container'); this._$handles = this._$handleContainer.find('.bezierizer-handle'); this._ctx = this._$canvas[0].getContext('2d'); this._$canvas[0].height = this._$canvas.height(); this._$canvas[0].width = this._$canvas.width(); this._$handles.dragon({ within: this._$handleContainer }); this._points = {}; this.setHandlePositions({ x1: 0.25 ,y1: 0.5 ,x2: 0.75 ,y2: 0.5 }); this._initBindings(); }
javascript
function Bezierizer (container) { this.$el = $(container); this.$el.append($(HTML_TEMPLATE)); this._$canvasContainer = this.$el.find('.bezierizer-canvas-container'); this._$canvas = this._$canvasContainer.find('canvas'); this._$handleContainer = this.$el.find('.bezierizer-handle-container'); this._$handles = this._$handleContainer.find('.bezierizer-handle'); this._ctx = this._$canvas[0].getContext('2d'); this._$canvas[0].height = this._$canvas.height(); this._$canvas[0].width = this._$canvas.width(); this._$handles.dragon({ within: this._$handleContainer }); this._points = {}; this.setHandlePositions({ x1: 0.25 ,y1: 0.5 ,x2: 0.75 ,y2: 0.5 }); this._initBindings(); }
[ "function", "Bezierizer", "(", "container", ")", "{", "this", ".", "$el", "=", "$", "(", "container", ")", ";", "this", ".", "$el", ".", "append", "(", "$", "(", "HTML_TEMPLATE", ")", ")", ";", "this", ".", "_$canvasContainer", "=", "this", ".", "$el", ".", "find", "(", "'.bezierizer-canvas-container'", ")", ";", "this", ".", "_$canvas", "=", "this", ".", "_$canvasContainer", ".", "find", "(", "'canvas'", ")", ";", "this", ".", "_$handleContainer", "=", "this", ".", "$el", ".", "find", "(", "'.bezierizer-handle-container'", ")", ";", "this", ".", "_$handles", "=", "this", ".", "_$handleContainer", ".", "find", "(", "'.bezierizer-handle'", ")", ";", "this", ".", "_ctx", "=", "this", ".", "_$canvas", "[", "0", "]", ".", "getContext", "(", "'2d'", ")", ";", "this", ".", "_$canvas", "[", "0", "]", ".", "height", "=", "this", ".", "_$canvas", ".", "height", "(", ")", ";", "this", ".", "_$canvas", "[", "0", "]", ".", "width", "=", "this", ".", "_$canvas", ".", "width", "(", ")", ";", "this", ".", "_$handles", ".", "dragon", "(", "{", "within", ":", "this", ".", "_$handleContainer", "}", ")", ";", "this", ".", "_points", "=", "{", "}", ";", "this", ".", "setHandlePositions", "(", "{", "x1", ":", "0.25", ",", "y1", ":", "0.5", ",", "x2", ":", "0.75", ",", "y2", ":", "0.5", "}", ")", ";", "this", ".", "_initBindings", "(", ")", ";", "}" ]
Creates a Bezierizer widget and inserts it into the DOM. @param {Element} container The container element to insert the Bezierizer widget into. @constructor
[ "Creates", "a", "Bezierizer", "widget", "and", "inserts", "it", "into", "the", "DOM", "." ]
f1886b556279875bbb0da5051f7b716727b28768
https://github.com/jeremyckahn/bezierizer/blob/f1886b556279875bbb0da5051f7b716727b28768/dist/bezierizer.js#L47-L73
57,477
StefanoMagrassi/gulp-tracer
lib/renderer.js
function() { if (cache.styles) { return cache.styles; } cache.styles = {}; cache.styles[CONSTS.LOG] = chalk.white; cache.styles[CONSTS.INFO] = chalk.cyan; cache.styles[CONSTS.SUCCESS] = chalk.bold.green; cache.styles[CONSTS.WARN] = chalk.yellow; cache.styles[CONSTS.ERROR] = chalk.bold.red; return cache.styles; }
javascript
function() { if (cache.styles) { return cache.styles; } cache.styles = {}; cache.styles[CONSTS.LOG] = chalk.white; cache.styles[CONSTS.INFO] = chalk.cyan; cache.styles[CONSTS.SUCCESS] = chalk.bold.green; cache.styles[CONSTS.WARN] = chalk.yellow; cache.styles[CONSTS.ERROR] = chalk.bold.red; return cache.styles; }
[ "function", "(", ")", "{", "if", "(", "cache", ".", "styles", ")", "{", "return", "cache", ".", "styles", ";", "}", "cache", ".", "styles", "=", "{", "}", ";", "cache", ".", "styles", "[", "CONSTS", ".", "LOG", "]", "=", "chalk", ".", "white", ";", "cache", ".", "styles", "[", "CONSTS", ".", "INFO", "]", "=", "chalk", ".", "cyan", ";", "cache", ".", "styles", "[", "CONSTS", ".", "SUCCESS", "]", "=", "chalk", ".", "bold", ".", "green", ";", "cache", ".", "styles", "[", "CONSTS", ".", "WARN", "]", "=", "chalk", ".", "yellow", ";", "cache", ".", "styles", "[", "CONSTS", ".", "ERROR", "]", "=", "chalk", ".", "bold", ".", "red", ";", "return", "cache", ".", "styles", ";", "}" ]
Gets the chalk styles from cache, creating cache object if it doesn't exist. @return {object}
[ "Gets", "the", "chalk", "styles", "from", "cache", "creating", "cache", "object", "if", "it", "doesn", "t", "exist", "." ]
11839f916b0fa39260178678332a795215a17b16
https://github.com/StefanoMagrassi/gulp-tracer/blob/11839f916b0fa39260178678332a795215a17b16/lib/renderer.js#L32-L45
57,478
StefanoMagrassi/gulp-tracer
lib/renderer.js
function(type) { var t = '[' + type.toUpperCase() + ']'; return utils.filler(t, utils.longestKey(CONSTS, 2)); }
javascript
function(type) { var t = '[' + type.toUpperCase() + ']'; return utils.filler(t, utils.longestKey(CONSTS, 2)); }
[ "function", "(", "type", ")", "{", "var", "t", "=", "'['", "+", "type", ".", "toUpperCase", "(", ")", "+", "']'", ";", "return", "utils", ".", "filler", "(", "t", ",", "utils", ".", "longestKey", "(", "CONSTS", ",", "2", ")", ")", ";", "}" ]
Renders type tag column. @param {string} type @return {string}
[ "Renders", "type", "tag", "column", "." ]
11839f916b0fa39260178678332a795215a17b16
https://github.com/StefanoMagrassi/gulp-tracer/blob/11839f916b0fa39260178678332a795215a17b16/lib/renderer.js#L71-L75
57,479
StefanoMagrassi/gulp-tracer
lib/renderer.js
function(type, messages) { if (type !== CONSTS.LOG) { messages.unshift(tag(type)); } return messages.map(styles.bind(null, type)); }
javascript
function(type, messages) { if (type !== CONSTS.LOG) { messages.unshift(tag(type)); } return messages.map(styles.bind(null, type)); }
[ "function", "(", "type", ",", "messages", ")", "{", "if", "(", "type", "!==", "CONSTS", ".", "LOG", ")", "{", "messages", ".", "unshift", "(", "tag", "(", "type", ")", ")", ";", "}", "return", "messages", ".", "map", "(", "styles", ".", "bind", "(", "null", ",", "type", ")", ")", ";", "}" ]
Remaps messages applying styles. @param {string} type @param {array} messages @return {array}
[ "Remaps", "messages", "applying", "styles", "." ]
11839f916b0fa39260178678332a795215a17b16
https://github.com/StefanoMagrassi/gulp-tracer/blob/11839f916b0fa39260178678332a795215a17b16/lib/renderer.js#L83-L89
57,480
SamPlacette/charon
index.js
detectErrors
function detectErrors (err, responseSpec, next) { var callbackErr; if (err) { callbackErr = err; } else { var status = responseSpec.statusCode; if (status == 403) { callbackErr = new Charon.RequestForbiddenError(responseSpec); } else if (status == 404) { callbackErr = new Charon.ResourceNotFoundError(responseSpec); } else if (status == 409) { callbackErr = new Charon.ResourceConflictError(responseSpec); } else if (status >= 400 && status <= 499) { // 4xx error callbackErr = new Charon.ConsumerError(responseSpec); } else if (status >= 500 && status <= 599) { // 5xx error callbackErr = new Charon.ServiceError(responseSpec); } else if (! (status >= 200 && status <= 299)) { // not sure what this is, but it's not successful callbackErr = new Charon.RuntimeError('Unrecognized HTTP status code', responseSpec); } } this.invokeNext(callbackErr, responseSpec, next); }
javascript
function detectErrors (err, responseSpec, next) { var callbackErr; if (err) { callbackErr = err; } else { var status = responseSpec.statusCode; if (status == 403) { callbackErr = new Charon.RequestForbiddenError(responseSpec); } else if (status == 404) { callbackErr = new Charon.ResourceNotFoundError(responseSpec); } else if (status == 409) { callbackErr = new Charon.ResourceConflictError(responseSpec); } else if (status >= 400 && status <= 499) { // 4xx error callbackErr = new Charon.ConsumerError(responseSpec); } else if (status >= 500 && status <= 599) { // 5xx error callbackErr = new Charon.ServiceError(responseSpec); } else if (! (status >= 200 && status <= 299)) { // not sure what this is, but it's not successful callbackErr = new Charon.RuntimeError('Unrecognized HTTP status code', responseSpec); } } this.invokeNext(callbackErr, responseSpec, next); }
[ "function", "detectErrors", "(", "err", ",", "responseSpec", ",", "next", ")", "{", "var", "callbackErr", ";", "if", "(", "err", ")", "{", "callbackErr", "=", "err", ";", "}", "else", "{", "var", "status", "=", "responseSpec", ".", "statusCode", ";", "if", "(", "status", "==", "403", ")", "{", "callbackErr", "=", "new", "Charon", ".", "RequestForbiddenError", "(", "responseSpec", ")", ";", "}", "else", "if", "(", "status", "==", "404", ")", "{", "callbackErr", "=", "new", "Charon", ".", "ResourceNotFoundError", "(", "responseSpec", ")", ";", "}", "else", "if", "(", "status", "==", "409", ")", "{", "callbackErr", "=", "new", "Charon", ".", "ResourceConflictError", "(", "responseSpec", ")", ";", "}", "else", "if", "(", "status", ">=", "400", "&&", "status", "<=", "499", ")", "{", "// 4xx error", "callbackErr", "=", "new", "Charon", ".", "ConsumerError", "(", "responseSpec", ")", ";", "}", "else", "if", "(", "status", ">=", "500", "&&", "status", "<=", "599", ")", "{", "// 5xx error", "callbackErr", "=", "new", "Charon", ".", "ServiceError", "(", "responseSpec", ")", ";", "}", "else", "if", "(", "!", "(", "status", ">=", "200", "&&", "status", "<=", "299", ")", ")", "{", "// not sure what this is, but it's not successful", "callbackErr", "=", "new", "Charon", ".", "RuntimeError", "(", "'Unrecognized HTTP status code'", ",", "responseSpec", ")", ";", "}", "}", "this", ".", "invokeNext", "(", "callbackErr", ",", "responseSpec", ",", "next", ")", ";", "}" ]
A response middleware function. Attempts to detect errors in the ``responseSpec`` and create appropriate error instances to pass to the ``next`` callback as necessary. This logic should be common for most APIs, but it may be overidden by the integrator if so desired.
[ "A", "response", "middleware", "function", ".", "Attempts", "to", "detect", "errors", "in", "the", "responseSpec", "and", "create", "appropriate", "error", "instances", "to", "pass", "to", "the", "next", "callback", "as", "necessary", ".", "This", "logic", "should", "be", "common", "for", "most", "APIs", "but", "it", "may", "be", "overidden", "by", "the", "integrator", "if", "so", "desired", "." ]
c88bba7c2cd082b8fa90d02e82d0ffc2726c3558
https://github.com/SamPlacette/charon/blob/c88bba7c2cd082b8fa90d02e82d0ffc2726c3558/index.js#L190-L220
57,481
SamPlacette/charon
index.js
parseResource
function parseResource (err, responseSpec, next) { var resource = responseSpec ? responseSpec.body : undefined; this.invokeNext(err, resource, next); }
javascript
function parseResource (err, responseSpec, next) { var resource = responseSpec ? responseSpec.body : undefined; this.invokeNext(err, resource, next); }
[ "function", "parseResource", "(", "err", ",", "responseSpec", ",", "next", ")", "{", "var", "resource", "=", "responseSpec", "?", "responseSpec", ".", "body", ":", "undefined", ";", "this", ".", "invokeNext", "(", "err", ",", "resource", ",", "next", ")", ";", "}" ]
default resource parser. Executes after all callback wrappers. Responsible for parsing the resource from the response and passing ``err``, ``resource`` to the next callback.
[ "default", "resource", "parser", ".", "Executes", "after", "all", "callback", "wrappers", ".", "Responsible", "for", "parsing", "the", "resource", "from", "the", "response", "and", "passing", "err", "resource", "to", "the", "next", "callback", "." ]
c88bba7c2cd082b8fa90d02e82d0ffc2726c3558
https://github.com/SamPlacette/charon/blob/c88bba7c2cd082b8fa90d02e82d0ffc2726c3558/index.js#L369-L372
57,482
SamPlacette/charon
index.js
function (propertyName) { var value = this.client[propertyName]; if (! _.isUndefined(this[propertyName])) { // pass, defer to resource manager prototype properties } else if (_.isFunction(value)) { // copy functions (including the error ctors) by direct reference this[propertyName] = value; } else if (_.contains(this.client.serviceCallParams, propertyName)) { // default service call params which are not function values are proxied // via getter functions this[propertyName] = function () { return this.client[propertyName]; }; } // all other properties are assumed to be client configuration, and // should be accessed by referencing the ``client`` instance property. }
javascript
function (propertyName) { var value = this.client[propertyName]; if (! _.isUndefined(this[propertyName])) { // pass, defer to resource manager prototype properties } else if (_.isFunction(value)) { // copy functions (including the error ctors) by direct reference this[propertyName] = value; } else if (_.contains(this.client.serviceCallParams, propertyName)) { // default service call params which are not function values are proxied // via getter functions this[propertyName] = function () { return this.client[propertyName]; }; } // all other properties are assumed to be client configuration, and // should be accessed by referencing the ``client`` instance property. }
[ "function", "(", "propertyName", ")", "{", "var", "value", "=", "this", ".", "client", "[", "propertyName", "]", ";", "if", "(", "!", "_", ".", "isUndefined", "(", "this", "[", "propertyName", "]", ")", ")", "{", "// pass, defer to resource manager prototype properties", "}", "else", "if", "(", "_", ".", "isFunction", "(", "value", ")", ")", "{", "// copy functions (including the error ctors) by direct reference", "this", "[", "propertyName", "]", "=", "value", ";", "}", "else", "if", "(", "_", ".", "contains", "(", "this", ".", "client", ".", "serviceCallParams", ",", "propertyName", ")", ")", "{", "// default service call params which are not function values are proxied", "// via getter functions", "this", "[", "propertyName", "]", "=", "function", "(", ")", "{", "return", "this", ".", "client", "[", "propertyName", "]", ";", "}", ";", "}", "// all other properties are assumed to be client configuration, and", "// should be accessed by referencing the ``client`` instance property.", "}" ]
links a single property from the client (identified by ``propertyName`` to ``this`` instance
[ "links", "a", "single", "property", "from", "the", "client", "(", "identified", "by", "propertyName", "to", "this", "instance" ]
c88bba7c2cd082b8fa90d02e82d0ffc2726c3558
https://github.com/SamPlacette/charon/blob/c88bba7c2cd082b8fa90d02e82d0ffc2726c3558/index.js#L410-L426
57,483
melvincarvalho/rdf-shell
lib/ls.js
ls
function ls(uri, callback) { if (!uri) { callback(new Error('uri is required')) } util.getAll(uri, function(err, val) { var res = {} for (var i=0; i<val.length; i++) { if (val[i].predicate.uri === 'http://www.w3.org/ns/ldp#contains') { if (! res[val[i].object.uri]) res[val[i].object.uri] = {} res[val[i].object.uri].contains = val[i].object.uri } if (val[i].predicate.uri === 'http://www.w3.org/ns/posix/stat#mtime') { if (! res[val[i].subject.uri]) res[val[i].subject.uri] = {} res[val[i].subject.uri].mtime = val[i].object.value } } var arr =[] for( var k in res ) { if (res.hasOwnProperty(k)) { if (k && res[k] && res[k].mtime && res[k].contains) { arr.push({ file : res[k].contains, mtime : res[k].mtime }) } } } arr = arr.sort(function(a, b){ if (a.mtime < b.mtime) return -1 if (a.mtime > b.mtime) return 1 return 0 }) var ret = [] for (i=0; i<arr.length; i++) { ret.push(arr[i].file) } callback(null, ret) }) }
javascript
function ls(uri, callback) { if (!uri) { callback(new Error('uri is required')) } util.getAll(uri, function(err, val) { var res = {} for (var i=0; i<val.length; i++) { if (val[i].predicate.uri === 'http://www.w3.org/ns/ldp#contains') { if (! res[val[i].object.uri]) res[val[i].object.uri] = {} res[val[i].object.uri].contains = val[i].object.uri } if (val[i].predicate.uri === 'http://www.w3.org/ns/posix/stat#mtime') { if (! res[val[i].subject.uri]) res[val[i].subject.uri] = {} res[val[i].subject.uri].mtime = val[i].object.value } } var arr =[] for( var k in res ) { if (res.hasOwnProperty(k)) { if (k && res[k] && res[k].mtime && res[k].contains) { arr.push({ file : res[k].contains, mtime : res[k].mtime }) } } } arr = arr.sort(function(a, b){ if (a.mtime < b.mtime) return -1 if (a.mtime > b.mtime) return 1 return 0 }) var ret = [] for (i=0; i<arr.length; i++) { ret.push(arr[i].file) } callback(null, ret) }) }
[ "function", "ls", "(", "uri", ",", "callback", ")", "{", "if", "(", "!", "uri", ")", "{", "callback", "(", "new", "Error", "(", "'uri is required'", ")", ")", "}", "util", ".", "getAll", "(", "uri", ",", "function", "(", "err", ",", "val", ")", "{", "var", "res", "=", "{", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "val", ".", "length", ";", "i", "++", ")", "{", "if", "(", "val", "[", "i", "]", ".", "predicate", ".", "uri", "===", "'http://www.w3.org/ns/ldp#contains'", ")", "{", "if", "(", "!", "res", "[", "val", "[", "i", "]", ".", "object", ".", "uri", "]", ")", "res", "[", "val", "[", "i", "]", ".", "object", ".", "uri", "]", "=", "{", "}", "res", "[", "val", "[", "i", "]", ".", "object", ".", "uri", "]", ".", "contains", "=", "val", "[", "i", "]", ".", "object", ".", "uri", "}", "if", "(", "val", "[", "i", "]", ".", "predicate", ".", "uri", "===", "'http://www.w3.org/ns/posix/stat#mtime'", ")", "{", "if", "(", "!", "res", "[", "val", "[", "i", "]", ".", "subject", ".", "uri", "]", ")", "res", "[", "val", "[", "i", "]", ".", "subject", ".", "uri", "]", "=", "{", "}", "res", "[", "val", "[", "i", "]", ".", "subject", ".", "uri", "]", ".", "mtime", "=", "val", "[", "i", "]", ".", "object", ".", "value", "}", "}", "var", "arr", "=", "[", "]", "for", "(", "var", "k", "in", "res", ")", "{", "if", "(", "res", ".", "hasOwnProperty", "(", "k", ")", ")", "{", "if", "(", "k", "&&", "res", "[", "k", "]", "&&", "res", "[", "k", "]", ".", "mtime", "&&", "res", "[", "k", "]", ".", "contains", ")", "{", "arr", ".", "push", "(", "{", "file", ":", "res", "[", "k", "]", ".", "contains", ",", "mtime", ":", "res", "[", "k", "]", ".", "mtime", "}", ")", "}", "}", "}", "arr", "=", "arr", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "if", "(", "a", ".", "mtime", "<", "b", ".", "mtime", ")", "return", "-", "1", "if", "(", "a", ".", "mtime", ">", "b", ".", "mtime", ")", "return", "1", "return", "0", "}", ")", "var", "ret", "=", "[", "]", "for", "(", "i", "=", "0", ";", "i", "<", "arr", ".", "length", ";", "i", "++", ")", "{", "ret", ".", "push", "(", "arr", "[", "i", "]", ".", "file", ")", "}", "callback", "(", "null", ",", "ret", ")", "}", ")", "}" ]
get the contents of a container as an array @param {[type]} argv [description] @param {Function} callback [description] @return {[type]} [description]
[ "get", "the", "contents", "of", "a", "container", "as", "an", "array" ]
bf2015f6f333855e69a18ce3ec9e917bbddfb425
https://github.com/melvincarvalho/rdf-shell/blob/bf2015f6f333855e69a18ce3ec9e917bbddfb425/lib/ls.js#L11-L51
57,484
huafu/ember-dev-fixtures
private/utils/dev-fixtures/overlay.js
function (name) { name = name || BASE_OVERLAY; if (!this.instances[name]) { this.instances[name] = DevFixturesOverlay.create({name: name}); } return this.instances[name]; }
javascript
function (name) { name = name || BASE_OVERLAY; if (!this.instances[name]) { this.instances[name] = DevFixturesOverlay.create({name: name}); } return this.instances[name]; }
[ "function", "(", "name", ")", "{", "name", "=", "name", "||", "BASE_OVERLAY", ";", "if", "(", "!", "this", ".", "instances", "[", "name", "]", ")", "{", "this", ".", "instances", "[", "name", "]", "=", "DevFixturesOverlay", ".", "create", "(", "{", "name", ":", "name", "}", ")", ";", "}", "return", "this", ".", "instances", "[", "name", "]", ";", "}" ]
Get the singleton instance for the given overlay name @method for @param {string} name @return {DevFixturesOverlay}
[ "Get", "the", "singleton", "instance", "for", "the", "given", "overlay", "name" ]
811ed4d339c2dc840d5b297b5b244726cf1339ca
https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/utils/dev-fixtures/overlay.js#L197-L203
57,485
RnbWd/parse-browserify
lib/op.js
function(json) { var decoder = Parse.Op._opDecoderMap[json.__op]; if (decoder) { return decoder(json); } else { return undefined; } }
javascript
function(json) { var decoder = Parse.Op._opDecoderMap[json.__op]; if (decoder) { return decoder(json); } else { return undefined; } }
[ "function", "(", "json", ")", "{", "var", "decoder", "=", "Parse", ".", "Op", ".", "_opDecoderMap", "[", "json", ".", "__op", "]", ";", "if", "(", "decoder", ")", "{", "return", "decoder", "(", "json", ")", ";", "}", "else", "{", "return", "undefined", ";", "}", "}" ]
Converts a json object into an instance of a subclass of Parse.Op.
[ "Converts", "a", "json", "object", "into", "an", "instance", "of", "a", "subclass", "of", "Parse", ".", "Op", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/op.js#L45-L52
57,486
RnbWd/parse-browserify
lib/op.js
function() { var self = this; return _.map(this.relationsToRemove, function(objectId) { var object = Parse.Object._create(self._targetClassName); object.id = objectId; return object; }); }
javascript
function() { var self = this; return _.map(this.relationsToRemove, function(objectId) { var object = Parse.Object._create(self._targetClassName); object.id = objectId; return object; }); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "return", "_", ".", "map", "(", "this", ".", "relationsToRemove", ",", "function", "(", "objectId", ")", "{", "var", "object", "=", "Parse", ".", "Object", ".", "_create", "(", "self", ".", "_targetClassName", ")", ";", "object", ".", "id", "=", "objectId", ";", "return", "object", ";", "}", ")", ";", "}" ]
Returns an array of unfetched Parse.Object that are being removed from the relation. @return {Array}
[ "Returns", "an", "array", "of", "unfetched", "Parse", ".", "Object", "that", "are", "being", "removed", "from", "the", "relation", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/op.js#L434-L441
57,487
RnbWd/parse-browserify
lib/op.js
function() { var adds = null; var removes = null; var self = this; var idToPointer = function(id) { return { __type: 'Pointer', className: self._targetClassName, objectId: id }; }; var pointers = null; if (this.relationsToAdd.length > 0) { pointers = _.map(this.relationsToAdd, idToPointer); adds = { "__op": "AddRelation", "objects": pointers }; } if (this.relationsToRemove.length > 0) { pointers = _.map(this.relationsToRemove, idToPointer); removes = { "__op": "RemoveRelation", "objects": pointers }; } if (adds && removes) { return { "__op": "Batch", "ops": [adds, removes]}; } return adds || removes || {}; }
javascript
function() { var adds = null; var removes = null; var self = this; var idToPointer = function(id) { return { __type: 'Pointer', className: self._targetClassName, objectId: id }; }; var pointers = null; if (this.relationsToAdd.length > 0) { pointers = _.map(this.relationsToAdd, idToPointer); adds = { "__op": "AddRelation", "objects": pointers }; } if (this.relationsToRemove.length > 0) { pointers = _.map(this.relationsToRemove, idToPointer); removes = { "__op": "RemoveRelation", "objects": pointers }; } if (adds && removes) { return { "__op": "Batch", "ops": [adds, removes]}; } return adds || removes || {}; }
[ "function", "(", ")", "{", "var", "adds", "=", "null", ";", "var", "removes", "=", "null", ";", "var", "self", "=", "this", ";", "var", "idToPointer", "=", "function", "(", "id", ")", "{", "return", "{", "__type", ":", "'Pointer'", ",", "className", ":", "self", ".", "_targetClassName", ",", "objectId", ":", "id", "}", ";", "}", ";", "var", "pointers", "=", "null", ";", "if", "(", "this", ".", "relationsToAdd", ".", "length", ">", "0", ")", "{", "pointers", "=", "_", ".", "map", "(", "this", ".", "relationsToAdd", ",", "idToPointer", ")", ";", "adds", "=", "{", "\"__op\"", ":", "\"AddRelation\"", ",", "\"objects\"", ":", "pointers", "}", ";", "}", "if", "(", "this", ".", "relationsToRemove", ".", "length", ">", "0", ")", "{", "pointers", "=", "_", ".", "map", "(", "this", ".", "relationsToRemove", ",", "idToPointer", ")", ";", "removes", "=", "{", "\"__op\"", ":", "\"RemoveRelation\"", ",", "\"objects\"", ":", "pointers", "}", ";", "}", "if", "(", "adds", "&&", "removes", ")", "{", "return", "{", "\"__op\"", ":", "\"Batch\"", ",", "\"ops\"", ":", "[", "adds", ",", "removes", "]", "}", ";", "}", "return", "adds", "||", "removes", "||", "{", "}", ";", "}" ]
Returns a JSON version of the operation suitable for sending to Parse. @return {Object}
[ "Returns", "a", "JSON", "version", "of", "the", "operation", "suitable", "for", "sending", "to", "Parse", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/op.js#L447-L472
57,488
sdgluck/serialise-request
index.js
blobToString
function blobToString (blob) { return blobUtil .blobToArrayBuffer(blob) .then(function (buffer) { return String.fromCharCode.apply(null, new Uint16Array(buffer)) }) }
javascript
function blobToString (blob) { return blobUtil .blobToArrayBuffer(blob) .then(function (buffer) { return String.fromCharCode.apply(null, new Uint16Array(buffer)) }) }
[ "function", "blobToString", "(", "blob", ")", "{", "return", "blobUtil", ".", "blobToArrayBuffer", "(", "blob", ")", ".", "then", "(", "function", "(", "buffer", ")", "{", "return", "String", ".", "fromCharCode", ".", "apply", "(", "null", ",", "new", "Uint16Array", "(", "buffer", ")", ")", "}", ")", "}" ]
Turn a Blob into a String. @param {Blob} blob @returns {Promise}
[ "Turn", "a", "Blob", "into", "a", "String", "." ]
c0e108729bbe92cc05152d29ed32e7f7a7fffb82
https://github.com/sdgluck/serialise-request/blob/c0e108729bbe92cc05152d29ed32e7f7a7fffb82/index.js#L28-L34
57,489
sdgluck/serialise-request
index.js
remakeBody
function remakeBody (body, bodyType) { return blobUtil .base64StringToBlob(body) .then(function (blob) { switch (bodyType) { case BodyTypes.ARRAY_BUFFER: return blobUtil.blobToArrayBuffer(blob) case BodyTypes.BLOB: return blob case BodyTypes.FORM_DATA: throw new Error('Cannot make FormData from serialised Request') case BodyTypes.JSON: return blobToString(blob) .then(function (str) { return JSON.parse(str) }) case BodyTypes.TEXT: return blobToString(blob) default: throw new Error('Unknown requested body type "' + bodyType + '"') } }) }
javascript
function remakeBody (body, bodyType) { return blobUtil .base64StringToBlob(body) .then(function (blob) { switch (bodyType) { case BodyTypes.ARRAY_BUFFER: return blobUtil.blobToArrayBuffer(blob) case BodyTypes.BLOB: return blob case BodyTypes.FORM_DATA: throw new Error('Cannot make FormData from serialised Request') case BodyTypes.JSON: return blobToString(blob) .then(function (str) { return JSON.parse(str) }) case BodyTypes.TEXT: return blobToString(blob) default: throw new Error('Unknown requested body type "' + bodyType + '"') } }) }
[ "function", "remakeBody", "(", "body", ",", "bodyType", ")", "{", "return", "blobUtil", ".", "base64StringToBlob", "(", "body", ")", ".", "then", "(", "function", "(", "blob", ")", "{", "switch", "(", "bodyType", ")", "{", "case", "BodyTypes", ".", "ARRAY_BUFFER", ":", "return", "blobUtil", ".", "blobToArrayBuffer", "(", "blob", ")", "case", "BodyTypes", ".", "BLOB", ":", "return", "blob", "case", "BodyTypes", ".", "FORM_DATA", ":", "throw", "new", "Error", "(", "'Cannot make FormData from serialised Request'", ")", "case", "BodyTypes", ".", "JSON", ":", "return", "blobToString", "(", "blob", ")", ".", "then", "(", "function", "(", "str", ")", "{", "return", "JSON", ".", "parse", "(", "str", ")", "}", ")", "case", "BodyTypes", ".", "TEXT", ":", "return", "blobToString", "(", "blob", ")", "default", ":", "throw", "new", "Error", "(", "'Unknown requested body type \"'", "+", "bodyType", "+", "'\"'", ")", "}", "}", ")", "}" ]
Deserialise the body of a Request. @param {String} body @param {String} bodyType @returns {Promise}
[ "Deserialise", "the", "body", "of", "a", "Request", "." ]
c0e108729bbe92cc05152d29ed32e7f7a7fffb82
https://github.com/sdgluck/serialise-request/blob/c0e108729bbe92cc05152d29ed32e7f7a7fffb82/index.js#L42-L64
57,490
sdgluck/serialise-request
index.js
serialiseRequest
function serialiseRequest (request, toObject) { if (!(request instanceof Request)) { throw new Error('Expecting request to be instance of Request') } var headers = [] var headerNames = request.headers.keys() for (var i = 0; i < headerNames.length; i++) { var headerName = headerNames[i] headers[headerName] = request.headers.get(headerName) } var serialised = { method: request.method, url: request.url, headers: headers, context: request.context, referrer: request.referrer, mode: request.mode, credentials: request.credentials, redirect: request.redirect, integrity: request.integrity, cache: request.cache, bodyUsed: request.bodyUsed } return request .blob() .then(blobUtil.blobToBase64String) .then(function (base64) { serialised.__body = base64 return toObject ? serialised : JSON.stringify(serialised) }) }
javascript
function serialiseRequest (request, toObject) { if (!(request instanceof Request)) { throw new Error('Expecting request to be instance of Request') } var headers = [] var headerNames = request.headers.keys() for (var i = 0; i < headerNames.length; i++) { var headerName = headerNames[i] headers[headerName] = request.headers.get(headerName) } var serialised = { method: request.method, url: request.url, headers: headers, context: request.context, referrer: request.referrer, mode: request.mode, credentials: request.credentials, redirect: request.redirect, integrity: request.integrity, cache: request.cache, bodyUsed: request.bodyUsed } return request .blob() .then(blobUtil.blobToBase64String) .then(function (base64) { serialised.__body = base64 return toObject ? serialised : JSON.stringify(serialised) }) }
[ "function", "serialiseRequest", "(", "request", ",", "toObject", ")", "{", "if", "(", "!", "(", "request", "instanceof", "Request", ")", ")", "{", "throw", "new", "Error", "(", "'Expecting request to be instance of Request'", ")", "}", "var", "headers", "=", "[", "]", "var", "headerNames", "=", "request", ".", "headers", ".", "keys", "(", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "headerNames", ".", "length", ";", "i", "++", ")", "{", "var", "headerName", "=", "headerNames", "[", "i", "]", "headers", "[", "headerName", "]", "=", "request", ".", "headers", ".", "get", "(", "headerName", ")", "}", "var", "serialised", "=", "{", "method", ":", "request", ".", "method", ",", "url", ":", "request", ".", "url", ",", "headers", ":", "headers", ",", "context", ":", "request", ".", "context", ",", "referrer", ":", "request", ".", "referrer", ",", "mode", ":", "request", ".", "mode", ",", "credentials", ":", "request", ".", "credentials", ",", "redirect", ":", "request", ".", "redirect", ",", "integrity", ":", "request", ".", "integrity", ",", "cache", ":", "request", ".", "cache", ",", "bodyUsed", ":", "request", ".", "bodyUsed", "}", "return", "request", ".", "blob", "(", ")", ".", "then", "(", "blobUtil", ".", "blobToBase64String", ")", ".", "then", "(", "function", "(", "base64", ")", "{", "serialised", ".", "__body", "=", "base64", "return", "toObject", "?", "serialised", ":", "JSON", ".", "stringify", "(", "serialised", ")", "}", ")", "}" ]
Serialise a Request to a string or object. @param {Request} request @param {Boolean} [toObject] serialise to an object @returns {Promise}
[ "Serialise", "a", "Request", "to", "a", "string", "or", "object", "." ]
c0e108729bbe92cc05152d29ed32e7f7a7fffb82
https://github.com/sdgluck/serialise-request/blob/c0e108729bbe92cc05152d29ed32e7f7a7fffb82/index.js#L72-L107
57,491
sdgluck/serialise-request
index.js
deserialiseRequest
function deserialiseRequest (serialised) { var options var url if (typeof serialised === 'string') { options = JSON.parse(serialised) url = options.url } else if (typeof serialised === 'object') { options = serialised url = options.url } else { throw new Error('Expecting serialised request to be a string or object') } const request = new Request(url, options) const properties = { context: { enumerable: true, value: options.context } } const methods = Object.keys(BodyTypes).reduce(function (obj, key) { const methodName = BodyMethods[key] obj[methodName] = { enumerable: true, value: function () { if (request.bodyUsed) { return Promise.reject(new TypeError('Already used')) } request.bodyUsed = true return Promise.resolve(remakeBody(options.__body, key)) } } return obj }, properties) Object.defineProperties(request, methods) return request }
javascript
function deserialiseRequest (serialised) { var options var url if (typeof serialised === 'string') { options = JSON.parse(serialised) url = options.url } else if (typeof serialised === 'object') { options = serialised url = options.url } else { throw new Error('Expecting serialised request to be a string or object') } const request = new Request(url, options) const properties = { context: { enumerable: true, value: options.context } } const methods = Object.keys(BodyTypes).reduce(function (obj, key) { const methodName = BodyMethods[key] obj[methodName] = { enumerable: true, value: function () { if (request.bodyUsed) { return Promise.reject(new TypeError('Already used')) } request.bodyUsed = true return Promise.resolve(remakeBody(options.__body, key)) } } return obj }, properties) Object.defineProperties(request, methods) return request }
[ "function", "deserialiseRequest", "(", "serialised", ")", "{", "var", "options", "var", "url", "if", "(", "typeof", "serialised", "===", "'string'", ")", "{", "options", "=", "JSON", ".", "parse", "(", "serialised", ")", "url", "=", "options", ".", "url", "}", "else", "if", "(", "typeof", "serialised", "===", "'object'", ")", "{", "options", "=", "serialised", "url", "=", "options", ".", "url", "}", "else", "{", "throw", "new", "Error", "(", "'Expecting serialised request to be a string or object'", ")", "}", "const", "request", "=", "new", "Request", "(", "url", ",", "options", ")", "const", "properties", "=", "{", "context", ":", "{", "enumerable", ":", "true", ",", "value", ":", "options", ".", "context", "}", "}", "const", "methods", "=", "Object", ".", "keys", "(", "BodyTypes", ")", ".", "reduce", "(", "function", "(", "obj", ",", "key", ")", "{", "const", "methodName", "=", "BodyMethods", "[", "key", "]", "obj", "[", "methodName", "]", "=", "{", "enumerable", ":", "true", ",", "value", ":", "function", "(", ")", "{", "if", "(", "request", ".", "bodyUsed", ")", "{", "return", "Promise", ".", "reject", "(", "new", "TypeError", "(", "'Already used'", ")", ")", "}", "request", ".", "bodyUsed", "=", "true", "return", "Promise", ".", "resolve", "(", "remakeBody", "(", "options", ".", "__body", ",", "key", ")", ")", "}", "}", "return", "obj", "}", ",", "properties", ")", "Object", ".", "defineProperties", "(", "request", ",", "methods", ")", "return", "request", "}" ]
Deserialise a Request from a string or object. @param {Object|String} serialised @returns {Request}
[ "Deserialise", "a", "Request", "from", "a", "string", "or", "object", "." ]
c0e108729bbe92cc05152d29ed32e7f7a7fffb82
https://github.com/sdgluck/serialise-request/blob/c0e108729bbe92cc05152d29ed32e7f7a7fffb82/index.js#L114-L155
57,492
TJkrusinski/buzzfeed-headlines
lib/scraper.js
scrapePage
function scrapePage(cb, pages, links) { links = links || []; pages = pages || basePages.slice(); var url = pages.pop(); jsdom.env({ url: url, scripts: ['http://code.jquery.com/jquery.js'], done: function(err, window){ if (err) return cb(err); _getLinks(window, links); if (!pages.length) return cb(null, links); scrapePage(cb, pages, links); } }); }
javascript
function scrapePage(cb, pages, links) { links = links || []; pages = pages || basePages.slice(); var url = pages.pop(); jsdom.env({ url: url, scripts: ['http://code.jquery.com/jquery.js'], done: function(err, window){ if (err) return cb(err); _getLinks(window, links); if (!pages.length) return cb(null, links); scrapePage(cb, pages, links); } }); }
[ "function", "scrapePage", "(", "cb", ",", "pages", ",", "links", ")", "{", "links", "=", "links", "||", "[", "]", ";", "pages", "=", "pages", "||", "basePages", ".", "slice", "(", ")", ";", "var", "url", "=", "pages", ".", "pop", "(", ")", ";", "jsdom", ".", "env", "(", "{", "url", ":", "url", ",", "scripts", ":", "[", "'http://code.jquery.com/jquery.js'", "]", ",", "done", ":", "function", "(", "err", ",", "window", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "_getLinks", "(", "window", ",", "links", ")", ";", "if", "(", "!", "pages", ".", "length", ")", "return", "cb", "(", "null", ",", "links", ")", ";", "scrapePage", "(", "cb", ",", "pages", ",", "links", ")", ";", "}", "}", ")", ";", "}" ]
Scrape a page @param {Function} cb @param {Number} pages - max number of pages @param {String} links - the links accumulated thus far @return undefined @api public
[ "Scrape", "a", "page" ]
542f6a81c56a3bb57da3a7f5b391da0788f76e5e
https://github.com/TJkrusinski/buzzfeed-headlines/blob/542f6a81c56a3bb57da3a7f5b391da0788f76e5e/lib/scraper.js#L29-L45
57,493
TJkrusinski/buzzfeed-headlines
lib/scraper.js
_getLinks
function _getLinks (window, links) { var $ = window.$; $('a.lede__link').each(function(){ var text = $(this).text().trim(); if (!text) return; links.push(text); }); }
javascript
function _getLinks (window, links) { var $ = window.$; $('a.lede__link').each(function(){ var text = $(this).text().trim(); if (!text) return; links.push(text); }); }
[ "function", "_getLinks", "(", "window", ",", "links", ")", "{", "var", "$", "=", "window", ".", "$", ";", "$", "(", "'a.lede__link'", ")", ".", "each", "(", "function", "(", ")", "{", "var", "text", "=", "$", "(", "this", ")", ".", "text", "(", ")", ".", "trim", "(", ")", ";", "if", "(", "!", "text", ")", "return", ";", "links", ".", "push", "(", "text", ")", ";", "}", ")", ";", "}" ]
Get article links from the page @param {Object} window - jsdom `window` object @param {Array} links - array of headline links @api private
[ "Get", "article", "links", "from", "the", "page" ]
542f6a81c56a3bb57da3a7f5b391da0788f76e5e
https://github.com/TJkrusinski/buzzfeed-headlines/blob/542f6a81c56a3bb57da3a7f5b391da0788f76e5e/lib/scraper.js#L56-L64
57,494
nutella-framework/nutella_lib.js
src/simple-mqtt-client/client-browser.js
generateRandomClientId
function generateRandomClientId() { var length = 22; var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; var result = ''; for (var i = length; i > 0; --i) { result += chars[Math.round(Math.random() * (chars.length - 1))]; } return result; }
javascript
function generateRandomClientId() { var length = 22; var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; var result = ''; for (var i = length; i > 0; --i) { result += chars[Math.round(Math.random() * (chars.length - 1))]; } return result; }
[ "function", "generateRandomClientId", "(", ")", "{", "var", "length", "=", "22", ";", "var", "chars", "=", "'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'", ";", "var", "result", "=", "''", ";", "for", "(", "var", "i", "=", "length", ";", "i", ">", "0", ";", "--", "i", ")", "{", "result", "+=", "chars", "[", "Math", ".", "round", "(", "Math", ".", "random", "(", ")", "*", "(", "chars", ".", "length", "-", "1", ")", ")", "]", ";", "}", "return", "result", ";", "}" ]
Helper function that generates a random client ID
[ "Helper", "function", "that", "generates", "a", "random", "client", "ID" ]
b3a3406a407e2a1ada6edcc503b70991f9cb249b
https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/simple-mqtt-client/client-browser.js#L30-L38
57,495
nutella-framework/nutella_lib.js
src/simple-mqtt-client/client-browser.js
connectBrowser
function connectBrowser (subscriptions, backlog, host, done_cb, secure) { // Associate the right port var websocket_uri; if(secure == true) { websocket_uri ='wss://' + host + ':1885/mqtt'; } else { websocket_uri ='ws://' + host + ':1884/mqtt'; } // Create client var client = new mqtt_lib.Client(websocket_uri, generateRandomClientId()); // Register callback for connection lost client.onConnectionLost = function() { // TODO try to reconnect }; // Register callback for received message client.onMessageArrived = function (message) { // Execute all the appropriate callbacks: // the ones specific to this channel with a single parameter (message) // the ones associated to a wildcard channel, with two parameters (message and channel) var cbs = findCallbacks(subscriptions, message.destinationName); if (cbs!==undefined) { cbs.forEach(function(cb) { if (Object.keys(subscriptions).indexOf(message.destinationName)!==-1) cb(message.payloadString); else cb(message.payloadString, message.destinationName); }); } }; // Connect client.connect({onSuccess: function() { // Execute optional done callback passing true if (done_cb!==undefined) done_cb(true); // Execute the backlog of operations performed while the client wasn't connected backlog.forEach(function(e) { e.op.apply(this, e.params); }); }, onFailure: function() { // Execute optional done callback passing false if (done_cb!==undefined) done_cb(false); else console.error('There was a problem initializing nutella.'); }}); return client; }
javascript
function connectBrowser (subscriptions, backlog, host, done_cb, secure) { // Associate the right port var websocket_uri; if(secure == true) { websocket_uri ='wss://' + host + ':1885/mqtt'; } else { websocket_uri ='ws://' + host + ':1884/mqtt'; } // Create client var client = new mqtt_lib.Client(websocket_uri, generateRandomClientId()); // Register callback for connection lost client.onConnectionLost = function() { // TODO try to reconnect }; // Register callback for received message client.onMessageArrived = function (message) { // Execute all the appropriate callbacks: // the ones specific to this channel with a single parameter (message) // the ones associated to a wildcard channel, with two parameters (message and channel) var cbs = findCallbacks(subscriptions, message.destinationName); if (cbs!==undefined) { cbs.forEach(function(cb) { if (Object.keys(subscriptions).indexOf(message.destinationName)!==-1) cb(message.payloadString); else cb(message.payloadString, message.destinationName); }); } }; // Connect client.connect({onSuccess: function() { // Execute optional done callback passing true if (done_cb!==undefined) done_cb(true); // Execute the backlog of operations performed while the client wasn't connected backlog.forEach(function(e) { e.op.apply(this, e.params); }); }, onFailure: function() { // Execute optional done callback passing false if (done_cb!==undefined) done_cb(false); else console.error('There was a problem initializing nutella.'); }}); return client; }
[ "function", "connectBrowser", "(", "subscriptions", ",", "backlog", ",", "host", ",", "done_cb", ",", "secure", ")", "{", "// Associate the right port", "var", "websocket_uri", ";", "if", "(", "secure", "==", "true", ")", "{", "websocket_uri", "=", "'wss://'", "+", "host", "+", "':1885/mqtt'", ";", "}", "else", "{", "websocket_uri", "=", "'ws://'", "+", "host", "+", "':1884/mqtt'", ";", "}", "// Create client", "var", "client", "=", "new", "mqtt_lib", ".", "Client", "(", "websocket_uri", ",", "generateRandomClientId", "(", ")", ")", ";", "// Register callback for connection lost", "client", ".", "onConnectionLost", "=", "function", "(", ")", "{", "// TODO try to reconnect", "}", ";", "// Register callback for received message", "client", ".", "onMessageArrived", "=", "function", "(", "message", ")", "{", "// Execute all the appropriate callbacks:", "// the ones specific to this channel with a single parameter (message)", "// the ones associated to a wildcard channel, with two parameters (message and channel)", "var", "cbs", "=", "findCallbacks", "(", "subscriptions", ",", "message", ".", "destinationName", ")", ";", "if", "(", "cbs", "!==", "undefined", ")", "{", "cbs", ".", "forEach", "(", "function", "(", "cb", ")", "{", "if", "(", "Object", ".", "keys", "(", "subscriptions", ")", ".", "indexOf", "(", "message", ".", "destinationName", ")", "!==", "-", "1", ")", "cb", "(", "message", ".", "payloadString", ")", ";", "else", "cb", "(", "message", ".", "payloadString", ",", "message", ".", "destinationName", ")", ";", "}", ")", ";", "}", "}", ";", "// Connect", "client", ".", "connect", "(", "{", "onSuccess", ":", "function", "(", ")", "{", "// Execute optional done callback passing true", "if", "(", "done_cb", "!==", "undefined", ")", "done_cb", "(", "true", ")", ";", "// Execute the backlog of operations performed while the client wasn't connected", "backlog", ".", "forEach", "(", "function", "(", "e", ")", "{", "e", ".", "op", ".", "apply", "(", "this", ",", "e", ".", "params", ")", ";", "}", ")", ";", "}", ",", "onFailure", ":", "function", "(", ")", "{", "// Execute optional done callback passing false", "if", "(", "done_cb", "!==", "undefined", ")", "done_cb", "(", "false", ")", ";", "else", "console", ".", "error", "(", "'There was a problem initializing nutella.'", ")", ";", "}", "}", ")", ";", "return", "client", ";", "}" ]
Helper function that connects the MQTT client in the browser
[ "Helper", "function", "that", "connects", "the", "MQTT", "client", "in", "the", "browser" ]
b3a3406a407e2a1ada6edcc503b70991f9cb249b
https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/simple-mqtt-client/client-browser.js#L43-L93
57,496
nutella-framework/nutella_lib.js
src/simple-mqtt-client/client-browser.js
subscribeBrowser
function subscribeBrowser (client, subscriptions, backlog, channel, callback, done_callback) { if ( addToBacklog(client, backlog, subscribeBrowser, [client, subscriptions, backlog, channel, callback, done_callback]) ) return; if (subscriptions[channel]===undefined) { subscriptions[channel] = [callback]; client.subscribe(channel, {qos: 0, onSuccess: function() { // If there is a done_callback defined, execute it if (done_callback!==undefined) done_callback(); }}); } else { subscriptions[channel].push(callback); // If there is a done_callback defined, execute it if (done_callback!==undefined) done_callback(); } }
javascript
function subscribeBrowser (client, subscriptions, backlog, channel, callback, done_callback) { if ( addToBacklog(client, backlog, subscribeBrowser, [client, subscriptions, backlog, channel, callback, done_callback]) ) return; if (subscriptions[channel]===undefined) { subscriptions[channel] = [callback]; client.subscribe(channel, {qos: 0, onSuccess: function() { // If there is a done_callback defined, execute it if (done_callback!==undefined) done_callback(); }}); } else { subscriptions[channel].push(callback); // If there is a done_callback defined, execute it if (done_callback!==undefined) done_callback(); } }
[ "function", "subscribeBrowser", "(", "client", ",", "subscriptions", ",", "backlog", ",", "channel", ",", "callback", ",", "done_callback", ")", "{", "if", "(", "addToBacklog", "(", "client", ",", "backlog", ",", "subscribeBrowser", ",", "[", "client", ",", "subscriptions", ",", "backlog", ",", "channel", ",", "callback", ",", "done_callback", "]", ")", ")", "return", ";", "if", "(", "subscriptions", "[", "channel", "]", "===", "undefined", ")", "{", "subscriptions", "[", "channel", "]", "=", "[", "callback", "]", ";", "client", ".", "subscribe", "(", "channel", ",", "{", "qos", ":", "0", ",", "onSuccess", ":", "function", "(", ")", "{", "// If there is a done_callback defined, execute it", "if", "(", "done_callback", "!==", "undefined", ")", "done_callback", "(", ")", ";", "}", "}", ")", ";", "}", "else", "{", "subscriptions", "[", "channel", "]", ".", "push", "(", "callback", ")", ";", "// If there is a done_callback defined, execute it", "if", "(", "done_callback", "!==", "undefined", ")", "done_callback", "(", ")", ";", "}", "}" ]
Helper function that subscribes to a channel in the browser
[ "Helper", "function", "that", "subscribes", "to", "a", "channel", "in", "the", "browser" ]
b3a3406a407e2a1ada6edcc503b70991f9cb249b
https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/simple-mqtt-client/client-browser.js#L122-L135
57,497
nutella-framework/nutella_lib.js
src/simple-mqtt-client/client-browser.js
function(client, subscriptions, backlog, channel, callback, done_callback) { if ( addToBacklog(client, backlog, unsubscribeBrowser, [client, subscriptions, backlog, channel, callback, done_callback]) ) return; if (subscriptions[channel]===undefined) return; subscriptions[channel].splice(subscriptions[channel].indexOf(callback), 1); if (subscriptions[channel].length===0) { delete subscriptions[channel]; client.unsubscribe(channel, {onSuccess : function() { // If there is a done_callback defined, execute it if (done_callback!==undefined) done_callback(); }}); } }
javascript
function(client, subscriptions, backlog, channel, callback, done_callback) { if ( addToBacklog(client, backlog, unsubscribeBrowser, [client, subscriptions, backlog, channel, callback, done_callback]) ) return; if (subscriptions[channel]===undefined) return; subscriptions[channel].splice(subscriptions[channel].indexOf(callback), 1); if (subscriptions[channel].length===0) { delete subscriptions[channel]; client.unsubscribe(channel, {onSuccess : function() { // If there is a done_callback defined, execute it if (done_callback!==undefined) done_callback(); }}); } }
[ "function", "(", "client", ",", "subscriptions", ",", "backlog", ",", "channel", ",", "callback", ",", "done_callback", ")", "{", "if", "(", "addToBacklog", "(", "client", ",", "backlog", ",", "unsubscribeBrowser", ",", "[", "client", ",", "subscriptions", ",", "backlog", ",", "channel", ",", "callback", ",", "done_callback", "]", ")", ")", "return", ";", "if", "(", "subscriptions", "[", "channel", "]", "===", "undefined", ")", "return", ";", "subscriptions", "[", "channel", "]", ".", "splice", "(", "subscriptions", "[", "channel", "]", ".", "indexOf", "(", "callback", ")", ",", "1", ")", ";", "if", "(", "subscriptions", "[", "channel", "]", ".", "length", "===", "0", ")", "{", "delete", "subscriptions", "[", "channel", "]", ";", "client", ".", "unsubscribe", "(", "channel", ",", "{", "onSuccess", ":", "function", "(", ")", "{", "// If there is a done_callback defined, execute it", "if", "(", "done_callback", "!==", "undefined", ")", "done_callback", "(", ")", ";", "}", "}", ")", ";", "}", "}" ]
Helper function that unsubscribes from a channel in the browser
[ "Helper", "function", "that", "unsubscribes", "from", "a", "channel", "in", "the", "browser" ]
b3a3406a407e2a1ada6edcc503b70991f9cb249b
https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/simple-mqtt-client/client-browser.js#L156-L168
57,498
nutella-framework/nutella_lib.js
src/simple-mqtt-client/client-browser.js
function (client, backlog, channel, message) { if ( addToBacklog(client, backlog, publishBrowser, [client, backlog, channel, message]) ) return; message = new mqtt_lib.Message(message); message.destinationName = channel; client.send(message); }
javascript
function (client, backlog, channel, message) { if ( addToBacklog(client, backlog, publishBrowser, [client, backlog, channel, message]) ) return; message = new mqtt_lib.Message(message); message.destinationName = channel; client.send(message); }
[ "function", "(", "client", ",", "backlog", ",", "channel", ",", "message", ")", "{", "if", "(", "addToBacklog", "(", "client", ",", "backlog", ",", "publishBrowser", ",", "[", "client", ",", "backlog", ",", "channel", ",", "message", "]", ")", ")", "return", ";", "message", "=", "new", "mqtt_lib", ".", "Message", "(", "message", ")", ";", "message", ".", "destinationName", "=", "channel", ";", "client", ".", "send", "(", "message", ")", ";", "}" ]
Helper function that publishes to a channel in the browser
[ "Helper", "function", "that", "publishes", "to", "a", "channel", "in", "the", "browser" ]
b3a3406a407e2a1ada6edcc503b70991f9cb249b
https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/simple-mqtt-client/client-browser.js#L195-L200
57,499
nutella-framework/nutella_lib.js
src/simple-mqtt-client/client-browser.js
findCallbacks
function findCallbacks (subscriptions, channel) { // First try to see if a callback for the exact channel exists if(Object.keys(subscriptions).indexOf(channel)!==-1) return subscriptions[channel]; // If it doesn't then let's try to see if the channel matches a wildcard callback var pattern = matchesWildcard(subscriptions, channel); if (pattern!== undefined) { return subscriptions[pattern]; } // If there's no exact match or wildcard we have to return undefined return undefined; }
javascript
function findCallbacks (subscriptions, channel) { // First try to see if a callback for the exact channel exists if(Object.keys(subscriptions).indexOf(channel)!==-1) return subscriptions[channel]; // If it doesn't then let's try to see if the channel matches a wildcard callback var pattern = matchesWildcard(subscriptions, channel); if (pattern!== undefined) { return subscriptions[pattern]; } // If there's no exact match or wildcard we have to return undefined return undefined; }
[ "function", "findCallbacks", "(", "subscriptions", ",", "channel", ")", "{", "// First try to see if a callback for the exact channel exists", "if", "(", "Object", ".", "keys", "(", "subscriptions", ")", ".", "indexOf", "(", "channel", ")", "!==", "-", "1", ")", "return", "subscriptions", "[", "channel", "]", ";", "// If it doesn't then let's try to see if the channel matches a wildcard callback", "var", "pattern", "=", "matchesWildcard", "(", "subscriptions", ",", "channel", ")", ";", "if", "(", "pattern", "!==", "undefined", ")", "{", "return", "subscriptions", "[", "pattern", "]", ";", "}", "// If there's no exact match or wildcard we have to return undefined", "return", "undefined", ";", "}" ]
Helper function that selects the right callback when a message is received
[ "Helper", "function", "that", "selects", "the", "right", "callback", "when", "a", "message", "is", "received" ]
b3a3406a407e2a1ada6edcc503b70991f9cb249b
https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/simple-mqtt-client/client-browser.js#L233-L244