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
42,000
konfirm/node-is-type
source/type.js
isType
function isType(type, input) { if (input === null) { return type.toLowerCase() === 'null'; } return typeof input === type.toLowerCase() || Type.is(type, input); }
javascript
function isType(type, input) { if (input === null) { return type.toLowerCase() === 'null'; } return typeof input === type.toLowerCase() || Type.is(type, input); }
[ "function", "isType", "(", "type", ",", "input", ")", "{", "if", "(", "input", "===", "null", ")", "{", "return", "type", ".", "toLowerCase", "(", ")", "===", "'null'", ";", "}", "return", "typeof", "input", "===", "type", ".", "toLowerCase", "(", ")", "||", "Type", ".", "is", "(", "type", ",", "input", ")", ";", "}" ]
Determine if the given input matches the type @param {string} type @param {any} input @return {boolean} is type
[ "Determine", "if", "the", "given", "input", "matches", "the", "type" ]
daaa18de5ccfbca7661357bcee855bb7df26c5c8
https://github.com/konfirm/node-is-type/blob/daaa18de5ccfbca7661357bcee855bb7df26c5c8/source/type.js#L36-L42
42,001
konfirm/node-is-type
source/type.js
cachedTypeDetector
function cachedTypeDetector(type) { if (!cache.has(type)) { cache.set(type, (input) => isType(type, input) || typeInAncestry(type, input)); } return cache.get(type); }
javascript
function cachedTypeDetector(type) { if (!cache.has(type)) { cache.set(type, (input) => isType(type, input) || typeInAncestry(type, input)); } return cache.get(type); }
[ "function", "cachedTypeDetector", "(", "type", ")", "{", "if", "(", "!", "cache", ".", "has", "(", "type", ")", ")", "{", "cache", ".", "set", "(", "type", ",", "(", "input", ")", "=>", "isType", "(", "type", ",", "input", ")", "||", "typeInAncestry", "(", "type", ",", "input", ")", ")", ";", "}", "return", "cache", ".", "get", "(", "type", ")", ";", "}" ]
Ensure a delegate function exists for the given type and return it @param {string} type @return {function} detector
[ "Ensure", "a", "delegate", "function", "exists", "for", "the", "given", "type", "and", "return", "it" ]
daaa18de5ccfbca7661357bcee855bb7df26c5c8
https://github.com/konfirm/node-is-type/blob/daaa18de5ccfbca7661357bcee855bb7df26c5c8/source/type.js#L50-L56
42,002
bootprint/customize-write-files
index.js
mapFiles
async function mapFiles (customizeResult, targetDir, callback) { const files = mergeEngineResults(customizeResult) const results = mapValues(files, (file, filename) => { // Write each file const fullpath = path.join(targetDir, filename) return callback(fullpath, file.contents) }) return deep(results) }
javascript
async function mapFiles (customizeResult, targetDir, callback) { const files = mergeEngineResults(customizeResult) const results = mapValues(files, (file, filename) => { // Write each file const fullpath = path.join(targetDir, filename) return callback(fullpath, file.contents) }) return deep(results) }
[ "async", "function", "mapFiles", "(", "customizeResult", ",", "targetDir", ",", "callback", ")", "{", "const", "files", "=", "mergeEngineResults", "(", "customizeResult", ")", "const", "results", "=", "mapValues", "(", "files", ",", "(", "file", ",", "filename", ")", "=>", "{", "// Write each file", "const", "fullpath", "=", "path", ".", "join", "(", "targetDir", ",", "filename", ")", "return", "callback", "(", "fullpath", ",", "file", ".", "contents", ")", "}", ")", "return", "deep", "(", "results", ")", "}" ]
Map the merged files in the customize-result onto a function a promised object of values. The type T is the return value of the callback (promised) @param {object<object<string|Buffer|Readable|undefined>>} customizeResult @param {function(fullpath: string, contents: (string|Buffer|Readable|undefined)):Promise<T>} callback functions that is called for each file @return {Promise<object<T>>}
[ "Map", "the", "merged", "files", "in", "the", "customize", "-", "result", "onto", "a", "function", "a", "promised", "object", "of", "values", "." ]
af77ce78b5196f40ce90670bfdb6e1e7e496a415
https://github.com/bootprint/customize-write-files/blob/af77ce78b5196f40ce90670bfdb6e1e7e496a415/index.js#L65-L73
42,003
bootprint/customize-write-files
index.js
mapValues
function mapValues (obj, fn) { return Object.keys(obj).reduce(function (subresult, key) { subresult[key] = fn(obj[key], key) return subresult }, {}) }
javascript
function mapValues (obj, fn) { return Object.keys(obj).reduce(function (subresult, key) { subresult[key] = fn(obj[key], key) return subresult }, {}) }
[ "function", "mapValues", "(", "obj", ",", "fn", ")", "{", "return", "Object", ".", "keys", "(", "obj", ")", ".", "reduce", "(", "function", "(", "subresult", ",", "key", ")", "{", "subresult", "[", "key", "]", "=", "fn", "(", "obj", "[", "key", "]", ",", "key", ")", "return", "subresult", "}", ",", "{", "}", ")", "}" ]
Apply a function to each value of an object and return the result @param {object<any>} obj @param {function(any, string): any} fn @returns {object<any>} @private
[ "Apply", "a", "function", "to", "each", "value", "of", "an", "object", "and", "return", "the", "result" ]
af77ce78b5196f40ce90670bfdb6e1e7e496a415
https://github.com/bootprint/customize-write-files/blob/af77ce78b5196f40ce90670bfdb6e1e7e496a415/index.js#L82-L87
42,004
eface2face/meteor-blaze
blaze.js
function (elem, func) { var elt = new TeardownCallback(func); var propName = DOMBackend.Teardown._CB_PROP; if (! elem[propName]) { // create an empty node that is never unlinked elem[propName] = new TeardownCallback; // Set up the event, only the first time. $jq(elem).on(DOMBackend.Teardown._JQUERY_EVENT_NAME, NOOP); } elt.linkBefore(elem[propName]); return elt; // so caller can call stop() }
javascript
function (elem, func) { var elt = new TeardownCallback(func); var propName = DOMBackend.Teardown._CB_PROP; if (! elem[propName]) { // create an empty node that is never unlinked elem[propName] = new TeardownCallback; // Set up the event, only the first time. $jq(elem).on(DOMBackend.Teardown._JQUERY_EVENT_NAME, NOOP); } elt.linkBefore(elem[propName]); return elt; // so caller can call stop() }
[ "function", "(", "elem", ",", "func", ")", "{", "var", "elt", "=", "new", "TeardownCallback", "(", "func", ")", ";", "var", "propName", "=", "DOMBackend", ".", "Teardown", ".", "_CB_PROP", ";", "if", "(", "!", "elem", "[", "propName", "]", ")", "{", "// create an empty node that is never unlinked", "elem", "[", "propName", "]", "=", "new", "TeardownCallback", ";", "// Set up the event, only the first time.", "$jq", "(", "elem", ")", ".", "on", "(", "DOMBackend", ".", "Teardown", ".", "_JQUERY_EVENT_NAME", ",", "NOOP", ")", ";", "}", "elt", ".", "linkBefore", "(", "elem", "[", "propName", "]", ")", ";", "return", "elt", ";", "// so caller can call stop()", "}" ]
Registers a callback function to be called when the given element or one of its ancestors is removed from the DOM via the backend library. The callback function is called at most once, and it receives the element in question as an argument.
[ "Registers", "a", "callback", "function", "to", "be", "called", "when", "the", "given", "element", "or", "one", "of", "its", "ancestors", "is", "removed", "from", "the", "DOM", "via", "the", "backend", "library", ".", "The", "callback", "function", "is", "called", "at", "most", "once", "and", "it", "receives", "the", "element", "in", "question", "as", "an", "argument", "." ]
c284d160b7edf2bab3a2568a94094d5fea7bac7f
https://github.com/eface2face/meteor-blaze/blob/c284d160b7edf2bab3a2568a94094d5fea7bac7f/blaze.js#L160-L175
42,005
eface2face/meteor-blaze
blaze.js
function (elem) { var elems = []; // Array.prototype.slice.call doesn't work when given a NodeList in // IE8 ("JScript object expected"). var nodeList = elem.getElementsByTagName('*'); for (var i = 0; i < nodeList.length; i++) { elems.push(nodeList[i]); } elems.push(elem); $jq.cleanData(elems); }
javascript
function (elem) { var elems = []; // Array.prototype.slice.call doesn't work when given a NodeList in // IE8 ("JScript object expected"). var nodeList = elem.getElementsByTagName('*'); for (var i = 0; i < nodeList.length; i++) { elems.push(nodeList[i]); } elems.push(elem); $jq.cleanData(elems); }
[ "function", "(", "elem", ")", "{", "var", "elems", "=", "[", "]", ";", "// Array.prototype.slice.call doesn't work when given a NodeList in", "// IE8 (\"JScript object expected\").", "var", "nodeList", "=", "elem", ".", "getElementsByTagName", "(", "'*'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "nodeList", ".", "length", ";", "i", "++", ")", "{", "elems", ".", "push", "(", "nodeList", "[", "i", "]", ")", ";", "}", "elems", ".", "push", "(", "elem", ")", ";", "$jq", ".", "cleanData", "(", "elems", ")", ";", "}" ]
Recursively call all teardown hooks, in the backend and registered through DOMBackend.onElementTeardown.
[ "Recursively", "call", "all", "teardown", "hooks", "in", "the", "backend", "and", "registered", "through", "DOMBackend", ".", "onElementTeardown", "." ]
c284d160b7edf2bab3a2568a94094d5fea7bac7f
https://github.com/eface2face/meteor-blaze/blob/c284d160b7edf2bab3a2568a94094d5fea7bac7f/blaze.js#L178-L188
42,006
eface2face/meteor-blaze
blaze.js
function () { var eventDict = element.$blaze_events; if (! eventDict) return; // newHandlerRecs has only one item unless you specify multiple // event types. If this code is slow, it's because we have to // iterate over handlerList here. Clearing a whole handlerList // via stop() methods is O(N^2) in the number of handlers on // an element. for (var i = 0; i < newHandlerRecs.length; i++) { var handlerToRemove = newHandlerRecs[i]; var info = eventDict[handlerToRemove.type]; if (! info) continue; var handlerList = info.handlers; for (var j = handlerList.length - 1; j >= 0; j--) { if (handlerList[j] === handlerToRemove) { handlerToRemove.unbind(); handlerList.splice(j, 1); // remove handlerList[j] } } } newHandlerRecs.length = 0; }
javascript
function () { var eventDict = element.$blaze_events; if (! eventDict) return; // newHandlerRecs has only one item unless you specify multiple // event types. If this code is slow, it's because we have to // iterate over handlerList here. Clearing a whole handlerList // via stop() methods is O(N^2) in the number of handlers on // an element. for (var i = 0; i < newHandlerRecs.length; i++) { var handlerToRemove = newHandlerRecs[i]; var info = eventDict[handlerToRemove.type]; if (! info) continue; var handlerList = info.handlers; for (var j = handlerList.length - 1; j >= 0; j--) { if (handlerList[j] === handlerToRemove) { handlerToRemove.unbind(); handlerList.splice(j, 1); // remove handlerList[j] } } } newHandlerRecs.length = 0; }
[ "function", "(", ")", "{", "var", "eventDict", "=", "element", ".", "$blaze_events", ";", "if", "(", "!", "eventDict", ")", "return", ";", "// newHandlerRecs has only one item unless you specify multiple", "// event types. If this code is slow, it's because we have to", "// iterate over handlerList here. Clearing a whole handlerList", "// via stop() methods is O(N^2) in the number of handlers on", "// an element.", "for", "(", "var", "i", "=", "0", ";", "i", "<", "newHandlerRecs", ".", "length", ";", "i", "++", ")", "{", "var", "handlerToRemove", "=", "newHandlerRecs", "[", "i", "]", ";", "var", "info", "=", "eventDict", "[", "handlerToRemove", ".", "type", "]", ";", "if", "(", "!", "info", ")", "continue", ";", "var", "handlerList", "=", "info", ".", "handlers", ";", "for", "(", "var", "j", "=", "handlerList", ".", "length", "-", "1", ";", "j", ">=", "0", ";", "j", "--", ")", "{", "if", "(", "handlerList", "[", "j", "]", "===", "handlerToRemove", ")", "{", "handlerToRemove", ".", "unbind", "(", ")", ";", "handlerList", ".", "splice", "(", "j", ",", "1", ")", ";", "// remove handlerList[j]", "}", "}", "}", "newHandlerRecs", ".", "length", "=", "0", ";", "}" ]
closes over just `element` and `newHandlerRecs`
[ "closes", "over", "just", "element", "and", "newHandlerRecs" ]
c284d160b7edf2bab3a2568a94094d5fea7bac7f
https://github.com/eface2face/meteor-blaze/blob/c284d160b7edf2bab3a2568a94094d5fea7bac7f/blaze.js#L884-L907
42,007
eface2face/meteor-blaze
blaze.js
function (content) { checkRenderContent(content); if (content instanceof Blaze.Template) { return content.constructView(); } else if (content instanceof Blaze.View) { return content; } else { var func = content; if (typeof func !== 'function') { func = function () { return content; }; } return Blaze.View('render', func); } }
javascript
function (content) { checkRenderContent(content); if (content instanceof Blaze.Template) { return content.constructView(); } else if (content instanceof Blaze.View) { return content; } else { var func = content; if (typeof func !== 'function') { func = function () { return content; }; } return Blaze.View('render', func); } }
[ "function", "(", "content", ")", "{", "checkRenderContent", "(", "content", ")", ";", "if", "(", "content", "instanceof", "Blaze", ".", "Template", ")", "{", "return", "content", ".", "constructView", "(", ")", ";", "}", "else", "if", "(", "content", "instanceof", "Blaze", ".", "View", ")", "{", "return", "content", ";", "}", "else", "{", "var", "func", "=", "content", ";", "if", "(", "typeof", "func", "!==", "'function'", ")", "{", "func", "=", "function", "(", ")", "{", "return", "content", ";", "}", ";", "}", "return", "Blaze", ".", "View", "(", "'render'", ",", "func", ")", ";", "}", "}" ]
For Blaze.render and Blaze.toHTML, take content and wrap it in a View, unless it's a single View or Template already.
[ "For", "Blaze", ".", "render", "and", "Blaze", ".", "toHTML", "take", "content", "and", "wrap", "it", "in", "a", "View", "unless", "it", "s", "a", "single", "View", "or", "Template", "already", "." ]
c284d160b7edf2bab3a2568a94094d5fea7bac7f
https://github.com/eface2face/meteor-blaze/blob/c284d160b7edf2bab3a2568a94094d5fea7bac7f/blaze.js#L2094-L2110
42,008
eface2face/meteor-blaze
blaze.js
function (x) { if (typeof x === 'function') { return function () { var data = Blaze.getData(); if (data == null) data = {}; return x.apply(data, arguments); }; } return x; }
javascript
function (x) { if (typeof x === 'function') { return function () { var data = Blaze.getData(); if (data == null) data = {}; return x.apply(data, arguments); }; } return x; }
[ "function", "(", "x", ")", "{", "if", "(", "typeof", "x", "===", "'function'", ")", "{", "return", "function", "(", ")", "{", "var", "data", "=", "Blaze", ".", "getData", "(", ")", ";", "if", "(", "data", "==", "null", ")", "data", "=", "{", "}", ";", "return", "x", ".", "apply", "(", "data", ",", "arguments", ")", ";", "}", ";", "}", "return", "x", ";", "}" ]
If `x` is a function, binds the value of `this` for that function to the current data context.
[ "If", "x", "is", "a", "function", "binds", "the", "value", "of", "this", "for", "that", "function", "to", "the", "current", "data", "context", "." ]
c284d160b7edf2bab3a2568a94094d5fea7bac7f
https://github.com/eface2face/meteor-blaze/blob/c284d160b7edf2bab3a2568a94094d5fea7bac7f/blaze.js#L2797-L2807
42,009
the-labo/the-resource-base
lib/isResourceClass.js
isResourceClass
function isResourceClass(Class) { const hitByClass = Class.prototype instanceof TheResource || Class === TheResource if (hitByClass) { return true } let named = Class while (!!named) { const hit = named.name && named.name.startsWith('TheResource') if (hit) { return true } named = named.__proto__ } return false }
javascript
function isResourceClass(Class) { const hitByClass = Class.prototype instanceof TheResource || Class === TheResource if (hitByClass) { return true } let named = Class while (!!named) { const hit = named.name && named.name.startsWith('TheResource') if (hit) { return true } named = named.__proto__ } return false }
[ "function", "isResourceClass", "(", "Class", ")", "{", "const", "hitByClass", "=", "Class", ".", "prototype", "instanceof", "TheResource", "||", "Class", "===", "TheResource", "if", "(", "hitByClass", ")", "{", "return", "true", "}", "let", "named", "=", "Class", "while", "(", "!", "!", "named", ")", "{", "const", "hit", "=", "named", ".", "name", "&&", "named", ".", "name", ".", "startsWith", "(", "'TheResource'", ")", "if", "(", "hit", ")", "{", "return", "true", "}", "named", "=", "named", ".", "__proto__", "}", "return", "false", "}" ]
Detect is a resource class @param Class
[ "Detect", "is", "a", "resource", "class" ]
76be3780904893641851f17e9edda316c63f147a
https://github.com/the-labo/the-resource-base/blob/76be3780904893641851f17e9edda316c63f147a/lib/isResourceClass.js#L13-L28
42,010
mongodb-js/deployment-model
lib/probe.js
Probe
function Probe(connection, done) { if (!(this instanceof Probe)) { return new Probe(connection, done); } if (typeof connection === 'string') { connection = Connection.from( Deployment.getId(connection)); } debug('connection is `%j`', connection); this.deployment = new Deployment({ _id: Instance.getId(connection.getId()), name: connection.name }); this.connection = connection; this.db = null; this.metadata = null; if (typeof done === 'function') { this.exec(done); } }
javascript
function Probe(connection, done) { if (!(this instanceof Probe)) { return new Probe(connection, done); } if (typeof connection === 'string') { connection = Connection.from( Deployment.getId(connection)); } debug('connection is `%j`', connection); this.deployment = new Deployment({ _id: Instance.getId(connection.getId()), name: connection.name }); this.connection = connection; this.db = null; this.metadata = null; if (typeof done === 'function') { this.exec(done); } }
[ "function", "Probe", "(", "connection", ",", "done", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Probe", ")", ")", "{", "return", "new", "Probe", "(", "connection", ",", "done", ")", ";", "}", "if", "(", "typeof", "connection", "===", "'string'", ")", "{", "connection", "=", "Connection", ".", "from", "(", "Deployment", ".", "getId", "(", "connection", ")", ")", ";", "}", "debug", "(", "'connection is `%j`'", ",", "connection", ")", ";", "this", ".", "deployment", "=", "new", "Deployment", "(", "{", "_id", ":", "Instance", ".", "getId", "(", "connection", ".", "getId", "(", ")", ")", ",", "name", ":", "connection", ".", "name", "}", ")", ";", "this", ".", "connection", "=", "connection", ";", "this", ".", "db", "=", "null", ";", "this", ".", "metadata", "=", "null", ";", "if", "(", "typeof", "done", "===", "'function'", ")", "{", "this", ".", "exec", "(", "done", ")", ";", "}", "}" ]
Use the metadata of `connection` to discover details about the MongoDB deployment behind it and persist the results in `store`. @param {Connection} connection @param {Function} done - Callback `(err, {Deployment})` @return {Probe} @api public
[ "Use", "the", "metadata", "of", "connection", "to", "discover", "details", "about", "the", "MongoDB", "deployment", "behind", "it", "and", "persist", "the", "results", "in", "store", "." ]
f3a7da2ede53db020e1fc9d1899071184d5c5e9f
https://github.com/mongodb-js/deployment-model/blob/f3a7da2ede53db020e1fc9d1899071184d5c5e9f/lib/probe.js#L21-L45
42,011
Mammut-FE/nejm
src/util/chain/NodeList.js
function(_dest, _src){ var _nodeName, _attr; if (_dest.nodeType !== 1) { return; } // lt ie9 才有 if (_dest.clearAttributes) { _dest.clearAttributes(); _dest.mergeAttributes(_src); } // 判断是否有需要处理属性的节点 _nodeName = _dest.nodeName.toLowerCase(); if(_prop = _definitions.fixProps[_nodeName]){ _dest[_prop] = _src[_prop]; } //移除节点标示 _dest.removeAttribute($._$signal); // 移除ID: TODO? 是否允许有重复ID? _dest.removeAttribute("id"); }
javascript
function(_dest, _src){ var _nodeName, _attr; if (_dest.nodeType !== 1) { return; } // lt ie9 才有 if (_dest.clearAttributes) { _dest.clearAttributes(); _dest.mergeAttributes(_src); } // 判断是否有需要处理属性的节点 _nodeName = _dest.nodeName.toLowerCase(); if(_prop = _definitions.fixProps[_nodeName]){ _dest[_prop] = _src[_prop]; } //移除节点标示 _dest.removeAttribute($._$signal); // 移除ID: TODO? 是否允许有重复ID? _dest.removeAttribute("id"); }
[ "function", "(", "_dest", ",", "_src", ")", "{", "var", "_nodeName", ",", "_attr", ";", "if", "(", "_dest", ".", "nodeType", "!==", "1", ")", "{", "return", ";", "}", "// lt ie9 才有", "if", "(", "_dest", ".", "clearAttributes", ")", "{", "_dest", ".", "clearAttributes", "(", ")", ";", "_dest", ".", "mergeAttributes", "(", "_src", ")", ";", "}", "// 判断是否有需要处理属性的节点", "_nodeName", "=", "_dest", ".", "nodeName", ".", "toLowerCase", "(", ")", ";", "if", "(", "_prop", "=", "_definitions", ".", "fixProps", "[", "_nodeName", "]", ")", "{", "_dest", "[", "_prop", "]", "=", "_src", "[", "_prop", "]", ";", "}", "//移除节点标示", "_dest", ".", "removeAttribute", "(", "$", ".", "_$signal", ")", ";", "// 移除ID: TODO? 是否允许有重复ID?", "_dest", ".", "removeAttribute", "(", "\"id\"", ")", ";", "}" ]
dest src attribute fixed
[ "dest", "src", "attribute", "fixed" ]
dfc09ac66a8d67620a7aea65e34d8a179976b3fb
https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/util/chain/NodeList.js#L387-L407
42,012
hairyhenderson/node-fellowshipone
lib/person_addresses.js
PersonAddresses
function PersonAddresses (f1, personID) { if (!personID) { throw new Error('PersonAddresses requires a person ID!') } Addresses.call(this, f1, { path: '/People/' + personID + '/Addresses' }) }
javascript
function PersonAddresses (f1, personID) { if (!personID) { throw new Error('PersonAddresses requires a person ID!') } Addresses.call(this, f1, { path: '/People/' + personID + '/Addresses' }) }
[ "function", "PersonAddresses", "(", "f1", ",", "personID", ")", "{", "if", "(", "!", "personID", ")", "{", "throw", "new", "Error", "(", "'PersonAddresses requires a person ID!'", ")", "}", "Addresses", ".", "call", "(", "this", ",", "f1", ",", "{", "path", ":", "'/People/'", "+", "personID", "+", "'/Addresses'", "}", ")", "}" ]
The Addresses object, in a Person context. @param {Object} f1 - the F1 object @param {Number} personID - the Person ID, for context
[ "The", "Addresses", "object", "in", "a", "Person", "context", "." ]
5e80eb9ec31fb6dceee1e8c211e7b6e0e373b08b
https://github.com/hairyhenderson/node-fellowshipone/blob/5e80eb9ec31fb6dceee1e8c211e7b6e0e373b08b/lib/person_addresses.js#L10-L17
42,013
the-labo/the-html
shim/TheHtmlStyle.js
TheHtmlStyle
function TheHtmlStyle(_ref) { var className = _ref.className, id = _ref.id, options = _ref.options; return _react.default.createElement(_theStyle.TheStyle, (0, _extends2.default)({ id: id }, { className: (0, _classnames.default)('the-html-style', className), styles: TheHtmlStyle.data(options) })); }
javascript
function TheHtmlStyle(_ref) { var className = _ref.className, id = _ref.id, options = _ref.options; return _react.default.createElement(_theStyle.TheStyle, (0, _extends2.default)({ id: id }, { className: (0, _classnames.default)('the-html-style', className), styles: TheHtmlStyle.data(options) })); }
[ "function", "TheHtmlStyle", "(", "_ref", ")", "{", "var", "className", "=", "_ref", ".", "className", ",", "id", "=", "_ref", ".", "id", ",", "options", "=", "_ref", ".", "options", ";", "return", "_react", ".", "default", ".", "createElement", "(", "_theStyle", ".", "TheStyle", ",", "(", "0", ",", "_extends2", ".", "default", ")", "(", "{", "id", ":", "id", "}", ",", "{", "className", ":", "(", "0", ",", "_classnames", ".", "default", ")", "(", "'the-html-style'", ",", "className", ")", ",", "styles", ":", "TheHtmlStyle", ".", "data", "(", "options", ")", "}", ")", ")", ";", "}" ]
Style for TheHtml
[ "Style", "for", "TheHtml" ]
df3c2ccff712a4a2da45f2ce1d8695eca007d08c
https://github.com/the-labo/the-html/blob/df3c2ccff712a4a2da45f2ce1d8695eca007d08c/shim/TheHtmlStyle.js#L21-L31
42,014
nanlabs/econsole
index.js
initFileLogger
function initFileLogger(filepath) { currentFilePath = filepath || currentFilePath; var logDir = path.dirname(currentFilePath); appenders.push(logToFile); if(!fs.existsSync(logDir)) fs.mkdirSync(logDir); }
javascript
function initFileLogger(filepath) { currentFilePath = filepath || currentFilePath; var logDir = path.dirname(currentFilePath); appenders.push(logToFile); if(!fs.existsSync(logDir)) fs.mkdirSync(logDir); }
[ "function", "initFileLogger", "(", "filepath", ")", "{", "currentFilePath", "=", "filepath", "||", "currentFilePath", ";", "var", "logDir", "=", "path", ".", "dirname", "(", "currentFilePath", ")", ";", "appenders", ".", "push", "(", "logToFile", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "logDir", ")", ")", "fs", ".", "mkdirSync", "(", "logDir", ")", ";", "}" ]
Initialzes the file logger @param filepath path to the log file
[ "Initialzes", "the", "file", "logger" ]
2377a33e266b4e39a35cf981ece14b6b6a16af46
https://github.com/nanlabs/econsole/blob/2377a33e266b4e39a35cf981ece14b6b6a16af46/index.js#L134-L140
42,015
nanlabs/econsole
index.js
writeLog
function writeLog(level, msg) { var line; if(showSourceInfo) { var si = getSourceInfo(); if (includeDate) { line = util.format("[%s] <%s>\t[%s:%s] %s", moment().format(), level, si.file, si.lineNumber, msg); } else { line = util.format("<%s>\t[%s:%s] %s", level, si.file, si.lineNumber, msg); } } else { if (includeDate) { line = util.format("[%s] <%s>\t%s", moment().format(), level, msg); } else { line = util.format("<%s>\t%s", level, msg); } } line += '\n'; appenders.forEach(function(appender) { appender(level, line); }); }
javascript
function writeLog(level, msg) { var line; if(showSourceInfo) { var si = getSourceInfo(); if (includeDate) { line = util.format("[%s] <%s>\t[%s:%s] %s", moment().format(), level, si.file, si.lineNumber, msg); } else { line = util.format("<%s>\t[%s:%s] %s", level, si.file, si.lineNumber, msg); } } else { if (includeDate) { line = util.format("[%s] <%s>\t%s", moment().format(), level, msg); } else { line = util.format("<%s>\t%s", level, msg); } } line += '\n'; appenders.forEach(function(appender) { appender(level, line); }); }
[ "function", "writeLog", "(", "level", ",", "msg", ")", "{", "var", "line", ";", "if", "(", "showSourceInfo", ")", "{", "var", "si", "=", "getSourceInfo", "(", ")", ";", "if", "(", "includeDate", ")", "{", "line", "=", "util", ".", "format", "(", "\"[%s] <%s>\\t[%s:%s] %s\"", ",", "moment", "(", ")", ".", "format", "(", ")", ",", "level", ",", "si", ".", "file", ",", "si", ".", "lineNumber", ",", "msg", ")", ";", "}", "else", "{", "line", "=", "util", ".", "format", "(", "\"<%s>\\t[%s:%s] %s\"", ",", "level", ",", "si", ".", "file", ",", "si", ".", "lineNumber", ",", "msg", ")", ";", "}", "}", "else", "{", "if", "(", "includeDate", ")", "{", "line", "=", "util", ".", "format", "(", "\"[%s] <%s>\\t%s\"", ",", "moment", "(", ")", ".", "format", "(", ")", ",", "level", ",", "msg", ")", ";", "}", "else", "{", "line", "=", "util", ".", "format", "(", "\"<%s>\\t%s\"", ",", "level", ",", "msg", ")", ";", "}", "}", "line", "+=", "'\\n'", ";", "appenders", ".", "forEach", "(", "function", "(", "appender", ")", "{", "appender", "(", "level", ",", "line", ")", ";", "}", ")", ";", "}" ]
Writes the log to stderr Partially based on clim (http://github.com/epeli/node-clim) Copyright (c) 2009-2011 Esa-Matti Suuronen <[email protected]>
[ "Writes", "the", "log", "to", "stderr" ]
2377a33e266b4e39a35cf981ece14b6b6a16af46
https://github.com/nanlabs/econsole/blob/2377a33e266b4e39a35cf981ece14b6b6a16af46/index.js#L148-L169
42,016
nanlabs/econsole
index.js
getSourceInfo
function getSourceInfo() { var exec = getStack()[3]; var pos = exec.getFileName().lastIndexOf('\\'); if(pos < 0) exec.getFileName().lastIndexOf('/'); return { methodName: exec.getFunctionName() || 'anonymous', file: exec.getFileName().substring(pos + 1), lineNumber: exec.getLineNumber() }; }
javascript
function getSourceInfo() { var exec = getStack()[3]; var pos = exec.getFileName().lastIndexOf('\\'); if(pos < 0) exec.getFileName().lastIndexOf('/'); return { methodName: exec.getFunctionName() || 'anonymous', file: exec.getFileName().substring(pos + 1), lineNumber: exec.getLineNumber() }; }
[ "function", "getSourceInfo", "(", ")", "{", "var", "exec", "=", "getStack", "(", ")", "[", "3", "]", ";", "var", "pos", "=", "exec", ".", "getFileName", "(", ")", ".", "lastIndexOf", "(", "'\\\\'", ")", ";", "if", "(", "pos", "<", "0", ")", "exec", ".", "getFileName", "(", ")", ".", "lastIndexOf", "(", "'/'", ")", ";", "return", "{", "methodName", ":", "exec", ".", "getFunctionName", "(", ")", "||", "'anonymous'", ",", "file", ":", "exec", ".", "getFileName", "(", ")", ".", "substring", "(", "pos", "+", "1", ")", ",", "lineNumber", ":", "exec", ".", "getLineNumber", "(", ")", "}", ";", "}" ]
Gets the source information from the line being log
[ "Gets", "the", "source", "information", "from", "the", "line", "being", "log" ]
2377a33e266b4e39a35cf981ece14b6b6a16af46
https://github.com/nanlabs/econsole/blob/2377a33e266b4e39a35cf981ece14b6b6a16af46/index.js#L190-L201
42,017
DavidSouther/JEFRi
modeler/angular/app/scripts/lib/angular/ui/angular-ui.js
function ($scope, element, attrs) { var opts = {}; if (attrs.uiAnimate) { opts = $scope.$eval(attrs.uiAnimate); if (angular.isString(opts)) { opts = {'class': opts}; } } opts = angular.extend({'class': 'ui-animate'}, options, opts); element.addClass(opts['class']); $timeout(function () { element.removeClass(opts['class']); }, 20, false); }
javascript
function ($scope, element, attrs) { var opts = {}; if (attrs.uiAnimate) { opts = $scope.$eval(attrs.uiAnimate); if (angular.isString(opts)) { opts = {'class': opts}; } } opts = angular.extend({'class': 'ui-animate'}, options, opts); element.addClass(opts['class']); $timeout(function () { element.removeClass(opts['class']); }, 20, false); }
[ "function", "(", "$scope", ",", "element", ",", "attrs", ")", "{", "var", "opts", "=", "{", "}", ";", "if", "(", "attrs", ".", "uiAnimate", ")", "{", "opts", "=", "$scope", ".", "$eval", "(", "attrs", ".", "uiAnimate", ")", ";", "if", "(", "angular", ".", "isString", "(", "opts", ")", ")", "{", "opts", "=", "{", "'class'", ":", "opts", "}", ";", "}", "}", "opts", "=", "angular", ".", "extend", "(", "{", "'class'", ":", "'ui-animate'", "}", ",", "options", ",", "opts", ")", ";", "element", ".", "addClass", "(", "opts", "[", "'class'", "]", ")", ";", "$timeout", "(", "function", "(", ")", "{", "element", ".", "removeClass", "(", "opts", "[", "'class'", "]", ")", ";", "}", ",", "20", ",", "false", ")", ";", "}" ]
supports using directive as element, attribute and class
[ "supports", "using", "directive", "as", "element", "attribute", "and", "class" ]
161f24e242e05b9b2114cc1123a257141a60eaf2
https://github.com/DavidSouther/JEFRi/blob/161f24e242e05b9b2114cc1123a257141a60eaf2/modeler/angular/app/scripts/lib/angular/ui/angular-ui.js#L32-L46
42,018
DavidSouther/JEFRi
modeler/angular/app/scripts/lib/angular/ui/angular-ui.js
bindMapEvents
function bindMapEvents(scope, eventsStr, googleObject, element) { angular.forEach(eventsStr.split(' '), function (eventName) { //Prefix all googlemap events with 'map-', so eg 'click' //for the googlemap doesn't interfere with a normal 'click' event var $event = { type: 'map-' + eventName }; google.maps.event.addListener(googleObject, eventName, function (evt) { element.trigger(angular.extend({}, $event, evt)); //We create an $apply if it isn't happening. we need better support for this //We don't want to use timeout because tons of these events fire at once, //and we only need one $apply if (!scope.$$phase) scope.$apply(); }); }); }
javascript
function bindMapEvents(scope, eventsStr, googleObject, element) { angular.forEach(eventsStr.split(' '), function (eventName) { //Prefix all googlemap events with 'map-', so eg 'click' //for the googlemap doesn't interfere with a normal 'click' event var $event = { type: 'map-' + eventName }; google.maps.event.addListener(googleObject, eventName, function (evt) { element.trigger(angular.extend({}, $event, evt)); //We create an $apply if it isn't happening. we need better support for this //We don't want to use timeout because tons of these events fire at once, //and we only need one $apply if (!scope.$$phase) scope.$apply(); }); }); }
[ "function", "bindMapEvents", "(", "scope", ",", "eventsStr", ",", "googleObject", ",", "element", ")", "{", "angular", ".", "forEach", "(", "eventsStr", ".", "split", "(", "' '", ")", ",", "function", "(", "eventName", ")", "{", "//Prefix all googlemap events with 'map-', so eg 'click' \r", "//for the googlemap doesn't interfere with a normal 'click' event\r", "var", "$event", "=", "{", "type", ":", "'map-'", "+", "eventName", "}", ";", "google", ".", "maps", ".", "event", ".", "addListener", "(", "googleObject", ",", "eventName", ",", "function", "(", "evt", ")", "{", "element", ".", "trigger", "(", "angular", ".", "extend", "(", "{", "}", ",", "$event", ",", "evt", ")", ")", ";", "//We create an $apply if it isn't happening. we need better support for this\r", "//We don't want to use timeout because tons of these events fire at once,\r", "//and we only need one $apply\r", "if", "(", "!", "scope", ".", "$$phase", ")", "scope", ".", "$apply", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Setup map events from a google map object to trigger on a given element too, then we just use ui-event to catch events from an element
[ "Setup", "map", "events", "from", "a", "google", "map", "object", "to", "trigger", "on", "a", "given", "element", "too", "then", "we", "just", "use", "ui", "-", "event", "to", "catch", "events", "from", "an", "element" ]
161f24e242e05b9b2114cc1123a257141a60eaf2
https://github.com/DavidSouther/JEFRi/blob/161f24e242e05b9b2114cc1123a257141a60eaf2/modeler/angular/app/scripts/lib/angular/ui/angular-ui.js#L468-L481
42,019
liamray/nexl-engine
nexl-engine/nexl-source-utils.js
resolveIncludeDirectives
function resolveIncludeDirectives(text, fileItem) { var result = []; // parse source code with esprima try { var srcParsed = esprima.parse(text); } catch (e) { logger.error(buildErrMsg(fileItem.ancestor, 'Failed to parse a [%s] JavaScript file. Reason : [%s]', fileItem.filePath, e)); throw buildShortErrMsg(fileItem.ancestor, 'Failed to parse a [%s] JavaScript file. Reason : [%s]', path.basename(fileItem.filePath), e) } // iterating over and looking for include directives for (var key in srcParsed.body) { var item = srcParsed.body[key]; // resolve include directive from dom item var includeDirective = resolveIncludeDirectiveDom(item); if (includeDirective != null) { result.push(includeDirective); } } return result; }
javascript
function resolveIncludeDirectives(text, fileItem) { var result = []; // parse source code with esprima try { var srcParsed = esprima.parse(text); } catch (e) { logger.error(buildErrMsg(fileItem.ancestor, 'Failed to parse a [%s] JavaScript file. Reason : [%s]', fileItem.filePath, e)); throw buildShortErrMsg(fileItem.ancestor, 'Failed to parse a [%s] JavaScript file. Reason : [%s]', path.basename(fileItem.filePath), e) } // iterating over and looking for include directives for (var key in srcParsed.body) { var item = srcParsed.body[key]; // resolve include directive from dom item var includeDirective = resolveIncludeDirectiveDom(item); if (includeDirective != null) { result.push(includeDirective); } } return result; }
[ "function", "resolveIncludeDirectives", "(", "text", ",", "fileItem", ")", "{", "var", "result", "=", "[", "]", ";", "// parse source code with esprima", "try", "{", "var", "srcParsed", "=", "esprima", ".", "parse", "(", "text", ")", ";", "}", "catch", "(", "e", ")", "{", "logger", ".", "error", "(", "buildErrMsg", "(", "fileItem", ".", "ancestor", ",", "'Failed to parse a [%s] JavaScript file. Reason : [%s]'", ",", "fileItem", ".", "filePath", ",", "e", ")", ")", ";", "throw", "buildShortErrMsg", "(", "fileItem", ".", "ancestor", ",", "'Failed to parse a [%s] JavaScript file. Reason : [%s]'", ",", "path", ".", "basename", "(", "fileItem", ".", "filePath", ")", ",", "e", ")", "}", "// iterating over and looking for include directives", "for", "(", "var", "key", "in", "srcParsed", ".", "body", ")", "{", "var", "item", "=", "srcParsed", ".", "body", "[", "key", "]", ";", "// resolve include directive from dom item", "var", "includeDirective", "=", "resolveIncludeDirectiveDom", "(", "item", ")", ";", "if", "(", "includeDirective", "!=", "null", ")", "{", "result", ".", "push", "(", "includeDirective", ")", ";", "}", "}", "return", "result", ";", "}" ]
parses JavaScript provided as text and resolves nexl include directives ( like "@import ../../src.js"; )
[ "parses", "JavaScript", "provided", "as", "text", "and", "resolves", "nexl", "include", "directives", "(", "like" ]
47cd168460dbe724626953047b4d3268ba981abf
https://github.com/liamray/nexl-engine/blob/47cd168460dbe724626953047b4d3268ba981abf/nexl-engine/nexl-source-utils.js#L63-L86
42,020
Mammut-FE/nejm
src/util/ajax/proxy/upload.js
function(){ var _body,_text; try{ var _body = this.__frame.contentWindow.document.body, _text = (_body.innerText||_body.textContent||'').trim(); // check result for same domain with upload proxy html if (_text.indexOf(_xflag)>=0|| _body.innerHTML.indexOf(_xflag)>=0){ // use post message path return; } }catch(ex){ // ignore if not same domain return; } this.__onLoadRequest(_text); }
javascript
function(){ var _body,_text; try{ var _body = this.__frame.contentWindow.document.body, _text = (_body.innerText||_body.textContent||'').trim(); // check result for same domain with upload proxy html if (_text.indexOf(_xflag)>=0|| _body.innerHTML.indexOf(_xflag)>=0){ // use post message path return; } }catch(ex){ // ignore if not same domain return; } this.__onLoadRequest(_text); }
[ "function", "(", ")", "{", "var", "_body", ",", "_text", ";", "try", "{", "var", "_body", "=", "this", ".", "__frame", ".", "contentWindow", ".", "document", ".", "body", ",", "_text", "=", "(", "_body", ".", "innerText", "||", "_body", ".", "textContent", "||", "''", ")", ".", "trim", "(", ")", ";", "// check result for same domain with upload proxy html", "if", "(", "_text", ".", "indexOf", "(", "_xflag", ")", ">=", "0", "||", "_body", ".", "innerHTML", ".", "indexOf", "(", "_xflag", ")", ">=", "0", ")", "{", "// use post message path", "return", ";", "}", "}", "catch", "(", "ex", ")", "{", "// ignore if not same domain", "return", ";", "}", "this", ".", "__onLoadRequest", "(", "_text", ")", ";", "}" ]
same domain upload result check
[ "same", "domain", "upload", "result", "check" ]
dfc09ac66a8d67620a7aea65e34d8a179976b3fb
https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/util/ajax/proxy/upload.js#L113-L129
42,021
Mammut-FE/nejm
src/util/ajax/proxy/upload.js
function(_url,_mode,_cookie){ _j0._$request(_url,{ type:'json', method:'POST', cookie:_cookie, mode:parseInt(_mode)||0, onload:function(_data){ if (!this.__timer) return; this._$dispatchEvent('onuploading',_data); this.__timer = window.setTimeout( _doProgress._$bind( this,_url,_mode,_cookie ),1000 ); }._$bind(this), onerror:function(_error){ if (!this.__timer) return; this.__timer = window.setTimeout( _doProgress._$bind( this,_url,_mode,_cookie ),1000 ); }._$bind(this) }); }
javascript
function(_url,_mode,_cookie){ _j0._$request(_url,{ type:'json', method:'POST', cookie:_cookie, mode:parseInt(_mode)||0, onload:function(_data){ if (!this.__timer) return; this._$dispatchEvent('onuploading',_data); this.__timer = window.setTimeout( _doProgress._$bind( this,_url,_mode,_cookie ),1000 ); }._$bind(this), onerror:function(_error){ if (!this.__timer) return; this.__timer = window.setTimeout( _doProgress._$bind( this,_url,_mode,_cookie ),1000 ); }._$bind(this) }); }
[ "function", "(", "_url", ",", "_mode", ",", "_cookie", ")", "{", "_j0", ".", "_$request", "(", "_url", ",", "{", "type", ":", "'json'", ",", "method", ":", "'POST'", ",", "cookie", ":", "_cookie", ",", "mode", ":", "parseInt", "(", "_mode", ")", "||", "0", ",", "onload", ":", "function", "(", "_data", ")", "{", "if", "(", "!", "this", ".", "__timer", ")", "return", ";", "this", ".", "_$dispatchEvent", "(", "'onuploading'", ",", "_data", ")", ";", "this", ".", "__timer", "=", "window", ".", "setTimeout", "(", "_doProgress", ".", "_$bind", "(", "this", ",", "_url", ",", "_mode", ",", "_cookie", ")", ",", "1000", ")", ";", "}", ".", "_$bind", "(", "this", ")", ",", "onerror", ":", "function", "(", "_error", ")", "{", "if", "(", "!", "this", ".", "__timer", ")", "return", ";", "this", ".", "__timer", "=", "window", ".", "setTimeout", "(", "_doProgress", ".", "_$bind", "(", "this", ",", "_url", ",", "_mode", ",", "_cookie", ")", ",", "1000", ")", ";", "}", ".", "_$bind", "(", "this", ")", "}", ")", ";", "}" ]
check upload progress
[ "check", "upload", "progress" ]
dfc09ac66a8d67620a7aea65e34d8a179976b3fb
https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/util/ajax/proxy/upload.js#L131-L155
42,022
vesln/hydro
lib/cli/index.js
Cli
function Cli(hydro, argv) { if (!(this instanceof Cli)) { return new Cli(hydro, argv); } this.hydro = hydro; this.argv = argv; this.options = {}; this.conf = []; this.commands = [ 'help', 'version' ]; this.arrayParams = { plugins: true }; }
javascript
function Cli(hydro, argv) { if (!(this instanceof Cli)) { return new Cli(hydro, argv); } this.hydro = hydro; this.argv = argv; this.options = {}; this.conf = []; this.commands = [ 'help', 'version' ]; this.arrayParams = { plugins: true }; }
[ "function", "Cli", "(", "hydro", ",", "argv", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Cli", ")", ")", "{", "return", "new", "Cli", "(", "hydro", ",", "argv", ")", ";", "}", "this", ".", "hydro", "=", "hydro", ";", "this", ".", "argv", "=", "argv", ";", "this", ".", "options", "=", "{", "}", ";", "this", ".", "conf", "=", "[", "]", ";", "this", ".", "commands", "=", "[", "'help'", ",", "'version'", "]", ";", "this", ".", "arrayParams", "=", "{", "plugins", ":", "true", "}", ";", "}" ]
CLI runner. @param {Object} hydro @param {Object} argv @constructor
[ "CLI", "runner", "." ]
3f4d2e4926f913976187376e82f1496514c39890
https://github.com/vesln/hydro/blob/3f4d2e4926f913976187376e82f1496514c39890/lib/cli/index.js#L16-L27
42,023
LaxarJS/laxar-tooling
src/artifact_collector.js
followEntryRefs
function followEntryRefs( key, callback ) { return function( entry ) { const refs = entry[ key ] || []; return Promise.all( refs.map( callback ) ).then( flatten ); }; }
javascript
function followEntryRefs( key, callback ) { return function( entry ) { const refs = entry[ key ] || []; return Promise.all( refs.map( callback ) ).then( flatten ); }; }
[ "function", "followEntryRefs", "(", "key", ",", "callback", ")", "{", "return", "function", "(", "entry", ")", "{", "const", "refs", "=", "entry", "[", "key", "]", "||", "[", "]", ";", "return", "Promise", ".", "all", "(", "refs", ".", "map", "(", "callback", ")", ")", ".", "then", "(", "flatten", ")", ";", "}", ";", "}" ]
Create a function that expects an artifact entry as a parameter and follows the given key of it with a given function. @private @param {String} key the key to follow @param {Function} callback the function to call for each ref listed in the key @return {Function} a function returning a promise for a list of entries returned by callback
[ "Create", "a", "function", "that", "expects", "an", "artifact", "entry", "as", "a", "parameter", "and", "follows", "the", "given", "key", "of", "it", "with", "a", "given", "function", "." ]
1c4a221994f342ec03a98b68533c4de77ccfeec6
https://github.com/LaxarJS/laxar-tooling/blob/1c4a221994f342ec03a98b68533c4de77ccfeec6/src/artifact_collector.js#L715-L720
42,024
veo-labs/openveo-api
lib/storages/databases/mongodb/MongoDatabase.js
MongoDatabase
function MongoDatabase(configuration) { MongoDatabase.super_.call(this, configuration); Object.defineProperties(this, { /** * The name of the replica set. * * @property replicaSet * @type String * @final */ replicaSet: {value: configuration.replicaSet}, /** * A comma separated list of secondary servers. * * @property seedlist * @type String * @final */ seedlist: {value: configuration.seedlist}, /** * The connected database. * * @property database * @type Db * @final */ db: { value: null, writable: true } }); }
javascript
function MongoDatabase(configuration) { MongoDatabase.super_.call(this, configuration); Object.defineProperties(this, { /** * The name of the replica set. * * @property replicaSet * @type String * @final */ replicaSet: {value: configuration.replicaSet}, /** * A comma separated list of secondary servers. * * @property seedlist * @type String * @final */ seedlist: {value: configuration.seedlist}, /** * The connected database. * * @property database * @type Db * @final */ db: { value: null, writable: true } }); }
[ "function", "MongoDatabase", "(", "configuration", ")", "{", "MongoDatabase", ".", "super_", ".", "call", "(", "this", ",", "configuration", ")", ";", "Object", ".", "defineProperties", "(", "this", ",", "{", "/**\n * The name of the replica set.\n *\n * @property replicaSet\n * @type String\n * @final\n */", "replicaSet", ":", "{", "value", ":", "configuration", ".", "replicaSet", "}", ",", "/**\n * A comma separated list of secondary servers.\n *\n * @property seedlist\n * @type String\n * @final\n */", "seedlist", ":", "{", "value", ":", "configuration", ".", "seedlist", "}", ",", "/**\n * The connected database.\n *\n * @property database\n * @type Db\n * @final\n */", "db", ":", "{", "value", ":", "null", ",", "writable", ":", "true", "}", "}", ")", ";", "}" ]
Defines a MongoDB Database. @class MongoDatabase @extends Database @constructor @param {Object} configuration A database configuration object @param {String} configuration.host MongoDB server host @param {Number} configuration.port MongoDB server port @param {String} configuration.database The name of the database @param {String} configuration.username The name of the database user @param {String} configuration.password The password of the database user @param {String} [configuration.replicaSet] The name of the ReplicaSet @param {String} [configuration.seedlist] The comma separated list of secondary servers
[ "Defines", "a", "MongoDB", "Database", "." ]
493a811e9a5ba4d3e14910facaa7452caba1ab38
https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/storages/databases/mongodb/MongoDatabase.js#L32-L68
42,025
veo-labs/openveo-api
lib/storages/databases/mongodb/MongoDatabase.js
buildFilters
function buildFilters(filters) { var builtFilters = []; filters.forEach(function(filter) { builtFilters.push(MongoDatabase.buildFilter(filter)); }); return builtFilters; }
javascript
function buildFilters(filters) { var builtFilters = []; filters.forEach(function(filter) { builtFilters.push(MongoDatabase.buildFilter(filter)); }); return builtFilters; }
[ "function", "buildFilters", "(", "filters", ")", "{", "var", "builtFilters", "=", "[", "]", ";", "filters", ".", "forEach", "(", "function", "(", "filter", ")", "{", "builtFilters", ".", "push", "(", "MongoDatabase", ".", "buildFilter", "(", "filter", ")", ")", ";", "}", ")", ";", "return", "builtFilters", ";", "}" ]
Builds a list of filters. @param {Array} filters The list of filters to build @return {Array} The list of built filters
[ "Builds", "a", "list", "of", "filters", "." ]
493a811e9a5ba4d3e14910facaa7452caba1ab38
https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/storages/databases/mongodb/MongoDatabase.js#L93-L99
42,026
veo-labs/openveo-api
lib/storages/ResourceFilter.js
isValidType
function isValidType(value, authorizedTypes) { var valueToString = Object.prototype.toString.call(value); for (var i = 0; i < authorizedTypes.length; i++) if (valueToString === '[object ' + authorizedTypes[i] + ']') return true; return false; }
javascript
function isValidType(value, authorizedTypes) { var valueToString = Object.prototype.toString.call(value); for (var i = 0; i < authorizedTypes.length; i++) if (valueToString === '[object ' + authorizedTypes[i] + ']') return true; return false; }
[ "function", "isValidType", "(", "value", ",", "authorizedTypes", ")", "{", "var", "valueToString", "=", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "value", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "authorizedTypes", ".", "length", ";", "i", "++", ")", "if", "(", "valueToString", "===", "'[object '", "+", "authorizedTypes", "[", "i", "]", "+", "']'", ")", "return", "true", ";", "return", "false", ";", "}" ]
Validates the type of a value. @method isValidType @private @param {String} value The value to test @param {Array} The list of authorized types as strings @return {Boolean} true if valid, false otherwise
[ "Validates", "the", "type", "of", "a", "value", "." ]
493a811e9a5ba4d3e14910facaa7452caba1ab38
https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/storages/ResourceFilter.js#L93-L100
42,027
veo-labs/openveo-api
lib/storages/ResourceFilter.js
addComparisonOperation
function addComparisonOperation(field, value, operator, authorizedTypes) { if (!isValidType(field, ['String'])) throw new TypeError('Invalid field'); if (!isValidType(value, authorizedTypes)) throw new TypeError('Invalid value'); this.operations.push({ type: operator, field: field, value: value }); return this; }
javascript
function addComparisonOperation(field, value, operator, authorizedTypes) { if (!isValidType(field, ['String'])) throw new TypeError('Invalid field'); if (!isValidType(value, authorizedTypes)) throw new TypeError('Invalid value'); this.operations.push({ type: operator, field: field, value: value }); return this; }
[ "function", "addComparisonOperation", "(", "field", ",", "value", ",", "operator", ",", "authorizedTypes", ")", "{", "if", "(", "!", "isValidType", "(", "field", ",", "[", "'String'", "]", ")", ")", "throw", "new", "TypeError", "(", "'Invalid field'", ")", ";", "if", "(", "!", "isValidType", "(", "value", ",", "authorizedTypes", ")", ")", "throw", "new", "TypeError", "(", "'Invalid value'", ")", ";", "this", ".", "operations", ".", "push", "(", "{", "type", ":", "operator", ",", "field", ":", "field", ",", "value", ":", "value", "}", ")", ";", "return", "this", ";", "}" ]
Adds a comparison operation to the filter. @method addComparisonOperation @private @param {String} field The name of the field @param {String|Number|Boolean|Date} value The value to compare the field to @param {String} Resource filter operator @param {Array} The list of authorized types as strings @return {ResourceFilter} The actual filter @throws {TypeError} An error if field and / or value is not valid
[ "Adds", "a", "comparison", "operation", "to", "the", "filter", "." ]
493a811e9a5ba4d3e14910facaa7452caba1ab38
https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/storages/ResourceFilter.js#L114-L124
42,028
veo-labs/openveo-api
lib/storages/ResourceFilter.js
addLogicalOperation
function addLogicalOperation(filters, operator) { for (var i = 0; i < filters.length; i++) if (!(filters[i] instanceof ResourceFilter)) throw new TypeError('Invalid filters'); if (this.hasOperation(operator)) { // This logical operator already exists in the list of operations // Just add the new filters to the operator for (var operation of this.operations) { if (operation.type === operator) operation.filters = operation.filters.concat(filters); } } else { // This logical operator does not exist yet in the list of operations this.operations.push({ type: operator, filters: filters }); } return this; }
javascript
function addLogicalOperation(filters, operator) { for (var i = 0; i < filters.length; i++) if (!(filters[i] instanceof ResourceFilter)) throw new TypeError('Invalid filters'); if (this.hasOperation(operator)) { // This logical operator already exists in the list of operations // Just add the new filters to the operator for (var operation of this.operations) { if (operation.type === operator) operation.filters = operation.filters.concat(filters); } } else { // This logical operator does not exist yet in the list of operations this.operations.push({ type: operator, filters: filters }); } return this; }
[ "function", "addLogicalOperation", "(", "filters", ",", "operator", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "filters", ".", "length", ";", "i", "++", ")", "if", "(", "!", "(", "filters", "[", "i", "]", "instanceof", "ResourceFilter", ")", ")", "throw", "new", "TypeError", "(", "'Invalid filters'", ")", ";", "if", "(", "this", ".", "hasOperation", "(", "operator", ")", ")", "{", "// This logical operator already exists in the list of operations", "// Just add the new filters to the operator", "for", "(", "var", "operation", "of", "this", ".", "operations", ")", "{", "if", "(", "operation", ".", "type", "===", "operator", ")", "operation", ".", "filters", "=", "operation", ".", "filters", ".", "concat", "(", "filters", ")", ";", "}", "}", "else", "{", "// This logical operator does not exist yet in the list of operations", "this", ".", "operations", ".", "push", "(", "{", "type", ":", "operator", ",", "filters", ":", "filters", "}", ")", ";", "}", "return", "this", ";", "}" ]
Adds a logical operation to the filter. Only one logical operation can be added in a filter. @method addLogicalOperation @private @param {Array} filters The list of filters @return {ResourceFilter} The actual filter @throws {TypeError} An error if field and / or value is not valid
[ "Adds", "a", "logical", "operation", "to", "the", "filter", "." ]
493a811e9a5ba4d3e14910facaa7452caba1ab38
https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/storages/ResourceFilter.js#L137-L162
42,029
rtgibbons/grunt-cloudfiles
tasks/cloudfiles.js
hashFile
function hashFile(filename, callback) { var calledBack = false, md5sum = crypto.createHash('md5'), stream = fs.ReadStream(filename); stream.on('data', function (data) { md5sum.update(data); }); stream.on('end', function () { var hash = md5sum.digest('hex'); callback(null, hash); }); stream.on('error', function(err) { handleResponse(err); }); function handleResponse(err, hash) { if (calledBack) { return; } calledBack = true; callback(err, hash); } }
javascript
function hashFile(filename, callback) { var calledBack = false, md5sum = crypto.createHash('md5'), stream = fs.ReadStream(filename); stream.on('data', function (data) { md5sum.update(data); }); stream.on('end', function () { var hash = md5sum.digest('hex'); callback(null, hash); }); stream.on('error', function(err) { handleResponse(err); }); function handleResponse(err, hash) { if (calledBack) { return; } calledBack = true; callback(err, hash); } }
[ "function", "hashFile", "(", "filename", ",", "callback", ")", "{", "var", "calledBack", "=", "false", ",", "md5sum", "=", "crypto", ".", "createHash", "(", "'md5'", ")", ",", "stream", "=", "fs", ".", "ReadStream", "(", "filename", ")", ";", "stream", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "md5sum", ".", "update", "(", "data", ")", ";", "}", ")", ";", "stream", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "var", "hash", "=", "md5sum", ".", "digest", "(", "'hex'", ")", ";", "callback", "(", "null", ",", "hash", ")", ";", "}", ")", ";", "stream", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "handleResponse", "(", "err", ")", ";", "}", ")", ";", "function", "handleResponse", "(", "err", ",", "hash", ")", "{", "if", "(", "calledBack", ")", "{", "return", ";", "}", "calledBack", "=", "true", ";", "callback", "(", "err", ",", "hash", ")", ";", "}", "}" ]
Used to MD5 a file, useful when checking against already uploaded assets
[ "Used", "to", "MD5", "a", "file", "useful", "when", "checking", "against", "already", "uploaded", "assets" ]
e4f55d379f935b1bb9bc39a9000930073cff1570
https://github.com/rtgibbons/grunt-cloudfiles/blob/e4f55d379f935b1bb9bc39a9000930073cff1570/tasks/cloudfiles.js#L198-L225
42,030
dapphub/dapple-core
controller.js
function (state, cli) { var name = cli['<name>']; var chains = Object.keys(state.state.pointers); if(chains.indexOf(name) > -1) { console.log(`Error: Chain ${name} is already known, please choose another name.`); process.exit(); } newChain({name}, state, (err, chaindata) => { if(typeof chaindata === 'string') return true; state.state.pointers[chaindata.name] = chaindata.chainenv; state.state.head = chaindata.name; state.saveState(true); }); }
javascript
function (state, cli) { var name = cli['<name>']; var chains = Object.keys(state.state.pointers); if(chains.indexOf(name) > -1) { console.log(`Error: Chain ${name} is already known, please choose another name.`); process.exit(); } newChain({name}, state, (err, chaindata) => { if(typeof chaindata === 'string') return true; state.state.pointers[chaindata.name] = chaindata.chainenv; state.state.head = chaindata.name; state.saveState(true); }); }
[ "function", "(", "state", ",", "cli", ")", "{", "var", "name", "=", "cli", "[", "'<name>'", "]", ";", "var", "chains", "=", "Object", ".", "keys", "(", "state", ".", "state", ".", "pointers", ")", ";", "if", "(", "chains", ".", "indexOf", "(", "name", ")", ">", "-", "1", ")", "{", "console", ".", "log", "(", "`", "${", "name", "}", "`", ")", ";", "process", ".", "exit", "(", ")", ";", "}", "newChain", "(", "{", "name", "}", ",", "state", ",", "(", "err", ",", "chaindata", ")", "=>", "{", "if", "(", "typeof", "chaindata", "===", "'string'", ")", "return", "true", ";", "state", ".", "state", ".", "pointers", "[", "chaindata", ".", "name", "]", "=", "chaindata", ".", "chainenv", ";", "state", ".", "state", ".", "head", "=", "chaindata", ".", "name", ";", "state", ".", "saveState", "(", "true", ")", ";", "}", ")", ";", "}" ]
Create a new environment
[ "Create", "a", "new", "environment" ]
4e59dc44b728bc431c1b5b49f32755e796ab496e
https://github.com/dapphub/dapple-core/blob/4e59dc44b728bc431c1b5b49f32755e796ab496e/controller.js#L18-L35
42,031
vsch/obj-each-break
index.js
hasOwnProperties
function hasOwnProperties(exclude) { const arg = this; if (!isObjectLike(arg)) return false; if (!isValid(exclude)) { const keys = Object.keys(arg); return keys.length > 0; } return !!eachProp.call(arg, resolveTestFunc(exclude, objectHasNotOwnPropertyBreakTrue, arrayContainsNotKeyBreakTrue, testFuncNotBreakTrue, alwaysBreakTrue, keyNotEqualsBreakTrue), exclude); }
javascript
function hasOwnProperties(exclude) { const arg = this; if (!isObjectLike(arg)) return false; if (!isValid(exclude)) { const keys = Object.keys(arg); return keys.length > 0; } return !!eachProp.call(arg, resolveTestFunc(exclude, objectHasNotOwnPropertyBreakTrue, arrayContainsNotKeyBreakTrue, testFuncNotBreakTrue, alwaysBreakTrue, keyNotEqualsBreakTrue), exclude); }
[ "function", "hasOwnProperties", "(", "exclude", ")", "{", "const", "arg", "=", "this", ";", "if", "(", "!", "isObjectLike", "(", "arg", ")", ")", "return", "false", ";", "if", "(", "!", "isValid", "(", "exclude", ")", ")", "{", "const", "keys", "=", "Object", ".", "keys", "(", "arg", ")", ";", "return", "keys", ".", "length", ">", "0", ";", "}", "return", "!", "!", "eachProp", ".", "call", "(", "arg", ",", "resolveTestFunc", "(", "exclude", ",", "objectHasNotOwnPropertyBreakTrue", ",", "arrayContainsNotKeyBreakTrue", ",", "testFuncNotBreakTrue", ",", "alwaysBreakTrue", ",", "keyNotEqualsBreakTrue", ")", ",", "exclude", ")", ";", "}" ]
test if this has own properties ie. not empty object, optionally apply exclusion filter to ignore some properties @this {*} value to test @param exclude {*} function, array, object or value containing keys to be excluded @return {boolean}
[ "test", "if", "this", "has", "own", "properties", "ie", ".", "not", "empty", "object", "optionally", "apply", "exclusion", "filter", "to", "ignore", "some", "properties" ]
c23f6573045a9442ae9bb4655a93901de88e5601
https://github.com/vsch/obj-each-break/blob/c23f6573045a9442ae9bb4655a93901de88e5601/index.js#L159-L168
42,032
vsch/obj-each-break
index.js
objFiltered
function objFiltered(filter, thisArg) { const dst = isArray(this) ? [] : {}; copyFiltered.call(dst, this, filter, thisArg); return dst; }
javascript
function objFiltered(filter, thisArg) { const dst = isArray(this) ? [] : {}; copyFiltered.call(dst, this, filter, thisArg); return dst; }
[ "function", "objFiltered", "(", "filter", ",", "thisArg", ")", "{", "const", "dst", "=", "isArray", "(", "this", ")", "?", "[", "]", ":", "{", "}", ";", "copyFiltered", ".", "call", "(", "dst", ",", "this", ",", "filter", ",", "thisArg", ")", ";", "return", "dst", ";", "}" ]
filter function applied to objects and array's own properties not just indexed contents results in object or array @this array or object @param filter see copyFiltered @param thisArg if filter is function then what to use for this @return {object|array} depending on this passed on call
[ "filter", "function", "applied", "to", "objects", "and", "array", "s", "own", "properties", "not", "just", "indexed", "contents", "results", "in", "object", "or", "array" ]
c23f6573045a9442ae9bb4655a93901de88e5601
https://github.com/vsch/obj-each-break/blob/c23f6573045a9442ae9bb4655a93901de88e5601/index.js#L509-L513
42,033
vsch/obj-each-break
index.js
objMapped
function objMapped(callback, thisArg = UNDEFINED) { const dst = isArray(this) ? [] : {}; eachProp.call(this, (value, key, src) => { const result = callback.call(thisArg, value, key, src); if (result === BREAK) return BREAK; if (result !== UNDEFINED) { dst[key] = result; } }); return dst; }
javascript
function objMapped(callback, thisArg = UNDEFINED) { const dst = isArray(this) ? [] : {}; eachProp.call(this, (value, key, src) => { const result = callback.call(thisArg, value, key, src); if (result === BREAK) return BREAK; if (result !== UNDEFINED) { dst[key] = result; } }); return dst; }
[ "function", "objMapped", "(", "callback", ",", "thisArg", "=", "UNDEFINED", ")", "{", "const", "dst", "=", "isArray", "(", "this", ")", "?", "[", "]", ":", "{", "}", ";", "eachProp", ".", "call", "(", "this", ",", "(", "value", ",", "key", ",", "src", ")", "=>", "{", "const", "result", "=", "callback", ".", "call", "(", "thisArg", ",", "value", ",", "key", ",", "src", ")", ";", "if", "(", "result", "===", "BREAK", ")", "return", "BREAK", ";", "if", "(", "result", "!==", "UNDEFINED", ")", "{", "dst", "[", "key", "]", "=", "result", ";", "}", "}", ")", ";", "return", "dst", ";", "}" ]
map function applied to objects and array's own properties not just indexed contents results in object or array @this array or object @param callback function(value,key,collection) if BREAK returned then breaks out of loop, returned BREAK value ignored @param thisArg what to use for this for callback @return {object|array} depending on this passed on call
[ "map", "function", "applied", "to", "objects", "and", "array", "s", "own", "properties", "not", "just", "indexed", "contents", "results", "in", "object", "or", "array" ]
c23f6573045a9442ae9bb4655a93901de88e5601
https://github.com/vsch/obj-each-break/blob/c23f6573045a9442ae9bb4655a93901de88e5601/index.js#L548-L558
42,034
vsch/obj-each-break
index.js
objMap
function objMap(callback, thisArg = UNDEFINED) { const dst = []; each.call(this, (value, key, src) => { const result = callback.call(thisArg, value, key, src); if (result === BREAK) return BREAK; if (result !== UNDEFINED) { dst.push(result); } }); return dst; }
javascript
function objMap(callback, thisArg = UNDEFINED) { const dst = []; each.call(this, (value, key, src) => { const result = callback.call(thisArg, value, key, src); if (result === BREAK) return BREAK; if (result !== UNDEFINED) { dst.push(result); } }); return dst; }
[ "function", "objMap", "(", "callback", ",", "thisArg", "=", "UNDEFINED", ")", "{", "const", "dst", "=", "[", "]", ";", "each", ".", "call", "(", "this", ",", "(", "value", ",", "key", ",", "src", ")", "=>", "{", "const", "result", "=", "callback", ".", "call", "(", "thisArg", ",", "value", ",", "key", ",", "src", ")", ";", "if", "(", "result", "===", "BREAK", ")", "return", "BREAK", ";", "if", "(", "result", "!==", "UNDEFINED", ")", "{", "dst", ".", "push", "(", "result", ")", ";", "}", "}", ")", ";", "return", "dst", ";", "}" ]
map function applied to objects and array's own properties not just indexed contents results accumulated in an array @this array or object @param callback function taking (value, key, collection) and returning value to accumulate, undefined is skipped, BREAK will break out of loop, returned BREAK value ignored @param thisArg what to use for this for callback @return {array} depending on this passed on call
[ "map", "function", "applied", "to", "objects", "and", "array", "s", "own", "properties", "not", "just", "indexed", "contents", "results", "accumulated", "in", "an", "array" ]
c23f6573045a9442ae9bb4655a93901de88e5601
https://github.com/vsch/obj-each-break/blob/c23f6573045a9442ae9bb4655a93901de88e5601/index.js#L571-L581
42,035
vsch/obj-each-break
index.js
objSome
function objSome(callback, thisArg = UNDEFINED) { return !!each.call(this, (value, key, src) => { BREAK.setDefault(true); const result = callback.call(thisArg, value, key, src); if (result === BREAK) return BREAK; if (result) return BREAK(true); }); }
javascript
function objSome(callback, thisArg = UNDEFINED) { return !!each.call(this, (value, key, src) => { BREAK.setDefault(true); const result = callback.call(thisArg, value, key, src); if (result === BREAK) return BREAK; if (result) return BREAK(true); }); }
[ "function", "objSome", "(", "callback", ",", "thisArg", "=", "UNDEFINED", ")", "{", "return", "!", "!", "each", ".", "call", "(", "this", ",", "(", "value", ",", "key", ",", "src", ")", "=>", "{", "BREAK", ".", "setDefault", "(", "true", ")", ";", "const", "result", "=", "callback", ".", "call", "(", "thisArg", ",", "value", ",", "key", ",", "src", ")", ";", "if", "(", "result", "===", "BREAK", ")", "return", "BREAK", ";", "if", "(", "result", ")", "return", "BREAK", "(", "true", ")", ";", "}", ")", ";", "}" ]
some function applied to objects and array's own properties not just indexed contents results accumulated in an array @this array or object @param callback function taking (value, key, collection) and returning value to test for truth if BREAK returned then result of function will be true, if BREAK(arg) then result is !!arg @param thisArg what to use for this for callback @return {boolean} whether callback returned true for some values
[ "some", "function", "applied", "to", "objects", "and", "array", "s", "own", "properties", "not", "just", "indexed", "contents", "results", "accumulated", "in", "an", "array" ]
c23f6573045a9442ae9bb4655a93901de88e5601
https://github.com/vsch/obj-each-break/blob/c23f6573045a9442ae9bb4655a93901de88e5601/index.js#L595-L602
42,036
vsch/obj-each-break
index.js
objReduceLeft
function objReduceLeft(callback/*, initialValue = UNDEFINED*/) { const args = Array.prototype.slice.call(arguments, 0); args.unshift(each); return objReduceIterated.apply(this, args); }
javascript
function objReduceLeft(callback/*, initialValue = UNDEFINED*/) { const args = Array.prototype.slice.call(arguments, 0); args.unshift(each); return objReduceIterated.apply(this, args); }
[ "function", "objReduceLeft", "(", "callback", "/*, initialValue = UNDEFINED*/", ")", "{", "const", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "args", ".", "unshift", "(", "each", ")", ";", "return", "objReduceIterated", ".", "apply", "(", "this", ",", "args", ")", ";", "}" ]
reduce function applied to object's and array's own properties not just indexed contents where order of reduction is left to right, first indexed properties, then ascii sorted non-indexed properties @this array or object @param callback function taking (prevValue, value, key, collection) and returning reduced value if BREAK returned then the result will be the accumulated value up to this point, or if BREAK(arg) is returned then the result will be arg //@param initialValue what to use for initial reduced value instead of array element @return {boolean} whether callback returned true for all keys/values
[ "reduce", "function", "applied", "to", "object", "s", "and", "array", "s", "own", "properties", "not", "just", "indexed", "contents", "where", "order", "of", "reduction", "is", "left", "to", "right", "first", "indexed", "properties", "then", "ascii", "sorted", "non", "-", "indexed", "properties" ]
c23f6573045a9442ae9bb4655a93901de88e5601
https://github.com/vsch/obj-each-break/blob/c23f6573045a9442ae9bb4655a93901de88e5601/index.js#L692-L696
42,037
vsch/obj-each-break
index.js
objReduceRight
function objReduceRight(callback/*, initialValue = UNDEFINED*/) { const args = Array.prototype.slice.call(arguments, 0); args.unshift(eachRight); return objReduceIterated.apply(this, args); }
javascript
function objReduceRight(callback/*, initialValue = UNDEFINED*/) { const args = Array.prototype.slice.call(arguments, 0); args.unshift(eachRight); return objReduceIterated.apply(this, args); }
[ "function", "objReduceRight", "(", "callback", "/*, initialValue = UNDEFINED*/", ")", "{", "const", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "args", ".", "unshift", "(", "eachRight", ")", ";", "return", "objReduceIterated", ".", "apply", "(", "this", ",", "args", ")", ";", "}" ]
reduceRight function applied to object's and array's own properties not just indexed contents where order of reduction is right to left, ascii sorted non-indexed properties in reverse order, then indexed properties in reverse order @this array or object @param callback function taking (prevValue, value, key, collection) and returning reduced value if BREAK returned then the result will be the accumulated value up to this point, or if BREAK(arg) is returned then the result will be arg //@param initialValue what to use for initial reduced value instead of array element @return {boolean} whether callback returned true for all keys/values
[ "reduceRight", "function", "applied", "to", "object", "s", "and", "array", "s", "own", "properties", "not", "just", "indexed", "contents", "where", "order", "of", "reduction", "is", "right", "to", "left", "ascii", "sorted", "non", "-", "indexed", "properties", "in", "reverse", "order", "then", "indexed", "properties", "in", "reverse", "order" ]
c23f6573045a9442ae9bb4655a93901de88e5601
https://github.com/vsch/obj-each-break/blob/c23f6573045a9442ae9bb4655a93901de88e5601/index.js#L712-L716
42,038
ofidj/fidj
.todo/miapp.sdk.base.js
encodeParams
function encodeParams(params) { var queryString; if (params && Object.keys(params)) { queryString = [].slice.call(arguments).reduce(function (a, b) { return a.concat(b instanceof Array ? b : [b]); }, []).filter(function (c) { return "object" === typeof c; }).reduce(function (p, c) { !(c instanceof Array) ? p = p.concat(Object.keys(c).map(function (key) { return [key, c[key]]; })) : p.push(c); return p; }, []).reduce(function (p, c) { c.length === 2 ? p.push(c) : p = p.concat(c); return p; }, []).reduce(function (p, c) { c[1] instanceof Array ? c[1].forEach(function (v) { p.push([c[0], v]); }) : p.push(c); return p; }, []).map(function (c) { c[1] = encodeURIComponent(c[1]); return c.join("="); }).join("&"); } return queryString; }
javascript
function encodeParams(params) { var queryString; if (params && Object.keys(params)) { queryString = [].slice.call(arguments).reduce(function (a, b) { return a.concat(b instanceof Array ? b : [b]); }, []).filter(function (c) { return "object" === typeof c; }).reduce(function (p, c) { !(c instanceof Array) ? p = p.concat(Object.keys(c).map(function (key) { return [key, c[key]]; })) : p.push(c); return p; }, []).reduce(function (p, c) { c.length === 2 ? p.push(c) : p = p.concat(c); return p; }, []).reduce(function (p, c) { c[1] instanceof Array ? c[1].forEach(function (v) { p.push([c[0], v]); }) : p.push(c); return p; }, []).map(function (c) { c[1] = encodeURIComponent(c[1]); return c.join("="); }).join("&"); } return queryString; }
[ "function", "encodeParams", "(", "params", ")", "{", "var", "queryString", ";", "if", "(", "params", "&&", "Object", ".", "keys", "(", "params", ")", ")", "{", "queryString", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", ".", "reduce", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", ".", "concat", "(", "b", "instanceof", "Array", "?", "b", ":", "[", "b", "]", ")", ";", "}", ",", "[", "]", ")", ".", "filter", "(", "function", "(", "c", ")", "{", "return", "\"object\"", "===", "typeof", "c", ";", "}", ")", ".", "reduce", "(", "function", "(", "p", ",", "c", ")", "{", "!", "(", "c", "instanceof", "Array", ")", "?", "p", "=", "p", ".", "concat", "(", "Object", ".", "keys", "(", "c", ")", ".", "map", "(", "function", "(", "key", ")", "{", "return", "[", "key", ",", "c", "[", "key", "]", "]", ";", "}", ")", ")", ":", "p", ".", "push", "(", "c", ")", ";", "return", "p", ";", "}", ",", "[", "]", ")", ".", "reduce", "(", "function", "(", "p", ",", "c", ")", "{", "c", ".", "length", "===", "2", "?", "p", ".", "push", "(", "c", ")", ":", "p", "=", "p", ".", "concat", "(", "c", ")", ";", "return", "p", ";", "}", ",", "[", "]", ")", ".", "reduce", "(", "function", "(", "p", ",", "c", ")", "{", "c", "[", "1", "]", "instanceof", "Array", "?", "c", "[", "1", "]", ".", "forEach", "(", "function", "(", "v", ")", "{", "p", ".", "push", "(", "[", "c", "[", "0", "]", ",", "v", "]", ")", ";", "}", ")", ":", "p", ".", "push", "(", "c", ")", ";", "return", "p", ";", "}", ",", "[", "]", ")", ".", "map", "(", "function", "(", "c", ")", "{", "c", "[", "1", "]", "=", "encodeURIComponent", "(", "c", "[", "1", "]", ")", ";", "return", "c", ".", "join", "(", "\"=\"", ")", ";", "}", ")", ".", "join", "(", "\"&\"", ")", ";", "}", "return", "queryString", ";", "}" ]
method to encode the query string parameters
[ "method", "to", "encode", "the", "query", "string", "parameters" ]
e57ebece54ee68211d43802a8e0feeef098d3e36
https://github.com/ofidj/fidj/blob/e57ebece54ee68211d43802a8e0feeef098d3e36/.todo/miapp.sdk.base.js#L390-L416
42,039
1stdibs/backbone-base-and-form-view
examples/example-todo-formview.js
function (e) { var keyCode = e.keyCode || e.which; // If the user pressed enter if (keyCode === 13) { this.addRow(); // Get the last row viewEvents, then get the title field, then have jQuery // find the input and trigger a focus event. _.last(this.subs.get('row')).subs.get('title').$('input').trigger('focus'); } }
javascript
function (e) { var keyCode = e.keyCode || e.which; // If the user pressed enter if (keyCode === 13) { this.addRow(); // Get the last row viewEvents, then get the title field, then have jQuery // find the input and trigger a focus event. _.last(this.subs.get('row')).subs.get('title').$('input').trigger('focus'); } }
[ "function", "(", "e", ")", "{", "var", "keyCode", "=", "e", ".", "keyCode", "||", "e", ".", "which", ";", "// If the user pressed enter", "if", "(", "keyCode", "===", "13", ")", "{", "this", ".", "addRow", "(", ")", ";", "// Get the last row viewEvents, then get the title field, then have jQuery", "// find the input and trigger a focus event.", "_", ".", "last", "(", "this", ".", "subs", ".", "get", "(", "'row'", ")", ")", ".", "subs", ".", "get", "(", "'title'", ")", ".", "$", "(", "'input'", ")", ".", "trigger", "(", "'focus'", ")", ";", "}", "}" ]
When the user presses enter, add a row
[ "When", "the", "user", "presses", "enter", "add", "a", "row" ]
9c49f9ac059ba3177b61f7395151de78b506e8f7
https://github.com/1stdibs/backbone-base-and-form-view/blob/9c49f9ac059ba3177b61f7395151de78b506e8f7/examples/example-todo-formview.js#L167-L176
42,040
LeisureLink/magicbus
lib/amqp/queue.js
getAssertQueueOptions
function getAssertQueueOptions() { const aliases ={ queueLimit: 'maxLength', deadLetter: 'deadLetterExchange', deadLetterRoutingKey: 'deadLetterRoutingKey' }; const itemsToOmit = ['limit', 'noBatch']; let aliased = _.transform(options, function(result, value, key) { let alias = aliases[key]; result[alias || key] = value; }); return _.omit(aliased, itemsToOmit); }
javascript
function getAssertQueueOptions() { const aliases ={ queueLimit: 'maxLength', deadLetter: 'deadLetterExchange', deadLetterRoutingKey: 'deadLetterRoutingKey' }; const itemsToOmit = ['limit', 'noBatch']; let aliased = _.transform(options, function(result, value, key) { let alias = aliases[key]; result[alias || key] = value; }); return _.omit(aliased, itemsToOmit); }
[ "function", "getAssertQueueOptions", "(", ")", "{", "const", "aliases", "=", "{", "queueLimit", ":", "'maxLength'", ",", "deadLetter", ":", "'deadLetterExchange'", ",", "deadLetterRoutingKey", ":", "'deadLetterRoutingKey'", "}", ";", "const", "itemsToOmit", "=", "[", "'limit'", ",", "'noBatch'", "]", ";", "let", "aliased", "=", "_", ".", "transform", "(", "options", ",", "function", "(", "result", ",", "value", ",", "key", ")", "{", "let", "alias", "=", "aliases", "[", "key", "]", ";", "result", "[", "alias", "||", "key", "]", "=", "value", ";", "}", ")", ";", "return", "_", ".", "omit", "(", "aliased", ",", "itemsToOmit", ")", ";", "}" ]
Get options for amqp assertQueue call @private
[ "Get", "options", "for", "amqp", "assertQueue", "call" ]
0370c38ebb8c7917cfd3894263d734aefc2d3d29
https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/amqp/queue.js#L66-L80
42,041
LeisureLink/magicbus
lib/amqp/queue.js
purge
function purge() { qLog.info(`Purging queue ${channelName} - ${connectionName}`); return channel.purgeQueue(channelName).then(function(){ qLog.debug(`Successfully purged queue ${channelName} - ${connectionName}`); }); }
javascript
function purge() { qLog.info(`Purging queue ${channelName} - ${connectionName}`); return channel.purgeQueue(channelName).then(function(){ qLog.debug(`Successfully purged queue ${channelName} - ${connectionName}`); }); }
[ "function", "purge", "(", ")", "{", "qLog", ".", "info", "(", "`", "${", "channelName", "}", "${", "connectionName", "}", "`", ")", ";", "return", "channel", ".", "purgeQueue", "(", "channelName", ")", ".", "then", "(", "function", "(", ")", "{", "qLog", ".", "debug", "(", "`", "${", "channelName", "}", "${", "connectionName", "}", "`", ")", ";", "}", ")", ";", "}" ]
Purge message queue. Useful for testing @public
[ "Purge", "message", "queue", ".", "Useful", "for", "testing" ]
0370c38ebb8c7917cfd3894263d734aefc2d3d29
https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/amqp/queue.js#L86-L91
42,042
LeisureLink/magicbus
lib/amqp/queue.js
getNoBatchOps
function getNoBatchOps(raw) { messages.receivedCount += 1; return { ack: function() { qLog.debug(`Acking tag ${raw.fields.deliveryTag} on ${messages.name} - ${messages.connectionName}`); channel.ack({ fields: { deliveryTag: raw.fields.deliveryTag } }, false); }, nack: function() { qLog.debug(`Nacking tag ${raw.fields.deliveryTag} on ${messages.name} - ${messages.connectionName}`); channel.nack({ fields: { deliveryTag: raw.fields.deliveryTag } }, false); }, reject: function() { qLog.debug(`Rejecting tag ${raw.fields.deliveryTag} on ${messages.name} - ${messages.connectionName}`); channel.nack({ fields: { deliveryTag: raw.fields.deliveryTag } }, false, false); } }; }
javascript
function getNoBatchOps(raw) { messages.receivedCount += 1; return { ack: function() { qLog.debug(`Acking tag ${raw.fields.deliveryTag} on ${messages.name} - ${messages.connectionName}`); channel.ack({ fields: { deliveryTag: raw.fields.deliveryTag } }, false); }, nack: function() { qLog.debug(`Nacking tag ${raw.fields.deliveryTag} on ${messages.name} - ${messages.connectionName}`); channel.nack({ fields: { deliveryTag: raw.fields.deliveryTag } }, false); }, reject: function() { qLog.debug(`Rejecting tag ${raw.fields.deliveryTag} on ${messages.name} - ${messages.connectionName}`); channel.nack({ fields: { deliveryTag: raw.fields.deliveryTag } }, false, false); } }; }
[ "function", "getNoBatchOps", "(", "raw", ")", "{", "messages", ".", "receivedCount", "+=", "1", ";", "return", "{", "ack", ":", "function", "(", ")", "{", "qLog", ".", "debug", "(", "`", "${", "raw", ".", "fields", ".", "deliveryTag", "}", "${", "messages", ".", "name", "}", "${", "messages", ".", "connectionName", "}", "`", ")", ";", "channel", ".", "ack", "(", "{", "fields", ":", "{", "deliveryTag", ":", "raw", ".", "fields", ".", "deliveryTag", "}", "}", ",", "false", ")", ";", "}", ",", "nack", ":", "function", "(", ")", "{", "qLog", ".", "debug", "(", "`", "${", "raw", ".", "fields", ".", "deliveryTag", "}", "${", "messages", ".", "name", "}", "${", "messages", ".", "connectionName", "}", "`", ")", ";", "channel", ".", "nack", "(", "{", "fields", ":", "{", "deliveryTag", ":", "raw", ".", "fields", ".", "deliveryTag", "}", "}", ",", "false", ")", ";", "}", ",", "reject", ":", "function", "(", ")", "{", "qLog", ".", "debug", "(", "`", "${", "raw", ".", "fields", ".", "deliveryTag", "}", "${", "messages", ".", "name", "}", "${", "messages", ".", "connectionName", "}", "`", ")", ";", "channel", ".", "nack", "(", "{", "fields", ":", "{", "deliveryTag", ":", "raw", ".", "fields", ".", "deliveryTag", "}", "}", ",", "false", ",", "false", ")", ";", "}", "}", ";", "}" ]
Get message operations for an unbatched queue @private
[ "Get", "message", "operations", "for", "an", "unbatched", "queue" ]
0370c38ebb8c7917cfd3894263d734aefc2d3d29
https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/amqp/queue.js#L129-L146
42,043
LeisureLink/magicbus
lib/amqp/queue.js
getResolutionOperations
function getResolutionOperations(raw, consumeOptions) { if (consumeOptions.noAck) { return getUntrackedOps(raw); } if (consumeOptions.noBatch) { return getNoBatchOps(raw); } return getTrackedOps(raw); }
javascript
function getResolutionOperations(raw, consumeOptions) { if (consumeOptions.noAck) { return getUntrackedOps(raw); } if (consumeOptions.noBatch) { return getNoBatchOps(raw); } return getTrackedOps(raw); }
[ "function", "getResolutionOperations", "(", "raw", ",", "consumeOptions", ")", "{", "if", "(", "consumeOptions", ".", "noAck", ")", "{", "return", "getUntrackedOps", "(", "raw", ")", ";", "}", "if", "(", "consumeOptions", ".", "noBatch", ")", "{", "return", "getNoBatchOps", "(", "raw", ")", ";", "}", "return", "getTrackedOps", "(", "raw", ")", ";", "}" ]
Get message operations @private
[ "Get", "message", "operations" ]
0370c38ebb8c7917cfd3894263d734aefc2d3d29
https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/amqp/queue.js#L152-L162
42,044
LeisureLink/magicbus
lib/amqp/queue.js
subscribe
function subscribe(callback, subscribeOptions) { let consumeOptions = {}; _.assign(consumeOptions, options, subscribeOptions); consumeOptions = _.pick(consumeOptions, ['consumerTag', 'noAck', 'noBatch', 'limit', 'exclusive', 'priority', 'arguments']); let shouldAck = !consumeOptions.noAck; let shouldBatch = !consumeOptions.noBatch; if (shouldAck && shouldBatch) { messages.listenForSignal(); } qLog.info(`Starting subscription ${channelName} - ${connectionName} with ${JSON.stringify(consumeOptions)}`); return (consumeOptions.limit !== false ? channel.prefetch(consumeOptions.limit || 500) : Promise.resolve()) .then(() => { function handler(raw) { let ops = getResolutionOperations(raw, consumeOptions); qLog.silly(`Received message on queue ${channelName} - ${connectionName}`); if (shouldAck && shouldBatch) { messages.addMessage(ops.message); } try { callback(raw, ops); } catch(e) { qLog.error(`Error handing message on queue ${channelName} - ${connectionName}`, e); ops.reject(); } } return channel.consume(channelName, handler, _.omit(consumeOptions, ['noBatch', 'limit'])); }).then(function(result) { channel.tag = result.consumerTag; return result; }); }
javascript
function subscribe(callback, subscribeOptions) { let consumeOptions = {}; _.assign(consumeOptions, options, subscribeOptions); consumeOptions = _.pick(consumeOptions, ['consumerTag', 'noAck', 'noBatch', 'limit', 'exclusive', 'priority', 'arguments']); let shouldAck = !consumeOptions.noAck; let shouldBatch = !consumeOptions.noBatch; if (shouldAck && shouldBatch) { messages.listenForSignal(); } qLog.info(`Starting subscription ${channelName} - ${connectionName} with ${JSON.stringify(consumeOptions)}`); return (consumeOptions.limit !== false ? channel.prefetch(consumeOptions.limit || 500) : Promise.resolve()) .then(() => { function handler(raw) { let ops = getResolutionOperations(raw, consumeOptions); qLog.silly(`Received message on queue ${channelName} - ${connectionName}`); if (shouldAck && shouldBatch) { messages.addMessage(ops.message); } try { callback(raw, ops); } catch(e) { qLog.error(`Error handing message on queue ${channelName} - ${connectionName}`, e); ops.reject(); } } return channel.consume(channelName, handler, _.omit(consumeOptions, ['noBatch', 'limit'])); }).then(function(result) { channel.tag = result.consumerTag; return result; }); }
[ "function", "subscribe", "(", "callback", ",", "subscribeOptions", ")", "{", "let", "consumeOptions", "=", "{", "}", ";", "_", ".", "assign", "(", "consumeOptions", ",", "options", ",", "subscribeOptions", ")", ";", "consumeOptions", "=", "_", ".", "pick", "(", "consumeOptions", ",", "[", "'consumerTag'", ",", "'noAck'", ",", "'noBatch'", ",", "'limit'", ",", "'exclusive'", ",", "'priority'", ",", "'arguments'", "]", ")", ";", "let", "shouldAck", "=", "!", "consumeOptions", ".", "noAck", ";", "let", "shouldBatch", "=", "!", "consumeOptions", ".", "noBatch", ";", "if", "(", "shouldAck", "&&", "shouldBatch", ")", "{", "messages", ".", "listenForSignal", "(", ")", ";", "}", "qLog", ".", "info", "(", "`", "${", "channelName", "}", "${", "connectionName", "}", "${", "JSON", ".", "stringify", "(", "consumeOptions", ")", "}", "`", ")", ";", "return", "(", "consumeOptions", ".", "limit", "!==", "false", "?", "channel", ".", "prefetch", "(", "consumeOptions", ".", "limit", "||", "500", ")", ":", "Promise", ".", "resolve", "(", ")", ")", ".", "then", "(", "(", ")", "=>", "{", "function", "handler", "(", "raw", ")", "{", "let", "ops", "=", "getResolutionOperations", "(", "raw", ",", "consumeOptions", ")", ";", "qLog", ".", "silly", "(", "`", "${", "channelName", "}", "${", "connectionName", "}", "`", ")", ";", "if", "(", "shouldAck", "&&", "shouldBatch", ")", "{", "messages", ".", "addMessage", "(", "ops", ".", "message", ")", ";", "}", "try", "{", "callback", "(", "raw", ",", "ops", ")", ";", "}", "catch", "(", "e", ")", "{", "qLog", ".", "error", "(", "`", "${", "channelName", "}", "${", "connectionName", "}", "`", ",", "e", ")", ";", "ops", ".", "reject", "(", ")", ";", "}", "}", "return", "channel", ".", "consume", "(", "channelName", ",", "handler", ",", "_", ".", "omit", "(", "consumeOptions", ",", "[", "'noBatch'", ",", "'limit'", "]", ")", ")", ";", "}", ")", ".", "then", "(", "function", "(", "result", ")", "{", "channel", ".", "tag", "=", "result", ".", "consumerTag", ";", "return", "result", ";", "}", ")", ";", "}" ]
Subscribe to the queue's messages @public @param {Function} callback - the function to call for each message received from queue. Should have signature function (message, operations) where operations contains ack, nack, and reject functions @param {Object} subscribeOptions - details in consuming from the queue. Overrides any equivalent options sent in to Queue constructor - passed to amqplib's consume function @param {Number} subscribeOptions.limit - the channel prefetch limit @param {bool} subscribeOptions.noAck - if true, the broker won't expect an acknowledgement of messages delivered to this consumer; i.e., it will dequeue messages as soon as they've been sent down the wire. Defaults to false (i.e., you will be expected to acknowledge messages). @param {bool} subscribeOptions.noBatch - if true, ack/nack/reject operations will execute immediately and not be batched @param {String} subscribeOptions.consumerTag - a name which the server will use to distinguish message deliveries for the consumer; mustn't be already in use on the channel. It's usually easier to omit this, in which case the server will create a random name and supply it in the reply. @param {bool} subscribeOptions.exclusive - if true, the broker won't let anyone else consume from this queue; if there already is a consumer, there goes your channel (so usually only useful if you've made a 'private' queue by letting the server choose its name). @param {Number} subscribeOptions.priority - gives a priority to the consumer; higher priority consumers get messages in preference to lower priority consumers. See this RabbitMQ extension's documentation @param {Object} subscribeOptions.arguments - arbitrary arguments. Go to town.
[ "Subscribe", "to", "the", "queue", "s", "messages" ]
0370c38ebb8c7917cfd3894263d734aefc2d3d29
https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/amqp/queue.js#L177-L212
42,045
LeisureLink/magicbus
lib/amqp/queue.js
define
function define() { let aqOptions = getAssertQueueOptions(); topLog.info(`Declaring queue \'${channelName}\' on connection \'${connectionName}\' with the options: ${JSON.stringify(_.omit(aqOptions, ['name']))}`); return channel.assertQueue(channelName, aqOptions); }
javascript
function define() { let aqOptions = getAssertQueueOptions(); topLog.info(`Declaring queue \'${channelName}\' on connection \'${connectionName}\' with the options: ${JSON.stringify(_.omit(aqOptions, ['name']))}`); return channel.assertQueue(channelName, aqOptions); }
[ "function", "define", "(", ")", "{", "let", "aqOptions", "=", "getAssertQueueOptions", "(", ")", ";", "topLog", ".", "info", "(", "`", "\\'", "${", "channelName", "}", "\\'", "\\'", "${", "connectionName", "}", "\\'", "${", "JSON", ".", "stringify", "(", "_", ".", "omit", "(", "aqOptions", ",", "[", "'name'", "]", ")", ")", "}", "`", ")", ";", "return", "channel", ".", "assertQueue", "(", "channelName", ",", "aqOptions", ")", ";", "}" ]
Define the queue @public
[ "Define", "the", "queue" ]
0370c38ebb8c7917cfd3894263d734aefc2d3d29
https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/amqp/queue.js#L230-L234
42,046
Mammut-FE/nejm
src/util/ajax/platform/message.patch.js
function(_map,_index,_list){ if (_u._$indexOf(_checklist,_map.w)<0){ _checklist.push(_map.w); _list.splice(_index,1); _map.w.name = _map.d; } }
javascript
function(_map,_index,_list){ if (_u._$indexOf(_checklist,_map.w)<0){ _checklist.push(_map.w); _list.splice(_index,1); _map.w.name = _map.d; } }
[ "function", "(", "_map", ",", "_index", ",", "_list", ")", "{", "if", "(", "_u", ".", "_$indexOf", "(", "_checklist", ",", "_map", ".", "w", ")", "<", "0", ")", "{", "_checklist", ".", "push", "(", "_map", ".", "w", ")", ";", "_list", ".", "splice", "(", "_index", ",", "1", ")", ";", "_map", ".", "w", ".", "name", "=", "_map", ".", "d", ";", "}", "}" ]
set window.name
[ "set", "window", ".", "name" ]
dfc09ac66a8d67620a7aea65e34d8a179976b3fb
https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/util/ajax/platform/message.patch.js#L63-L69
42,047
Mammut-FE/nejm
src/util/ajax/platform/message.patch.js
function(_data){ var _result = {}; _data = _data||_o; _result.origin = _data.origin||''; _result.ref = location.href; _result.self = _data.source; _result.data = JSON.stringify(_data.data); return _key+_u._$object2string(_result,'|',!0); }
javascript
function(_data){ var _result = {}; _data = _data||_o; _result.origin = _data.origin||''; _result.ref = location.href; _result.self = _data.source; _result.data = JSON.stringify(_data.data); return _key+_u._$object2string(_result,'|',!0); }
[ "function", "(", "_data", ")", "{", "var", "_result", "=", "{", "}", ";", "_data", "=", "_data", "||", "_o", ";", "_result", ".", "origin", "=", "_data", ".", "origin", "||", "''", ";", "_result", ".", "ref", "=", "location", ".", "href", ";", "_result", ".", "self", "=", "_data", ".", "source", ";", "_result", ".", "data", "=", "JSON", ".", "stringify", "(", "_data", ".", "data", ")", ";", "return", "_key", "+", "_u", ".", "_$object2string", "(", "_result", ",", "'|'", ",", "!", "0", ")", ";", "}" ]
serialize send data
[ "serialize", "send", "data" ]
dfc09ac66a8d67620a7aea65e34d8a179976b3fb
https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/util/ajax/platform/message.patch.js#L84-L92
42,048
odopod/code-library
packages/odo-on-swipe/dist/odo-on-swipe.js
OnSwipe
function OnSwipe(element, fn) { var axis = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : OdoPointer.Axis.X; classCallCheck(this, OnSwipe); this.fn = fn; this.pointer = new OdoPointer(element, { axis: axis }); this._onEnd = this._handlePointerEnd.bind(this); this.pointer.on(OdoPointer.EventType.END, this._onEnd); }
javascript
function OnSwipe(element, fn) { var axis = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : OdoPointer.Axis.X; classCallCheck(this, OnSwipe); this.fn = fn; this.pointer = new OdoPointer(element, { axis: axis }); this._onEnd = this._handlePointerEnd.bind(this); this.pointer.on(OdoPointer.EventType.END, this._onEnd); }
[ "function", "OnSwipe", "(", "element", ",", "fn", ")", "{", "var", "axis", "=", "arguments", ".", "length", ">", "2", "&&", "arguments", "[", "2", "]", "!==", "undefined", "?", "arguments", "[", "2", "]", ":", "OdoPointer", ".", "Axis", ".", "X", ";", "classCallCheck", "(", "this", ",", "OnSwipe", ")", ";", "this", ".", "fn", "=", "fn", ";", "this", ".", "pointer", "=", "new", "OdoPointer", "(", "element", ",", "{", "axis", ":", "axis", "}", ")", ";", "this", ".", "_onEnd", "=", "this", ".", "_handlePointerEnd", ".", "bind", "(", "this", ")", ";", "this", ".", "pointer", ".", "on", "(", "OdoPointer", ".", "EventType", ".", "END", ",", "this", ".", "_onEnd", ")", ";", "}" ]
Provides a callback for swipe events. @param {Element} element Element to watch for swipes. @param {function(PointerEvent)} fn Callback when swiped. @param {OdoPointer.Axis} [axis] Optional axis. Defaults to 'x'. @constructor
[ "Provides", "a", "callback", "for", "swipe", "events", "." ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/packages/odo-on-swipe/dist/odo-on-swipe.js#L23-L36
42,049
odopod/code-library
docs/odo-on-swipe/scripts/demo.js
swiped
function swiped(event) { console.log(event); event.currentTarget.querySelector('span').textContent = 'Swiped ' + event.direction; }
javascript
function swiped(event) { console.log(event); event.currentTarget.querySelector('span').textContent = 'Swiped ' + event.direction; }
[ "function", "swiped", "(", "event", ")", "{", "console", ".", "log", "(", "event", ")", ";", "event", ".", "currentTarget", ".", "querySelector", "(", "'span'", ")", ".", "textContent", "=", "'Swiped '", "+", "event", ".", "direction", ";", "}" ]
On Swipe handler. @param {PointerEvent} event Pointer event object.
[ "On", "Swipe", "handler", "." ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/docs/odo-on-swipe/scripts/demo.js#L10-L13
42,050
odopod/code-library
packages/odo-helpers/src/events.js
getTransitionEndEvent
function getTransitionEndEvent() { const div = document.createElement('div'); div.style.transitionProperty = 'width'; // Test the value which was just set. If it wasn't able to be set, // then it shouldn't use unprefixed transitions. /* istanbul ignore next */ if (div.style.transitionProperty !== 'width' && 'webkitTransition' in div.style) { return 'webkitTransitionEnd'; } return { // Saf < 7, Android Browser < 4.4 WebkitTransition: 'webkitTransitionEnd', transition: 'transitionend', }[OdoDevice.Dom.TRANSITION]; }
javascript
function getTransitionEndEvent() { const div = document.createElement('div'); div.style.transitionProperty = 'width'; // Test the value which was just set. If it wasn't able to be set, // then it shouldn't use unprefixed transitions. /* istanbul ignore next */ if (div.style.transitionProperty !== 'width' && 'webkitTransition' in div.style) { return 'webkitTransitionEnd'; } return { // Saf < 7, Android Browser < 4.4 WebkitTransition: 'webkitTransitionEnd', transition: 'transitionend', }[OdoDevice.Dom.TRANSITION]; }
[ "function", "getTransitionEndEvent", "(", ")", "{", "const", "div", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "div", ".", "style", ".", "transitionProperty", "=", "'width'", ";", "// Test the value which was just set. If it wasn't able to be set,", "// then it shouldn't use unprefixed transitions.", "/* istanbul ignore next */", "if", "(", "div", ".", "style", ".", "transitionProperty", "!==", "'width'", "&&", "'webkitTransition'", "in", "div", ".", "style", ")", "{", "return", "'webkitTransitionEnd'", ";", "}", "return", "{", "// Saf < 7, Android Browser < 4.4", "WebkitTransition", ":", "'webkitTransitionEnd'", ",", "transition", ":", "'transitionend'", ",", "}", "[", "OdoDevice", ".", "Dom", ".", "TRANSITION", "]", ";", "}" ]
Returns a normalized transition end event name. Issue with Modernizr prefixing related to stock Android 4.1.2 That version of Android has both unprefixed and prefixed transitions built in, but will only listen to the prefixed on in certain cases https://github.com/Modernizr/Modernizr/issues/897 @return {string} A patched transition end event name.
[ "Returns", "a", "normalized", "transition", "end", "event", "name", "." ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/packages/odo-helpers/src/events.js#L28-L44
42,051
vega/vega-transforms
src/Pivot.js
aggregateParams
function aggregateParams(_, pulse) { var key = _.field, value = _.value, op = (_.op === 'count' ? '__count__' : _.op) || 'sum', fields = accessorFields(key).concat(accessorFields(value)), keys = pivotKeys(key, _.limit || 0, pulse); return { key: _.key, groupby: _.groupby, ops: keys.map(function() { return op; }), fields: keys.map(function(k) { return get(k, key, value, fields); }), as: keys.map(function(k) { return k + ''; }), modified: _.modified.bind(_) }; }
javascript
function aggregateParams(_, pulse) { var key = _.field, value = _.value, op = (_.op === 'count' ? '__count__' : _.op) || 'sum', fields = accessorFields(key).concat(accessorFields(value)), keys = pivotKeys(key, _.limit || 0, pulse); return { key: _.key, groupby: _.groupby, ops: keys.map(function() { return op; }), fields: keys.map(function(k) { return get(k, key, value, fields); }), as: keys.map(function(k) { return k + ''; }), modified: _.modified.bind(_) }; }
[ "function", "aggregateParams", "(", "_", ",", "pulse", ")", "{", "var", "key", "=", "_", ".", "field", ",", "value", "=", "_", ".", "value", ",", "op", "=", "(", "_", ".", "op", "===", "'count'", "?", "'__count__'", ":", "_", ".", "op", ")", "||", "'sum'", ",", "fields", "=", "accessorFields", "(", "key", ")", ".", "concat", "(", "accessorFields", "(", "value", ")", ")", ",", "keys", "=", "pivotKeys", "(", "key", ",", "_", ".", "limit", "||", "0", ",", "pulse", ")", ";", "return", "{", "key", ":", "_", ".", "key", ",", "groupby", ":", "_", ".", "groupby", ",", "ops", ":", "keys", ".", "map", "(", "function", "(", ")", "{", "return", "op", ";", "}", ")", ",", "fields", ":", "keys", ".", "map", "(", "function", "(", "k", ")", "{", "return", "get", "(", "k", ",", "key", ",", "value", ",", "fields", ")", ";", "}", ")", ",", "as", ":", "keys", ".", "map", "(", "function", "(", "k", ")", "{", "return", "k", "+", "''", ";", "}", ")", ",", "modified", ":", "_", ".", "modified", ".", "bind", "(", "_", ")", "}", ";", "}" ]
Shoehorn a pivot transform into an aggregate transform! First collect all unique pivot field values. Then generate aggregate fields for each output pivot field.
[ "Shoehorn", "a", "pivot", "transform", "into", "an", "aggregate", "transform!", "First", "collect", "all", "unique", "pivot", "field", "values", ".", "Then", "generate", "aggregate", "fields", "for", "each", "output", "pivot", "field", "." ]
0f7049cc73ec67630a487aa916119769073d5a87
https://github.com/vega/vega-transforms/blob/0f7049cc73ec67630a487aa916119769073d5a87/src/Pivot.js#L49-L64
42,052
vega/vega-transforms
src/Pivot.js
get
function get(k, key, value, fields) { return accessor( function(d) { return key(d) === k ? value(d) : NaN; }, fields, k + '' ); }
javascript
function get(k, key, value, fields) { return accessor( function(d) { return key(d) === k ? value(d) : NaN; }, fields, k + '' ); }
[ "function", "get", "(", "k", ",", "key", ",", "value", ",", "fields", ")", "{", "return", "accessor", "(", "function", "(", "d", ")", "{", "return", "key", "(", "d", ")", "===", "k", "?", "value", "(", "d", ")", ":", "NaN", ";", "}", ",", "fields", ",", "k", "+", "''", ")", ";", "}" ]
Generate aggregate field accessor. Output NaN for non-existent values; aggregator will ignore!
[ "Generate", "aggregate", "field", "accessor", ".", "Output", "NaN", "for", "non", "-", "existent", "values", ";", "aggregator", "will", "ignore!" ]
0f7049cc73ec67630a487aa916119769073d5a87
https://github.com/vega/vega-transforms/blob/0f7049cc73ec67630a487aa916119769073d5a87/src/Pivot.js#L68-L74
42,053
odopod/code-library
packages/odo-viewport/dist/odo-viewport.js
ViewportItem
function ViewportItem(options, parent) { classCallCheck(this, ViewportItem); this.parent = parent; this.id = Math.random().toString(36).substring(7); this.triggered = false; this.threshold = 200; this.isThresholdPercentage = false; // Override defaults with options. Object.assign(this, options); // The whole point is to have a callback function. Don't do anything if it's not given. if (typeof this.enter !== 'function') { throw new TypeError('Viewport.add :: No `enter` function provided in Viewport options.'); } this.parseThreshold(); this.hasExitCallback = typeof this.exit === 'function'; // Cache element's offsets and dimensions. this.update(); }
javascript
function ViewportItem(options, parent) { classCallCheck(this, ViewportItem); this.parent = parent; this.id = Math.random().toString(36).substring(7); this.triggered = false; this.threshold = 200; this.isThresholdPercentage = false; // Override defaults with options. Object.assign(this, options); // The whole point is to have a callback function. Don't do anything if it's not given. if (typeof this.enter !== 'function') { throw new TypeError('Viewport.add :: No `enter` function provided in Viewport options.'); } this.parseThreshold(); this.hasExitCallback = typeof this.exit === 'function'; // Cache element's offsets and dimensions. this.update(); }
[ "function", "ViewportItem", "(", "options", ",", "parent", ")", "{", "classCallCheck", "(", "this", ",", "ViewportItem", ")", ";", "this", ".", "parent", "=", "parent", ";", "this", ".", "id", "=", "Math", ".", "random", "(", ")", ".", "toString", "(", "36", ")", ".", "substring", "(", "7", ")", ";", "this", ".", "triggered", "=", "false", ";", "this", ".", "threshold", "=", "200", ";", "this", ".", "isThresholdPercentage", "=", "false", ";", "// Override defaults with options.", "Object", ".", "assign", "(", "this", ",", "options", ")", ";", "// The whole point is to have a callback function. Don't do anything if it's not given.", "if", "(", "typeof", "this", ".", "enter", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "'Viewport.add :: No `enter` function provided in Viewport options.'", ")", ";", "}", "this", ".", "parseThreshold", "(", ")", ";", "this", ".", "hasExitCallback", "=", "typeof", "this", ".", "exit", "===", "'function'", ";", "// Cache element's offsets and dimensions.", "this", ".", "update", "(", ")", ";", "}" ]
A viewport item represents an element being watched by the Viewport component. @param {Object} options Viewport item options. @param {Viewport} parent A reference to the viewport. @constructor
[ "A", "viewport", "item", "represents", "an", "element", "being", "watched", "by", "the", "Viewport", "component", "." ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/packages/odo-viewport/dist/odo-viewport.js#L40-L63
42,054
odopod/code-library
packages/odo-viewport/dist/odo-viewport.js
Viewport
function Viewport() { classCallCheck(this, Viewport); this.addId = null; this.hasActiveHandlers = false; this.items = new Map(); // Assume there is no horizontal scrollbar. documentElement.clientHeight // is incorrect on iOS 8 because it includes toolbars. this.viewportHeight = window.innerHeight; this.viewportWidth = document.documentElement.clientWidth; this.viewportTop = 0; // What's nice here is that rAF won't execute until the user is on this tab, // so if they open the page in a new tab which they aren't looking at, // this will execute when they come back to that tab. requestAnimationFrame(this.handleScroll.bind(this)); }
javascript
function Viewport() { classCallCheck(this, Viewport); this.addId = null; this.hasActiveHandlers = false; this.items = new Map(); // Assume there is no horizontal scrollbar. documentElement.clientHeight // is incorrect on iOS 8 because it includes toolbars. this.viewportHeight = window.innerHeight; this.viewportWidth = document.documentElement.clientWidth; this.viewportTop = 0; // What's nice here is that rAF won't execute until the user is on this tab, // so if they open the page in a new tab which they aren't looking at, // this will execute when they come back to that tab. requestAnimationFrame(this.handleScroll.bind(this)); }
[ "function", "Viewport", "(", ")", "{", "classCallCheck", "(", "this", ",", "Viewport", ")", ";", "this", ".", "addId", "=", "null", ";", "this", ".", "hasActiveHandlers", "=", "false", ";", "this", ".", "items", "=", "new", "Map", "(", ")", ";", "// Assume there is no horizontal scrollbar. documentElement.clientHeight", "// is incorrect on iOS 8 because it includes toolbars.", "this", ".", "viewportHeight", "=", "window", ".", "innerHeight", ";", "this", ".", "viewportWidth", "=", "document", ".", "documentElement", ".", "clientWidth", ";", "this", ".", "viewportTop", "=", "0", ";", "// What's nice here is that rAF won't execute until the user is on this tab,", "// so if they open the page in a new tab which they aren't looking at,", "// this will execute when they come back to that tab.", "requestAnimationFrame", "(", "this", ".", "handleScroll", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Viewport singleton. @constructor
[ "Viewport", "singleton", "." ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/packages/odo-viewport/dist/odo-viewport.js#L132-L149
42,055
popomore/ypkgfiles
index.js
resolveEntry
function resolveEntry(options) { const cwd = options.cwd; const pkg = options.pkg; let entries = []; if (is.array(options.entry)) entries = options.entry; if (is.string(options.entry)) entries.push(options.entry); const result = new Set(); try { // set the entry that module exports result.add(require.resolve(cwd)); } catch (_) { // ignore } for (let entry of entries) { const dir = path.join(cwd, entry); // if entry is directory, find all js in the directory if (fs.existsSync(dir) && fs.statSync(dir).isDirectory()) { entry = path.join(entry, '**/*.js'); } const files = glob.sync(entry, { cwd }); for (const file of files) { result.add(path.join(cwd, file)); } } if (pkg.bin) { const keys = Object.keys(pkg.bin); for (const key of keys) { result.add(path.join(cwd, pkg.bin[key])); } } const dts = path.join(cwd, 'index.d.ts'); if (fs.existsSync(dts)) { result.add(dts); } return Array.from(result); }
javascript
function resolveEntry(options) { const cwd = options.cwd; const pkg = options.pkg; let entries = []; if (is.array(options.entry)) entries = options.entry; if (is.string(options.entry)) entries.push(options.entry); const result = new Set(); try { // set the entry that module exports result.add(require.resolve(cwd)); } catch (_) { // ignore } for (let entry of entries) { const dir = path.join(cwd, entry); // if entry is directory, find all js in the directory if (fs.existsSync(dir) && fs.statSync(dir).isDirectory()) { entry = path.join(entry, '**/*.js'); } const files = glob.sync(entry, { cwd }); for (const file of files) { result.add(path.join(cwd, file)); } } if (pkg.bin) { const keys = Object.keys(pkg.bin); for (const key of keys) { result.add(path.join(cwd, pkg.bin[key])); } } const dts = path.join(cwd, 'index.d.ts'); if (fs.existsSync(dts)) { result.add(dts); } return Array.from(result); }
[ "function", "resolveEntry", "(", "options", ")", "{", "const", "cwd", "=", "options", ".", "cwd", ";", "const", "pkg", "=", "options", ".", "pkg", ";", "let", "entries", "=", "[", "]", ";", "if", "(", "is", ".", "array", "(", "options", ".", "entry", ")", ")", "entries", "=", "options", ".", "entry", ";", "if", "(", "is", ".", "string", "(", "options", ".", "entry", ")", ")", "entries", ".", "push", "(", "options", ".", "entry", ")", ";", "const", "result", "=", "new", "Set", "(", ")", ";", "try", "{", "// set the entry that module exports", "result", ".", "add", "(", "require", ".", "resolve", "(", "cwd", ")", ")", ";", "}", "catch", "(", "_", ")", "{", "// ignore", "}", "for", "(", "let", "entry", "of", "entries", ")", "{", "const", "dir", "=", "path", ".", "join", "(", "cwd", ",", "entry", ")", ";", "// if entry is directory, find all js in the directory", "if", "(", "fs", ".", "existsSync", "(", "dir", ")", "&&", "fs", ".", "statSync", "(", "dir", ")", ".", "isDirectory", "(", ")", ")", "{", "entry", "=", "path", ".", "join", "(", "entry", ",", "'**/*.js'", ")", ";", "}", "const", "files", "=", "glob", ".", "sync", "(", "entry", ",", "{", "cwd", "}", ")", ";", "for", "(", "const", "file", "of", "files", ")", "{", "result", ".", "add", "(", "path", ".", "join", "(", "cwd", ",", "file", ")", ")", ";", "}", "}", "if", "(", "pkg", ".", "bin", ")", "{", "const", "keys", "=", "Object", ".", "keys", "(", "pkg", ".", "bin", ")", ";", "for", "(", "const", "key", "of", "keys", ")", "{", "result", ".", "add", "(", "path", ".", "join", "(", "cwd", ",", "pkg", ".", "bin", "[", "key", "]", ")", ")", ";", "}", "}", "const", "dts", "=", "path", ".", "join", "(", "cwd", ",", "'index.d.ts'", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "dts", ")", ")", "{", "result", ".", "add", "(", "dts", ")", ";", "}", "return", "Array", ".", "from", "(", "result", ")", ";", "}" ]
return entries with fullpath based on options.entry
[ "return", "entries", "with", "fullpath", "based", "on", "options", ".", "entry" ]
f99f76089e6a30318be8013fc21dfa9838016d29
https://github.com/popomore/ypkgfiles/blob/f99f76089e6a30318be8013fc21dfa9838016d29/index.js#L53-L94
42,056
lmalave/aframe-speech-command-component
examples/components/set-image.js
function () { var data = this.data; var targetEl = this.data.target; // Only set up once. if (targetEl.dataset.setImageFadeSetup) { return; } targetEl.dataset.setImageFadeSetup = true; // Create animation. targetEl.setAttribute('animation__fade', { property: 'material.color', startEvents: 'set-image-fade', dir: 'alternate', dur: data.dur, from: '#FFF', to: '#000' }); }
javascript
function () { var data = this.data; var targetEl = this.data.target; // Only set up once. if (targetEl.dataset.setImageFadeSetup) { return; } targetEl.dataset.setImageFadeSetup = true; // Create animation. targetEl.setAttribute('animation__fade', { property: 'material.color', startEvents: 'set-image-fade', dir: 'alternate', dur: data.dur, from: '#FFF', to: '#000' }); }
[ "function", "(", ")", "{", "var", "data", "=", "this", ".", "data", ";", "var", "targetEl", "=", "this", ".", "data", ".", "target", ";", "// Only set up once.", "if", "(", "targetEl", ".", "dataset", ".", "setImageFadeSetup", ")", "{", "return", ";", "}", "targetEl", ".", "dataset", ".", "setImageFadeSetup", "=", "true", ";", "// Create animation.", "targetEl", ".", "setAttribute", "(", "'animation__fade'", ",", "{", "property", ":", "'material.color'", ",", "startEvents", ":", "'set-image-fade'", ",", "dir", ":", "'alternate'", ",", "dur", ":", "data", ".", "dur", ",", "from", ":", "'#FFF'", ",", "to", ":", "'#000'", "}", ")", ";", "}" ]
Setup fade-in + fade-out.
[ "Setup", "fade", "-", "in", "+", "fade", "-", "out", "." ]
5859588e54649c585c74b2cdc41c13a28cbb89c1
https://github.com/lmalave/aframe-speech-command-component/blob/5859588e54649c585c74b2cdc41c13a28cbb89c1/examples/components/set-image.js#L35-L52
42,057
dominictarr/map-filter-reduce
make.js
arrayGroup
function arrayGroup (set, get, reduce) { //we can use a different lookup path on the right hand object //is always the "needle" function _compare (hay, needle) { for(var i in set) { var x = u.get(hay, set[i]), y = needle[i] if(x !== y) return compare(x, y) } return 0 } return function (a, b) { if(a && !Array.isArray(a)) a = reduce([], a) var A = a = a || [] var i = search(A, get.map(function (fn) { return fn(b) }), _compare) if(i >= 0) A[i] = reduce(A[i], b) else A.splice(~i, 0, reduce(undefined, b)) return a } }
javascript
function arrayGroup (set, get, reduce) { //we can use a different lookup path on the right hand object //is always the "needle" function _compare (hay, needle) { for(var i in set) { var x = u.get(hay, set[i]), y = needle[i] if(x !== y) return compare(x, y) } return 0 } return function (a, b) { if(a && !Array.isArray(a)) a = reduce([], a) var A = a = a || [] var i = search(A, get.map(function (fn) { return fn(b) }), _compare) if(i >= 0) A[i] = reduce(A[i], b) else A.splice(~i, 0, reduce(undefined, b)) return a } }
[ "function", "arrayGroup", "(", "set", ",", "get", ",", "reduce", ")", "{", "//we can use a different lookup path on the right hand object", "//is always the \"needle\"", "function", "_compare", "(", "hay", ",", "needle", ")", "{", "for", "(", "var", "i", "in", "set", ")", "{", "var", "x", "=", "u", ".", "get", "(", "hay", ",", "set", "[", "i", "]", ")", ",", "y", "=", "needle", "[", "i", "]", "if", "(", "x", "!==", "y", ")", "return", "compare", "(", "x", ",", "y", ")", "}", "return", "0", "}", "return", "function", "(", "a", ",", "b", ")", "{", "if", "(", "a", "&&", "!", "Array", ".", "isArray", "(", "a", ")", ")", "a", "=", "reduce", "(", "[", "]", ",", "a", ")", "var", "A", "=", "a", "=", "a", "||", "[", "]", "var", "i", "=", "search", "(", "A", ",", "get", ".", "map", "(", "function", "(", "fn", ")", "{", "return", "fn", "(", "b", ")", "}", ")", ",", "_compare", ")", "if", "(", "i", ">=", "0", ")", "A", "[", "i", "]", "=", "reduce", "(", "A", "[", "i", "]", ",", "b", ")", "else", "A", ".", "splice", "(", "~", "i", ",", "0", ",", "reduce", "(", "undefined", ",", "b", ")", ")", "return", "a", "}", "}" ]
rawpaths, reducedpaths, reduce
[ "rawpaths", "reducedpaths", "reduce" ]
2f94c186a812066c3d52612887189ac552bd386d
https://github.com/dominictarr/map-filter-reduce/blob/2f94c186a812066c3d52612887189ac552bd386d/make.js#L95-L117
42,058
dominictarr/map-filter-reduce
make.js
_compare
function _compare (hay, needle) { for(var i in set) { var x = u.get(hay, set[i]), y = needle[i] if(x !== y) return compare(x, y) } return 0 }
javascript
function _compare (hay, needle) { for(var i in set) { var x = u.get(hay, set[i]), y = needle[i] if(x !== y) return compare(x, y) } return 0 }
[ "function", "_compare", "(", "hay", ",", "needle", ")", "{", "for", "(", "var", "i", "in", "set", ")", "{", "var", "x", "=", "u", ".", "get", "(", "hay", ",", "set", "[", "i", "]", ")", ",", "y", "=", "needle", "[", "i", "]", "if", "(", "x", "!==", "y", ")", "return", "compare", "(", "x", ",", "y", ")", "}", "return", "0", "}" ]
we can use a different lookup path on the right hand object is always the "needle"
[ "we", "can", "use", "a", "different", "lookup", "path", "on", "the", "right", "hand", "object", "is", "always", "the", "needle" ]
2f94c186a812066c3d52612887189ac552bd386d
https://github.com/dominictarr/map-filter-reduce/blob/2f94c186a812066c3d52612887189ac552bd386d/make.js#L99-L105
42,059
odopod/code-library
packages/odo-helpers/src/even-heights.js
getTallest
function getTallest(elements) { let tallest = 0; for (let i = elements.length - 1; i >= 0; i--) { if (elements[i].offsetHeight > tallest) { tallest = elements[i].offsetHeight; } } return tallest; }
javascript
function getTallest(elements) { let tallest = 0; for (let i = elements.length - 1; i >= 0; i--) { if (elements[i].offsetHeight > tallest) { tallest = elements[i].offsetHeight; } } return tallest; }
[ "function", "getTallest", "(", "elements", ")", "{", "let", "tallest", "=", "0", ";", "for", "(", "let", "i", "=", "elements", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "elements", "[", "i", "]", ".", "offsetHeight", ">", "tallest", ")", "{", "tallest", "=", "elements", "[", "i", "]", ".", "offsetHeight", ";", "}", "}", "return", "tallest", ";", "}" ]
Determine which element in an array is the tallest. @param {ArrayLike<HTMLElement>} elements Array-like of elements. @return {number} Height of the tallest element.
[ "Determine", "which", "element", "in", "an", "array", "is", "the", "tallest", "." ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/packages/odo-helpers/src/even-heights.js#L6-L16
42,060
odopod/code-library
packages/odo-helpers/src/even-heights.js
setAllHeights
function setAllHeights(elements, height) { for (let i = elements.length - 1; i >= 0; i--) { elements[i].style.height = height; } }
javascript
function setAllHeights(elements, height) { for (let i = elements.length - 1; i >= 0; i--) { elements[i].style.height = height; } }
[ "function", "setAllHeights", "(", "elements", ",", "height", ")", "{", "for", "(", "let", "i", "=", "elements", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "elements", "[", "i", "]", ".", "style", ".", "height", "=", "height", ";", "}", "}" ]
Set the height of every element in an array to a value. @param {ArrayLike<HTMLElement>} elements Array-like of elements. @param {string} height Height value to set.
[ "Set", "the", "height", "of", "every", "element", "in", "an", "array", "to", "a", "value", "." ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/packages/odo-helpers/src/even-heights.js#L23-L27
42,061
jyotiska/prettytable
prettytable.js
function (table) { var finalLine = '+'; for (var i = 0; i < table.maxWidth.length; i++) { finalLine += Array(table.maxWidth[i] + 3).join('-') + '+'; } return finalLine; }
javascript
function (table) { var finalLine = '+'; for (var i = 0; i < table.maxWidth.length; i++) { finalLine += Array(table.maxWidth[i] + 3).join('-') + '+'; } return finalLine; }
[ "function", "(", "table", ")", "{", "var", "finalLine", "=", "'+'", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "table", ".", "maxWidth", ".", "length", ";", "i", "++", ")", "{", "finalLine", "+=", "Array", "(", "table", ".", "maxWidth", "[", "i", "]", "+", "3", ")", ".", "join", "(", "'-'", ")", "+", "'+'", ";", "}", "return", "finalLine", ";", "}" ]
Draw a line based on the max width of each column and return
[ "Draw", "a", "line", "based", "on", "the", "max", "width", "of", "each", "column", "and", "return" ]
3211819c22e4db4fad2501d4d0b26094d6e94885
https://github.com/jyotiska/prettytable/blob/3211819c22e4db4fad2501d4d0b26094d6e94885/prettytable.js#L51-L57
42,062
jyotiska/prettytable
prettytable.js
function ( a, b) { if (typeof reverse === 'boolean' && reverse === true) { if (a[colindex] < b[colindex]) { return 1; } else if (a[colindex] > b[colindex]) { return -1; } else { return 0; } } else { if (a[colindex] < b[colindex]) { return -1; } else if (a[colindex] > b[colindex]) { return 1; } else { return 0; } } }
javascript
function ( a, b) { if (typeof reverse === 'boolean' && reverse === true) { if (a[colindex] < b[colindex]) { return 1; } else if (a[colindex] > b[colindex]) { return -1; } else { return 0; } } else { if (a[colindex] < b[colindex]) { return -1; } else if (a[colindex] > b[colindex]) { return 1; } else { return 0; } } }
[ "function", "(", "a", ",", "b", ")", "{", "if", "(", "typeof", "reverse", "===", "'boolean'", "&&", "reverse", "===", "true", ")", "{", "if", "(", "a", "[", "colindex", "]", "<", "b", "[", "colindex", "]", ")", "{", "return", "1", ";", "}", "else", "if", "(", "a", "[", "colindex", "]", ">", "b", "[", "colindex", "]", ")", "{", "return", "-", "1", ";", "}", "else", "{", "return", "0", ";", "}", "}", "else", "{", "if", "(", "a", "[", "colindex", "]", "<", "b", "[", "colindex", "]", ")", "{", "return", "-", "1", ";", "}", "else", "if", "(", "a", "[", "colindex", "]", ">", "b", "[", "colindex", "]", ")", "{", "return", "1", ";", "}", "else", "{", "return", "0", ";", "}", "}", "}" ]
Comparator method which takes the column index and sort direction
[ "Comparator", "method", "which", "takes", "the", "column", "index", "and", "sort", "direction" ]
3211819c22e4db4fad2501d4d0b26094d6e94885
https://github.com/jyotiska/prettytable/blob/3211819c22e4db4fad2501d4d0b26094d6e94885/prettytable.js#L192-L215
42,063
dominictarr/map-filter-reduce
util.js
paths
function paths (object, test) { var p = [] if(test(object)) return [] for(var key in object) { var value = object[key] if(test(value)) p.push(key) else if(isObject(value)) p = p.concat(paths(value, test).map(function (path) { return [key].concat(path) })) } return p }
javascript
function paths (object, test) { var p = [] if(test(object)) return [] for(var key in object) { var value = object[key] if(test(value)) p.push(key) else if(isObject(value)) p = p.concat(paths(value, test).map(function (path) { return [key].concat(path) })) } return p }
[ "function", "paths", "(", "object", ",", "test", ")", "{", "var", "p", "=", "[", "]", "if", "(", "test", "(", "object", ")", ")", "return", "[", "]", "for", "(", "var", "key", "in", "object", ")", "{", "var", "value", "=", "object", "[", "key", "]", "if", "(", "test", "(", "value", ")", ")", "p", ".", "push", "(", "key", ")", "else", "if", "(", "isObject", "(", "value", ")", ")", "p", "=", "p", ".", "concat", "(", "paths", "(", "value", ",", "test", ")", ".", "map", "(", "function", "(", "path", ")", "{", "return", "[", "key", "]", ".", "concat", "(", "path", ")", "}", ")", ")", "}", "return", "p", "}" ]
get all paths within an object this can probably be optimized to create less arrays!
[ "get", "all", "paths", "within", "an", "object", "this", "can", "probably", "be", "optimized", "to", "create", "less", "arrays!" ]
2f94c186a812066c3d52612887189ac552bd386d
https://github.com/dominictarr/map-filter-reduce/blob/2f94c186a812066c3d52612887189ac552bd386d/util.js#L170-L182
42,064
vega/vega-transforms
src/Aggregate.js
collect
function collect(cells) { var key, i, t, v; for (key in cells) { t = cells[key].tuple; for (i=0; i<n; ++i) { vals[i][(v = t[dims[i]])] = v; } } }
javascript
function collect(cells) { var key, i, t, v; for (key in cells) { t = cells[key].tuple; for (i=0; i<n; ++i) { vals[i][(v = t[dims[i]])] = v; } } }
[ "function", "collect", "(", "cells", ")", "{", "var", "key", ",", "i", ",", "t", ",", "v", ";", "for", "(", "key", "in", "cells", ")", "{", "t", "=", "cells", "[", "key", "]", ".", "tuple", ";", "for", "(", "i", "=", "0", ";", "i", "<", "n", ";", "++", "i", ")", "{", "vals", "[", "i", "]", "[", "(", "v", "=", "t", "[", "dims", "[", "i", "]", "]", ")", "]", "=", "v", ";", "}", "}", "}" ]
collect all group-by domain values
[ "collect", "all", "group", "-", "by", "domain", "values" ]
0f7049cc73ec67630a487aa916119769073d5a87
https://github.com/vega/vega-transforms/blob/0f7049cc73ec67630a487aa916119769073d5a87/src/Aggregate.js#L99-L107
42,065
vega/vega-transforms
src/Aggregate.js
generate
function generate(base, tuple, index) { var name = dims[index], v = vals[index++], k, key; for (k in v) { tuple[name] = v[k]; key = base ? base + '|' + k : k; if (index < n) generate(key, tuple, index); else if (!curr[key]) aggr.cell(key, tuple); } }
javascript
function generate(base, tuple, index) { var name = dims[index], v = vals[index++], k, key; for (k in v) { tuple[name] = v[k]; key = base ? base + '|' + k : k; if (index < n) generate(key, tuple, index); else if (!curr[key]) aggr.cell(key, tuple); } }
[ "function", "generate", "(", "base", ",", "tuple", ",", "index", ")", "{", "var", "name", "=", "dims", "[", "index", "]", ",", "v", "=", "vals", "[", "index", "++", "]", ",", "k", ",", "key", ";", "for", "(", "k", "in", "v", ")", "{", "tuple", "[", "name", "]", "=", "v", "[", "k", "]", ";", "key", "=", "base", "?", "base", "+", "'|'", "+", "k", ":", "k", ";", "if", "(", "index", "<", "n", ")", "generate", "(", "key", ",", "tuple", ",", "index", ")", ";", "else", "if", "(", "!", "curr", "[", "key", "]", ")", "aggr", ".", "cell", "(", "key", ",", "tuple", ")", ";", "}", "}" ]
iterate over key cross-product, create cells as needed
[ "iterate", "over", "key", "cross", "-", "product", "create", "cells", "as", "needed" ]
0f7049cc73ec67630a487aa916119769073d5a87
https://github.com/vega/vega-transforms/blob/0f7049cc73ec67630a487aa916119769073d5a87/src/Aggregate.js#L112-L123
42,066
odopod/code-library
packages/odo-tap/dist/odo-tap.js
Tap
function Tap(element, fn, preventEventDefault) { classCallCheck(this, Tap); this.element = element; this.fn = fn; this.preventEventDefault = preventEventDefault; this.pointer = new OdoPointer(element, { preventEventDefault: preventEventDefault }); this._listen(); }
javascript
function Tap(element, fn, preventEventDefault) { classCallCheck(this, Tap); this.element = element; this.fn = fn; this.preventEventDefault = preventEventDefault; this.pointer = new OdoPointer(element, { preventEventDefault: preventEventDefault }); this._listen(); }
[ "function", "Tap", "(", "element", ",", "fn", ",", "preventEventDefault", ")", "{", "classCallCheck", "(", "this", ",", "Tap", ")", ";", "this", ".", "element", "=", "element", ";", "this", ".", "fn", "=", "fn", ";", "this", ".", "preventEventDefault", "=", "preventEventDefault", ";", "this", ".", "pointer", "=", "new", "OdoPointer", "(", "element", ",", "{", "preventEventDefault", ":", "preventEventDefault", "}", ")", ";", "this", ".", "_listen", "(", ")", ";", "}" ]
Interprets touchs on an element as taps. @param {Element} element Element to watch. @param {Function} fn Callback function when the element is tapped. @param {boolean} preventEventDefault Whether or not to prevent the default event during drags. @constructor
[ "Interprets", "touchs", "on", "an", "element", "as", "taps", "." ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/packages/odo-tap/dist/odo-tap.js#L38-L49
42,067
odopod/code-library
packages/odo-pointer/src/pointer-event.js
getVelocity
function getVelocity(deltaTime, deltaX, deltaY) { return new Coordinate( finiteOrZero(deltaX / deltaTime), finiteOrZero(deltaY / deltaTime), ); }
javascript
function getVelocity(deltaTime, deltaX, deltaY) { return new Coordinate( finiteOrZero(deltaX / deltaTime), finiteOrZero(deltaY / deltaTime), ); }
[ "function", "getVelocity", "(", "deltaTime", ",", "deltaX", ",", "deltaY", ")", "{", "return", "new", "Coordinate", "(", "finiteOrZero", "(", "deltaX", "/", "deltaTime", ")", ",", "finiteOrZero", "(", "deltaY", "/", "deltaTime", ")", ",", ")", ";", "}" ]
Calculate the velocity between two points. @param {number} deltaTime Change in time. @param {number} deltaX Change in x. @param {number} deltaY Change in y. @return {Coordinate} Velocity of the drag.
[ "Calculate", "the", "velocity", "between", "two", "points", "." ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/packages/odo-pointer/src/pointer-event.js#L33-L38
42,068
odopod/code-library
packages/odo-pointer/src/pointer-event.js
getDirection
function getDirection(coord1, coord2) { if (Math.abs(coord1.x - coord2.x) >= Math.abs(coord1.y - coord2.y)) { return getTheDirection( coord1.x, coord2.x, Direction.LEFT, Direction.RIGHT, Direction.NONE, ); } return getTheDirection( coord1.y, coord2.y, Direction.UP, Direction.DOWN, Direction.NONE, ); }
javascript
function getDirection(coord1, coord2) { if (Math.abs(coord1.x - coord2.x) >= Math.abs(coord1.y - coord2.y)) { return getTheDirection( coord1.x, coord2.x, Direction.LEFT, Direction.RIGHT, Direction.NONE, ); } return getTheDirection( coord1.y, coord2.y, Direction.UP, Direction.DOWN, Direction.NONE, ); }
[ "function", "getDirection", "(", "coord1", ",", "coord2", ")", "{", "if", "(", "Math", ".", "abs", "(", "coord1", ".", "x", "-", "coord2", ".", "x", ")", ">=", "Math", ".", "abs", "(", "coord1", ".", "y", "-", "coord2", ".", "y", ")", ")", "{", "return", "getTheDirection", "(", "coord1", ".", "x", ",", "coord2", ".", "x", ",", "Direction", ".", "LEFT", ",", "Direction", ".", "RIGHT", ",", "Direction", ".", "NONE", ",", ")", ";", "}", "return", "getTheDirection", "(", "coord1", ".", "y", ",", "coord2", ".", "y", ",", "Direction", ".", "UP", ",", "Direction", ".", "DOWN", ",", "Direction", ".", "NONE", ",", ")", ";", "}" ]
angle to direction define. @param {Coordinate} coord1 The starting coordinate. @param {Coordinate} coord2 The ending coordinate. @return {string} Direction constant.
[ "angle", "to", "direction", "define", "." ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/packages/odo-pointer/src/pointer-event.js#L56-L68
42,069
vega/vega-transforms
src/Sample.js
update
function update(t) { var p, idx; if (res.length < num) { res.push(t); } else { idx = ~~((cnt + 1) * random()); if (idx < res.length && idx >= cap) { p = res[idx]; if (map[tupleid(p)]) out.rem.push(p); // eviction res[idx] = t; } } ++cnt; }
javascript
function update(t) { var p, idx; if (res.length < num) { res.push(t); } else { idx = ~~((cnt + 1) * random()); if (idx < res.length && idx >= cap) { p = res[idx]; if (map[tupleid(p)]) out.rem.push(p); // eviction res[idx] = t; } } ++cnt; }
[ "function", "update", "(", "t", ")", "{", "var", "p", ",", "idx", ";", "if", "(", "res", ".", "length", "<", "num", ")", "{", "res", ".", "push", "(", "t", ")", ";", "}", "else", "{", "idx", "=", "~", "~", "(", "(", "cnt", "+", "1", ")", "*", "random", "(", ")", ")", ";", "if", "(", "idx", "<", "res", ".", "length", "&&", "idx", ">=", "cap", ")", "{", "p", "=", "res", "[", "idx", "]", ";", "if", "(", "map", "[", "tupleid", "(", "p", ")", "]", ")", "out", ".", "rem", ".", "push", "(", "p", ")", ";", "// eviction", "res", "[", "idx", "]", "=", "t", ";", "}", "}", "++", "cnt", ";", "}" ]
sample reservoir update function
[ "sample", "reservoir", "update", "function" ]
0f7049cc73ec67630a487aa916119769073d5a87
https://github.com/vega/vega-transforms/blob/0f7049cc73ec67630a487aa916119769073d5a87/src/Sample.js#L40-L54
42,070
odopod/code-library
utils/get-class-name.js
toPascalCase
function toPascalCase(name) { return name.charAt(0).toUpperCase() + name.replace(/-(.)?/g, (match, c) => c.toUpperCase()).slice(1); }
javascript
function toPascalCase(name) { return name.charAt(0).toUpperCase() + name.replace(/-(.)?/g, (match, c) => c.toUpperCase()).slice(1); }
[ "function", "toPascalCase", "(", "name", ")", "{", "return", "name", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "name", ".", "replace", "(", "/", "-(.)?", "/", "g", ",", "(", "match", ",", "c", ")", "=>", "c", ".", "toUpperCase", "(", ")", ")", ".", "slice", "(", "1", ")", ";", "}" ]
Transforms kabeb-case string to PascalCase
[ "Transforms", "kabeb", "-", "case", "string", "to", "PascalCase" ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/utils/get-class-name.js#L4-L6
42,071
odopod/code-library
packages/odo-tabs/dist/odo-tabs.js
TabsEvent
function TabsEvent(type, index) { classCallCheck(this, TabsEvent); this.type = type; /** @type {number} */ this.index = index; /** @type {boolean} Whether `preventDefault` has been called. */ this.defaultPrevented = false; }
javascript
function TabsEvent(type, index) { classCallCheck(this, TabsEvent); this.type = type; /** @type {number} */ this.index = index; /** @type {boolean} Whether `preventDefault` has been called. */ this.defaultPrevented = false; }
[ "function", "TabsEvent", "(", "type", ",", "index", ")", "{", "classCallCheck", "(", "this", ",", "TabsEvent", ")", ";", "this", ".", "type", "=", "type", ";", "/** @type {number} */", "this", ".", "index", "=", "index", ";", "/** @type {boolean} Whether `preventDefault` has been called. */", "this", ".", "defaultPrevented", "=", "false", ";", "}" ]
Object representing a tab event. @param {string} type Event type. @param {number} index Index of tab. @constructor
[ "Object", "representing", "a", "tab", "event", "." ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/packages/odo-tabs/dist/odo-tabs.js#L47-L57
42,072
odopod/code-library
packages/odo-tabs/dist/odo-tabs.js
Tabs
function Tabs(element) { classCallCheck(this, Tabs); /** @type {Element} */ var _this = possibleConstructorReturn(this, _TinyEmitter.call(this)); _this.element = element; /** @private {number} */ _this._selectedIndex = -1; /** * List items, children of the tabs list. * @type {Array.<Element>} */ _this.tabs = Array.from(_this.element.children); /** * Anchor elements inside the tab. * @type {Array.<HTMLAnchorElement>} */ _this.anchors = _this.tabs.map(function (tab) { return tab.querySelector('a'); }); /** * Tab pane elements. * @type {Array.<HTMLElement>} */ _this.panes = _this.anchors.map(function (anchor) { return document.getElementById(anchor.getAttribute('href').substring(1)); }); /** * Wrapper for the panes. * @type {HTMLElement} */ _this.panesContainer = _this.panes[0].parentElement; /** * Get an array of [possible] hashes. * @type {Array.<?string>} */ _this.hashes = _this.anchors.map(function (anchor) { return anchor.getAttribute('data-hash'); }); _this.init(); return _this; }
javascript
function Tabs(element) { classCallCheck(this, Tabs); /** @type {Element} */ var _this = possibleConstructorReturn(this, _TinyEmitter.call(this)); _this.element = element; /** @private {number} */ _this._selectedIndex = -1; /** * List items, children of the tabs list. * @type {Array.<Element>} */ _this.tabs = Array.from(_this.element.children); /** * Anchor elements inside the tab. * @type {Array.<HTMLAnchorElement>} */ _this.anchors = _this.tabs.map(function (tab) { return tab.querySelector('a'); }); /** * Tab pane elements. * @type {Array.<HTMLElement>} */ _this.panes = _this.anchors.map(function (anchor) { return document.getElementById(anchor.getAttribute('href').substring(1)); }); /** * Wrapper for the panes. * @type {HTMLElement} */ _this.panesContainer = _this.panes[0].parentElement; /** * Get an array of [possible] hashes. * @type {Array.<?string>} */ _this.hashes = _this.anchors.map(function (anchor) { return anchor.getAttribute('data-hash'); }); _this.init(); return _this; }
[ "function", "Tabs", "(", "element", ")", "{", "classCallCheck", "(", "this", ",", "Tabs", ")", ";", "/** @type {Element} */", "var", "_this", "=", "possibleConstructorReturn", "(", "this", ",", "_TinyEmitter", ".", "call", "(", "this", ")", ")", ";", "_this", ".", "element", "=", "element", ";", "/** @private {number} */", "_this", ".", "_selectedIndex", "=", "-", "1", ";", "/**\n * List items, children of the tabs list.\n * @type {Array.<Element>}\n */", "_this", ".", "tabs", "=", "Array", ".", "from", "(", "_this", ".", "element", ".", "children", ")", ";", "/**\n * Anchor elements inside the tab.\n * @type {Array.<HTMLAnchorElement>}\n */", "_this", ".", "anchors", "=", "_this", ".", "tabs", ".", "map", "(", "function", "(", "tab", ")", "{", "return", "tab", ".", "querySelector", "(", "'a'", ")", ";", "}", ")", ";", "/**\n * Tab pane elements.\n * @type {Array.<HTMLElement>}\n */", "_this", ".", "panes", "=", "_this", ".", "anchors", ".", "map", "(", "function", "(", "anchor", ")", "{", "return", "document", ".", "getElementById", "(", "anchor", ".", "getAttribute", "(", "'href'", ")", ".", "substring", "(", "1", ")", ")", ";", "}", ")", ";", "/**\n * Wrapper for the panes.\n * @type {HTMLElement}\n */", "_this", ".", "panesContainer", "=", "_this", ".", "panes", "[", "0", "]", ".", "parentElement", ";", "/**\n * Get an array of [possible] hashes.\n * @type {Array.<?string>}\n */", "_this", ".", "hashes", "=", "_this", ".", "anchors", ".", "map", "(", "function", "(", "anchor", ")", "{", "return", "anchor", ".", "getAttribute", "(", "'data-hash'", ")", ";", "}", ")", ";", "_this", ".", "init", "(", ")", ";", "return", "_this", ";", "}" ]
A tabs component. @param {Element} element The tabs list element. @constructor
[ "A", "tabs", "component", "." ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/packages/odo-tabs/dist/odo-tabs.js#L91-L140
42,073
odopod/code-library
packages/odo-expandable/dist/odo-expandable.js
initializeAll
function initializeAll() { var elements = Array.from(document.querySelectorAll('[' + Settings.Attribute.TRIGGER + ']')); var singleInstances = []; var groupInstances = []; var groupIds = []; elements.forEach(function (item) { var groupId = item.getAttribute(Settings.Attribute.GROUP); if (groupId) { if (!groupIds.includes(groupId)) { var group = elements.filter(function (el) { return el.getAttribute(Settings.Attribute.GROUP) === groupId; }); var isAnimated = group.some(function (el) { return el.hasAttribute(Settings.Attribute.ANIMATED); }); groupInstances.push(isAnimated ? new ExpandableAccordion(group) : new ExpandableGroup(group)); groupIds.push(groupId); } } else { singleInstances.push(new ExpandableItem(item.getAttribute(Settings.Attribute.TRIGGER))); } }); return singleInstances.concat(groupInstances); }
javascript
function initializeAll() { var elements = Array.from(document.querySelectorAll('[' + Settings.Attribute.TRIGGER + ']')); var singleInstances = []; var groupInstances = []; var groupIds = []; elements.forEach(function (item) { var groupId = item.getAttribute(Settings.Attribute.GROUP); if (groupId) { if (!groupIds.includes(groupId)) { var group = elements.filter(function (el) { return el.getAttribute(Settings.Attribute.GROUP) === groupId; }); var isAnimated = group.some(function (el) { return el.hasAttribute(Settings.Attribute.ANIMATED); }); groupInstances.push(isAnimated ? new ExpandableAccordion(group) : new ExpandableGroup(group)); groupIds.push(groupId); } } else { singleInstances.push(new ExpandableItem(item.getAttribute(Settings.Attribute.TRIGGER))); } }); return singleInstances.concat(groupInstances); }
[ "function", "initializeAll", "(", ")", "{", "var", "elements", "=", "Array", ".", "from", "(", "document", ".", "querySelectorAll", "(", "'['", "+", "Settings", ".", "Attribute", ".", "TRIGGER", "+", "']'", ")", ")", ";", "var", "singleInstances", "=", "[", "]", ";", "var", "groupInstances", "=", "[", "]", ";", "var", "groupIds", "=", "[", "]", ";", "elements", ".", "forEach", "(", "function", "(", "item", ")", "{", "var", "groupId", "=", "item", ".", "getAttribute", "(", "Settings", ".", "Attribute", ".", "GROUP", ")", ";", "if", "(", "groupId", ")", "{", "if", "(", "!", "groupIds", ".", "includes", "(", "groupId", ")", ")", "{", "var", "group", "=", "elements", ".", "filter", "(", "function", "(", "el", ")", "{", "return", "el", ".", "getAttribute", "(", "Settings", ".", "Attribute", ".", "GROUP", ")", "===", "groupId", ";", "}", ")", ";", "var", "isAnimated", "=", "group", ".", "some", "(", "function", "(", "el", ")", "{", "return", "el", ".", "hasAttribute", "(", "Settings", ".", "Attribute", ".", "ANIMATED", ")", ";", "}", ")", ";", "groupInstances", ".", "push", "(", "isAnimated", "?", "new", "ExpandableAccordion", "(", "group", ")", ":", "new", "ExpandableGroup", "(", "group", ")", ")", ";", "groupIds", ".", "push", "(", "groupId", ")", ";", "}", "}", "else", "{", "singleInstances", ".", "push", "(", "new", "ExpandableItem", "(", "item", ".", "getAttribute", "(", "Settings", ".", "Attribute", ".", "TRIGGER", ")", ")", ")", ";", "}", "}", ")", ";", "return", "singleInstances", ".", "concat", "(", "groupInstances", ")", ";", "}" ]
Instantiates all instances of the expandable. Groups are instantiated separate from Expandables and require different parameters. This helper chunks out and groups the grouped expandables before instantiating all of them. @return {Array.<ExpandableItem|ExpandableGroup|ExpandableAccordion>} all instances of both types. @public
[ "Instantiates", "all", "instances", "of", "the", "expandable", ".", "Groups", "are", "instantiated", "separate", "from", "Expandables", "and", "require", "different", "parameters", ".", "This", "helper", "chunks", "out", "and", "groups", "the", "grouped", "expandables", "before", "instantiating", "all", "of", "them", "." ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/packages/odo-expandable/dist/odo-expandable.js#L450-L476
42,074
odopod/code-library
packages/odo-module/src/module.js
getSelector
function getSelector(Module, selector) { // Verify that a base selector is defined. if (typeof selector === 'undefined') { if (Module.Selectors && Module.Selectors.BASE) { return Module.Selectors.BASE; } // Support both `ClassName` and `Classes` enumerations. const classes = Module.ClassName || Module.Classes; if (classes && classes.BASE) { return '.' + classes.BASE; } throw new TypeError('A base selector for this module must be specified.'); } return selector; }
javascript
function getSelector(Module, selector) { // Verify that a base selector is defined. if (typeof selector === 'undefined') { if (Module.Selectors && Module.Selectors.BASE) { return Module.Selectors.BASE; } // Support both `ClassName` and `Classes` enumerations. const classes = Module.ClassName || Module.Classes; if (classes && classes.BASE) { return '.' + classes.BASE; } throw new TypeError('A base selector for this module must be specified.'); } return selector; }
[ "function", "getSelector", "(", "Module", ",", "selector", ")", "{", "// Verify that a base selector is defined.", "if", "(", "typeof", "selector", "===", "'undefined'", ")", "{", "if", "(", "Module", ".", "Selectors", "&&", "Module", ".", "Selectors", ".", "BASE", ")", "{", "return", "Module", ".", "Selectors", ".", "BASE", ";", "}", "// Support both `ClassName` and `Classes` enumerations.", "const", "classes", "=", "Module", ".", "ClassName", "||", "Module", ".", "Classes", ";", "if", "(", "classes", "&&", "classes", ".", "BASE", ")", "{", "return", "'.'", "+", "classes", ".", "BASE", ";", "}", "throw", "new", "TypeError", "(", "'A base selector for this module must be specified.'", ")", ";", "}", "return", "selector", ";", "}" ]
Determine the base selector for this module. @param {Object} Module @param {string} [selector] @return {string} Updated selector string. @throws {TypeError} If the selector cannot be determined.
[ "Determine", "the", "base", "selector", "for", "this", "module", "." ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/packages/odo-module/src/module.js#L26-L43
42,075
odopod/code-library
packages/odo-module/src/module.js
validate
function validate(Module, selector) { // Verify that the Module is an Object or Class. const type = Object.prototype.toString.call(Module); const isObject = type === '[object Object]'; const isFunction = type === '[object Function]'; if (!(isObject || isFunction)) { throw new TypeError(`Module must be an Function (class) or Object. Got "${Object.prototype.toString.call(Module)}".`); } // Verify that the module has not yet been registered. if (store.has(selector)) { throw new TypeError('The base selector for this module has already been registered. Please use a unique base selector.'); } }
javascript
function validate(Module, selector) { // Verify that the Module is an Object or Class. const type = Object.prototype.toString.call(Module); const isObject = type === '[object Object]'; const isFunction = type === '[object Function]'; if (!(isObject || isFunction)) { throw new TypeError(`Module must be an Function (class) or Object. Got "${Object.prototype.toString.call(Module)}".`); } // Verify that the module has not yet been registered. if (store.has(selector)) { throw new TypeError('The base selector for this module has already been registered. Please use a unique base selector.'); } }
[ "function", "validate", "(", "Module", ",", "selector", ")", "{", "// Verify that the Module is an Object or Class.", "const", "type", "=", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "Module", ")", ";", "const", "isObject", "=", "type", "===", "'[object Object]'", ";", "const", "isFunction", "=", "type", "===", "'[object Function]'", ";", "if", "(", "!", "(", "isObject", "||", "isFunction", ")", ")", "{", "throw", "new", "TypeError", "(", "`", "${", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "Module", ")", "}", "`", ")", ";", "}", "// Verify that the module has not yet been registered.", "if", "(", "store", ".", "has", "(", "selector", ")", ")", "{", "throw", "new", "TypeError", "(", "'The base selector for this module has already been registered. Please use a unique base selector.'", ")", ";", "}", "}" ]
Ensure all required properties exist. @param {Object} Module @param {string} [selector] @throws {TypeError} When something is missing. @private
[ "Ensure", "all", "required", "properties", "exist", "." ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/packages/odo-module/src/module.js#L52-L65
42,076
odopod/code-library
packages/odo-module/src/module.js
register
function register(Module, selector) { const _selector = getSelector(Module, selector); validate(Module, _selector); const methods = OdoModuleMethods(Module, _selector); // Apply OdoModule static methods. Object.keys(methods).forEach((method) => { Module[method] = methods[method]; }); // Apply the OdoModule static property. Module.Instances = new Map(); // Internally register the module. store.set(_selector, Module); return Module; }
javascript
function register(Module, selector) { const _selector = getSelector(Module, selector); validate(Module, _selector); const methods = OdoModuleMethods(Module, _selector); // Apply OdoModule static methods. Object.keys(methods).forEach((method) => { Module[method] = methods[method]; }); // Apply the OdoModule static property. Module.Instances = new Map(); // Internally register the module. store.set(_selector, Module); return Module; }
[ "function", "register", "(", "Module", ",", "selector", ")", "{", "const", "_selector", "=", "getSelector", "(", "Module", ",", "selector", ")", ";", "validate", "(", "Module", ",", "_selector", ")", ";", "const", "methods", "=", "OdoModuleMethods", "(", "Module", ",", "_selector", ")", ";", "// Apply OdoModule static methods.", "Object", ".", "keys", "(", "methods", ")", ".", "forEach", "(", "(", "method", ")", "=>", "{", "Module", "[", "method", "]", "=", "methods", "[", "method", "]", ";", "}", ")", ";", "// Apply the OdoModule static property.", "Module", ".", "Instances", "=", "new", "Map", "(", ")", ";", "// Internally register the module.", "store", ".", "set", "(", "_selector", ",", "Module", ")", ";", "return", "Module", ";", "}" ]
Adds static methods and internally registers the module. @param {Object} Module @param {string} [selector] @return {Object} The module.
[ "Adds", "static", "methods", "and", "internally", "registers", "the", "module", "." ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/packages/odo-module/src/module.js#L73-L92
42,077
odopod/code-library
packages/odo-dual-viewer/dist/odo-dual-viewer.js
DualViewer
function DualViewer(el, opts) { classCallCheck(this, DualViewer); var _this = possibleConstructorReturn(this, _TinyEmitter.call(this)); _this.element = el; _this.options = Object.assign({}, DualViewer.Defaults, opts); _this._isVertical = _this.options.isVertical; /** @private {Element} */ _this._scrubberEl = null; /** @private {Element} */ _this._overlayEl = null; /** @private {Element} */ _this._underlayEl = null; /** @private {Element} */ _this._overlayObjectEl = null; /** * Dragger component * @type {OdoDraggable} * @private */ _this._draggable = null; /** * Boundary for the scrubber. * @type {Rect} * @private */ _this._scrubberLimits = null; /** * The axis to drag depends on the carousel direction. * @type {OdoPointer.Axis} * @private */ _this._dragAxis = _this._isVertical ? 'y' : 'x'; /** * Height or width. * @type {string} * @private */ _this._dimensionAttr = _this._isVertical ? 'height' : 'width'; /** * Previous percentage revealed. Needed for window resizes to reset back to * correct position. * @type {number} * @private */ _this._previousPercent = _this.options.startPosition; /** * Current position of the dual viewer. * @type {number} * @private */ _this._position = DualViewer.Position.CENTER; /** @private {boolean} */ _this._isResting = true; _this.decorate(); return _this; }
javascript
function DualViewer(el, opts) { classCallCheck(this, DualViewer); var _this = possibleConstructorReturn(this, _TinyEmitter.call(this)); _this.element = el; _this.options = Object.assign({}, DualViewer.Defaults, opts); _this._isVertical = _this.options.isVertical; /** @private {Element} */ _this._scrubberEl = null; /** @private {Element} */ _this._overlayEl = null; /** @private {Element} */ _this._underlayEl = null; /** @private {Element} */ _this._overlayObjectEl = null; /** * Dragger component * @type {OdoDraggable} * @private */ _this._draggable = null; /** * Boundary for the scrubber. * @type {Rect} * @private */ _this._scrubberLimits = null; /** * The axis to drag depends on the carousel direction. * @type {OdoPointer.Axis} * @private */ _this._dragAxis = _this._isVertical ? 'y' : 'x'; /** * Height or width. * @type {string} * @private */ _this._dimensionAttr = _this._isVertical ? 'height' : 'width'; /** * Previous percentage revealed. Needed for window resizes to reset back to * correct position. * @type {number} * @private */ _this._previousPercent = _this.options.startPosition; /** * Current position of the dual viewer. * @type {number} * @private */ _this._position = DualViewer.Position.CENTER; /** @private {boolean} */ _this._isResting = true; _this.decorate(); return _this; }
[ "function", "DualViewer", "(", "el", ",", "opts", ")", "{", "classCallCheck", "(", "this", ",", "DualViewer", ")", ";", "var", "_this", "=", "possibleConstructorReturn", "(", "this", ",", "_TinyEmitter", ".", "call", "(", "this", ")", ")", ";", "_this", ".", "element", "=", "el", ";", "_this", ".", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "DualViewer", ".", "Defaults", ",", "opts", ")", ";", "_this", ".", "_isVertical", "=", "_this", ".", "options", ".", "isVertical", ";", "/** @private {Element} */", "_this", ".", "_scrubberEl", "=", "null", ";", "/** @private {Element} */", "_this", ".", "_overlayEl", "=", "null", ";", "/** @private {Element} */", "_this", ".", "_underlayEl", "=", "null", ";", "/** @private {Element} */", "_this", ".", "_overlayObjectEl", "=", "null", ";", "/**\n * Dragger component\n * @type {OdoDraggable}\n * @private\n */", "_this", ".", "_draggable", "=", "null", ";", "/**\n * Boundary for the scrubber.\n * @type {Rect}\n * @private\n */", "_this", ".", "_scrubberLimits", "=", "null", ";", "/**\n * The axis to drag depends on the carousel direction.\n * @type {OdoPointer.Axis}\n * @private\n */", "_this", ".", "_dragAxis", "=", "_this", ".", "_isVertical", "?", "'y'", ":", "'x'", ";", "/**\n * Height or width.\n * @type {string}\n * @private\n */", "_this", ".", "_dimensionAttr", "=", "_this", ".", "_isVertical", "?", "'height'", ":", "'width'", ";", "/**\n * Previous percentage revealed. Needed for window resizes to reset back to\n * correct position.\n * @type {number}\n * @private\n */", "_this", ".", "_previousPercent", "=", "_this", ".", "options", ".", "startPosition", ";", "/**\n * Current position of the dual viewer.\n * @type {number}\n * @private\n */", "_this", ".", "_position", "=", "DualViewer", ".", "Position", ".", "CENTER", ";", "/** @private {boolean} */", "_this", ".", "_isResting", "=", "true", ";", "_this", ".", "decorate", "(", ")", ";", "return", "_this", ";", "}" ]
Component which has a draggable element in the middle which reveals one or the other sides as the user drags. @constructor
[ "Component", "which", "has", "a", "draggable", "element", "in", "the", "middle", "which", "reveals", "one", "or", "the", "other", "sides", "as", "the", "user", "drags", "." ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/packages/odo-dual-viewer/dist/odo-dual-viewer.js#L89-L160
42,078
odopod/code-library
packages/odo-responsive-images/dist/odo-responsive-images.js
arrayify
function arrayify(thing) { if (Array.isArray(thing)) { return thing; } if (thing && typeof thing.length === 'number') { return Array.from(thing); } return [thing]; }
javascript
function arrayify(thing) { if (Array.isArray(thing)) { return thing; } if (thing && typeof thing.length === 'number') { return Array.from(thing); } return [thing]; }
[ "function", "arrayify", "(", "thing", ")", "{", "if", "(", "Array", ".", "isArray", "(", "thing", ")", ")", "{", "return", "thing", ";", "}", "if", "(", "thing", "&&", "typeof", "thing", ".", "length", "===", "'number'", ")", "{", "return", "Array", ".", "from", "(", "thing", ")", ";", "}", "return", "[", "thing", "]", ";", "}" ]
If the first parameter is not an array, return an array containing the first parameter. @param {*} thing Anything. @return {Array.<*>} Array of things.
[ "If", "the", "first", "parameter", "is", "not", "an", "array", "return", "an", "array", "containing", "the", "first", "parameter", "." ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/packages/odo-responsive-images/dist/odo-responsive-images.js#L88-L98
42,079
odopod/code-library
docs/odo-scroll-feedback/scripts/demo.js
scrollToIndex
function scrollToIndex(index) { var duration = 400; var start = window.pageYOffset; var end = index * window.innerHeight; var amount = end - start; var startTime = +new Date(); var easing = function easing(k) { return -0.5 * (Math.cos(Math.PI * k) - 1); }; var step = function step(value /* , percent */) { window.scrollTo(0, value); }; var complete = function complete() { isScrolling = false; }; var looper = function looper() { var now = +new Date(); var remainingTime = startTime + duration - now; var percent = 1 - (remainingTime / duration || 0); // Abort if already past 100%. if (percent >= 1) { // Make sure it always finishes with 1. step(end, 1); complete(); return; } // Apply easing. percent = easing(percent); // Tick. step(start + amount * percent, percent); // Request animation frame. requestAnimationFrame(looper); }; isScrolling = true; requestAnimationFrame(looper); }
javascript
function scrollToIndex(index) { var duration = 400; var start = window.pageYOffset; var end = index * window.innerHeight; var amount = end - start; var startTime = +new Date(); var easing = function easing(k) { return -0.5 * (Math.cos(Math.PI * k) - 1); }; var step = function step(value /* , percent */) { window.scrollTo(0, value); }; var complete = function complete() { isScrolling = false; }; var looper = function looper() { var now = +new Date(); var remainingTime = startTime + duration - now; var percent = 1 - (remainingTime / duration || 0); // Abort if already past 100%. if (percent >= 1) { // Make sure it always finishes with 1. step(end, 1); complete(); return; } // Apply easing. percent = easing(percent); // Tick. step(start + amount * percent, percent); // Request animation frame. requestAnimationFrame(looper); }; isScrolling = true; requestAnimationFrame(looper); }
[ "function", "scrollToIndex", "(", "index", ")", "{", "var", "duration", "=", "400", ";", "var", "start", "=", "window", ".", "pageYOffset", ";", "var", "end", "=", "index", "*", "window", ".", "innerHeight", ";", "var", "amount", "=", "end", "-", "start", ";", "var", "startTime", "=", "+", "new", "Date", "(", ")", ";", "var", "easing", "=", "function", "easing", "(", "k", ")", "{", "return", "-", "0.5", "*", "(", "Math", ".", "cos", "(", "Math", ".", "PI", "*", "k", ")", "-", "1", ")", ";", "}", ";", "var", "step", "=", "function", "step", "(", "value", "/* , percent */", ")", "{", "window", ".", "scrollTo", "(", "0", ",", "value", ")", ";", "}", ";", "var", "complete", "=", "function", "complete", "(", ")", "{", "isScrolling", "=", "false", ";", "}", ";", "var", "looper", "=", "function", "looper", "(", ")", "{", "var", "now", "=", "+", "new", "Date", "(", ")", ";", "var", "remainingTime", "=", "startTime", "+", "duration", "-", "now", ";", "var", "percent", "=", "1", "-", "(", "remainingTime", "/", "duration", "||", "0", ")", ";", "// Abort if already past 100%.", "if", "(", "percent", ">=", "1", ")", "{", "// Make sure it always finishes with 1.", "step", "(", "end", ",", "1", ")", ";", "complete", "(", ")", ";", "return", ";", "}", "// Apply easing.", "percent", "=", "easing", "(", "percent", ")", ";", "// Tick.", "step", "(", "start", "+", "amount", "*", "percent", ",", "percent", ")", ";", "// Request animation frame.", "requestAnimationFrame", "(", "looper", ")", ";", "}", ";", "isScrolling", "=", "true", ";", "requestAnimationFrame", "(", "looper", ")", ";", "}" ]
Animate scrolling the page - without jQuery. Code adapted from DualViewer's stepper.js
[ "Animate", "scrolling", "the", "page", "-", "without", "jQuery", ".", "Code", "adapted", "from", "DualViewer", "s", "stepper", ".", "js" ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/docs/odo-scroll-feedback/scripts/demo.js#L13-L57
42,080
odopod/code-library
docs/odo-scroll-feedback/scripts/demo.js
getHueDifference
function getHueDifference(value) { return hues.reduce(function (min, hue) { var diff = Math.abs(hue - value); if (diff < min) { return diff; } return min; }, Infinity); }
javascript
function getHueDifference(value) { return hues.reduce(function (min, hue) { var diff = Math.abs(hue - value); if (diff < min) { return diff; } return min; }, Infinity); }
[ "function", "getHueDifference", "(", "value", ")", "{", "return", "hues", ".", "reduce", "(", "function", "(", "min", ",", "hue", ")", "{", "var", "diff", "=", "Math", ".", "abs", "(", "hue", "-", "value", ")", ";", "if", "(", "diff", "<", "min", ")", "{", "return", "diff", ";", "}", "return", "min", ";", "}", ",", "Infinity", ")", ";", "}" ]
Returns the hue with the smallest difference.
[ "Returns", "the", "hue", "with", "the", "smallest", "difference", "." ]
ceb47654545ec0b734c8650b3128a6c07504845a
https://github.com/odopod/code-library/blob/ceb47654545ec0b734c8650b3128a6c07504845a/docs/odo-scroll-feedback/scripts/demo.js#L95-L103
42,081
vega/vega-transforms
src/Window.js
adjustRange
function adjustRange(w, bisect) { var r0 = w.i0, r1 = w.i1 - 1, c = w.compare, d = w.data, n = d.length - 1; if (r0 > 0 && !c(d[r0], d[r0-1])) w.i0 = bisect.left(d, d[r0]); if (r1 < n && !c(d[r1], d[r1+1])) w.i1 = bisect.right(d, d[r1]); }
javascript
function adjustRange(w, bisect) { var r0 = w.i0, r1 = w.i1 - 1, c = w.compare, d = w.data, n = d.length - 1; if (r0 > 0 && !c(d[r0], d[r0-1])) w.i0 = bisect.left(d, d[r0]); if (r1 < n && !c(d[r1], d[r1+1])) w.i1 = bisect.right(d, d[r1]); }
[ "function", "adjustRange", "(", "w", ",", "bisect", ")", "{", "var", "r0", "=", "w", ".", "i0", ",", "r1", "=", "w", ".", "i1", "-", "1", ",", "c", "=", "w", ".", "compare", ",", "d", "=", "w", ".", "data", ",", "n", "=", "d", ".", "length", "-", "1", ";", "if", "(", "r0", ">", "0", "&&", "!", "c", "(", "d", "[", "r0", "]", ",", "d", "[", "r0", "-", "1", "]", ")", ")", "w", ".", "i0", "=", "bisect", ".", "left", "(", "d", ",", "d", "[", "r0", "]", ")", ";", "if", "(", "r1", "<", "n", "&&", "!", "c", "(", "d", "[", "r1", "]", ",", "d", "[", "r1", "+", "1", "]", ")", ")", "w", ".", "i1", "=", "bisect", ".", "right", "(", "d", ",", "d", "[", "r1", "]", ")", ";", "}" ]
if frame type is 'range', adjust window for peer values
[ "if", "frame", "type", "is", "range", "adjust", "window", "for", "peer", "values" ]
0f7049cc73ec67630a487aa916119769073d5a87
https://github.com/vega/vega-transforms/blob/0f7049cc73ec67630a487aa916119769073d5a87/src/Window.js#L132-L141
42,082
pbeshai/react-taco-table
lib/Formatters.js
makePlusMinus
function makePlusMinus(formatter) { return function plusMinusWrapped(value) { if (value != null && value > 0) { return '+' + formatter(value); } return formatter(value); }; }
javascript
function makePlusMinus(formatter) { return function plusMinusWrapped(value) { if (value != null && value > 0) { return '+' + formatter(value); } return formatter(value); }; }
[ "function", "makePlusMinus", "(", "formatter", ")", "{", "return", "function", "plusMinusWrapped", "(", "value", ")", "{", "if", "(", "value", "!=", "null", "&&", "value", ">", "0", ")", "{", "return", "'+'", "+", "formatter", "(", "value", ")", ";", "}", "return", "formatter", "(", "value", ")", ";", "}", ";", "}" ]
Wraps a formatting function and puts a + in front of formatted value if it is positive. @param {Function} formatter formatter function @return {Function} a formatter function
[ "Wraps", "a", "formatting", "function", "and", "puts", "a", "+", "in", "front", "of", "formatted", "value", "if", "it", "is", "positive", "." ]
db059ad7d051aefbaf00aea7f7a870e59711968a
https://github.com/pbeshai/react-taco-table/blob/db059ad7d051aefbaf00aea7f7a870e59711968a/lib/Formatters.js#L68-L76
42,083
pbeshai/react-taco-table
lib/Formatters.js
makePercent
function makePercent(formatter) { return function percentWrapped(value) { if (value != null) { return formatter(value * 100) + '%'; } return formatter(value); }; }
javascript
function makePercent(formatter) { return function percentWrapped(value) { if (value != null) { return formatter(value * 100) + '%'; } return formatter(value); }; }
[ "function", "makePercent", "(", "formatter", ")", "{", "return", "function", "percentWrapped", "(", "value", ")", "{", "if", "(", "value", "!=", "null", ")", "{", "return", "formatter", "(", "value", "*", "100", ")", "+", "'%'", ";", "}", "return", "formatter", "(", "value", ")", ";", "}", ";", "}" ]
Wraps a formatting function by multiplying the value by 100 and adds a % to the end. @param {Function} formatter formatter function @return {Function} a formatter function
[ "Wraps", "a", "formatting", "function", "by", "multiplying", "the", "value", "by", "100", "and", "adds", "a", "%", "to", "the", "end", "." ]
db059ad7d051aefbaf00aea7f7a870e59711968a
https://github.com/pbeshai/react-taco-table/blob/db059ad7d051aefbaf00aea7f7a870e59711968a/lib/Formatters.js#L85-L93
42,084
nayrnet/node-domoticz-mqtt
domoticz.js
function(options) { events.EventEmitter.call(this); // inherit from EventEmitter TRACE = options.log; IDX = options.idx; STATUS = options.status; HOST = options.host; REQUEST = options.request; this.domoMQTT = this.connect(HOST); }
javascript
function(options) { events.EventEmitter.call(this); // inherit from EventEmitter TRACE = options.log; IDX = options.idx; STATUS = options.status; HOST = options.host; REQUEST = options.request; this.domoMQTT = this.connect(HOST); }
[ "function", "(", "options", ")", "{", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "// inherit from EventEmitter", "TRACE", "=", "options", ".", "log", ";", "IDX", "=", "options", ".", "idx", ";", "STATUS", "=", "options", ".", "status", ";", "HOST", "=", "options", ".", "host", ";", "REQUEST", "=", "options", ".", "request", ";", "this", ".", "domoMQTT", "=", "this", ".", "connect", "(", "HOST", ")", ";", "}" ]
Device IDX you want to watch. Get Options
[ "Device", "IDX", "you", "want", "to", "watch", ".", "Get", "Options" ]
14922c6470cc8eca073bd2d297f3b77ce285ac7d
https://github.com/nayrnet/node-domoticz-mqtt/blob/14922c6470cc8eca073bd2d297f3b77ce285ac7d/domoticz.js#L14-L22
42,085
enyojs/onyx
src/MoreToolbar/MoreToolbar.js
function () { var c = this.findCollapsibleItem(); if (c) { //apply movedClass is needed if(this.movedClass && this.movedClass.length > 0 && !c.hasClass(this.movedClass)) { c.addClass(this.movedClass); } // passing null to add child to the front of the control list this.$.menu.addChild(c, null); var p = this.$.menu.hasNode(); if (p && c.hasNode()) { c.insertNodeInParent(p); } return true; } }
javascript
function () { var c = this.findCollapsibleItem(); if (c) { //apply movedClass is needed if(this.movedClass && this.movedClass.length > 0 && !c.hasClass(this.movedClass)) { c.addClass(this.movedClass); } // passing null to add child to the front of the control list this.$.menu.addChild(c, null); var p = this.$.menu.hasNode(); if (p && c.hasNode()) { c.insertNodeInParent(p); } return true; } }
[ "function", "(", ")", "{", "var", "c", "=", "this", ".", "findCollapsibleItem", "(", ")", ";", "if", "(", "c", ")", "{", "//apply movedClass is needed", "if", "(", "this", ".", "movedClass", "&&", "this", ".", "movedClass", ".", "length", ">", "0", "&&", "!", "c", ".", "hasClass", "(", "this", ".", "movedClass", ")", ")", "{", "c", ".", "addClass", "(", "this", ".", "movedClass", ")", ";", "}", "// passing null to add child to the front of the control list", "this", ".", "$", ".", "menu", ".", "addChild", "(", "c", ",", "null", ")", ";", "var", "p", "=", "this", ".", "$", ".", "menu", ".", "hasNode", "(", ")", ";", "if", "(", "p", "&&", "c", ".", "hasNode", "(", ")", ")", "{", "c", ".", "insertNodeInParent", "(", "p", ")", ";", "}", "return", "true", ";", "}", "}" ]
Removes the next collapsible item from the toolbar and adds it to the menu. @private
[ "Removes", "the", "next", "collapsible", "item", "from", "the", "toolbar", "and", "adds", "it", "to", "the", "menu", "." ]
919ea0da6f05296aa5ca0b5f45f0b439ac4a906a
https://github.com/enyojs/onyx/blob/919ea0da6f05296aa5ca0b5f45f0b439ac4a906a/src/MoreToolbar/MoreToolbar.js#L185-L200
42,086
enyojs/onyx
src/MoreToolbar/MoreToolbar.js
function () { var c$ = this.$.menu.children; var c = c$[0]; if (c) { //remove any applied movedClass if (this.movedClass && this.movedClass.length > 0 && c.hasClass(this.movedClass)) { c.removeClass(this.movedClass); } this.$.client.addChild(c); var p = this.$.client.hasNode(); if (p && c.hasNode()) { var nextChild; var currIndex; for (var i = 0; i < this.$.client.children.length; i++) { var curr = this.$.client.children[i]; if(curr.toolbarIndex !== undefined && curr.toolbarIndex != i) { nextChild = curr; currIndex = i; break; } } if (nextChild && nextChild.hasNode()) { c.insertNodeInParent(p, nextChild.node); var newChild = this.$.client.children.pop(); this.$.client.children.splice(currIndex, 0, newChild); } else { c.appendNodeToParent(p); } } return true; } }
javascript
function () { var c$ = this.$.menu.children; var c = c$[0]; if (c) { //remove any applied movedClass if (this.movedClass && this.movedClass.length > 0 && c.hasClass(this.movedClass)) { c.removeClass(this.movedClass); } this.$.client.addChild(c); var p = this.$.client.hasNode(); if (p && c.hasNode()) { var nextChild; var currIndex; for (var i = 0; i < this.$.client.children.length; i++) { var curr = this.$.client.children[i]; if(curr.toolbarIndex !== undefined && curr.toolbarIndex != i) { nextChild = curr; currIndex = i; break; } } if (nextChild && nextChild.hasNode()) { c.insertNodeInParent(p, nextChild.node); var newChild = this.$.client.children.pop(); this.$.client.children.splice(currIndex, 0, newChild); } else { c.appendNodeToParent(p); } } return true; } }
[ "function", "(", ")", "{", "var", "c$", "=", "this", ".", "$", ".", "menu", ".", "children", ";", "var", "c", "=", "c$", "[", "0", "]", ";", "if", "(", "c", ")", "{", "//remove any applied movedClass", "if", "(", "this", ".", "movedClass", "&&", "this", ".", "movedClass", ".", "length", ">", "0", "&&", "c", ".", "hasClass", "(", "this", ".", "movedClass", ")", ")", "{", "c", ".", "removeClass", "(", "this", ".", "movedClass", ")", ";", "}", "this", ".", "$", ".", "client", ".", "addChild", "(", "c", ")", ";", "var", "p", "=", "this", ".", "$", ".", "client", ".", "hasNode", "(", ")", ";", "if", "(", "p", "&&", "c", ".", "hasNode", "(", ")", ")", "{", "var", "nextChild", ";", "var", "currIndex", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "$", ".", "client", ".", "children", ".", "length", ";", "i", "++", ")", "{", "var", "curr", "=", "this", ".", "$", ".", "client", ".", "children", "[", "i", "]", ";", "if", "(", "curr", ".", "toolbarIndex", "!==", "undefined", "&&", "curr", ".", "toolbarIndex", "!=", "i", ")", "{", "nextChild", "=", "curr", ";", "currIndex", "=", "i", ";", "break", ";", "}", "}", "if", "(", "nextChild", "&&", "nextChild", ".", "hasNode", "(", ")", ")", "{", "c", ".", "insertNodeInParent", "(", "p", ",", "nextChild", ".", "node", ")", ";", "var", "newChild", "=", "this", ".", "$", ".", "client", ".", "children", ".", "pop", "(", ")", ";", "this", ".", "$", ".", "client", ".", "children", ".", "splice", "(", "currIndex", ",", "0", ",", "newChild", ")", ";", "}", "else", "{", "c", ".", "appendNodeToParent", "(", "p", ")", ";", "}", "}", "return", "true", ";", "}", "}" ]
Removes the first child of the menu and adds it back to the toolbar. @private
[ "Removes", "the", "first", "child", "of", "the", "menu", "and", "adds", "it", "back", "to", "the", "toolbar", "." ]
919ea0da6f05296aa5ca0b5f45f0b439ac4a906a
https://github.com/enyojs/onyx/blob/919ea0da6f05296aa5ca0b5f45f0b439ac4a906a/src/MoreToolbar/MoreToolbar.js#L207-L238
42,087
enyojs/onyx
src/MoreToolbar/MoreToolbar.js
function () { if (this.$.client.hasNode()) { var c$ = this.$.client.children; var n = c$.length && c$[c$.length-1].hasNode(); if (n) { this.$.client.reflow(); //Workaround: scrollWidth value not working in Firefox, so manually compute //return (this.$.client.node.scrollWidth > this.$.client.node.clientWidth); return ((n.offsetLeft + n.offsetWidth) > this.$.client.node.clientWidth); } } }
javascript
function () { if (this.$.client.hasNode()) { var c$ = this.$.client.children; var n = c$.length && c$[c$.length-1].hasNode(); if (n) { this.$.client.reflow(); //Workaround: scrollWidth value not working in Firefox, so manually compute //return (this.$.client.node.scrollWidth > this.$.client.node.clientWidth); return ((n.offsetLeft + n.offsetWidth) > this.$.client.node.clientWidth); } } }
[ "function", "(", ")", "{", "if", "(", "this", ".", "$", ".", "client", ".", "hasNode", "(", ")", ")", "{", "var", "c$", "=", "this", ".", "$", ".", "client", ".", "children", ";", "var", "n", "=", "c$", ".", "length", "&&", "c$", "[", "c$", ".", "length", "-", "1", "]", ".", "hasNode", "(", ")", ";", "if", "(", "n", ")", "{", "this", ".", "$", ".", "client", ".", "reflow", "(", ")", ";", "//Workaround: scrollWidth value not working in Firefox, so manually compute", "//return (this.$.client.node.scrollWidth > this.$.client.node.clientWidth);", "return", "(", "(", "n", ".", "offsetLeft", "+", "n", ".", "offsetWidth", ")", ">", "this", ".", "$", ".", "client", ".", "node", ".", "clientWidth", ")", ";", "}", "}", "}" ]
Determines whether the toolbar has content that is not visible. @return {Boolean} `true` if some toolbar content is not visible. @private
[ "Determines", "whether", "the", "toolbar", "has", "content", "that", "is", "not", "visible", "." ]
919ea0da6f05296aa5ca0b5f45f0b439ac4a906a
https://github.com/enyojs/onyx/blob/919ea0da6f05296aa5ca0b5f45f0b439ac4a906a/src/MoreToolbar/MoreToolbar.js#L263-L274
42,088
pbeshai/react-taco-table
src/plugins/HeatmapPlugin.js
tdStyle
function tdStyle(cellData, { columnSummary, column, rowData, isBottomData }) { let domain; let backgroundScale; let colorScale; let colorShift; let colorScheme; let reverseColors; let includeBottomData; // read in from plugin options if (column.plugins && column.plugins.heatmap) { domain = column.plugins.heatmap.domain; backgroundScale = column.plugins.heatmap.backgroundScale; colorScale = column.plugins.heatmap.colorScale; colorShift = column.plugins.heatmap.colorShift; colorScheme = column.plugins.heatmap.colorScheme; reverseColors = column.plugins.heatmap.reverseColors; includeBottomData = column.plugins.heatmap.includeBottomData; } // skip in bottom data area unless this column explicitly says to include it if (isBottomData && !includeBottomData) { return undefined; } // compute the sort value const sortValue = Utils.getSortValueFromCellData(cellData, column, rowData); // do not heatmap null or undefined values if (sortValue == null) { return undefined; } // default domain if not provided comes from columnSummary if (!domain) { // if we didn't get a min/max, just use [0, 1] const colMin = columnSummary.min == null ? 0 : columnSummary.min; const colMax = columnSummary.max == null ? 1 : columnSummary.max; domain = [colMin, colMax]; } // reverse the domain if specified to get the color scheme inverted if (reverseColors) { domain = domain.slice().reverse(); } const domainScale = d3.scaleLinear().domain(domain) .range([0, 1]) .clamp(true); // if a background scale is provided, use it let backgroundColor; if (backgroundScale) { if (backgroundScale.domain) { backgroundScale.domain(domain); } backgroundColor = backgroundScale(sortValue); } // if a color scale is provided, use it let color; if (colorScale) { if (colorScale.domain) { colorScale.domain(domain); } color = colorScale(sortValue); // if a color shift is defined, shift the background color by this amount (0, 1) } else if (backgroundScale && colorShift) { const shiftedValue = domainScale.invert((domainScale(sortValue) + colorShift) % 1); color = backgroundScale(shiftedValue); } // if no background scale and color scale provided, use default - magma if (backgroundScale == null) { colorScheme = colorScheme || defaultColorScheme; backgroundColor = d3[`interpolate${colorScheme}`](domainScale(sortValue)); if (!colorScale) { colorShift = colorShift || 0.5; color = d3[`interpolate${colorScheme}`]((domainScale(sortValue) + colorShift) % 1); } } return { backgroundColor, color, }; }
javascript
function tdStyle(cellData, { columnSummary, column, rowData, isBottomData }) { let domain; let backgroundScale; let colorScale; let colorShift; let colorScheme; let reverseColors; let includeBottomData; // read in from plugin options if (column.plugins && column.plugins.heatmap) { domain = column.plugins.heatmap.domain; backgroundScale = column.plugins.heatmap.backgroundScale; colorScale = column.plugins.heatmap.colorScale; colorShift = column.plugins.heatmap.colorShift; colorScheme = column.plugins.heatmap.colorScheme; reverseColors = column.plugins.heatmap.reverseColors; includeBottomData = column.plugins.heatmap.includeBottomData; } // skip in bottom data area unless this column explicitly says to include it if (isBottomData && !includeBottomData) { return undefined; } // compute the sort value const sortValue = Utils.getSortValueFromCellData(cellData, column, rowData); // do not heatmap null or undefined values if (sortValue == null) { return undefined; } // default domain if not provided comes from columnSummary if (!domain) { // if we didn't get a min/max, just use [0, 1] const colMin = columnSummary.min == null ? 0 : columnSummary.min; const colMax = columnSummary.max == null ? 1 : columnSummary.max; domain = [colMin, colMax]; } // reverse the domain if specified to get the color scheme inverted if (reverseColors) { domain = domain.slice().reverse(); } const domainScale = d3.scaleLinear().domain(domain) .range([0, 1]) .clamp(true); // if a background scale is provided, use it let backgroundColor; if (backgroundScale) { if (backgroundScale.domain) { backgroundScale.domain(domain); } backgroundColor = backgroundScale(sortValue); } // if a color scale is provided, use it let color; if (colorScale) { if (colorScale.domain) { colorScale.domain(domain); } color = colorScale(sortValue); // if a color shift is defined, shift the background color by this amount (0, 1) } else if (backgroundScale && colorShift) { const shiftedValue = domainScale.invert((domainScale(sortValue) + colorShift) % 1); color = backgroundScale(shiftedValue); } // if no background scale and color scale provided, use default - magma if (backgroundScale == null) { colorScheme = colorScheme || defaultColorScheme; backgroundColor = d3[`interpolate${colorScheme}`](domainScale(sortValue)); if (!colorScale) { colorShift = colorShift || 0.5; color = d3[`interpolate${colorScheme}`]((domainScale(sortValue) + colorShift) % 1); } } return { backgroundColor, color, }; }
[ "function", "tdStyle", "(", "cellData", ",", "{", "columnSummary", ",", "column", ",", "rowData", ",", "isBottomData", "}", ")", "{", "let", "domain", ";", "let", "backgroundScale", ";", "let", "colorScale", ";", "let", "colorShift", ";", "let", "colorScheme", ";", "let", "reverseColors", ";", "let", "includeBottomData", ";", "// read in from plugin options", "if", "(", "column", ".", "plugins", "&&", "column", ".", "plugins", ".", "heatmap", ")", "{", "domain", "=", "column", ".", "plugins", ".", "heatmap", ".", "domain", ";", "backgroundScale", "=", "column", ".", "plugins", ".", "heatmap", ".", "backgroundScale", ";", "colorScale", "=", "column", ".", "plugins", ".", "heatmap", ".", "colorScale", ";", "colorShift", "=", "column", ".", "plugins", ".", "heatmap", ".", "colorShift", ";", "colorScheme", "=", "column", ".", "plugins", ".", "heatmap", ".", "colorScheme", ";", "reverseColors", "=", "column", ".", "plugins", ".", "heatmap", ".", "reverseColors", ";", "includeBottomData", "=", "column", ".", "plugins", ".", "heatmap", ".", "includeBottomData", ";", "}", "// skip in bottom data area unless this column explicitly says to include it", "if", "(", "isBottomData", "&&", "!", "includeBottomData", ")", "{", "return", "undefined", ";", "}", "// compute the sort value", "const", "sortValue", "=", "Utils", ".", "getSortValueFromCellData", "(", "cellData", ",", "column", ",", "rowData", ")", ";", "// do not heatmap null or undefined values", "if", "(", "sortValue", "==", "null", ")", "{", "return", "undefined", ";", "}", "// default domain if not provided comes from columnSummary", "if", "(", "!", "domain", ")", "{", "// if we didn't get a min/max, just use [0, 1]", "const", "colMin", "=", "columnSummary", ".", "min", "==", "null", "?", "0", ":", "columnSummary", ".", "min", ";", "const", "colMax", "=", "columnSummary", ".", "max", "==", "null", "?", "1", ":", "columnSummary", ".", "max", ";", "domain", "=", "[", "colMin", ",", "colMax", "]", ";", "}", "// reverse the domain if specified to get the color scheme inverted", "if", "(", "reverseColors", ")", "{", "domain", "=", "domain", ".", "slice", "(", ")", ".", "reverse", "(", ")", ";", "}", "const", "domainScale", "=", "d3", ".", "scaleLinear", "(", ")", ".", "domain", "(", "domain", ")", ".", "range", "(", "[", "0", ",", "1", "]", ")", ".", "clamp", "(", "true", ")", ";", "// if a background scale is provided, use it", "let", "backgroundColor", ";", "if", "(", "backgroundScale", ")", "{", "if", "(", "backgroundScale", ".", "domain", ")", "{", "backgroundScale", ".", "domain", "(", "domain", ")", ";", "}", "backgroundColor", "=", "backgroundScale", "(", "sortValue", ")", ";", "}", "// if a color scale is provided, use it", "let", "color", ";", "if", "(", "colorScale", ")", "{", "if", "(", "colorScale", ".", "domain", ")", "{", "colorScale", ".", "domain", "(", "domain", ")", ";", "}", "color", "=", "colorScale", "(", "sortValue", ")", ";", "// if a color shift is defined, shift the background color by this amount (0, 1)", "}", "else", "if", "(", "backgroundScale", "&&", "colorShift", ")", "{", "const", "shiftedValue", "=", "domainScale", ".", "invert", "(", "(", "domainScale", "(", "sortValue", ")", "+", "colorShift", ")", "%", "1", ")", ";", "color", "=", "backgroundScale", "(", "shiftedValue", ")", ";", "}", "// if no background scale and color scale provided, use default - magma", "if", "(", "backgroundScale", "==", "null", ")", "{", "colorScheme", "=", "colorScheme", "||", "defaultColorScheme", ";", "backgroundColor", "=", "d3", "[", "`", "${", "colorScheme", "}", "`", "]", "(", "domainScale", "(", "sortValue", ")", ")", ";", "if", "(", "!", "colorScale", ")", "{", "colorShift", "=", "colorShift", "||", "0.5", ";", "color", "=", "d3", "[", "`", "${", "colorScheme", "}", "`", "]", "(", "(", "domainScale", "(", "sortValue", ")", "+", "colorShift", ")", "%", "1", ")", ";", "}", "}", "return", "{", "backgroundColor", ",", "color", ",", "}", ";", "}" ]
Compute the style for the td elements by setting the background and color based on the sort value. @param {Object} cellData the data for the cell @param {Object} props Additional properties for the cell @param {Object} props.columnSummary the column summary @param {Object} props.column The column definition @param {Object} props.rowData the data for the row @param {Boolean} props.isBottomData whether the row is in bottom data area @return {Object} the style object
[ "Compute", "the", "style", "for", "the", "td", "elements", "by", "setting", "the", "background", "and", "color", "based", "on", "the", "sort", "value", "." ]
db059ad7d051aefbaf00aea7f7a870e59711968a
https://github.com/pbeshai/react-taco-table/blob/db059ad7d051aefbaf00aea7f7a870e59711968a/src/plugins/HeatmapPlugin.js#L104-L194
42,089
pbeshai/react-taco-table
lib/TdClassNames.js
minMaxClassName
function minMaxClassName(cellData, _ref) { var columnSummary = _ref.columnSummary; var column = _ref.column; var rowData = _ref.rowData; var sortValue = Utils.getSortValueFromCellData(cellData, column, rowData); if (sortValue === columnSummary.min) { return 'highlight-min-max highlight-min'; } else if (sortValue === columnSummary.max) { return 'highlight-min-max highlight-max'; } return undefined; }
javascript
function minMaxClassName(cellData, _ref) { var columnSummary = _ref.columnSummary; var column = _ref.column; var rowData = _ref.rowData; var sortValue = Utils.getSortValueFromCellData(cellData, column, rowData); if (sortValue === columnSummary.min) { return 'highlight-min-max highlight-min'; } else if (sortValue === columnSummary.max) { return 'highlight-min-max highlight-max'; } return undefined; }
[ "function", "minMaxClassName", "(", "cellData", ",", "_ref", ")", "{", "var", "columnSummary", "=", "_ref", ".", "columnSummary", ";", "var", "column", "=", "_ref", ".", "column", ";", "var", "rowData", "=", "_ref", ".", "rowData", ";", "var", "sortValue", "=", "Utils", ".", "getSortValueFromCellData", "(", "cellData", ",", "column", ",", "rowData", ")", ";", "if", "(", "sortValue", "===", "columnSummary", ".", "min", ")", "{", "return", "'highlight-min-max highlight-min'", ";", "}", "else", "if", "(", "sortValue", "===", "columnSummary", ".", "max", ")", "{", "return", "'highlight-min-max highlight-max'", ";", "}", "return", "undefined", ";", "}" ]
Adds `highlight-min-max` and one of `highlight-min`, `highlight-max` to the cells that match min and max in the summary @param {Any} cellData the data for the cell @param {Object} props Additional props for the cell @param {Object} props.columnSummary The column summary @param {Object} props.column The column definition @param {Array} props.rowData the data for the row @return {String} classnames
[ "Adds", "highlight", "-", "min", "-", "max", "and", "one", "of", "highlight", "-", "min", "highlight", "-", "max", "to", "the", "cells", "that", "match", "min", "and", "max", "in", "the", "summary" ]
db059ad7d051aefbaf00aea7f7a870e59711968a
https://github.com/pbeshai/react-taco-table/blob/db059ad7d051aefbaf00aea7f7a870e59711968a/lib/TdClassNames.js#L28-L41
42,090
pbeshai/react-taco-table
lib/TdClassNames.js
minClassName
function minClassName(cellData, _ref2) { var columnSummary = _ref2.columnSummary; var column = _ref2.column; var rowData = _ref2.rowData; var sortValue = Utils.getSortValueFromCellData(cellData, column, rowData); if (sortValue === columnSummary.min) { return 'highlight-min'; } return undefined; }
javascript
function minClassName(cellData, _ref2) { var columnSummary = _ref2.columnSummary; var column = _ref2.column; var rowData = _ref2.rowData; var sortValue = Utils.getSortValueFromCellData(cellData, column, rowData); if (sortValue === columnSummary.min) { return 'highlight-min'; } return undefined; }
[ "function", "minClassName", "(", "cellData", ",", "_ref2", ")", "{", "var", "columnSummary", "=", "_ref2", ".", "columnSummary", ";", "var", "column", "=", "_ref2", ".", "column", ";", "var", "rowData", "=", "_ref2", ".", "rowData", ";", "var", "sortValue", "=", "Utils", ".", "getSortValueFromCellData", "(", "cellData", ",", "column", ",", "rowData", ")", ";", "if", "(", "sortValue", "===", "columnSummary", ".", "min", ")", "{", "return", "'highlight-min'", ";", "}", "return", "undefined", ";", "}" ]
Adds `highlight-min` to the cells that match min in the summary. @param {Any} cellData the data for the cell @param {Object} props Additional props for the cell @param {Object} props.columnSummary The column summary @param {Object} props.column The column definition @param {Array} props.rowData the data for the row @return {String} classnames TdClassNames is a collection of utility functions that can be used in column definitions as the `tdClassName` attribute. These functions typically combine cell data and summary information to produce a meaningful class name. They can take the following arguments: - `cellData` {Object} The data for the cell - `columnSummary` {Object} The summary for the column - `column` {Object} The definition for the column - `rowData` {Object} The data for the row - `highlightedColumn` {Boolean} true if this column is highlighted - `highlightedRow` {Boolean} true if this row is highlighted - `rowNumber` {Number} The row number - `tableData` {Array} the data for the whole table - `columns` {Array} the definitions for all columns @module TdClassNames
[ "Adds", "highlight", "-", "min", "to", "the", "cells", "that", "match", "min", "in", "the", "summary", "." ]
db059ad7d051aefbaf00aea7f7a870e59711968a
https://github.com/pbeshai/react-taco-table/blob/db059ad7d051aefbaf00aea7f7a870e59711968a/lib/TdClassNames.js#L75-L86
42,091
pbeshai/react-taco-table
lib/TdClassNames.js
maxClassName
function maxClassName(cellData, _ref3) { var columnSummary = _ref3.columnSummary; var column = _ref3.column; var rowData = _ref3.rowData; var sortValue = Utils.getSortValueFromCellData(cellData, column, rowData); if (sortValue === columnSummary.max) { return 'highlight-max'; } return undefined; }
javascript
function maxClassName(cellData, _ref3) { var columnSummary = _ref3.columnSummary; var column = _ref3.column; var rowData = _ref3.rowData; var sortValue = Utils.getSortValueFromCellData(cellData, column, rowData); if (sortValue === columnSummary.max) { return 'highlight-max'; } return undefined; }
[ "function", "maxClassName", "(", "cellData", ",", "_ref3", ")", "{", "var", "columnSummary", "=", "_ref3", ".", "columnSummary", ";", "var", "column", "=", "_ref3", ".", "column", ";", "var", "rowData", "=", "_ref3", ".", "rowData", ";", "var", "sortValue", "=", "Utils", ".", "getSortValueFromCellData", "(", "cellData", ",", "column", ",", "rowData", ")", ";", "if", "(", "sortValue", "===", "columnSummary", ".", "max", ")", "{", "return", "'highlight-max'", ";", "}", "return", "undefined", ";", "}" ]
Adds `highlight-max` to the cells that match max in the summary. @param {Any} cellData the data for the cell @param {Object} props Additional props for the cell @param {Object} props.columnSummary The column summary @param {Object} props.column The column definition @param {Array} props.rowData the data for the row @return {String} classnames
[ "Adds", "highlight", "-", "max", "to", "the", "cells", "that", "match", "max", "in", "the", "summary", "." ]
db059ad7d051aefbaf00aea7f7a870e59711968a
https://github.com/pbeshai/react-taco-table/blob/db059ad7d051aefbaf00aea7f7a870e59711968a/lib/TdClassNames.js#L99-L110
42,092
pbeshai/react-taco-table
lib/Utils.js
getCellData
function getCellData(column, rowData, rowNumber, tableData, columns, isBottomData) { var value = column.value; var id = column.id; // if it is bottom data, just use the value directly. if (isBottomData) { return rowData[id]; } // call value as a function if (typeof value === 'function') { return value(rowData, { rowNumber: rowNumber, tableData: tableData, columns: columns }); // interpret value as a key } else if (value != null) { return rowData[value]; } // otherwise, use the ID as a key return rowData[id]; }
javascript
function getCellData(column, rowData, rowNumber, tableData, columns, isBottomData) { var value = column.value; var id = column.id; // if it is bottom data, just use the value directly. if (isBottomData) { return rowData[id]; } // call value as a function if (typeof value === 'function') { return value(rowData, { rowNumber: rowNumber, tableData: tableData, columns: columns }); // interpret value as a key } else if (value != null) { return rowData[value]; } // otherwise, use the ID as a key return rowData[id]; }
[ "function", "getCellData", "(", "column", ",", "rowData", ",", "rowNumber", ",", "tableData", ",", "columns", ",", "isBottomData", ")", "{", "var", "value", "=", "column", ".", "value", ";", "var", "id", "=", "column", ".", "id", ";", "// if it is bottom data, just use the value directly.", "if", "(", "isBottomData", ")", "{", "return", "rowData", "[", "id", "]", ";", "}", "// call value as a function", "if", "(", "typeof", "value", "===", "'function'", ")", "{", "return", "value", "(", "rowData", ",", "{", "rowNumber", ":", "rowNumber", ",", "tableData", ":", "tableData", ",", "columns", ":", "columns", "}", ")", ";", "// interpret value as a key", "}", "else", "if", "(", "value", "!=", "null", ")", "{", "return", "rowData", "[", "value", "]", ";", "}", "// otherwise, use the ID as a key", "return", "rowData", "[", "id", "]", ";", "}" ]
Gets the value of a cell given the row data. If column.value is a function, it gets called, otherwise it is interpreted as a key to rowData. If column.value is not defined, column.id is used as a key to rowData. @param {Object} column The column definition @param {Object} rowData The data for the row @param {Number} rowNumber The number of the row @param {Object[]} tableData The array of data for the whole table @param {Object[]} columns The column definitions for the whole table @return {Any} The value for this cell
[ "Gets", "the", "value", "of", "a", "cell", "given", "the", "row", "data", ".", "If", "column", ".", "value", "is", "a", "function", "it", "gets", "called", "otherwise", "it", "is", "interpreted", "as", "a", "key", "to", "rowData", ".", "If", "column", ".", "value", "is", "not", "defined", "column", ".", "id", "is", "used", "as", "a", "key", "to", "rowData", "." ]
db059ad7d051aefbaf00aea7f7a870e59711968a
https://github.com/pbeshai/react-taco-table/blob/db059ad7d051aefbaf00aea7f7a870e59711968a/lib/Utils.js#L42-L63
42,093
pbeshai/react-taco-table
lib/Utils.js
getSortValueFromCellData
function getSortValueFromCellData(cellData, column, rowData) { var sortValue = column.sortValue; if (sortValue) { return sortValue(cellData, rowData); } return cellData; }
javascript
function getSortValueFromCellData(cellData, column, rowData) { var sortValue = column.sortValue; if (sortValue) { return sortValue(cellData, rowData); } return cellData; }
[ "function", "getSortValueFromCellData", "(", "cellData", ",", "column", ",", "rowData", ")", "{", "var", "sortValue", "=", "column", ".", "sortValue", ";", "if", "(", "sortValue", ")", "{", "return", "sortValue", "(", "cellData", ",", "rowData", ")", ";", "}", "return", "cellData", ";", "}" ]
Gets the sort value of a cell given the cell data and row data. If no sortValue function is provided on the column, the cellData is returned. @param {Object} cellData The cell data @param {Object} column The column definition @param {Object} rowData The data for the row @return {Any} The sort value for this cell A collection of utility functions that make it easier to work with table data. @module Utils
[ "Gets", "the", "sort", "value", "of", "a", "cell", "given", "the", "cell", "data", "and", "row", "data", ".", "If", "no", "sortValue", "function", "is", "provided", "on", "the", "column", "the", "cellData", "is", "returned", "." ]
db059ad7d051aefbaf00aea7f7a870e59711968a
https://github.com/pbeshai/react-taco-table/blob/db059ad7d051aefbaf00aea7f7a870e59711968a/lib/Utils.js#L80-L89
42,094
pbeshai/react-taco-table
lib/Utils.js
getSortValue
function getSortValue(column, rowData, rowNumber, tableData, columns) { var cellData = getCellData(column, rowData, rowNumber, tableData, columns); return getSortValueFromCellData(cellData, column, rowData); }
javascript
function getSortValue(column, rowData, rowNumber, tableData, columns) { var cellData = getCellData(column, rowData, rowNumber, tableData, columns); return getSortValueFromCellData(cellData, column, rowData); }
[ "function", "getSortValue", "(", "column", ",", "rowData", ",", "rowNumber", ",", "tableData", ",", "columns", ")", "{", "var", "cellData", "=", "getCellData", "(", "column", ",", "rowData", ",", "rowNumber", ",", "tableData", ",", "columns", ")", ";", "return", "getSortValueFromCellData", "(", "cellData", ",", "column", ",", "rowData", ")", ";", "}" ]
Gets the sort value for a cell by first computing the cell data. If no sortValue function is provided on the column, the cellData is returned. @param {Object} column The column definition @param {Object} rowData The data for the row @param {Number} rowNumber The number of the row @param {Object[]} tableData The array of data for the whole table @param {Object[]} columns The column definitions for the whole table @return {Any} The sort value for this cell
[ "Gets", "the", "sort", "value", "for", "a", "cell", "by", "first", "computing", "the", "cell", "data", ".", "If", "no", "sortValue", "function", "is", "provided", "on", "the", "column", "the", "cellData", "is", "returned", "." ]
db059ad7d051aefbaf00aea7f7a870e59711968a
https://github.com/pbeshai/react-taco-table/blob/db059ad7d051aefbaf00aea7f7a870e59711968a/lib/Utils.js#L103-L107
42,095
pbeshai/react-taco-table
lib/Utils.js
sortData
function sortData(data, columnId, sortDirection, columns) { var column = getColumnById(columns, columnId); if (!column) { if (process.env.NODE_ENV !== 'production') { console.warn('No column found by ID', columnId, columns); } return data; } // read the type from `sortType` property if defined, otherwise use `type` var sortType = column.sortType == null ? column.type : column.sortType; var comparator = getSortComparator(sortType); var dataToSort = data.map(function (rowData, index) { return { rowData: rowData, index: index, sortValue: getSortValue(column, rowData, index, data, columns) }; }); // check if already sorted, and if so, just reverse var sortedData = void 0; // if already sorted in the opposite order, just reverse it if (alreadySorted(!sortDirection, dataToSort, comparator)) { sortedData = dataToSort.reverse(); // if not sorted, stable sort it } else { sortedData = (0, _stable2.default)(dataToSort, comparator); if (sortDirection === _SortDirection2.default.Descending) { sortedData.reverse(); } } sortedData = sortedData.map(function (sortItem) { return sortItem.rowData; }); return sortedData; }
javascript
function sortData(data, columnId, sortDirection, columns) { var column = getColumnById(columns, columnId); if (!column) { if (process.env.NODE_ENV !== 'production') { console.warn('No column found by ID', columnId, columns); } return data; } // read the type from `sortType` property if defined, otherwise use `type` var sortType = column.sortType == null ? column.type : column.sortType; var comparator = getSortComparator(sortType); var dataToSort = data.map(function (rowData, index) { return { rowData: rowData, index: index, sortValue: getSortValue(column, rowData, index, data, columns) }; }); // check if already sorted, and if so, just reverse var sortedData = void 0; // if already sorted in the opposite order, just reverse it if (alreadySorted(!sortDirection, dataToSort, comparator)) { sortedData = dataToSort.reverse(); // if not sorted, stable sort it } else { sortedData = (0, _stable2.default)(dataToSort, comparator); if (sortDirection === _SortDirection2.default.Descending) { sortedData.reverse(); } } sortedData = sortedData.map(function (sortItem) { return sortItem.rowData; }); return sortedData; }
[ "function", "sortData", "(", "data", ",", "columnId", ",", "sortDirection", ",", "columns", ")", "{", "var", "column", "=", "getColumnById", "(", "columns", ",", "columnId", ")", ";", "if", "(", "!", "column", ")", "{", "if", "(", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", ")", "{", "console", ".", "warn", "(", "'No column found by ID'", ",", "columnId", ",", "columns", ")", ";", "}", "return", "data", ";", "}", "// read the type from `sortType` property if defined, otherwise use `type`", "var", "sortType", "=", "column", ".", "sortType", "==", "null", "?", "column", ".", "type", ":", "column", ".", "sortType", ";", "var", "comparator", "=", "getSortComparator", "(", "sortType", ")", ";", "var", "dataToSort", "=", "data", ".", "map", "(", "function", "(", "rowData", ",", "index", ")", "{", "return", "{", "rowData", ":", "rowData", ",", "index", ":", "index", ",", "sortValue", ":", "getSortValue", "(", "column", ",", "rowData", ",", "index", ",", "data", ",", "columns", ")", "}", ";", "}", ")", ";", "// check if already sorted, and if so, just reverse", "var", "sortedData", "=", "void", "0", ";", "// if already sorted in the opposite order, just reverse it", "if", "(", "alreadySorted", "(", "!", "sortDirection", ",", "dataToSort", ",", "comparator", ")", ")", "{", "sortedData", "=", "dataToSort", ".", "reverse", "(", ")", ";", "// if not sorted, stable sort it", "}", "else", "{", "sortedData", "=", "(", "0", ",", "_stable2", ".", "default", ")", "(", "dataToSort", ",", "comparator", ")", ";", "if", "(", "sortDirection", "===", "_SortDirection2", ".", "default", ".", "Descending", ")", "{", "sortedData", ".", "reverse", "(", ")", ";", "}", "}", "sortedData", "=", "sortedData", ".", "map", "(", "function", "(", "sortItem", ")", "{", "return", "sortItem", ".", "rowData", ";", "}", ")", ";", "return", "sortedData", ";", "}" ]
Sorts the data based on sort value and column type. Uses a stable sort by keeping track of the original position to break ties unless the data is already sorted, in which case it just reverses the array. @param {Object[]} data the array of data for the whole table @param {String} columnId the column ID of the column to sort by @param {Boolean} sortDirection The direction to sort in @param {Object[]} columns The column definitions for the whole table @return {Object[]} The sorted data
[ "Sorts", "the", "data", "based", "on", "sort", "value", "and", "column", "type", ".", "Uses", "a", "stable", "sort", "by", "keeping", "track", "of", "the", "original", "position", "to", "break", "ties", "unless", "the", "data", "is", "already", "sorted", "in", "which", "case", "it", "just", "reverses", "the", "array", "." ]
db059ad7d051aefbaf00aea7f7a870e59711968a
https://github.com/pbeshai/react-taco-table/blob/db059ad7d051aefbaf00aea7f7a870e59711968a/lib/Utils.js#L237-L279
42,096
pbeshai/react-taco-table
lib/Utils.js
renderCell
function renderCell(cellData, column, rowData, rowNumber, tableData, columns, isBottomData, columnSummary) { var renderer = column.renderer; var renderOnNull = column.renderOnNull; // render if not bottom data-- bottomData's cellData is already rendered. if (!isBottomData) { // do not render if value is null and `renderOnNull` is not explicitly set to true if (cellData == null && renderOnNull !== true) { return null; // render normally if a renderer is provided } else if (renderer != null) { return renderer(cellData, { column: column, rowData: rowData, rowNumber: rowNumber, tableData: tableData, columns: columns, columnSummary: columnSummary }); } } // otherwise, render the raw cell data return cellData; }
javascript
function renderCell(cellData, column, rowData, rowNumber, tableData, columns, isBottomData, columnSummary) { var renderer = column.renderer; var renderOnNull = column.renderOnNull; // render if not bottom data-- bottomData's cellData is already rendered. if (!isBottomData) { // do not render if value is null and `renderOnNull` is not explicitly set to true if (cellData == null && renderOnNull !== true) { return null; // render normally if a renderer is provided } else if (renderer != null) { return renderer(cellData, { column: column, rowData: rowData, rowNumber: rowNumber, tableData: tableData, columns: columns, columnSummary: columnSummary }); } } // otherwise, render the raw cell data return cellData; }
[ "function", "renderCell", "(", "cellData", ",", "column", ",", "rowData", ",", "rowNumber", ",", "tableData", ",", "columns", ",", "isBottomData", ",", "columnSummary", ")", "{", "var", "renderer", "=", "column", ".", "renderer", ";", "var", "renderOnNull", "=", "column", ".", "renderOnNull", ";", "// render if not bottom data-- bottomData's cellData is already rendered.", "if", "(", "!", "isBottomData", ")", "{", "// do not render if value is null and `renderOnNull` is not explicitly set to true", "if", "(", "cellData", "==", "null", "&&", "renderOnNull", "!==", "true", ")", "{", "return", "null", ";", "// render normally if a renderer is provided", "}", "else", "if", "(", "renderer", "!=", "null", ")", "{", "return", "renderer", "(", "cellData", ",", "{", "column", ":", "column", ",", "rowData", ":", "rowData", ",", "rowNumber", ":", "rowNumber", ",", "tableData", ":", "tableData", ",", "columns", ":", "columns", ",", "columnSummary", ":", "columnSummary", "}", ")", ";", "}", "}", "// otherwise, render the raw cell data", "return", "cellData", ";", "}" ]
Renders a cell's contents based on the renderer function. If no renderer is provided, it just returns the raw cell data. In such cases, the user should take care that cellData can be rendered directly. @param {Any} cellData The data for the cell @param {Object} column The column definition @param {Object} rowData The data for the row @param {Number} rowNumber The number of the row @param {Object[]} tableData The array of data for the whole table @param {Object[]} columns The column definitions for the whole table @return {Renderable} The contents of the cell
[ "Renders", "a", "cell", "s", "contents", "based", "on", "the", "renderer", "function", ".", "If", "no", "renderer", "is", "provided", "it", "just", "returns", "the", "raw", "cell", "data", ".", "In", "such", "cases", "the", "user", "should", "take", "care", "that", "cellData", "can", "be", "rendered", "directly", "." ]
db059ad7d051aefbaf00aea7f7a870e59711968a
https://github.com/pbeshai/react-taco-table/blob/db059ad7d051aefbaf00aea7f7a870e59711968a/lib/Utils.js#L295-L314
42,097
pbeshai/react-taco-table
lib/Utils.js
validateColumns
function validateColumns(columns) { if (!columns) { return; } // check IDs var ids = {}; columns.forEach(function (column, i) { var id = column.id; if (!ids[id]) { ids[id] = [i]; } else { ids[id].push(i); } }); Object.keys(ids).forEach(function (id) { if (ids[id].length > 1) { console.warn('Column ID \'' + id + '\' used in multiple columns ' + ids[id].join(', '), ids[id].map(function (index) { return columns[index]; })); } }); }
javascript
function validateColumns(columns) { if (!columns) { return; } // check IDs var ids = {}; columns.forEach(function (column, i) { var id = column.id; if (!ids[id]) { ids[id] = [i]; } else { ids[id].push(i); } }); Object.keys(ids).forEach(function (id) { if (ids[id].length > 1) { console.warn('Column ID \'' + id + '\' used in multiple columns ' + ids[id].join(', '), ids[id].map(function (index) { return columns[index]; })); } }); }
[ "function", "validateColumns", "(", "columns", ")", "{", "if", "(", "!", "columns", ")", "{", "return", ";", "}", "// check IDs", "var", "ids", "=", "{", "}", ";", "columns", ".", "forEach", "(", "function", "(", "column", ",", "i", ")", "{", "var", "id", "=", "column", ".", "id", ";", "if", "(", "!", "ids", "[", "id", "]", ")", "{", "ids", "[", "id", "]", "=", "[", "i", "]", ";", "}", "else", "{", "ids", "[", "id", "]", ".", "push", "(", "i", ")", ";", "}", "}", ")", ";", "Object", ".", "keys", "(", "ids", ")", ".", "forEach", "(", "function", "(", "id", ")", "{", "if", "(", "ids", "[", "id", "]", ".", "length", ">", "1", ")", "{", "console", ".", "warn", "(", "'Column ID \\''", "+", "id", "+", "'\\' used in multiple columns '", "+", "ids", "[", "id", "]", ".", "join", "(", "', '", ")", ",", "ids", "[", "id", "]", ".", "map", "(", "function", "(", "index", ")", "{", "return", "columns", "[", "index", "]", ";", "}", ")", ")", ";", "}", "}", ")", ";", "}" ]
Checks an array of column definitions to see if there are any issues. Checks if - multiple columns have the same ID Typically only used in development. @param {Object[]} columns The column definitions for the whole table @returns {void}
[ "Checks", "an", "array", "of", "column", "definitions", "to", "see", "if", "there", "are", "any", "issues", ".", "Checks", "if" ]
db059ad7d051aefbaf00aea7f7a870e59711968a
https://github.com/pbeshai/react-taco-table/blob/db059ad7d051aefbaf00aea7f7a870e59711968a/lib/Utils.js#L327-L350
42,098
BernzSed/axios-push
src/utils/merge.js
forEach
function forEach(obj, fn) { // Don't bother if no value provided if (obj === null || typeof obj === 'undefined') { return; } // Force an array if not already something iterable if (typeof obj !== 'object') { /* eslint no-param-reassign:0 */ obj = [obj]; } if (Array.isArray(obj)) { // Iterate over array values for (let i = 0, l = obj.length; i < l; i += 1) { fn.call(null, obj[i], i, obj); } } else { // Iterate over object keys Object.entries(obj).forEach(([key, val]) => { fn.call(null, val, key, obj); }); } }
javascript
function forEach(obj, fn) { // Don't bother if no value provided if (obj === null || typeof obj === 'undefined') { return; } // Force an array if not already something iterable if (typeof obj !== 'object') { /* eslint no-param-reassign:0 */ obj = [obj]; } if (Array.isArray(obj)) { // Iterate over array values for (let i = 0, l = obj.length; i < l; i += 1) { fn.call(null, obj[i], i, obj); } } else { // Iterate over object keys Object.entries(obj).forEach(([key, val]) => { fn.call(null, val, key, obj); }); } }
[ "function", "forEach", "(", "obj", ",", "fn", ")", "{", "// Don't bother if no value provided", "if", "(", "obj", "===", "null", "||", "typeof", "obj", "===", "'undefined'", ")", "{", "return", ";", "}", "// Force an array if not already something iterable", "if", "(", "typeof", "obj", "!==", "'object'", ")", "{", "/* eslint no-param-reassign:0 */", "obj", "=", "[", "obj", "]", ";", "}", "if", "(", "Array", ".", "isArray", "(", "obj", ")", ")", "{", "// Iterate over array values", "for", "(", "let", "i", "=", "0", ",", "l", "=", "obj", ".", "length", ";", "i", "<", "l", ";", "i", "+=", "1", ")", "{", "fn", ".", "call", "(", "null", ",", "obj", "[", "i", "]", ",", "i", ",", "obj", ")", ";", "}", "}", "else", "{", "// Iterate over object keys", "Object", ".", "entries", "(", "obj", ")", ".", "forEach", "(", "(", "[", "key", ",", "val", "]", ")", "=>", "{", "fn", ".", "call", "(", "null", ",", "val", ",", "key", ",", "obj", ")", ";", "}", ")", ";", "}", "}" ]
This is copied from axios utils to preserve axios's logic
[ "This", "is", "copied", "from", "axios", "utils", "to", "preserve", "axios", "s", "logic" ]
068c8cec98a7fc3db1042e3662fc042c8f42b66d
https://github.com/BernzSed/axios-push/blob/068c8cec98a7fc3db1042e3662fc042c8f42b66d/src/utils/merge.js#L3-L26
42,099
darrylhodgins/piface-node
examples/pfio.inputs.changed.js
watchInputs
function watchInputs() { var state; state = pfio.read_input(); if (state !== prev_state) { EventBus.emit('pfio.inputs.changed', state, prev_state); prev_state = state; } setTimeout(watchInputs, 10); }
javascript
function watchInputs() { var state; state = pfio.read_input(); if (state !== prev_state) { EventBus.emit('pfio.inputs.changed', state, prev_state); prev_state = state; } setTimeout(watchInputs, 10); }
[ "function", "watchInputs", "(", ")", "{", "var", "state", ";", "state", "=", "pfio", ".", "read_input", "(", ")", ";", "if", "(", "state", "!==", "prev_state", ")", "{", "EventBus", ".", "emit", "(", "'pfio.inputs.changed'", ",", "state", ",", "prev_state", ")", ";", "prev_state", "=", "state", ";", "}", "setTimeout", "(", "watchInputs", ",", "10", ")", ";", "}" ]
Watches for state changes
[ "Watches", "for", "state", "changes" ]
8ef10874612e6215255918af4e19aba03272d8f8
https://github.com/darrylhodgins/piface-node/blob/8ef10874612e6215255918af4e19aba03272d8f8/examples/pfio.inputs.changed.js#L25-L33