id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
19,000
datathings/greycat
plugins/incub/visualizer/old/src/js/demo_vivagraph.js
addLinkToParent
function addLinkToParent(idNode, idParentNode){ g.addLink(idParentNode, idNode, nodesToBeLinked[idNode].name); delete nodesToBeLinked[idNode]; //we remove the node from childrenNodes var index = childrenNodes.indexOf(idNode); if (index > -1) { childrenNodes.splice(index, 1); } }
javascript
function addLinkToParent(idNode, idParentNode){ g.addLink(idParentNode, idNode, nodesToBeLinked[idNode].name); delete nodesToBeLinked[idNode]; //we remove the node from childrenNodes var index = childrenNodes.indexOf(idNode); if (index > -1) { childrenNodes.splice(index, 1); } }
[ "function", "addLinkToParent", "(", "idNode", ",", "idParentNode", ")", "{", "g", ".", "addLink", "(", "idParentNode", ",", "idNode", ",", "nodesToBeLinked", "[", "idNode", "]", ".", "name", ")", ";", "delete", "nodesToBeLinked", "[", "idNode", "]", ";", "//we remove the node from childrenNodes", "var", "index", "=", "childrenNodes", ".", "indexOf", "(", "idNode", ")", ";", "if", "(", "index", ">", "-", "1", ")", "{", "childrenNodes", ".", "splice", "(", "index", ",", "1", ")", ";", "}", "}" ]
Add a link to the graph between the node and its parent @param idNode @param idParentNode
[ "Add", "a", "link", "to", "the", "graph", "between", "the", "node", "and", "its", "parent" ]
602243bdd50e1f869bb19e3ac2991c540ea7af79
https://github.com/datathings/greycat/blob/602243bdd50e1f869bb19e3ac2991c540ea7af79/plugins/incub/visualizer/old/src/js/demo_vivagraph.js#L574-L583
19,001
datathings/greycat
plugins/incub/visualizer/old/src/js/demo_vivagraph.js
toggleLayout
function toggleLayout() { $('.nodeLabel').remove(); isPaused = !isPaused; if (isPaused) { $('#toggleLayout').html('<i class="fa fa-play"></i>Resume layout'); renderer.pause(); } else { $('#toggleLayout').html('<i class="fa fa-pause"></i>Pause layout'); renderer.resume(); } return false; }
javascript
function toggleLayout() { $('.nodeLabel').remove(); isPaused = !isPaused; if (isPaused) { $('#toggleLayout').html('<i class="fa fa-play"></i>Resume layout'); renderer.pause(); } else { $('#toggleLayout').html('<i class="fa fa-pause"></i>Pause layout'); renderer.resume(); } return false; }
[ "function", "toggleLayout", "(", ")", "{", "$", "(", "'.nodeLabel'", ")", ".", "remove", "(", ")", ";", "isPaused", "=", "!", "isPaused", ";", "if", "(", "isPaused", ")", "{", "$", "(", "'#toggleLayout'", ")", ".", "html", "(", "'<i class=\"fa fa-play\"></i>Resume layout'", ")", ";", "renderer", ".", "pause", "(", ")", ";", "}", "else", "{", "$", "(", "'#toggleLayout'", ")", ".", "html", "(", "'<i class=\"fa fa-pause\"></i>Pause layout'", ")", ";", "renderer", ".", "resume", "(", ")", ";", "}", "return", "false", ";", "}" ]
Allows the rendering to be paused or resumed @returns {boolean}
[ "Allows", "the", "rendering", "to", "be", "paused", "or", "resumed" ]
602243bdd50e1f869bb19e3ac2991c540ea7af79
https://github.com/datathings/greycat/blob/602243bdd50e1f869bb19e3ac2991c540ea7af79/plugins/incub/visualizer/old/src/js/demo_vivagraph.js#L589-L600
19,002
datathings/greycat
plugins/incub/benchmark/src/main/resources/static/c3.js
splitTickText
function splitTickText(d, maxWidth) { var tickText = textFormatted(d), subtext, spaceIndex, textWidth, splitted = []; if (Object.prototype.toString.call(tickText) === "[object Array]") { return tickText; } if (!maxWidth || maxWidth <= 0) { maxWidth = isVertical ? 95 : params.isCategory ? (Math.ceil(scale1(ticks[1]) - scale1(ticks[0])) - 12) : 110; } function split(splitted, text) { spaceIndex = undefined; for (var i = 1; i < text.length; i++) { if (text.charAt(i) === ' ') { spaceIndex = i; } subtext = text.substr(0, i + 1); textWidth = sizeFor1Char.w * subtext.length; // if text width gets over tick width, split by space index or crrent index if (maxWidth < textWidth) { return split( splitted.concat(text.substr(0, spaceIndex ? spaceIndex : i)), text.slice(spaceIndex ? spaceIndex + 1 : i) ); } } return splitted.concat(text); } return split(splitted, tickText + ""); }
javascript
function splitTickText(d, maxWidth) { var tickText = textFormatted(d), subtext, spaceIndex, textWidth, splitted = []; if (Object.prototype.toString.call(tickText) === "[object Array]") { return tickText; } if (!maxWidth || maxWidth <= 0) { maxWidth = isVertical ? 95 : params.isCategory ? (Math.ceil(scale1(ticks[1]) - scale1(ticks[0])) - 12) : 110; } function split(splitted, text) { spaceIndex = undefined; for (var i = 1; i < text.length; i++) { if (text.charAt(i) === ' ') { spaceIndex = i; } subtext = text.substr(0, i + 1); textWidth = sizeFor1Char.w * subtext.length; // if text width gets over tick width, split by space index or crrent index if (maxWidth < textWidth) { return split( splitted.concat(text.substr(0, spaceIndex ? spaceIndex : i)), text.slice(spaceIndex ? spaceIndex + 1 : i) ); } } return splitted.concat(text); } return split(splitted, tickText + ""); }
[ "function", "splitTickText", "(", "d", ",", "maxWidth", ")", "{", "var", "tickText", "=", "textFormatted", "(", "d", ")", ",", "subtext", ",", "spaceIndex", ",", "textWidth", ",", "splitted", "=", "[", "]", ";", "if", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "tickText", ")", "===", "\"[object Array]\"", ")", "{", "return", "tickText", ";", "}", "if", "(", "!", "maxWidth", "||", "maxWidth", "<=", "0", ")", "{", "maxWidth", "=", "isVertical", "?", "95", ":", "params", ".", "isCategory", "?", "(", "Math", ".", "ceil", "(", "scale1", "(", "ticks", "[", "1", "]", ")", "-", "scale1", "(", "ticks", "[", "0", "]", ")", ")", "-", "12", ")", ":", "110", ";", "}", "function", "split", "(", "splitted", ",", "text", ")", "{", "spaceIndex", "=", "undefined", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "text", ".", "length", ";", "i", "++", ")", "{", "if", "(", "text", ".", "charAt", "(", "i", ")", "===", "' '", ")", "{", "spaceIndex", "=", "i", ";", "}", "subtext", "=", "text", ".", "substr", "(", "0", ",", "i", "+", "1", ")", ";", "textWidth", "=", "sizeFor1Char", ".", "w", "*", "subtext", ".", "length", ";", "// if text width gets over tick width, split by space index or crrent index", "if", "(", "maxWidth", "<", "textWidth", ")", "{", "return", "split", "(", "splitted", ".", "concat", "(", "text", ".", "substr", "(", "0", ",", "spaceIndex", "?", "spaceIndex", ":", "i", ")", ")", ",", "text", ".", "slice", "(", "spaceIndex", "?", "spaceIndex", "+", "1", ":", "i", ")", ")", ";", "}", "}", "return", "splitted", ".", "concat", "(", "text", ")", ";", "}", "return", "split", "(", "splitted", ",", "tickText", "+", "\"\"", ")", ";", "}" ]
this should be called only when category axis
[ "this", "should", "be", "called", "only", "when", "category", "axis" ]
602243bdd50e1f869bb19e3ac2991c540ea7af79
https://github.com/datathings/greycat/blob/602243bdd50e1f869bb19e3ac2991c540ea7af79/plugins/incub/benchmark/src/main/resources/static/c3.js#L7126-L7158
19,003
datathings/greycat
plugins/incub/visualizer/old/src/js/react_layout.js
createColumnsFromProperties
function createColumnsFromProperties(){ var res = []; for (var i = 0; i < nodeProperties.length; ++i){ var prop = nodeProperties[i]; var obj = { id: prop, name: prop, field: prop }; res.push(obj); } return res; }
javascript
function createColumnsFromProperties(){ var res = []; for (var i = 0; i < nodeProperties.length; ++i){ var prop = nodeProperties[i]; var obj = { id: prop, name: prop, field: prop }; res.push(obj); } return res; }
[ "function", "createColumnsFromProperties", "(", ")", "{", "var", "res", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "nodeProperties", ".", "length", ";", "++", "i", ")", "{", "var", "prop", "=", "nodeProperties", "[", "i", "]", ";", "var", "obj", "=", "{", "id", ":", "prop", ",", "name", ":", "prop", ",", "field", ":", "prop", "}", ";", "res", ".", "push", "(", "obj", ")", ";", "}", "return", "res", ";", "}" ]
Create columns for the slickgrid from the properties of the nodes @returns {Array}
[ "Create", "columns", "for", "the", "slickgrid", "from", "the", "properties", "of", "the", "nodes" ]
602243bdd50e1f869bb19e3ac2991c540ea7af79
https://github.com/datathings/greycat/blob/602243bdd50e1f869bb19e3ac2991c540ea7af79/plugins/incub/visualizer/old/src/js/react_layout.js#L683-L695
19,004
GoogleChromeLabs/imagecapture-polyfill
docs/index.js
gotMedia
function gotMedia(mediaStream) { // Extract video track. videoDevice = mediaStream.getVideoTracks()[0]; log('Using camera', videoDevice.label); const captureDevice = new ImageCapture(videoDevice, mediaStream); interval = setInterval(function () { captureDevice.grabFrame().then(processFrame).catch(error => { err((new Date()).toISOString(), 'Error while grabbing frame:', error); }); captureDevice.takePhoto().then(processPhoto).catch(error => { err((new Date()).toISOString(), 'Error while taking photo:', error); }); }, 300); }
javascript
function gotMedia(mediaStream) { // Extract video track. videoDevice = mediaStream.getVideoTracks()[0]; log('Using camera', videoDevice.label); const captureDevice = new ImageCapture(videoDevice, mediaStream); interval = setInterval(function () { captureDevice.grabFrame().then(processFrame).catch(error => { err((new Date()).toISOString(), 'Error while grabbing frame:', error); }); captureDevice.takePhoto().then(processPhoto).catch(error => { err((new Date()).toISOString(), 'Error while taking photo:', error); }); }, 300); }
[ "function", "gotMedia", "(", "mediaStream", ")", "{", "// Extract video track.", "videoDevice", "=", "mediaStream", ".", "getVideoTracks", "(", ")", "[", "0", "]", ";", "log", "(", "'Using camera'", ",", "videoDevice", ".", "label", ")", ";", "const", "captureDevice", "=", "new", "ImageCapture", "(", "videoDevice", ",", "mediaStream", ")", ";", "interval", "=", "setInterval", "(", "function", "(", ")", "{", "captureDevice", ".", "grabFrame", "(", ")", ".", "then", "(", "processFrame", ")", ".", "catch", "(", "error", "=>", "{", "err", "(", "(", "new", "Date", "(", ")", ")", ".", "toISOString", "(", ")", ",", "'Error while grabbing frame:'", ",", "error", ")", ";", "}", ")", ";", "captureDevice", ".", "takePhoto", "(", ")", ".", "then", "(", "processPhoto", ")", ".", "catch", "(", "error", "=>", "{", "err", "(", "(", "new", "Date", "(", ")", ")", ".", "toISOString", "(", ")", ",", "'Error while taking photo:'", ",", "error", ")", ";", "}", ")", ";", "}", ",", "300", ")", ";", "}" ]
We have a video capture device. Exercise various capturing modes. @param {MediaStream} mediaStream
[ "We", "have", "a", "video", "capture", "device", ".", "Exercise", "various", "capturing", "modes", "." ]
18e7db21ac97d350c9c51f7502d2d0822d8bf2ae
https://github.com/GoogleChromeLabs/imagecapture-polyfill/blob/18e7db21ac97d350c9c51f7502d2d0822d8bf2ae/docs/index.js#L69-L84
19,005
jesseditson/fs-router
index.js
findRoutes
function findRoutes (dir, fileExtensions) { let files = fs.readdirSync(dir) let resolve = f => path.join(dir, f) let routes = files.filter(f => fileExtensions.indexOf(path.extname(f)) !== -1).map(resolve) let dirs = files.filter(f => fs.statSync(path.join(dir, f)).isDirectory()).map(resolve) return routes.concat(...dirs.map(subdir => findRoutes(subdir, fileExtensions))) }
javascript
function findRoutes (dir, fileExtensions) { let files = fs.readdirSync(dir) let resolve = f => path.join(dir, f) let routes = files.filter(f => fileExtensions.indexOf(path.extname(f)) !== -1).map(resolve) let dirs = files.filter(f => fs.statSync(path.join(dir, f)).isDirectory()).map(resolve) return routes.concat(...dirs.map(subdir => findRoutes(subdir, fileExtensions))) }
[ "function", "findRoutes", "(", "dir", ",", "fileExtensions", ")", "{", "let", "files", "=", "fs", ".", "readdirSync", "(", "dir", ")", "let", "resolve", "=", "f", "=>", "path", ".", "join", "(", "dir", ",", "f", ")", "let", "routes", "=", "files", ".", "filter", "(", "f", "=>", "fileExtensions", ".", "indexOf", "(", "path", ".", "extname", "(", "f", ")", ")", "!==", "-", "1", ")", ".", "map", "(", "resolve", ")", "let", "dirs", "=", "files", ".", "filter", "(", "f", "=>", "fs", ".", "statSync", "(", "path", ".", "join", "(", "dir", ",", "f", ")", ")", ".", "isDirectory", "(", ")", ")", ".", "map", "(", "resolve", ")", "return", "routes", ".", "concat", "(", "...", "dirs", ".", "map", "(", "subdir", "=>", "findRoutes", "(", "subdir", ",", "fileExtensions", ")", ")", ")", "}" ]
recursively searches for all js files inside a directory tree, and returns their full paths
[ "recursively", "searches", "for", "all", "js", "files", "inside", "a", "directory", "tree", "and", "returns", "their", "full", "paths" ]
5f174888ce578908713a6b8b490d4c5b24997296
https://github.com/jesseditson/fs-router/blob/5f174888ce578908713a6b8b490d4c5b24997296/index.js#L41-L47
19,006
ysmood/yaku
src/yaku.aplus.js
scheduleHandler
function scheduleHandler (p1, p2) { return setTimeout(function () { var x, handler = p1._s ? p2._onFulfilled : p2._onRejected; // 2.2.7.3 // 2.2.7.4 if (handler === void 0) { settlePromise(p2, p1._s, p1._v); return; } try { // 2.2.5 x = handler(p1._v); } catch (err) { // 2.2.7.2 settlePromise(p2, $rejected, err); return; } // 2.2.7.1 settleWithX(p2, x); }); }
javascript
function scheduleHandler (p1, p2) { return setTimeout(function () { var x, handler = p1._s ? p2._onFulfilled : p2._onRejected; // 2.2.7.3 // 2.2.7.4 if (handler === void 0) { settlePromise(p2, p1._s, p1._v); return; } try { // 2.2.5 x = handler(p1._v); } catch (err) { // 2.2.7.2 settlePromise(p2, $rejected, err); return; } // 2.2.7.1 settleWithX(p2, x); }); }
[ "function", "scheduleHandler", "(", "p1", ",", "p2", ")", "{", "return", "setTimeout", "(", "function", "(", ")", "{", "var", "x", ",", "handler", "=", "p1", ".", "_s", "?", "p2", ".", "_onFulfilled", ":", "p2", ".", "_onRejected", ";", "// 2.2.7.3", "// 2.2.7.4", "if", "(", "handler", "===", "void", "0", ")", "{", "settlePromise", "(", "p2", ",", "p1", ".", "_s", ",", "p1", ".", "_v", ")", ";", "return", ";", "}", "try", "{", "// 2.2.5", "x", "=", "handler", "(", "p1", ".", "_v", ")", ";", "}", "catch", "(", "err", ")", "{", "// 2.2.7.2", "settlePromise", "(", "p2", ",", "$rejected", ",", "err", ")", ";", "return", ";", "}", "// 2.2.7.1", "settleWithX", "(", "p2", ",", "x", ")", ";", "}", ")", ";", "}" ]
Resolve the value returned by onFulfilled or onRejected. @private @param {Yaku} p1 @param {Yaku} p2
[ "Resolve", "the", "value", "returned", "by", "onFulfilled", "or", "onRejected", "." ]
f0fb064d23dfada832751832800f2199de566e22
https://github.com/ysmood/yaku/blob/f0fb064d23dfada832751832800f2199de566e22/src/yaku.aplus.js#L116-L139
19,007
ysmood/yaku
src/yaku.aplus.js
settleWithX
function settleWithX (p, x) { // 2.3.1 if (x === p && x) { settlePromise(p, $rejected, new TypeError('promise_circular_chain')); return; } // 2.3.2 // 2.3.3 var xthen, type = typeof x; if (x !== null && (type === 'function' || type === 'object')) { try { // 2.3.2.1 xthen = x.then; } catch (err) { // 2.3.3.2 settlePromise(p, $rejected, err); return; } if (typeof xthen === 'function') { settleXthen(p, x, xthen); } else { // 2.3.3.4 settlePromise(p, $resolved, x); } } else { // 2.3.4 settlePromise(p, $resolved, x); } return p; }
javascript
function settleWithX (p, x) { // 2.3.1 if (x === p && x) { settlePromise(p, $rejected, new TypeError('promise_circular_chain')); return; } // 2.3.2 // 2.3.3 var xthen, type = typeof x; if (x !== null && (type === 'function' || type === 'object')) { try { // 2.3.2.1 xthen = x.then; } catch (err) { // 2.3.3.2 settlePromise(p, $rejected, err); return; } if (typeof xthen === 'function') { settleXthen(p, x, xthen); } else { // 2.3.3.4 settlePromise(p, $resolved, x); } } else { // 2.3.4 settlePromise(p, $resolved, x); } return p; }
[ "function", "settleWithX", "(", "p", ",", "x", ")", "{", "// 2.3.1", "if", "(", "x", "===", "p", "&&", "x", ")", "{", "settlePromise", "(", "p", ",", "$rejected", ",", "new", "TypeError", "(", "'promise_circular_chain'", ")", ")", ";", "return", ";", "}", "// 2.3.2", "// 2.3.3", "var", "xthen", ",", "type", "=", "typeof", "x", ";", "if", "(", "x", "!==", "null", "&&", "(", "type", "===", "'function'", "||", "type", "===", "'object'", ")", ")", "{", "try", "{", "// 2.3.2.1", "xthen", "=", "x", ".", "then", ";", "}", "catch", "(", "err", ")", "{", "// 2.3.3.2", "settlePromise", "(", "p", ",", "$rejected", ",", "err", ")", ";", "return", ";", "}", "if", "(", "typeof", "xthen", "===", "'function'", ")", "{", "settleXthen", "(", "p", ",", "x", ",", "xthen", ")", ";", "}", "else", "{", "// 2.3.3.4", "settlePromise", "(", "p", ",", "$resolved", ",", "x", ")", ";", "}", "}", "else", "{", "// 2.3.4", "settlePromise", "(", "p", ",", "$resolved", ",", "x", ")", ";", "}", "return", "p", ";", "}" ]
Resolve or reject primise with value x. The x can also be a thenable. @private @param {Yaku} p @param {Any | Thenable} x A normal value or a thenable.
[ "Resolve", "or", "reject", "primise", "with", "value", "x", ".", "The", "x", "can", "also", "be", "a", "thenable", "." ]
f0fb064d23dfada832751832800f2199de566e22
https://github.com/ysmood/yaku/blob/f0fb064d23dfada832751832800f2199de566e22/src/yaku.aplus.js#L177-L207
19,008
ysmood/yaku
src/Observable.js
function (onNext, onError) { var self = this, subscriber = new Observable(); subscriber._onNext = onNext; subscriber._onError = onError; subscriber._nextErr = genNextErr(subscriber.next); subscriber.publisher = self; self.subscribers.push(subscriber); return subscriber; }
javascript
function (onNext, onError) { var self = this, subscriber = new Observable(); subscriber._onNext = onNext; subscriber._onError = onError; subscriber._nextErr = genNextErr(subscriber.next); subscriber.publisher = self; self.subscribers.push(subscriber); return subscriber; }
[ "function", "(", "onNext", ",", "onError", ")", "{", "var", "self", "=", "this", ",", "subscriber", "=", "new", "Observable", "(", ")", ";", "subscriber", ".", "_onNext", "=", "onNext", ";", "subscriber", ".", "_onError", "=", "onError", ";", "subscriber", ".", "_nextErr", "=", "genNextErr", "(", "subscriber", ".", "next", ")", ";", "subscriber", ".", "publisher", "=", "self", ";", "self", ".", "subscribers", ".", "push", "(", "subscriber", ")", ";", "return", "subscriber", ";", "}" ]
It will create a new Observable, like promise. @param {Function} onNext @param {Function} onError @return {Observable}
[ "It", "will", "create", "a", "new", "Observable", "like", "promise", "." ]
f0fb064d23dfada832751832800f2199de566e22
https://github.com/ysmood/yaku/blob/f0fb064d23dfada832751832800f2199de566e22/src/Observable.js#L103-L113
19,009
ysmood/yaku
src/yaku.core.js
genScheduler
function genScheduler (initQueueSize, fn) { /** * All async promise will be scheduled in * here, so that they can be execute on the next tick. * @private */ var fnQueue = Arr(initQueueSize) , fnQueueLen = 0; /** * Run all queued functions. * @private */ function flush () { var i = 0; while (i < fnQueueLen) { fn(fnQueue[i], fnQueue[i + 1]); fnQueue[i++] = $undefined; fnQueue[i++] = $undefined; } fnQueueLen = 0; if (fnQueue.length > initQueueSize) fnQueue.length = initQueueSize; } return function (v, arg) { fnQueue[fnQueueLen++] = v; fnQueue[fnQueueLen++] = arg; if (fnQueueLen === 2) nextTick(flush); }; }
javascript
function genScheduler (initQueueSize, fn) { /** * All async promise will be scheduled in * here, so that they can be execute on the next tick. * @private */ var fnQueue = Arr(initQueueSize) , fnQueueLen = 0; /** * Run all queued functions. * @private */ function flush () { var i = 0; while (i < fnQueueLen) { fn(fnQueue[i], fnQueue[i + 1]); fnQueue[i++] = $undefined; fnQueue[i++] = $undefined; } fnQueueLen = 0; if (fnQueue.length > initQueueSize) fnQueue.length = initQueueSize; } return function (v, arg) { fnQueue[fnQueueLen++] = v; fnQueue[fnQueueLen++] = arg; if (fnQueueLen === 2) nextTick(flush); }; }
[ "function", "genScheduler", "(", "initQueueSize", ",", "fn", ")", "{", "/**\n * All async promise will be scheduled in\n * here, so that they can be execute on the next tick.\n * @private\n */", "var", "fnQueue", "=", "Arr", "(", "initQueueSize", ")", ",", "fnQueueLen", "=", "0", ";", "/**\n * Run all queued functions.\n * @private\n */", "function", "flush", "(", ")", "{", "var", "i", "=", "0", ";", "while", "(", "i", "<", "fnQueueLen", ")", "{", "fn", "(", "fnQueue", "[", "i", "]", ",", "fnQueue", "[", "i", "+", "1", "]", ")", ";", "fnQueue", "[", "i", "++", "]", "=", "$undefined", ";", "fnQueue", "[", "i", "++", "]", "=", "$undefined", ";", "}", "fnQueueLen", "=", "0", ";", "if", "(", "fnQueue", ".", "length", ">", "initQueueSize", ")", "fnQueue", ".", "length", "=", "initQueueSize", ";", "}", "return", "function", "(", "v", ",", "arg", ")", "{", "fnQueue", "[", "fnQueueLen", "++", "]", "=", "v", ";", "fnQueue", "[", "fnQueueLen", "++", "]", "=", "arg", ";", "if", "(", "fnQueueLen", "===", "2", ")", "nextTick", "(", "flush", ")", ";", "}", ";", "}" ]
Generate a scheduler. @private @param {Integer} initQueueSize @param {Function} fn `(Yaku, Value) ->` The schedule handler. @return {Function} `(Yaku, Value) ->` The scheduler.
[ "Generate", "a", "scheduler", "." ]
f0fb064d23dfada832751832800f2199de566e22
https://github.com/ysmood/yaku/blob/f0fb064d23dfada832751832800f2199de566e22/src/yaku.core.js#L389-L420
19,010
ysmood/yaku
src/yaku.core.js
flush
function flush () { var i = 0; while (i < fnQueueLen) { fn(fnQueue[i], fnQueue[i + 1]); fnQueue[i++] = $undefined; fnQueue[i++] = $undefined; } fnQueueLen = 0; if (fnQueue.length > initQueueSize) fnQueue.length = initQueueSize; }
javascript
function flush () { var i = 0; while (i < fnQueueLen) { fn(fnQueue[i], fnQueue[i + 1]); fnQueue[i++] = $undefined; fnQueue[i++] = $undefined; } fnQueueLen = 0; if (fnQueue.length > initQueueSize) fnQueue.length = initQueueSize; }
[ "function", "flush", "(", ")", "{", "var", "i", "=", "0", ";", "while", "(", "i", "<", "fnQueueLen", ")", "{", "fn", "(", "fnQueue", "[", "i", "]", ",", "fnQueue", "[", "i", "+", "1", "]", ")", ";", "fnQueue", "[", "i", "++", "]", "=", "$undefined", ";", "fnQueue", "[", "i", "++", "]", "=", "$undefined", ";", "}", "fnQueueLen", "=", "0", ";", "if", "(", "fnQueue", ".", "length", ">", "initQueueSize", ")", "fnQueue", ".", "length", "=", "initQueueSize", ";", "}" ]
Run all queued functions. @private
[ "Run", "all", "queued", "functions", "." ]
f0fb064d23dfada832751832800f2199de566e22
https://github.com/ysmood/yaku/blob/f0fb064d23dfada832751832800f2199de566e22/src/yaku.core.js#L402-L412
19,011
ysmood/yaku
src/yaku.core.js
settleWithX
function settleWithX (p, x) { // 2.3.1 if (x === p && x) { settlePromise(p, $rejected, genTypeError($promiseCircularChain)); return p; } // 2.3.2 // 2.3.3 if (x !== $null && (isFunction(x) || isObject(x))) { // 2.3.2.1 var xthen = genTryCatcher(getThen)(x); if (xthen === $tryErr) { // 2.3.3.2 settlePromise(p, $rejected, xthen.e); return p; } if (isFunction(xthen)) { // Fix https://bugs.chromium.org/p/v8/issues/detail?id=4162 if (isYaku(x)) settleXthen(p, x, xthen); else nextTick(function () { settleXthen(p, x, xthen); }); } else // 2.3.3.4 settlePromise(p, $resolved, x); } else // 2.3.4 settlePromise(p, $resolved, x); return p; }
javascript
function settleWithX (p, x) { // 2.3.1 if (x === p && x) { settlePromise(p, $rejected, genTypeError($promiseCircularChain)); return p; } // 2.3.2 // 2.3.3 if (x !== $null && (isFunction(x) || isObject(x))) { // 2.3.2.1 var xthen = genTryCatcher(getThen)(x); if (xthen === $tryErr) { // 2.3.3.2 settlePromise(p, $rejected, xthen.e); return p; } if (isFunction(xthen)) { // Fix https://bugs.chromium.org/p/v8/issues/detail?id=4162 if (isYaku(x)) settleXthen(p, x, xthen); else nextTick(function () { settleXthen(p, x, xthen); }); } else // 2.3.3.4 settlePromise(p, $resolved, x); } else // 2.3.4 settlePromise(p, $resolved, x); return p; }
[ "function", "settleWithX", "(", "p", ",", "x", ")", "{", "// 2.3.1", "if", "(", "x", "===", "p", "&&", "x", ")", "{", "settlePromise", "(", "p", ",", "$rejected", ",", "genTypeError", "(", "$promiseCircularChain", ")", ")", ";", "return", "p", ";", "}", "// 2.3.2", "// 2.3.3", "if", "(", "x", "!==", "$null", "&&", "(", "isFunction", "(", "x", ")", "||", "isObject", "(", "x", ")", ")", ")", "{", "// 2.3.2.1", "var", "xthen", "=", "genTryCatcher", "(", "getThen", ")", "(", "x", ")", ";", "if", "(", "xthen", "===", "$tryErr", ")", "{", "// 2.3.3.2", "settlePromise", "(", "p", ",", "$rejected", ",", "xthen", ".", "e", ")", ";", "return", "p", ";", "}", "if", "(", "isFunction", "(", "xthen", ")", ")", "{", "// Fix https://bugs.chromium.org/p/v8/issues/detail?id=4162", "if", "(", "isYaku", "(", "x", ")", ")", "settleXthen", "(", "p", ",", "x", ",", "xthen", ")", ";", "else", "nextTick", "(", "function", "(", ")", "{", "settleXthen", "(", "p", ",", "x", ",", "xthen", ")", ";", "}", ")", ";", "}", "else", "// 2.3.3.4", "settlePromise", "(", "p", ",", "$resolved", ",", "x", ")", ";", "}", "else", "// 2.3.4", "settlePromise", "(", "p", ",", "$resolved", ",", "x", ")", ";", "return", "p", ";", "}" ]
Resolve or reject promise with value x. The x can also be a thenable. @private @param {Yaku} p @param {Any | Thenable} x A normal value or a thenable.
[ "Resolve", "or", "reject", "promise", "with", "value", "x", ".", "The", "x", "can", "also", "be", "a", "thenable", "." ]
f0fb064d23dfada832751832800f2199de566e22
https://github.com/ysmood/yaku/blob/f0fb064d23dfada832751832800f2199de566e22/src/yaku.core.js#L653-L688
19,012
uploadcare/uploadcare-widget
scripts/serve.js
saveUrl
function saveUrl(url) { fs.writeFile('serve-url.log', url, error => { if (error) { return console.log(error) } console.log('serve-url.log updated!') }) }
javascript
function saveUrl(url) { fs.writeFile('serve-url.log', url, error => { if (error) { return console.log(error) } console.log('serve-url.log updated!') }) }
[ "function", "saveUrl", "(", "url", ")", "{", "fs", ".", "writeFile", "(", "'serve-url.log'", ",", "url", ",", "error", "=>", "{", "if", "(", "error", ")", "{", "return", "console", ".", "log", "(", "error", ")", "}", "console", ".", "log", "(", "'serve-url.log updated!'", ")", "}", ")", "}" ]
Save url generated by ngrok to file @param url
[ "Save", "url", "generated", "by", "ngrok", "to", "file" ]
19f9d6424df2b94e83c088e33a155d87dc06ea0a
https://github.com/uploadcare/uploadcare-widget/blob/19f9d6424df2b94e83c088e33a155d87dc06ea0a/scripts/serve.js#L18-L26
19,013
uploadcare/uploadcare-widget
app/assets/javascripts/uploadcare/vendor/pusher.js
connectionDelay
function connectionDelay() { var delay = self.connectionWait; if (delay === 0) { if (self.connectedAt) { var t = 1000; var connectedFor = new Date().getTime() - self.connectedAt; if (connectedFor < t) { delay = t - connectedFor; } } } return delay; }
javascript
function connectionDelay() { var delay = self.connectionWait; if (delay === 0) { if (self.connectedAt) { var t = 1000; var connectedFor = new Date().getTime() - self.connectedAt; if (connectedFor < t) { delay = t - connectedFor; } } } return delay; }
[ "function", "connectionDelay", "(", ")", "{", "var", "delay", "=", "self", ".", "connectionWait", ";", "if", "(", "delay", "===", "0", ")", "{", "if", "(", "self", ".", "connectedAt", ")", "{", "var", "t", "=", "1000", ";", "var", "connectedFor", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", "-", "self", ".", "connectedAt", ";", "if", "(", "connectedFor", "<", "t", ")", "{", "delay", "=", "t", "-", "connectedFor", ";", "}", "}", "}", "return", "delay", ";", "}" ]
Returns the delay before the next connection attempt should be made This function guards against attempting to connect more frequently than once every second
[ "Returns", "the", "delay", "before", "the", "next", "connection", "attempt", "should", "be", "made", "This", "function", "guards", "against", "attempting", "to", "connect", "more", "frequently", "than", "once", "every", "second" ]
19f9d6424df2b94e83c088e33a155d87dc06ea0a
https://github.com/uploadcare/uploadcare-widget/blob/19f9d6424df2b94e83c088e33a155d87dc06ea0a/app/assets/javascripts/uploadcare/vendor/pusher.js#L710-L722
19,014
uploadcare/uploadcare-widget
app/assets/javascripts/uploadcare/vendor/pusher.js
parseWebSocketEvent
function parseWebSocketEvent(event) { try { var params = JSON.parse(event.data); if (typeof params.data === 'string') { try { params.data = JSON.parse(params.data); } catch (e) { if (!(e instanceof SyntaxError)) { throw e; } } } return params; } catch (e) { self.emit('error', {type: 'MessageParseError', error: e, data: event.data}); } }
javascript
function parseWebSocketEvent(event) { try { var params = JSON.parse(event.data); if (typeof params.data === 'string') { try { params.data = JSON.parse(params.data); } catch (e) { if (!(e instanceof SyntaxError)) { throw e; } } } return params; } catch (e) { self.emit('error', {type: 'MessageParseError', error: e, data: event.data}); } }
[ "function", "parseWebSocketEvent", "(", "event", ")", "{", "try", "{", "var", "params", "=", "JSON", ".", "parse", "(", "event", ".", "data", ")", ";", "if", "(", "typeof", "params", ".", "data", "===", "'string'", ")", "{", "try", "{", "params", ".", "data", "=", "JSON", ".", "parse", "(", "params", ".", "data", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "!", "(", "e", "instanceof", "SyntaxError", ")", ")", "{", "throw", "e", ";", "}", "}", "}", "return", "params", ";", "}", "catch", "(", "e", ")", "{", "self", ".", "emit", "(", "'error'", ",", "{", "type", ":", "'MessageParseError'", ",", "error", ":", "e", ",", "data", ":", "event", ".", "data", "}", ")", ";", "}", "}" ]
Parses an event from the WebSocket to get the JSON payload that we require @param {MessageEvent} event The event from the WebSocket.onmessage handler.
[ "Parses", "an", "event", "from", "the", "WebSocket", "to", "get", "the", "JSON", "payload", "that", "we", "require" ]
19f9d6424df2b94e83c088e33a155d87dc06ea0a
https://github.com/uploadcare/uploadcare-widget/blob/19f9d6424df2b94e83c088e33a155d87dc06ea0a/app/assets/javascripts/uploadcare/vendor/pusher.js#L798-L816
19,015
uploadcare/uploadcare-widget
app/assets/javascripts/uploadcare/vendor/pusher.js
updateState
function updateState(newState, data) { var prevState = self.state; self.state = newState; // Only emit when the state changes if (prevState !== newState) { Pusher.debug('State changed', prevState + ' -> ' + newState); self.emit('state_change', {previous: prevState, current: newState}); self.emit(newState, data); } }
javascript
function updateState(newState, data) { var prevState = self.state; self.state = newState; // Only emit when the state changes if (prevState !== newState) { Pusher.debug('State changed', prevState + ' -> ' + newState); self.emit('state_change', {previous: prevState, current: newState}); self.emit(newState, data); } }
[ "function", "updateState", "(", "newState", ",", "data", ")", "{", "var", "prevState", "=", "self", ".", "state", ";", "self", ".", "state", "=", "newState", ";", "// Only emit when the state changes", "if", "(", "prevState", "!==", "newState", ")", "{", "Pusher", ".", "debug", "(", "'State changed'", ",", "prevState", "+", "' -> '", "+", "newState", ")", ";", "self", ".", "emit", "(", "'state_change'", ",", "{", "previous", ":", "prevState", ",", "current", ":", "newState", "}", ")", ";", "self", ".", "emit", "(", "newState", ",", "data", ")", ";", "}", "}" ]
Updates the public state information exposed by connection This is distinct from the internal state information used by _machine to manage the connection
[ "Updates", "the", "public", "state", "information", "exposed", "by", "connection", "This", "is", "distinct", "from", "the", "internal", "state", "information", "used", "by", "_machine", "to", "manage", "the", "connection" ]
19f9d6424df2b94e83c088e33a155d87dc06ea0a
https://github.com/uploadcare/uploadcare-widget/blob/19f9d6424df2b94e83c088e33a155d87dc06ea0a/app/assets/javascripts/uploadcare/vendor/pusher.js#L832-L842
19,016
TooTallNate/node-spotify-web
lib/spotify.js
Spotify
function Spotify () { if (!(this instanceof Spotify)) return new Spotify(); EventEmitter.call(this); this.seq = 0; this.heartbeatInterval = 18E4; // 180s, from "spotify.web.client.js" this.agent = superagent.agent(); this.connected = false; // true after the WebSocket "connect" message is sent this._callbacks = Object.create(null); this.authServer = 'play.spotify.com'; this.authUrl = '/xhr/json/auth.php'; this.landingUrl = '/'; this.userAgent = 'Mozilla/5.0 (Chrome/13.37 compatible-ish) spotify-web/' + pkg.version; // base URLs for Image files like album artwork, artist prfiles, etc. // these values taken from "spotify.web.client.js" this.sourceUrl = 'https://d3rt1990lpmkn.cloudfront.net'; this.sourceUrls = { tiny: this.sourceUrl + '/60/', small: this.sourceUrl + '/120/', normal: this.sourceUrl + '/300/', large: this.sourceUrl + '/640/', avatar: this.sourceUrl + '/artist_image/' }; // mappings for the protobuf `enum Size` this.sourceUrls.DEFAULT = this.sourceUrls.normal; this.sourceUrls.SMALL = this.sourceUrls.tiny; this.sourceUrls.LARGE = this.sourceUrls.large; this.sourceUrls.XLARGE = this.sourceUrls.avatar; // WebSocket callbacks this._onopen = this._onopen.bind(this); this._onclose = this._onclose.bind(this); this._onmessage = this._onmessage.bind(this); // start the "heartbeat" once the WebSocket connection is established this.once('connect', this._startHeartbeat); // handle "message" commands... this.on('message', this._onmessagecommand); // needs to emulate Spotify's "CodeValidator" object this._context = vm.createContext(); this._context.reply = this._reply.bind(this); // binded callback for when user doesn't pass a callback function this._defaultCallback = this._defaultCallback.bind(this); }
javascript
function Spotify () { if (!(this instanceof Spotify)) return new Spotify(); EventEmitter.call(this); this.seq = 0; this.heartbeatInterval = 18E4; // 180s, from "spotify.web.client.js" this.agent = superagent.agent(); this.connected = false; // true after the WebSocket "connect" message is sent this._callbacks = Object.create(null); this.authServer = 'play.spotify.com'; this.authUrl = '/xhr/json/auth.php'; this.landingUrl = '/'; this.userAgent = 'Mozilla/5.0 (Chrome/13.37 compatible-ish) spotify-web/' + pkg.version; // base URLs for Image files like album artwork, artist prfiles, etc. // these values taken from "spotify.web.client.js" this.sourceUrl = 'https://d3rt1990lpmkn.cloudfront.net'; this.sourceUrls = { tiny: this.sourceUrl + '/60/', small: this.sourceUrl + '/120/', normal: this.sourceUrl + '/300/', large: this.sourceUrl + '/640/', avatar: this.sourceUrl + '/artist_image/' }; // mappings for the protobuf `enum Size` this.sourceUrls.DEFAULT = this.sourceUrls.normal; this.sourceUrls.SMALL = this.sourceUrls.tiny; this.sourceUrls.LARGE = this.sourceUrls.large; this.sourceUrls.XLARGE = this.sourceUrls.avatar; // WebSocket callbacks this._onopen = this._onopen.bind(this); this._onclose = this._onclose.bind(this); this._onmessage = this._onmessage.bind(this); // start the "heartbeat" once the WebSocket connection is established this.once('connect', this._startHeartbeat); // handle "message" commands... this.on('message', this._onmessagecommand); // needs to emulate Spotify's "CodeValidator" object this._context = vm.createContext(); this._context.reply = this._reply.bind(this); // binded callback for when user doesn't pass a callback function this._defaultCallback = this._defaultCallback.bind(this); }
[ "function", "Spotify", "(", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Spotify", ")", ")", "return", "new", "Spotify", "(", ")", ";", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "seq", "=", "0", ";", "this", ".", "heartbeatInterval", "=", "18E4", ";", "// 180s, from \"spotify.web.client.js\"", "this", ".", "agent", "=", "superagent", ".", "agent", "(", ")", ";", "this", ".", "connected", "=", "false", ";", "// true after the WebSocket \"connect\" message is sent", "this", ".", "_callbacks", "=", "Object", ".", "create", "(", "null", ")", ";", "this", ".", "authServer", "=", "'play.spotify.com'", ";", "this", ".", "authUrl", "=", "'/xhr/json/auth.php'", ";", "this", ".", "landingUrl", "=", "'/'", ";", "this", ".", "userAgent", "=", "'Mozilla/5.0 (Chrome/13.37 compatible-ish) spotify-web/'", "+", "pkg", ".", "version", ";", "// base URLs for Image files like album artwork, artist prfiles, etc.", "// these values taken from \"spotify.web.client.js\"", "this", ".", "sourceUrl", "=", "'https://d3rt1990lpmkn.cloudfront.net'", ";", "this", ".", "sourceUrls", "=", "{", "tiny", ":", "this", ".", "sourceUrl", "+", "'/60/'", ",", "small", ":", "this", ".", "sourceUrl", "+", "'/120/'", ",", "normal", ":", "this", ".", "sourceUrl", "+", "'/300/'", ",", "large", ":", "this", ".", "sourceUrl", "+", "'/640/'", ",", "avatar", ":", "this", ".", "sourceUrl", "+", "'/artist_image/'", "}", ";", "// mappings for the protobuf `enum Size`", "this", ".", "sourceUrls", ".", "DEFAULT", "=", "this", ".", "sourceUrls", ".", "normal", ";", "this", ".", "sourceUrls", ".", "SMALL", "=", "this", ".", "sourceUrls", ".", "tiny", ";", "this", ".", "sourceUrls", ".", "LARGE", "=", "this", ".", "sourceUrls", ".", "large", ";", "this", ".", "sourceUrls", ".", "XLARGE", "=", "this", ".", "sourceUrls", ".", "avatar", ";", "// WebSocket callbacks", "this", ".", "_onopen", "=", "this", ".", "_onopen", ".", "bind", "(", "this", ")", ";", "this", ".", "_onclose", "=", "this", ".", "_onclose", ".", "bind", "(", "this", ")", ";", "this", ".", "_onmessage", "=", "this", ".", "_onmessage", ".", "bind", "(", "this", ")", ";", "// start the \"heartbeat\" once the WebSocket connection is established", "this", ".", "once", "(", "'connect'", ",", "this", ".", "_startHeartbeat", ")", ";", "// handle \"message\" commands...", "this", ".", "on", "(", "'message'", ",", "this", ".", "_onmessagecommand", ")", ";", "// needs to emulate Spotify's \"CodeValidator\" object", "this", ".", "_context", "=", "vm", ".", "createContext", "(", ")", ";", "this", ".", "_context", ".", "reply", "=", "this", ".", "_reply", ".", "bind", "(", "this", ")", ";", "// binded callback for when user doesn't pass a callback function", "this", ".", "_defaultCallback", "=", "this", ".", "_defaultCallback", ".", "bind", "(", "this", ")", ";", "}" ]
Spotify Web base class. @api public
[ "Spotify", "Web", "base", "class", "." ]
9ace59c486d32f194bb01fb578b2f0ddfabbe9a9
https://github.com/TooTallNate/node-spotify-web/blob/9ace59c486d32f194bb01fb578b2f0ddfabbe9a9/lib/spotify.js#L76-L125
19,017
TooTallNate/node-spotify-web
lib/spotify.js
function(schema, dontRecurse) { if ('string' === typeof schema) { var schemaName = schema.split("#"); schema = schemas.build(schemaName[0], schemaName[1]); if (!schema) throw new Error('Could not load schema: ' + schemaName.join('#')); } else if (schema && !dontRecurse && (!schema.hasOwnProperty('parse') && !schema.hasOwnProperty('serialize'))) { var keys = Object.keys(schema); keys.forEach(function(key) { schema[key] = loadSchema(schema[key], true); }); } return schema; }
javascript
function(schema, dontRecurse) { if ('string' === typeof schema) { var schemaName = schema.split("#"); schema = schemas.build(schemaName[0], schemaName[1]); if (!schema) throw new Error('Could not load schema: ' + schemaName.join('#')); } else if (schema && !dontRecurse && (!schema.hasOwnProperty('parse') && !schema.hasOwnProperty('serialize'))) { var keys = Object.keys(schema); keys.forEach(function(key) { schema[key] = loadSchema(schema[key], true); }); } return schema; }
[ "function", "(", "schema", ",", "dontRecurse", ")", "{", "if", "(", "'string'", "===", "typeof", "schema", ")", "{", "var", "schemaName", "=", "schema", ".", "split", "(", "\"#\"", ")", ";", "schema", "=", "schemas", ".", "build", "(", "schemaName", "[", "0", "]", ",", "schemaName", "[", "1", "]", ")", ";", "if", "(", "!", "schema", ")", "throw", "new", "Error", "(", "'Could not load schema: '", "+", "schemaName", ".", "join", "(", "'#'", ")", ")", ";", "}", "else", "if", "(", "schema", "&&", "!", "dontRecurse", "&&", "(", "!", "schema", ".", "hasOwnProperty", "(", "'parse'", ")", "&&", "!", "schema", ".", "hasOwnProperty", "(", "'serialize'", ")", ")", ")", "{", "var", "keys", "=", "Object", ".", "keys", "(", "schema", ")", ";", "keys", ".", "forEach", "(", "function", "(", "key", ")", "{", "schema", "[", "key", "]", "=", "loadSchema", "(", "schema", "[", "key", "]", ",", "true", ")", ";", "}", ")", ";", "}", "return", "schema", ";", "}" ]
load payload and response schemas
[ "load", "payload", "and", "response", "schemas" ]
9ace59c486d32f194bb01fb578b2f0ddfabbe9a9
https://github.com/TooTallNate/node-spotify-web/blob/9ace59c486d32f194bb01fb578b2f0ddfabbe9a9/lib/spotify.js#L553-L566
19,018
TooTallNate/node-spotify-web
lib/error.js
SpotifyError
function SpotifyError (err) { this.domain = err[0] || 0; this.code = err[1] || 0; this.description = err[2] || ''; this.data = err[3] || null; // Error impl this.name = domains[this.domain]; var msg = codes[this.code]; if (this.description) msg += ' (' + this.description + ')'; this.message = msg; Error.captureStackTrace(this, SpotifyError); }
javascript
function SpotifyError (err) { this.domain = err[0] || 0; this.code = err[1] || 0; this.description = err[2] || ''; this.data = err[3] || null; // Error impl this.name = domains[this.domain]; var msg = codes[this.code]; if (this.description) msg += ' (' + this.description + ')'; this.message = msg; Error.captureStackTrace(this, SpotifyError); }
[ "function", "SpotifyError", "(", "err", ")", "{", "this", ".", "domain", "=", "err", "[", "0", "]", "||", "0", ";", "this", ".", "code", "=", "err", "[", "1", "]", "||", "0", ";", "this", ".", "description", "=", "err", "[", "2", "]", "||", "''", ";", "this", ".", "data", "=", "err", "[", "3", "]", "||", "null", ";", "// Error impl", "this", ".", "name", "=", "domains", "[", "this", ".", "domain", "]", ";", "var", "msg", "=", "codes", "[", "this", ".", "code", "]", ";", "if", "(", "this", ".", "description", ")", "msg", "+=", "' ('", "+", "this", ".", "description", "+", "')'", ";", "this", ".", "message", "=", "msg", ";", "Error", ".", "captureStackTrace", "(", "this", ",", "SpotifyError", ")", ";", "}" ]
Spotify error class. Sample `err` objects: [ 11, 1, 'Invalid user' ] [ 12, 8, '' ] [ 14, 408, '' ] [ 14, 429, '' ]
[ "Spotify", "error", "class", "." ]
9ace59c486d32f194bb01fb578b2f0ddfabbe9a9
https://github.com/TooTallNate/node-spotify-web/blob/9ace59c486d32f194bb01fb578b2f0ddfabbe9a9/lib/error.js#L48-L60
19,019
MazeMap/Leaflet.TileLayer.PouchDBCached
L.TileLayer.PouchDBCached.js
function(coords, done) { var tile = document.createElement("img"); tile.onerror = L.bind(this._tileOnError, this, done, tile); if (this.options.crossOrigin) { tile.crossOrigin = ""; } /* Alt tag is *set to empty string to keep screen readers from reading URL and for compliance reasons http://www.w3.org/TR/WCAG20-TECHS/H67 */ tile.alt = ""; var tileUrl = this.getTileUrl(coords); if (this.options.useCache) { this._db.get( tileUrl, { revs_info: true }, this._onCacheLookup(tile, tileUrl, done) ); } else { // Fall back to standard behaviour tile.onload = L.bind(this._tileOnLoad, this, done, tile); tile.src = tileUrl; } return tile; }
javascript
function(coords, done) { var tile = document.createElement("img"); tile.onerror = L.bind(this._tileOnError, this, done, tile); if (this.options.crossOrigin) { tile.crossOrigin = ""; } /* Alt tag is *set to empty string to keep screen readers from reading URL and for compliance reasons http://www.w3.org/TR/WCAG20-TECHS/H67 */ tile.alt = ""; var tileUrl = this.getTileUrl(coords); if (this.options.useCache) { this._db.get( tileUrl, { revs_info: true }, this._onCacheLookup(tile, tileUrl, done) ); } else { // Fall back to standard behaviour tile.onload = L.bind(this._tileOnLoad, this, done, tile); tile.src = tileUrl; } return tile; }
[ "function", "(", "coords", ",", "done", ")", "{", "var", "tile", "=", "document", ".", "createElement", "(", "\"img\"", ")", ";", "tile", ".", "onerror", "=", "L", ".", "bind", "(", "this", ".", "_tileOnError", ",", "this", ",", "done", ",", "tile", ")", ";", "if", "(", "this", ".", "options", ".", "crossOrigin", ")", "{", "tile", ".", "crossOrigin", "=", "\"\"", ";", "}", "/*\n\t\t Alt tag is *set to empty string to keep screen readers from reading URL and for compliance reasons\n\t\t http://www.w3.org/TR/WCAG20-TECHS/H67\n\t\t */", "tile", ".", "alt", "=", "\"\"", ";", "var", "tileUrl", "=", "this", ".", "getTileUrl", "(", "coords", ")", ";", "if", "(", "this", ".", "options", ".", "useCache", ")", "{", "this", ".", "_db", ".", "get", "(", "tileUrl", ",", "{", "revs_info", ":", "true", "}", ",", "this", ".", "_onCacheLookup", "(", "tile", ",", "tileUrl", ",", "done", ")", ")", ";", "}", "else", "{", "// Fall back to standard behaviour", "tile", ".", "onload", "=", "L", ".", "bind", "(", "this", ".", "_tileOnLoad", ",", "this", ",", "done", ",", "tile", ")", ";", "tile", ".", "src", "=", "tileUrl", ";", "}", "return", "tile", ";", "}" ]
Overwrites L.TileLayer.prototype.createTile
[ "Overwrites", "L", ".", "TileLayer", ".", "prototype", ".", "createTile" ]
ca83b60dcdd276d7cd7f9c4f24eb1fd1138b2c72
https://github.com/MazeMap/Leaflet.TileLayer.PouchDBCached/blob/ca83b60dcdd276d7cd7f9c4f24eb1fd1138b2c72/L.TileLayer.PouchDBCached.js#L56-L86
19,020
MazeMap/Leaflet.TileLayer.PouchDBCached
L.TileLayer.PouchDBCached.js
function(coords) { var zoom = coords.z; if (this.options.zoomReverse) { zoom = this.options.maxZoom - zoom; } zoom += this.options.zoomOffset; return L.Util.template( this._url, L.extend( { r: this.options.detectRetina && L.Browser.retina && this.options.maxZoom > 0 ? "@2x" : "", s: this._getSubdomain(coords), x: coords.x, y: this.options.tms ? this._globalTileRange.max.y - coords.y : coords.y, z: this.options.maxNativeZoom ? Math.min(zoom, this.options.maxNativeZoom) : zoom, }, this.options ) ); }
javascript
function(coords) { var zoom = coords.z; if (this.options.zoomReverse) { zoom = this.options.maxZoom - zoom; } zoom += this.options.zoomOffset; return L.Util.template( this._url, L.extend( { r: this.options.detectRetina && L.Browser.retina && this.options.maxZoom > 0 ? "@2x" : "", s: this._getSubdomain(coords), x: coords.x, y: this.options.tms ? this._globalTileRange.max.y - coords.y : coords.y, z: this.options.maxNativeZoom ? Math.min(zoom, this.options.maxNativeZoom) : zoom, }, this.options ) ); }
[ "function", "(", "coords", ")", "{", "var", "zoom", "=", "coords", ".", "z", ";", "if", "(", "this", ".", "options", ".", "zoomReverse", ")", "{", "zoom", "=", "this", ".", "options", ".", "maxZoom", "-", "zoom", ";", "}", "zoom", "+=", "this", ".", "options", ".", "zoomOffset", ";", "return", "L", ".", "Util", ".", "template", "(", "this", ".", "_url", ",", "L", ".", "extend", "(", "{", "r", ":", "this", ".", "options", ".", "detectRetina", "&&", "L", ".", "Browser", ".", "retina", "&&", "this", ".", "options", ".", "maxZoom", ">", "0", "?", "\"@2x\"", ":", "\"\"", ",", "s", ":", "this", ".", "_getSubdomain", "(", "coords", ")", ",", "x", ":", "coords", ".", "x", ",", "y", ":", "this", ".", "options", ".", "tms", "?", "this", ".", "_globalTileRange", ".", "max", ".", "y", "-", "coords", ".", "y", ":", "coords", ".", "y", ",", "z", ":", "this", ".", "options", ".", "maxNativeZoom", "?", "Math", ".", "min", "(", "zoom", ",", "this", ".", "options", ".", "maxNativeZoom", ")", ":", "zoom", ",", "}", ",", "this", ".", "options", ")", ")", ";", "}" ]
Modified L.TileLayer.getTileUrl, this will use the zoom given by the parameter coords instead of the maps current zoomlevel.
[ "Modified", "L", ".", "TileLayer", ".", "getTileUrl", "this", "will", "use", "the", "zoom", "given", "by", "the", "parameter", "coords", "instead", "of", "the", "maps", "current", "zoomlevel", "." ]
ca83b60dcdd276d7cd7f9c4f24eb1fd1138b2c72
https://github.com/MazeMap/Leaflet.TileLayer.PouchDBCached/blob/ca83b60dcdd276d7cd7f9c4f24eb1fd1138b2c72/L.TileLayer.PouchDBCached.js#L276-L304
19,021
MazeMap/Leaflet.TileLayer.PouchDBCached
L.TileLayer.PouchDBCached.js
function(tile, remaining, seedData) { if (!remaining.length) { this.fire("seedend", seedData); return; } this.fire("seedprogress", { bbox: seedData.bbox, minZoom: seedData.minZoom, maxZoom: seedData.maxZoom, queueLength: seedData.queueLength, remainingLength: remaining.length, }); var url = remaining.shift(); this._db.get( url, function(err, data) { if (!data) { /// FIXME: Do something on tile error!! tile.onload = function(ev) { this._saveTile(tile, url, null); //(ev) this._seedOneTile(tile, remaining, seedData); }.bind(this); tile.crossOrigin = "Anonymous"; tile.src = url; } else { this._seedOneTile(tile, remaining, seedData); } }.bind(this) ); }
javascript
function(tile, remaining, seedData) { if (!remaining.length) { this.fire("seedend", seedData); return; } this.fire("seedprogress", { bbox: seedData.bbox, minZoom: seedData.minZoom, maxZoom: seedData.maxZoom, queueLength: seedData.queueLength, remainingLength: remaining.length, }); var url = remaining.shift(); this._db.get( url, function(err, data) { if (!data) { /// FIXME: Do something on tile error!! tile.onload = function(ev) { this._saveTile(tile, url, null); //(ev) this._seedOneTile(tile, remaining, seedData); }.bind(this); tile.crossOrigin = "Anonymous"; tile.src = url; } else { this._seedOneTile(tile, remaining, seedData); } }.bind(this) ); }
[ "function", "(", "tile", ",", "remaining", ",", "seedData", ")", "{", "if", "(", "!", "remaining", ".", "length", ")", "{", "this", ".", "fire", "(", "\"seedend\"", ",", "seedData", ")", ";", "return", ";", "}", "this", ".", "fire", "(", "\"seedprogress\"", ",", "{", "bbox", ":", "seedData", ".", "bbox", ",", "minZoom", ":", "seedData", ".", "minZoom", ",", "maxZoom", ":", "seedData", ".", "maxZoom", ",", "queueLength", ":", "seedData", ".", "queueLength", ",", "remainingLength", ":", "remaining", ".", "length", ",", "}", ")", ";", "var", "url", "=", "remaining", ".", "shift", "(", ")", ";", "this", ".", "_db", ".", "get", "(", "url", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "!", "data", ")", "{", "/// FIXME: Do something on tile error!!", "tile", ".", "onload", "=", "function", "(", "ev", ")", "{", "this", ".", "_saveTile", "(", "tile", ",", "url", ",", "null", ")", ";", "//(ev)", "this", ".", "_seedOneTile", "(", "tile", ",", "remaining", ",", "seedData", ")", ";", "}", ".", "bind", "(", "this", ")", ";", "tile", ".", "crossOrigin", "=", "\"Anonymous\"", ";", "tile", ".", "src", "=", "url", ";", "}", "else", "{", "this", ".", "_seedOneTile", "(", "tile", ",", "remaining", ",", "seedData", ")", ";", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Uses a defined tile to eat through one item in the queue and asynchronously recursively call itself when the tile has finished loading.
[ "Uses", "a", "defined", "tile", "to", "eat", "through", "one", "item", "in", "the", "queue", "and", "asynchronously", "recursively", "call", "itself", "when", "the", "tile", "has", "finished", "loading", "." ]
ca83b60dcdd276d7cd7f9c4f24eb1fd1138b2c72
https://github.com/MazeMap/Leaflet.TileLayer.PouchDBCached/blob/ca83b60dcdd276d7cd7f9c4f24eb1fd1138b2c72/L.TileLayer.PouchDBCached.js#L309-L340
19,022
antoniogarrote/rdfstore-js
src/query_plan.js
function(left, right, cost, identifier, allVars, joinVars) { this.left = left; this.right = right; this.cost = cost; this.i = identifier; this.vars = allVars; this.join = joinVars; }
javascript
function(left, right, cost, identifier, allVars, joinVars) { this.left = left; this.right = right; this.cost = cost; this.i = identifier; this.vars = allVars; this.join = joinVars; }
[ "function", "(", "left", ",", "right", ",", "cost", ",", "identifier", ",", "allVars", ",", "joinVars", ")", "{", "this", ".", "left", "=", "left", ";", "this", ".", "right", "=", "right", ";", "this", ".", "cost", "=", "cost", ";", "this", ".", "i", "=", "identifier", ";", "this", ".", "vars", "=", "allVars", ";", "this", ".", "join", "=", "joinVars", ";", "}" ]
A new query plan object @param left @param right @param cost @param identifier @param allVars @param joinVars @constructor
[ "A", "new", "query", "plan", "object" ]
1b19a61ede04ba19605ca3b7dc331c990ab7336f
https://github.com/antoniogarrote/rdfstore-js/blob/1b19a61ede04ba19605ca3b7dc331c990ab7336f/src/query_plan.js#L14-L23
19,023
antoniogarrote/rdfstore-js
src/query_plan.js
function(vars, groupVars) { for(var j=0; j<vars.length; j++) { var thisVar = "/"+vars[j]+"/"; if(groupVars.indexOf(thisVar) != -1) { return true; } } return false; }
javascript
function(vars, groupVars) { for(var j=0; j<vars.length; j++) { var thisVar = "/"+vars[j]+"/"; if(groupVars.indexOf(thisVar) != -1) { return true; } } return false; }
[ "function", "(", "vars", ",", "groupVars", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "vars", ".", "length", ";", "j", "++", ")", "{", "var", "thisVar", "=", "\"/\"", "+", "vars", "[", "j", "]", "+", "\"/\"", ";", "if", "(", "groupVars", ".", "indexOf", "(", "thisVar", ")", "!=", "-", "1", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns true if the any of the passed vars are in the vars associated to the group.
[ "Returns", "true", "if", "the", "any", "of", "the", "passed", "vars", "are", "in", "the", "vars", "associated", "to", "the", "group", "." ]
1b19a61ede04ba19605ca3b7dc331c990ab7336f
https://github.com/antoniogarrote/rdfstore-js/blob/1b19a61ede04ba19605ca3b7dc331c990ab7336f/src/query_plan.js#L118-L128
19,024
antoniogarrote/rdfstore-js
src/query_plan.js
function(bgp, toJoin, newGroups, newGroupVars) { var acumGroups = []; var acumId = ""; var acumVars = ""; for(var gid in toJoin) { acumId = acumId+gid; // new group id acumGroups = acumGroups.concat(groups[gid]); acumVars = acumVars + groupVars[gid]; // @todo bug here? we were not adding... } acumVars = acumVars + vars.join("/") + "/"; acumGroups.push(bgp); newGroups[acumId] = acumGroups; newGroupVars[acumId] = acumVars; }
javascript
function(bgp, toJoin, newGroups, newGroupVars) { var acumGroups = []; var acumId = ""; var acumVars = ""; for(var gid in toJoin) { acumId = acumId+gid; // new group id acumGroups = acumGroups.concat(groups[gid]); acumVars = acumVars + groupVars[gid]; // @todo bug here? we were not adding... } acumVars = acumVars + vars.join("/") + "/"; acumGroups.push(bgp); newGroups[acumId] = acumGroups; newGroupVars[acumId] = acumVars; }
[ "function", "(", "bgp", ",", "toJoin", ",", "newGroups", ",", "newGroupVars", ")", "{", "var", "acumGroups", "=", "[", "]", ";", "var", "acumId", "=", "\"\"", ";", "var", "acumVars", "=", "\"\"", ";", "for", "(", "var", "gid", "in", "toJoin", ")", "{", "acumId", "=", "acumId", "+", "gid", ";", "// new group id", "acumGroups", "=", "acumGroups", ".", "concat", "(", "groups", "[", "gid", "]", ")", ";", "acumVars", "=", "acumVars", "+", "groupVars", "[", "gid", "]", ";", "// @todo bug here? we were not adding...", "}", "acumVars", "=", "acumVars", "+", "vars", ".", "join", "(", "\"/\"", ")", "+", "\"/\"", ";", "acumGroups", ".", "push", "(", "bgp", ")", ";", "newGroups", "[", "acumId", "]", "=", "acumGroups", ";", "newGroupVars", "[", "acumId", "]", "=", "acumVars", ";", "}" ]
Creates a new group merging the vars and the groups
[ "Creates", "a", "new", "group", "merging", "the", "vars", "and", "the", "groups" ]
1b19a61ede04ba19605ca3b7dc331c990ab7336f
https://github.com/antoniogarrote/rdfstore-js/blob/1b19a61ede04ba19605ca3b7dc331c990ab7336f/src/query_plan.js#L131-L146
19,025
antoniogarrote/rdfstore-js
frontend/js/rdfquery.js
function (absolute) { var aPath, bPath, i = 0, j, resultPath = [], result = ''; if (typeof absolute === 'string') { absolute = $.uri(absolute, {}); } if (absolute.scheme !== this.scheme || absolute.authority !== this.authority) { return absolute.toString(); } if (absolute.path !== this.path) { aPath = absolute.path.split('/'); bPath = this.path.split('/'); if (aPath[1] !== bPath[1]) { result = absolute.path; } else { while (aPath[i] === bPath[i]) { i += 1; } j = i; for (; i < bPath.length - 1; i += 1) { resultPath.push('..'); } for (; j < aPath.length; j += 1) { resultPath.push(aPath[j]); } result = resultPath.join('/'); } result = absolute.query === undefined ? result : result + '?' + absolute.query; result = absolute.fragment === undefined ? result : result + '#' + absolute.fragment; return result; } if (absolute.query !== undefined && absolute.query !== this.query) { return '?' + absolute.query + (absolute.fragment === undefined ? '' : '#' + absolute.fragment); } if (absolute.fragment !== undefined && absolute.fragment !== this.fragment) { return '#' + absolute.fragment; } return ''; }
javascript
function (absolute) { var aPath, bPath, i = 0, j, resultPath = [], result = ''; if (typeof absolute === 'string') { absolute = $.uri(absolute, {}); } if (absolute.scheme !== this.scheme || absolute.authority !== this.authority) { return absolute.toString(); } if (absolute.path !== this.path) { aPath = absolute.path.split('/'); bPath = this.path.split('/'); if (aPath[1] !== bPath[1]) { result = absolute.path; } else { while (aPath[i] === bPath[i]) { i += 1; } j = i; for (; i < bPath.length - 1; i += 1) { resultPath.push('..'); } for (; j < aPath.length; j += 1) { resultPath.push(aPath[j]); } result = resultPath.join('/'); } result = absolute.query === undefined ? result : result + '?' + absolute.query; result = absolute.fragment === undefined ? result : result + '#' + absolute.fragment; return result; } if (absolute.query !== undefined && absolute.query !== this.query) { return '?' + absolute.query + (absolute.fragment === undefined ? '' : '#' + absolute.fragment); } if (absolute.fragment !== undefined && absolute.fragment !== this.fragment) { return '#' + absolute.fragment; } return ''; }
[ "function", "(", "absolute", ")", "{", "var", "aPath", ",", "bPath", ",", "i", "=", "0", ",", "j", ",", "resultPath", "=", "[", "]", ",", "result", "=", "''", ";", "if", "(", "typeof", "absolute", "===", "'string'", ")", "{", "absolute", "=", "$", ".", "uri", "(", "absolute", ",", "{", "}", ")", ";", "}", "if", "(", "absolute", ".", "scheme", "!==", "this", ".", "scheme", "||", "absolute", ".", "authority", "!==", "this", ".", "authority", ")", "{", "return", "absolute", ".", "toString", "(", ")", ";", "}", "if", "(", "absolute", ".", "path", "!==", "this", ".", "path", ")", "{", "aPath", "=", "absolute", ".", "path", ".", "split", "(", "'/'", ")", ";", "bPath", "=", "this", ".", "path", ".", "split", "(", "'/'", ")", ";", "if", "(", "aPath", "[", "1", "]", "!==", "bPath", "[", "1", "]", ")", "{", "result", "=", "absolute", ".", "path", ";", "}", "else", "{", "while", "(", "aPath", "[", "i", "]", "===", "bPath", "[", "i", "]", ")", "{", "i", "+=", "1", ";", "}", "j", "=", "i", ";", "for", "(", ";", "i", "<", "bPath", ".", "length", "-", "1", ";", "i", "+=", "1", ")", "{", "resultPath", ".", "push", "(", "'..'", ")", ";", "}", "for", "(", ";", "j", "<", "aPath", ".", "length", ";", "j", "+=", "1", ")", "{", "resultPath", ".", "push", "(", "aPath", "[", "j", "]", ")", ";", "}", "result", "=", "resultPath", ".", "join", "(", "'/'", ")", ";", "}", "result", "=", "absolute", ".", "query", "===", "undefined", "?", "result", ":", "result", "+", "'?'", "+", "absolute", ".", "query", ";", "result", "=", "absolute", ".", "fragment", "===", "undefined", "?", "result", ":", "result", "+", "'#'", "+", "absolute", ".", "fragment", ";", "return", "result", ";", "}", "if", "(", "absolute", ".", "query", "!==", "undefined", "&&", "absolute", ".", "query", "!==", "this", ".", "query", ")", "{", "return", "'?'", "+", "absolute", ".", "query", "+", "(", "absolute", ".", "fragment", "===", "undefined", "?", "''", ":", "'#'", "+", "absolute", ".", "fragment", ")", ";", "}", "if", "(", "absolute", ".", "fragment", "!==", "undefined", "&&", "absolute", ".", "fragment", "!==", "this", ".", "fragment", ")", "{", "return", "'#'", "+", "absolute", ".", "fragment", ";", "}", "return", "''", ";", "}" ]
Creates a relative URI giving the path from this URI to the absolute URI passed as a parameter @param {String|jQuery.uri} absolute @returns String
[ "Creates", "a", "relative", "URI", "giving", "the", "path", "from", "this", "URI", "to", "the", "absolute", "URI", "passed", "as", "a", "parameter" ]
1b19a61ede04ba19605ca3b7dc331c990ab7336f
https://github.com/antoniogarrote/rdfstore-js/blob/1b19a61ede04ba19605ca3b7dc331c990ab7336f/frontend/js/rdfquery.js#L174-L212
19,026
antoniogarrote/rdfstore-js
frontend/js/rdfquery.js
function () { var result = ''; if (this._string) { return this._string; } else { result = this.scheme === undefined ? result : (result + this.scheme + ':'); result = this.authority === undefined ? result : (result + '//' + this.authority); result = result + this.path; result = this.query === undefined ? result : (result + '?' + this.query); result = this.fragment === undefined ? result : (result + '#' + this.fragment); this._string = result; return result; } }
javascript
function () { var result = ''; if (this._string) { return this._string; } else { result = this.scheme === undefined ? result : (result + this.scheme + ':'); result = this.authority === undefined ? result : (result + '//' + this.authority); result = result + this.path; result = this.query === undefined ? result : (result + '?' + this.query); result = this.fragment === undefined ? result : (result + '#' + this.fragment); this._string = result; return result; } }
[ "function", "(", ")", "{", "var", "result", "=", "''", ";", "if", "(", "this", ".", "_string", ")", "{", "return", "this", ".", "_string", ";", "}", "else", "{", "result", "=", "this", ".", "scheme", "===", "undefined", "?", "result", ":", "(", "result", "+", "this", ".", "scheme", "+", "':'", ")", ";", "result", "=", "this", ".", "authority", "===", "undefined", "?", "result", ":", "(", "result", "+", "'//'", "+", "this", ".", "authority", ")", ";", "result", "=", "result", "+", "this", ".", "path", ";", "result", "=", "this", ".", "query", "===", "undefined", "?", "result", ":", "(", "result", "+", "'?'", "+", "this", ".", "query", ")", ";", "result", "=", "this", ".", "fragment", "===", "undefined", "?", "result", ":", "(", "result", "+", "'#'", "+", "this", ".", "fragment", ")", ";", "this", ".", "_string", "=", "result", ";", "return", "result", ";", "}", "}" ]
Returns the URI as an absolute string @returns String
[ "Returns", "the", "URI", "as", "an", "absolute", "string" ]
1b19a61ede04ba19605ca3b7dc331c990ab7336f
https://github.com/antoniogarrote/rdfstore-js/blob/1b19a61ede04ba19605ca3b7dc331c990ab7336f/frontend/js/rdfquery.js#L218-L231
19,027
antoniogarrote/rdfstore-js
frontend/js/rdfquery.js
function (options) { options = $.extend({ namespaces: this.namespaces, base: this.base }, options || {}); return $.rdf.dump(this.triples(), options); }
javascript
function (options) { options = $.extend({ namespaces: this.namespaces, base: this.base }, options || {}); return $.rdf.dump(this.triples(), options); }
[ "function", "(", "options", ")", "{", "options", "=", "$", ".", "extend", "(", "{", "namespaces", ":", "this", ".", "namespaces", ",", "base", ":", "this", ".", "base", "}", ",", "options", "||", "{", "}", ")", ";", "return", "$", ".", "rdf", ".", "dump", "(", "this", ".", "triples", "(", ")", ",", "options", ")", ";", "}" ]
Dumps the triples in the databank into a format that can be shown to the user or sent to a server. @param {Object} [options] Options that control the formatting of the triples. See {@link jQuery.rdf.dump} for details. @returns {Object|Node|String} @see jQuery.rdf.dump
[ "Dumps", "the", "triples", "in", "the", "databank", "into", "a", "format", "that", "can", "be", "shown", "to", "the", "user", "or", "sent", "to", "a", "server", "." ]
1b19a61ede04ba19605ca3b7dc331c990ab7336f
https://github.com/antoniogarrote/rdfstore-js/blob/1b19a61ede04ba19605ca3b7dc331c990ab7336f/frontend/js/rdfquery.js#L2792-L2795
19,028
antoniogarrote/rdfstore-js
frontend/js/rdfquery.js
function (triple) { var binding = {}; binding = testResource(triple.subject, this.subject, binding); if (binding === null) { return null; } binding = testResource(triple.property, this.property, binding); if (binding === null) { return null; } binding = testResource(triple.object, this.object, binding); return binding; }
javascript
function (triple) { var binding = {}; binding = testResource(triple.subject, this.subject, binding); if (binding === null) { return null; } binding = testResource(triple.property, this.property, binding); if (binding === null) { return null; } binding = testResource(triple.object, this.object, binding); return binding; }
[ "function", "(", "triple", ")", "{", "var", "binding", "=", "{", "}", ";", "binding", "=", "testResource", "(", "triple", ".", "subject", ",", "this", ".", "subject", ",", "binding", ")", ";", "if", "(", "binding", "===", "null", ")", "{", "return", "null", ";", "}", "binding", "=", "testResource", "(", "triple", ".", "property", ",", "this", ".", "property", ",", "binding", ")", ";", "if", "(", "binding", "===", "null", ")", "{", "return", "null", ";", "}", "binding", "=", "testResource", "(", "triple", ".", "object", ",", "this", ".", "object", ",", "binding", ")", ";", "return", "binding", ";", "}" ]
Creates a new Object holding variable bindings by matching the passed triple against this pattern. @param {jQuery.rdf.triple} triple A {@link jQuery.rdf.triple} for this pattern to match against. @returns {null|Object} An object containing the bindings of variables (as specified in this pattern) to values (as specified in the triple), or <code>null</code> if the triple doesn't match the pattern. pattern = $.rdf.pattern('?thing a ?class'); bindings = pattern.exec($.rdf.triple('<> a foaf:Person', { namespaces: ns })); thing = bindings.thing; // the resource for this page class = bindings.class; // a resource for foaf:Person
[ "Creates", "a", "new", "Object", "holding", "variable", "bindings", "by", "matching", "the", "passed", "triple", "against", "this", "pattern", "." ]
1b19a61ede04ba19605ca3b7dc331c990ab7336f
https://github.com/antoniogarrote/rdfstore-js/blob/1b19a61ede04ba19605ca3b7dc331c990ab7336f/frontend/js/rdfquery.js#L3020-L3032
19,029
antoniogarrote/rdfstore-js
frontend/js/rdfquery.js
function (bindings) { var t = this; if (!this.isFixed()) { t = this.fill(bindings); } if (t.isFixed()) { return $.rdf.triple(t.subject, t.property, t.object, { source: this.toString() }); } else { return null; } }
javascript
function (bindings) { var t = this; if (!this.isFixed()) { t = this.fill(bindings); } if (t.isFixed()) { return $.rdf.triple(t.subject, t.property, t.object, { source: this.toString() }); } else { return null; } }
[ "function", "(", "bindings", ")", "{", "var", "t", "=", "this", ";", "if", "(", "!", "this", ".", "isFixed", "(", ")", ")", "{", "t", "=", "this", ".", "fill", "(", "bindings", ")", ";", "}", "if", "(", "t", ".", "isFixed", "(", ")", ")", "{", "return", "$", ".", "rdf", ".", "triple", "(", "t", ".", "subject", ",", "t", ".", "property", ",", "t", ".", "object", ",", "{", "source", ":", "this", ".", "toString", "(", ")", "}", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Creates a new triple based on the bindings passed to the pattern, if possible. @param {Object} bindings An object holding the variable bindings to be used to replace any placeholders in the pattern. These bindings are of the type held by the {@link jQuery.rdf} object. @returns {null|jQuery.rdf.triple} A new {@link jQuery.rdf.triple} object, or null if not all the variable placeholders in the pattern are specified in the bindings. The {@link jQuery.rdf.triple#source} of the generated triple is set to the string value of this pattern. @example pattern = $.rdf.pattern('?thing a ?class'); // triple is a new triple '<> a foaf:Person' triple = pattern.triple({ thing: $.rdf.resource('<>'), class: $.rdf.resource('foaf:Person', { namespaces: ns }) });
[ "Creates", "a", "new", "triple", "based", "on", "the", "bindings", "passed", "to", "the", "pattern", "if", "possible", "." ]
1b19a61ede04ba19605ca3b7dc331c990ab7336f
https://github.com/antoniogarrote/rdfstore-js/blob/1b19a61ede04ba19605ca3b7dc331c990ab7336f/frontend/js/rdfquery.js#L3059-L3069
19,030
antoniogarrote/rdfstore-js
src/utils.js
function(term) { try { if(term == null) { return ""; } if(term.token==='uri') { return "u"+term.value; } else if(term.token === 'blank') { return "b"+term.value; } else if(term.token === 'literal') { var l = "l"+term.value; l = l + (term.type || ""); l = l + (term.lang || ""); return l; } } catch(e) { if(typeof(term) === 'object') { var key = ""; for(p in term) { key = key + p + term[p]; } return key; } return term; } }
javascript
function(term) { try { if(term == null) { return ""; } if(term.token==='uri') { return "u"+term.value; } else if(term.token === 'blank') { return "b"+term.value; } else if(term.token === 'literal') { var l = "l"+term.value; l = l + (term.type || ""); l = l + (term.lang || ""); return l; } } catch(e) { if(typeof(term) === 'object') { var key = ""; for(p in term) { key = key + p + term[p]; } return key; } return term; } }
[ "function", "(", "term", ")", "{", "try", "{", "if", "(", "term", "==", "null", ")", "{", "return", "\"\"", ";", "}", "if", "(", "term", ".", "token", "===", "'uri'", ")", "{", "return", "\"u\"", "+", "term", ".", "value", ";", "}", "else", "if", "(", "term", ".", "token", "===", "'blank'", ")", "{", "return", "\"b\"", "+", "term", ".", "value", ";", "}", "else", "if", "(", "term", ".", "token", "===", "'literal'", ")", "{", "var", "l", "=", "\"l\"", "+", "term", ".", "value", ";", "l", "=", "l", "+", "(", "term", ".", "type", "||", "\"\"", ")", ";", "l", "=", "l", "+", "(", "term", ".", "lang", "||", "\"\"", ")", ";", "return", "l", ";", "}", "}", "catch", "(", "e", ")", "{", "if", "(", "typeof", "(", "term", ")", "===", "'object'", ")", "{", "var", "key", "=", "\"\"", ";", "for", "(", "p", "in", "term", ")", "{", "key", "=", "key", "+", "p", "+", "term", "[", "p", "]", ";", "}", "return", "key", ";", "}", "return", "term", ";", "}", "}" ]
Function that generates a hash key for a bound term. @param term @returns {*}
[ "Function", "that", "generates", "a", "hash", "key", "for", "a", "bound", "term", "." ]
1b19a61ede04ba19605ca3b7dc331c990ab7336f
https://github.com/antoniogarrote/rdfstore-js/blob/1b19a61ede04ba19605ca3b7dc331c990ab7336f/src/utils.js#L34-L60
19,031
antoniogarrote/rdfstore-js
lubm/browser/server.js
function(filename, charset, callback) { fs.readFile(filename, function (err, data) { if (err) throw err; zlib.gzip(data, function(err, result) { callback(result); }); }); }
javascript
function(filename, charset, callback) { fs.readFile(filename, function (err, data) { if (err) throw err; zlib.gzip(data, function(err, result) { callback(result); }); }); }
[ "function", "(", "filename", ",", "charset", ",", "callback", ")", "{", "fs", ".", "readFile", "(", "filename", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "throw", "err", ";", "zlib", ".", "gzip", "(", "data", ",", "function", "(", "err", ",", "result", ")", "{", "callback", "(", "result", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
gzip file.
[ "gzip", "file", "." ]
1b19a61ede04ba19605ca3b7dc331c990ab7336f
https://github.com/antoniogarrote/rdfstore-js/blob/1b19a61ede04ba19605ca3b7dc331c990ab7336f/lubm/browser/server.js#L35-L45
19,032
antoniogarrote/rdfstore-js
src/store.js
function(){ if(arguments.length == 1) { return new Store(arguments[0]); } else if(arguments.length == 2) { return new Store(arguments[0], arguments[1]); } else { return new Store(); }; }
javascript
function(){ if(arguments.length == 1) { return new Store(arguments[0]); } else if(arguments.length == 2) { return new Store(arguments[0], arguments[1]); } else { return new Store(); }; }
[ "function", "(", ")", "{", "if", "(", "arguments", ".", "length", "==", "1", ")", "{", "return", "new", "Store", "(", "arguments", "[", "0", "]", ")", ";", "}", "else", "if", "(", "arguments", ".", "length", "==", "2", ")", "{", "return", "new", "Store", "(", "arguments", "[", "0", "]", ",", "arguments", "[", "1", "]", ")", ";", "}", "else", "{", "return", "new", "Store", "(", ")", ";", "}", ";", "}" ]
Creates a new instance of the store. The function accepts two optional arguments. <br/> If only one argument is passed it must be a callback function that will be invoked when the store had been created.<br/> <br/> If two arguments are passed the first one must be a map of configuration parameters for the store, and the second one the callback function.<br/> <br/> Take a look at the Store constructor function for a detailed list of possible configuration parameters.<br/> @param {Object[]} [args] Arguments to be passed to the store that will be created @param {Function} [callback] Callback function that will be invoked with an error flag and the connection/store object.
[ "Creates", "a", "new", "instance", "of", "the", "store", "." ]
1b19a61ede04ba19605ca3b7dc331c990ab7336f
https://github.com/antoniogarrote/rdfstore-js/blob/1b19a61ede04ba19605ca3b7dc331c990ab7336f/src/store.js#L909-L917
19,033
antoniogarrote/rdfstore-js
spec/browser/nodeunit.js
function (callback) { return function (new_method, assert_method, arity) { return function () { var message = arguments[arity - 1]; var a = exports.assertion({method: new_method, message: message}); try { assert[assert_method].apply(null, arguments); } catch (e) { a.error = e; } callback(a); }; }; }
javascript
function (callback) { return function (new_method, assert_method, arity) { return function () { var message = arguments[arity - 1]; var a = exports.assertion({method: new_method, message: message}); try { assert[assert_method].apply(null, arguments); } catch (e) { a.error = e; } callback(a); }; }; }
[ "function", "(", "callback", ")", "{", "return", "function", "(", "new_method", ",", "assert_method", ",", "arity", ")", "{", "return", "function", "(", ")", "{", "var", "message", "=", "arguments", "[", "arity", "-", "1", "]", ";", "var", "a", "=", "exports", ".", "assertion", "(", "{", "method", ":", "new_method", ",", "message", ":", "message", "}", ")", ";", "try", "{", "assert", "[", "assert_method", "]", ".", "apply", "(", "null", ",", "arguments", ")", ";", "}", "catch", "(", "e", ")", "{", "a", ".", "error", "=", "e", ";", "}", "callback", "(", "a", ")", ";", "}", ";", "}", ";", "}" ]
Create a wrapper function for assert module methods. Executes a callback after the it's complete with an assertion object representing the result. @param {Function} callback @api private
[ "Create", "a", "wrapper", "function", "for", "assert", "module", "methods", ".", "Executes", "a", "callback", "after", "the", "it", "s", "complete", "with", "an", "assertion", "object", "representing", "the", "result", "." ]
1b19a61ede04ba19605ca3b7dc331c990ab7336f
https://github.com/antoniogarrote/rdfstore-js/blob/1b19a61ede04ba19605ca3b7dc331c990ab7336f/spec/browser/nodeunit.js#L1515-L1529
19,034
antoniogarrote/rdfstore-js
spec/browser/nodeunit.js
function (setUp, tearDown, fn) { return function (test) { var context = {}; if (tearDown) { var done = test.done; test.done = function (err) { try { tearDown.call(context, function (err2) { if (err && err2) { test._assertion_list.push( types.assertion({error: err}) ); return done(err2); } done(err || err2); }); } catch (e) { done(e); } }; } if (setUp) { setUp.call(context, function (err) { if (err) { return test.done(err); } fn.call(context, test); }); } else { fn.call(context, test); } }; }
javascript
function (setUp, tearDown, fn) { return function (test) { var context = {}; if (tearDown) { var done = test.done; test.done = function (err) { try { tearDown.call(context, function (err2) { if (err && err2) { test._assertion_list.push( types.assertion({error: err}) ); return done(err2); } done(err || err2); }); } catch (e) { done(e); } }; } if (setUp) { setUp.call(context, function (err) { if (err) { return test.done(err); } fn.call(context, test); }); } else { fn.call(context, test); } }; }
[ "function", "(", "setUp", ",", "tearDown", ",", "fn", ")", "{", "return", "function", "(", "test", ")", "{", "var", "context", "=", "{", "}", ";", "if", "(", "tearDown", ")", "{", "var", "done", "=", "test", ".", "done", ";", "test", ".", "done", "=", "function", "(", "err", ")", "{", "try", "{", "tearDown", ".", "call", "(", "context", ",", "function", "(", "err2", ")", "{", "if", "(", "err", "&&", "err2", ")", "{", "test", ".", "_assertion_list", ".", "push", "(", "types", ".", "assertion", "(", "{", "error", ":", "err", "}", ")", ")", ";", "return", "done", "(", "err2", ")", ";", "}", "done", "(", "err", "||", "err2", ")", ";", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "done", "(", "e", ")", ";", "}", "}", ";", "}", "if", "(", "setUp", ")", "{", "setUp", ".", "call", "(", "context", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "test", ".", "done", "(", "err", ")", ";", "}", "fn", ".", "call", "(", "context", ",", "test", ")", ";", "}", ")", ";", "}", "else", "{", "fn", ".", "call", "(", "context", ",", "test", ")", ";", "}", "}", ";", "}" ]
Wraps a test function with setUp and tearDown functions. Used by testCase. @param {Function} setUp @param {Function} tearDown @param {Function} fn @api private
[ "Wraps", "a", "test", "function", "with", "setUp", "and", "tearDown", "functions", ".", "Used", "by", "testCase", "." ]
1b19a61ede04ba19605ca3b7dc331c990ab7336f
https://github.com/antoniogarrote/rdfstore-js/blob/1b19a61ede04ba19605ca3b7dc331c990ab7336f/spec/browser/nodeunit.js#L1822-L1856
19,035
antoniogarrote/rdfstore-js
spec/browser/nodeunit.js
function (setUp, tearDown, group) { var tests = {}; var keys = _keys(group); for (var i = 0; i < keys.length; i += 1) { var k = keys[i]; if (typeof group[k] === 'function') { tests[k] = wrapTest(setUp, tearDown, group[k]); } else if (typeof group[k] === 'object') { tests[k] = wrapGroup(setUp, tearDown, group[k]); } } return tests; }
javascript
function (setUp, tearDown, group) { var tests = {}; var keys = _keys(group); for (var i = 0; i < keys.length; i += 1) { var k = keys[i]; if (typeof group[k] === 'function') { tests[k] = wrapTest(setUp, tearDown, group[k]); } else if (typeof group[k] === 'object') { tests[k] = wrapGroup(setUp, tearDown, group[k]); } } return tests; }
[ "function", "(", "setUp", ",", "tearDown", ",", "group", ")", "{", "var", "tests", "=", "{", "}", ";", "var", "keys", "=", "_keys", "(", "group", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "+=", "1", ")", "{", "var", "k", "=", "keys", "[", "i", "]", ";", "if", "(", "typeof", "group", "[", "k", "]", "===", "'function'", ")", "{", "tests", "[", "k", "]", "=", "wrapTest", "(", "setUp", ",", "tearDown", ",", "group", "[", "k", "]", ")", ";", "}", "else", "if", "(", "typeof", "group", "[", "k", "]", "===", "'object'", ")", "{", "tests", "[", "k", "]", "=", "wrapGroup", "(", "setUp", ",", "tearDown", ",", "group", "[", "k", "]", ")", ";", "}", "}", "return", "tests", ";", "}" ]
Wraps a group of tests with setUp and tearDown functions. Used by testCase. @param {Function} setUp @param {Function} tearDown @param {Object} group @api private
[ "Wraps", "a", "group", "of", "tests", "with", "setUp", "and", "tearDown", "functions", ".", "Used", "by", "testCase", "." ]
1b19a61ede04ba19605ca3b7dc331c990ab7336f
https://github.com/antoniogarrote/rdfstore-js/blob/1b19a61ede04ba19605ca3b7dc331c990ab7336f/spec/browser/nodeunit.js#L1869-L1882
19,036
antoniogarrote/rdfstore-js
src/rvn3_parser.js
convertEntity
function convertEntity(entity) { switch (entity[0]) { case '"': { if(entity.indexOf("^^") > 0) { var parts = entity.split("^^"); return {literal: parts[0] + "^^<" + parts[1] + ">" }; } else { return { literal: entity }; } } case '_': return { blank: entity.replace('b', '') }; default: return { token: 'uri', value: entity, prefix: null, suffix: null }; } }
javascript
function convertEntity(entity) { switch (entity[0]) { case '"': { if(entity.indexOf("^^") > 0) { var parts = entity.split("^^"); return {literal: parts[0] + "^^<" + parts[1] + ">" }; } else { return { literal: entity }; } } case '_': return { blank: entity.replace('b', '') }; default: return { token: 'uri', value: entity, prefix: null, suffix: null }; } }
[ "function", "convertEntity", "(", "entity", ")", "{", "switch", "(", "entity", "[", "0", "]", ")", "{", "case", "'\"'", ":", "{", "if", "(", "entity", ".", "indexOf", "(", "\"^^\"", ")", ">", "0", ")", "{", "var", "parts", "=", "entity", ".", "split", "(", "\"^^\"", ")", ";", "return", "{", "literal", ":", "parts", "[", "0", "]", "+", "\"^^<\"", "+", "parts", "[", "1", "]", "+", "\">\"", "}", ";", "}", "else", "{", "return", "{", "literal", ":", "entity", "}", ";", "}", "}", "case", "'_'", ":", "return", "{", "blank", ":", "entity", ".", "replace", "(", "'b'", ",", "''", ")", "}", ";", "default", ":", "return", "{", "token", ":", "'uri'", ",", "value", ":", "entity", ",", "prefix", ":", "null", ",", "suffix", ":", "null", "}", ";", "}", "}" ]
Converts an entity in N3.js representation to this library's representation
[ "Converts", "an", "entity", "in", "N3", ".", "js", "representation", "to", "this", "library", "s", "representation" ]
1b19a61ede04ba19605ca3b7dc331c990ab7336f
https://github.com/antoniogarrote/rdfstore-js/blob/1b19a61ede04ba19605ca3b7dc331c990ab7336f/src/rvn3_parser.js#L47-L60
19,037
mozilla/fxa-shared
oauth/scopes.js
coerce
function coerce(scopes) { if (scopes instanceof ScopeSet) { return scopes; } // If we receive a string, assume it's a single scope. // We deliberately do not attempt to split the string on whitespace here, // because we want to force callers to explicitly choose between // exports.fromString() or exports.fromURLEncodedString depending on // what encoding they expect to have received the string in. if (typeof scopes === 'string') { return new ScopeSet([scopes]); } return new ScopeSet(scopes); }
javascript
function coerce(scopes) { if (scopes instanceof ScopeSet) { return scopes; } // If we receive a string, assume it's a single scope. // We deliberately do not attempt to split the string on whitespace here, // because we want to force callers to explicitly choose between // exports.fromString() or exports.fromURLEncodedString depending on // what encoding they expect to have received the string in. if (typeof scopes === 'string') { return new ScopeSet([scopes]); } return new ScopeSet(scopes); }
[ "function", "coerce", "(", "scopes", ")", "{", "if", "(", "scopes", "instanceof", "ScopeSet", ")", "{", "return", "scopes", ";", "}", "// If we receive a string, assume it's a single scope.", "// We deliberately do not attempt to split the string on whitespace here,", "// because we want to force callers to explicitly choose between", "// exports.fromString() or exports.fromURLEncodedString depending on", "// what encoding they expect to have received the string in.", "if", "(", "typeof", "scopes", "===", "'string'", ")", "{", "return", "new", "ScopeSet", "(", "[", "scopes", "]", ")", ";", "}", "return", "new", "ScopeSet", "(", "scopes", ")", ";", "}" ]
A little helper function for coercing different kinds of input data into a `ScopeSet` instance.
[ "A", "little", "helper", "function", "for", "coercing", "different", "kinds", "of", "input", "data", "into", "a", "ScopeSet", "instance", "." ]
e95c36400472642311554dab53dde8068f973c59
https://github.com/mozilla/fxa-shared/blob/e95c36400472642311554dab53dde8068f973c59/oauth/scopes.js#L437-L450
19,038
mozilla/fxa-shared
feature-flags/index.js
initialise
function initialise (config, log, defaults) { const { interval, redis: redisConfig } = config; if (! (interval > 0 && interval < Infinity)) { throw new TypeError('Invalid interval'); } if (! log) { throw new TypeError('Missing log argument'); } const redis = require('../redis')({ ...redisConfig, enabled: true, prefix: FLAGS_PREFIX, }, log); let cache, timeout; refresh(); /** * @typedef {Object} FeatureFlags * * @property {Function} get * * @property {Function} terminate */ return { get, terminate }; async function refresh () { try { if (cache) { // Eliminate any latency during refresh by keeping the old cached result // until the refreshed promise has actually resolved. const result = await redis.get(FLAGS_KEY); cache = Promise.resolve(JSON.parse(result)); } else { cache = redis.get(FLAGS_KEY).then(result => JSON.parse(result)); // The positioning of `await` is deliberate here. // The initial value of `cache` must be a promise // so that callers can access it uniformly. // But we don't want `setTimeout` to be invoked // until after that promise has completed. await cache; } } catch (error) { } timeout = setTimeout(refresh, interval); } /** * Get the current state for all experiments. * Asynchronous, but returns the cached state * so it doesn't add latency, * except during initialisation. * * @returns {Promise} */ async function get () { try { return await cache || defaults || {}; } catch (error) { if (defaults) { return defaults; } throw error; } } /** * Terminate the refresh loop * and close all redis connections. * Useful for e.g. terminating tests cleanly. * * @returns {Promise} */ function terminate () { if (timeout) { clearTimeout(timeout); timeout = null; } return redis.close(); } }
javascript
function initialise (config, log, defaults) { const { interval, redis: redisConfig } = config; if (! (interval > 0 && interval < Infinity)) { throw new TypeError('Invalid interval'); } if (! log) { throw new TypeError('Missing log argument'); } const redis = require('../redis')({ ...redisConfig, enabled: true, prefix: FLAGS_PREFIX, }, log); let cache, timeout; refresh(); /** * @typedef {Object} FeatureFlags * * @property {Function} get * * @property {Function} terminate */ return { get, terminate }; async function refresh () { try { if (cache) { // Eliminate any latency during refresh by keeping the old cached result // until the refreshed promise has actually resolved. const result = await redis.get(FLAGS_KEY); cache = Promise.resolve(JSON.parse(result)); } else { cache = redis.get(FLAGS_KEY).then(result => JSON.parse(result)); // The positioning of `await` is deliberate here. // The initial value of `cache` must be a promise // so that callers can access it uniformly. // But we don't want `setTimeout` to be invoked // until after that promise has completed. await cache; } } catch (error) { } timeout = setTimeout(refresh, interval); } /** * Get the current state for all experiments. * Asynchronous, but returns the cached state * so it doesn't add latency, * except during initialisation. * * @returns {Promise} */ async function get () { try { return await cache || defaults || {}; } catch (error) { if (defaults) { return defaults; } throw error; } } /** * Terminate the refresh loop * and close all redis connections. * Useful for e.g. terminating tests cleanly. * * @returns {Promise} */ function terminate () { if (timeout) { clearTimeout(timeout); timeout = null; } return redis.close(); } }
[ "function", "initialise", "(", "config", ",", "log", ",", "defaults", ")", "{", "const", "{", "interval", ",", "redis", ":", "redisConfig", "}", "=", "config", ";", "if", "(", "!", "(", "interval", ">", "0", "&&", "interval", "<", "Infinity", ")", ")", "{", "throw", "new", "TypeError", "(", "'Invalid interval'", ")", ";", "}", "if", "(", "!", "log", ")", "{", "throw", "new", "TypeError", "(", "'Missing log argument'", ")", ";", "}", "const", "redis", "=", "require", "(", "'../redis'", ")", "(", "{", "...", "redisConfig", ",", "enabled", ":", "true", ",", "prefix", ":", "FLAGS_PREFIX", ",", "}", ",", "log", ")", ";", "let", "cache", ",", "timeout", ";", "refresh", "(", ")", ";", "/**\n * @typedef {Object} FeatureFlags\n *\n * @property {Function} get\n *\n * @property {Function} terminate\n */", "return", "{", "get", ",", "terminate", "}", ";", "async", "function", "refresh", "(", ")", "{", "try", "{", "if", "(", "cache", ")", "{", "// Eliminate any latency during refresh by keeping the old cached result", "// until the refreshed promise has actually resolved.", "const", "result", "=", "await", "redis", ".", "get", "(", "FLAGS_KEY", ")", ";", "cache", "=", "Promise", ".", "resolve", "(", "JSON", ".", "parse", "(", "result", ")", ")", ";", "}", "else", "{", "cache", "=", "redis", ".", "get", "(", "FLAGS_KEY", ")", ".", "then", "(", "result", "=>", "JSON", ".", "parse", "(", "result", ")", ")", ";", "// The positioning of `await` is deliberate here.", "// The initial value of `cache` must be a promise", "// so that callers can access it uniformly.", "// But we don't want `setTimeout` to be invoked", "// until after that promise has completed.", "await", "cache", ";", "}", "}", "catch", "(", "error", ")", "{", "}", "timeout", "=", "setTimeout", "(", "refresh", ",", "interval", ")", ";", "}", "/**\n * Get the current state for all experiments.\n * Asynchronous, but returns the cached state\n * so it doesn't add latency,\n * except during initialisation.\n *\n * @returns {Promise}\n */", "async", "function", "get", "(", ")", "{", "try", "{", "return", "await", "cache", "||", "defaults", "||", "{", "}", ";", "}", "catch", "(", "error", ")", "{", "if", "(", "defaults", ")", "{", "return", "defaults", ";", "}", "throw", "error", ";", "}", "}", "/**\n * Terminate the refresh loop\n * and close all redis connections.\n * Useful for e.g. terminating tests cleanly.\n *\n * @returns {Promise}\n */", "function", "terminate", "(", ")", "{", "if", "(", "timeout", ")", "{", "clearTimeout", "(", "timeout", ")", ";", "timeout", "=", "null", ";", "}", "return", "redis", ".", "close", "(", ")", ";", "}", "}" ]
Initialise the feature-flag module. @param {Object} config - Configuration object. @param {Object} config.interval - Refresh interval. @param {Object} [config.redis] - Redis config. @param {String} [config.redis.host] - Redis host name or IP address. @param {Number} [config.redis.port] - Redis port. @param {Number} [config.redis.maxConnections] - Maximum number of connections in Redis pool. @param {Number} [config.redis.maxPending] - Maximum number of clients waiting for a connection. @param {Number} [config.redis.minConnections] - Minimum number of clients in Redis pool. @param {Object} log - Log object. @param {Object} [defaults] - Default experiment state to return in the event of error. If not set, calls to FeatureFlags.get may fail. @returns {FeatureFlags}
[ "Initialise", "the", "feature", "-", "flag", "module", "." ]
e95c36400472642311554dab53dde8068f973c59
https://github.com/mozilla/fxa-shared/blob/e95c36400472642311554dab53dde8068f973c59/feature-flags/index.js#L31-L118
19,039
kentcdodds/webpack-config-utils
src/get-if-utils.js
getIfUtils
function getIfUtils(env, vars = ['production', 'prod', 'test', 'development', 'dev']) { env = typeof env === 'string' ? {[env]: true} : env if (typeof env !== 'object') { throw new Error( `webpack-config-utils:getIfUtils: env passed should be a string/Object. Was ${JSON.stringify(env)}` ) } return vars.reduce((utils, variable) => { const envValue = !!env[variable] const capitalVariable = capitalizeWord(variable) utils[`if${capitalVariable}`] = (value, alternate) => { return isUndefined(value) ? envValue : propIf(envValue, value, alternate) } utils[`ifNot${capitalVariable}`] = (value, alternate) => { return isUndefined(value) ? !envValue : propIfNot(envValue, value, alternate) } return utils }, {}) }
javascript
function getIfUtils(env, vars = ['production', 'prod', 'test', 'development', 'dev']) { env = typeof env === 'string' ? {[env]: true} : env if (typeof env !== 'object') { throw new Error( `webpack-config-utils:getIfUtils: env passed should be a string/Object. Was ${JSON.stringify(env)}` ) } return vars.reduce((utils, variable) => { const envValue = !!env[variable] const capitalVariable = capitalizeWord(variable) utils[`if${capitalVariable}`] = (value, alternate) => { return isUndefined(value) ? envValue : propIf(envValue, value, alternate) } utils[`ifNot${capitalVariable}`] = (value, alternate) => { return isUndefined(value) ? !envValue : propIfNot(envValue, value, alternate) } return utils }, {}) }
[ "function", "getIfUtils", "(", "env", ",", "vars", "=", "[", "'production'", ",", "'prod'", ",", "'test'", ",", "'development'", ",", "'dev'", "]", ")", "{", "env", "=", "typeof", "env", "===", "'string'", "?", "{", "[", "env", "]", ":", "true", "}", ":", "env", "if", "(", "typeof", "env", "!==", "'object'", ")", "{", "throw", "new", "Error", "(", "`", "${", "JSON", ".", "stringify", "(", "env", ")", "}", "`", ")", "}", "return", "vars", ".", "reduce", "(", "(", "utils", ",", "variable", ")", "=>", "{", "const", "envValue", "=", "!", "!", "env", "[", "variable", "]", "const", "capitalVariable", "=", "capitalizeWord", "(", "variable", ")", "utils", "[", "`", "${", "capitalVariable", "}", "`", "]", "=", "(", "value", ",", "alternate", ")", "=>", "{", "return", "isUndefined", "(", "value", ")", "?", "envValue", ":", "propIf", "(", "envValue", ",", "value", ",", "alternate", ")", "}", "utils", "[", "`", "${", "capitalVariable", "}", "`", "]", "=", "(", "value", ",", "alternate", ")", "=>", "{", "return", "isUndefined", "(", "value", ")", "?", "!", "envValue", ":", "propIfNot", "(", "envValue", ",", "value", ",", "alternate", ")", "}", "return", "utils", "}", ",", "{", "}", ")", "}" ]
The object returned from getIfUtils @typedef {Object} IfUtils @property {function} ifProduction - a wrapper around `propIf` function that returns the given `value` if the environment is `"production"` or the `alternate` if not @property {function} ifNotProduction, - a wrapper around `propIf` function that returns the given `value` if the environment is not `"production"` or the `alternate` if it is @property {function} ifProd - a wrapper around `propIf` function that returns the given `value` if the environment is `"prod"` or the `alternate` if not @property {function} ifNotProd, - a wrapper around `propIf` function that returns the given `value` if the environment is not `"prod"` or the `alternate` if it is @property {function} ifTest - a wrapper around `propIf` function that returns the given `value` if the environment is `"test"` or the `alternate` if not @property {function} ifNotTest, - a wrapper around `propIf` function that returns the given `value` if the environment is not `"test"` or the `alternate` if it is @property {function} ifDevelopment - a wrapper around `propIf` function that returns the given `value` if the environment is `"development"` or the `alternate` if not @property {function} ifNotDevelopment, - a wrapper around `propIf` function that returns the given `value` if the environment is not `"development"` or the `alternate` if it is @property {function} ifDev - a wrapper around `propIf` function that returns the given `value` if the environment is `"dev"` or the `alternate` if not @property {function} ifNotDev, - a wrapper around `propIf` function that returns the given `value` if the environment is not `"dev"` or the `alternate` if it is This returns an object with methods to help you conditionally set values to your webpack configuration object. @param {Object|string} env This would be either the `env` object from webpack (function config API) or the value of `process.env.NODE_ENV`. @param {Array} vars A list of valid environments if utils are generated for @return {IfUtils} the IfUtils object for the given environment
[ "The", "object", "returned", "from", "getIfUtils" ]
816ac556f1b9a88c07ba2bc31d312948a653b057
https://github.com/kentcdodds/webpack-config-utils/blob/816ac556f1b9a88c07ba2bc31d312948a653b057/src/get-if-utils.js#L37-L55
19,040
eddyerburgh/avoriaz
dist/avoriaz.amd.js
ListCache
function ListCache(entries) { var this$1 = this; var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this$1.set(entry[0], entry[1]); } }
javascript
function ListCache(entries) { var this$1 = this; var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this$1.set(entry[0], entry[1]); } }
[ "function", "ListCache", "(", "entries", ")", "{", "var", "this$1", "=", "this", ";", "var", "index", "=", "-", "1", ",", "length", "=", "entries", "==", "null", "?", "0", ":", "entries", ".", "length", ";", "this", ".", "clear", "(", ")", ";", "while", "(", "++", "index", "<", "length", ")", "{", "var", "entry", "=", "entries", "[", "index", "]", ";", "this$1", ".", "set", "(", "entry", "[", "0", "]", ",", "entry", "[", "1", "]", ")", ";", "}", "}" ]
Creates an list cache object. @private @constructor @param {Array} [entries] The key-value pairs to cache.
[ "Creates", "an", "list", "cache", "object", "." ]
4070f017bf1d0175c54ab383f880ef815cc887c6
https://github.com/eddyerburgh/avoriaz/blob/4070f017bf1d0175c54ab383f880ef815cc887c6/dist/avoriaz.amd.js#L176-L187
19,041
olov/ng-annotate
lut.js
findNodeFromPos
function findNodeFromPos(pos) { const lut = this.begins; assert(is.finitenumber(pos) && pos >= 0); let left = 0; let right = lut.length - 1; while (left < right) { const mid = Math.floor((left + right) / 2); assert(mid >= 0 && mid < lut.length); if (pos > lut[mid].range[0]) { left = mid + 1; } else { right = mid; } } if (left > right) { assert(last(lut).range[0] < pos); return null; } const found = left; const foundPos = lut[found].range[0]; assert(foundPos >= pos); if (found >= 1) { const prevPos = lut[found - 1].range[0]; assert(prevPos < pos); } return lut[found]; }
javascript
function findNodeFromPos(pos) { const lut = this.begins; assert(is.finitenumber(pos) && pos >= 0); let left = 0; let right = lut.length - 1; while (left < right) { const mid = Math.floor((left + right) / 2); assert(mid >= 0 && mid < lut.length); if (pos > lut[mid].range[0]) { left = mid + 1; } else { right = mid; } } if (left > right) { assert(last(lut).range[0] < pos); return null; } const found = left; const foundPos = lut[found].range[0]; assert(foundPos >= pos); if (found >= 1) { const prevPos = lut[found - 1].range[0]; assert(prevPos < pos); } return lut[found]; }
[ "function", "findNodeFromPos", "(", "pos", ")", "{", "const", "lut", "=", "this", ".", "begins", ";", "assert", "(", "is", ".", "finitenumber", "(", "pos", ")", "&&", "pos", ">=", "0", ")", ";", "let", "left", "=", "0", ";", "let", "right", "=", "lut", ".", "length", "-", "1", ";", "while", "(", "left", "<", "right", ")", "{", "const", "mid", "=", "Math", ".", "floor", "(", "(", "left", "+", "right", ")", "/", "2", ")", ";", "assert", "(", "mid", ">=", "0", "&&", "mid", "<", "lut", ".", "length", ")", ";", "if", "(", "pos", ">", "lut", "[", "mid", "]", ".", "range", "[", "0", "]", ")", "{", "left", "=", "mid", "+", "1", ";", "}", "else", "{", "right", "=", "mid", ";", "}", "}", "if", "(", "left", ">", "right", ")", "{", "assert", "(", "last", "(", "lut", ")", ".", "range", "[", "0", "]", "<", "pos", ")", ";", "return", "null", ";", "}", "const", "found", "=", "left", ";", "const", "foundPos", "=", "lut", "[", "found", "]", ".", "range", "[", "0", "]", ";", "assert", "(", "foundPos", ">=", "pos", ")", ";", "if", "(", "found", ">=", "1", ")", "{", "const", "prevPos", "=", "lut", "[", "found", "-", "1", "]", ".", "range", "[", "0", "]", ";", "assert", "(", "prevPos", "<", "pos", ")", ";", "}", "return", "lut", "[", "found", "]", ";", "}" ]
binary search lut to find node beginning at pos or as close after pos as possible. null if none
[ "binary", "search", "lut", "to", "find", "node", "beginning", "at", "pos", "or", "as", "close", "after", "pos", "as", "possible", ".", "null", "if", "none" ]
f5c709c682c99afe9e1413d9081734a62e3e5cdf
https://github.com/olov/ng-annotate/blob/f5c709c682c99afe9e1413d9081734a62e3e5cdf/lut.js#L56-L86
19,042
olov/ng-annotate
ng-annotate-main.js
replaceNodeWith
function replaceNodeWith(node, newNode) { let done = false; const parent = node.$parent; const keys = Object.keys(parent); keys.forEach(function(key) { if (parent[key] === node) { parent[key] = newNode; done = true; } }); if (done) { return; } // second pass, now check arrays keys.forEach(function(key) { if (Array.isArray(parent[key])) { const arr = parent[key]; for (let i = 0; i < arr.length; i++) { if (arr[i] === node) { arr[i] = newNode; done = true; } } } }); assert(done); }
javascript
function replaceNodeWith(node, newNode) { let done = false; const parent = node.$parent; const keys = Object.keys(parent); keys.forEach(function(key) { if (parent[key] === node) { parent[key] = newNode; done = true; } }); if (done) { return; } // second pass, now check arrays keys.forEach(function(key) { if (Array.isArray(parent[key])) { const arr = parent[key]; for (let i = 0; i < arr.length; i++) { if (arr[i] === node) { arr[i] = newNode; done = true; } } } }); assert(done); }
[ "function", "replaceNodeWith", "(", "node", ",", "newNode", ")", "{", "let", "done", "=", "false", ";", "const", "parent", "=", "node", ".", "$parent", ";", "const", "keys", "=", "Object", ".", "keys", "(", "parent", ")", ";", "keys", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "parent", "[", "key", "]", "===", "node", ")", "{", "parent", "[", "key", "]", "=", "newNode", ";", "done", "=", "true", ";", "}", "}", ")", ";", "if", "(", "done", ")", "{", "return", ";", "}", "// second pass, now check arrays", "keys", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "Array", ".", "isArray", "(", "parent", "[", "key", "]", ")", ")", "{", "const", "arr", "=", "parent", "[", "key", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "arr", ".", "length", ";", "i", "++", ")", "{", "if", "(", "arr", "[", "i", "]", "===", "node", ")", "{", "arr", "[", "i", "]", "=", "newNode", ";", "done", "=", "true", ";", "}", "}", "}", "}", ")", ";", "assert", "(", "done", ")", ";", "}" ]
stand-in for not having a jsshaper-style ref's
[ "stand", "-", "in", "for", "not", "having", "a", "jsshaper", "-", "style", "ref", "s" ]
f5c709c682c99afe9e1413d9081734a62e3e5cdf
https://github.com/olov/ng-annotate/blob/f5c709c682c99afe9e1413d9081734a62e3e5cdf/ng-annotate-main.js#L451-L480
19,043
kurttheviking/html2plaintext
index.js
_escapeHtml
function _escapeHtml (input) { return String(input) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#039;'); }
javascript
function _escapeHtml (input) { return String(input) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#039;'); }
[ "function", "_escapeHtml", "(", "input", ")", "{", "return", "String", "(", "input", ")", ".", "replace", "(", "/", "&", "/", "g", ",", "'&amp;'", ")", ".", "replace", "(", "/", "<", "/", "g", ",", "'&lt;'", ")", ".", "replace", "(", "/", ">", "/", "g", ",", "'&gt;'", ")", ".", "replace", "(", "/", "\"", "/", "g", ",", "'&quot;'", ")", ".", "replace", "(", "/", "'", "/", "g", ",", "'&#039;'", ")", ";", "}" ]
"private" helper for ensuring html entities are properly escaped
[ "private", "helper", "for", "ensuring", "html", "entities", "are", "properly", "escaped" ]
dbb7104a7fb87a790cf7ac294e0b9ca13dc67982
https://github.com/kurttheviking/html2plaintext/blob/dbb7104a7fb87a790cf7ac294e0b9ca13dc67982/index.js#L6-L13
19,044
kurttheviking/html2plaintext
index.js
_list
function _list (str, isOrdered) { if (!str) return str; var $ = cheerio.load(str); var listEl = isOrdered ? 'ol' : 'ul'; $(listEl).each(function (i, el) { var $out = cheerio.load('<p></p>'); var $el = $(el); $el.find('li').each(function (j, li) { var tick = isOrdered ? String(j + 1) + '.' : '-'; $out('p').append(tick + ' ' + _escapeHtml($(li).text()) + '<br />'); }); // avoid excess spacing coming off last element // (we are wrapping with a <p> anyway) $out('br').last().remove(); $el.replaceWith($out.html()); }); return $.html(); }
javascript
function _list (str, isOrdered) { if (!str) return str; var $ = cheerio.load(str); var listEl = isOrdered ? 'ol' : 'ul'; $(listEl).each(function (i, el) { var $out = cheerio.load('<p></p>'); var $el = $(el); $el.find('li').each(function (j, li) { var tick = isOrdered ? String(j + 1) + '.' : '-'; $out('p').append(tick + ' ' + _escapeHtml($(li).text()) + '<br />'); }); // avoid excess spacing coming off last element // (we are wrapping with a <p> anyway) $out('br').last().remove(); $el.replaceWith($out.html()); }); return $.html(); }
[ "function", "_list", "(", "str", ",", "isOrdered", ")", "{", "if", "(", "!", "str", ")", "return", "str", ";", "var", "$", "=", "cheerio", ".", "load", "(", "str", ")", ";", "var", "listEl", "=", "isOrdered", "?", "'ol'", ":", "'ul'", ";", "$", "(", "listEl", ")", ".", "each", "(", "function", "(", "i", ",", "el", ")", "{", "var", "$out", "=", "cheerio", ".", "load", "(", "'<p></p>'", ")", ";", "var", "$el", "=", "$", "(", "el", ")", ";", "$el", ".", "find", "(", "'li'", ")", ".", "each", "(", "function", "(", "j", ",", "li", ")", "{", "var", "tick", "=", "isOrdered", "?", "String", "(", "j", "+", "1", ")", "+", "'.'", ":", "'-'", ";", "$out", "(", "'p'", ")", ".", "append", "(", "tick", "+", "' '", "+", "_escapeHtml", "(", "$", "(", "li", ")", ".", "text", "(", ")", ")", "+", "'<br />'", ")", ";", "}", ")", ";", "// avoid excess spacing coming off last element", "// (we are wrapping with a <p> anyway)", "$out", "(", "'br'", ")", ".", "last", "(", ")", ".", "remove", "(", ")", ";", "$el", ".", "replaceWith", "(", "$out", ".", "html", "(", ")", ")", ";", "}", ")", ";", "return", "$", ".", "html", "(", ")", ";", "}" ]
"private" helper for list processing into plaintext
[ "private", "helper", "for", "list", "processing", "into", "plaintext" ]
dbb7104a7fb87a790cf7ac294e0b9ca13dc67982
https://github.com/kurttheviking/html2plaintext/blob/dbb7104a7fb87a790cf7ac294e0b9ca13dc67982/index.js#L16-L40
19,045
uber/express-statsd
lib/express-statsd.js
sendStats
function sendStats() { var key = req[options.requestKey]; key = key ? key + '.' : ''; // Status Code var statusCode = res.statusCode || 'unknown_status'; client.increment(key + 'status_code.' + statusCode); // Response Time var duration = new Date().getTime() - startTime; client.timing(key + 'response_time', duration); cleanup(); }
javascript
function sendStats() { var key = req[options.requestKey]; key = key ? key + '.' : ''; // Status Code var statusCode = res.statusCode || 'unknown_status'; client.increment(key + 'status_code.' + statusCode); // Response Time var duration = new Date().getTime() - startTime; client.timing(key + 'response_time', duration); cleanup(); }
[ "function", "sendStats", "(", ")", "{", "var", "key", "=", "req", "[", "options", ".", "requestKey", "]", ";", "key", "=", "key", "?", "key", "+", "'.'", ":", "''", ";", "// Status Code", "var", "statusCode", "=", "res", ".", "statusCode", "||", "'unknown_status'", ";", "client", ".", "increment", "(", "key", "+", "'status_code.'", "+", "statusCode", ")", ";", "// Response Time", "var", "duration", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", "-", "startTime", ";", "client", ".", "timing", "(", "key", "+", "'response_time'", ",", "duration", ")", ";", "cleanup", "(", ")", ";", "}" ]
Function called on response finish that sends stats to statsd
[ "Function", "called", "on", "response", "finish", "that", "sends", "stats", "to", "statsd" ]
4e3ee7dd68c2bcebaa1718d4310b1b32a8b66e47
https://github.com/uber/express-statsd/blob/4e3ee7dd68c2bcebaa1718d4310b1b32a8b66e47/lib/express-statsd.js#L20-L33
19,046
chartshq/datamodel
src/converter/auto-resolver.js
Auto
function Auto (data, options) { const converters = { FlatJSON, DSVStr, DSVArr }; const dataFormat = detectDataFormat(data); if (!dataFormat) { throw new Error('Couldn\'t detect the data format'); } return converters[dataFormat](data, options); }
javascript
function Auto (data, options) { const converters = { FlatJSON, DSVStr, DSVArr }; const dataFormat = detectDataFormat(data); if (!dataFormat) { throw new Error('Couldn\'t detect the data format'); } return converters[dataFormat](data, options); }
[ "function", "Auto", "(", "data", ",", "options", ")", "{", "const", "converters", "=", "{", "FlatJSON", ",", "DSVStr", ",", "DSVArr", "}", ";", "const", "dataFormat", "=", "detectDataFormat", "(", "data", ")", ";", "if", "(", "!", "dataFormat", ")", "{", "throw", "new", "Error", "(", "'Couldn\\'t detect the data format'", ")", ";", "}", "return", "converters", "[", "dataFormat", "]", "(", "data", ",", "options", ")", ";", "}" ]
Parses the input data and detect the format automatically. @param {string|Array} data - The input data. @param {Object} options - An optional config specific to data format. @return {Array.<Object>} Returns an array of headers and column major data.
[ "Parses", "the", "input", "data", "and", "detect", "the", "format", "automatically", "." ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/converter/auto-resolver.js#L13-L22
19,047
chartshq/datamodel
src/converter/dsv-str.js
DSVStr
function DSVStr (str, options) { const defaultOption = { firstRowHeader: true, fieldSeparator: ',' }; options = Object.assign({}, defaultOption, options); const dsv = d3Dsv(options.fieldSeparator); return DSVArr(dsv.parseRows(str), options); }
javascript
function DSVStr (str, options) { const defaultOption = { firstRowHeader: true, fieldSeparator: ',' }; options = Object.assign({}, defaultOption, options); const dsv = d3Dsv(options.fieldSeparator); return DSVArr(dsv.parseRows(str), options); }
[ "function", "DSVStr", "(", "str", ",", "options", ")", "{", "const", "defaultOption", "=", "{", "firstRowHeader", ":", "true", ",", "fieldSeparator", ":", "','", "}", ";", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "defaultOption", ",", "options", ")", ";", "const", "dsv", "=", "d3Dsv", "(", "options", ".", "fieldSeparator", ")", ";", "return", "DSVArr", "(", "dsv", ".", "parseRows", "(", "str", ")", ",", "options", ")", ";", "}" ]
Parses and converts data formatted in DSV string to a manageable internal format. @todo Support to be given for https://tools.ietf.org/html/rfc4180. @todo Sample implementation https://github.com/knrz/CSV.js/. @param {string} str - The input DSV string. @param {Object} options - Option to control the behaviour of the parsing. @param {boolean} [options.firstRowHeader=true] - Whether the first row of the dsv string data is header or not. @param {string} [options.fieldSeparator=","] - The separator of two consecutive field. @return {Array} Returns an array of headers and column major data. @example // Sample input data: const data = ` a,b,c 1,2,3 4,5,6 7,8,9 `
[ "Parses", "and", "converts", "data", "formatted", "in", "DSV", "string", "to", "a", "manageable", "internal", "format", "." ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/converter/dsv-str.js#L25-L34
19,048
chartshq/datamodel
src/field-creator.js
createUnitField
function createUnitField(data, schema) { data = data || []; let partialField; switch (schema.type) { case FieldType.MEASURE: switch (schema.subtype) { case MeasureSubtype.CONTINUOUS: partialField = new PartialField(schema.name, data, schema, new ContinuousParser()); return new Continuous(partialField, `0-${data.length - 1}`); default: partialField = new PartialField(schema.name, data, schema, new ContinuousParser()); return new Continuous(partialField, `0-${data.length - 1}`); } case FieldType.DIMENSION: switch (schema.subtype) { case DimensionSubtype.CATEGORICAL: partialField = new PartialField(schema.name, data, schema, new CategoricalParser()); return new Categorical(partialField, `0-${data.length - 1}`); case DimensionSubtype.TEMPORAL: partialField = new PartialField(schema.name, data, schema, new TemporalParser(schema)); return new Temporal(partialField, `0-${data.length - 1}`); case DimensionSubtype.BINNED: partialField = new PartialField(schema.name, data, schema, new BinnedParser()); return new Binned(partialField, `0-${data.length - 1}`); default: partialField = new PartialField(schema.name, data, schema, new CategoricalParser()); return new Categorical(partialField, `0-${data.length - 1}`); } default: partialField = new PartialField(schema.name, data, schema, new CategoricalParser()); return new Categorical(partialField, `0-${data.length - 1}`); } }
javascript
function createUnitField(data, schema) { data = data || []; let partialField; switch (schema.type) { case FieldType.MEASURE: switch (schema.subtype) { case MeasureSubtype.CONTINUOUS: partialField = new PartialField(schema.name, data, schema, new ContinuousParser()); return new Continuous(partialField, `0-${data.length - 1}`); default: partialField = new PartialField(schema.name, data, schema, new ContinuousParser()); return new Continuous(partialField, `0-${data.length - 1}`); } case FieldType.DIMENSION: switch (schema.subtype) { case DimensionSubtype.CATEGORICAL: partialField = new PartialField(schema.name, data, schema, new CategoricalParser()); return new Categorical(partialField, `0-${data.length - 1}`); case DimensionSubtype.TEMPORAL: partialField = new PartialField(schema.name, data, schema, new TemporalParser(schema)); return new Temporal(partialField, `0-${data.length - 1}`); case DimensionSubtype.BINNED: partialField = new PartialField(schema.name, data, schema, new BinnedParser()); return new Binned(partialField, `0-${data.length - 1}`); default: partialField = new PartialField(schema.name, data, schema, new CategoricalParser()); return new Categorical(partialField, `0-${data.length - 1}`); } default: partialField = new PartialField(schema.name, data, schema, new CategoricalParser()); return new Categorical(partialField, `0-${data.length - 1}`); } }
[ "function", "createUnitField", "(", "data", ",", "schema", ")", "{", "data", "=", "data", "||", "[", "]", ";", "let", "partialField", ";", "switch", "(", "schema", ".", "type", ")", "{", "case", "FieldType", ".", "MEASURE", ":", "switch", "(", "schema", ".", "subtype", ")", "{", "case", "MeasureSubtype", ".", "CONTINUOUS", ":", "partialField", "=", "new", "PartialField", "(", "schema", ".", "name", ",", "data", ",", "schema", ",", "new", "ContinuousParser", "(", ")", ")", ";", "return", "new", "Continuous", "(", "partialField", ",", "`", "${", "data", ".", "length", "-", "1", "}", "`", ")", ";", "default", ":", "partialField", "=", "new", "PartialField", "(", "schema", ".", "name", ",", "data", ",", "schema", ",", "new", "ContinuousParser", "(", ")", ")", ";", "return", "new", "Continuous", "(", "partialField", ",", "`", "${", "data", ".", "length", "-", "1", "}", "`", ")", ";", "}", "case", "FieldType", ".", "DIMENSION", ":", "switch", "(", "schema", ".", "subtype", ")", "{", "case", "DimensionSubtype", ".", "CATEGORICAL", ":", "partialField", "=", "new", "PartialField", "(", "schema", ".", "name", ",", "data", ",", "schema", ",", "new", "CategoricalParser", "(", ")", ")", ";", "return", "new", "Categorical", "(", "partialField", ",", "`", "${", "data", ".", "length", "-", "1", "}", "`", ")", ";", "case", "DimensionSubtype", ".", "TEMPORAL", ":", "partialField", "=", "new", "PartialField", "(", "schema", ".", "name", ",", "data", ",", "schema", ",", "new", "TemporalParser", "(", "schema", ")", ")", ";", "return", "new", "Temporal", "(", "partialField", ",", "`", "${", "data", ".", "length", "-", "1", "}", "`", ")", ";", "case", "DimensionSubtype", ".", "BINNED", ":", "partialField", "=", "new", "PartialField", "(", "schema", ".", "name", ",", "data", ",", "schema", ",", "new", "BinnedParser", "(", ")", ")", ";", "return", "new", "Binned", "(", "partialField", ",", "`", "${", "data", ".", "length", "-", "1", "}", "`", ")", ";", "default", ":", "partialField", "=", "new", "PartialField", "(", "schema", ".", "name", ",", "data", ",", "schema", ",", "new", "CategoricalParser", "(", ")", ")", ";", "return", "new", "Categorical", "(", "partialField", ",", "`", "${", "data", ".", "length", "-", "1", "}", "`", ")", ";", "}", "default", ":", "partialField", "=", "new", "PartialField", "(", "schema", ".", "name", ",", "data", ",", "schema", ",", "new", "CategoricalParser", "(", ")", ")", ";", "return", "new", "Categorical", "(", "partialField", ",", "`", "${", "data", ".", "length", "-", "1", "}", "`", ")", ";", "}", "}" ]
Creates a field instance according to the provided data and schema. @param {Array} data - The field data array. @param {Object} schema - The field schema object. @return {Field} Returns the newly created field instance.
[ "Creates", "a", "field", "instance", "according", "to", "the", "provided", "data", "and", "schema", "." ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/field-creator.js#L21-L54
19,049
chartshq/datamodel
plugins/md.js
generateNestedMap
function generateNestedMap(objArray) { let mainMap = new Map(); objArray.forEach((obj) => { let params = obj.name.split('.'); let i = 0; let k = mainMap; while (k.has(params[i])) { k = k.get(params[i]); i++; } let kk = new Map(); kk.set('value', obj.description.replace(/(\r\n|\n|\r)/gm, ' ')); kk.set('type', obj.type.names.join('\n\n').replace(/\./gi, '')); k.set(params[i], kk); }); return mainMap; }
javascript
function generateNestedMap(objArray) { let mainMap = new Map(); objArray.forEach((obj) => { let params = obj.name.split('.'); let i = 0; let k = mainMap; while (k.has(params[i])) { k = k.get(params[i]); i++; } let kk = new Map(); kk.set('value', obj.description.replace(/(\r\n|\n|\r)/gm, ' ')); kk.set('type', obj.type.names.join('\n\n').replace(/\./gi, '')); k.set(params[i], kk); }); return mainMap; }
[ "function", "generateNestedMap", "(", "objArray", ")", "{", "let", "mainMap", "=", "new", "Map", "(", ")", ";", "objArray", ".", "forEach", "(", "(", "obj", ")", "=>", "{", "let", "params", "=", "obj", ".", "name", ".", "split", "(", "'.'", ")", ";", "let", "i", "=", "0", ";", "let", "k", "=", "mainMap", ";", "while", "(", "k", ".", "has", "(", "params", "[", "i", "]", ")", ")", "{", "k", "=", "k", ".", "get", "(", "params", "[", "i", "]", ")", ";", "i", "++", ";", "}", "let", "kk", "=", "new", "Map", "(", ")", ";", "kk", ".", "set", "(", "'value'", ",", "obj", ".", "description", ".", "replace", "(", "/", "(\\r\\n|\\n|\\r)", "/", "gm", ",", "' '", ")", ")", ";", "kk", ".", "set", "(", "'type'", ",", "obj", ".", "type", ".", "names", ".", "join", "(", "'\\n\\n'", ")", ".", "replace", "(", "/", "\\.", "/", "gi", ",", "''", ")", ")", ";", "k", ".", "set", "(", "params", "[", "i", "]", ",", "kk", ")", ";", "}", ")", ";", "return", "mainMap", ";", "}" ]
This method generates a nested hashmap for the parameters table @param {Object} objArray the Array structure containing the parameters
[ "This", "method", "generates", "a", "nested", "hashmap", "for", "the", "parameters", "table" ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/plugins/md.js#L12-L29
19,050
chartshq/datamodel
src/operator/group-by-function.js
sum
function sum (arr) { if (isArray(arr) && !(arr[0] instanceof Array)) { const filteredNumber = getFilteredValues(arr); const totalSum = filteredNumber.length ? filteredNumber.reduce((acc, curr) => acc + curr, 0) : InvalidAwareTypes.NULL; return totalSum; } return InvalidAwareTypes.NULL; }
javascript
function sum (arr) { if (isArray(arr) && !(arr[0] instanceof Array)) { const filteredNumber = getFilteredValues(arr); const totalSum = filteredNumber.length ? filteredNumber.reduce((acc, curr) => acc + curr, 0) : InvalidAwareTypes.NULL; return totalSum; } return InvalidAwareTypes.NULL; }
[ "function", "sum", "(", "arr", ")", "{", "if", "(", "isArray", "(", "arr", ")", "&&", "!", "(", "arr", "[", "0", "]", "instanceof", "Array", ")", ")", "{", "const", "filteredNumber", "=", "getFilteredValues", "(", "arr", ")", ";", "const", "totalSum", "=", "filteredNumber", ".", "length", "?", "filteredNumber", ".", "reduce", "(", "(", "acc", ",", "curr", ")", "=>", "acc", "+", "curr", ",", "0", ")", ":", "InvalidAwareTypes", ".", "NULL", ";", "return", "totalSum", ";", "}", "return", "InvalidAwareTypes", ".", "NULL", ";", "}" ]
Reducer function that returns the sum of all the values. @public @param {Array.<number>} arr - The input array. @return {number} Returns the sum of the array.
[ "Reducer", "function", "that", "returns", "the", "sum", "of", "all", "the", "values", "." ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/operator/group-by-function.js#L17-L26
19,051
chartshq/datamodel
src/operator/group-by-function.js
avg
function avg (arr) { if (isArray(arr) && !(arr[0] instanceof Array)) { const totalSum = sum(arr); const len = arr.length || 1; return (Number.isNaN(totalSum) || totalSum instanceof InvalidAwareTypes) ? InvalidAwareTypes.NULL : totalSum / len; } return InvalidAwareTypes.NULL; }
javascript
function avg (arr) { if (isArray(arr) && !(arr[0] instanceof Array)) { const totalSum = sum(arr); const len = arr.length || 1; return (Number.isNaN(totalSum) || totalSum instanceof InvalidAwareTypes) ? InvalidAwareTypes.NULL : totalSum / len; } return InvalidAwareTypes.NULL; }
[ "function", "avg", "(", "arr", ")", "{", "if", "(", "isArray", "(", "arr", ")", "&&", "!", "(", "arr", "[", "0", "]", "instanceof", "Array", ")", ")", "{", "const", "totalSum", "=", "sum", "(", "arr", ")", ";", "const", "len", "=", "arr", ".", "length", "||", "1", ";", "return", "(", "Number", ".", "isNaN", "(", "totalSum", ")", "||", "totalSum", "instanceof", "InvalidAwareTypes", ")", "?", "InvalidAwareTypes", ".", "NULL", ":", "totalSum", "/", "len", ";", "}", "return", "InvalidAwareTypes", ".", "NULL", ";", "}" ]
Reducer function that returns the average of all the values. @public @param {Array.<number>} arr - The input array. @return {number} Returns the mean value of the array.
[ "Reducer", "function", "that", "returns", "the", "average", "of", "all", "the", "values", "." ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/operator/group-by-function.js#L35-L43
19,052
chartshq/datamodel
src/operator/group-by-function.js
min
function min (arr) { if (isArray(arr) && !(arr[0] instanceof Array)) { // Filter out undefined, null and NaN values const filteredValues = getFilteredValues(arr); return (filteredValues.length) ? Math.min(...filteredValues) : InvalidAwareTypes.NULL; } return InvalidAwareTypes.NULL; }
javascript
function min (arr) { if (isArray(arr) && !(arr[0] instanceof Array)) { // Filter out undefined, null and NaN values const filteredValues = getFilteredValues(arr); return (filteredValues.length) ? Math.min(...filteredValues) : InvalidAwareTypes.NULL; } return InvalidAwareTypes.NULL; }
[ "function", "min", "(", "arr", ")", "{", "if", "(", "isArray", "(", "arr", ")", "&&", "!", "(", "arr", "[", "0", "]", "instanceof", "Array", ")", ")", "{", "// Filter out undefined, null and NaN values", "const", "filteredValues", "=", "getFilteredValues", "(", "arr", ")", ";", "return", "(", "filteredValues", ".", "length", ")", "?", "Math", ".", "min", "(", "...", "filteredValues", ")", ":", "InvalidAwareTypes", ".", "NULL", ";", "}", "return", "InvalidAwareTypes", ".", "NULL", ";", "}" ]
Reducer function that gives the min value amongst all the values. @public @param {Array.<number>} arr - The input array. @return {number} Returns the minimum value of the array.
[ "Reducer", "function", "that", "gives", "the", "min", "value", "amongst", "all", "the", "values", "." ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/operator/group-by-function.js#L52-L60
19,053
chartshq/datamodel
src/operator/group-by-function.js
variance
function variance (arr) { let mean = avg(arr); return avg(arr.map(num => (num - mean) ** 2)); }
javascript
function variance (arr) { let mean = avg(arr); return avg(arr.map(num => (num - mean) ** 2)); }
[ "function", "variance", "(", "arr", ")", "{", "let", "mean", "=", "avg", "(", "arr", ")", ";", "return", "avg", "(", "arr", ".", "map", "(", "num", "=>", "(", "num", "-", "mean", ")", "**", "2", ")", ")", ";", "}" ]
Calculates the variance of the input array. @param {Array.<number>} arr - The input array. @return {number} Returns the variance of the input array.
[ "Calculates", "the", "variance", "of", "the", "input", "array", "." ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/operator/group-by-function.js#L121-L124
19,054
chartshq/datamodel
src/operator/data-builder.js
getSortFn
function getSortFn (dataType, sortType, index) { let retFunc; switch (dataType) { case MeasureSubtype.CONTINUOUS: case DimensionSubtype.TEMPORAL: if (sortType === 'desc') { retFunc = (a, b) => b[index] - a[index]; } else { retFunc = (a, b) => a[index] - b[index]; } break; default: retFunc = (a, b) => { const a1 = `${a[index]}`; const b1 = `${b[index]}`; if (a1 < b1) { return sortType === 'desc' ? 1 : -1; } if (a1 > b1) { return sortType === 'desc' ? -1 : 1; } return 0; }; } return retFunc; }
javascript
function getSortFn (dataType, sortType, index) { let retFunc; switch (dataType) { case MeasureSubtype.CONTINUOUS: case DimensionSubtype.TEMPORAL: if (sortType === 'desc') { retFunc = (a, b) => b[index] - a[index]; } else { retFunc = (a, b) => a[index] - b[index]; } break; default: retFunc = (a, b) => { const a1 = `${a[index]}`; const b1 = `${b[index]}`; if (a1 < b1) { return sortType === 'desc' ? 1 : -1; } if (a1 > b1) { return sortType === 'desc' ? -1 : 1; } return 0; }; } return retFunc; }
[ "function", "getSortFn", "(", "dataType", ",", "sortType", ",", "index", ")", "{", "let", "retFunc", ";", "switch", "(", "dataType", ")", "{", "case", "MeasureSubtype", ".", "CONTINUOUS", ":", "case", "DimensionSubtype", ".", "TEMPORAL", ":", "if", "(", "sortType", "===", "'desc'", ")", "{", "retFunc", "=", "(", "a", ",", "b", ")", "=>", "b", "[", "index", "]", "-", "a", "[", "index", "]", ";", "}", "else", "{", "retFunc", "=", "(", "a", ",", "b", ")", "=>", "a", "[", "index", "]", "-", "b", "[", "index", "]", ";", "}", "break", ";", "default", ":", "retFunc", "=", "(", "a", ",", "b", ")", "=>", "{", "const", "a1", "=", "`", "${", "a", "[", "index", "]", "}", "`", ";", "const", "b1", "=", "`", "${", "b", "[", "index", "]", "}", "`", ";", "if", "(", "a1", "<", "b1", ")", "{", "return", "sortType", "===", "'desc'", "?", "1", ":", "-", "1", ";", "}", "if", "(", "a1", ">", "b1", ")", "{", "return", "sortType", "===", "'desc'", "?", "-", "1", ":", "1", ";", "}", "return", "0", ";", "}", ";", "}", "return", "retFunc", ";", "}" ]
Generates the sorting functions to sort the data of a DataModel instance according to the input data type. @param {string} dataType - The data type e.g. 'measure', 'datetime' etc. @param {string} sortType - The sorting order i.e. 'asc' or 'desc'. @param {integer} index - The index of the data which will be sorted. @return {Function} Returns the the sorting function.
[ "Generates", "the", "sorting", "functions", "to", "sort", "the", "data", "of", "a", "DataModel", "instance", "according", "to", "the", "input", "data", "type", "." ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/operator/data-builder.js#L15-L40
19,055
chartshq/datamodel
src/operator/data-builder.js
groupData
function groupData(data, fieldIndex) { const hashMap = new Map(); const groupedData = []; data.forEach((datum) => { const fieldVal = datum[fieldIndex]; if (hashMap.has(fieldVal)) { groupedData[hashMap.get(fieldVal)][1].push(datum); } else { groupedData.push([fieldVal, [datum]]); hashMap.set(fieldVal, groupedData.length - 1); } }); return groupedData; }
javascript
function groupData(data, fieldIndex) { const hashMap = new Map(); const groupedData = []; data.forEach((datum) => { const fieldVal = datum[fieldIndex]; if (hashMap.has(fieldVal)) { groupedData[hashMap.get(fieldVal)][1].push(datum); } else { groupedData.push([fieldVal, [datum]]); hashMap.set(fieldVal, groupedData.length - 1); } }); return groupedData; }
[ "function", "groupData", "(", "data", ",", "fieldIndex", ")", "{", "const", "hashMap", "=", "new", "Map", "(", ")", ";", "const", "groupedData", "=", "[", "]", ";", "data", ".", "forEach", "(", "(", "datum", ")", "=>", "{", "const", "fieldVal", "=", "datum", "[", "fieldIndex", "]", ";", "if", "(", "hashMap", ".", "has", "(", "fieldVal", ")", ")", "{", "groupedData", "[", "hashMap", ".", "get", "(", "fieldVal", ")", "]", "[", "1", "]", ".", "push", "(", "datum", ")", ";", "}", "else", "{", "groupedData", ".", "push", "(", "[", "fieldVal", ",", "[", "datum", "]", "]", ")", ";", "hashMap", ".", "set", "(", "fieldVal", ",", "groupedData", ".", "length", "-", "1", ")", ";", "}", "}", ")", ";", "return", "groupedData", ";", "}" ]
Groups the data according to the specified target field. @param {Array} data - The input data array. @param {number} fieldIndex - The target field index within schema array. @return {Array} Returns an array containing the grouped data.
[ "Groups", "the", "data", "according", "to", "the", "specified", "target", "field", "." ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/operator/data-builder.js#L49-L64
19,056
chartshq/datamodel
src/operator/data-builder.js
createSortingFnArg
function createSortingFnArg(groupedDatum, targetFields, targetFieldDetails) { const arg = { label: groupedDatum[0] }; targetFields.reduce((acc, next, idx) => { acc[next] = groupedDatum[1].map(datum => datum[targetFieldDetails[idx].index]); return acc; }, arg); return arg; }
javascript
function createSortingFnArg(groupedDatum, targetFields, targetFieldDetails) { const arg = { label: groupedDatum[0] }; targetFields.reduce((acc, next, idx) => { acc[next] = groupedDatum[1].map(datum => datum[targetFieldDetails[idx].index]); return acc; }, arg); return arg; }
[ "function", "createSortingFnArg", "(", "groupedDatum", ",", "targetFields", ",", "targetFieldDetails", ")", "{", "const", "arg", "=", "{", "label", ":", "groupedDatum", "[", "0", "]", "}", ";", "targetFields", ".", "reduce", "(", "(", "acc", ",", "next", ",", "idx", ")", "=>", "{", "acc", "[", "next", "]", "=", "groupedDatum", "[", "1", "]", ".", "map", "(", "datum", "=>", "datum", "[", "targetFieldDetails", "[", "idx", "]", ".", "index", "]", ")", ";", "return", "acc", ";", "}", ",", "arg", ")", ";", "return", "arg", ";", "}" ]
Creates the argument value used for sorting function when sort is done with another fields. @param {Array} groupedDatum - The grouped datum for a single dimension field value. @param {Array} targetFields - An array of the sorting fields. @param {Array} targetFieldDetails - An array of the sorting field details in schema. @return {Object} Returns an object containing the value of sorting fields and the target field name.
[ "Creates", "the", "argument", "value", "used", "for", "sorting", "function", "when", "sort", "is", "done", "with", "another", "fields", "." ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/operator/data-builder.js#L75-L86
19,057
chartshq/datamodel
src/operator/data-builder.js
sortData
function sortData(dataObj, sortingDetails) { const { data, schema } = dataObj; let fieldName; let sortMeta; let fDetails; let i = sortingDetails.length - 1; for (; i >= 0; i--) { fieldName = sortingDetails[i][0]; sortMeta = sortingDetails[i][1]; fDetails = fieldInSchema(schema, fieldName); if (!fDetails) { // eslint-disable-next-line no-continue continue; } if (isCallable(sortMeta)) { // eslint-disable-next-line no-loop-func mergeSort(data, (a, b) => sortMeta(a[fDetails.index], b[fDetails.index])); } else if (isArray(sortMeta)) { const groupedData = groupData(data, fDetails.index); const sortingFn = sortMeta[sortMeta.length - 1]; const targetFields = sortMeta.slice(0, sortMeta.length - 1); const targetFieldDetails = targetFields.map(f => fieldInSchema(schema, f)); groupedData.forEach((groupedDatum) => { groupedDatum.push(createSortingFnArg(groupedDatum, targetFields, targetFieldDetails)); }); mergeSort(groupedData, (a, b) => { const m = a[2]; const n = b[2]; return sortingFn(m, n); }); // Empty the array data.length = 0; groupedData.forEach((datum) => { data.push(...datum[1]); }); } else { sortMeta = String(sortMeta).toLowerCase() === 'desc' ? 'desc' : 'asc'; mergeSort(data, getSortFn(fDetails.type, sortMeta, fDetails.index)); } } dataObj.uids = []; data.forEach((value) => { dataObj.uids.push(value.pop()); }); }
javascript
function sortData(dataObj, sortingDetails) { const { data, schema } = dataObj; let fieldName; let sortMeta; let fDetails; let i = sortingDetails.length - 1; for (; i >= 0; i--) { fieldName = sortingDetails[i][0]; sortMeta = sortingDetails[i][1]; fDetails = fieldInSchema(schema, fieldName); if (!fDetails) { // eslint-disable-next-line no-continue continue; } if (isCallable(sortMeta)) { // eslint-disable-next-line no-loop-func mergeSort(data, (a, b) => sortMeta(a[fDetails.index], b[fDetails.index])); } else if (isArray(sortMeta)) { const groupedData = groupData(data, fDetails.index); const sortingFn = sortMeta[sortMeta.length - 1]; const targetFields = sortMeta.slice(0, sortMeta.length - 1); const targetFieldDetails = targetFields.map(f => fieldInSchema(schema, f)); groupedData.forEach((groupedDatum) => { groupedDatum.push(createSortingFnArg(groupedDatum, targetFields, targetFieldDetails)); }); mergeSort(groupedData, (a, b) => { const m = a[2]; const n = b[2]; return sortingFn(m, n); }); // Empty the array data.length = 0; groupedData.forEach((datum) => { data.push(...datum[1]); }); } else { sortMeta = String(sortMeta).toLowerCase() === 'desc' ? 'desc' : 'asc'; mergeSort(data, getSortFn(fDetails.type, sortMeta, fDetails.index)); } } dataObj.uids = []; data.forEach((value) => { dataObj.uids.push(value.pop()); }); }
[ "function", "sortData", "(", "dataObj", ",", "sortingDetails", ")", "{", "const", "{", "data", ",", "schema", "}", "=", "dataObj", ";", "let", "fieldName", ";", "let", "sortMeta", ";", "let", "fDetails", ";", "let", "i", "=", "sortingDetails", ".", "length", "-", "1", ";", "for", "(", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "fieldName", "=", "sortingDetails", "[", "i", "]", "[", "0", "]", ";", "sortMeta", "=", "sortingDetails", "[", "i", "]", "[", "1", "]", ";", "fDetails", "=", "fieldInSchema", "(", "schema", ",", "fieldName", ")", ";", "if", "(", "!", "fDetails", ")", "{", "// eslint-disable-next-line no-continue", "continue", ";", "}", "if", "(", "isCallable", "(", "sortMeta", ")", ")", "{", "// eslint-disable-next-line no-loop-func", "mergeSort", "(", "data", ",", "(", "a", ",", "b", ")", "=>", "sortMeta", "(", "a", "[", "fDetails", ".", "index", "]", ",", "b", "[", "fDetails", ".", "index", "]", ")", ")", ";", "}", "else", "if", "(", "isArray", "(", "sortMeta", ")", ")", "{", "const", "groupedData", "=", "groupData", "(", "data", ",", "fDetails", ".", "index", ")", ";", "const", "sortingFn", "=", "sortMeta", "[", "sortMeta", ".", "length", "-", "1", "]", ";", "const", "targetFields", "=", "sortMeta", ".", "slice", "(", "0", ",", "sortMeta", ".", "length", "-", "1", ")", ";", "const", "targetFieldDetails", "=", "targetFields", ".", "map", "(", "f", "=>", "fieldInSchema", "(", "schema", ",", "f", ")", ")", ";", "groupedData", ".", "forEach", "(", "(", "groupedDatum", ")", "=>", "{", "groupedDatum", ".", "push", "(", "createSortingFnArg", "(", "groupedDatum", ",", "targetFields", ",", "targetFieldDetails", ")", ")", ";", "}", ")", ";", "mergeSort", "(", "groupedData", ",", "(", "a", ",", "b", ")", "=>", "{", "const", "m", "=", "a", "[", "2", "]", ";", "const", "n", "=", "b", "[", "2", "]", ";", "return", "sortingFn", "(", "m", ",", "n", ")", ";", "}", ")", ";", "// Empty the array", "data", ".", "length", "=", "0", ";", "groupedData", ".", "forEach", "(", "(", "datum", ")", "=>", "{", "data", ".", "push", "(", "...", "datum", "[", "1", "]", ")", ";", "}", ")", ";", "}", "else", "{", "sortMeta", "=", "String", "(", "sortMeta", ")", ".", "toLowerCase", "(", ")", "===", "'desc'", "?", "'desc'", ":", "'asc'", ";", "mergeSort", "(", "data", ",", "getSortFn", "(", "fDetails", ".", "type", ",", "sortMeta", ",", "fDetails", ".", "index", ")", ")", ";", "}", "}", "dataObj", ".", "uids", "=", "[", "]", ";", "data", ".", "forEach", "(", "(", "value", ")", "=>", "{", "dataObj", ".", "uids", ".", "push", "(", "value", ".", "pop", "(", ")", ")", ";", "}", ")", ";", "}" ]
Sorts the data before return in dataBuilder. @param {Object} dataObj - An object containing the data and schema. @param {Array} sortingDetails - An array containing the sorting configs.
[ "Sorts", "the", "data", "before", "return", "in", "dataBuilder", "." ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/operator/data-builder.js#L94-L145
19,058
chartshq/datamodel
src/operator/merge-sort.js
defSortFn
function defSortFn (a, b) { const a1 = `${a}`; const b1 = `${b}`; if (a1 < b1) { return -1; } if (a1 > b1) { return 1; } return 0; }
javascript
function defSortFn (a, b) { const a1 = `${a}`; const b1 = `${b}`; if (a1 < b1) { return -1; } if (a1 > b1) { return 1; } return 0; }
[ "function", "defSortFn", "(", "a", ",", "b", ")", "{", "const", "a1", "=", "`", "${", "a", "}", "`", ";", "const", "b1", "=", "`", "${", "b", "}", "`", ";", "if", "(", "a1", "<", "b1", ")", "{", "return", "-", "1", ";", "}", "if", "(", "a1", ">", "b1", ")", "{", "return", "1", ";", "}", "return", "0", ";", "}" ]
The default sort function. @param {*} a - The first value. @param {*} b - The second value. @return {number} Returns the comparison result e.g. 1 or 0 or -1.
[ "The", "default", "sort", "function", "." ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/operator/merge-sort.js#L8-L18
19,059
chartshq/datamodel
src/operator/merge-sort.js
merge
function merge (arr, lo, mid, hi, sortFn) { const mainArr = arr; const auxArr = []; for (let i = lo; i <= hi; i += 1) { auxArr[i] = mainArr[i]; } let a = lo; let b = mid + 1; for (let i = lo; i <= hi; i += 1) { if (a > mid) { mainArr[i] = auxArr[b]; b += 1; } else if (b > hi) { mainArr[i] = auxArr[a]; a += 1; } else if (sortFn(auxArr[a], auxArr[b]) <= 0) { mainArr[i] = auxArr[a]; a += 1; } else { mainArr[i] = auxArr[b]; b += 1; } } }
javascript
function merge (arr, lo, mid, hi, sortFn) { const mainArr = arr; const auxArr = []; for (let i = lo; i <= hi; i += 1) { auxArr[i] = mainArr[i]; } let a = lo; let b = mid + 1; for (let i = lo; i <= hi; i += 1) { if (a > mid) { mainArr[i] = auxArr[b]; b += 1; } else if (b > hi) { mainArr[i] = auxArr[a]; a += 1; } else if (sortFn(auxArr[a], auxArr[b]) <= 0) { mainArr[i] = auxArr[a]; a += 1; } else { mainArr[i] = auxArr[b]; b += 1; } } }
[ "function", "merge", "(", "arr", ",", "lo", ",", "mid", ",", "hi", ",", "sortFn", ")", "{", "const", "mainArr", "=", "arr", ";", "const", "auxArr", "=", "[", "]", ";", "for", "(", "let", "i", "=", "lo", ";", "i", "<=", "hi", ";", "i", "+=", "1", ")", "{", "auxArr", "[", "i", "]", "=", "mainArr", "[", "i", "]", ";", "}", "let", "a", "=", "lo", ";", "let", "b", "=", "mid", "+", "1", ";", "for", "(", "let", "i", "=", "lo", ";", "i", "<=", "hi", ";", "i", "+=", "1", ")", "{", "if", "(", "a", ">", "mid", ")", "{", "mainArr", "[", "i", "]", "=", "auxArr", "[", "b", "]", ";", "b", "+=", "1", ";", "}", "else", "if", "(", "b", ">", "hi", ")", "{", "mainArr", "[", "i", "]", "=", "auxArr", "[", "a", "]", ";", "a", "+=", "1", ";", "}", "else", "if", "(", "sortFn", "(", "auxArr", "[", "a", "]", ",", "auxArr", "[", "b", "]", ")", "<=", "0", ")", "{", "mainArr", "[", "i", "]", "=", "auxArr", "[", "a", "]", ";", "a", "+=", "1", ";", "}", "else", "{", "mainArr", "[", "i", "]", "=", "auxArr", "[", "b", "]", ";", "b", "+=", "1", ";", "}", "}", "}" ]
The helper function for merge sort which creates the sorted array from the two halves of the input array. @param {Array} arr - The target array which needs to be merged. @param {number} lo - The starting index of the first array half. @param {number} mid - The ending index of the first array half. @param {number} hi - The ending index of the second array half. @param {Function} sortFn - The sort function.
[ "The", "helper", "function", "for", "merge", "sort", "which", "creates", "the", "sorted", "array", "from", "the", "two", "halves", "of", "the", "input", "array", "." ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/operator/merge-sort.js#L30-L54
19,060
chartshq/datamodel
src/operator/merge-sort.js
sort
function sort (arr, lo, hi, sortFn) { if (hi === lo) { return arr; } const mid = lo + Math.floor((hi - lo) / 2); sort(arr, lo, mid, sortFn); sort(arr, mid + 1, hi, sortFn); merge(arr, lo, mid, hi, sortFn); return arr; }
javascript
function sort (arr, lo, hi, sortFn) { if (hi === lo) { return arr; } const mid = lo + Math.floor((hi - lo) / 2); sort(arr, lo, mid, sortFn); sort(arr, mid + 1, hi, sortFn); merge(arr, lo, mid, hi, sortFn); return arr; }
[ "function", "sort", "(", "arr", ",", "lo", ",", "hi", ",", "sortFn", ")", "{", "if", "(", "hi", "===", "lo", ")", "{", "return", "arr", ";", "}", "const", "mid", "=", "lo", "+", "Math", ".", "floor", "(", "(", "hi", "-", "lo", ")", "/", "2", ")", ";", "sort", "(", "arr", ",", "lo", ",", "mid", ",", "sortFn", ")", ";", "sort", "(", "arr", ",", "mid", "+", "1", ",", "hi", ",", "sortFn", ")", ";", "merge", "(", "arr", ",", "lo", ",", "mid", ",", "hi", ",", "sortFn", ")", ";", "return", "arr", ";", "}" ]
The helper function for merge sort which would be called recursively for sorting the array halves. @param {Array} arr - The target array which needs to be sorted. @param {number} lo - The starting index of the array half. @param {number} hi - The ending index of the array half. @param {Function} sortFn - The sort function. @return {Array} Returns the target array itself.
[ "The", "helper", "function", "for", "merge", "sort", "which", "would", "be", "called", "recursively", "for", "sorting", "the", "array", "halves", "." ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/operator/merge-sort.js#L66-L75
19,061
chartshq/datamodel
src/operator/group-by.js
getFieldArr
function getFieldArr (dataModel, fieldArr) { const retArr = []; const fieldStore = dataModel.getFieldspace(); const dimensions = fieldStore.getDimension(); Object.entries(dimensions).forEach(([key]) => { if (fieldArr && fieldArr.length) { if (fieldArr.indexOf(key) !== -1) { retArr.push(key); } } else { retArr.push(key); } }); return retArr; }
javascript
function getFieldArr (dataModel, fieldArr) { const retArr = []; const fieldStore = dataModel.getFieldspace(); const dimensions = fieldStore.getDimension(); Object.entries(dimensions).forEach(([key]) => { if (fieldArr && fieldArr.length) { if (fieldArr.indexOf(key) !== -1) { retArr.push(key); } } else { retArr.push(key); } }); return retArr; }
[ "function", "getFieldArr", "(", "dataModel", ",", "fieldArr", ")", "{", "const", "retArr", "=", "[", "]", ";", "const", "fieldStore", "=", "dataModel", ".", "getFieldspace", "(", ")", ";", "const", "dimensions", "=", "fieldStore", ".", "getDimension", "(", ")", ";", "Object", ".", "entries", "(", "dimensions", ")", ".", "forEach", "(", "(", "[", "key", "]", ")", "=>", "{", "if", "(", "fieldArr", "&&", "fieldArr", ".", "length", ")", "{", "if", "(", "fieldArr", ".", "indexOf", "(", "key", ")", "!==", "-", "1", ")", "{", "retArr", ".", "push", "(", "key", ")", ";", "}", "}", "else", "{", "retArr", ".", "push", "(", "key", ")", ";", "}", "}", ")", ";", "return", "retArr", ";", "}" ]
This function sanitize the user given field and return a common Array structure field list @param {DataModel} dataModel the dataModel operating on @param {Array} fieldArr user input of field Array @return {Array} arrays of field name
[ "This", "function", "sanitize", "the", "user", "given", "field", "and", "return", "a", "common", "Array", "structure", "field", "list" ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/operator/group-by.js#L15-L31
19,062
chartshq/datamodel
src/operator/group-by.js
getReducerObj
function getReducerObj (dataModel, reducers = {}) { const retObj = {}; const fieldStore = dataModel.getFieldspace(); const measures = fieldStore.getMeasure(); const defReducer = reducerStore.defaultReducer(); Object.keys(measures).forEach((measureName) => { if (typeof reducers[measureName] !== 'string') { reducers[measureName] = measures[measureName].defAggFn(); } const reducerFn = reducerStore.resolve(reducers[measureName]); if (reducerFn) { retObj[measureName] = reducerFn; } else { retObj[measureName] = defReducer; reducers[measureName] = defaultReducerName; } }); return retObj; }
javascript
function getReducerObj (dataModel, reducers = {}) { const retObj = {}; const fieldStore = dataModel.getFieldspace(); const measures = fieldStore.getMeasure(); const defReducer = reducerStore.defaultReducer(); Object.keys(measures).forEach((measureName) => { if (typeof reducers[measureName] !== 'string') { reducers[measureName] = measures[measureName].defAggFn(); } const reducerFn = reducerStore.resolve(reducers[measureName]); if (reducerFn) { retObj[measureName] = reducerFn; } else { retObj[measureName] = defReducer; reducers[measureName] = defaultReducerName; } }); return retObj; }
[ "function", "getReducerObj", "(", "dataModel", ",", "reducers", "=", "{", "}", ")", "{", "const", "retObj", "=", "{", "}", ";", "const", "fieldStore", "=", "dataModel", ".", "getFieldspace", "(", ")", ";", "const", "measures", "=", "fieldStore", ".", "getMeasure", "(", ")", ";", "const", "defReducer", "=", "reducerStore", ".", "defaultReducer", "(", ")", ";", "Object", ".", "keys", "(", "measures", ")", ".", "forEach", "(", "(", "measureName", ")", "=>", "{", "if", "(", "typeof", "reducers", "[", "measureName", "]", "!==", "'string'", ")", "{", "reducers", "[", "measureName", "]", "=", "measures", "[", "measureName", "]", ".", "defAggFn", "(", ")", ";", "}", "const", "reducerFn", "=", "reducerStore", ".", "resolve", "(", "reducers", "[", "measureName", "]", ")", ";", "if", "(", "reducerFn", ")", "{", "retObj", "[", "measureName", "]", "=", "reducerFn", ";", "}", "else", "{", "retObj", "[", "measureName", "]", "=", "defReducer", ";", "reducers", "[", "measureName", "]", "=", "defaultReducerName", ";", "}", "}", ")", ";", "return", "retObj", ";", "}" ]
This sanitize the reducer provide by the user and create a common type of object. user can give function Also @param {DataModel} dataModel dataModel to worked on @param {Object|function} [reducers={}] reducer provided by the users @return {Object} object containing reducer function for every measure
[ "This", "sanitize", "the", "reducer", "provide", "by", "the", "user", "and", "create", "a", "common", "type", "of", "object", ".", "user", "can", "give", "function", "Also" ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/operator/group-by.js#L40-L59
19,063
chartshq/datamodel
src/operator/group-by.js
groupBy
function groupBy (dataModel, fieldArr, reducers, existingDataModel) { const sFieldArr = getFieldArr(dataModel, fieldArr); const reducerObj = getReducerObj(dataModel, reducers); const fieldStore = dataModel.getFieldspace(); const fieldStoreObj = fieldStore.fieldsObj(); const dbName = fieldStore.name; const dimensionArr = []; const measureArr = []; const schema = []; const hashMap = {}; const data = []; let newDataModel; // Prepare the schema Object.entries(fieldStoreObj).forEach(([key, value]) => { if (sFieldArr.indexOf(key) !== -1 || reducerObj[key]) { schema.push(extend2({}, value.schema())); switch (value.schema().type) { case FieldType.MEASURE: measureArr.push(key); break; default: case FieldType.DIMENSION: dimensionArr.push(key); } } }); // Prepare the data let rowCount = 0; rowDiffsetIterator(dataModel._rowDiffset, (i) => { let hash = ''; dimensionArr.forEach((_) => { hash = `${hash}-${fieldStoreObj[_].partialField.data[i]}`; }); if (hashMap[hash] === undefined) { hashMap[hash] = rowCount; data.push({}); dimensionArr.forEach((_) => { data[rowCount][_] = fieldStoreObj[_].partialField.data[i]; }); measureArr.forEach((_) => { data[rowCount][_] = [fieldStoreObj[_].partialField.data[i]]; }); rowCount += 1; } else { measureArr.forEach((_) => { data[hashMap[hash]][_].push(fieldStoreObj[_].partialField.data[i]); }); } }); // reduction let cachedStore = {}; let cloneProvider = () => dataModel.detachedRoot(); data.forEach((row) => { const tuple = row; measureArr.forEach((_) => { tuple[_] = reducerObj[_](row[_], cloneProvider, cachedStore); }); }); if (existingDataModel) { existingDataModel.__calculateFieldspace(); newDataModel = existingDataModel; } else { newDataModel = new DataModel(data, schema, { name: dbName }); } return newDataModel; }
javascript
function groupBy (dataModel, fieldArr, reducers, existingDataModel) { const sFieldArr = getFieldArr(dataModel, fieldArr); const reducerObj = getReducerObj(dataModel, reducers); const fieldStore = dataModel.getFieldspace(); const fieldStoreObj = fieldStore.fieldsObj(); const dbName = fieldStore.name; const dimensionArr = []; const measureArr = []; const schema = []; const hashMap = {}; const data = []; let newDataModel; // Prepare the schema Object.entries(fieldStoreObj).forEach(([key, value]) => { if (sFieldArr.indexOf(key) !== -1 || reducerObj[key]) { schema.push(extend2({}, value.schema())); switch (value.schema().type) { case FieldType.MEASURE: measureArr.push(key); break; default: case FieldType.DIMENSION: dimensionArr.push(key); } } }); // Prepare the data let rowCount = 0; rowDiffsetIterator(dataModel._rowDiffset, (i) => { let hash = ''; dimensionArr.forEach((_) => { hash = `${hash}-${fieldStoreObj[_].partialField.data[i]}`; }); if (hashMap[hash] === undefined) { hashMap[hash] = rowCount; data.push({}); dimensionArr.forEach((_) => { data[rowCount][_] = fieldStoreObj[_].partialField.data[i]; }); measureArr.forEach((_) => { data[rowCount][_] = [fieldStoreObj[_].partialField.data[i]]; }); rowCount += 1; } else { measureArr.forEach((_) => { data[hashMap[hash]][_].push(fieldStoreObj[_].partialField.data[i]); }); } }); // reduction let cachedStore = {}; let cloneProvider = () => dataModel.detachedRoot(); data.forEach((row) => { const tuple = row; measureArr.forEach((_) => { tuple[_] = reducerObj[_](row[_], cloneProvider, cachedStore); }); }); if (existingDataModel) { existingDataModel.__calculateFieldspace(); newDataModel = existingDataModel; } else { newDataModel = new DataModel(data, schema, { name: dbName }); } return newDataModel; }
[ "function", "groupBy", "(", "dataModel", ",", "fieldArr", ",", "reducers", ",", "existingDataModel", ")", "{", "const", "sFieldArr", "=", "getFieldArr", "(", "dataModel", ",", "fieldArr", ")", ";", "const", "reducerObj", "=", "getReducerObj", "(", "dataModel", ",", "reducers", ")", ";", "const", "fieldStore", "=", "dataModel", ".", "getFieldspace", "(", ")", ";", "const", "fieldStoreObj", "=", "fieldStore", ".", "fieldsObj", "(", ")", ";", "const", "dbName", "=", "fieldStore", ".", "name", ";", "const", "dimensionArr", "=", "[", "]", ";", "const", "measureArr", "=", "[", "]", ";", "const", "schema", "=", "[", "]", ";", "const", "hashMap", "=", "{", "}", ";", "const", "data", "=", "[", "]", ";", "let", "newDataModel", ";", "// Prepare the schema", "Object", ".", "entries", "(", "fieldStoreObj", ")", ".", "forEach", "(", "(", "[", "key", ",", "value", "]", ")", "=>", "{", "if", "(", "sFieldArr", ".", "indexOf", "(", "key", ")", "!==", "-", "1", "||", "reducerObj", "[", "key", "]", ")", "{", "schema", ".", "push", "(", "extend2", "(", "{", "}", ",", "value", ".", "schema", "(", ")", ")", ")", ";", "switch", "(", "value", ".", "schema", "(", ")", ".", "type", ")", "{", "case", "FieldType", ".", "MEASURE", ":", "measureArr", ".", "push", "(", "key", ")", ";", "break", ";", "default", ":", "case", "FieldType", ".", "DIMENSION", ":", "dimensionArr", ".", "push", "(", "key", ")", ";", "}", "}", "}", ")", ";", "// Prepare the data", "let", "rowCount", "=", "0", ";", "rowDiffsetIterator", "(", "dataModel", ".", "_rowDiffset", ",", "(", "i", ")", "=>", "{", "let", "hash", "=", "''", ";", "dimensionArr", ".", "forEach", "(", "(", "_", ")", "=>", "{", "hash", "=", "`", "${", "hash", "}", "${", "fieldStoreObj", "[", "_", "]", ".", "partialField", ".", "data", "[", "i", "]", "}", "`", ";", "}", ")", ";", "if", "(", "hashMap", "[", "hash", "]", "===", "undefined", ")", "{", "hashMap", "[", "hash", "]", "=", "rowCount", ";", "data", ".", "push", "(", "{", "}", ")", ";", "dimensionArr", ".", "forEach", "(", "(", "_", ")", "=>", "{", "data", "[", "rowCount", "]", "[", "_", "]", "=", "fieldStoreObj", "[", "_", "]", ".", "partialField", ".", "data", "[", "i", "]", ";", "}", ")", ";", "measureArr", ".", "forEach", "(", "(", "_", ")", "=>", "{", "data", "[", "rowCount", "]", "[", "_", "]", "=", "[", "fieldStoreObj", "[", "_", "]", ".", "partialField", ".", "data", "[", "i", "]", "]", ";", "}", ")", ";", "rowCount", "+=", "1", ";", "}", "else", "{", "measureArr", ".", "forEach", "(", "(", "_", ")", "=>", "{", "data", "[", "hashMap", "[", "hash", "]", "]", "[", "_", "]", ".", "push", "(", "fieldStoreObj", "[", "_", "]", ".", "partialField", ".", "data", "[", "i", "]", ")", ";", "}", ")", ";", "}", "}", ")", ";", "// reduction", "let", "cachedStore", "=", "{", "}", ";", "let", "cloneProvider", "=", "(", ")", "=>", "dataModel", ".", "detachedRoot", "(", ")", ";", "data", ".", "forEach", "(", "(", "row", ")", "=>", "{", "const", "tuple", "=", "row", ";", "measureArr", ".", "forEach", "(", "(", "_", ")", "=>", "{", "tuple", "[", "_", "]", "=", "reducerObj", "[", "_", "]", "(", "row", "[", "_", "]", ",", "cloneProvider", ",", "cachedStore", ")", ";", "}", ")", ";", "}", ")", ";", "if", "(", "existingDataModel", ")", "{", "existingDataModel", ".", "__calculateFieldspace", "(", ")", ";", "newDataModel", "=", "existingDataModel", ";", "}", "else", "{", "newDataModel", "=", "new", "DataModel", "(", "data", ",", "schema", ",", "{", "name", ":", "dbName", "}", ")", ";", "}", "return", "newDataModel", ";", "}" ]
main function which perform the group-by operations which reduce the measures value is the fields are common according to the reducer function provided @param {DataModel} dataModel the dataModel to worked @param {Array} fieldArr fields according to which the groupby should be worked @param {Object|Function} reducers reducers function @param {DataModel} existingDataModel Existing datamodel instance @return {DataModel} new dataModel with the group by
[ "main", "function", "which", "perform", "the", "group", "-", "by", "operations", "which", "reduce", "the", "measures", "value", "is", "the", "fields", "are", "common", "according", "to", "the", "reducer", "function", "provided" ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/operator/group-by.js#L70-L139
19,064
chartshq/datamodel
src/converter/flat-json.js
FlatJSON
function FlatJSON (arr) { const header = {}; let i = 0; let insertionIndex; const columns = []; const push = columnMajor(columns); arr.forEach((item) => { const fields = []; for (let key in item) { if (key in header) { insertionIndex = header[key]; } else { header[key] = i++; insertionIndex = i - 1; } fields[insertionIndex] = item[key]; } push(...fields); }); return [Object.keys(header), columns]; }
javascript
function FlatJSON (arr) { const header = {}; let i = 0; let insertionIndex; const columns = []; const push = columnMajor(columns); arr.forEach((item) => { const fields = []; for (let key in item) { if (key in header) { insertionIndex = header[key]; } else { header[key] = i++; insertionIndex = i - 1; } fields[insertionIndex] = item[key]; } push(...fields); }); return [Object.keys(header), columns]; }
[ "function", "FlatJSON", "(", "arr", ")", "{", "const", "header", "=", "{", "}", ";", "let", "i", "=", "0", ";", "let", "insertionIndex", ";", "const", "columns", "=", "[", "]", ";", "const", "push", "=", "columnMajor", "(", "columns", ")", ";", "arr", ".", "forEach", "(", "(", "item", ")", "=>", "{", "const", "fields", "=", "[", "]", ";", "for", "(", "let", "key", "in", "item", ")", "{", "if", "(", "key", "in", "header", ")", "{", "insertionIndex", "=", "header", "[", "key", "]", ";", "}", "else", "{", "header", "[", "key", "]", "=", "i", "++", ";", "insertionIndex", "=", "i", "-", "1", ";", "}", "fields", "[", "insertionIndex", "]", "=", "item", "[", "key", "]", ";", "}", "push", "(", "...", "fields", ")", ";", "}", ")", ";", "return", "[", "Object", ".", "keys", "(", "header", ")", ",", "columns", "]", ";", "}" ]
Parses and converts data formatted in JSON to a manageable internal format. @param {Array.<Object>} arr - The input data formatted in JSON. @return {Array.<Object>} Returns an array of headers and column major data. @example // Sample input data: const data = [ { "a": 1, "b": 2, "c": 3 }, { "a": 4, "b": 5, "c": 6 }, { "a": 7, "b": 8, "c": 9 } ];
[ "Parses", "and", "converts", "data", "formatted", "in", "JSON", "to", "a", "manageable", "internal", "format", "." ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/converter/flat-json.js#L29-L51
19,065
chartshq/datamodel
src/helper.js
prepareSelectionData
function prepareSelectionData (fields, i) { const resp = {}; for (let field of fields) { resp[field.name()] = new Value(field.partialField.data[i], field); } return resp; }
javascript
function prepareSelectionData (fields, i) { const resp = {}; for (let field of fields) { resp[field.name()] = new Value(field.partialField.data[i], field); } return resp; }
[ "function", "prepareSelectionData", "(", "fields", ",", "i", ")", "{", "const", "resp", "=", "{", "}", ";", "for", "(", "let", "field", "of", "fields", ")", "{", "resp", "[", "field", ".", "name", "(", ")", "]", "=", "new", "Value", "(", "field", ".", "partialField", ".", "data", "[", "i", "]", ",", "field", ")", ";", "}", "return", "resp", ";", "}" ]
Prepares the selection data.
[ "Prepares", "the", "selection", "data", "." ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/helper.js#L16-L22
19,066
chartshq/datamodel
src/converter/dsv-arr.js
DSVArr
function DSVArr (arr, options) { const defaultOption = { firstRowHeader: true, }; options = Object.assign({}, defaultOption, options); let header; const columns = []; const push = columnMajor(columns); if (options.firstRowHeader) { // If header present then mutate the array. // Do in-place mutation to save space. header = arr.splice(0, 1)[0]; } else { header = []; } arr.forEach(field => push(...field)); return [header, columns]; }
javascript
function DSVArr (arr, options) { const defaultOption = { firstRowHeader: true, }; options = Object.assign({}, defaultOption, options); let header; const columns = []; const push = columnMajor(columns); if (options.firstRowHeader) { // If header present then mutate the array. // Do in-place mutation to save space. header = arr.splice(0, 1)[0]; } else { header = []; } arr.forEach(field => push(...field)); return [header, columns]; }
[ "function", "DSVArr", "(", "arr", ",", "options", ")", "{", "const", "defaultOption", "=", "{", "firstRowHeader", ":", "true", ",", "}", ";", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "defaultOption", ",", "options", ")", ";", "let", "header", ";", "const", "columns", "=", "[", "]", ";", "const", "push", "=", "columnMajor", "(", "columns", ")", ";", "if", "(", "options", ".", "firstRowHeader", ")", "{", "// If header present then mutate the array.", "// Do in-place mutation to save space.", "header", "=", "arr", ".", "splice", "(", "0", ",", "1", ")", "[", "0", "]", ";", "}", "else", "{", "header", "=", "[", "]", ";", "}", "arr", ".", "forEach", "(", "field", "=>", "push", "(", "...", "field", ")", ")", ";", "return", "[", "header", ",", "columns", "]", ";", "}" ]
Parses and converts data formatted in DSV array to a manageable internal format. @param {Array.<Array>} arr - A 2D array containing of the DSV data. @param {Object} options - Option to control the behaviour of the parsing. @param {boolean} [options.firstRowHeader=true] - Whether the first row of the dsv data is header or not. @return {Array} Returns an array of headers and column major data. @example // Sample input data: const data = [ ["a", "b", "c"], [1, 2, 3], [4, 5, 6], [7, 8, 9] ];
[ "Parses", "and", "converts", "data", "formatted", "in", "DSV", "array", "to", "a", "manageable", "internal", "format", "." ]
cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e
https://github.com/chartshq/datamodel/blob/cb2c3df2c31cdbfbcc22ddf3856c61178bbcc28e/src/converter/dsv-arr.js#L20-L41
19,067
pelias/whosonfirst
src/components/extractFields.js
getLanguages
function getLanguages(properties) { if (!Array.isArray(properties['wof:lang_x_official'])) { return []; } return properties['wof:lang_x_official'] .filter(l => (typeof l === 'string' && l.length === 3)) .map(l => l.toLowerCase()); }
javascript
function getLanguages(properties) { if (!Array.isArray(properties['wof:lang_x_official'])) { return []; } return properties['wof:lang_x_official'] .filter(l => (typeof l === 'string' && l.length === 3)) .map(l => l.toLowerCase()); }
[ "function", "getLanguages", "(", "properties", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "properties", "[", "'wof:lang_x_official'", "]", ")", ")", "{", "return", "[", "]", ";", "}", "return", "properties", "[", "'wof:lang_x_official'", "]", ".", "filter", "(", "l", "=>", "(", "typeof", "l", "===", "'string'", "&&", "l", ".", "length", "===", "3", ")", ")", ".", "map", "(", "l", "=>", "l", ".", "toLowerCase", "(", ")", ")", ";", "}" ]
get an array of language codes spoken at this location
[ "get", "an", "array", "of", "language", "codes", "spoken", "at", "this", "location" ]
56fdb2f00ad0c97510ea44166aaee5d8b0cc334a
https://github.com/pelias/whosonfirst/blob/56fdb2f00ad0c97510ea44166aaee5d8b0cc334a/src/components/extractFields.js#L71-L78
19,068
pelias/whosonfirst
src/components/extractFields.js
concatArrayFields
function concatArrayFields(properties, fields){ let arr = []; fields.forEach(field => { if (Array.isArray(properties[field]) && properties[field].length) { arr = arr.concat(properties[field]); } }); // dedupe array return arr.filter((item, pos, self) => self.indexOf(item) === pos); }
javascript
function concatArrayFields(properties, fields){ let arr = []; fields.forEach(field => { if (Array.isArray(properties[field]) && properties[field].length) { arr = arr.concat(properties[field]); } }); // dedupe array return arr.filter((item, pos, self) => self.indexOf(item) === pos); }
[ "function", "concatArrayFields", "(", "properties", ",", "fields", ")", "{", "let", "arr", "=", "[", "]", ";", "fields", ".", "forEach", "(", "field", "=>", "{", "if", "(", "Array", ".", "isArray", "(", "properties", "[", "field", "]", ")", "&&", "properties", "[", "field", "]", ".", "length", ")", "{", "arr", "=", "arr", ".", "concat", "(", "properties", "[", "field", "]", ")", ";", "}", "}", ")", ";", "// dedupe array", "return", "arr", ".", "filter", "(", "(", "item", ",", "pos", ",", "self", ")", "=>", "self", ".", "indexOf", "(", "item", ")", "===", "pos", ")", ";", "}" ]
convenience function to safely concat array fields
[ "convenience", "function", "to", "safely", "concat", "array", "fields" ]
56fdb2f00ad0c97510ea44166aaee5d8b0cc334a
https://github.com/pelias/whosonfirst/blob/56fdb2f00ad0c97510ea44166aaee5d8b0cc334a/src/components/extractFields.js#L81-L90
19,069
pelias/whosonfirst
utils/sqlite_extract_data.js
extractDB
function extractDB( dbpath ){ let targetWofIds = Array.isArray(config.importPlace) ? config.importPlace: [config.importPlace]; // connect to sql db let db = new Sqlite3( dbpath, { readonly: true } ); // convert ids to integers and remove any which fail to convert let cleanIds = targetWofIds.map(id => parseInt(id, 10)).filter(id => !isNaN(id)); // placefilter is used to select only records targeted by the 'importPlace' config option // note: if no 'importPlace' ids are provided then we process all ids which aren't 0 let placefilter = (cleanIds.length > 0) ? sql.placefilter : '!= 0'; // note: we need to use replace instead of bound params in order to be able // to query an array of values using IN. let dataQuery = sql.data.replace(/@placefilter/g, placefilter).replace(/@wofids/g, cleanIds.join(',')); let metaQuery = sql.meta.replace(/@placefilter/g, placefilter).replace(/@wofids/g, cleanIds.join(',')); // extract all data to disk for( let row of db.prepare(dataQuery).iterate() ){ if( 'postalcode' === row.placetype && true !== config.importPostalcodes ){ return; } if( 'venue' === row.placetype && true !== config.importVenues ){ return; } if( 'constituency' === row.placetype && true !== config.importConstituencies ){ return; } if( 'intersection' === row.placetype && true !== config.importIntersections ){ return; } writeJson( row ); } // write meta data to disk for( let row of db.prepare(metaQuery).iterate() ){ if( 'postalcode' === row.placetype && true !== config.importPostalcodes ){ return; } if( 'venue' === row.placetype && true !== config.importVenues ){ return; } if( 'constituency' === row.placetype && true !== config.importConstituencies ){ return; } if( 'intersection' === row.placetype && true !== config.importIntersections ){ return; } if( !row.hasOwnProperty('path') ){ // ensure path property is present (required by some importers) row.path = wofIdToPath(row.id).concat(row.id+'.geojson').join(path.sep); } metafiles.write( row ); } // close connection db.close(); }
javascript
function extractDB( dbpath ){ let targetWofIds = Array.isArray(config.importPlace) ? config.importPlace: [config.importPlace]; // connect to sql db let db = new Sqlite3( dbpath, { readonly: true } ); // convert ids to integers and remove any which fail to convert let cleanIds = targetWofIds.map(id => parseInt(id, 10)).filter(id => !isNaN(id)); // placefilter is used to select only records targeted by the 'importPlace' config option // note: if no 'importPlace' ids are provided then we process all ids which aren't 0 let placefilter = (cleanIds.length > 0) ? sql.placefilter : '!= 0'; // note: we need to use replace instead of bound params in order to be able // to query an array of values using IN. let dataQuery = sql.data.replace(/@placefilter/g, placefilter).replace(/@wofids/g, cleanIds.join(',')); let metaQuery = sql.meta.replace(/@placefilter/g, placefilter).replace(/@wofids/g, cleanIds.join(',')); // extract all data to disk for( let row of db.prepare(dataQuery).iterate() ){ if( 'postalcode' === row.placetype && true !== config.importPostalcodes ){ return; } if( 'venue' === row.placetype && true !== config.importVenues ){ return; } if( 'constituency' === row.placetype && true !== config.importConstituencies ){ return; } if( 'intersection' === row.placetype && true !== config.importIntersections ){ return; } writeJson( row ); } // write meta data to disk for( let row of db.prepare(metaQuery).iterate() ){ if( 'postalcode' === row.placetype && true !== config.importPostalcodes ){ return; } if( 'venue' === row.placetype && true !== config.importVenues ){ return; } if( 'constituency' === row.placetype && true !== config.importConstituencies ){ return; } if( 'intersection' === row.placetype && true !== config.importIntersections ){ return; } if( !row.hasOwnProperty('path') ){ // ensure path property is present (required by some importers) row.path = wofIdToPath(row.id).concat(row.id+'.geojson').join(path.sep); } metafiles.write( row ); } // close connection db.close(); }
[ "function", "extractDB", "(", "dbpath", ")", "{", "let", "targetWofIds", "=", "Array", ".", "isArray", "(", "config", ".", "importPlace", ")", "?", "config", ".", "importPlace", ":", "[", "config", ".", "importPlace", "]", ";", "// connect to sql db", "let", "db", "=", "new", "Sqlite3", "(", "dbpath", ",", "{", "readonly", ":", "true", "}", ")", ";", "// convert ids to integers and remove any which fail to convert", "let", "cleanIds", "=", "targetWofIds", ".", "map", "(", "id", "=>", "parseInt", "(", "id", ",", "10", ")", ")", ".", "filter", "(", "id", "=>", "!", "isNaN", "(", "id", ")", ")", ";", "// placefilter is used to select only records targeted by the 'importPlace' config option", "// note: if no 'importPlace' ids are provided then we process all ids which aren't 0", "let", "placefilter", "=", "(", "cleanIds", ".", "length", ">", "0", ")", "?", "sql", ".", "placefilter", ":", "'!= 0'", ";", "// note: we need to use replace instead of bound params in order to be able", "// to query an array of values using IN.", "let", "dataQuery", "=", "sql", ".", "data", ".", "replace", "(", "/", "@placefilter", "/", "g", ",", "placefilter", ")", ".", "replace", "(", "/", "@wofids", "/", "g", ",", "cleanIds", ".", "join", "(", "','", ")", ")", ";", "let", "metaQuery", "=", "sql", ".", "meta", ".", "replace", "(", "/", "@placefilter", "/", "g", ",", "placefilter", ")", ".", "replace", "(", "/", "@wofids", "/", "g", ",", "cleanIds", ".", "join", "(", "','", ")", ")", ";", "// extract all data to disk", "for", "(", "let", "row", "of", "db", ".", "prepare", "(", "dataQuery", ")", ".", "iterate", "(", ")", ")", "{", "if", "(", "'postalcode'", "===", "row", ".", "placetype", "&&", "true", "!==", "config", ".", "importPostalcodes", ")", "{", "return", ";", "}", "if", "(", "'venue'", "===", "row", ".", "placetype", "&&", "true", "!==", "config", ".", "importVenues", ")", "{", "return", ";", "}", "if", "(", "'constituency'", "===", "row", ".", "placetype", "&&", "true", "!==", "config", ".", "importConstituencies", ")", "{", "return", ";", "}", "if", "(", "'intersection'", "===", "row", ".", "placetype", "&&", "true", "!==", "config", ".", "importIntersections", ")", "{", "return", ";", "}", "writeJson", "(", "row", ")", ";", "}", "// write meta data to disk", "for", "(", "let", "row", "of", "db", ".", "prepare", "(", "metaQuery", ")", ".", "iterate", "(", ")", ")", "{", "if", "(", "'postalcode'", "===", "row", ".", "placetype", "&&", "true", "!==", "config", ".", "importPostalcodes", ")", "{", "return", ";", "}", "if", "(", "'venue'", "===", "row", ".", "placetype", "&&", "true", "!==", "config", ".", "importVenues", ")", "{", "return", ";", "}", "if", "(", "'constituency'", "===", "row", ".", "placetype", "&&", "true", "!==", "config", ".", "importConstituencies", ")", "{", "return", ";", "}", "if", "(", "'intersection'", "===", "row", ".", "placetype", "&&", "true", "!==", "config", ".", "importIntersections", ")", "{", "return", ";", "}", "if", "(", "!", "row", ".", "hasOwnProperty", "(", "'path'", ")", ")", "{", "// ensure path property is present (required by some importers)", "row", ".", "path", "=", "wofIdToPath", "(", "row", ".", "id", ")", ".", "concat", "(", "row", ".", "id", "+", "'.geojson'", ")", ".", "join", "(", "path", ".", "sep", ")", ";", "}", "metafiles", ".", "write", "(", "row", ")", ";", "}", "// close connection", "db", ".", "close", "(", ")", ";", "}" ]
extract from a single db file
[ "extract", "from", "a", "single", "db", "file" ]
56fdb2f00ad0c97510ea44166aaee5d8b0cc334a
https://github.com/pelias/whosonfirst/blob/56fdb2f00ad0c97510ea44166aaee5d8b0cc334a/utils/sqlite_extract_data.js#L103-L145
19,070
pelias/whosonfirst
utils/sqlite_extract_data.js
findSubdivisions
function findSubdivisions( filename ){ // load configuration variables const config = require('pelias-config').generate(require('../schema')).imports.whosonfirst; const sqliteDir = path.join(config.datapath, 'sqlite'); let targetWofIds = Array.isArray(config.importPlace) ? config.importPlace: [config.importPlace]; // connect to sql db let db = new Sqlite3( path.join( sqliteDir, filename ), { readonly: true } ); // convert ids to integers and remove any which fail to convert let cleanIds = targetWofIds.map(id => parseInt(id, 10)).filter(id => !isNaN(id)); // placefilter is used to select only records targeted by the 'importPlace' config option // note: if no 'importPlace' ids are provided then we process all ids which aren't 0 let placefilter = (cleanIds.length > 0) ? sql.placefilter : '!= 0'; // query db // note: we need to use replace instead of using bound params in order to // be able to query an array of values using IN. let query = sql.subdiv.replace(/@placefilter/g, placefilter).replace(/@wofids/g, cleanIds.join(',')); return db.prepare(query).all().map( row => row.subdivision.toLowerCase()); }
javascript
function findSubdivisions( filename ){ // load configuration variables const config = require('pelias-config').generate(require('../schema')).imports.whosonfirst; const sqliteDir = path.join(config.datapath, 'sqlite'); let targetWofIds = Array.isArray(config.importPlace) ? config.importPlace: [config.importPlace]; // connect to sql db let db = new Sqlite3( path.join( sqliteDir, filename ), { readonly: true } ); // convert ids to integers and remove any which fail to convert let cleanIds = targetWofIds.map(id => parseInt(id, 10)).filter(id => !isNaN(id)); // placefilter is used to select only records targeted by the 'importPlace' config option // note: if no 'importPlace' ids are provided then we process all ids which aren't 0 let placefilter = (cleanIds.length > 0) ? sql.placefilter : '!= 0'; // query db // note: we need to use replace instead of using bound params in order to // be able to query an array of values using IN. let query = sql.subdiv.replace(/@placefilter/g, placefilter).replace(/@wofids/g, cleanIds.join(',')); return db.prepare(query).all().map( row => row.subdivision.toLowerCase()); }
[ "function", "findSubdivisions", "(", "filename", ")", "{", "// load configuration variables", "const", "config", "=", "require", "(", "'pelias-config'", ")", ".", "generate", "(", "require", "(", "'../schema'", ")", ")", ".", "imports", ".", "whosonfirst", ";", "const", "sqliteDir", "=", "path", ".", "join", "(", "config", ".", "datapath", ",", "'sqlite'", ")", ";", "let", "targetWofIds", "=", "Array", ".", "isArray", "(", "config", ".", "importPlace", ")", "?", "config", ".", "importPlace", ":", "[", "config", ".", "importPlace", "]", ";", "// connect to sql db", "let", "db", "=", "new", "Sqlite3", "(", "path", ".", "join", "(", "sqliteDir", ",", "filename", ")", ",", "{", "readonly", ":", "true", "}", ")", ";", "// convert ids to integers and remove any which fail to convert", "let", "cleanIds", "=", "targetWofIds", ".", "map", "(", "id", "=>", "parseInt", "(", "id", ",", "10", ")", ")", ".", "filter", "(", "id", "=>", "!", "isNaN", "(", "id", ")", ")", ";", "// placefilter is used to select only records targeted by the 'importPlace' config option", "// note: if no 'importPlace' ids are provided then we process all ids which aren't 0", "let", "placefilter", "=", "(", "cleanIds", ".", "length", ">", "0", ")", "?", "sql", ".", "placefilter", ":", "'!= 0'", ";", "// query db", "// note: we need to use replace instead of using bound params in order to", "// be able to query an array of values using IN.", "let", "query", "=", "sql", ".", "subdiv", ".", "replace", "(", "/", "@placefilter", "/", "g", ",", "placefilter", ")", ".", "replace", "(", "/", "@wofids", "/", "g", ",", "cleanIds", ".", "join", "(", "','", ")", ")", ";", "return", "db", ".", "prepare", "(", "query", ")", ".", "all", "(", ")", ".", "map", "(", "row", "=>", "row", ".", "subdivision", ".", "toLowerCase", "(", ")", ")", ";", "}" ]
return all distinct subdivisions of the data
[ "return", "all", "distinct", "subdivisions", "of", "the", "data" ]
56fdb2f00ad0c97510ea44166aaee5d8b0cc334a
https://github.com/pelias/whosonfirst/blob/56fdb2f00ad0c97510ea44166aaee5d8b0cc334a/utils/sqlite_extract_data.js#L187-L209
19,071
pelias/whosonfirst
src/peliasDocGenerators.js
setupDocument
function setupDocument(record, hierarchy) { var wofDoc = new Document( 'whosonfirst', record.place_type, record.id ); if (record.name) { wofDoc.setName('default', record.name); // index a version of postcode which doesn't contain whitespace if (record.place_type === 'postalcode' && typeof record.name === 'string') { var sans_whitespace = record.name.replace(/\s/g, ''); if (sans_whitespace !== record.name) { wofDoc.setNameAlias('default', sans_whitespace); } } // index name aliases for all other records (where available) else if (record.name_aliases.length) { record.name_aliases.forEach(alias => { wofDoc.setNameAlias('default', alias); }); } } wofDoc.setCentroid({ lat: record.lat, lon: record.lon }); // only set population if available if (record.population) { wofDoc.setPopulation(record.population); } // only set popularity if available if (record.popularity) { wofDoc.setPopularity(record.popularity); } // WOF bbox is defined as: // lowerLeft.lon, lowerLeft.lat, upperRight.lon, upperRight.lat // so convert to what ES understands if (!_.isUndefined(record.bounding_box)) { var parsedBoundingBox = record.bounding_box.split(',').map(parseFloat); var marshaledBoundingBoxBox = { upperLeft: { lat: parsedBoundingBox[3], lon: parsedBoundingBox[0] }, lowerRight: { lat: parsedBoundingBox[1], lon: parsedBoundingBox[2] } }; wofDoc.setBoundingBox(marshaledBoundingBoxBox); } // a `hierarchy` is composed of potentially multiple WOF records, so iterate // and assign fields if (!_.isUndefined(hierarchy)) { hierarchy.forEach(function(hierarchyElement) { assignField(hierarchyElement, wofDoc); }); } // add self to parent hierarchy for postalcodes only if (record.place_type === 'postalcode') { assignField(record, wofDoc); } return wofDoc; }
javascript
function setupDocument(record, hierarchy) { var wofDoc = new Document( 'whosonfirst', record.place_type, record.id ); if (record.name) { wofDoc.setName('default', record.name); // index a version of postcode which doesn't contain whitespace if (record.place_type === 'postalcode' && typeof record.name === 'string') { var sans_whitespace = record.name.replace(/\s/g, ''); if (sans_whitespace !== record.name) { wofDoc.setNameAlias('default', sans_whitespace); } } // index name aliases for all other records (where available) else if (record.name_aliases.length) { record.name_aliases.forEach(alias => { wofDoc.setNameAlias('default', alias); }); } } wofDoc.setCentroid({ lat: record.lat, lon: record.lon }); // only set population if available if (record.population) { wofDoc.setPopulation(record.population); } // only set popularity if available if (record.popularity) { wofDoc.setPopularity(record.popularity); } // WOF bbox is defined as: // lowerLeft.lon, lowerLeft.lat, upperRight.lon, upperRight.lat // so convert to what ES understands if (!_.isUndefined(record.bounding_box)) { var parsedBoundingBox = record.bounding_box.split(',').map(parseFloat); var marshaledBoundingBoxBox = { upperLeft: { lat: parsedBoundingBox[3], lon: parsedBoundingBox[0] }, lowerRight: { lat: parsedBoundingBox[1], lon: parsedBoundingBox[2] } }; wofDoc.setBoundingBox(marshaledBoundingBoxBox); } // a `hierarchy` is composed of potentially multiple WOF records, so iterate // and assign fields if (!_.isUndefined(hierarchy)) { hierarchy.forEach(function(hierarchyElement) { assignField(hierarchyElement, wofDoc); }); } // add self to parent hierarchy for postalcodes only if (record.place_type === 'postalcode') { assignField(record, wofDoc); } return wofDoc; }
[ "function", "setupDocument", "(", "record", ",", "hierarchy", ")", "{", "var", "wofDoc", "=", "new", "Document", "(", "'whosonfirst'", ",", "record", ".", "place_type", ",", "record", ".", "id", ")", ";", "if", "(", "record", ".", "name", ")", "{", "wofDoc", ".", "setName", "(", "'default'", ",", "record", ".", "name", ")", ";", "// index a version of postcode which doesn't contain whitespace", "if", "(", "record", ".", "place_type", "===", "'postalcode'", "&&", "typeof", "record", ".", "name", "===", "'string'", ")", "{", "var", "sans_whitespace", "=", "record", ".", "name", ".", "replace", "(", "/", "\\s", "/", "g", ",", "''", ")", ";", "if", "(", "sans_whitespace", "!==", "record", ".", "name", ")", "{", "wofDoc", ".", "setNameAlias", "(", "'default'", ",", "sans_whitespace", ")", ";", "}", "}", "// index name aliases for all other records (where available)", "else", "if", "(", "record", ".", "name_aliases", ".", "length", ")", "{", "record", ".", "name_aliases", ".", "forEach", "(", "alias", "=>", "{", "wofDoc", ".", "setNameAlias", "(", "'default'", ",", "alias", ")", ";", "}", ")", ";", "}", "}", "wofDoc", ".", "setCentroid", "(", "{", "lat", ":", "record", ".", "lat", ",", "lon", ":", "record", ".", "lon", "}", ")", ";", "// only set population if available", "if", "(", "record", ".", "population", ")", "{", "wofDoc", ".", "setPopulation", "(", "record", ".", "population", ")", ";", "}", "// only set popularity if available", "if", "(", "record", ".", "popularity", ")", "{", "wofDoc", ".", "setPopularity", "(", "record", ".", "popularity", ")", ";", "}", "// WOF bbox is defined as:", "// lowerLeft.lon, lowerLeft.lat, upperRight.lon, upperRight.lat", "// so convert to what ES understands", "if", "(", "!", "_", ".", "isUndefined", "(", "record", ".", "bounding_box", ")", ")", "{", "var", "parsedBoundingBox", "=", "record", ".", "bounding_box", ".", "split", "(", "','", ")", ".", "map", "(", "parseFloat", ")", ";", "var", "marshaledBoundingBoxBox", "=", "{", "upperLeft", ":", "{", "lat", ":", "parsedBoundingBox", "[", "3", "]", ",", "lon", ":", "parsedBoundingBox", "[", "0", "]", "}", ",", "lowerRight", ":", "{", "lat", ":", "parsedBoundingBox", "[", "1", "]", ",", "lon", ":", "parsedBoundingBox", "[", "2", "]", "}", "}", ";", "wofDoc", ".", "setBoundingBox", "(", "marshaledBoundingBoxBox", ")", ";", "}", "// a `hierarchy` is composed of potentially multiple WOF records, so iterate", "// and assign fields", "if", "(", "!", "_", ".", "isUndefined", "(", "hierarchy", ")", ")", "{", "hierarchy", ".", "forEach", "(", "function", "(", "hierarchyElement", ")", "{", "assignField", "(", "hierarchyElement", ",", "wofDoc", ")", ";", "}", ")", ";", "}", "// add self to parent hierarchy for postalcodes only", "if", "(", "record", ".", "place_type", "===", "'postalcode'", ")", "{", "assignField", "(", "record", ",", "wofDoc", ")", ";", "}", "return", "wofDoc", ";", "}" ]
method that extracts the logic for Document creation. `hierarchy` is optional
[ "method", "that", "extracts", "the", "logic", "for", "Document", "creation", ".", "hierarchy", "is", "optional" ]
56fdb2f00ad0c97510ea44166aaee5d8b0cc334a
https://github.com/pelias/whosonfirst/blob/56fdb2f00ad0c97510ea44166aaee5d8b0cc334a/src/peliasDocGenerators.js#L61-L128
19,072
pelias/whosonfirst
src/wofIdToPath.js
wofIdToPath
function wofIdToPath( id ){ let strId = id.toString(); let parts = []; while( strId.length ){ let part = strId.substr(0, 3); parts.push(part); strId = strId.substr(3); } return parts; }
javascript
function wofIdToPath( id ){ let strId = id.toString(); let parts = []; while( strId.length ){ let part = strId.substr(0, 3); parts.push(part); strId = strId.substr(3); } return parts; }
[ "function", "wofIdToPath", "(", "id", ")", "{", "let", "strId", "=", "id", ".", "toString", "(", ")", ";", "let", "parts", "=", "[", "]", ";", "while", "(", "strId", ".", "length", ")", "{", "let", "part", "=", "strId", ".", "substr", "(", "0", ",", "3", ")", ";", "parts", ".", "push", "(", "part", ")", ";", "strId", "=", "strId", ".", "substr", "(", "3", ")", ";", "}", "return", "parts", ";", "}" ]
convert wofid integer to array of path components
[ "convert", "wofid", "integer", "to", "array", "of", "path", "components" ]
56fdb2f00ad0c97510ea44166aaee5d8b0cc334a
https://github.com/pelias/whosonfirst/blob/56fdb2f00ad0c97510ea44166aaee5d8b0cc334a/src/wofIdToPath.js#L4-L13
19,073
pencil-js/pencil.js
modules/text/text.js
formatString
function formatString (string) { const separator = "\n"; return Array.isArray(string) ? string.reduce((acc, line) => acc.concat(line.split(separator)), []) : string.split(separator); }
javascript
function formatString (string) { const separator = "\n"; return Array.isArray(string) ? string.reduce((acc, line) => acc.concat(line.split(separator)), []) : string.split(separator); }
[ "function", "formatString", "(", "string", ")", "{", "const", "separator", "=", "\"\\n\"", ";", "return", "Array", ".", "isArray", "(", "string", ")", "?", "string", ".", "reduce", "(", "(", "acc", ",", "line", ")", "=>", "acc", ".", "concat", "(", "line", ".", "split", "(", "separator", ")", ")", ",", "[", "]", ")", ":", "string", ".", "split", "(", "separator", ")", ";", "}" ]
Reformat passed arguments into an array of line string @param {String|Array<String>} string - @return {Array<String>}
[ "Reformat", "passed", "arguments", "into", "an", "array", "of", "line", "string" ]
faa58f24946fd6b08ac920d26d735ca0d3a31861
https://github.com/pencil-js/pencil.js/blob/faa58f24946fd6b08ac920d26d735ca0d3a31861/modules/text/text.js#L12-L17
19,074
pencil-js/pencil.js
modules/pencil.js/pencil.js
from
function from (json) { const instance = exportableClasses[json.constructor].from(json); if (json.children) { instance.add(...json.children.map(child => from(child))); } return instance; }
javascript
function from (json) { const instance = exportableClasses[json.constructor].from(json); if (json.children) { instance.add(...json.children.map(child => from(child))); } return instance; }
[ "function", "from", "(", "json", ")", "{", "const", "instance", "=", "exportableClasses", "[", "json", ".", "constructor", "]", ".", "from", "(", "json", ")", ";", "if", "(", "json", ".", "children", ")", "{", "instance", ".", "add", "(", "...", "json", ".", "children", ".", "map", "(", "child", "=>", "from", "(", "child", ")", ")", ")", ";", "}", "return", "instance", ";", "}" ]
Construct Pencil objects from a JSON @param {Object} json - Valid JSON @return {*}
[ "Construct", "Pencil", "objects", "from", "a", "JSON" ]
faa58f24946fd6b08ac920d26d735ca0d3a31861
https://github.com/pencil-js/pencil.js/blob/faa58f24946fd6b08ac920d26d735ca0d3a31861/modules/pencil.js/pencil.js#L89-L95
19,075
pencil-js/pencil.js
modules/vector/vector.js
sanitizeParameters
function sanitizeParameters (definition) { let scalar; try { // eslint-disable-next-line no-use-before-define const vector = Vector.from(definition); scalar = vector.getDelta(); } catch (e) { scalar = definition.getDelta ? definition.getDelta() : definition; } return scalar; }
javascript
function sanitizeParameters (definition) { let scalar; try { // eslint-disable-next-line no-use-before-define const vector = Vector.from(definition); scalar = vector.getDelta(); } catch (e) { scalar = definition.getDelta ? definition.getDelta() : definition; } return scalar; }
[ "function", "sanitizeParameters", "(", "definition", ")", "{", "let", "scalar", ";", "try", "{", "// eslint-disable-next-line no-use-before-define", "const", "vector", "=", "Vector", ".", "from", "(", "definition", ")", ";", "scalar", "=", "vector", ".", "getDelta", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "scalar", "=", "definition", ".", "getDelta", "?", "definition", ".", "getDelta", "(", ")", ":", "definition", ";", "}", "return", "scalar", ";", "}" ]
Accept all kind of type and return only Number or Position @param {VectorDefinition|PositionDefinition|Number} definition - Value definition @return {Position|Number}
[ "Accept", "all", "kind", "of", "type", "and", "return", "only", "Number", "or", "Position" ]
faa58f24946fd6b08ac920d26d735ca0d3a31861
https://github.com/pencil-js/pencil.js/blob/faa58f24946fd6b08ac920d26d735ca0d3a31861/modules/vector/vector.js#L8-L19
19,076
js-data/js-data-angular
dist/js-data-angular.js
logResponse
function logResponse(data, isRejection) { data = data || {}; // examine the data object if (data instanceof Error) { // log the Error object _this.defaults.error('FAILED: ' + (data.message || 'Unknown Error'), data); return DSUtils.Promise.reject(data); } else if ((typeof data === 'undefined' ? 'undefined' : _typeof(data)) === 'object') { var str = start.toUTCString() + ' - ' + config.method + ' ' + config.url + ' - ' + data.status + ' ' + (new Date().getTime() - start.getTime()) + 'ms'; if (data.status >= 200 && data.status < 300 && !isRejection) { if (_this.defaults.log) { _this.defaults.log(str, data); } return data; } else { if (_this.defaults.error) { _this.defaults.error('FAILED: ' + str, data); } return DSUtils.Promise.reject(data); } } else { // unknown type for 'data' that is not an Object or Error _this.defaults.error('FAILED', data); return DSUtils.Promise.reject(data); } }
javascript
function logResponse(data, isRejection) { data = data || {}; // examine the data object if (data instanceof Error) { // log the Error object _this.defaults.error('FAILED: ' + (data.message || 'Unknown Error'), data); return DSUtils.Promise.reject(data); } else if ((typeof data === 'undefined' ? 'undefined' : _typeof(data)) === 'object') { var str = start.toUTCString() + ' - ' + config.method + ' ' + config.url + ' - ' + data.status + ' ' + (new Date().getTime() - start.getTime()) + 'ms'; if (data.status >= 200 && data.status < 300 && !isRejection) { if (_this.defaults.log) { _this.defaults.log(str, data); } return data; } else { if (_this.defaults.error) { _this.defaults.error('FAILED: ' + str, data); } return DSUtils.Promise.reject(data); } } else { // unknown type for 'data' that is not an Object or Error _this.defaults.error('FAILED', data); return DSUtils.Promise.reject(data); } }
[ "function", "logResponse", "(", "data", ",", "isRejection", ")", "{", "data", "=", "data", "||", "{", "}", ";", "// examine the data object", "if", "(", "data", "instanceof", "Error", ")", "{", "// log the Error object", "_this", ".", "defaults", ".", "error", "(", "'FAILED: '", "+", "(", "data", ".", "message", "||", "'Unknown Error'", ")", ",", "data", ")", ";", "return", "DSUtils", ".", "Promise", ".", "reject", "(", "data", ")", ";", "}", "else", "if", "(", "(", "typeof", "data", "===", "'undefined'", "?", "'undefined'", ":", "_typeof", "(", "data", ")", ")", "===", "'object'", ")", "{", "var", "str", "=", "start", ".", "toUTCString", "(", ")", "+", "' - '", "+", "config", ".", "method", "+", "' '", "+", "config", ".", "url", "+", "' - '", "+", "data", ".", "status", "+", "' '", "+", "(", "new", "Date", "(", ")", ".", "getTime", "(", ")", "-", "start", ".", "getTime", "(", ")", ")", "+", "'ms'", ";", "if", "(", "data", ".", "status", ">=", "200", "&&", "data", ".", "status", "<", "300", "&&", "!", "isRejection", ")", "{", "if", "(", "_this", ".", "defaults", ".", "log", ")", "{", "_this", ".", "defaults", ".", "log", "(", "str", ",", "data", ")", ";", "}", "return", "data", ";", "}", "else", "{", "if", "(", "_this", ".", "defaults", ".", "error", ")", "{", "_this", ".", "defaults", ".", "error", "(", "'FAILED: '", "+", "str", ",", "data", ")", ";", "}", "return", "DSUtils", ".", "Promise", ".", "reject", "(", "data", ")", ";", "}", "}", "else", "{", "// unknown type for 'data' that is not an Object or Error", "_this", ".", "defaults", ".", "error", "(", "'FAILED'", ",", "data", ")", ";", "return", "DSUtils", ".", "Promise", ".", "reject", "(", "data", ")", ";", "}", "}" ]
logs the HTTP response
[ "logs", "the", "HTTP", "response" ]
2890d89a5951c225a3870b7711b65b4889042170
https://github.com/js-data/js-data-angular/blob/2890d89a5951c225a3870b7711b65b4889042170/dist/js-data-angular.js#L530-L556
19,077
syntax-tree/mdast-util-toc
lib/search.js
isClosingHeading
function isClosingHeading(node, depth) { return depth && node && node.type === HEADING && node.depth <= depth }
javascript
function isClosingHeading(node, depth) { return depth && node && node.type === HEADING && node.depth <= depth }
[ "function", "isClosingHeading", "(", "node", ",", "depth", ")", "{", "return", "depth", "&&", "node", "&&", "node", ".", "type", "===", "HEADING", "&&", "node", ".", "depth", "<=", "depth", "}" ]
Check if `node` is the next heading.
[ "Check", "if", "node", "is", "the", "next", "heading", "." ]
32d2a8fd91c3c0cfb2c568cc11ed457cd9386cd8
https://github.com/syntax-tree/mdast-util-toc/blob/32d2a8fd91c3c0cfb2c568cc11ed457cd9386cd8/lib/search.js#L82-L84
19,078
segmentio/analytics.js-core
lib/analytics.js
pickPrefix
function pickPrefix(prefix, object) { var length = prefix.length; var sub; return foldl( function(acc, val, key) { if (key.substr(0, length) === prefix) { sub = key.substr(length); acc[sub] = val; } return acc; }, {}, object ); }
javascript
function pickPrefix(prefix, object) { var length = prefix.length; var sub; return foldl( function(acc, val, key) { if (key.substr(0, length) === prefix) { sub = key.substr(length); acc[sub] = val; } return acc; }, {}, object ); }
[ "function", "pickPrefix", "(", "prefix", ",", "object", ")", "{", "var", "length", "=", "prefix", ".", "length", ";", "var", "sub", ";", "return", "foldl", "(", "function", "(", "acc", ",", "val", ",", "key", ")", "{", "if", "(", "key", ".", "substr", "(", "0", ",", "length", ")", "===", "prefix", ")", "{", "sub", "=", "key", ".", "substr", "(", "length", ")", ";", "acc", "[", "sub", "]", "=", "val", ";", "}", "return", "acc", ";", "}", ",", "{", "}", ",", "object", ")", ";", "}" ]
Create a shallow copy of an input object containing only the properties whose keys are specified by a prefix, stripped of that prefix @param {String} prefix @param {Object} object @return {Object} @api private
[ "Create", "a", "shallow", "copy", "of", "an", "input", "object", "containing", "only", "the", "properties", "whose", "keys", "are", "specified", "by", "a", "prefix", "stripped", "of", "that", "prefix" ]
2facc5f327b84513ebbede2e5392483ea654f117
https://github.com/segmentio/analytics.js-core/blob/2facc5f327b84513ebbede2e5392483ea654f117/lib/analytics.js#L769-L783
19,079
segmentio/analytics.js-core
lib/normalize.js
normalize
function normalize(msg, list) { var lower = map(function(s) { return s.toLowerCase(); }, list); var opts = msg.options || {}; var integrations = opts.integrations || {}; var providers = opts.providers || {}; var context = opts.context || {}; var ret = {}; debug('<-', msg); // integrations. each(function(value, key) { if (!integration(key)) return; if (!has.call(integrations, key)) integrations[key] = value; delete opts[key]; }, opts); // providers. delete opts.providers; each(function(value, key) { if (!integration(key)) return; if (type(integrations[key]) === 'object') return; if (has.call(integrations, key) && typeof providers[key] === 'boolean') return; integrations[key] = value; }, providers); // move all toplevel options to msg // and the rest to context. each(function(value, key) { if (includes(key, toplevel)) { ret[key] = opts[key]; } else { context[key] = opts[key]; } }, opts); // generate and attach a messageId to msg msg.messageId = 'ajs-' + md5(json.stringify(msg) + uuid()); // cleanup delete msg.options; ret.integrations = integrations; ret.context = context; ret = defaults(ret, msg); debug('->', ret); return ret; function integration(name) { return !!( includes(name, list) || name.toLowerCase() === 'all' || includes(name.toLowerCase(), lower) ); } }
javascript
function normalize(msg, list) { var lower = map(function(s) { return s.toLowerCase(); }, list); var opts = msg.options || {}; var integrations = opts.integrations || {}; var providers = opts.providers || {}; var context = opts.context || {}; var ret = {}; debug('<-', msg); // integrations. each(function(value, key) { if (!integration(key)) return; if (!has.call(integrations, key)) integrations[key] = value; delete opts[key]; }, opts); // providers. delete opts.providers; each(function(value, key) { if (!integration(key)) return; if (type(integrations[key]) === 'object') return; if (has.call(integrations, key) && typeof providers[key] === 'boolean') return; integrations[key] = value; }, providers); // move all toplevel options to msg // and the rest to context. each(function(value, key) { if (includes(key, toplevel)) { ret[key] = opts[key]; } else { context[key] = opts[key]; } }, opts); // generate and attach a messageId to msg msg.messageId = 'ajs-' + md5(json.stringify(msg) + uuid()); // cleanup delete msg.options; ret.integrations = integrations; ret.context = context; ret = defaults(ret, msg); debug('->', ret); return ret; function integration(name) { return !!( includes(name, list) || name.toLowerCase() === 'all' || includes(name.toLowerCase(), lower) ); } }
[ "function", "normalize", "(", "msg", ",", "list", ")", "{", "var", "lower", "=", "map", "(", "function", "(", "s", ")", "{", "return", "s", ".", "toLowerCase", "(", ")", ";", "}", ",", "list", ")", ";", "var", "opts", "=", "msg", ".", "options", "||", "{", "}", ";", "var", "integrations", "=", "opts", ".", "integrations", "||", "{", "}", ";", "var", "providers", "=", "opts", ".", "providers", "||", "{", "}", ";", "var", "context", "=", "opts", ".", "context", "||", "{", "}", ";", "var", "ret", "=", "{", "}", ";", "debug", "(", "'<-'", ",", "msg", ")", ";", "// integrations.", "each", "(", "function", "(", "value", ",", "key", ")", "{", "if", "(", "!", "integration", "(", "key", ")", ")", "return", ";", "if", "(", "!", "has", ".", "call", "(", "integrations", ",", "key", ")", ")", "integrations", "[", "key", "]", "=", "value", ";", "delete", "opts", "[", "key", "]", ";", "}", ",", "opts", ")", ";", "// providers.", "delete", "opts", ".", "providers", ";", "each", "(", "function", "(", "value", ",", "key", ")", "{", "if", "(", "!", "integration", "(", "key", ")", ")", "return", ";", "if", "(", "type", "(", "integrations", "[", "key", "]", ")", "===", "'object'", ")", "return", ";", "if", "(", "has", ".", "call", "(", "integrations", ",", "key", ")", "&&", "typeof", "providers", "[", "key", "]", "===", "'boolean'", ")", "return", ";", "integrations", "[", "key", "]", "=", "value", ";", "}", ",", "providers", ")", ";", "// move all toplevel options to msg", "// and the rest to context.", "each", "(", "function", "(", "value", ",", "key", ")", "{", "if", "(", "includes", "(", "key", ",", "toplevel", ")", ")", "{", "ret", "[", "key", "]", "=", "opts", "[", "key", "]", ";", "}", "else", "{", "context", "[", "key", "]", "=", "opts", "[", "key", "]", ";", "}", "}", ",", "opts", ")", ";", "// generate and attach a messageId to msg", "msg", ".", "messageId", "=", "'ajs-'", "+", "md5", "(", "json", ".", "stringify", "(", "msg", ")", "+", "uuid", "(", ")", ")", ";", "// cleanup", "delete", "msg", ".", "options", ";", "ret", ".", "integrations", "=", "integrations", ";", "ret", ".", "context", "=", "context", ";", "ret", "=", "defaults", "(", "ret", ",", "msg", ")", ";", "debug", "(", "'->'", ",", "ret", ")", ";", "return", "ret", ";", "function", "integration", "(", "name", ")", "{", "return", "!", "!", "(", "includes", "(", "name", ",", "list", ")", "||", "name", ".", "toLowerCase", "(", ")", "===", "'all'", "||", "includes", "(", "name", ".", "toLowerCase", "(", ")", ",", "lower", ")", ")", ";", "}", "}" ]
Normalize `msg` based on integrations `list`. @param {Object} msg @param {Array} list @return {Function}
[ "Normalize", "msg", "based", "on", "integrations", "list", "." ]
2facc5f327b84513ebbede2e5392483ea654f117
https://github.com/segmentio/analytics.js-core/blob/2facc5f327b84513ebbede2e5392483ea654f117/lib/normalize.js#L43-L99
19,080
sebelga/gstore-node
lib/entity.js
convertGeoPoints
function convertGeoPoints() { if (!{}.hasOwnProperty.call(this.schema.__meta, 'geoPointsProps')) { return; } this.schema.__meta.geoPointsProps.forEach((property) => { if ({}.hasOwnProperty.call(_this.entityData, property) && _this.entityData[property] !== null && _this.entityData[property].constructor.name !== 'GeoPoint') { _this.entityData[property] = _this.gstore.ds.geoPoint(_this.entityData[property]); } }); }
javascript
function convertGeoPoints() { if (!{}.hasOwnProperty.call(this.schema.__meta, 'geoPointsProps')) { return; } this.schema.__meta.geoPointsProps.forEach((property) => { if ({}.hasOwnProperty.call(_this.entityData, property) && _this.entityData[property] !== null && _this.entityData[property].constructor.name !== 'GeoPoint') { _this.entityData[property] = _this.gstore.ds.geoPoint(_this.entityData[property]); } }); }
[ "function", "convertGeoPoints", "(", ")", "{", "if", "(", "!", "{", "}", ".", "hasOwnProperty", ".", "call", "(", "this", ".", "schema", ".", "__meta", ",", "'geoPointsProps'", ")", ")", "{", "return", ";", "}", "this", ".", "schema", ".", "__meta", ".", "geoPointsProps", ".", "forEach", "(", "(", "property", ")", "=>", "{", "if", "(", "{", "}", ".", "hasOwnProperty", ".", "call", "(", "_this", ".", "entityData", ",", "property", ")", "&&", "_this", ".", "entityData", "[", "property", "]", "!==", "null", "&&", "_this", ".", "entityData", "[", "property", "]", ".", "constructor", ".", "name", "!==", "'GeoPoint'", ")", "{", "_this", ".", "entityData", "[", "property", "]", "=", "_this", ".", "gstore", ".", "ds", ".", "geoPoint", "(", "_this", ".", "entityData", "[", "property", "]", ")", ";", "}", "}", ")", ";", "}" ]
If the entityData has some property of type 'geoPoint' and its value is an js object with "latitude" and "longitude" we convert it to a datastore GeoPoint.
[ "If", "the", "entityData", "has", "some", "property", "of", "type", "geoPoint", "and", "its", "value", "is", "an", "js", "object", "with", "latitude", "and", "longitude", "we", "convert", "it", "to", "a", "datastore", "GeoPoint", "." ]
349ffe9f284d3315307a2e0f88e3fb5c01d3eac5
https://github.com/sebelga/gstore-node/blob/349ffe9f284d3315307a2e0f88e3fb5c01d3eac5/lib/entity.js#L168-L180
19,081
sebelga/gstore-node
lib/model.js
metaData
function metaData() { const meta = {}; Object.keys(schema.paths).forEach((k) => { switch (schema.paths[k].type) { case 'geoPoint': // This allows us to automatically convert valid lng/lat objects // to Datastore.geoPoints meta.geoPointsProps = meta.geoPointsProps || []; meta.geoPointsProps.push(k); break; case 'entityKey': meta.refProps = meta.refProps || {}; meta.refProps[k] = true; break; default: } }); return meta; }
javascript
function metaData() { const meta = {}; Object.keys(schema.paths).forEach((k) => { switch (schema.paths[k].type) { case 'geoPoint': // This allows us to automatically convert valid lng/lat objects // to Datastore.geoPoints meta.geoPointsProps = meta.geoPointsProps || []; meta.geoPointsProps.push(k); break; case 'entityKey': meta.refProps = meta.refProps || {}; meta.refProps[k] = true; break; default: } }); return meta; }
[ "function", "metaData", "(", ")", "{", "const", "meta", "=", "{", "}", ";", "Object", ".", "keys", "(", "schema", ".", "paths", ")", ".", "forEach", "(", "(", "k", ")", "=>", "{", "switch", "(", "schema", ".", "paths", "[", "k", "]", ".", "type", ")", "{", "case", "'geoPoint'", ":", "// This allows us to automatically convert valid lng/lat objects", "// to Datastore.geoPoints", "meta", ".", "geoPointsProps", "=", "meta", ".", "geoPointsProps", "||", "[", "]", ";", "meta", ".", "geoPointsProps", ".", "push", "(", "k", ")", ";", "break", ";", "case", "'entityKey'", ":", "meta", ".", "refProps", "=", "meta", ".", "refProps", "||", "{", "}", ";", "meta", ".", "refProps", "[", "k", "]", "=", "true", ";", "break", ";", "default", ":", "}", "}", ")", ";", "return", "meta", ";", "}" ]
To improve performance and avoid looping over and over the entityData or Schema we keep here some meta data to be used later in models and entities methods
[ "To", "improve", "performance", "and", "avoid", "looping", "over", "and", "over", "the", "entityData", "or", "Schema", "we", "keep", "here", "some", "meta", "data", "to", "be", "used", "later", "in", "models", "and", "entities", "methods" ]
349ffe9f284d3315307a2e0f88e3fb5c01d3eac5
https://github.com/sebelga/gstore-node/blob/349ffe9f284d3315307a2e0f88e3fb5c01d3eac5/lib/model.js#L75-L95
19,082
sebelga/gstore-node
lib/model.js
applyMethods
function applyMethods(entity, schema) { Object.keys(schema.methods).forEach((method) => { entity[method] = schema.methods[method]; }); return entity; }
javascript
function applyMethods(entity, schema) { Object.keys(schema.methods).forEach((method) => { entity[method] = schema.methods[method]; }); return entity; }
[ "function", "applyMethods", "(", "entity", ",", "schema", ")", "{", "Object", ".", "keys", "(", "schema", ".", "methods", ")", ".", "forEach", "(", "(", "method", ")", "=>", "{", "entity", "[", "method", "]", "=", "schema", ".", "methods", "[", "method", "]", ";", "}", ")", ";", "return", "entity", ";", "}" ]
Add custom methods declared on the Schema to the Entity Class @param {Entity} entity Model.prototype @param {any} schema Model Schema @returns Model.prototype
[ "Add", "custom", "methods", "declared", "on", "the", "Schema", "to", "the", "Entity", "Class" ]
349ffe9f284d3315307a2e0f88e3fb5c01d3eac5
https://github.com/sebelga/gstore-node/blob/349ffe9f284d3315307a2e0f88e3fb5c01d3eac5/lib/model.js#L961-L966
19,083
sebelga/gstore-node
lib/schema.js
defaultOptions
function defaultOptions(options) { const optionsDefault = { validateBeforeSave: true, explicitOnly: true, queries: { readAll: false, format: queries.formats.JSON, }, }; options = extend(true, {}, optionsDefault, options); if (options.joi) { const joiOptionsDefault = { options: { allowUnknown: options.explicitOnly !== true, }, }; if (is.object(options.joi)) { options.joi = extend(true, {}, joiOptionsDefault, options.joi); } else { options.joi = Object.assign({}, joiOptionsDefault); } if (!Object.prototype.hasOwnProperty.call(options.joi.options, 'stripUnknown')) { options.joi.options.stripUnknown = options.joi.options.allowUnknown !== true; } } return options; }
javascript
function defaultOptions(options) { const optionsDefault = { validateBeforeSave: true, explicitOnly: true, queries: { readAll: false, format: queries.formats.JSON, }, }; options = extend(true, {}, optionsDefault, options); if (options.joi) { const joiOptionsDefault = { options: { allowUnknown: options.explicitOnly !== true, }, }; if (is.object(options.joi)) { options.joi = extend(true, {}, joiOptionsDefault, options.joi); } else { options.joi = Object.assign({}, joiOptionsDefault); } if (!Object.prototype.hasOwnProperty.call(options.joi.options, 'stripUnknown')) { options.joi.options.stripUnknown = options.joi.options.allowUnknown !== true; } } return options; }
[ "function", "defaultOptions", "(", "options", ")", "{", "const", "optionsDefault", "=", "{", "validateBeforeSave", ":", "true", ",", "explicitOnly", ":", "true", ",", "queries", ":", "{", "readAll", ":", "false", ",", "format", ":", "queries", ".", "formats", ".", "JSON", ",", "}", ",", "}", ";", "options", "=", "extend", "(", "true", ",", "{", "}", ",", "optionsDefault", ",", "options", ")", ";", "if", "(", "options", ".", "joi", ")", "{", "const", "joiOptionsDefault", "=", "{", "options", ":", "{", "allowUnknown", ":", "options", ".", "explicitOnly", "!==", "true", ",", "}", ",", "}", ";", "if", "(", "is", ".", "object", "(", "options", ".", "joi", ")", ")", "{", "options", ".", "joi", "=", "extend", "(", "true", ",", "{", "}", ",", "joiOptionsDefault", ",", "options", ".", "joi", ")", ";", "}", "else", "{", "options", ".", "joi", "=", "Object", ".", "assign", "(", "{", "}", ",", "joiOptionsDefault", ")", ";", "}", "if", "(", "!", "Object", ".", "prototype", ".", "hasOwnProperty", ".", "call", "(", "options", ".", "joi", ".", "options", ",", "'stripUnknown'", ")", ")", "{", "options", ".", "joi", ".", "options", ".", "stripUnknown", "=", "options", ".", "joi", ".", "options", ".", "allowUnknown", "!==", "true", ";", "}", "}", "return", "options", ";", "}" ]
Merge options passed with the default option for Schemas @param options
[ "Merge", "options", "passed", "with", "the", "default", "option", "for", "Schemas" ]
349ffe9f284d3315307a2e0f88e3fb5c01d3eac5
https://github.com/sebelga/gstore-node/blob/349ffe9f284d3315307a2e0f88e3fb5c01d3eac5/lib/schema.js#L201-L227
19,084
sebelga/gstore-node
lib/dataloader.js
createDataLoader
function createDataLoader(ds) { ds = typeof ds !== 'undefined' ? ds : this && this.ds; if (!ds) { throw new Error('A Datastore instance has to be passed'); } return new DataLoader(keys => ( ds.get(keys).then(([res]) => { // When providing an Array with 1 Key item, google-datastore // returns a single item. // For predictable results in gstore, all responses from Datastore.get() // calls return an Array const entities = arrify(res); const entitiesByKey = {}; entities.forEach((entity) => { entitiesByKey[keyToString(entity[ds.KEY])] = entity; }); return keys.map(key => entitiesByKey[keyToString(key)] || null); }) ), { cacheKeyFn: _key => keyToString(_key), maxBatchSize: 1000, }); }
javascript
function createDataLoader(ds) { ds = typeof ds !== 'undefined' ? ds : this && this.ds; if (!ds) { throw new Error('A Datastore instance has to be passed'); } return new DataLoader(keys => ( ds.get(keys).then(([res]) => { // When providing an Array with 1 Key item, google-datastore // returns a single item. // For predictable results in gstore, all responses from Datastore.get() // calls return an Array const entities = arrify(res); const entitiesByKey = {}; entities.forEach((entity) => { entitiesByKey[keyToString(entity[ds.KEY])] = entity; }); return keys.map(key => entitiesByKey[keyToString(key)] || null); }) ), { cacheKeyFn: _key => keyToString(_key), maxBatchSize: 1000, }); }
[ "function", "createDataLoader", "(", "ds", ")", "{", "ds", "=", "typeof", "ds", "!==", "'undefined'", "?", "ds", ":", "this", "&&", "this", ".", "ds", ";", "if", "(", "!", "ds", ")", "{", "throw", "new", "Error", "(", "'A Datastore instance has to be passed'", ")", ";", "}", "return", "new", "DataLoader", "(", "keys", "=>", "(", "ds", ".", "get", "(", "keys", ")", ".", "then", "(", "(", "[", "res", "]", ")", "=>", "{", "// When providing an Array with 1 Key item, google-datastore", "// returns a single item.", "// For predictable results in gstore, all responses from Datastore.get()", "// calls return an Array", "const", "entities", "=", "arrify", "(", "res", ")", ";", "const", "entitiesByKey", "=", "{", "}", ";", "entities", ".", "forEach", "(", "(", "entity", ")", "=>", "{", "entitiesByKey", "[", "keyToString", "(", "entity", "[", "ds", ".", "KEY", "]", ")", "]", "=", "entity", ";", "}", ")", ";", "return", "keys", ".", "map", "(", "key", "=>", "entitiesByKey", "[", "keyToString", "(", "key", ")", "]", "||", "null", ")", ";", "}", ")", ")", ",", "{", "cacheKeyFn", ":", "_key", "=>", "keyToString", "(", "_key", ")", ",", "maxBatchSize", ":", "1000", ",", "}", ")", ";", "}" ]
Create a DataLoader instance @param {Datastore} ds @google-cloud Datastore instance
[ "Create", "a", "DataLoader", "instance" ]
349ffe9f284d3315307a2e0f88e3fb5c01d3eac5
https://github.com/sebelga/gstore-node/blob/349ffe9f284d3315307a2e0f88e3fb5c01d3eac5/lib/dataloader.js#L16-L41
19,085
caolan/forms
lib/widgets.js
function (type) { return function (opts) { var opt = opts || {}; var userAttrs = getUserAttrs(opt); var w = { classes: opt.classes, type: type, formatValue: function (value) { return (value || value === 0) ? value : null; } }; w.toHTML = function (name, field) { var f = field || {}; var attrs = { type: type, name: name, id: f.id === false ? false : (f.id || true), classes: w.classes, value: w.formatValue(f.value) }; return tag('input', [attrs, userAttrs, w.attrs || {}]); }; return w; }; }
javascript
function (type) { return function (opts) { var opt = opts || {}; var userAttrs = getUserAttrs(opt); var w = { classes: opt.classes, type: type, formatValue: function (value) { return (value || value === 0) ? value : null; } }; w.toHTML = function (name, field) { var f = field || {}; var attrs = { type: type, name: name, id: f.id === false ? false : (f.id || true), classes: w.classes, value: w.formatValue(f.value) }; return tag('input', [attrs, userAttrs, w.attrs || {}]); }; return w; }; }
[ "function", "(", "type", ")", "{", "return", "function", "(", "opts", ")", "{", "var", "opt", "=", "opts", "||", "{", "}", ";", "var", "userAttrs", "=", "getUserAttrs", "(", "opt", ")", ";", "var", "w", "=", "{", "classes", ":", "opt", ".", "classes", ",", "type", ":", "type", ",", "formatValue", ":", "function", "(", "value", ")", "{", "return", "(", "value", "||", "value", "===", "0", ")", "?", "value", ":", "null", ";", "}", "}", ";", "w", ".", "toHTML", "=", "function", "(", "name", ",", "field", ")", "{", "var", "f", "=", "field", "||", "{", "}", ";", "var", "attrs", "=", "{", "type", ":", "type", ",", "name", ":", "name", ",", "id", ":", "f", ".", "id", "===", "false", "?", "false", ":", "(", "f", ".", "id", "||", "true", ")", ",", "classes", ":", "w", ".", "classes", ",", "value", ":", "w", ".", "formatValue", "(", "f", ".", "value", ")", "}", ";", "return", "tag", "(", "'input'", ",", "[", "attrs", ",", "userAttrs", ",", "w", ".", "attrs", "||", "{", "}", "]", ")", ";", "}", ";", "return", "w", ";", "}", ";", "}" ]
used to generate different input elements varying only by type attribute
[ "used", "to", "generate", "different", "input", "elements", "varying", "only", "by", "type", "attribute" ]
748976ad38fd653873504cc776e73c8d47199a9c
https://github.com/caolan/forms/blob/748976ad38fd653873504cc776e73c8d47199a9c/lib/widgets.js#L22-L46
19,086
instana/nodejs-sensor
packages/collector/src/agentConnection.js
sendRequestsSync
function sendRequestsSync(requests) { // only try to require optional dependency netlinkwrapper once if (!netLinkHasBeenRequired) { netLinkHasBeenRequired = true; try { netLink = require('netlinkwrapper')(); } catch (requireNetlinkError) { logger.warn( 'Failed to require optional dependency netlinkwrapper, uncaught exception will not be reported to Instana.' ); } } if (!netLink) { return; } var port = agentOpts.port; if (typeof port !== 'number') { try { port = parseInt(port, 10); } catch (nonNumericPortError) { logger.warn('Detected non-numeric port configuration value %s, uncaught exception will not be reported.', port); return; } } try { netLink.connect(port, agentOpts.host); netLink.blocking(false); requests.forEach(function(request) { sendHttpPostRequestSync(port, request.path, request.data); }); } catch (netLinkError) { logger.warn('Failed to report uncaught exception due to network error.', { error: netLinkError }); } finally { try { netLink.disconnect(); } catch (ignoreDisconnectError) { logger.debug('Failed to disconnect after trying to report uncaught exception.'); } } }
javascript
function sendRequestsSync(requests) { // only try to require optional dependency netlinkwrapper once if (!netLinkHasBeenRequired) { netLinkHasBeenRequired = true; try { netLink = require('netlinkwrapper')(); } catch (requireNetlinkError) { logger.warn( 'Failed to require optional dependency netlinkwrapper, uncaught exception will not be reported to Instana.' ); } } if (!netLink) { return; } var port = agentOpts.port; if (typeof port !== 'number') { try { port = parseInt(port, 10); } catch (nonNumericPortError) { logger.warn('Detected non-numeric port configuration value %s, uncaught exception will not be reported.', port); return; } } try { netLink.connect(port, agentOpts.host); netLink.blocking(false); requests.forEach(function(request) { sendHttpPostRequestSync(port, request.path, request.data); }); } catch (netLinkError) { logger.warn('Failed to report uncaught exception due to network error.', { error: netLinkError }); } finally { try { netLink.disconnect(); } catch (ignoreDisconnectError) { logger.debug('Failed to disconnect after trying to report uncaught exception.'); } } }
[ "function", "sendRequestsSync", "(", "requests", ")", "{", "// only try to require optional dependency netlinkwrapper once", "if", "(", "!", "netLinkHasBeenRequired", ")", "{", "netLinkHasBeenRequired", "=", "true", ";", "try", "{", "netLink", "=", "require", "(", "'netlinkwrapper'", ")", "(", ")", ";", "}", "catch", "(", "requireNetlinkError", ")", "{", "logger", ".", "warn", "(", "'Failed to require optional dependency netlinkwrapper, uncaught exception will not be reported to Instana.'", ")", ";", "}", "}", "if", "(", "!", "netLink", ")", "{", "return", ";", "}", "var", "port", "=", "agentOpts", ".", "port", ";", "if", "(", "typeof", "port", "!==", "'number'", ")", "{", "try", "{", "port", "=", "parseInt", "(", "port", ",", "10", ")", ";", "}", "catch", "(", "nonNumericPortError", ")", "{", "logger", ".", "warn", "(", "'Detected non-numeric port configuration value %s, uncaught exception will not be reported.'", ",", "port", ")", ";", "return", ";", "}", "}", "try", "{", "netLink", ".", "connect", "(", "port", ",", "agentOpts", ".", "host", ")", ";", "netLink", ".", "blocking", "(", "false", ")", ";", "requests", ".", "forEach", "(", "function", "(", "request", ")", "{", "sendHttpPostRequestSync", "(", "port", ",", "request", ".", "path", ",", "request", ".", "data", ")", ";", "}", ")", ";", "}", "catch", "(", "netLinkError", ")", "{", "logger", ".", "warn", "(", "'Failed to report uncaught exception due to network error.'", ",", "{", "error", ":", "netLinkError", "}", ")", ";", "}", "finally", "{", "try", "{", "netLink", ".", "disconnect", "(", ")", ";", "}", "catch", "(", "ignoreDisconnectError", ")", "{", "logger", ".", "debug", "(", "'Failed to disconnect after trying to report uncaught exception.'", ")", ";", "}", "}", "}" ]
Sends multiple HTTP POST requests to the agent. This function is synchronous, that is, it blocks the event loop! YOU MUST NOT USE THIS FUNCTION, except for the one use case where it is actually required to block the event loop (reporting an uncaught exception tot the agent in the process.on('uncaughtException') handler).
[ "Sends", "multiple", "HTTP", "POST", "requests", "to", "the", "agent", ".", "This", "function", "is", "synchronous", "that", "is", "it", "blocks", "the", "event", "loop!" ]
7e42fd64e1b38e9704a4f73a4c64ef5fac54e722
https://github.com/instana/nodejs-sensor/blob/7e42fd64e1b38e9704a4f73a4c64ef5fac54e722/packages/collector/src/agentConnection.js#L301-L342
19,087
instana/nodejs-sensor
packages/collector/src/agentConnection.js
sendHttpPostRequestSync
function sendHttpPostRequestSync(port, path, data) { logger.debug({ payload: data }, 'Sending payload synchronously to %s', path); try { var payload = JSON.stringify(data); var payloadLength = buffer.fromString(payload, 'utf8').length; } catch (payloadSerializationError) { logger.warn('Could not serialize payload, uncaught exception will not be reported.', { error: payloadSerializationError }); return; } // prettier-ignore netLink.write( 'POST ' + path + ' HTTP/1.1\u000d\u000a' + 'Host: ' + agentOpts.host + '\u000d\u000a' + 'Content-Type: application/json; charset=UTF-8\u000d\u000a' + 'Content-Length: ' + payloadLength + '\u000d\u000a' + '\u000d\u000a' + // extra CRLF before body payload ); }
javascript
function sendHttpPostRequestSync(port, path, data) { logger.debug({ payload: data }, 'Sending payload synchronously to %s', path); try { var payload = JSON.stringify(data); var payloadLength = buffer.fromString(payload, 'utf8').length; } catch (payloadSerializationError) { logger.warn('Could not serialize payload, uncaught exception will not be reported.', { error: payloadSerializationError }); return; } // prettier-ignore netLink.write( 'POST ' + path + ' HTTP/1.1\u000d\u000a' + 'Host: ' + agentOpts.host + '\u000d\u000a' + 'Content-Type: application/json; charset=UTF-8\u000d\u000a' + 'Content-Length: ' + payloadLength + '\u000d\u000a' + '\u000d\u000a' + // extra CRLF before body payload ); }
[ "function", "sendHttpPostRequestSync", "(", "port", ",", "path", ",", "data", ")", "{", "logger", ".", "debug", "(", "{", "payload", ":", "data", "}", ",", "'Sending payload synchronously to %s'", ",", "path", ")", ";", "try", "{", "var", "payload", "=", "JSON", ".", "stringify", "(", "data", ")", ";", "var", "payloadLength", "=", "buffer", ".", "fromString", "(", "payload", ",", "'utf8'", ")", ".", "length", ";", "}", "catch", "(", "payloadSerializationError", ")", "{", "logger", ".", "warn", "(", "'Could not serialize payload, uncaught exception will not be reported.'", ",", "{", "error", ":", "payloadSerializationError", "}", ")", ";", "return", ";", "}", "// prettier-ignore", "netLink", ".", "write", "(", "'POST '", "+", "path", "+", "' HTTP/1.1\\u000d\\u000a'", "+", "'Host: '", "+", "agentOpts", ".", "host", "+", "'\\u000d\\u000a'", "+", "'Content-Type: application/json; charset=UTF-8\\u000d\\u000a'", "+", "'Content-Length: '", "+", "payloadLength", "+", "'\\u000d\\u000a'", "+", "'\\u000d\\u000a'", "+", "// extra CRLF before body", "payload", ")", ";", "}" ]
Sends a single, synchronous HTTP POST request to the agent. This function is synchronous, that is, it blocks the event loop! YOU MUST NOT USE THIS FUNCTION, except for the one use case where it is actually required to block the event loop (reporting an uncaught exception tot the agent in the process.on('uncaughtException') handler).
[ "Sends", "a", "single", "synchronous", "HTTP", "POST", "request", "to", "the", "agent", ".", "This", "function", "is", "synchronous", "that", "is", "it", "blocks", "the", "event", "loop!" ]
7e42fd64e1b38e9704a4f73a4c64ef5fac54e722
https://github.com/instana/nodejs-sensor/blob/7e42fd64e1b38e9704a4f73a4c64ef5fac54e722/packages/collector/src/agentConnection.js#L351-L372
19,088
instana/nodejs-sensor
packages/core/src/tracing/instrumentation/frameworks/fastify.js
instrument
function instrument(build) { if (typeof build !== 'function') { return build; } // copy further exported properties Object.keys(build).forEach(function(k) { overwrittenBuild[k] = build[k]; }); return overwrittenBuild; function overwrittenBuild() { var app = build.apply(this, arguments); if (app.route) { var originalRoute = app.route; app.route = function shimmedRoute(opts) { if (opts.handler) { var originalHandler = opts.handler; opts.handler = function shimmedHandler() { annotateHttpEntrySpanWithPathTemplate(app, opts); return originalHandler.apply(this, arguments); }; } if (opts.beforeHandler) { var originalBeforeHandler = opts.beforeHandler; opts.beforeHandler = function shimmedBeforeHandler() { annotateHttpEntrySpanWithPathTemplate(app, opts); return originalBeforeHandler.apply(this, arguments); }; } return originalRoute.apply(this, arguments); }; } return app; } }
javascript
function instrument(build) { if (typeof build !== 'function') { return build; } // copy further exported properties Object.keys(build).forEach(function(k) { overwrittenBuild[k] = build[k]; }); return overwrittenBuild; function overwrittenBuild() { var app = build.apply(this, arguments); if (app.route) { var originalRoute = app.route; app.route = function shimmedRoute(opts) { if (opts.handler) { var originalHandler = opts.handler; opts.handler = function shimmedHandler() { annotateHttpEntrySpanWithPathTemplate(app, opts); return originalHandler.apply(this, arguments); }; } if (opts.beforeHandler) { var originalBeforeHandler = opts.beforeHandler; opts.beforeHandler = function shimmedBeforeHandler() { annotateHttpEntrySpanWithPathTemplate(app, opts); return originalBeforeHandler.apply(this, arguments); }; } return originalRoute.apply(this, arguments); }; } return app; } }
[ "function", "instrument", "(", "build", ")", "{", "if", "(", "typeof", "build", "!==", "'function'", ")", "{", "return", "build", ";", "}", "// copy further exported properties", "Object", ".", "keys", "(", "build", ")", ".", "forEach", "(", "function", "(", "k", ")", "{", "overwrittenBuild", "[", "k", "]", "=", "build", "[", "k", "]", ";", "}", ")", ";", "return", "overwrittenBuild", ";", "function", "overwrittenBuild", "(", ")", "{", "var", "app", "=", "build", ".", "apply", "(", "this", ",", "arguments", ")", ";", "if", "(", "app", ".", "route", ")", "{", "var", "originalRoute", "=", "app", ".", "route", ";", "app", ".", "route", "=", "function", "shimmedRoute", "(", "opts", ")", "{", "if", "(", "opts", ".", "handler", ")", "{", "var", "originalHandler", "=", "opts", ".", "handler", ";", "opts", ".", "handler", "=", "function", "shimmedHandler", "(", ")", "{", "annotateHttpEntrySpanWithPathTemplate", "(", "app", ",", "opts", ")", ";", "return", "originalHandler", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", ";", "}", "if", "(", "opts", ".", "beforeHandler", ")", "{", "var", "originalBeforeHandler", "=", "opts", ".", "beforeHandler", ";", "opts", ".", "beforeHandler", "=", "function", "shimmedBeforeHandler", "(", ")", "{", "annotateHttpEntrySpanWithPathTemplate", "(", "app", ",", "opts", ")", ";", "return", "originalBeforeHandler", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", ";", "}", "return", "originalRoute", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", ";", "}", "return", "app", ";", "}", "}" ]
Fastify exposes a function as its module's export. We are replacing this exposed function so that we gain access to the created fastify object. This is necessary so that we can overwrite the fastify.route method. fastify.route is the central routing registration method to which all other functions delegate. We overwrite fastify.route so that we can wrap users's request handlers. During request handler execution time, we can identify the full path template.
[ "Fastify", "exposes", "a", "function", "as", "its", "module", "s", "export", ".", "We", "are", "replacing", "this", "exposed", "function", "so", "that", "we", "gain", "access", "to", "the", "created", "fastify", "object", ".", "This", "is", "necessary", "so", "that", "we", "can", "overwrite", "the", "fastify", ".", "route", "method", ".", "fastify", ".", "route", "is", "the", "central", "routing", "registration", "method", "to", "which", "all", "other", "functions", "delegate", ".", "We", "overwrite", "fastify", ".", "route", "so", "that", "we", "can", "wrap", "users", "s", "request", "handlers", ".", "During", "request", "handler", "execution", "time", "we", "can", "identify", "the", "full", "path", "template", "." ]
7e42fd64e1b38e9704a4f73a4c64ef5fac54e722
https://github.com/instana/nodejs-sensor/blob/7e42fd64e1b38e9704a4f73a4c64ef5fac54e722/packages/core/src/tracing/instrumentation/frameworks/fastify.js#L30-L70
19,089
FGRibreau/node-request-retry
index.js
makePromise
function makePromise(requestInstance, promiseFactoryFn) { // Resolver function wich assigns the promise (resolve, reject) functions // to the requestInstance function Resolver(resolve, reject) { this._resolve = resolve; this._reject = reject; } return promiseFactoryFn(Resolver.bind(requestInstance)); }
javascript
function makePromise(requestInstance, promiseFactoryFn) { // Resolver function wich assigns the promise (resolve, reject) functions // to the requestInstance function Resolver(resolve, reject) { this._resolve = resolve; this._reject = reject; } return promiseFactoryFn(Resolver.bind(requestInstance)); }
[ "function", "makePromise", "(", "requestInstance", ",", "promiseFactoryFn", ")", "{", "// Resolver function wich assigns the promise (resolve, reject) functions", "// to the requestInstance", "function", "Resolver", "(", "resolve", ",", "reject", ")", "{", "this", ".", "_resolve", "=", "resolve", ";", "this", ".", "_reject", "=", "reject", ";", "}", "return", "promiseFactoryFn", "(", "Resolver", ".", "bind", "(", "requestInstance", ")", ")", ";", "}" ]
It calls the promiseFactory function passing it the resolver for the promise @param {Object} requestInstance - The Request Retry instance @param {Function} promiseFactoryFn - The Request Retry instance @return {Object} - The promise instance
[ "It", "calls", "the", "promiseFactory", "function", "passing", "it", "the", "resolver", "for", "the", "promise" ]
0c6fb14d271b09a15f53ff44f3a16d640a914677
https://github.com/FGRibreau/node-request-retry/blob/0c6fb14d271b09a15f53ff44f3a16d640a914677/index.js#L35-L45
19,090
FGRibreau/node-request-retry
index.js
makeHelper
function makeHelper(obj, verb) { obj[verb] = function helper(url, options, f) { // ('url') if(_.isString(url)){ // ('url', f) if(_.isFunction(options)){ f = options; } if(!_.isObject(options)){ options = {}; } // ('url', {object}) options.url = url; } if(_.isObject(url)){ if(_.isFunction(options)){ f = options; } options = url; } options.method = verb.toUpperCase(); return obj(options, f); }; }
javascript
function makeHelper(obj, verb) { obj[verb] = function helper(url, options, f) { // ('url') if(_.isString(url)){ // ('url', f) if(_.isFunction(options)){ f = options; } if(!_.isObject(options)){ options = {}; } // ('url', {object}) options.url = url; } if(_.isObject(url)){ if(_.isFunction(options)){ f = options; } options = url; } options.method = verb.toUpperCase(); return obj(options, f); }; }
[ "function", "makeHelper", "(", "obj", ",", "verb", ")", "{", "obj", "[", "verb", "]", "=", "function", "helper", "(", "url", ",", "options", ",", "f", ")", "{", "// ('url')", "if", "(", "_", ".", "isString", "(", "url", ")", ")", "{", "// ('url', f)", "if", "(", "_", ".", "isFunction", "(", "options", ")", ")", "{", "f", "=", "options", ";", "}", "if", "(", "!", "_", ".", "isObject", "(", "options", ")", ")", "{", "options", "=", "{", "}", ";", "}", "// ('url', {object})", "options", ".", "url", "=", "url", ";", "}", "if", "(", "_", ".", "isObject", "(", "url", ")", ")", "{", "if", "(", "_", ".", "isFunction", "(", "options", ")", ")", "{", "f", "=", "options", ";", "}", "options", "=", "url", ";", "}", "options", ".", "method", "=", "verb", ".", "toUpperCase", "(", ")", ";", "return", "obj", "(", "options", ",", "f", ")", ";", "}", ";", "}" ]
adds a helper for HTTP method `verb` to object `obj`
[ "adds", "a", "helper", "for", "HTTP", "method", "verb", "to", "object", "obj" ]
0c6fb14d271b09a15f53ff44f3a16d640a914677
https://github.com/FGRibreau/node-request-retry/blob/0c6fb14d271b09a15f53ff44f3a16d640a914677/index.js#L183-L210
19,091
matrix-org/matrix-appservice-bridge
lib/components/state-lookup.js
StateLookup
function StateLookup(opts) { if (!opts.client) { throw new Error("client property must be supplied"); } this._client = opts.client; this._eventTypes = {}; // store it as a map var self = this; (opts.eventTypes || []).forEach(function(t) { self._eventTypes[t] = true; }); this._dict = { // $room_id: { // syncPromise: Promise, // events: { // $event_type: { // $state_key: { Event } // } // } // } }; }
javascript
function StateLookup(opts) { if (!opts.client) { throw new Error("client property must be supplied"); } this._client = opts.client; this._eventTypes = {}; // store it as a map var self = this; (opts.eventTypes || []).forEach(function(t) { self._eventTypes[t] = true; }); this._dict = { // $room_id: { // syncPromise: Promise, // events: { // $event_type: { // $state_key: { Event } // } // } // } }; }
[ "function", "StateLookup", "(", "opts", ")", "{", "if", "(", "!", "opts", ".", "client", ")", "{", "throw", "new", "Error", "(", "\"client property must be supplied\"", ")", ";", "}", "this", ".", "_client", "=", "opts", ".", "client", ";", "this", ".", "_eventTypes", "=", "{", "}", ";", "// store it as a map", "var", "self", "=", "this", ";", "(", "opts", ".", "eventTypes", "||", "[", "]", ")", ".", "forEach", "(", "function", "(", "t", ")", "{", "self", ".", "_eventTypes", "[", "t", "]", "=", "true", ";", "}", ")", ";", "this", ".", "_dict", "=", "{", "// $room_id: {", "// syncPromise: Promise,", "// events: {", "// $event_type: {", "// $state_key: { Event }", "// }", "// }", "// }", "}", ";", "}" ]
Construct a new state lookup entity. This component stores state events for specific event types which can be queried at a later date. This component will perform network requests to fetch the current state for a given room ID. It relies on {@link StateLookup#onEvent} being called with later events in order to stay up-to-date. This should be connected to the <code>onEvent</code> handler on the {@link Bridge}. @constructor @param {Object} opts Options for this constructor @param {MatrixClient} opts.client Required. The client which will perform /state requests. @param {string[]} opts.eventTypes The state event types to track. @throws if there is no client.
[ "Construct", "a", "new", "state", "lookup", "entity", "." ]
33eb59890b36c0caf043d312f64a04d2526e4554
https://github.com/matrix-org/matrix-appservice-bridge/blob/33eb59890b36c0caf043d312f64a04d2526e4554/lib/components/state-lookup.js#L20-L42
19,092
matrix-org/matrix-appservice-bridge
lib/components/state-lookup.js
function() { self._client.roomState(roomId).then(function(events) { events.forEach(function(ev) { if (self._eventTypes[ev.type]) { if (!r.events[ev.type]) { r.events[ev.type] = {}; } r.events[ev.type][ev.state_key] = ev; } }); resolve(r); }, function(err) { if (err.httpStatus >= 400 && err.httpStatus < 600) { // 4xx, 5xx reject(err); // don't have permission, don't retry. } // wait a bit then try again Promise.delay(3000).then(function() { if (!self._dict[roomId]) { return; } queryRoomState(); }); }); }
javascript
function() { self._client.roomState(roomId).then(function(events) { events.forEach(function(ev) { if (self._eventTypes[ev.type]) { if (!r.events[ev.type]) { r.events[ev.type] = {}; } r.events[ev.type][ev.state_key] = ev; } }); resolve(r); }, function(err) { if (err.httpStatus >= 400 && err.httpStatus < 600) { // 4xx, 5xx reject(err); // don't have permission, don't retry. } // wait a bit then try again Promise.delay(3000).then(function() { if (!self._dict[roomId]) { return; } queryRoomState(); }); }); }
[ "function", "(", ")", "{", "self", ".", "_client", ".", "roomState", "(", "roomId", ")", ".", "then", "(", "function", "(", "events", ")", "{", "events", ".", "forEach", "(", "function", "(", "ev", ")", "{", "if", "(", "self", ".", "_eventTypes", "[", "ev", ".", "type", "]", ")", "{", "if", "(", "!", "r", ".", "events", "[", "ev", ".", "type", "]", ")", "{", "r", ".", "events", "[", "ev", ".", "type", "]", "=", "{", "}", ";", "}", "r", ".", "events", "[", "ev", ".", "type", "]", "[", "ev", ".", "state_key", "]", "=", "ev", ";", "}", "}", ")", ";", "resolve", "(", "r", ")", ";", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ".", "httpStatus", ">=", "400", "&&", "err", ".", "httpStatus", "<", "600", ")", "{", "// 4xx, 5xx", "reject", "(", "err", ")", ";", "// don't have permission, don't retry.", "}", "// wait a bit then try again", "Promise", ".", "delay", "(", "3000", ")", ".", "then", "(", "function", "(", ")", "{", "if", "(", "!", "self", ".", "_dict", "[", "roomId", "]", ")", "{", "return", ";", "}", "queryRoomState", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
convoluted query function so we can do retries on errors
[ "convoluted", "query", "function", "so", "we", "can", "do", "retries", "on", "errors" ]
33eb59890b36c0caf043d312f64a04d2526e4554
https://github.com/matrix-org/matrix-appservice-bridge/blob/33eb59890b36c0caf043d312f64a04d2526e4554/lib/components/state-lookup.js#L92-L116
19,093
matrix-org/matrix-appservice-bridge
lib/components/bridge-store.js
function(d, err, result) { if (err) { d.reject(err); } else { d.resolve(result); } }
javascript
function(d, err, result) { if (err) { d.reject(err); } else { d.resolve(result); } }
[ "function", "(", "d", ",", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "d", ".", "reject", "(", "err", ")", ";", "}", "else", "{", "d", ".", "resolve", "(", "result", ")", ";", "}", "}" ]
wrapper to use promises
[ "wrapper", "to", "use", "promises" ]
33eb59890b36c0caf043d312f64a04d2526e4554
https://github.com/matrix-org/matrix-appservice-bridge/blob/33eb59890b36c0caf043d312f64a04d2526e4554/lib/components/bridge-store.js#L5-L12
19,094
matrix-org/matrix-appservice-bridge
lib/components/request.js
Request
function Request(opts) { opts = opts || {}; this.id = opts.id || generateRequestId(); this.data = opts.data; this.startTs = Date.now(); this.defer = new Promise.defer(); }
javascript
function Request(opts) { opts = opts || {}; this.id = opts.id || generateRequestId(); this.data = opts.data; this.startTs = Date.now(); this.defer = new Promise.defer(); }
[ "function", "Request", "(", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "id", "=", "opts", ".", "id", "||", "generateRequestId", "(", ")", ";", "this", ".", "data", "=", "opts", ".", "data", ";", "this", ".", "startTs", "=", "Date", ".", "now", "(", ")", ";", "this", ".", "defer", "=", "new", "Promise", ".", "defer", "(", ")", ";", "}" ]
Construct a new Request. @constructor @param {Object} opts Options for this request. @param {string=} opts.id Optional ID to set on this request. One will be generated if this is not provided. @param {*=} opts.data Optional data to associate with this request.
[ "Construct", "a", "new", "Request", "." ]
33eb59890b36c0caf043d312f64a04d2526e4554
https://github.com/matrix-org/matrix-appservice-bridge/blob/33eb59890b36c0caf043d312f64a04d2526e4554/lib/components/request.js#L16-L22
19,095
matrix-org/matrix-appservice-bridge
lib/components/room-bridge-store.js
Entry
function Entry(doc) { doc = doc || {}; this.id = doc.id; this.matrix = doc.matrix_id ? new MatrixRoom(doc.matrix_id, doc.matrix) : undefined; this.remote = doc.remote_id ? new RemoteRoom(doc.remote_id, doc.remote) : undefined; this.data = doc.data; }
javascript
function Entry(doc) { doc = doc || {}; this.id = doc.id; this.matrix = doc.matrix_id ? new MatrixRoom(doc.matrix_id, doc.matrix) : undefined; this.remote = doc.remote_id ? new RemoteRoom(doc.remote_id, doc.remote) : undefined; this.data = doc.data; }
[ "function", "Entry", "(", "doc", ")", "{", "doc", "=", "doc", "||", "{", "}", ";", "this", ".", "id", "=", "doc", ".", "id", ";", "this", ".", "matrix", "=", "doc", ".", "matrix_id", "?", "new", "MatrixRoom", "(", "doc", ".", "matrix_id", ",", "doc", ".", "matrix", ")", ":", "undefined", ";", "this", ".", "remote", "=", "doc", ".", "remote_id", "?", "new", "RemoteRoom", "(", "doc", ".", "remote_id", ",", "doc", ".", "remote", ")", ":", "undefined", ";", "this", ".", "data", "=", "doc", ".", "data", ";", "}" ]
Construct a new RoomBridgeStore Entry. @constructor @typedef RoomBridgeStore~Entry @property {string} id The unique ID for this entry. @property {?MatrixRoom} matrix The matrix room, if applicable. @property {?RemoteRoom} remote The remote room, if applicable. @property {?Object} data Information about this mapping, which may be an empty.
[ "Construct", "a", "new", "RoomBridgeStore", "Entry", "." ]
33eb59890b36c0caf043d312f64a04d2526e4554
https://github.com/matrix-org/matrix-appservice-bridge/blob/33eb59890b36c0caf043d312f64a04d2526e4554/lib/components/room-bridge-store.js#L438-L444
19,096
matrix-org/matrix-appservice-bridge
lib/components/room-bridge-store.js
serializeEntry
function serializeEntry(entry) { return { id: entry.id, remote_id: entry.remote ? entry.remote.getId() : undefined, matrix_id: entry.matrix ? entry.matrix.getId() : undefined, remote: entry.remote ? entry.remote.serialize() : undefined, matrix: entry.matrix ? entry.matrix.serialize() : undefined, data: entry.data } }
javascript
function serializeEntry(entry) { return { id: entry.id, remote_id: entry.remote ? entry.remote.getId() : undefined, matrix_id: entry.matrix ? entry.matrix.getId() : undefined, remote: entry.remote ? entry.remote.serialize() : undefined, matrix: entry.matrix ? entry.matrix.serialize() : undefined, data: entry.data } }
[ "function", "serializeEntry", "(", "entry", ")", "{", "return", "{", "id", ":", "entry", ".", "id", ",", "remote_id", ":", "entry", ".", "remote", "?", "entry", ".", "remote", ".", "getId", "(", ")", ":", "undefined", ",", "matrix_id", ":", "entry", ".", "matrix", "?", "entry", ".", "matrix", ".", "getId", "(", ")", ":", "undefined", ",", "remote", ":", "entry", ".", "remote", "?", "entry", ".", "remote", ".", "serialize", "(", ")", ":", "undefined", ",", "matrix", ":", "entry", ".", "matrix", "?", "entry", ".", "matrix", ".", "serialize", "(", ")", ":", "undefined", ",", "data", ":", "entry", ".", "data", "}", "}" ]
not a member function so callers can provide a POJO
[ "not", "a", "member", "function", "so", "callers", "can", "provide", "a", "POJO" ]
33eb59890b36c0caf043d312f64a04d2526e4554
https://github.com/matrix-org/matrix-appservice-bridge/blob/33eb59890b36c0caf043d312f64a04d2526e4554/lib/components/room-bridge-store.js#L447-L456
19,097
matrix-org/matrix-appservice-bridge
lib/models/users/matrix.js
MatrixUser
function MatrixUser(userId, data, escape=true) { if (!userId) { throw new Error("Missing user_id"); } if (data && Object.prototype.toString.call(data) !== "[object Object]") { throw new Error("data arg must be an Object"); } this.userId = userId; const split = this.userId.split(":"); this.localpart = split[0].substring(1); this.host = split[1]; if (escape) { this.escapeUserId(); } this._data = data || {}; }
javascript
function MatrixUser(userId, data, escape=true) { if (!userId) { throw new Error("Missing user_id"); } if (data && Object.prototype.toString.call(data) !== "[object Object]") { throw new Error("data arg must be an Object"); } this.userId = userId; const split = this.userId.split(":"); this.localpart = split[0].substring(1); this.host = split[1]; if (escape) { this.escapeUserId(); } this._data = data || {}; }
[ "function", "MatrixUser", "(", "userId", ",", "data", ",", "escape", "=", "true", ")", "{", "if", "(", "!", "userId", ")", "{", "throw", "new", "Error", "(", "\"Missing user_id\"", ")", ";", "}", "if", "(", "data", "&&", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "data", ")", "!==", "\"[object Object]\"", ")", "{", "throw", "new", "Error", "(", "\"data arg must be an Object\"", ")", ";", "}", "this", ".", "userId", "=", "userId", ";", "const", "split", "=", "this", ".", "userId", ".", "split", "(", "\":\"", ")", ";", "this", ".", "localpart", "=", "split", "[", "0", "]", ".", "substring", "(", "1", ")", ";", "this", ".", "host", "=", "split", "[", "1", "]", ";", "if", "(", "escape", ")", "{", "this", ".", "escapeUserId", "(", ")", ";", "}", "this", ".", "_data", "=", "data", "||", "{", "}", ";", "}" ]
Construct a Matrix user. @constructor @param {string} userId The user_id of the user. @param {Object=} data Serialized data values @param {boolean} escape [true] Escape the user's localpart.
[ "Construct", "a", "Matrix", "user", "." ]
33eb59890b36c0caf043d312f64a04d2526e4554
https://github.com/matrix-org/matrix-appservice-bridge/blob/33eb59890b36c0caf043d312f64a04d2526e4554/lib/models/users/matrix.js#L10-L25
19,098
matrix-org/matrix-appservice-bridge
lib/components/app-service-bot.js
AppServiceBot
function AppServiceBot(client, registration, memberCache) { this.client = client; this.registration = registration.getOutput(); this.memberCache = memberCache; var self = this; // yank out the exclusive user ID regex strings this.exclusiveUserRegexes = []; if (this.registration.namespaces && this.registration.namespaces.users) { this.registration.namespaces.users.forEach(function(userEntry) { if (!userEntry.exclusive) { return; } self.exclusiveUserRegexes.push(userEntry.regex); }); } }
javascript
function AppServiceBot(client, registration, memberCache) { this.client = client; this.registration = registration.getOutput(); this.memberCache = memberCache; var self = this; // yank out the exclusive user ID regex strings this.exclusiveUserRegexes = []; if (this.registration.namespaces && this.registration.namespaces.users) { this.registration.namespaces.users.forEach(function(userEntry) { if (!userEntry.exclusive) { return; } self.exclusiveUserRegexes.push(userEntry.regex); }); } }
[ "function", "AppServiceBot", "(", "client", ",", "registration", ",", "memberCache", ")", "{", "this", ".", "client", "=", "client", ";", "this", ".", "registration", "=", "registration", ".", "getOutput", "(", ")", ";", "this", ".", "memberCache", "=", "memberCache", ";", "var", "self", "=", "this", ";", "// yank out the exclusive user ID regex strings", "this", ".", "exclusiveUserRegexes", "=", "[", "]", ";", "if", "(", "this", ".", "registration", ".", "namespaces", "&&", "this", ".", "registration", ".", "namespaces", ".", "users", ")", "{", "this", ".", "registration", ".", "namespaces", ".", "users", ".", "forEach", "(", "function", "(", "userEntry", ")", "{", "if", "(", "!", "userEntry", ".", "exclusive", ")", "{", "return", ";", "}", "self", ".", "exclusiveUserRegexes", ".", "push", "(", "userEntry", ".", "regex", ")", ";", "}", ")", ";", "}", "}" ]
Construct an AS bot user which has various helper methods. @constructor @param {MatrixClient} client The client instance configured for the AS bot. @param {AppServiceRegistration} registration The registration that the bot is following. Used to determine which user IDs it is controlling. @param {MembershipCache} memberCache The bridges membership cache instance, for storing membership the bot has discovered.
[ "Construct", "an", "AS", "bot", "user", "which", "has", "various", "helper", "methods", "." ]
33eb59890b36c0caf043d312f64a04d2526e4554
https://github.com/matrix-org/matrix-appservice-bridge/blob/33eb59890b36c0caf043d312f64a04d2526e4554/lib/components/app-service-bot.js#L12-L27
19,099
lirown/graphql-custom-directives
src/custom.js
defaultResolveFn
function defaultResolveFn(source, args, context, info) { var fieldName = info.fieldName; // ensure source is a value for which property access is acceptable. if (typeof source === 'object' || typeof source === 'function') { return typeof source[fieldName] === 'function' ? source[fieldName]() : source[fieldName]; } }
javascript
function defaultResolveFn(source, args, context, info) { var fieldName = info.fieldName; // ensure source is a value for which property access is acceptable. if (typeof source === 'object' || typeof source === 'function') { return typeof source[fieldName] === 'function' ? source[fieldName]() : source[fieldName]; } }
[ "function", "defaultResolveFn", "(", "source", ",", "args", ",", "context", ",", "info", ")", "{", "var", "fieldName", "=", "info", ".", "fieldName", ";", "// ensure source is a value for which property access is acceptable.", "if", "(", "typeof", "source", "===", "'object'", "||", "typeof", "source", "===", "'function'", ")", "{", "return", "typeof", "source", "[", "fieldName", "]", "===", "'function'", "?", "source", "[", "fieldName", "]", "(", ")", ":", "source", "[", "fieldName", "]", ";", "}", "}" ]
If a resolve function is not given, then a default resolve behavior is used which takes the property of the source object of the same name as the field and returns it as the result, or if it's a function, returns the result of calling that function.
[ "If", "a", "resolve", "function", "is", "not", "given", "then", "a", "default", "resolve", "behavior", "is", "used", "which", "takes", "the", "property", "of", "the", "source", "object", "of", "the", "same", "name", "as", "the", "field", "and", "returns", "it", "as", "the", "result", "or", "if", "it", "s", "a", "function", "returns", "the", "result", "of", "calling", "that", "function", "." ]
a0709eaa07f264e3431ce91188e4ac30978644d6
https://github.com/lirown/graphql-custom-directives/blob/a0709eaa07f264e3431ce91188e4ac30978644d6/src/custom.js#L12-L20