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
49,000
redarrowlabs/strongback
bin/form/field-wrapper.js
FieldLabel
function FieldLabel(props) { var label = props.label, indicator = props.indicator, tooltipProps = props.tooltipProps, infoIconProps = props.infoIconProps; var indicatorEl = null; if (indicator === 'optional') { indicatorEl = React.createElement("span", { className: 'indicator' }, "(optional)"); } if (indicator === 'required') { indicatorEl = React.createElement("span", { className: 'indicator' }, "*"); } var indicatorClass = classNames({ 'optional': props.indicator === 'optional', 'required': props.indicator === 'required' }); var tooltipEl = null; if (infoIconProps && tooltipProps != null) { tooltipEl = React.createElement(tooltip_1.Tooltip, { tooltip: tooltipProps.tooltip, tooltipAlignment: tooltipProps.tooltipAlignment, tooltipPosition: tooltipProps.tooltipPosition }, React.createElement(info_icon_1.InfoIcon, { iconContent: infoIconProps.iconContent, iconCustomTypeName: infoIconProps.iconCustomTypeName })); } else if (tooltipProps != null) { tooltipEl = React.createElement(tooltip_1.Tooltip, { tooltip: tooltipProps.tooltip, tooltipAlignment: tooltipProps.tooltipAlignment, tooltipPosition: tooltipProps.tooltipPosition }); } else if (infoIconProps != null) { tooltipEl = React.createElement(info_icon_1.InfoIcon, { iconContent: infoIconProps.iconContent, iconCustomTypeName: infoIconProps.iconCustomTypeName }); } return React.createElement("div", { className: indicatorClass }, label, " ", indicatorEl, " ", tooltipEl); }
javascript
function FieldLabel(props) { var label = props.label, indicator = props.indicator, tooltipProps = props.tooltipProps, infoIconProps = props.infoIconProps; var indicatorEl = null; if (indicator === 'optional') { indicatorEl = React.createElement("span", { className: 'indicator' }, "(optional)"); } if (indicator === 'required') { indicatorEl = React.createElement("span", { className: 'indicator' }, "*"); } var indicatorClass = classNames({ 'optional': props.indicator === 'optional', 'required': props.indicator === 'required' }); var tooltipEl = null; if (infoIconProps && tooltipProps != null) { tooltipEl = React.createElement(tooltip_1.Tooltip, { tooltip: tooltipProps.tooltip, tooltipAlignment: tooltipProps.tooltipAlignment, tooltipPosition: tooltipProps.tooltipPosition }, React.createElement(info_icon_1.InfoIcon, { iconContent: infoIconProps.iconContent, iconCustomTypeName: infoIconProps.iconCustomTypeName })); } else if (tooltipProps != null) { tooltipEl = React.createElement(tooltip_1.Tooltip, { tooltip: tooltipProps.tooltip, tooltipAlignment: tooltipProps.tooltipAlignment, tooltipPosition: tooltipProps.tooltipPosition }); } else if (infoIconProps != null) { tooltipEl = React.createElement(info_icon_1.InfoIcon, { iconContent: infoIconProps.iconContent, iconCustomTypeName: infoIconProps.iconCustomTypeName }); } return React.createElement("div", { className: indicatorClass }, label, " ", indicatorEl, " ", tooltipEl); }
[ "function", "FieldLabel", "(", "props", ")", "{", "var", "label", "=", "props", ".", "label", ",", "indicator", "=", "props", ".", "indicator", ",", "tooltipProps", "=", "props", ".", "tooltipProps", ",", "infoIconProps", "=", "props", ".", "infoIconProps", ";", "var", "indicatorEl", "=", "null", ";", "if", "(", "indicator", "===", "'optional'", ")", "{", "indicatorEl", "=", "React", ".", "createElement", "(", "\"span\"", ",", "{", "className", ":", "'indicator'", "}", ",", "\"(optional)\"", ")", ";", "}", "if", "(", "indicator", "===", "'required'", ")", "{", "indicatorEl", "=", "React", ".", "createElement", "(", "\"span\"", ",", "{", "className", ":", "'indicator'", "}", ",", "\"*\"", ")", ";", "}", "var", "indicatorClass", "=", "classNames", "(", "{", "'optional'", ":", "props", ".", "indicator", "===", "'optional'", ",", "'required'", ":", "props", ".", "indicator", "===", "'required'", "}", ")", ";", "var", "tooltipEl", "=", "null", ";", "if", "(", "infoIconProps", "&&", "tooltipProps", "!=", "null", ")", "{", "tooltipEl", "=", "React", ".", "createElement", "(", "tooltip_1", ".", "Tooltip", ",", "{", "tooltip", ":", "tooltipProps", ".", "tooltip", ",", "tooltipAlignment", ":", "tooltipProps", ".", "tooltipAlignment", ",", "tooltipPosition", ":", "tooltipProps", ".", "tooltipPosition", "}", ",", "React", ".", "createElement", "(", "info_icon_1", ".", "InfoIcon", ",", "{", "iconContent", ":", "infoIconProps", ".", "iconContent", ",", "iconCustomTypeName", ":", "infoIconProps", ".", "iconCustomTypeName", "}", ")", ")", ";", "}", "else", "if", "(", "tooltipProps", "!=", "null", ")", "{", "tooltipEl", "=", "React", ".", "createElement", "(", "tooltip_1", ".", "Tooltip", ",", "{", "tooltip", ":", "tooltipProps", ".", "tooltip", ",", "tooltipAlignment", ":", "tooltipProps", ".", "tooltipAlignment", ",", "tooltipPosition", ":", "tooltipProps", ".", "tooltipPosition", "}", ")", ";", "}", "else", "if", "(", "infoIconProps", "!=", "null", ")", "{", "tooltipEl", "=", "React", ".", "createElement", "(", "info_icon_1", ".", "InfoIcon", ",", "{", "iconContent", ":", "infoIconProps", ".", "iconContent", ",", "iconCustomTypeName", ":", "infoIconProps", ".", "iconCustomTypeName", "}", ")", ";", "}", "return", "React", ".", "createElement", "(", "\"div\"", ",", "{", "className", ":", "indicatorClass", "}", ",", "label", ",", "\" \"", ",", "indicatorEl", ",", "\" \"", ",", "tooltipEl", ")", ";", "}" ]
The label of the field, including indicators.
[ "The", "label", "of", "the", "field", "including", "indicators", "." ]
cdc8e0431a7fdf4faeb4016ba498b9146fc166aa
https://github.com/redarrowlabs/strongback/blob/cdc8e0431a7fdf4faeb4016ba498b9146fc166aa/bin/form/field-wrapper.js#L52-L82
49,001
redarrowlabs/strongback
bin/form/field-wrapper.js
FieldError
function FieldError(props) { var touched = props.touched, error = props.error; if (touched && error) { return React.createElement("div", { className: 'c-form-field--error-message' }, error); } return null; }
javascript
function FieldError(props) { var touched = props.touched, error = props.error; if (touched && error) { return React.createElement("div", { className: 'c-form-field--error-message' }, error); } return null; }
[ "function", "FieldError", "(", "props", ")", "{", "var", "touched", "=", "props", ".", "touched", ",", "error", "=", "props", ".", "error", ";", "if", "(", "touched", "&&", "error", ")", "{", "return", "React", ".", "createElement", "(", "\"div\"", ",", "{", "className", ":", "'c-form-field--error-message'", "}", ",", "error", ")", ";", "}", "return", "null", ";", "}" ]
The error message section of a field.
[ "The", "error", "message", "section", "of", "a", "field", "." ]
cdc8e0431a7fdf4faeb4016ba498b9146fc166aa
https://github.com/redarrowlabs/strongback/blob/cdc8e0431a7fdf4faeb4016ba498b9146fc166aa/bin/form/field-wrapper.js#L84-L90
49,002
dizmo/functions-buffered
dist/lib/buffered.js
buffered
function buffered(fn) { var ms = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 200; var id = void 0; var bn = function bn() { var _this = this; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return new Promise(function (resolve) { clearTimeout(id); id = setTimeout(function () { return resolve(fn.apply(_this, args)); }, ms); }); }; bn.cancel = function () { clearTimeout(id); }; return bn; }
javascript
function buffered(fn) { var ms = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 200; var id = void 0; var bn = function bn() { var _this = this; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return new Promise(function (resolve) { clearTimeout(id); id = setTimeout(function () { return resolve(fn.apply(_this, args)); }, ms); }); }; bn.cancel = function () { clearTimeout(id); }; return bn; }
[ "function", "buffered", "(", "fn", ")", "{", "var", "ms", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "200", ";", "var", "id", "=", "void", "0", ";", "var", "bn", "=", "function", "bn", "(", ")", "{", "var", "_this", "=", "this", ";", "for", "(", "var", "_len", "=", "arguments", ".", "length", ",", "args", "=", "Array", "(", "_len", ")", ",", "_key", "=", "0", ";", "_key", "<", "_len", ";", "_key", "++", ")", "{", "args", "[", "_key", "]", "=", "arguments", "[", "_key", "]", ";", "}", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "clearTimeout", "(", "id", ")", ";", "id", "=", "setTimeout", "(", "function", "(", ")", "{", "return", "resolve", "(", "fn", ".", "apply", "(", "_this", ",", "args", ")", ")", ";", "}", ",", "ms", ")", ";", "}", ")", ";", "}", ";", "bn", ".", "cancel", "=", "function", "(", ")", "{", "clearTimeout", "(", "id", ")", ";", "}", ";", "return", "bn", ";", "}" ]
Returns a buffered and cancelable version for the provided function. The buffered function does *not* get invoked, before the specified delay in milliseconds passes, no matter how much it gets invoked in between. Also upon the invocation of the *actual* function a promise is returned. Further, it is also possible to *cancel* a particular invocation before the delay passes. @param fn an arbitrary function @param ms delay in milliseconds @returns a buffered function
[ "Returns", "a", "buffered", "and", "cancelable", "version", "for", "the", "provided", "function", "." ]
63139ca7d68767890076ccd11368804e87816f07
https://github.com/dizmo/functions-buffered/blob/63139ca7d68767890076ccd11368804e87816f07/dist/lib/buffered.js#L20-L42
49,003
Maximilianos/imgGlitch
dist/imgGlitch.js
imgGlitch
function imgGlitch(img, options) { var imgElement = 'string' === typeof img ? document.querySelector(img) : img; if (!(imgElement instanceof HTMLImageElement && imgElement.constructor === HTMLImageElement)) { throw new TypeError('renderImgCorruption expects input img to be a valid image element'); } var corrupt64 = getCorrupt64(options); var data = imgElement.src; var corruption = undefined; return { start: start, stop: stop, clear: clear }; /** * Start rendering the * corruption * */ function start() { corruption = requestAnimationFrame(render); } /** * Render the corruption * */ function render() { imgElement.src = corrupt64(data); start(); } /** * Stop rendering the * corruption * */ function stop() { cancelAnimationFrame(corruption); } /** * Stop rendering the * corruption and * clear its effects * */ function clear() { stop(); imgElement.src = data; } }
javascript
function imgGlitch(img, options) { var imgElement = 'string' === typeof img ? document.querySelector(img) : img; if (!(imgElement instanceof HTMLImageElement && imgElement.constructor === HTMLImageElement)) { throw new TypeError('renderImgCorruption expects input img to be a valid image element'); } var corrupt64 = getCorrupt64(options); var data = imgElement.src; var corruption = undefined; return { start: start, stop: stop, clear: clear }; /** * Start rendering the * corruption * */ function start() { corruption = requestAnimationFrame(render); } /** * Render the corruption * */ function render() { imgElement.src = corrupt64(data); start(); } /** * Stop rendering the * corruption * */ function stop() { cancelAnimationFrame(corruption); } /** * Stop rendering the * corruption and * clear its effects * */ function clear() { stop(); imgElement.src = data; } }
[ "function", "imgGlitch", "(", "img", ",", "options", ")", "{", "var", "imgElement", "=", "'string'", "===", "typeof", "img", "?", "document", ".", "querySelector", "(", "img", ")", ":", "img", ";", "if", "(", "!", "(", "imgElement", "instanceof", "HTMLImageElement", "&&", "imgElement", ".", "constructor", "===", "HTMLImageElement", ")", ")", "{", "throw", "new", "TypeError", "(", "'renderImgCorruption expects input img to be a valid image element'", ")", ";", "}", "var", "corrupt64", "=", "getCorrupt64", "(", "options", ")", ";", "var", "data", "=", "imgElement", ".", "src", ";", "var", "corruption", "=", "undefined", ";", "return", "{", "start", ":", "start", ",", "stop", ":", "stop", ",", "clear", ":", "clear", "}", ";", "/**\n * Start rendering the\n * corruption\n *\n */", "function", "start", "(", ")", "{", "corruption", "=", "requestAnimationFrame", "(", "render", ")", ";", "}", "/**\n * Render the corruption\n *\n */", "function", "render", "(", ")", "{", "imgElement", ".", "src", "=", "corrupt64", "(", "data", ")", ";", "start", "(", ")", ";", "}", "/**\n * Stop rendering the\n * corruption\n *\n */", "function", "stop", "(", ")", "{", "cancelAnimationFrame", "(", "corruption", ")", ";", "}", "/**\n * Stop rendering the\n * corruption and\n * clear its effects\n *\n */", "function", "clear", "(", ")", "{", "stop", "(", ")", ";", "imgElement", ".", "src", "=", "data", ";", "}", "}" ]
Render the base64 corruption based image glitch effect @param img @param options @returns {{start, stop, clear}}
[ "Render", "the", "base64", "corruption", "based", "image", "glitch", "effect" ]
806ec31c5f6368ec91e2cc94cea44a35813c80c5
https://github.com/Maximilianos/imgGlitch/blob/806ec31c5f6368ec91e2cc94cea44a35813c80c5/dist/imgGlitch.js#L72-L127
49,004
halfbakedsneed/chowdown
src/document/index.js
add
function add(name, methods) { // Create a container class that extends Document for our methods. class ConcreteDocument extends Document { constructor(document, root) { super(name, document, root); } } // Assign the methods to the new classes prototype. assignIn(ConcreteDocument.prototype, methods); // Add a factory method for the new type. Document.factory[name] = (document, root) => new ConcreteDocument(document, root); }
javascript
function add(name, methods) { // Create a container class that extends Document for our methods. class ConcreteDocument extends Document { constructor(document, root) { super(name, document, root); } } // Assign the methods to the new classes prototype. assignIn(ConcreteDocument.prototype, methods); // Add a factory method for the new type. Document.factory[name] = (document, root) => new ConcreteDocument(document, root); }
[ "function", "add", "(", "name", ",", "methods", ")", "{", "// Create a container class that extends Document for our methods.", "class", "ConcreteDocument", "extends", "Document", "{", "constructor", "(", "document", ",", "root", ")", "{", "super", "(", "name", ",", "document", ",", "root", ")", ";", "}", "}", "// Assign the methods to the new classes prototype.", "assignIn", "(", "ConcreteDocument", ".", "prototype", ",", "methods", ")", ";", "// Add a factory method for the new type.", "Document", ".", "factory", "[", "name", "]", "=", "(", "document", ",", "root", ")", "=>", "new", "ConcreteDocument", "(", "document", ",", "root", ")", ";", "}" ]
Creates and adds a a factory method for a new subtype of document. @param {string} name The name of the subtype. @param {object} methods The methods the class will have.
[ "Creates", "and", "adds", "a", "a", "factory", "method", "for", "a", "new", "subtype", "of", "document", "." ]
b0e322c6070f82d557886afec9217b41f5214543
https://github.com/halfbakedsneed/chowdown/blob/b0e322c6070f82d557886afec9217b41f5214543/src/document/index.js#L136-L150
49,005
fex-team/fis-packager-map
index.js
function(subpath, regs){ for(var i = 0, len = regs.length; i < len; i++){ var reg = regs[i]; if(reg && fis.util.filter(subpath, reg)){ return i; } } return false; }
javascript
function(subpath, regs){ for(var i = 0, len = regs.length; i < len; i++){ var reg = regs[i]; if(reg && fis.util.filter(subpath, reg)){ return i; } } return false; }
[ "function", "(", "subpath", ",", "regs", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "regs", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "reg", "=", "regs", "[", "i", "]", ";", "if", "(", "reg", "&&", "fis", ".", "util", ".", "filter", "(", "subpath", ",", "reg", ")", ")", "{", "return", "i", ";", "}", "}", "return", "false", ";", "}" ]
determine if subpath hit a pack config
[ "determine", "if", "subpath", "hit", "a", "pack", "config" ]
277a78adb101ef69ce9a19823ffce79d98f3f389
https://github.com/fex-team/fis-packager-map/blob/277a78adb101ef69ce9a19823ffce79d98f3f389/index.js#L37-L45
49,006
meetings/gearsloth
lib/config/validate.js
confBool
function confBool(obj, field) { if (field in obj) obj[field] = bool(obj[field]); }
javascript
function confBool(obj, field) { if (field in obj) obj[field] = bool(obj[field]); }
[ "function", "confBool", "(", "obj", ",", "field", ")", "{", "if", "(", "field", "in", "obj", ")", "obj", "[", "field", "]", "=", "bool", "(", "obj", "[", "field", "]", ")", ";", "}" ]
Validate and clean a boolean field.
[ "Validate", "and", "clean", "a", "boolean", "field", "." ]
21d07729d6197bdbea515f32922896e3ae485d46
https://github.com/meetings/gearsloth/blob/21d07729d6197bdbea515f32922896e3ae485d46/lib/config/validate.js#L78-L81
49,007
djordjelacmanovic/yql-node
index.js
function (consumer_key, consumer_secret) { this.oauth = new OAuth.OAuth( 'https://query.yahooapis.com/v1/yql/', 'https://query.yahooapis.com/v1/yql/', consumer_key, //consumer key consumer_secret, //consumer secret '1.0', null, 'HMAC-SHA1' ); this.oauth.setClientOptions({ requestTokenHttpMethod: 'POST' }); return this; }
javascript
function (consumer_key, consumer_secret) { this.oauth = new OAuth.OAuth( 'https://query.yahooapis.com/v1/yql/', 'https://query.yahooapis.com/v1/yql/', consumer_key, //consumer key consumer_secret, //consumer secret '1.0', null, 'HMAC-SHA1' ); this.oauth.setClientOptions({ requestTokenHttpMethod: 'POST' }); return this; }
[ "function", "(", "consumer_key", ",", "consumer_secret", ")", "{", "this", ".", "oauth", "=", "new", "OAuth", ".", "OAuth", "(", "'https://query.yahooapis.com/v1/yql/'", ",", "'https://query.yahooapis.com/v1/yql/'", ",", "consumer_key", ",", "//consumer key", "consumer_secret", ",", "//consumer secret", "'1.0'", ",", "null", ",", "'HMAC-SHA1'", ")", ";", "this", ".", "oauth", ".", "setClientOptions", "(", "{", "requestTokenHttpMethod", ":", "'POST'", "}", ")", ";", "return", "this", ";", "}" ]
yql-node used to output only xml, now the formatAsJSON chainloader should help.
[ "yql", "-", "node", "used", "to", "output", "only", "xml", "now", "the", "formatAsJSON", "chainloader", "should", "help", "." ]
855f264e39b9a77475b54741b47bfcf5016cee7f
https://github.com/djordjelacmanovic/yql-node/blob/855f264e39b9a77475b54741b47bfcf5016cee7f/index.js#L8-L21
49,008
dominictarr/libnested
index.js
clone
function clone (obj) { if(!isObject(obj, true)) return obj var _obj _obj = Array.isArray(obj) ? [] : {} for(var k in obj) _obj[k] = clone(obj[k]) return _obj }
javascript
function clone (obj) { if(!isObject(obj, true)) return obj var _obj _obj = Array.isArray(obj) ? [] : {} for(var k in obj) _obj[k] = clone(obj[k]) return _obj }
[ "function", "clone", "(", "obj", ")", "{", "if", "(", "!", "isObject", "(", "obj", ",", "true", ")", ")", "return", "obj", "var", "_obj", "_obj", "=", "Array", ".", "isArray", "(", "obj", ")", "?", "[", "]", ":", "{", "}", "for", "(", "var", "k", "in", "obj", ")", "_obj", "[", "k", "]", "=", "clone", "(", "obj", "[", "k", "]", ")", "return", "_obj", "}" ]
note, cyclic objects are not supported. will cause an stack overflow.
[ "note", "cyclic", "objects", "are", "not", "supported", ".", "will", "cause", "an", "stack", "overflow", "." ]
06b06a22d968323ae619166e2078f955dc57ecbe
https://github.com/dominictarr/libnested/blob/06b06a22d968323ae619166e2078f955dc57ecbe/index.js#L86-L92
49,009
jeanamarante/catena
tasks/util/stream.js
iteratePipeFile
function iteratePipeFile () { if (!isIterating()) { return undefined; } let data = iterateData; let file = data.collection[data.i]; data.i++; if (data.i >= data.collection.length) { resetIterateData(); pipeLastFile(file); } else { pipeFile(file, iteratePipeFile); } }
javascript
function iteratePipeFile () { if (!isIterating()) { return undefined; } let data = iterateData; let file = data.collection[data.i]; data.i++; if (data.i >= data.collection.length) { resetIterateData(); pipeLastFile(file); } else { pipeFile(file, iteratePipeFile); } }
[ "function", "iteratePipeFile", "(", ")", "{", "if", "(", "!", "isIterating", "(", ")", ")", "{", "return", "undefined", ";", "}", "let", "data", "=", "iterateData", ";", "let", "file", "=", "data", ".", "collection", "[", "data", ".", "i", "]", ";", "data", ".", "i", "++", ";", "if", "(", "data", ".", "i", ">=", "data", ".", "collection", ".", "length", ")", "{", "resetIterateData", "(", ")", ";", "pipeLastFile", "(", "file", ")", ";", "}", "else", "{", "pipeFile", "(", "file", ",", "iteratePipeFile", ")", ";", "}", "}" ]
Recursively pipe all files. @function iteratePipeFile @api private
[ "Recursively", "pipe", "all", "files", "." ]
c7762332f71c0fd7cfafba8d1e3cd66053529954
https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/util/stream.js#L113-L127
49,010
jeanamarante/catena
tasks/util/stream.js
iterateWriteArray
function iterateWriteArray () { if (!isIterating()) { return undefined; } let data = iterateData; let content = data.collection[data.i]; data.i++; if (data.i >= data.collection.length) { resetIterateData(); writable.write(content, 'utf8', onWriteFinish); } else { writable.write(content, 'utf8', iterateWriteArray); } }
javascript
function iterateWriteArray () { if (!isIterating()) { return undefined; } let data = iterateData; let content = data.collection[data.i]; data.i++; if (data.i >= data.collection.length) { resetIterateData(); writable.write(content, 'utf8', onWriteFinish); } else { writable.write(content, 'utf8', iterateWriteArray); } }
[ "function", "iterateWriteArray", "(", ")", "{", "if", "(", "!", "isIterating", "(", ")", ")", "{", "return", "undefined", ";", "}", "let", "data", "=", "iterateData", ";", "let", "content", "=", "data", ".", "collection", "[", "data", ".", "i", "]", ";", "data", ".", "i", "++", ";", "if", "(", "data", ".", "i", ">=", "data", ".", "collection", ".", "length", ")", "{", "resetIterateData", "(", ")", ";", "writable", ".", "write", "(", "content", ",", "'utf8'", ",", "onWriteFinish", ")", ";", "}", "else", "{", "writable", ".", "write", "(", "content", ",", "'utf8'", ",", "iterateWriteArray", ")", ";", "}", "}" ]
Recursively write content in array. @function iterateWriteArray @api private
[ "Recursively", "write", "content", "in", "array", "." ]
c7762332f71c0fd7cfafba8d1e3cd66053529954
https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/util/stream.js#L136-L151
49,011
jeanamarante/catena
tasks/util/stream.js
iterateWriteLinkedList
function iterateWriteLinkedList () { if (!isIterating()) { return undefined; } let data = iterateData; let content = iterateData.item.content; data.item = data.item.next; if (data.item === null) { resetIterateData(); writable.write(content, 'utf8', onWriteFinish); } else { writable.write(content, 'utf8', iterateWriteLinkedList); } }
javascript
function iterateWriteLinkedList () { if (!isIterating()) { return undefined; } let data = iterateData; let content = iterateData.item.content; data.item = data.item.next; if (data.item === null) { resetIterateData(); writable.write(content, 'utf8', onWriteFinish); } else { writable.write(content, 'utf8', iterateWriteLinkedList); } }
[ "function", "iterateWriteLinkedList", "(", ")", "{", "if", "(", "!", "isIterating", "(", ")", ")", "{", "return", "undefined", ";", "}", "let", "data", "=", "iterateData", ";", "let", "content", "=", "iterateData", ".", "item", ".", "content", ";", "data", ".", "item", "=", "data", ".", "item", ".", "next", ";", "if", "(", "data", ".", "item", "===", "null", ")", "{", "resetIterateData", "(", ")", ";", "writable", ".", "write", "(", "content", ",", "'utf8'", ",", "onWriteFinish", ")", ";", "}", "else", "{", "writable", ".", "write", "(", "content", ",", "'utf8'", ",", "iterateWriteLinkedList", ")", ";", "}", "}" ]
Recursively write content in linked list. @function iterateWriteLinkedList @api private
[ "Recursively", "write", "content", "in", "linked", "list", "." ]
c7762332f71c0fd7cfafba8d1e3cd66053529954
https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/util/stream.js#L160-L175
49,012
jeanamarante/catena
tasks/util/stream.js
pipeFile
function pipeFile (file, endCallback) { testPipeFile(); testFunction(endCallback, 'endCallback'); let readable = fs.createReadStream(file); readableEndCallback = endCallback; readable.once('error', throwAsyncError); readable.once('close', onReadableClose); readable.pipe(writable, { end: false }); }
javascript
function pipeFile (file, endCallback) { testPipeFile(); testFunction(endCallback, 'endCallback'); let readable = fs.createReadStream(file); readableEndCallback = endCallback; readable.once('error', throwAsyncError); readable.once('close', onReadableClose); readable.pipe(writable, { end: false }); }
[ "function", "pipeFile", "(", "file", ",", "endCallback", ")", "{", "testPipeFile", "(", ")", ";", "testFunction", "(", "endCallback", ",", "'endCallback'", ")", ";", "let", "readable", "=", "fs", ".", "createReadStream", "(", "file", ")", ";", "readableEndCallback", "=", "endCallback", ";", "readable", ".", "once", "(", "'error'", ",", "throwAsyncError", ")", ";", "readable", ".", "once", "(", "'close'", ",", "onReadableClose", ")", ";", "readable", ".", "pipe", "(", "writable", ",", "{", "end", ":", "false", "}", ")", ";", "}" ]
Pipe file contents without ending WriteStream. @function pipeFile @param {String} file @param {Function} endCallback @api public
[ "Pipe", "file", "contents", "without", "ending", "WriteStream", "." ]
c7762332f71c0fd7cfafba8d1e3cd66053529954
https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/util/stream.js#L186-L198
49,013
jeanamarante/catena
tasks/util/stream.js
pipeFileArray
function pipeFileArray (arr) { testPipeFile(); // Just end WriteStream if no files need to be read to keep default pipe behavior. if (arr.length === 0) { writable.end(); } else { iterateData.collection = arr; iteratePipeFile(); } }
javascript
function pipeFileArray (arr) { testPipeFile(); // Just end WriteStream if no files need to be read to keep default pipe behavior. if (arr.length === 0) { writable.end(); } else { iterateData.collection = arr; iteratePipeFile(); } }
[ "function", "pipeFileArray", "(", "arr", ")", "{", "testPipeFile", "(", ")", ";", "// Just end WriteStream if no files need to be read to keep default pipe behavior.", "if", "(", "arr", ".", "length", "===", "0", ")", "{", "writable", ".", "end", "(", ")", ";", "}", "else", "{", "iterateData", ".", "collection", "=", "arr", ";", "iteratePipeFile", "(", ")", ";", "}", "}" ]
Pipe files recursively and then end WriteStream. @function pipeFileArray @param {Array} arr @api public
[ "Pipe", "files", "recursively", "and", "then", "end", "WriteStream", "." ]
c7762332f71c0fd7cfafba8d1e3cd66053529954
https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/util/stream.js#L208-L219
49,014
jeanamarante/catena
tasks/util/stream.js
pipeLastFile
function pipeLastFile (file) { testPipeFile(); let readable = fs.createReadStream(file); readable.once('error', throwAsyncError); readable.pipe(writable); }
javascript
function pipeLastFile (file) { testPipeFile(); let readable = fs.createReadStream(file); readable.once('error', throwAsyncError); readable.pipe(writable); }
[ "function", "pipeLastFile", "(", "file", ")", "{", "testPipeFile", "(", ")", ";", "let", "readable", "=", "fs", ".", "createReadStream", "(", "file", ")", ";", "readable", ".", "once", "(", "'error'", ",", "throwAsyncError", ")", ";", "readable", ".", "pipe", "(", "writable", ")", ";", "}" ]
Pipe file contents and then end WriteStream. @function pipeLastFile @param {String} file @api public
[ "Pipe", "file", "contents", "and", "then", "end", "WriteStream", "." ]
c7762332f71c0fd7cfafba8d1e3cd66053529954
https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/util/stream.js#L229-L237
49,015
observing/leverage
index.js
Leverage
function Leverage(client, sub, options) { if (!this) return new Leverage(client, sub, options); // // Flakey detection if we got a options argument or an actual Redis client. We // could do an instanceOf RedisClient check but I don't want to have Redis as // a dependency of this module. // if ('object' === typeof sub && !options && !sub.send_command) { options = sub; sub = null; } options = options || {}; // !IMPORTANT // // As the scripts are introduced to the `prototype` of our Leverage module we // want to make sure that we don't pollute this namespace to much. That's why // we've decided to move most of our internal logic in to a `._` private // object that contains most of our logic. This way we only have a small // number prototypes and properties that should not be overridden by scripts. // // !IMPORTANT this._ = Object.create(null, { // // The namespace is used to prefix all keys that are used by this module. // namespace: { value: options.namespace || 'leverage' }, // // Stores the SHA1 keys from the scripts that are added. // SHA1: { value: options.SHA1 || Object.create(null) }, // // Stores the scripts that we're currently using in Leverage // scripts: { value: Leverage.scripts.slice(), }, // // The amount of items we should log for our Pub/Sub. // backlog: { value: options.backlog || 100000 }, // // How many seconds should the item stay alive in our backlog. // expire: { value: options.expire || 1000 }, // // The pre-configured & authenticated Redis client that is used to send // commands and is loaded with the scripts. // client: { value: client }, // // Dedicated client that is used for subscribing to a given channel. // sub: { value: sub }, // // Introduce a bunch of private methods. // load: { value: Leverage.load.bind(this) }, prepare: { value: Leverage.prepare.bind(this) }, refresh: { value: Leverage.refresh.bind(this) }, seval: { value: Leverage.seval.bind(this) } }); // // Proxy all readyState changes to another event to make some of our internal // usage a bit easier. // this.on('readystatechange', function readystatechange(state) { debug('updated the readyState to %s', state); this.emit('readystate#'+ state); }); if (this._.client === this._.sub) { throw new Error('The pub and sub clients should separate connections'); } this._.load(); }
javascript
function Leverage(client, sub, options) { if (!this) return new Leverage(client, sub, options); // // Flakey detection if we got a options argument or an actual Redis client. We // could do an instanceOf RedisClient check but I don't want to have Redis as // a dependency of this module. // if ('object' === typeof sub && !options && !sub.send_command) { options = sub; sub = null; } options = options || {}; // !IMPORTANT // // As the scripts are introduced to the `prototype` of our Leverage module we // want to make sure that we don't pollute this namespace to much. That's why // we've decided to move most of our internal logic in to a `._` private // object that contains most of our logic. This way we only have a small // number prototypes and properties that should not be overridden by scripts. // // !IMPORTANT this._ = Object.create(null, { // // The namespace is used to prefix all keys that are used by this module. // namespace: { value: options.namespace || 'leverage' }, // // Stores the SHA1 keys from the scripts that are added. // SHA1: { value: options.SHA1 || Object.create(null) }, // // Stores the scripts that we're currently using in Leverage // scripts: { value: Leverage.scripts.slice(), }, // // The amount of items we should log for our Pub/Sub. // backlog: { value: options.backlog || 100000 }, // // How many seconds should the item stay alive in our backlog. // expire: { value: options.expire || 1000 }, // // The pre-configured & authenticated Redis client that is used to send // commands and is loaded with the scripts. // client: { value: client }, // // Dedicated client that is used for subscribing to a given channel. // sub: { value: sub }, // // Introduce a bunch of private methods. // load: { value: Leverage.load.bind(this) }, prepare: { value: Leverage.prepare.bind(this) }, refresh: { value: Leverage.refresh.bind(this) }, seval: { value: Leverage.seval.bind(this) } }); // // Proxy all readyState changes to another event to make some of our internal // usage a bit easier. // this.on('readystatechange', function readystatechange(state) { debug('updated the readyState to %s', state); this.emit('readystate#'+ state); }); if (this._.client === this._.sub) { throw new Error('The pub and sub clients should separate connections'); } this._.load(); }
[ "function", "Leverage", "(", "client", ",", "sub", ",", "options", ")", "{", "if", "(", "!", "this", ")", "return", "new", "Leverage", "(", "client", ",", "sub", ",", "options", ")", ";", "//", "// Flakey detection if we got a options argument or an actual Redis client. We", "// could do an instanceOf RedisClient check but I don't want to have Redis as", "// a dependency of this module.", "//", "if", "(", "'object'", "===", "typeof", "sub", "&&", "!", "options", "&&", "!", "sub", ".", "send_command", ")", "{", "options", "=", "sub", ";", "sub", "=", "null", ";", "}", "options", "=", "options", "||", "{", "}", ";", "// !IMPORTANT", "//", "// As the scripts are introduced to the `prototype` of our Leverage module we", "// want to make sure that we don't pollute this namespace to much. That's why", "// we've decided to move most of our internal logic in to a `._` private", "// object that contains most of our logic. This way we only have a small", "// number prototypes and properties that should not be overridden by scripts.", "//", "// !IMPORTANT", "this", ".", "_", "=", "Object", ".", "create", "(", "null", ",", "{", "//", "// The namespace is used to prefix all keys that are used by this module.", "//", "namespace", ":", "{", "value", ":", "options", ".", "namespace", "||", "'leverage'", "}", ",", "//", "// Stores the SHA1 keys from the scripts that are added.", "//", "SHA1", ":", "{", "value", ":", "options", ".", "SHA1", "||", "Object", ".", "create", "(", "null", ")", "}", ",", "//", "// Stores the scripts that we're currently using in Leverage", "//", "scripts", ":", "{", "value", ":", "Leverage", ".", "scripts", ".", "slice", "(", ")", ",", "}", ",", "//", "// The amount of items we should log for our Pub/Sub.", "//", "backlog", ":", "{", "value", ":", "options", ".", "backlog", "||", "100000", "}", ",", "//", "// How many seconds should the item stay alive in our backlog.", "//", "expire", ":", "{", "value", ":", "options", ".", "expire", "||", "1000", "}", ",", "//", "// The pre-configured & authenticated Redis client that is used to send", "// commands and is loaded with the scripts.", "//", "client", ":", "{", "value", ":", "client", "}", ",", "//", "// Dedicated client that is used for subscribing to a given channel.", "//", "sub", ":", "{", "value", ":", "sub", "}", ",", "//", "// Introduce a bunch of private methods.", "//", "load", ":", "{", "value", ":", "Leverage", ".", "load", ".", "bind", "(", "this", ")", "}", ",", "prepare", ":", "{", "value", ":", "Leverage", ".", "prepare", ".", "bind", "(", "this", ")", "}", ",", "refresh", ":", "{", "value", ":", "Leverage", ".", "refresh", ".", "bind", "(", "this", ")", "}", ",", "seval", ":", "{", "value", ":", "Leverage", ".", "seval", ".", "bind", "(", "this", ")", "}", "}", ")", ";", "//", "// Proxy all readyState changes to another event to make some of our internal", "// usage a bit easier.", "//", "this", ".", "on", "(", "'readystatechange'", ",", "function", "readystatechange", "(", "state", ")", "{", "debug", "(", "'updated the readyState to %s'", ",", "state", ")", ";", "this", ".", "emit", "(", "'readystate#'", "+", "state", ")", ";", "}", ")", ";", "if", "(", "this", ".", "_", ".", "client", "===", "this", ".", "_", ".", "sub", ")", "{", "throw", "new", "Error", "(", "'The pub and sub clients should separate connections'", ")", ";", "}", "this", ".", "_", ".", "load", "(", ")", ";", "}" ]
Leverage the awesome power of Lua scripting. @constructor @param {Redis} client Redis client to publish the messages over. @param {Redis} sub Redis client to subscribe with. @param {Object} options Options.
[ "Leverage", "the", "awesome", "power", "of", "Lua", "scripting", "." ]
8a5896d9bdee81542a32e68053490224e488db3e
https://github.com/observing/leverage/blob/8a5896d9bdee81542a32e68053490224e488db3e/index.js#L27-L126
49,016
observing/leverage
index.js
failed
function failed(err) { leverage.emit(channel +'::error', err); if (!bailout) return debug('received an error without bailout mode, gnoring it', err.message); leverage.emit(channel +'::bailout', err); leverage.unsubscribe(channel); }
javascript
function failed(err) { leverage.emit(channel +'::error', err); if (!bailout) return debug('received an error without bailout mode, gnoring it', err.message); leverage.emit(channel +'::bailout', err); leverage.unsubscribe(channel); }
[ "function", "failed", "(", "err", ")", "{", "leverage", ".", "emit", "(", "channel", "+", "'::error'", ",", "err", ")", ";", "if", "(", "!", "bailout", ")", "return", "debug", "(", "'received an error without bailout mode, gnoring it'", ",", "err", ".", "message", ")", ";", "leverage", ".", "emit", "(", "channel", "+", "'::bailout'", ",", "err", ")", ";", "leverage", ".", "unsubscribe", "(", "channel", ")", ";", "}" ]
Bailout and cancel all the things @param {Error} Err The error that occurred @api private
[ "Bailout", "and", "cancel", "all", "the", "things" ]
8a5896d9bdee81542a32e68053490224e488db3e
https://github.com/observing/leverage/blob/8a5896d9bdee81542a32e68053490224e488db3e/index.js#L215-L222
49,017
observing/leverage
index.js
parse
function parse(packet) { if ('object' === typeof packet) return packet; try { return JSON.parse(packet); } catch (e) { return failed(e); } }
javascript
function parse(packet) { if ('object' === typeof packet) return packet; try { return JSON.parse(packet); } catch (e) { return failed(e); } }
[ "function", "parse", "(", "packet", ")", "{", "if", "(", "'object'", "===", "typeof", "packet", ")", "return", "packet", ";", "try", "{", "return", "JSON", ".", "parse", "(", "packet", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "failed", "(", "e", ")", ";", "}", "}" ]
Parse the packet. @param {String} packet The encoded message. @returns {Object} @api private
[ "Parse", "the", "packet", "." ]
8a5896d9bdee81542a32e68053490224e488db3e
https://github.com/observing/leverage/blob/8a5896d9bdee81542a32e68053490224e488db3e/index.js#L241-L246
49,018
observing/leverage
index.js
flush
function flush() { if (queue.length) { // // We might want to indicate that these are already queued, so we don't // fetch data again. // queue.splice(0).sort(function sort(a, b) { return a.id - b.id; }).forEach(onmessage); } }
javascript
function flush() { if (queue.length) { // // We might want to indicate that these are already queued, so we don't // fetch data again. // queue.splice(0).sort(function sort(a, b) { return a.id - b.id; }).forEach(onmessage); } }
[ "function", "flush", "(", ")", "{", "if", "(", "queue", ".", "length", ")", "{", "//", "// We might want to indicate that these are already queued, so we don't", "// fetch data again.", "//", "queue", ".", "splice", "(", "0", ")", ".", "sort", "(", "function", "sort", "(", "a", ",", "b", ")", "{", "return", "a", ".", "id", "-", "b", ".", "id", ";", "}", ")", ".", "forEach", "(", "onmessage", ")", ";", "}", "}" ]
We have messages queued, now that we've successfully send the message we probably want to try and resend all of these messages and hope that we we've restored the reliability again. @api private
[ "We", "have", "messages", "queued", "now", "that", "we", "ve", "successfully", "send", "the", "message", "we", "probably", "want", "to", "try", "and", "resend", "all", "of", "these", "messages", "and", "hope", "that", "we", "we", "ve", "restored", "the", "reliability", "again", "." ]
8a5896d9bdee81542a32e68053490224e488db3e
https://github.com/observing/leverage/blob/8a5896d9bdee81542a32e68053490224e488db3e/index.js#L265-L275
49,019
observing/leverage
index.js
allowed
function allowed(packet) { if (!packet) return false; if (uv.position === 'inactive' || (!uv.received(packet.id) && ordered)) { queue.push(packet); return false; } return true; }
javascript
function allowed(packet) { if (!packet) return false; if (uv.position === 'inactive' || (!uv.received(packet.id) && ordered)) { queue.push(packet); return false; } return true; }
[ "function", "allowed", "(", "packet", ")", "{", "if", "(", "!", "packet", ")", "return", "false", ";", "if", "(", "uv", ".", "position", "===", "'inactive'", "||", "(", "!", "uv", ".", "received", "(", "packet", ".", "id", ")", "&&", "ordered", ")", ")", "{", "queue", ".", "push", "(", "packet", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Checks if we are allowed to emit the message. @param {Object} packet The message packet. @api private
[ "Checks", "if", "we", "are", "allowed", "to", "emit", "the", "message", "." ]
8a5896d9bdee81542a32e68053490224e488db3e
https://github.com/observing/leverage/blob/8a5896d9bdee81542a32e68053490224e488db3e/index.js#L283-L292
49,020
observing/leverage
index.js
onmessage
function onmessage(packet) { if (arguments.length === 2) packet = arguments[1]; packet = parse(packet); if (allowed(packet)) emit(packet); }
javascript
function onmessage(packet) { if (arguments.length === 2) packet = arguments[1]; packet = parse(packet); if (allowed(packet)) emit(packet); }
[ "function", "onmessage", "(", "packet", ")", "{", "if", "(", "arguments", ".", "length", "===", "2", ")", "packet", "=", "arguments", "[", "1", "]", ";", "packet", "=", "parse", "(", "packet", ")", ";", "if", "(", "allowed", "(", "packet", ")", ")", "emit", "(", "packet", ")", ";", "}" ]
Handle incomming messages. @param {String} packet The message @api private
[ "Handle", "incomming", "messages", "." ]
8a5896d9bdee81542a32e68053490224e488db3e
https://github.com/observing/leverage/blob/8a5896d9bdee81542a32e68053490224e488db3e/index.js#L300-L305
49,021
meetings/gearsloth
lib/adapters/composite.js
initialize
function initialize(config, callback, config_helper) { config_helper = config_helper || require('../config/index'); if(!checkConfSanity(config)) { callback(new Error('conf.dbopt is not sane, can\'t initialize composite adapter')); return; } populateDatabasesArray(config, config_helper, function(err, databases) { if(err) return callback(err); var adapter = new Compositeadapter(config, databases); callback(null, adapter); }); }
javascript
function initialize(config, callback, config_helper) { config_helper = config_helper || require('../config/index'); if(!checkConfSanity(config)) { callback(new Error('conf.dbopt is not sane, can\'t initialize composite adapter')); return; } populateDatabasesArray(config, config_helper, function(err, databases) { if(err) return callback(err); var adapter = new Compositeadapter(config, databases); callback(null, adapter); }); }
[ "function", "initialize", "(", "config", ",", "callback", ",", "config_helper", ")", "{", "config_helper", "=", "config_helper", "||", "require", "(", "'../config/index'", ")", ";", "if", "(", "!", "checkConfSanity", "(", "config", ")", ")", "{", "callback", "(", "new", "Error", "(", "'conf.dbopt is not sane, can\\'t initialize composite adapter'", ")", ")", ";", "return", ";", "}", "populateDatabasesArray", "(", "config", ",", "config_helper", ",", "function", "(", "err", ",", "databases", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "var", "adapter", "=", "new", "Compositeadapter", "(", "config", ",", "databases", ")", ";", "callback", "(", "null", ",", "adapter", ")", ";", "}", ")", ";", "}" ]
A composite adapter that consists of multiple adapters. The adapters may be of a different type. `config.dbopt` should be an array containing JSON-objects that will be used to initialize the individual adapters. This function uses config/index.js's initializeDb-function to initialize the adapters. @param {Object} config - Configuration object as passed from config.js @param {Function} callback @param {Object} config_helper - A helper to use for initializing adapters (for testing)
[ "A", "composite", "adapter", "that", "consists", "of", "multiple", "adapters", ".", "The", "adapters", "may", "be", "of", "a", "different", "type", "." ]
21d07729d6197bdbea515f32922896e3ae485d46
https://github.com/meetings/gearsloth/blob/21d07729d6197bdbea515f32922896e3ae485d46/lib/adapters/composite.js#L25-L39
49,022
veyo-care/deep-sync
src/index.js
deepSync
function deepSync(target, source, overwrite) { if (!(((target) && (typeof target === 'object')) && ((source) && (typeof source === 'object'))) || (source instanceof Array) || (target instanceof Array)) { throw new TypeError('Source and Target must be objects.'); } let sourceKeys = new Set(); let temp = {}; if (target && typeof target === 'object') { Object.keys(target).forEach(function (key) { temp[key] = target[key]; }) } Object.keys(source).forEach(function (key) { sourceKeys.add(key); if (typeof source[key] !== 'object' || !source[key]) { // keep old value if the key can be found if (target[key]) { if (overwrite === true) { temp[key] = source[key]; } else { temp[key] = target[key]; } } else { temp[key] = source[key]; } } else { if (!target[key]) { temp[key] = source[key]; } else { temp[key] = deepSync(target[key], source[key], overwrite); } } }); // remove keys that are not present in the sync source for (let targetKey in temp) { if (!sourceKeys.has(targetKey)) { delete temp[targetKey]; } } return temp; }
javascript
function deepSync(target, source, overwrite) { if (!(((target) && (typeof target === 'object')) && ((source) && (typeof source === 'object'))) || (source instanceof Array) || (target instanceof Array)) { throw new TypeError('Source and Target must be objects.'); } let sourceKeys = new Set(); let temp = {}; if (target && typeof target === 'object') { Object.keys(target).forEach(function (key) { temp[key] = target[key]; }) } Object.keys(source).forEach(function (key) { sourceKeys.add(key); if (typeof source[key] !== 'object' || !source[key]) { // keep old value if the key can be found if (target[key]) { if (overwrite === true) { temp[key] = source[key]; } else { temp[key] = target[key]; } } else { temp[key] = source[key]; } } else { if (!target[key]) { temp[key] = source[key]; } else { temp[key] = deepSync(target[key], source[key], overwrite); } } }); // remove keys that are not present in the sync source for (let targetKey in temp) { if (!sourceKeys.has(targetKey)) { delete temp[targetKey]; } } return temp; }
[ "function", "deepSync", "(", "target", ",", "source", ",", "overwrite", ")", "{", "if", "(", "!", "(", "(", "(", "target", ")", "&&", "(", "typeof", "target", "===", "'object'", ")", ")", "&&", "(", "(", "source", ")", "&&", "(", "typeof", "source", "===", "'object'", ")", ")", ")", "||", "(", "source", "instanceof", "Array", ")", "||", "(", "target", "instanceof", "Array", ")", ")", "{", "throw", "new", "TypeError", "(", "'Source and Target must be objects.'", ")", ";", "}", "let", "sourceKeys", "=", "new", "Set", "(", ")", ";", "let", "temp", "=", "{", "}", ";", "if", "(", "target", "&&", "typeof", "target", "===", "'object'", ")", "{", "Object", ".", "keys", "(", "target", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "temp", "[", "key", "]", "=", "target", "[", "key", "]", ";", "}", ")", "}", "Object", ".", "keys", "(", "source", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "sourceKeys", ".", "add", "(", "key", ")", ";", "if", "(", "typeof", "source", "[", "key", "]", "!==", "'object'", "||", "!", "source", "[", "key", "]", ")", "{", "// keep old value if the key can be found", "if", "(", "target", "[", "key", "]", ")", "{", "if", "(", "overwrite", "===", "true", ")", "{", "temp", "[", "key", "]", "=", "source", "[", "key", "]", ";", "}", "else", "{", "temp", "[", "key", "]", "=", "target", "[", "key", "]", ";", "}", "}", "else", "{", "temp", "[", "key", "]", "=", "source", "[", "key", "]", ";", "}", "}", "else", "{", "if", "(", "!", "target", "[", "key", "]", ")", "{", "temp", "[", "key", "]", "=", "source", "[", "key", "]", ";", "}", "else", "{", "temp", "[", "key", "]", "=", "deepSync", "(", "target", "[", "key", "]", ",", "source", "[", "key", "]", ",", "overwrite", ")", ";", "}", "}", "}", ")", ";", "// remove keys that are not present in the sync source", "for", "(", "let", "targetKey", "in", "temp", ")", "{", "if", "(", "!", "sourceKeys", ".", "has", "(", "targetKey", ")", ")", "{", "delete", "temp", "[", "targetKey", "]", ";", "}", "}", "return", "temp", ";", "}" ]
Recursively synchronizes two JS objects where the target becomes the source, without changing the targets values for the keys that is has in common with the source. Does not work with arrays for obvious reasons. @param target - the object to be synchronized @param source - the object to sync data from @param overwrite - overwrites existing keys if true @returns {{}}
[ "Recursively", "synchronizes", "two", "JS", "objects", "where", "the", "target", "becomes", "the", "source", "without", "changing", "the", "targets", "values", "for", "the", "keys", "that", "is", "has", "in", "common", "with", "the", "source", "." ]
cd385f22cfa08613ee0f673904dcc17b94b2c6fd
https://github.com/veyo-care/deep-sync/blob/cd385f22cfa08613ee0f673904dcc17b94b2c6fd/src/index.js#L16-L78
49,023
boylesoftware/x2node-patches
lib/record-patch-builder.js
equalSimpleArrays
function equalSimpleArrays(arr1, arr2) { if (arr1 && (arr1.length > 0)) return ( arr2 && (arr2.length === arr1.length) && arr2.every((v, i) => (v === arr1[i])) ); return (!arr2 || (arr2.length === 0)); }
javascript
function equalSimpleArrays(arr1, arr2) { if (arr1 && (arr1.length > 0)) return ( arr2 && (arr2.length === arr1.length) && arr2.every((v, i) => (v === arr1[i])) ); return (!arr2 || (arr2.length === 0)); }
[ "function", "equalSimpleArrays", "(", "arr1", ",", "arr2", ")", "{", "if", "(", "arr1", "&&", "(", "arr1", ".", "length", ">", "0", ")", ")", "return", "(", "arr2", "&&", "(", "arr2", ".", "length", "===", "arr1", ".", "length", ")", "&&", "arr2", ".", "every", "(", "(", "v", ",", "i", ")", "=>", "(", "v", "===", "arr1", "[", "i", "]", ")", ")", ")", ";", "return", "(", "!", "arr2", "||", "(", "arr2", ".", "length", "===", "0", ")", ")", ";", "}" ]
Test if two simple value arrays are equal. @private @param {?Array} arr1 Array 1. @param {?Array} arr2 Array 2. @returns {boolean} <code>true</code> if considered equal.
[ "Test", "if", "two", "simple", "value", "arrays", "are", "equal", "." ]
59debdb270c899bcca3f330217b68e2f746d9646
https://github.com/boylesoftware/x2node-patches/blob/59debdb270c899bcca3f330217b68e2f746d9646/lib/record-patch-builder.js#L49-L59
49,024
boylesoftware/x2node-patches
lib/record-patch-builder.js
equalSimpleMaps
function equalSimpleMaps(map1, map2) { const keys1 = (map1 && Object.keys(map1)); if (map1 && (keys1.length > 0)) { const keys2 = (map2 && Object.keys(map2)); return ( keys2 && (keys2.length === keys1.length) && keys2.every(k => (map2[k] === map1[k])) ); } return (!map2 || (Object.keys(map2).length === 0)); }
javascript
function equalSimpleMaps(map1, map2) { const keys1 = (map1 && Object.keys(map1)); if (map1 && (keys1.length > 0)) { const keys2 = (map2 && Object.keys(map2)); return ( keys2 && (keys2.length === keys1.length) && keys2.every(k => (map2[k] === map1[k])) ); } return (!map2 || (Object.keys(map2).length === 0)); }
[ "function", "equalSimpleMaps", "(", "map1", ",", "map2", ")", "{", "const", "keys1", "=", "(", "map1", "&&", "Object", ".", "keys", "(", "map1", ")", ")", ";", "if", "(", "map1", "&&", "(", "keys1", ".", "length", ">", "0", ")", ")", "{", "const", "keys2", "=", "(", "map2", "&&", "Object", ".", "keys", "(", "map2", ")", ")", ";", "return", "(", "keys2", "&&", "(", "keys2", ".", "length", "===", "keys1", ".", "length", ")", "&&", "keys2", ".", "every", "(", "k", "=>", "(", "map2", "[", "k", "]", "===", "map1", "[", "k", "]", ")", ")", ")", ";", "}", "return", "(", "!", "map2", "||", "(", "Object", ".", "keys", "(", "map2", ")", ".", "length", "===", "0", ")", ")", ";", "}" ]
Test if two simple value maps are equal. @private @param {?Object} map1 Map 1. @param {?Object} map2 Map 2. @returns {boolean} <code>true</code> if considered equal.
[ "Test", "if", "two", "simple", "value", "maps", "are", "equal", "." ]
59debdb270c899bcca3f330217b68e2f746d9646
https://github.com/boylesoftware/x2node-patches/blob/59debdb270c899bcca3f330217b68e2f746d9646/lib/record-patch-builder.js#L69-L82
49,025
boylesoftware/x2node-patches
lib/record-patch-builder.js
needsAdd
function needsAdd(ptr, record, value) { const propDesc = ptr.propDesc; if (propDesc.isArray()) { if (ptr.collectionElement) return true; if (propDesc.scalarValueType === 'object') return !equalObjectArrays(/*ptr.getValue(record), value*/); return !equalSimpleArrays(ptr.getValue(record), value); } if (propDesc.isMap() && !ptr.collectionElement) { if (propDesc.scalarValueType === 'object') return !equalObjectMaps(/*ptr.getValue(record), value*/); return !equalSimpleMaps(ptr.getValue(record), value); } if (propDesc.scalarValueType === 'object') return !equalObjects(/*ptr.getValue(record), value*/); return (ptr.getValue(record) !== value); }
javascript
function needsAdd(ptr, record, value) { const propDesc = ptr.propDesc; if (propDesc.isArray()) { if (ptr.collectionElement) return true; if (propDesc.scalarValueType === 'object') return !equalObjectArrays(/*ptr.getValue(record), value*/); return !equalSimpleArrays(ptr.getValue(record), value); } if (propDesc.isMap() && !ptr.collectionElement) { if (propDesc.scalarValueType === 'object') return !equalObjectMaps(/*ptr.getValue(record), value*/); return !equalSimpleMaps(ptr.getValue(record), value); } if (propDesc.scalarValueType === 'object') return !equalObjects(/*ptr.getValue(record), value*/); return (ptr.getValue(record) !== value); }
[ "function", "needsAdd", "(", "ptr", ",", "record", ",", "value", ")", "{", "const", "propDesc", "=", "ptr", ".", "propDesc", ";", "if", "(", "propDesc", ".", "isArray", "(", ")", ")", "{", "if", "(", "ptr", ".", "collectionElement", ")", "return", "true", ";", "if", "(", "propDesc", ".", "scalarValueType", "===", "'object'", ")", "return", "!", "equalObjectArrays", "(", "/*ptr.getValue(record), value*/", ")", ";", "return", "!", "equalSimpleArrays", "(", "ptr", ".", "getValue", "(", "record", ")", ",", "value", ")", ";", "}", "if", "(", "propDesc", ".", "isMap", "(", ")", "&&", "!", "ptr", ".", "collectionElement", ")", "{", "if", "(", "propDesc", ".", "scalarValueType", "===", "'object'", ")", "return", "!", "equalObjectMaps", "(", "/*ptr.getValue(record), value*/", ")", ";", "return", "!", "equalSimpleMaps", "(", "ptr", ".", "getValue", "(", "record", ")", ",", "value", ")", ";", "}", "if", "(", "propDesc", ".", "scalarValueType", "===", "'object'", ")", "return", "!", "equalObjects", "(", "/*ptr.getValue(record), value*/", ")", ";", "return", "(", "ptr", ".", "getValue", "(", "record", ")", "!==", "value", ")", ";", "}" ]
Tell if anything needs to be done to "add" the specified value at the specified by the pointer location in the specified record. @private @param {module:x2node-pointers~RecordElementPointer} ptr The pointer. @param {Object} record The record. @param {*} value The value. @returns {boolean} <code>true</code> if "add" patch operation would change the record.
[ "Tell", "if", "anything", "needs", "to", "be", "done", "to", "add", "the", "specified", "value", "at", "the", "specified", "by", "the", "pointer", "location", "in", "the", "specified", "record", "." ]
59debdb270c899bcca3f330217b68e2f746d9646
https://github.com/boylesoftware/x2node-patches/blob/59debdb270c899bcca3f330217b68e2f746d9646/lib/record-patch-builder.js#L137-L159
49,026
boylesoftware/x2node-patches
lib/record-patch-builder.js
build
function build(recordTypes, recordTypeName, patch) { // get the record type descriptor if (!recordTypes.hasRecordType(recordTypeName)) throw new common.X2UsageError( `Unknown record type ${recordTypeName}.`); const recordTypeDesc = recordTypes.getRecordTypeDesc(recordTypeName); // make sure the patch spec is an array if (!Array.isArray(patch)) throw new common.X2SyntaxError('Patch specification is not an array.'); // process patch operations const involvedPropPaths = new Set(); const updatedPropPaths = new Set(); const patchOps = patch.map((patchOpDef, opInd) => parsePatchOperation( recordTypes, recordTypeDesc, patchOpDef, opInd, involvedPropPaths, updatedPropPaths)); // return the patch object return new RecordPatch(patchOps, involvedPropPaths, updatedPropPaths); }
javascript
function build(recordTypes, recordTypeName, patch) { // get the record type descriptor if (!recordTypes.hasRecordType(recordTypeName)) throw new common.X2UsageError( `Unknown record type ${recordTypeName}.`); const recordTypeDesc = recordTypes.getRecordTypeDesc(recordTypeName); // make sure the patch spec is an array if (!Array.isArray(patch)) throw new common.X2SyntaxError('Patch specification is not an array.'); // process patch operations const involvedPropPaths = new Set(); const updatedPropPaths = new Set(); const patchOps = patch.map((patchOpDef, opInd) => parsePatchOperation( recordTypes, recordTypeDesc, patchOpDef, opInd, involvedPropPaths, updatedPropPaths)); // return the patch object return new RecordPatch(patchOps, involvedPropPaths, updatedPropPaths); }
[ "function", "build", "(", "recordTypes", ",", "recordTypeName", ",", "patch", ")", "{", "// get the record type descriptor", "if", "(", "!", "recordTypes", ".", "hasRecordType", "(", "recordTypeName", ")", ")", "throw", "new", "common", ".", "X2UsageError", "(", "`", "${", "recordTypeName", "}", "`", ")", ";", "const", "recordTypeDesc", "=", "recordTypes", ".", "getRecordTypeDesc", "(", "recordTypeName", ")", ";", "// make sure the patch spec is an array", "if", "(", "!", "Array", ".", "isArray", "(", "patch", ")", ")", "throw", "new", "common", ".", "X2SyntaxError", "(", "'Patch specification is not an array.'", ")", ";", "// process patch operations", "const", "involvedPropPaths", "=", "new", "Set", "(", ")", ";", "const", "updatedPropPaths", "=", "new", "Set", "(", ")", ";", "const", "patchOps", "=", "patch", ".", "map", "(", "(", "patchOpDef", ",", "opInd", ")", "=>", "parsePatchOperation", "(", "recordTypes", ",", "recordTypeDesc", ",", "patchOpDef", ",", "opInd", ",", "involvedPropPaths", ",", "updatedPropPaths", ")", ")", ";", "// return the patch object", "return", "new", "RecordPatch", "(", "patchOps", ",", "involvedPropPaths", ",", "updatedPropPaths", ")", ";", "}" ]
Build record patch object from JSON Patch specification. @function module:x2node-patches.build @param {module:x2node-records~RecordTypesLibrary} recordTypes Record types library. @param {string} recordTypeName Name of the record type, against records of which the patch will be applied. @param {Array.<Object>} patch RFC 6902 JSON patch specification. @returns {module:x2node-patches~RecordPatch} The patch object that can be used to apply the patch to records. @throws {module:x2node-common.X2UsageError} If the provided record type name is invalid. @throws {module:x2node-common.X2SyntaxError} If the provided patch specification is invalid.
[ "Build", "record", "patch", "object", "from", "JSON", "Patch", "specification", "." ]
59debdb270c899bcca3f330217b68e2f746d9646
https://github.com/boylesoftware/x2node-patches/blob/59debdb270c899bcca3f330217b68e2f746d9646/lib/record-patch-builder.js#L605-L626
49,027
boylesoftware/x2node-patches
lib/record-patch-builder.js
buildMerge
function buildMerge(recordTypes, recordTypeName, mergePatch) { // only object merge patches are supported if (((typeof mergePatch) !== 'object') || (mergePatch === null)) throw new common.X2SyntaxError('Merge patch must be an object.'); // build JSON patch const jsonPatch = new Array(); buildMergeLevel('', mergePatch, jsonPatch); // build and return the record patch return build(recordTypes, recordTypeName, jsonPatch); }
javascript
function buildMerge(recordTypes, recordTypeName, mergePatch) { // only object merge patches are supported if (((typeof mergePatch) !== 'object') || (mergePatch === null)) throw new common.X2SyntaxError('Merge patch must be an object.'); // build JSON patch const jsonPatch = new Array(); buildMergeLevel('', mergePatch, jsonPatch); // build and return the record patch return build(recordTypes, recordTypeName, jsonPatch); }
[ "function", "buildMerge", "(", "recordTypes", ",", "recordTypeName", ",", "mergePatch", ")", "{", "// only object merge patches are supported", "if", "(", "(", "(", "typeof", "mergePatch", ")", "!==", "'object'", ")", "||", "(", "mergePatch", "===", "null", ")", ")", "throw", "new", "common", ".", "X2SyntaxError", "(", "'Merge patch must be an object.'", ")", ";", "// build JSON patch", "const", "jsonPatch", "=", "new", "Array", "(", ")", ";", "buildMergeLevel", "(", "''", ",", "mergePatch", ",", "jsonPatch", ")", ";", "// build and return the record patch", "return", "build", "(", "recordTypes", ",", "recordTypeName", ",", "jsonPatch", ")", ";", "}" ]
Build record patch object from Merge Patch specification. @function module:x2node-patches.buildMerge @param {module:x2node-records~RecordTypesLibrary} recordTypes Record types library. @param {string} recordTypeName Name of the record type, against records of which the patch will be applied. @param {Object} mergePatch RFC 7396 merge patch specification. @returns {module:x2node-patches~RecordPatch} The patch object that can be used to apply the patch to records. @throws {module:x2node-common.X2UsageError} If the provided record type name is invalid. @throws {module:x2node-common.X2SyntaxError} If the provided patch specification is invalid.
[ "Build", "record", "patch", "object", "from", "Merge", "Patch", "specification", "." ]
59debdb270c899bcca3f330217b68e2f746d9646
https://github.com/boylesoftware/x2node-patches/blob/59debdb270c899bcca3f330217b68e2f746d9646/lib/record-patch-builder.js#L644-L656
49,028
boylesoftware/x2node-patches
lib/record-patch-builder.js
buildMergeLevel
function buildMergeLevel(basePtr, levelMergePatch, jsonPatch) { for (let propName in levelMergePatch) { const mergeVal = levelMergePatch[propName]; const path = basePtr + '/' + propName; if (mergeVal === null) { jsonPatch.push({ op: 'remove', path: path }); } else if (Array.isArray(mergeVal)) { jsonPatch.push({ op: 'replace', path: path, value: mergeVal }); } else if ((typeof mergeVal) === 'object') { const nestedPatch = new Array(); buildMergeLevel(path, mergeVal, nestedPatch); jsonPatch.push({ op: 'merge', path: path, value: mergeVal, patch: nestedPatch }); } else { jsonPatch.push({ op: 'replace', path: path, value: mergeVal }); } } }
javascript
function buildMergeLevel(basePtr, levelMergePatch, jsonPatch) { for (let propName in levelMergePatch) { const mergeVal = levelMergePatch[propName]; const path = basePtr + '/' + propName; if (mergeVal === null) { jsonPatch.push({ op: 'remove', path: path }); } else if (Array.isArray(mergeVal)) { jsonPatch.push({ op: 'replace', path: path, value: mergeVal }); } else if ((typeof mergeVal) === 'object') { const nestedPatch = new Array(); buildMergeLevel(path, mergeVal, nestedPatch); jsonPatch.push({ op: 'merge', path: path, value: mergeVal, patch: nestedPatch }); } else { jsonPatch.push({ op: 'replace', path: path, value: mergeVal }); } } }
[ "function", "buildMergeLevel", "(", "basePtr", ",", "levelMergePatch", ",", "jsonPatch", ")", "{", "for", "(", "let", "propName", "in", "levelMergePatch", ")", "{", "const", "mergeVal", "=", "levelMergePatch", "[", "propName", "]", ";", "const", "path", "=", "basePtr", "+", "'/'", "+", "propName", ";", "if", "(", "mergeVal", "===", "null", ")", "{", "jsonPatch", ".", "push", "(", "{", "op", ":", "'remove'", ",", "path", ":", "path", "}", ")", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "mergeVal", ")", ")", "{", "jsonPatch", ".", "push", "(", "{", "op", ":", "'replace'", ",", "path", ":", "path", ",", "value", ":", "mergeVal", "}", ")", ";", "}", "else", "if", "(", "(", "typeof", "mergeVal", ")", "===", "'object'", ")", "{", "const", "nestedPatch", "=", "new", "Array", "(", ")", ";", "buildMergeLevel", "(", "path", ",", "mergeVal", ",", "nestedPatch", ")", ";", "jsonPatch", ".", "push", "(", "{", "op", ":", "'merge'", ",", "path", ":", "path", ",", "value", ":", "mergeVal", ",", "patch", ":", "nestedPatch", "}", ")", ";", "}", "else", "{", "jsonPatch", ".", "push", "(", "{", "op", ":", "'replace'", ",", "path", ":", "path", ",", "value", ":", "mergeVal", "}", ")", ";", "}", "}", "}" ]
Recusrively build JSON patch from Merge patch's nesting level. @private @param {string} basePtr Base JSON pointer for the nesting level. @param {Object} levelMergePatch Nested Merge patch for the level. @param {Array.<Object>} jsonPatch Resulting JSON patch specification array.
[ "Recusrively", "build", "JSON", "patch", "from", "Merge", "patch", "s", "nesting", "level", "." ]
59debdb270c899bcca3f330217b68e2f746d9646
https://github.com/boylesoftware/x2node-patches/blob/59debdb270c899bcca3f330217b68e2f746d9646/lib/record-patch-builder.js#L666-L699
49,029
boylesoftware/x2node-patches
lib/record-patch-builder.js
resolvePropPointer
function resolvePropPointer(recordTypeDesc, propPointer, noDash, ptrUse) { // parse the pointer const ptr = pointers.parse(recordTypeDesc, propPointer, noDash); // check if top pointer if (ptr.isRoot()) throw new common.X2SyntaxError( 'Patch operations involving top records as a whole are not' + ' allowed.'); // check the use if (ptrUse === PTRUSE.SET) { if (!ptr.propDesc.modifiable) throw new common.X2SyntaxError( `May not update non-modifiable property ${ptr.propPath}.`); } else if (ptrUse === PTRUSE.ERASE) { if ((ptr.propDesc.isScalar() || !ptr.collectionElement) && !ptr.propDesc.optional) throw new common.X2SyntaxError( `May not remove a required property ${ptr.propPath}.`); } // return the resolved pointer return ptr; }
javascript
function resolvePropPointer(recordTypeDesc, propPointer, noDash, ptrUse) { // parse the pointer const ptr = pointers.parse(recordTypeDesc, propPointer, noDash); // check if top pointer if (ptr.isRoot()) throw new common.X2SyntaxError( 'Patch operations involving top records as a whole are not' + ' allowed.'); // check the use if (ptrUse === PTRUSE.SET) { if (!ptr.propDesc.modifiable) throw new common.X2SyntaxError( `May not update non-modifiable property ${ptr.propPath}.`); } else if (ptrUse === PTRUSE.ERASE) { if ((ptr.propDesc.isScalar() || !ptr.collectionElement) && !ptr.propDesc.optional) throw new common.X2SyntaxError( `May not remove a required property ${ptr.propPath}.`); } // return the resolved pointer return ptr; }
[ "function", "resolvePropPointer", "(", "recordTypeDesc", ",", "propPointer", ",", "noDash", ",", "ptrUse", ")", "{", "// parse the pointer", "const", "ptr", "=", "pointers", ".", "parse", "(", "recordTypeDesc", ",", "propPointer", ",", "noDash", ")", ";", "// check if top pointer", "if", "(", "ptr", ".", "isRoot", "(", ")", ")", "throw", "new", "common", ".", "X2SyntaxError", "(", "'Patch operations involving top records as a whole are not'", "+", "' allowed.'", ")", ";", "// check the use", "if", "(", "ptrUse", "===", "PTRUSE", ".", "SET", ")", "{", "if", "(", "!", "ptr", ".", "propDesc", ".", "modifiable", ")", "throw", "new", "common", ".", "X2SyntaxError", "(", "`", "${", "ptr", ".", "propPath", "}", "`", ")", ";", "}", "else", "if", "(", "ptrUse", "===", "PTRUSE", ".", "ERASE", ")", "{", "if", "(", "(", "ptr", ".", "propDesc", ".", "isScalar", "(", ")", "||", "!", "ptr", ".", "collectionElement", ")", "&&", "!", "ptr", ".", "propDesc", ".", "optional", ")", "throw", "new", "common", ".", "X2SyntaxError", "(", "`", "${", "ptr", ".", "propPath", "}", "`", ")", ";", "}", "// return the resolved pointer", "return", "ptr", ";", "}" ]
Resolve property pointer. @private @param {module:x2node-records~RecordTypeDescriptor} recordTypeDesc Record type descriptor. @param {string} propPointer Property pointer. @param {boolean} noDash <code>true</code> if dash at the end of the array property pointer is disallowed (in the context of the patch operation). @param {Symbol} ptrUse Intended property use in the patch operation. @returns {module:x2node-pointers~RecordElementPointer} The resolved property. @throws {module:x2node-common.X2SyntaxError} If the pointer is invalid.
[ "Resolve", "property", "pointer", "." ]
59debdb270c899bcca3f330217b68e2f746d9646
https://github.com/boylesoftware/x2node-patches/blob/59debdb270c899bcca3f330217b68e2f746d9646/lib/record-patch-builder.js#L838-L863
49,030
boylesoftware/x2node-patches
lib/record-patch-builder.js
validatePatchOperationValue
function validatePatchOperationValue( recordTypes, opType, opInd, pathPtr, val, forUpdate) { // error function const validate = errMsg => { if (errMsg) throw new common.X2SyntaxError( `Invalid value in patch operation #${opInd + 1} (${opType}):` + ` ${errMsg}`); }; // check if we have the value if (val === undefined) validate('no value is provided for the operation.'); // get target property descriptor const propDesc = pathPtr.propDesc; // "merge" operation is a special case if (opType === 'merge') { // value must be an object if (((typeof val) !== 'object') || (val === null)) validate('merge value must be a non-null object.'); // target must be a single object or a whole map if (!(propDesc.isMap() && !pathPtr.collectionElement) && !((propDesc.scalarValueType === 'object') && ( propDesc.isScalar() || pathPtr.collectionElement))) validate('invalid merge target record element type.'); // valid value, return it return val; } // validate if null is acceptable if (val === null) { if ((propDesc.isScalar() || !pathPtr.collectionElement) && !propDesc.optional) validate('null for required property.'); if (pathPtr.collectionElement && (propDesc.scalarValueType === 'object')) validate('null for nested object collection element.'); return val; // valid } // validate depending on the property type if (propDesc.isArray() && !pathPtr.collectionElement) { if (!Array.isArray(val)) validate('expected an array.'); if (!propDesc.optional && (val.length === 0)) validate('empty array for required property.'); val.forEach(v => { validate(isInvalidScalarValueType( recordTypes, v, propDesc, forUpdate)); }); } else if (propDesc.isMap() && !pathPtr.collectionElement) { if ((typeof val) !== 'object') validate('expected an object.'); const keys = Object.keys(val); if (!propDesc.optional && (keys.length === 0)) validate('empty object for required property.'); keys.forEach(k => { validate(isInvalidScalarValueType( recordTypes, val[k], propDesc, forUpdate)); }); } else { validate(isInvalidScalarValueType( recordTypes, val, propDesc, forUpdate)); } // the value is valid, return it return val; }
javascript
function validatePatchOperationValue( recordTypes, opType, opInd, pathPtr, val, forUpdate) { // error function const validate = errMsg => { if (errMsg) throw new common.X2SyntaxError( `Invalid value in patch operation #${opInd + 1} (${opType}):` + ` ${errMsg}`); }; // check if we have the value if (val === undefined) validate('no value is provided for the operation.'); // get target property descriptor const propDesc = pathPtr.propDesc; // "merge" operation is a special case if (opType === 'merge') { // value must be an object if (((typeof val) !== 'object') || (val === null)) validate('merge value must be a non-null object.'); // target must be a single object or a whole map if (!(propDesc.isMap() && !pathPtr.collectionElement) && !((propDesc.scalarValueType === 'object') && ( propDesc.isScalar() || pathPtr.collectionElement))) validate('invalid merge target record element type.'); // valid value, return it return val; } // validate if null is acceptable if (val === null) { if ((propDesc.isScalar() || !pathPtr.collectionElement) && !propDesc.optional) validate('null for required property.'); if (pathPtr.collectionElement && (propDesc.scalarValueType === 'object')) validate('null for nested object collection element.'); return val; // valid } // validate depending on the property type if (propDesc.isArray() && !pathPtr.collectionElement) { if (!Array.isArray(val)) validate('expected an array.'); if (!propDesc.optional && (val.length === 0)) validate('empty array for required property.'); val.forEach(v => { validate(isInvalidScalarValueType( recordTypes, v, propDesc, forUpdate)); }); } else if (propDesc.isMap() && !pathPtr.collectionElement) { if ((typeof val) !== 'object') validate('expected an object.'); const keys = Object.keys(val); if (!propDesc.optional && (keys.length === 0)) validate('empty object for required property.'); keys.forEach(k => { validate(isInvalidScalarValueType( recordTypes, val[k], propDesc, forUpdate)); }); } else { validate(isInvalidScalarValueType( recordTypes, val, propDesc, forUpdate)); } // the value is valid, return it return val; }
[ "function", "validatePatchOperationValue", "(", "recordTypes", ",", "opType", ",", "opInd", ",", "pathPtr", ",", "val", ",", "forUpdate", ")", "{", "// error function", "const", "validate", "=", "errMsg", "=>", "{", "if", "(", "errMsg", ")", "throw", "new", "common", ".", "X2SyntaxError", "(", "`", "${", "opInd", "+", "1", "}", "${", "opType", "}", "`", "+", "`", "${", "errMsg", "}", "`", ")", ";", "}", ";", "// check if we have the value", "if", "(", "val", "===", "undefined", ")", "validate", "(", "'no value is provided for the operation.'", ")", ";", "// get target property descriptor", "const", "propDesc", "=", "pathPtr", ".", "propDesc", ";", "// \"merge\" operation is a special case", "if", "(", "opType", "===", "'merge'", ")", "{", "// value must be an object", "if", "(", "(", "(", "typeof", "val", ")", "!==", "'object'", ")", "||", "(", "val", "===", "null", ")", ")", "validate", "(", "'merge value must be a non-null object.'", ")", ";", "// target must be a single object or a whole map", "if", "(", "!", "(", "propDesc", ".", "isMap", "(", ")", "&&", "!", "pathPtr", ".", "collectionElement", ")", "&&", "!", "(", "(", "propDesc", ".", "scalarValueType", "===", "'object'", ")", "&&", "(", "propDesc", ".", "isScalar", "(", ")", "||", "pathPtr", ".", "collectionElement", ")", ")", ")", "validate", "(", "'invalid merge target record element type.'", ")", ";", "// valid value, return it", "return", "val", ";", "}", "// validate if null is acceptable", "if", "(", "val", "===", "null", ")", "{", "if", "(", "(", "propDesc", ".", "isScalar", "(", ")", "||", "!", "pathPtr", ".", "collectionElement", ")", "&&", "!", "propDesc", ".", "optional", ")", "validate", "(", "'null for required property.'", ")", ";", "if", "(", "pathPtr", ".", "collectionElement", "&&", "(", "propDesc", ".", "scalarValueType", "===", "'object'", ")", ")", "validate", "(", "'null for nested object collection element.'", ")", ";", "return", "val", ";", "// valid", "}", "// validate depending on the property type", "if", "(", "propDesc", ".", "isArray", "(", ")", "&&", "!", "pathPtr", ".", "collectionElement", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "val", ")", ")", "validate", "(", "'expected an array.'", ")", ";", "if", "(", "!", "propDesc", ".", "optional", "&&", "(", "val", ".", "length", "===", "0", ")", ")", "validate", "(", "'empty array for required property.'", ")", ";", "val", ".", "forEach", "(", "v", "=>", "{", "validate", "(", "isInvalidScalarValueType", "(", "recordTypes", ",", "v", ",", "propDesc", ",", "forUpdate", ")", ")", ";", "}", ")", ";", "}", "else", "if", "(", "propDesc", ".", "isMap", "(", ")", "&&", "!", "pathPtr", ".", "collectionElement", ")", "{", "if", "(", "(", "typeof", "val", ")", "!==", "'object'", ")", "validate", "(", "'expected an object.'", ")", ";", "const", "keys", "=", "Object", ".", "keys", "(", "val", ")", ";", "if", "(", "!", "propDesc", ".", "optional", "&&", "(", "keys", ".", "length", "===", "0", ")", ")", "validate", "(", "'empty object for required property.'", ")", ";", "keys", ".", "forEach", "(", "k", "=>", "{", "validate", "(", "isInvalidScalarValueType", "(", "recordTypes", ",", "val", "[", "k", "]", ",", "propDesc", ",", "forUpdate", ")", ")", ";", "}", ")", ";", "}", "else", "{", "validate", "(", "isInvalidScalarValueType", "(", "recordTypes", ",", "val", ",", "propDesc", ",", "forUpdate", ")", ")", ";", "}", "// the value is valid, return it", "return", "val", ";", "}" ]
Validate value provided with a patch operation. @private @param {module:x2node-records~RecordTypesLibrary} recordTypes Record types library. @param {string} opType Patch operation type. @param {number} opInd Index of the patch operation in the list of operations. @param {module:x2node-pointers~RecordElementPointer} pathPtr Information object for the property path where the value is supposed to belong. @param {*} val The value to test. Can be <code>null</code>, but not <code>undefined</code>. @param {boolean} forUpdate <code>true</code> if the value is intended as a new value for the property, or <code>false</code> if only used to test the current property value. @returns {*} The value passed in as <code>val</code>. @throws {module:x2node-common.X2SyntaxError} If the value is invalid.
[ "Validate", "value", "provided", "with", "a", "patch", "operation", "." ]
59debdb270c899bcca3f330217b68e2f746d9646
https://github.com/boylesoftware/x2node-patches/blob/59debdb270c899bcca3f330217b68e2f746d9646/lib/record-patch-builder.js#L883-L955
49,031
boylesoftware/x2node-patches
lib/record-patch-builder.js
isValidRefValue
function isValidRefValue(recordTypes, val, propDesc) { if ((typeof val) !== 'string') return false; const hashInd = val.indexOf('#'); if ((hashInd <= 0) || (hashInd === val.length - 1)) return false; const refTarget = val.substring(0, hashInd); if (refTarget !== propDesc.refTarget) return false; const refTargetDesc = recordTypes.getRecordTypeDesc(refTarget); const refIdPropDesc = refTargetDesc.getPropertyDesc( refTargetDesc.idPropertyName); if ((refIdPropDesc.scalarValueType === 'number') && !Number.isFinite(Number(val.substring(hashInd + 1)))) return false; return true; }
javascript
function isValidRefValue(recordTypes, val, propDesc) { if ((typeof val) !== 'string') return false; const hashInd = val.indexOf('#'); if ((hashInd <= 0) || (hashInd === val.length - 1)) return false; const refTarget = val.substring(0, hashInd); if (refTarget !== propDesc.refTarget) return false; const refTargetDesc = recordTypes.getRecordTypeDesc(refTarget); const refIdPropDesc = refTargetDesc.getPropertyDesc( refTargetDesc.idPropertyName); if ((refIdPropDesc.scalarValueType === 'number') && !Number.isFinite(Number(val.substring(hashInd + 1)))) return false; return true; }
[ "function", "isValidRefValue", "(", "recordTypes", ",", "val", ",", "propDesc", ")", "{", "if", "(", "(", "typeof", "val", ")", "!==", "'string'", ")", "return", "false", ";", "const", "hashInd", "=", "val", ".", "indexOf", "(", "'#'", ")", ";", "if", "(", "(", "hashInd", "<=", "0", ")", "||", "(", "hashInd", "===", "val", ".", "length", "-", "1", ")", ")", "return", "false", ";", "const", "refTarget", "=", "val", ".", "substring", "(", "0", ",", "hashInd", ")", ";", "if", "(", "refTarget", "!==", "propDesc", ".", "refTarget", ")", "return", "false", ";", "const", "refTargetDesc", "=", "recordTypes", ".", "getRecordTypeDesc", "(", "refTarget", ")", ";", "const", "refIdPropDesc", "=", "refTargetDesc", ".", "getPropertyDesc", "(", "refTargetDesc", ".", "idPropertyName", ")", ";", "if", "(", "(", "refIdPropDesc", ".", "scalarValueType", "===", "'number'", ")", "&&", "!", "Number", ".", "isFinite", "(", "Number", "(", "val", ".", "substring", "(", "hashInd", "+", "1", ")", ")", ")", ")", "return", "false", ";", "return", "true", ";", "}" ]
Tell if the specified value is suitable to be the specified reference property's value. @private @param {module:x2node-records~RecordTypesLibrary} recordTypes Record types library. @param {*} val The value to test. @param {module:x2node-records~PropertyDescriptor} propDef Reference property descriptor. @returns {boolean} <code>true</code> if the value is a string (so not <code>null</code> or <code>undefined</code> either) and matches the reference property.
[ "Tell", "if", "the", "specified", "value", "is", "suitable", "to", "be", "the", "specified", "reference", "property", "s", "value", "." ]
59debdb270c899bcca3f330217b68e2f746d9646
https://github.com/boylesoftware/x2node-patches/blob/59debdb270c899bcca3f330217b68e2f746d9646/lib/record-patch-builder.js#L1025-L1047
49,032
boylesoftware/x2node-patches
lib/record-patch-builder.js
isValidObjectValue
function isValidObjectValue(recordTypes, val, objectPropDesc, forUpdate) { const container = objectPropDesc.nestedProperties; for (let propName of container.allPropertyNames) { const propDesc = container.getPropertyDesc(propName); if (propDesc.isView() || propDesc.isCalculated()) continue; const propVal = val[propName]; if ((propVal === undefined) || (propVal === null)) { if (!propDesc.optional && (!forUpdate || !propDesc.isGenerated())) return false; } else if (propDesc.isArray()) { if (!Array.isArray(propVal)) return false; if (!propDesc.optional && (propVal.length === 0)) return false; if (propVal.some( v => isInvalidScalarValueType( recordTypes, v, propDesc, forUpdate))) return false; } else if (propDesc.isMap()) { if ((typeof propVal) !== 'object') return false; const keys = Object.keys(propVal); if (!propDesc.optional && (keys.length === 0)) return false; if (keys.some( k => isInvalidScalarValueType( recordTypes, propVal[k], propDesc, forUpdate))) return false; } else { if (isInvalidScalarValueType( recordTypes, propVal, propDesc, forUpdate)) return false; } } return true; }
javascript
function isValidObjectValue(recordTypes, val, objectPropDesc, forUpdate) { const container = objectPropDesc.nestedProperties; for (let propName of container.allPropertyNames) { const propDesc = container.getPropertyDesc(propName); if (propDesc.isView() || propDesc.isCalculated()) continue; const propVal = val[propName]; if ((propVal === undefined) || (propVal === null)) { if (!propDesc.optional && (!forUpdate || !propDesc.isGenerated())) return false; } else if (propDesc.isArray()) { if (!Array.isArray(propVal)) return false; if (!propDesc.optional && (propVal.length === 0)) return false; if (propVal.some( v => isInvalidScalarValueType( recordTypes, v, propDesc, forUpdate))) return false; } else if (propDesc.isMap()) { if ((typeof propVal) !== 'object') return false; const keys = Object.keys(propVal); if (!propDesc.optional && (keys.length === 0)) return false; if (keys.some( k => isInvalidScalarValueType( recordTypes, propVal[k], propDesc, forUpdate))) return false; } else { if (isInvalidScalarValueType( recordTypes, propVal, propDesc, forUpdate)) return false; } } return true; }
[ "function", "isValidObjectValue", "(", "recordTypes", ",", "val", ",", "objectPropDesc", ",", "forUpdate", ")", "{", "const", "container", "=", "objectPropDesc", ".", "nestedProperties", ";", "for", "(", "let", "propName", "of", "container", ".", "allPropertyNames", ")", "{", "const", "propDesc", "=", "container", ".", "getPropertyDesc", "(", "propName", ")", ";", "if", "(", "propDesc", ".", "isView", "(", ")", "||", "propDesc", ".", "isCalculated", "(", ")", ")", "continue", ";", "const", "propVal", "=", "val", "[", "propName", "]", ";", "if", "(", "(", "propVal", "===", "undefined", ")", "||", "(", "propVal", "===", "null", ")", ")", "{", "if", "(", "!", "propDesc", ".", "optional", "&&", "(", "!", "forUpdate", "||", "!", "propDesc", ".", "isGenerated", "(", ")", ")", ")", "return", "false", ";", "}", "else", "if", "(", "propDesc", ".", "isArray", "(", ")", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "propVal", ")", ")", "return", "false", ";", "if", "(", "!", "propDesc", ".", "optional", "&&", "(", "propVal", ".", "length", "===", "0", ")", ")", "return", "false", ";", "if", "(", "propVal", ".", "some", "(", "v", "=>", "isInvalidScalarValueType", "(", "recordTypes", ",", "v", ",", "propDesc", ",", "forUpdate", ")", ")", ")", "return", "false", ";", "}", "else", "if", "(", "propDesc", ".", "isMap", "(", ")", ")", "{", "if", "(", "(", "typeof", "propVal", ")", "!==", "'object'", ")", "return", "false", ";", "const", "keys", "=", "Object", ".", "keys", "(", "propVal", ")", ";", "if", "(", "!", "propDesc", ".", "optional", "&&", "(", "keys", ".", "length", "===", "0", ")", ")", "return", "false", ";", "if", "(", "keys", ".", "some", "(", "k", "=>", "isInvalidScalarValueType", "(", "recordTypes", ",", "propVal", "[", "k", "]", ",", "propDesc", ",", "forUpdate", ")", ")", ")", "return", "false", ";", "}", "else", "{", "if", "(", "isInvalidScalarValueType", "(", "recordTypes", ",", "propVal", ",", "propDesc", ",", "forUpdate", ")", ")", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Tell if the specified object is suitable to be a value for the specified nested object property. @private @param {module:x2node-records~RecordTypesLibrary} recordTypes Record types library. @param {Object} val The object to test. May not be <code>null</code> nor <code>undefined</code>. @param {module:x2node-records~PropertyDescriptor} objectPropDesc Nested object property descriptor (either scalar or not). @param {boolean} forUpdate <code>true</code> if the object is intended as a new value for the property, or <code>false</code> if only used to test the current property value. @returns {boolean} <code>true</code> if valid.
[ "Tell", "if", "the", "specified", "object", "is", "suitable", "to", "be", "a", "value", "for", "the", "specified", "nested", "object", "property", "." ]
59debdb270c899bcca3f330217b68e2f746d9646
https://github.com/boylesoftware/x2node-patches/blob/59debdb270c899bcca3f330217b68e2f746d9646/lib/record-patch-builder.js#L1065-L1103
49,033
boylesoftware/x2node-patches
lib/record-patch-builder.js
validatePatchOperationFrom
function validatePatchOperationFrom(opType, opInd, pathPtr, fromPtr, forMove) { const invalidFrom = msg => new common.X2SyntaxError( `Invalid "from" pointer in patch operation #${opInd + 1} (${opType}):` + ` ${msg}`); if (forMove && pathPtr.isChildOf(fromPtr)) throw invalidFrom('may not move location into one of its children.'); const fromPropDesc = fromPtr.propDesc; const toPropDesc = pathPtr.propDesc; if (fromPropDesc.scalarValueType !== toPropDesc.scalarValueType) throw invalidFrom('incompatible property value types.'); if (toPropDesc.isRef() && (fromPropDesc.refTarget !== toPropDesc.refTarget)) throw invalidFrom('incompatible reference property targets.'); if ((toPropDesc.scalarValueType === 'object') && !isCompatibleObjects(fromPropDesc, toPropDesc)) throw invalidFrom('incompatible nested objects.'); if (toPropDesc.isArray() && !pathPtr.collectionElement) { if (!fromPropDesc.isArray() || fromPropDesc.collectionElement) throw invalidFrom('not an array.'); } else if (toPropDesc.isMap() && !pathPtr.collectionElement) { if (!fromPropDesc.isMap() || fromPropDesc.collectionElement) throw invalidFrom('not a map.'); } else { if (!fromPropDesc.isScalar() && !fromPtr.collectionElement) throw invalidFrom('not a scalar.'); } return fromPtr; }
javascript
function validatePatchOperationFrom(opType, opInd, pathPtr, fromPtr, forMove) { const invalidFrom = msg => new common.X2SyntaxError( `Invalid "from" pointer in patch operation #${opInd + 1} (${opType}):` + ` ${msg}`); if (forMove && pathPtr.isChildOf(fromPtr)) throw invalidFrom('may not move location into one of its children.'); const fromPropDesc = fromPtr.propDesc; const toPropDesc = pathPtr.propDesc; if (fromPropDesc.scalarValueType !== toPropDesc.scalarValueType) throw invalidFrom('incompatible property value types.'); if (toPropDesc.isRef() && (fromPropDesc.refTarget !== toPropDesc.refTarget)) throw invalidFrom('incompatible reference property targets.'); if ((toPropDesc.scalarValueType === 'object') && !isCompatibleObjects(fromPropDesc, toPropDesc)) throw invalidFrom('incompatible nested objects.'); if (toPropDesc.isArray() && !pathPtr.collectionElement) { if (!fromPropDesc.isArray() || fromPropDesc.collectionElement) throw invalidFrom('not an array.'); } else if (toPropDesc.isMap() && !pathPtr.collectionElement) { if (!fromPropDesc.isMap() || fromPropDesc.collectionElement) throw invalidFrom('not a map.'); } else { if (!fromPropDesc.isScalar() && !fromPtr.collectionElement) throw invalidFrom('not a scalar.'); } return fromPtr; }
[ "function", "validatePatchOperationFrom", "(", "opType", ",", "opInd", ",", "pathPtr", ",", "fromPtr", ",", "forMove", ")", "{", "const", "invalidFrom", "=", "msg", "=>", "new", "common", ".", "X2SyntaxError", "(", "`", "${", "opInd", "+", "1", "}", "${", "opType", "}", "`", "+", "`", "${", "msg", "}", "`", ")", ";", "if", "(", "forMove", "&&", "pathPtr", ".", "isChildOf", "(", "fromPtr", ")", ")", "throw", "invalidFrom", "(", "'may not move location into one of its children.'", ")", ";", "const", "fromPropDesc", "=", "fromPtr", ".", "propDesc", ";", "const", "toPropDesc", "=", "pathPtr", ".", "propDesc", ";", "if", "(", "fromPropDesc", ".", "scalarValueType", "!==", "toPropDesc", ".", "scalarValueType", ")", "throw", "invalidFrom", "(", "'incompatible property value types.'", ")", ";", "if", "(", "toPropDesc", ".", "isRef", "(", ")", "&&", "(", "fromPropDesc", ".", "refTarget", "!==", "toPropDesc", ".", "refTarget", ")", ")", "throw", "invalidFrom", "(", "'incompatible reference property targets.'", ")", ";", "if", "(", "(", "toPropDesc", ".", "scalarValueType", "===", "'object'", ")", "&&", "!", "isCompatibleObjects", "(", "fromPropDesc", ",", "toPropDesc", ")", ")", "throw", "invalidFrom", "(", "'incompatible nested objects.'", ")", ";", "if", "(", "toPropDesc", ".", "isArray", "(", ")", "&&", "!", "pathPtr", ".", "collectionElement", ")", "{", "if", "(", "!", "fromPropDesc", ".", "isArray", "(", ")", "||", "fromPropDesc", ".", "collectionElement", ")", "throw", "invalidFrom", "(", "'not an array.'", ")", ";", "}", "else", "if", "(", "toPropDesc", ".", "isMap", "(", ")", "&&", "!", "pathPtr", ".", "collectionElement", ")", "{", "if", "(", "!", "fromPropDesc", ".", "isMap", "(", ")", "||", "fromPropDesc", ".", "collectionElement", ")", "throw", "invalidFrom", "(", "'not a map.'", ")", ";", "}", "else", "{", "if", "(", "!", "fromPropDesc", ".", "isScalar", "(", ")", "&&", "!", "fromPtr", ".", "collectionElement", ")", "throw", "invalidFrom", "(", "'not a scalar.'", ")", ";", "}", "return", "fromPtr", ";", "}" ]
Validate "from" property provided with a patch operation. @private @param {string} opType Patch operation type. @param {number} opInd Index of the patch operation in the list of operations. @param {module:x2node-pointers~RecordElementPointer} pathPtr Information object for the property path where the "from" property is supposed to be placed. @param {module:x2node-pointers~RecordElementPointer} fromPtr Information object for the "from" property. @param {boolean} forMove <code>true</code> if moving, <code>false</code> if copying. @returns {module:x2node-pointers~RecordElementPointer} The pointer passed in as the <code>fromPtr</code>. @throws {module:x2node-common.X2SyntaxError} If the "from" is incompatible.
[ "Validate", "from", "property", "provided", "with", "a", "patch", "operation", "." ]
59debdb270c899bcca3f330217b68e2f746d9646
https://github.com/boylesoftware/x2node-patches/blob/59debdb270c899bcca3f330217b68e2f746d9646/lib/record-patch-builder.js#L1122-L1154
49,034
boylesoftware/x2node-patches
lib/record-patch-builder.js
isCompatibleObjects
function isCompatibleObjects(objectPropDesc1, objectPropDesc2) { const propNames2 = new Set(objectPropDesc2.allPropertyNames); const container1 = objectPropDesc1.nestedProperties; const container2 = objectPropDesc2.nestedProperties; for (let propName of objectPropDesc1.allPropertyNames) { const propDesc1 = container1.getPropertyDesc(propName); if (propDesc1.isView() || propDesc1.isCalculated()) continue; if (!propNames2.has(propName)) { if (!propDesc1.optional) return false; continue; } propNames2.delete(propName); const propDesc2 = container2.getPropertyDesc(propName); if (!propDesc1.optional && propDesc2.optional) return false; if ((propDesc1.isArray() && !propDesc2.isArray()) || (propDesc1.isMap() && !propDesc2.isMap()) || (propDesc1.isScalar() && !propDesc2.isScalar())) return false; if (propDesc1.scalarValueType !== propDesc2.scalarValueType) return false; if (propDesc1.isRef() && (propDesc1.refTarget !== propDesc2.refTarget)) return false; if ((propDesc1.scalarValueType === 'object') && !isCompatibleObjects(propDesc1, propDesc2)) return false; } for (let propName of propNames2) { const propDesc2 = container2.getPropertyDesc(propName); if (!propDesc2.isView() && !propDesc2.isCalculated()) return false; } return true; }
javascript
function isCompatibleObjects(objectPropDesc1, objectPropDesc2) { const propNames2 = new Set(objectPropDesc2.allPropertyNames); const container1 = objectPropDesc1.nestedProperties; const container2 = objectPropDesc2.nestedProperties; for (let propName of objectPropDesc1.allPropertyNames) { const propDesc1 = container1.getPropertyDesc(propName); if (propDesc1.isView() || propDesc1.isCalculated()) continue; if (!propNames2.has(propName)) { if (!propDesc1.optional) return false; continue; } propNames2.delete(propName); const propDesc2 = container2.getPropertyDesc(propName); if (!propDesc1.optional && propDesc2.optional) return false; if ((propDesc1.isArray() && !propDesc2.isArray()) || (propDesc1.isMap() && !propDesc2.isMap()) || (propDesc1.isScalar() && !propDesc2.isScalar())) return false; if (propDesc1.scalarValueType !== propDesc2.scalarValueType) return false; if (propDesc1.isRef() && (propDesc1.refTarget !== propDesc2.refTarget)) return false; if ((propDesc1.scalarValueType === 'object') && !isCompatibleObjects(propDesc1, propDesc2)) return false; } for (let propName of propNames2) { const propDesc2 = container2.getPropertyDesc(propName); if (!propDesc2.isView() && !propDesc2.isCalculated()) return false; } return true; }
[ "function", "isCompatibleObjects", "(", "objectPropDesc1", ",", "objectPropDesc2", ")", "{", "const", "propNames2", "=", "new", "Set", "(", "objectPropDesc2", ".", "allPropertyNames", ")", ";", "const", "container1", "=", "objectPropDesc1", ".", "nestedProperties", ";", "const", "container2", "=", "objectPropDesc2", ".", "nestedProperties", ";", "for", "(", "let", "propName", "of", "objectPropDesc1", ".", "allPropertyNames", ")", "{", "const", "propDesc1", "=", "container1", ".", "getPropertyDesc", "(", "propName", ")", ";", "if", "(", "propDesc1", ".", "isView", "(", ")", "||", "propDesc1", ".", "isCalculated", "(", ")", ")", "continue", ";", "if", "(", "!", "propNames2", ".", "has", "(", "propName", ")", ")", "{", "if", "(", "!", "propDesc1", ".", "optional", ")", "return", "false", ";", "continue", ";", "}", "propNames2", ".", "delete", "(", "propName", ")", ";", "const", "propDesc2", "=", "container2", ".", "getPropertyDesc", "(", "propName", ")", ";", "if", "(", "!", "propDesc1", ".", "optional", "&&", "propDesc2", ".", "optional", ")", "return", "false", ";", "if", "(", "(", "propDesc1", ".", "isArray", "(", ")", "&&", "!", "propDesc2", ".", "isArray", "(", ")", ")", "||", "(", "propDesc1", ".", "isMap", "(", ")", "&&", "!", "propDesc2", ".", "isMap", "(", ")", ")", "||", "(", "propDesc1", ".", "isScalar", "(", ")", "&&", "!", "propDesc2", ".", "isScalar", "(", ")", ")", ")", "return", "false", ";", "if", "(", "propDesc1", ".", "scalarValueType", "!==", "propDesc2", ".", "scalarValueType", ")", "return", "false", ";", "if", "(", "propDesc1", ".", "isRef", "(", ")", "&&", "(", "propDesc1", ".", "refTarget", "!==", "propDesc2", ".", "refTarget", ")", ")", "return", "false", ";", "if", "(", "(", "propDesc1", ".", "scalarValueType", "===", "'object'", ")", "&&", "!", "isCompatibleObjects", "(", "propDesc1", ",", "propDesc2", ")", ")", "return", "false", ";", "}", "for", "(", "let", "propName", "of", "propNames2", ")", "{", "const", "propDesc2", "=", "container2", ".", "getPropertyDesc", "(", "propName", ")", ";", "if", "(", "!", "propDesc2", ".", "isView", "(", ")", "&&", "!", "propDesc2", ".", "isCalculated", "(", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}" ]
Tell if a value of the nested object property 2 can be used as a value of the nested object property 1. @private @param {module:x2node-records~PropertyDescriptor} objectPropDesc1 Nested object property 1. @param {module:x2node-records~PropertyDescriptor} objectPropDesc2 Nested object property 2. @returns {boolean} <code>true</code> if compatible nested object properties.
[ "Tell", "if", "a", "value", "of", "the", "nested", "object", "property", "2", "can", "be", "used", "as", "a", "value", "of", "the", "nested", "object", "property", "1", "." ]
59debdb270c899bcca3f330217b68e2f746d9646
https://github.com/boylesoftware/x2node-patches/blob/59debdb270c899bcca3f330217b68e2f746d9646/lib/record-patch-builder.js#L1167-L1205
49,035
boylesoftware/x2node-patches
lib/record-patch-builder.js
addInvolvedProperty
function addInvolvedProperty(pathPtr, involvedPropPaths, updatedPropPaths) { if (updatedPropPaths) { const propPathParts = pathPtr.propPath.split('.'); let propPath = ''; for (let i = 0, len = propPathParts.length - 1; i < len; i++) { if (propPath.length > 0) propPath += '.'; propPath += propPathParts[i]; updatedPropPaths.add(propPath); } } const propDesc = pathPtr.propDesc; if (propDesc.scalarValueType === 'object') { addInvolvedObjectProperty(propDesc, involvedPropPaths, updatedPropPaths); } else { involvedPropPaths.add(pathPtr.propPath); if (updatedPropPaths) updatedPropPaths.add(pathPtr.propPath); } return pathPtr; }
javascript
function addInvolvedProperty(pathPtr, involvedPropPaths, updatedPropPaths) { if (updatedPropPaths) { const propPathParts = pathPtr.propPath.split('.'); let propPath = ''; for (let i = 0, len = propPathParts.length - 1; i < len; i++) { if (propPath.length > 0) propPath += '.'; propPath += propPathParts[i]; updatedPropPaths.add(propPath); } } const propDesc = pathPtr.propDesc; if (propDesc.scalarValueType === 'object') { addInvolvedObjectProperty(propDesc, involvedPropPaths, updatedPropPaths); } else { involvedPropPaths.add(pathPtr.propPath); if (updatedPropPaths) updatedPropPaths.add(pathPtr.propPath); } return pathPtr; }
[ "function", "addInvolvedProperty", "(", "pathPtr", ",", "involvedPropPaths", ",", "updatedPropPaths", ")", "{", "if", "(", "updatedPropPaths", ")", "{", "const", "propPathParts", "=", "pathPtr", ".", "propPath", ".", "split", "(", "'.'", ")", ";", "let", "propPath", "=", "''", ";", "for", "(", "let", "i", "=", "0", ",", "len", "=", "propPathParts", ".", "length", "-", "1", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "propPath", ".", "length", ">", "0", ")", "propPath", "+=", "'.'", ";", "propPath", "+=", "propPathParts", "[", "i", "]", ";", "updatedPropPaths", ".", "add", "(", "propPath", ")", ";", "}", "}", "const", "propDesc", "=", "pathPtr", ".", "propDesc", ";", "if", "(", "propDesc", ".", "scalarValueType", "===", "'object'", ")", "{", "addInvolvedObjectProperty", "(", "propDesc", ",", "involvedPropPaths", ",", "updatedPropPaths", ")", ";", "}", "else", "{", "involvedPropPaths", ".", "add", "(", "pathPtr", ".", "propPath", ")", ";", "if", "(", "updatedPropPaths", ")", "updatedPropPaths", ".", "add", "(", "pathPtr", ".", "propPath", ")", ";", "}", "return", "pathPtr", ";", "}" ]
Add property to the involved property paths collection. @private @param {module:x2node-pointers~RecordElementPointer} pathPtr Resolved property pointer. @param {Set.<string>} involvedPropPaths Involved property paths collection. @param {Set.<string>} [updatedPropPaths] Updated property paths collection if the involved property is to be updated by the patch. @returns {module:x2node-pointers~RecordElementPointer} The pointer passed in as <code>pathPtr</code>.
[ "Add", "property", "to", "the", "involved", "property", "paths", "collection", "." ]
59debdb270c899bcca3f330217b68e2f746d9646
https://github.com/boylesoftware/x2node-patches/blob/59debdb270c899bcca3f330217b68e2f746d9646/lib/record-patch-builder.js#L1219-L1242
49,036
boylesoftware/x2node-patches
lib/record-patch-builder.js
addInvolvedObjectProperty
function addInvolvedObjectProperty( objectPropDesc, involvedPropPaths, updatedPropPaths) { if (updatedPropPaths) updatedPropPaths.add( objectPropDesc.container.nestedPath + objectPropDesc.name); const container = objectPropDesc.nestedProperties; for (let propName of container.allPropertyNames) { const propDesc = container.getPropertyDesc(propName); if (propDesc.isCalculated() || propDesc.isView()) continue; if (propDesc.scalarValueType === 'object') { addInvolvedObjectProperty( objectPropDesc, involvedPropPaths, updatedPropPaths); } else { const propPath = container.nestedPath + propName; involvedPropPaths.add(propPath); if (updatedPropPaths) updatedPropPaths.add(propPath); } } }
javascript
function addInvolvedObjectProperty( objectPropDesc, involvedPropPaths, updatedPropPaths) { if (updatedPropPaths) updatedPropPaths.add( objectPropDesc.container.nestedPath + objectPropDesc.name); const container = objectPropDesc.nestedProperties; for (let propName of container.allPropertyNames) { const propDesc = container.getPropertyDesc(propName); if (propDesc.isCalculated() || propDesc.isView()) continue; if (propDesc.scalarValueType === 'object') { addInvolvedObjectProperty( objectPropDesc, involvedPropPaths, updatedPropPaths); } else { const propPath = container.nestedPath + propName; involvedPropPaths.add(propPath); if (updatedPropPaths) updatedPropPaths.add(propPath); } } }
[ "function", "addInvolvedObjectProperty", "(", "objectPropDesc", ",", "involvedPropPaths", ",", "updatedPropPaths", ")", "{", "if", "(", "updatedPropPaths", ")", "updatedPropPaths", ".", "add", "(", "objectPropDesc", ".", "container", ".", "nestedPath", "+", "objectPropDesc", ".", "name", ")", ";", "const", "container", "=", "objectPropDesc", ".", "nestedProperties", ";", "for", "(", "let", "propName", "of", "container", ".", "allPropertyNames", ")", "{", "const", "propDesc", "=", "container", ".", "getPropertyDesc", "(", "propName", ")", ";", "if", "(", "propDesc", ".", "isCalculated", "(", ")", "||", "propDesc", ".", "isView", "(", ")", ")", "continue", ";", "if", "(", "propDesc", ".", "scalarValueType", "===", "'object'", ")", "{", "addInvolvedObjectProperty", "(", "objectPropDesc", ",", "involvedPropPaths", ",", "updatedPropPaths", ")", ";", "}", "else", "{", "const", "propPath", "=", "container", ".", "nestedPath", "+", "propName", ";", "involvedPropPaths", ".", "add", "(", "propPath", ")", ";", "if", "(", "updatedPropPaths", ")", "updatedPropPaths", ".", "add", "(", "propPath", ")", ";", "}", "}", "}" ]
Recursively add nested object property to the involved property paths collection. @private @param {module:x2node-records~PropertyDescriptor} objectPropDesc Nested object property descriptor. @param {Set.<string>} involvedPropPaths Involved property paths collection. @param {Set.<string>} [updatedPropPaths] Updated property paths collection if the involved property is to be updated by the patch.
[ "Recursively", "add", "nested", "object", "property", "to", "the", "involved", "property", "paths", "collection", "." ]
59debdb270c899bcca3f330217b68e2f746d9646
https://github.com/boylesoftware/x2node-patches/blob/59debdb270c899bcca3f330217b68e2f746d9646/lib/record-patch-builder.js#L1255-L1277
49,037
soimy/arabic-persian-reshaper
index.js
convertArabicBack
function convertArabicBack(apfb) { var toReturn = "", selectedChar; theLoop: for( var i = 0 ; i < apfb.length ; ++i ) { selectedChar = apfb.charCodeAt(i); for( var j = 0 ; j < charsMap.length ; ++j ) { if( charsMap[j][4] == selectedChar || charsMap[j][2] == selectedChar || charsMap[j][1] == selectedChar || charsMap[j][3] == selectedChar ) { toReturn += String.fromCharCode(charsMap[j][0]); continue theLoop; } } for( var j = 0 ; j < combCharsMap.length ; ++j ) { if( combCharsMap[j][4] == selectedChar || combCharsMap[j][2] == selectedChar || combCharsMap[j][1] == selectedChar || combCharsMap[j][3] == selectedChar ) { toReturn += String.fromCharCode(combCharsMap[j][0][0]) + String.fromCharCode(combCharsMap[j][0][1]); continue theLoop; } } toReturn += String.fromCharCode( selectedChar ); } return toReturn; }
javascript
function convertArabicBack(apfb) { var toReturn = "", selectedChar; theLoop: for( var i = 0 ; i < apfb.length ; ++i ) { selectedChar = apfb.charCodeAt(i); for( var j = 0 ; j < charsMap.length ; ++j ) { if( charsMap[j][4] == selectedChar || charsMap[j][2] == selectedChar || charsMap[j][1] == selectedChar || charsMap[j][3] == selectedChar ) { toReturn += String.fromCharCode(charsMap[j][0]); continue theLoop; } } for( var j = 0 ; j < combCharsMap.length ; ++j ) { if( combCharsMap[j][4] == selectedChar || combCharsMap[j][2] == selectedChar || combCharsMap[j][1] == selectedChar || combCharsMap[j][3] == selectedChar ) { toReturn += String.fromCharCode(combCharsMap[j][0][0]) + String.fromCharCode(combCharsMap[j][0][1]); continue theLoop; } } toReturn += String.fromCharCode( selectedChar ); } return toReturn; }
[ "function", "convertArabicBack", "(", "apfb", ")", "{", "var", "toReturn", "=", "\"\"", ",", "selectedChar", ";", "theLoop", ":", "for", "(", "var", "i", "=", "0", ";", "i", "<", "apfb", ".", "length", ";", "++", "i", ")", "{", "selectedChar", "=", "apfb", ".", "charCodeAt", "(", "i", ")", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "charsMap", ".", "length", ";", "++", "j", ")", "{", "if", "(", "charsMap", "[", "j", "]", "[", "4", "]", "==", "selectedChar", "||", "charsMap", "[", "j", "]", "[", "2", "]", "==", "selectedChar", "||", "charsMap", "[", "j", "]", "[", "1", "]", "==", "selectedChar", "||", "charsMap", "[", "j", "]", "[", "3", "]", "==", "selectedChar", ")", "{", "toReturn", "+=", "String", ".", "fromCharCode", "(", "charsMap", "[", "j", "]", "[", "0", "]", ")", ";", "continue", "theLoop", ";", "}", "}", "for", "(", "var", "j", "=", "0", ";", "j", "<", "combCharsMap", ".", "length", ";", "++", "j", ")", "{", "if", "(", "combCharsMap", "[", "j", "]", "[", "4", "]", "==", "selectedChar", "||", "combCharsMap", "[", "j", "]", "[", "2", "]", "==", "selectedChar", "||", "combCharsMap", "[", "j", "]", "[", "1", "]", "==", "selectedChar", "||", "combCharsMap", "[", "j", "]", "[", "3", "]", "==", "selectedChar", ")", "{", "toReturn", "+=", "String", ".", "fromCharCode", "(", "combCharsMap", "[", "j", "]", "[", "0", "]", "[", "0", "]", ")", "+", "String", ".", "fromCharCode", "(", "combCharsMap", "[", "j", "]", "[", "0", "]", "[", "1", "]", ")", ";", "continue", "theLoop", ";", "}", "}", "toReturn", "+=", "String", ".", "fromCharCode", "(", "selectedChar", ")", ";", "}", "return", "toReturn", ";", "}" ]
convert from Arabic Presentation Forms B
[ "convert", "from", "Arabic", "Presentation", "Forms", "B" ]
ce8bc48d61f9290f07f720bcf474db425f0de1de
https://github.com/soimy/arabic-persian-reshaper/blob/ce8bc48d61f9290f07f720bcf474db425f0de1de/index.js#L211-L238
49,038
thlorenz/files-provider
files-provider.js
createFilesProvider
function createFilesProvider({ regex = null , single = HANDLE , multi = PROMPT_AND_HANDLE , choiceAll = true , handler = null , promptHeader = defaultPromptHeader , promptFooter = defaultPromptFooter } = {}) { return new FilesProvider({ regex , single , multi , choiceAll , handler , promptHeader , promptFooter }) }
javascript
function createFilesProvider({ regex = null , single = HANDLE , multi = PROMPT_AND_HANDLE , choiceAll = true , handler = null , promptHeader = defaultPromptHeader , promptFooter = defaultPromptFooter } = {}) { return new FilesProvider({ regex , single , multi , choiceAll , handler , promptHeader , promptFooter }) }
[ "function", "createFilesProvider", "(", "{", "regex", "=", "null", ",", "single", "=", "HANDLE", ",", "multi", "=", "PROMPT_AND_HANDLE", ",", "choiceAll", "=", "true", ",", "handler", "=", "null", ",", "promptHeader", "=", "defaultPromptHeader", ",", "promptFooter", "=", "defaultPromptFooter", "}", "=", "{", "}", ")", "{", "return", "new", "FilesProvider", "(", "{", "regex", ",", "single", ",", "multi", ",", "choiceAll", ",", "handler", ",", "promptHeader", ",", "promptFooter", "}", ")", "}" ]
Creates a FilesProvider @param {Object} $0 options @param {RegExp} $0.regex the regex to match the files with @param {Number} [$0.single = PROMPT] strategy for handling a single file `HANDLE|RETURN` @param {Number} [$0.multi = PROMPT_AND_HANDLE] strategy for handling multiple files `HANDLE|PROMPT|RETURN|PROMPT_AND_HANDLE` @param {Boolean} [$0.choiceAll = true] if `true` a choice to select all files is included when multiple files are found @param {function} $0.handler function to call when `HANDLE|PROMPT_AND_HANDLE` strategies are selected @param {String} $0.promptHeader header when prompting user to select a file @param {String} $0.promptFooter footer when prompting user to select a file @return {FilesProvider} the files provider
[ "Creates", "a", "FilesProvider" ]
ad6ca193ff612a00b480e8d2d05dc46880708c83
https://github.com/thlorenz/files-provider/blob/ad6ca193ff612a00b480e8d2d05dc46880708c83/files-provider.js#L171-L189
49,039
szanata/full_stack
lib/full_stack.js
prepareStackTrace
function prepareStackTrace( error, structuredStackTrace ) { // If error already have a cached trace inside, just return that // happens on true errors most if ( error.__cachedTrace ) { return error.__cachedTrace; } const stackTrace = utils.createStackTrace( error, structuredStackTrace ); error.__cachedTrace = utils.removeInternalFrames( filename, stackTrace ); if ( !error.__previous ) { let previousTraceError = currentTraceError; while ( previousTraceError ) { const previousTrace = utils.removeInternalFrames( filename, previousTraceError.stack ); // append old stack trace to the "cachedTrace" error.__cachedTrace += `${utils.separator}${utils.breakLn}${previousTraceError.__location}\n`; error.__cachedTrace += previousTrace.substring( previousTrace.indexOf( '\n' ) + 1 ); previousTraceError = previousTraceError.__previous; } } return error.__cachedTrace; }
javascript
function prepareStackTrace( error, structuredStackTrace ) { // If error already have a cached trace inside, just return that // happens on true errors most if ( error.__cachedTrace ) { return error.__cachedTrace; } const stackTrace = utils.createStackTrace( error, structuredStackTrace ); error.__cachedTrace = utils.removeInternalFrames( filename, stackTrace ); if ( !error.__previous ) { let previousTraceError = currentTraceError; while ( previousTraceError ) { const previousTrace = utils.removeInternalFrames( filename, previousTraceError.stack ); // append old stack trace to the "cachedTrace" error.__cachedTrace += `${utils.separator}${utils.breakLn}${previousTraceError.__location}\n`; error.__cachedTrace += previousTrace.substring( previousTrace.indexOf( '\n' ) + 1 ); previousTraceError = previousTraceError.__previous; } } return error.__cachedTrace; }
[ "function", "prepareStackTrace", "(", "error", ",", "structuredStackTrace", ")", "{", "// If error already have a cached trace inside, just return that", "// happens on true errors most", "if", "(", "error", ".", "__cachedTrace", ")", "{", "return", "error", ".", "__cachedTrace", ";", "}", "const", "stackTrace", "=", "utils", ".", "createStackTrace", "(", "error", ",", "structuredStackTrace", ")", ";", "error", ".", "__cachedTrace", "=", "utils", ".", "removeInternalFrames", "(", "filename", ",", "stackTrace", ")", ";", "if", "(", "!", "error", ".", "__previous", ")", "{", "let", "previousTraceError", "=", "currentTraceError", ";", "while", "(", "previousTraceError", ")", "{", "const", "previousTrace", "=", "utils", ".", "removeInternalFrames", "(", "filename", ",", "previousTraceError", ".", "stack", ")", ";", "// append old stack trace to the \"cachedTrace\"", "error", ".", "__cachedTrace", "+=", "`", "${", "utils", ".", "separator", "}", "${", "utils", ".", "breakLn", "}", "${", "previousTraceError", ".", "__location", "}", "\\n", "`", ";", "error", ".", "__cachedTrace", "+=", "previousTrace", ".", "substring", "(", "previousTrace", ".", "indexOf", "(", "'\\n'", ")", "+", "1", ")", ";", "previousTraceError", "=", "previousTraceError", ".", "__previous", ";", "}", "}", "return", "error", ".", "__cachedTrace", ";", "}" ]
Custom prepareStackTrace preparation, to be used on place o of the native @param {Error} error Error being used as start point for the stack @param {Callsite[]} structuredStackTrace Array of Callsites, which are previous stests from a stack trace, in a native object format
[ "Custom", "prepareStackTrace", "preparation", "to", "be", "used", "on", "place", "o", "of", "the", "native" ]
e9f3150219f4194def31e5a5175010536c0d9288
https://github.com/szanata/full_stack/blob/e9f3150219f4194def31e5a5175010536c0d9288/lib/full_stack.js#L28-L48
49,040
szanata/full_stack
lib/full_stack.js
wrapCallback
function wrapCallback( fn, frameLocation ) { const traceError = new Error(); traceError.__location = frameLocation; traceError.__previous = currentTraceError; return function $wrappedCallback( ...args ) { currentTraceError = traceError; try { return fn.call( this, ...args ); } catch ( e ) { throw e; // we just need the the 'finally' } finally { currentTraceError = null; } }; }
javascript
function wrapCallback( fn, frameLocation ) { const traceError = new Error(); traceError.__location = frameLocation; traceError.__previous = currentTraceError; return function $wrappedCallback( ...args ) { currentTraceError = traceError; try { return fn.call( this, ...args ); } catch ( e ) { throw e; // we just need the the 'finally' } finally { currentTraceError = null; } }; }
[ "function", "wrapCallback", "(", "fn", ",", "frameLocation", ")", "{", "const", "traceError", "=", "new", "Error", "(", ")", ";", "traceError", ".", "__location", "=", "frameLocation", ";", "traceError", ".", "__previous", "=", "currentTraceError", ";", "return", "function", "$wrappedCallback", "(", "...", "args", ")", "{", "currentTraceError", "=", "traceError", ";", "try", "{", "return", "fn", ".", "call", "(", "this", ",", "...", "args", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "e", ";", "// we just need the the 'finally'", "}", "finally", "{", "currentTraceError", "=", "null", ";", "}", "}", ";", "}" ]
Wrap given callback access its original trace @param {function} fn Callback function @param {String} frameLocation Code point where this callback was called. Eg. "MyClass.method"
[ "Wrap", "given", "callback", "access", "its", "original", "trace" ]
e9f3150219f4194def31e5a5175010536c0d9288
https://github.com/szanata/full_stack/blob/e9f3150219f4194def31e5a5175010536c0d9288/lib/full_stack.js#L56-L71
49,041
szanata/full_stack
lib/full_stack.js
$wrapped
function $wrapped( ...args ) { const wrappedArgs = args.slice(); args.forEach( ( arg, i ) => { if ( typeof arg === 'function' ) { wrappedArgs[i] = wrapCallback( args[i], origin ); } } ); return method.call( this, ...wrappedArgs ); }
javascript
function $wrapped( ...args ) { const wrappedArgs = args.slice(); args.forEach( ( arg, i ) => { if ( typeof arg === 'function' ) { wrappedArgs[i] = wrapCallback( args[i], origin ); } } ); return method.call( this, ...wrappedArgs ); }
[ "function", "$wrapped", "(", "...", "args", ")", "{", "const", "wrappedArgs", "=", "args", ".", "slice", "(", ")", ";", "args", ".", "forEach", "(", "(", "arg", ",", "i", ")", "=>", "{", "if", "(", "typeof", "arg", "===", "'function'", ")", "{", "wrappedArgs", "[", "i", "]", "=", "wrapCallback", "(", "args", "[", "i", "]", ",", "origin", ")", ";", "}", "}", ")", ";", "return", "method", ".", "call", "(", "this", ",", "...", "wrappedArgs", ")", ";", "}" ]
return a wrapped version of given object method
[ "return", "a", "wrapped", "version", "of", "given", "object", "method" ]
e9f3150219f4194def31e5a5175010536c0d9288
https://github.com/szanata/full_stack/blob/e9f3150219f4194def31e5a5175010536c0d9288/lib/full_stack.js#L100-L110
49,042
kuno/neco
deps/npm/lib/cache.js
ls_
function ls_ (req, depth, cb) { if (typeof cb !== "function") cb = depth, depth = 1 mkdir(npm.cache, function (er) { if (er) return log.er(cb, "no cache dir")(er) function dirFilter (f, type) { return type !== "dir" || ( f && f !== npm.cache + "/" + req && f !== npm.cache + "/" + req + "/" ) } find(path.join(npm.cache, req), dirFilter, depth, function (er, files) { if (er) return cb(er) return cb(null, files.map(function (f) { f = f.substr(npm.cache.length + 1) f = f.substr((f === req ? path.dirname(req) : req).length) .replace(/^\//, '') return f })) }) }) }
javascript
function ls_ (req, depth, cb) { if (typeof cb !== "function") cb = depth, depth = 1 mkdir(npm.cache, function (er) { if (er) return log.er(cb, "no cache dir")(er) function dirFilter (f, type) { return type !== "dir" || ( f && f !== npm.cache + "/" + req && f !== npm.cache + "/" + req + "/" ) } find(path.join(npm.cache, req), dirFilter, depth, function (er, files) { if (er) return cb(er) return cb(null, files.map(function (f) { f = f.substr(npm.cache.length + 1) f = f.substr((f === req ? path.dirname(req) : req).length) .replace(/^\//, '') return f })) }) }) }
[ "function", "ls_", "(", "req", ",", "depth", ",", "cb", ")", "{", "if", "(", "typeof", "cb", "!==", "\"function\"", ")", "cb", "=", "depth", ",", "depth", "=", "1", "mkdir", "(", "npm", ".", "cache", ",", "function", "(", "er", ")", "{", "if", "(", "er", ")", "return", "log", ".", "er", "(", "cb", ",", "\"no cache dir\"", ")", "(", "er", ")", "function", "dirFilter", "(", "f", ",", "type", ")", "{", "return", "type", "!==", "\"dir\"", "||", "(", "f", "&&", "f", "!==", "npm", ".", "cache", "+", "\"/\"", "+", "req", "&&", "f", "!==", "npm", ".", "cache", "+", "\"/\"", "+", "req", "+", "\"/\"", ")", "}", "find", "(", "path", ".", "join", "(", "npm", ".", "cache", ",", "req", ")", ",", "dirFilter", ",", "depth", ",", "function", "(", "er", ",", "files", ")", "{", "if", "(", "er", ")", "return", "cb", "(", "er", ")", "return", "cb", "(", "null", ",", "files", ".", "map", "(", "function", "(", "f", ")", "{", "f", "=", "f", ".", "substr", "(", "npm", ".", "cache", ".", "length", "+", "1", ")", "f", "=", "f", ".", "substr", "(", "(", "f", "===", "req", "?", "path", ".", "dirname", "(", "req", ")", ":", "req", ")", ".", "length", ")", ".", "replace", "(", "/", "^\\/", "/", ",", "''", ")", "return", "f", "}", ")", ")", "}", ")", "}", ")", "}" ]
Calls cb with list of cached pkgs matching show.
[ "Calls", "cb", "with", "list", "of", "cached", "pkgs", "matching", "show", "." ]
cf6361c1fcb9466c6b2ab3b127b5d0160ca50735
https://github.com/kuno/neco/blob/cf6361c1fcb9466c6b2ab3b127b5d0160ca50735/deps/npm/lib/cache.js#L139-L158
49,043
alexindigo/executioner
lib/parse.js
parse
function parse(cmd, params) { return Object.keys(params).reduce(iterator.bind(this, params), cmd); }
javascript
function parse(cmd, params) { return Object.keys(params).reduce(iterator.bind(this, params), cmd); }
[ "function", "parse", "(", "cmd", ",", "params", ")", "{", "return", "Object", ".", "keys", "(", "params", ")", ".", "reduce", "(", "iterator", ".", "bind", "(", "this", ",", "params", ")", ",", "cmd", ")", ";", "}" ]
Parses command and updated with provided parameters @param {string} cmd - command template @param {object} params - list of parameters @returns {string} - updated command
[ "Parses", "command", "and", "updated", "with", "provided", "parameters" ]
582f92897f47c13f4531e0b692aebb4a9f134eec
https://github.com/alexindigo/executioner/blob/582f92897f47c13f4531e0b692aebb4a9f134eec/lib/parse.js#L11-L14
49,044
alexindigo/executioner
lib/parse.js
iterator
function iterator(params, cmd, p) { var value = params[p]; // shortcut if (!cmd) return cmd; // fold booleans into strings accepted by shell if (typeof value == 'boolean') { value = value ? '1' : ''; } if (value !== null && ['undefined', 'string', 'number'].indexOf(typeof value) == -1) { // empty out cmd to signal the error return ''; } // use empty string for `undefined` return cmd.replace(new RegExp('\\$\\{' + p + '\\}', 'g'), (value !== undefined && value !== null) ? value : ''); }
javascript
function iterator(params, cmd, p) { var value = params[p]; // shortcut if (!cmd) return cmd; // fold booleans into strings accepted by shell if (typeof value == 'boolean') { value = value ? '1' : ''; } if (value !== null && ['undefined', 'string', 'number'].indexOf(typeof value) == -1) { // empty out cmd to signal the error return ''; } // use empty string for `undefined` return cmd.replace(new RegExp('\\$\\{' + p + '\\}', 'g'), (value !== undefined && value !== null) ? value : ''); }
[ "function", "iterator", "(", "params", ",", "cmd", ",", "p", ")", "{", "var", "value", "=", "params", "[", "p", "]", ";", "// shortcut", "if", "(", "!", "cmd", ")", "return", "cmd", ";", "// fold booleans into strings accepted by shell", "if", "(", "typeof", "value", "==", "'boolean'", ")", "{", "value", "=", "value", "?", "'1'", ":", "''", ";", "}", "if", "(", "value", "!==", "null", "&&", "[", "'undefined'", ",", "'string'", ",", "'number'", "]", ".", "indexOf", "(", "typeof", "value", ")", "==", "-", "1", ")", "{", "// empty out cmd to signal the error", "return", "''", ";", "}", "// use empty string for `undefined`", "return", "cmd", ".", "replace", "(", "new", "RegExp", "(", "'\\\\$\\\\{'", "+", "p", "+", "'\\\\}'", ",", "'g'", ")", ",", "(", "value", "!==", "undefined", "&&", "value", "!==", "null", ")", "?", "value", ":", "''", ")", ";", "}" ]
Iterator over params elements @param {object} params - list of parameters @param {string} cmd - command template @param {string} p - parameter key @returns {string} - updated command or empty string if one of the params didn't pass the filter
[ "Iterator", "over", "params", "elements" ]
582f92897f47c13f4531e0b692aebb4a9f134eec
https://github.com/alexindigo/executioner/blob/582f92897f47c13f4531e0b692aebb4a9f134eec/lib/parse.js#L25-L46
49,045
boylesoftware/x2node-dbos
lib/props-tree-builder.js
buildPropsTreeBranches
function buildPropsTreeBranches( recordTypes, topPropDesc, clause, baseValueExprCtx, scopePropPath, propPatterns, options) { // create the branching tree top node const topNode = PropertyTreeNode.createTopNode( recordTypes, topPropDesc, baseValueExprCtx, clause); // add direct patterns const valuePropsTrees = new Map(); const excludedPaths = new Set(); let wcPatterns = (!(options && options.noWildcards) && new Array()); for (let propPattern of propPatterns) { if (propPattern.startsWith('-')) excludedPaths.add(propPattern.substring(1)); else addProperty( topNode, scopePropPath, propPattern, clause, options, valuePropsTrees, wcPatterns); } // add wildcard patterns while (wcPatterns && (wcPatterns.length > 0)) { const wcPatterns2 = new Array(); wcPatterns.forEach(propPattern => { if (!excludedPaths.has(propPattern)) addProperty( topNode, scopePropPath, propPattern, clause, options, valuePropsTrees, wcPatterns2); }); wcPatterns = wcPatterns2; } // add scope if requested if (options && options.includeScopeProp && scopePropPath && !topNode.includesProp(scopePropPath)) { const scopeOptions = Object.create(options); scopeOptions.includeScopeProp = false; scopeOptions.noCalculated = true; scopeOptions.allowLeafObjects = true; addProperty(topNode, null, scopePropPath, clause, scopeOptions); } // de-branch the tree and merge in the value trees const assertSingleBranch = (branches, enable) => { if (enable && (branches.length > 1)) throw new Error('Internal X2 error: unexpected multiple branches.'); return branches; }; const valuePropsTreesArray = Array.from(valuePropsTrees.entries()); return assertSingleBranch(topNode.debranch().map( branch => valuePropsTreesArray.reduce((res, pair) => { const valuePropPath = pair[0]; const valuePropsTree = pair[1]; if (!res.includesProp(valuePropPath)) return res; return res.combine(valuePropsTree); }, branch) ), scopePropPath); }
javascript
function buildPropsTreeBranches( recordTypes, topPropDesc, clause, baseValueExprCtx, scopePropPath, propPatterns, options) { // create the branching tree top node const topNode = PropertyTreeNode.createTopNode( recordTypes, topPropDesc, baseValueExprCtx, clause); // add direct patterns const valuePropsTrees = new Map(); const excludedPaths = new Set(); let wcPatterns = (!(options && options.noWildcards) && new Array()); for (let propPattern of propPatterns) { if (propPattern.startsWith('-')) excludedPaths.add(propPattern.substring(1)); else addProperty( topNode, scopePropPath, propPattern, clause, options, valuePropsTrees, wcPatterns); } // add wildcard patterns while (wcPatterns && (wcPatterns.length > 0)) { const wcPatterns2 = new Array(); wcPatterns.forEach(propPattern => { if (!excludedPaths.has(propPattern)) addProperty( topNode, scopePropPath, propPattern, clause, options, valuePropsTrees, wcPatterns2); }); wcPatterns = wcPatterns2; } // add scope if requested if (options && options.includeScopeProp && scopePropPath && !topNode.includesProp(scopePropPath)) { const scopeOptions = Object.create(options); scopeOptions.includeScopeProp = false; scopeOptions.noCalculated = true; scopeOptions.allowLeafObjects = true; addProperty(topNode, null, scopePropPath, clause, scopeOptions); } // de-branch the tree and merge in the value trees const assertSingleBranch = (branches, enable) => { if (enable && (branches.length > 1)) throw new Error('Internal X2 error: unexpected multiple branches.'); return branches; }; const valuePropsTreesArray = Array.from(valuePropsTrees.entries()); return assertSingleBranch(topNode.debranch().map( branch => valuePropsTreesArray.reduce((res, pair) => { const valuePropPath = pair[0]; const valuePropsTree = pair[1]; if (!res.includesProp(valuePropPath)) return res; return res.combine(valuePropsTree); }, branch) ), scopePropPath); }
[ "function", "buildPropsTreeBranches", "(", "recordTypes", ",", "topPropDesc", ",", "clause", ",", "baseValueExprCtx", ",", "scopePropPath", ",", "propPatterns", ",", "options", ")", "{", "// create the branching tree top node", "const", "topNode", "=", "PropertyTreeNode", ".", "createTopNode", "(", "recordTypes", ",", "topPropDesc", ",", "baseValueExprCtx", ",", "clause", ")", ";", "// add direct patterns", "const", "valuePropsTrees", "=", "new", "Map", "(", ")", ";", "const", "excludedPaths", "=", "new", "Set", "(", ")", ";", "let", "wcPatterns", "=", "(", "!", "(", "options", "&&", "options", ".", "noWildcards", ")", "&&", "new", "Array", "(", ")", ")", ";", "for", "(", "let", "propPattern", "of", "propPatterns", ")", "{", "if", "(", "propPattern", ".", "startsWith", "(", "'-'", ")", ")", "excludedPaths", ".", "add", "(", "propPattern", ".", "substring", "(", "1", ")", ")", ";", "else", "addProperty", "(", "topNode", ",", "scopePropPath", ",", "propPattern", ",", "clause", ",", "options", ",", "valuePropsTrees", ",", "wcPatterns", ")", ";", "}", "// add wildcard patterns", "while", "(", "wcPatterns", "&&", "(", "wcPatterns", ".", "length", ">", "0", ")", ")", "{", "const", "wcPatterns2", "=", "new", "Array", "(", ")", ";", "wcPatterns", ".", "forEach", "(", "propPattern", "=>", "{", "if", "(", "!", "excludedPaths", ".", "has", "(", "propPattern", ")", ")", "addProperty", "(", "topNode", ",", "scopePropPath", ",", "propPattern", ",", "clause", ",", "options", ",", "valuePropsTrees", ",", "wcPatterns2", ")", ";", "}", ")", ";", "wcPatterns", "=", "wcPatterns2", ";", "}", "// add scope if requested", "if", "(", "options", "&&", "options", ".", "includeScopeProp", "&&", "scopePropPath", "&&", "!", "topNode", ".", "includesProp", "(", "scopePropPath", ")", ")", "{", "const", "scopeOptions", "=", "Object", ".", "create", "(", "options", ")", ";", "scopeOptions", ".", "includeScopeProp", "=", "false", ";", "scopeOptions", ".", "noCalculated", "=", "true", ";", "scopeOptions", ".", "allowLeafObjects", "=", "true", ";", "addProperty", "(", "topNode", ",", "null", ",", "scopePropPath", ",", "clause", ",", "scopeOptions", ")", ";", "}", "// de-branch the tree and merge in the value trees", "const", "assertSingleBranch", "=", "(", "branches", ",", "enable", ")", "=>", "{", "if", "(", "enable", "&&", "(", "branches", ".", "length", ">", "1", ")", ")", "throw", "new", "Error", "(", "'Internal X2 error: unexpected multiple branches.'", ")", ";", "return", "branches", ";", "}", ";", "const", "valuePropsTreesArray", "=", "Array", ".", "from", "(", "valuePropsTrees", ".", "entries", "(", ")", ")", ";", "return", "assertSingleBranch", "(", "topNode", ".", "debranch", "(", ")", ".", "map", "(", "branch", "=>", "valuePropsTreesArray", ".", "reduce", "(", "(", "res", ",", "pair", ")", "=>", "{", "const", "valuePropPath", "=", "pair", "[", "0", "]", ";", "const", "valuePropsTree", "=", "pair", "[", "1", "]", ";", "if", "(", "!", "res", ".", "includesProp", "(", "valuePropPath", ")", ")", "return", "res", ";", "return", "res", ".", "combine", "(", "valuePropsTree", ")", ";", "}", ",", "branch", ")", ")", ",", "scopePropPath", ")", ";", "}" ]
Build properties tree from a list of property path patterns and debranch it. @protected @param {module:x2node-records~RecordTypesLibrary} recordTypes Record types library. @param {module:x2node-records~PropertyDescriptor} topPropDesc Descriptor of the top property in the resulting tree. For example, when the tree is being built for a query that fetches records of a given record type, this is the descriptor of the "records" super-property. @param {string} clause Clause for the tree. Every node in the resulting tree will be marked as used in this clause. @param {module:x2node-dbos~ValueExpressionContext} baseValueExprCtx Context for any value expressions used by the properties in the tree. All property nodes in the resulting tree will include this context's base path in their <code>path</code> property. @param {string} [scopePropPath] Optional scope property path, including the base value expression context's base path. If provided, any attempt to add a property to the tree that does not lie on the same collection axis with the scope property will result in an error. Thus, if this argument is provided, the resulting tree is guaranteed to have only a single branch. Note, that collections <em>below</em> the scope property are not allowed either. Therefore, trees built using the same scope property will combine into a tree that will still have only a single branch. @param {Iterable.<string>} propPatterns Patterns of properties to include in the tree. The patterns are relative to (that is do not include) the base value expression context's base path. @param {Object} [options] Tree building logic options, if any. @param {boolean} [options.noWildcards] If <code>true</code>, wildcard patterns are not allowed. @param {boolean} [options.noAggregates] If <code>true</code>, aggregate properties are not allowed in the tree. @param {boolean} [options.noCalculated] If <code>true</code>, neither calculated value nor aggregate properties are allowed in the tree. @param {boolean} [options.ignoreScopedOrders] If <code>true</code>, scoped order specifications on any included collection properties are ignored. @param {boolean} [options.noScopedFilters] If <code>true</code>, no collection properties with scoped filters are allowed in the tree. @returns {Array.<module:x2node-dbos~PropertyTreeNode>} The resulting properties tree branches. If scope property was provided, there will be always only one branch in the returned array. @throws {module:x2node-common.X2SyntaxError} If the provided specifications or participating property definitions are invalid.
[ "Build", "properties", "tree", "from", "a", "list", "of", "property", "path", "patterns", "and", "debranch", "it", "." ]
d7b847d859b79dce0c46e04788201e05d5a70886
https://github.com/boylesoftware/x2node-dbos/blob/d7b847d859b79dce0c46e04788201e05d5a70886/lib/props-tree-builder.js#L720-L779
49,046
boylesoftware/x2node-dbos
lib/props-tree-builder.js
buildSuperPropsTreeBranches
function buildSuperPropsTreeBranches( recordTypes, recordTypeDesc, superPropNames) { // create the branching tree top node const topNode = PropertyTreeNode.createTopNode( recordTypes, { isScalar() { return true; }, isCalculated() { return false; }, refTarget: recordTypeDesc.superRecordTypeName }, new ValueExpressionContext('', [ recordTypes.getRecordTypeDesc(recordTypeDesc.superRecordTypeName) ]), 'select'); // add super-properties to the tree const valuePropsTrees = new Map(); for (let superPropName of superPropNames) addProperty( topNode, null, superPropName, 'select', null, valuePropsTrees); // de-branch the tree and merge in the value trees const valuePropsTreesArray = Array.from(valuePropsTrees.entries()); return topNode.debranch().map( branch => valuePropsTreesArray.reduce((res, pair) => { const valuePropPath = pair[0]; const valuePropsTree = pair[1]; if (!res.includesProp(valuePropPath)) return res; return res.combine(valuePropsTree); }, branch) ); }
javascript
function buildSuperPropsTreeBranches( recordTypes, recordTypeDesc, superPropNames) { // create the branching tree top node const topNode = PropertyTreeNode.createTopNode( recordTypes, { isScalar() { return true; }, isCalculated() { return false; }, refTarget: recordTypeDesc.superRecordTypeName }, new ValueExpressionContext('', [ recordTypes.getRecordTypeDesc(recordTypeDesc.superRecordTypeName) ]), 'select'); // add super-properties to the tree const valuePropsTrees = new Map(); for (let superPropName of superPropNames) addProperty( topNode, null, superPropName, 'select', null, valuePropsTrees); // de-branch the tree and merge in the value trees const valuePropsTreesArray = Array.from(valuePropsTrees.entries()); return topNode.debranch().map( branch => valuePropsTreesArray.reduce((res, pair) => { const valuePropPath = pair[0]; const valuePropsTree = pair[1]; if (!res.includesProp(valuePropPath)) return res; return res.combine(valuePropsTree); }, branch) ); }
[ "function", "buildSuperPropsTreeBranches", "(", "recordTypes", ",", "recordTypeDesc", ",", "superPropNames", ")", "{", "// create the branching tree top node", "const", "topNode", "=", "PropertyTreeNode", ".", "createTopNode", "(", "recordTypes", ",", "{", "isScalar", "(", ")", "{", "return", "true", ";", "}", ",", "isCalculated", "(", ")", "{", "return", "false", ";", "}", ",", "refTarget", ":", "recordTypeDesc", ".", "superRecordTypeName", "}", ",", "new", "ValueExpressionContext", "(", "''", ",", "[", "recordTypes", ".", "getRecordTypeDesc", "(", "recordTypeDesc", ".", "superRecordTypeName", ")", "]", ")", ",", "'select'", ")", ";", "// add super-properties to the tree", "const", "valuePropsTrees", "=", "new", "Map", "(", ")", ";", "for", "(", "let", "superPropName", "of", "superPropNames", ")", "addProperty", "(", "topNode", ",", "null", ",", "superPropName", ",", "'select'", ",", "null", ",", "valuePropsTrees", ")", ";", "// de-branch the tree and merge in the value trees", "const", "valuePropsTreesArray", "=", "Array", ".", "from", "(", "valuePropsTrees", ".", "entries", "(", ")", ")", ";", "return", "topNode", ".", "debranch", "(", ")", ".", "map", "(", "branch", "=>", "valuePropsTreesArray", ".", "reduce", "(", "(", "res", ",", "pair", ")", "=>", "{", "const", "valuePropPath", "=", "pair", "[", "0", "]", ";", "const", "valuePropsTree", "=", "pair", "[", "1", "]", ";", "if", "(", "!", "res", ".", "includesProp", "(", "valuePropPath", ")", ")", "return", "res", ";", "return", "res", ".", "combine", "(", "valuePropsTree", ")", ";", "}", ",", "branch", ")", ")", ";", "}" ]
Build properties tree for a super-properties query and debranch it. @protected @param {module:x2node-records~RecordTypesLibrary} recordTypes Record types library. @param {module:x2node-records~RecordTypeDescriptor} recordTypeDesc Record type descriptor. @param {Iterable.<string>} superPropName Selected super-property names. @returns {Array.<module:x2node-dbos~PropertyTreeNode>} The resulting properties tree branches. @throws {module:x2node-common.X2SyntaxError} If the provided specifications or participating property definitions are invalid.
[ "Build", "properties", "tree", "for", "a", "super", "-", "properties", "query", "and", "debranch", "it", "." ]
d7b847d859b79dce0c46e04788201e05d5a70886
https://github.com/boylesoftware/x2node-dbos/blob/d7b847d859b79dce0c46e04788201e05d5a70886/lib/props-tree-builder.js#L795-L827
49,047
boylesoftware/x2node-dbos
lib/props-tree-builder.js
buildSimplePropsTree
function buildSimplePropsTree( recordTypes, topPropDesc, clause, baseValueExprCtx, propPaths) { // create the branching tree top node const topNode = PropertyTreeNode.createTopNode( recordTypes, topPropDesc, baseValueExprCtx, clause); // add properties const valuePropsTrees = new Map(); const options = { ignoreScopedOrders: true, ignorePresenceTests: (clause !== 'select') }; for (let propPath of propPaths) addProperty(topNode, null, propPath, clause, options, valuePropsTrees); // make sure there was no value trees if (valuePropsTrees.size > 0) throw new Error( 'Internal X2 error: unexpected value trees for ' + Array.from(valuePropsTrees.keys()).join(', ') + '.'); // return the tree return topNode; }
javascript
function buildSimplePropsTree( recordTypes, topPropDesc, clause, baseValueExprCtx, propPaths) { // create the branching tree top node const topNode = PropertyTreeNode.createTopNode( recordTypes, topPropDesc, baseValueExprCtx, clause); // add properties const valuePropsTrees = new Map(); const options = { ignoreScopedOrders: true, ignorePresenceTests: (clause !== 'select') }; for (let propPath of propPaths) addProperty(topNode, null, propPath, clause, options, valuePropsTrees); // make sure there was no value trees if (valuePropsTrees.size > 0) throw new Error( 'Internal X2 error: unexpected value trees for ' + Array.from(valuePropsTrees.keys()).join(', ') + '.'); // return the tree return topNode; }
[ "function", "buildSimplePropsTree", "(", "recordTypes", ",", "topPropDesc", ",", "clause", ",", "baseValueExprCtx", ",", "propPaths", ")", "{", "// create the branching tree top node", "const", "topNode", "=", "PropertyTreeNode", ".", "createTopNode", "(", "recordTypes", ",", "topPropDesc", ",", "baseValueExprCtx", ",", "clause", ")", ";", "// add properties", "const", "valuePropsTrees", "=", "new", "Map", "(", ")", ";", "const", "options", "=", "{", "ignoreScopedOrders", ":", "true", ",", "ignorePresenceTests", ":", "(", "clause", "!==", "'select'", ")", "}", ";", "for", "(", "let", "propPath", "of", "propPaths", ")", "addProperty", "(", "topNode", ",", "null", ",", "propPath", ",", "clause", ",", "options", ",", "valuePropsTrees", ")", ";", "// make sure there was no value trees", "if", "(", "valuePropsTrees", ".", "size", ">", "0", ")", "throw", "new", "Error", "(", "'Internal X2 error: unexpected value trees for '", "+", "Array", ".", "from", "(", "valuePropsTrees", ".", "keys", "(", ")", ")", ".", "join", "(", "', '", ")", "+", "'.'", ")", ";", "// return the tree", "return", "topNode", ";", "}" ]
Build possibly branching properties tree assuming no side-value trees are involved. @protected @param {module:x2node-records~RecordTypesLibrary} recordTypes Record types library. @param {module:x2node-records~PropertyDescriptor} topPropDesc Descriptor of the top property in the resulting tree. For example, when the tree is being built for a query against records of a given record type, this is the descriptor of the "records" super-property. @param {string} clause Clause for the tree. Every node in the resulting tree will be marked as used in this clause. @param {module:x2node-dbos~ValueExpressionContext} baseValueExprCtx Context for any value expressions used by the properties in the tree. All property nodes in the resulting tree will include this context's base path in their <code>path</code> property. @param {Iterable.<string>} propPaths Paths of properties to include in the tree. The paths are relative to (that is do not include) the base value expression context's base path. @returns {module:x2node-dbos~PropertyTreeNode} The resulting properties tree. @throws {module:x2node-common.X2SyntaxError} If the provided paths are invalid.
[ "Build", "possibly", "branching", "properties", "tree", "assuming", "no", "side", "-", "value", "trees", "are", "involved", "." ]
d7b847d859b79dce0c46e04788201e05d5a70886
https://github.com/boylesoftware/x2node-dbos/blob/d7b847d859b79dce0c46e04788201e05d5a70886/lib/props-tree-builder.js#L852-L876
49,048
boylesoftware/x2node-dbos
lib/props-tree-builder.js
addProperty
function addProperty( topNode, scopePropPath, propPattern, clause, options, valuePropsTrees, wcPatterns) { // process the pattern parts let expandChildren = false; const propPatternParts = propPattern.split('.'); const numParts = propPatternParts.length; let parentNode = topNode; let patternPrefix = topNode.path, patternSuffix = ''; for (let i = 0; i < numParts; i++) { const propName = propPatternParts[i]; // check if wildcard if (propName === '*') { // check if allowed if (!wcPatterns) throw new common.X2SyntaxError( `Invalid property path "${propPattern}":` + ` wild cards are not allowed here.`); // set up the expansion expandChildren = true; if (i < numParts - 1) patternSuffix = '.' + propPatternParts.slice(i + 1).join('.'); // done looping through pattern parts break; } // get the child node let node = parentNode.getChild(propName); // create new node if necessary if (!node) { // create new child node node = parentNode.addChild( propName, clause, scopePropPath, options, propPattern, valuePropsTrees); } else { // existing node // include the existing node in the clause node.addClause(clause); } // add part to the reconstructed pattern prefix patternPrefix += propName + '.'; // advance down the tree parentNode = node; } // expand selected object if (!expandChildren && (parentNode.desc.scalarValueType === 'object')) { // set up the expansion if (wcPatterns) expandChildren = true; else if (!(options && options.allowLeafObjects)) // check if allowed throw new common.X2SyntaxError( `Invalid property path "${propPattern}":` + ` object properties are not allowed here.`); } // generate expanded patterns if (expandChildren) { // make sure there is a children container if (!parentNode.childrenContainer) throw new common.X2SyntaxError( `Invalid property pattern "${propPattern}":` + ` property ${parentNode.desc.container.nestedPath}` + `${parentNode.desc.name} of ` + `${String(parentNode.desc.container.recordTypeName)}` + ` is not an object nor reference and cannot be used as an` + ` intermediate property in a path.`); // generate patterns for all nested properties included by default parentNode.childrenContainer.allPropertyNames.forEach(propName => { const propDesc = parentNode.childrenContainer.getPropertyDesc( propName); if (propDesc.fetchByDefault) wcPatterns.push(patternPrefix + propName + patternSuffix); }); } // return the leaf node return parentNode; }
javascript
function addProperty( topNode, scopePropPath, propPattern, clause, options, valuePropsTrees, wcPatterns) { // process the pattern parts let expandChildren = false; const propPatternParts = propPattern.split('.'); const numParts = propPatternParts.length; let parentNode = topNode; let patternPrefix = topNode.path, patternSuffix = ''; for (let i = 0; i < numParts; i++) { const propName = propPatternParts[i]; // check if wildcard if (propName === '*') { // check if allowed if (!wcPatterns) throw new common.X2SyntaxError( `Invalid property path "${propPattern}":` + ` wild cards are not allowed here.`); // set up the expansion expandChildren = true; if (i < numParts - 1) patternSuffix = '.' + propPatternParts.slice(i + 1).join('.'); // done looping through pattern parts break; } // get the child node let node = parentNode.getChild(propName); // create new node if necessary if (!node) { // create new child node node = parentNode.addChild( propName, clause, scopePropPath, options, propPattern, valuePropsTrees); } else { // existing node // include the existing node in the clause node.addClause(clause); } // add part to the reconstructed pattern prefix patternPrefix += propName + '.'; // advance down the tree parentNode = node; } // expand selected object if (!expandChildren && (parentNode.desc.scalarValueType === 'object')) { // set up the expansion if (wcPatterns) expandChildren = true; else if (!(options && options.allowLeafObjects)) // check if allowed throw new common.X2SyntaxError( `Invalid property path "${propPattern}":` + ` object properties are not allowed here.`); } // generate expanded patterns if (expandChildren) { // make sure there is a children container if (!parentNode.childrenContainer) throw new common.X2SyntaxError( `Invalid property pattern "${propPattern}":` + ` property ${parentNode.desc.container.nestedPath}` + `${parentNode.desc.name} of ` + `${String(parentNode.desc.container.recordTypeName)}` + ` is not an object nor reference and cannot be used as an` + ` intermediate property in a path.`); // generate patterns for all nested properties included by default parentNode.childrenContainer.allPropertyNames.forEach(propName => { const propDesc = parentNode.childrenContainer.getPropertyDesc( propName); if (propDesc.fetchByDefault) wcPatterns.push(patternPrefix + propName + patternSuffix); }); } // return the leaf node return parentNode; }
[ "function", "addProperty", "(", "topNode", ",", "scopePropPath", ",", "propPattern", ",", "clause", ",", "options", ",", "valuePropsTrees", ",", "wcPatterns", ")", "{", "// process the pattern parts", "let", "expandChildren", "=", "false", ";", "const", "propPatternParts", "=", "propPattern", ".", "split", "(", "'.'", ")", ";", "const", "numParts", "=", "propPatternParts", ".", "length", ";", "let", "parentNode", "=", "topNode", ";", "let", "patternPrefix", "=", "topNode", ".", "path", ",", "patternSuffix", "=", "''", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "numParts", ";", "i", "++", ")", "{", "const", "propName", "=", "propPatternParts", "[", "i", "]", ";", "// check if wildcard", "if", "(", "propName", "===", "'*'", ")", "{", "// check if allowed", "if", "(", "!", "wcPatterns", ")", "throw", "new", "common", ".", "X2SyntaxError", "(", "`", "${", "propPattern", "}", "`", "+", "`", "`", ")", ";", "// set up the expansion", "expandChildren", "=", "true", ";", "if", "(", "i", "<", "numParts", "-", "1", ")", "patternSuffix", "=", "'.'", "+", "propPatternParts", ".", "slice", "(", "i", "+", "1", ")", ".", "join", "(", "'.'", ")", ";", "// done looping through pattern parts", "break", ";", "}", "// get the child node", "let", "node", "=", "parentNode", ".", "getChild", "(", "propName", ")", ";", "// create new node if necessary", "if", "(", "!", "node", ")", "{", "// create new child node", "node", "=", "parentNode", ".", "addChild", "(", "propName", ",", "clause", ",", "scopePropPath", ",", "options", ",", "propPattern", ",", "valuePropsTrees", ")", ";", "}", "else", "{", "// existing node", "// include the existing node in the clause", "node", ".", "addClause", "(", "clause", ")", ";", "}", "// add part to the reconstructed pattern prefix", "patternPrefix", "+=", "propName", "+", "'.'", ";", "// advance down the tree", "parentNode", "=", "node", ";", "}", "// expand selected object", "if", "(", "!", "expandChildren", "&&", "(", "parentNode", ".", "desc", ".", "scalarValueType", "===", "'object'", ")", ")", "{", "// set up the expansion", "if", "(", "wcPatterns", ")", "expandChildren", "=", "true", ";", "else", "if", "(", "!", "(", "options", "&&", "options", ".", "allowLeafObjects", ")", ")", "// check if allowed", "throw", "new", "common", ".", "X2SyntaxError", "(", "`", "${", "propPattern", "}", "`", "+", "`", "`", ")", ";", "}", "// generate expanded patterns", "if", "(", "expandChildren", ")", "{", "// make sure there is a children container", "if", "(", "!", "parentNode", ".", "childrenContainer", ")", "throw", "new", "common", ".", "X2SyntaxError", "(", "`", "${", "propPattern", "}", "`", "+", "`", "${", "parentNode", ".", "desc", ".", "container", ".", "nestedPath", "}", "`", "+", "`", "${", "parentNode", ".", "desc", ".", "name", "}", "`", "+", "`", "${", "String", "(", "parentNode", ".", "desc", ".", "container", ".", "recordTypeName", ")", "}", "`", "+", "`", "`", "+", "`", "`", ")", ";", "// generate patterns for all nested properties included by default", "parentNode", ".", "childrenContainer", ".", "allPropertyNames", ".", "forEach", "(", "propName", "=>", "{", "const", "propDesc", "=", "parentNode", ".", "childrenContainer", ".", "getPropertyDesc", "(", "propName", ")", ";", "if", "(", "propDesc", ".", "fetchByDefault", ")", "wcPatterns", ".", "push", "(", "patternPrefix", "+", "propName", "+", "patternSuffix", ")", ";", "}", ")", ";", "}", "// return the leaf node", "return", "parentNode", ";", "}" ]
Add property to the properties tree. @private @param {module:x2node-dbos~PropertyTreeNode} topNode Top node of the properties tree. @param {?string} scopeColPath Path of the scope collection property. If provided, the pattern may only belong to the scope collection property's axis. @param {string} propPattern Property pattern. May be a wildcard pattern if the <code>clause</code> argument is "select". @param {string} clause The query clause where the property is used. @param {Map.<string,module:x2node-dbos~PropertyTreeNode>} valuePropsTrees Map, to which to add generated value property trees. @param {Array.<string>} wcPatterns Array, to which to add extra patterns resulting in the wildcard pattern expansion. Not used unless the <code>clause</code> argument is "select". @returns {module:x2node-dbos~PropertyTreeNode} The leaf node representing the property.
[ "Add", "property", "to", "the", "properties", "tree", "." ]
d7b847d859b79dce0c46e04788201e05d5a70886
https://github.com/boylesoftware/x2node-dbos/blob/d7b847d859b79dce0c46e04788201e05d5a70886/lib/props-tree-builder.js#L897-L988
49,049
hash-bang/Node-Mongoose-Scenario
index.js
function(model, options, finish) { var asyncCreator = async() // Task runner that actually creates all the Mongo records // Deal with timeout errors (usually unsolvable circular references) {{{ .timeout(settings.timeout || 2000, function() { var taskIDs = {}; var remaining = this._struct // Prepare a lookup table of tasks IDs that have already finished {{{ .map(function(task) { if (task.completed) taskIDs[_(task.payload).keys().first()] = true; return task; }) // }}} // Remove non defered objects + completed tasks {{{ .filter(function(task) { return (task.type == 'deferObject' && !task.completed); }) // }}} // Remove any task that has resolved prereqs {{{ .filter(function(task) { if (!task.prereq.length) return true; // Has no prereqs anyway return ! task.prereq .every(function(prereq) { return (!! taskIDs[prereq]); }); }) // }}} // Remove any task that nothing else depends on {{{ .filter(function(task) { return true; }); // }}} finish( 'Unresolvable circular reference\n' + 'Remaining refs:\n' + remaining // Format the output {{{ .map(function(task) { return ( ' * ' + (_(task.payload).keys().first() || '???') + (task.prereq.length > 0 ? ' (Requires: ' + task.prereq .filter(function(prereq) { return (! taskIDs[prereq]); // Pre-req resolved ok? }) .join(', ') + ')': '') ); }) .join('\n') // }}} , { unresolved: remaining.map(function(task) { return _(task.payload).keys().first(); }), processed: this._struct .filter(function(task) { return (task.type == 'deferObject' && task.completed); }) .length, }); }); // }}} async() .then(function(next) { // Coherce args into scenario(<model>, [options], [callback]) {{{ if (!model) throw new Error('No arguments passed to scenario()'); if (_.isFunction(options)) { // Form: (model, callback) finish = options; } else if (options) { // Form: model(model, options) _.merge(settings, options); } if (!finish) finish = function() {}; next(); }) // }}} .then(function(next) { // Sanity checks {{{ if (!settings.connection) throw new Error('Invalid connection to Mongoose'); if (!_.isObject(model)) throw new Error('Invalid scenario invoke style - scenario(' + typeof model + ')'); next(); }) // }}} .then(function(next) { // Reset all state variables {{{ settings.progress.created = {}; if (settings.reset) settings.refs = {}; next(); }) /// }}} .then(function(next) { // Optionally Nuke existing models {{{ if (!settings.nuke) return next(); async() .set('models', _.isArray(settings.nuke) ? settings.nuke : settings.getModels()) .forEach('models', function(next, model) { var collection = settings.getCollection(model); if (!collection) return next('Model "' + model + '" is present in the Scenario schema but no model can be found matching that name, did you forget to load it?'); collection.remove({}, function(err) { if (err) next(err); settings.progress.nuked.push(model); next(); }); }) .end(next); }) // }}} .forEach(model, function(next, rows, collection) { // Compute FKs for each model {{{ if (settings.knownFK[collection]) return next(); // Already computed the FKs for this collection settings.knownFK[collection] = {}; var collectionSchema = settings.getCollectionSchema(collection); if (!collectionSchema) throw new Error('Collection "' + collection + '" not found in Mongoose schema. Did you forget to load its model?'); // Merge extracted keys into knownFKs storage settings.knownFK[collection] = extractFKs(collectionSchema); next(); }) // }}} .forEach(model, function(next, rows, collection) { // Process the Scenario profile {{{ async() .forEach(rows, function(next, row) { // Split all incomming items into defered tasks {{{ var rowFlattened = flatten(row); var id = row[settings.keys.ref] ? row[settings.keys.ref] : 'anon-' + settings.idVal++; var dependents = determineFKs(rowFlattened, settings.knownFK[collection]); var rowUnflattened = unflatten(rowFlattened); asyncCreator.defer(dependents, id, function(next) { createRow(collection, id, rowUnflattened, next); }); next(); }) // }}} .end(next); }) // }}} .then(function(next) { // Run all tasks {{{ asyncCreator .await() .end(next); }) // }}} // End {{{ .end(function(err) { if (err) return finish(err); finish(null, settings.progress); }); // }}} return scenarioImport; }
javascript
function(model, options, finish) { var asyncCreator = async() // Task runner that actually creates all the Mongo records // Deal with timeout errors (usually unsolvable circular references) {{{ .timeout(settings.timeout || 2000, function() { var taskIDs = {}; var remaining = this._struct // Prepare a lookup table of tasks IDs that have already finished {{{ .map(function(task) { if (task.completed) taskIDs[_(task.payload).keys().first()] = true; return task; }) // }}} // Remove non defered objects + completed tasks {{{ .filter(function(task) { return (task.type == 'deferObject' && !task.completed); }) // }}} // Remove any task that has resolved prereqs {{{ .filter(function(task) { if (!task.prereq.length) return true; // Has no prereqs anyway return ! task.prereq .every(function(prereq) { return (!! taskIDs[prereq]); }); }) // }}} // Remove any task that nothing else depends on {{{ .filter(function(task) { return true; }); // }}} finish( 'Unresolvable circular reference\n' + 'Remaining refs:\n' + remaining // Format the output {{{ .map(function(task) { return ( ' * ' + (_(task.payload).keys().first() || '???') + (task.prereq.length > 0 ? ' (Requires: ' + task.prereq .filter(function(prereq) { return (! taskIDs[prereq]); // Pre-req resolved ok? }) .join(', ') + ')': '') ); }) .join('\n') // }}} , { unresolved: remaining.map(function(task) { return _(task.payload).keys().first(); }), processed: this._struct .filter(function(task) { return (task.type == 'deferObject' && task.completed); }) .length, }); }); // }}} async() .then(function(next) { // Coherce args into scenario(<model>, [options], [callback]) {{{ if (!model) throw new Error('No arguments passed to scenario()'); if (_.isFunction(options)) { // Form: (model, callback) finish = options; } else if (options) { // Form: model(model, options) _.merge(settings, options); } if (!finish) finish = function() {}; next(); }) // }}} .then(function(next) { // Sanity checks {{{ if (!settings.connection) throw new Error('Invalid connection to Mongoose'); if (!_.isObject(model)) throw new Error('Invalid scenario invoke style - scenario(' + typeof model + ')'); next(); }) // }}} .then(function(next) { // Reset all state variables {{{ settings.progress.created = {}; if (settings.reset) settings.refs = {}; next(); }) /// }}} .then(function(next) { // Optionally Nuke existing models {{{ if (!settings.nuke) return next(); async() .set('models', _.isArray(settings.nuke) ? settings.nuke : settings.getModels()) .forEach('models', function(next, model) { var collection = settings.getCollection(model); if (!collection) return next('Model "' + model + '" is present in the Scenario schema but no model can be found matching that name, did you forget to load it?'); collection.remove({}, function(err) { if (err) next(err); settings.progress.nuked.push(model); next(); }); }) .end(next); }) // }}} .forEach(model, function(next, rows, collection) { // Compute FKs for each model {{{ if (settings.knownFK[collection]) return next(); // Already computed the FKs for this collection settings.knownFK[collection] = {}; var collectionSchema = settings.getCollectionSchema(collection); if (!collectionSchema) throw new Error('Collection "' + collection + '" not found in Mongoose schema. Did you forget to load its model?'); // Merge extracted keys into knownFKs storage settings.knownFK[collection] = extractFKs(collectionSchema); next(); }) // }}} .forEach(model, function(next, rows, collection) { // Process the Scenario profile {{{ async() .forEach(rows, function(next, row) { // Split all incomming items into defered tasks {{{ var rowFlattened = flatten(row); var id = row[settings.keys.ref] ? row[settings.keys.ref] : 'anon-' + settings.idVal++; var dependents = determineFKs(rowFlattened, settings.knownFK[collection]); var rowUnflattened = unflatten(rowFlattened); asyncCreator.defer(dependents, id, function(next) { createRow(collection, id, rowUnflattened, next); }); next(); }) // }}} .end(next); }) // }}} .then(function(next) { // Run all tasks {{{ asyncCreator .await() .end(next); }) // }}} // End {{{ .end(function(err) { if (err) return finish(err); finish(null, settings.progress); }); // }}} return scenarioImport; }
[ "function", "(", "model", ",", "options", ",", "finish", ")", "{", "var", "asyncCreator", "=", "async", "(", ")", "// Task runner that actually creates all the Mongo records", "// Deal with timeout errors (usually unsolvable circular references) {{{", ".", "timeout", "(", "settings", ".", "timeout", "||", "2000", ",", "function", "(", ")", "{", "var", "taskIDs", "=", "{", "}", ";", "var", "remaining", "=", "this", ".", "_struct", "// Prepare a lookup table of tasks IDs that have already finished {{{", ".", "map", "(", "function", "(", "task", ")", "{", "if", "(", "task", ".", "completed", ")", "taskIDs", "[", "_", "(", "task", ".", "payload", ")", ".", "keys", "(", ")", ".", "first", "(", ")", "]", "=", "true", ";", "return", "task", ";", "}", ")", "// }}}", "// Remove non defered objects + completed tasks {{{", ".", "filter", "(", "function", "(", "task", ")", "{", "return", "(", "task", ".", "type", "==", "'deferObject'", "&&", "!", "task", ".", "completed", ")", ";", "}", ")", "// }}}", "// Remove any task that has resolved prereqs {{{", ".", "filter", "(", "function", "(", "task", ")", "{", "if", "(", "!", "task", ".", "prereq", ".", "length", ")", "return", "true", ";", "// Has no prereqs anyway", "return", "!", "task", ".", "prereq", ".", "every", "(", "function", "(", "prereq", ")", "{", "return", "(", "!", "!", "taskIDs", "[", "prereq", "]", ")", ";", "}", ")", ";", "}", ")", "// }}}", "// Remove any task that nothing else depends on {{{", ".", "filter", "(", "function", "(", "task", ")", "{", "return", "true", ";", "}", ")", ";", "// }}}", "finish", "(", "'Unresolvable circular reference\\n'", "+", "'Remaining refs:\\n'", "+", "remaining", "// Format the output {{{", ".", "map", "(", "function", "(", "task", ")", "{", "return", "(", "' * '", "+", "(", "_", "(", "task", ".", "payload", ")", ".", "keys", "(", ")", ".", "first", "(", ")", "||", "'???'", ")", "+", "(", "task", ".", "prereq", ".", "length", ">", "0", "?", "' (Requires: '", "+", "task", ".", "prereq", ".", "filter", "(", "function", "(", "prereq", ")", "{", "return", "(", "!", "taskIDs", "[", "prereq", "]", ")", ";", "// Pre-req resolved ok?", "}", ")", ".", "join", "(", "', '", ")", "+", "')'", ":", "''", ")", ")", ";", "}", ")", ".", "join", "(", "'\\n'", ")", "// }}}", ",", "{", "unresolved", ":", "remaining", ".", "map", "(", "function", "(", "task", ")", "{", "return", "_", "(", "task", ".", "payload", ")", ".", "keys", "(", ")", ".", "first", "(", ")", ";", "}", ")", ",", "processed", ":", "this", ".", "_struct", ".", "filter", "(", "function", "(", "task", ")", "{", "return", "(", "task", ".", "type", "==", "'deferObject'", "&&", "task", ".", "completed", ")", ";", "}", ")", ".", "length", ",", "}", ")", ";", "}", ")", ";", "// }}}", "async", "(", ")", ".", "then", "(", "function", "(", "next", ")", "{", "// Coherce args into scenario(<model>, [options], [callback]) {{{", "if", "(", "!", "model", ")", "throw", "new", "Error", "(", "'No arguments passed to scenario()'", ")", ";", "if", "(", "_", ".", "isFunction", "(", "options", ")", ")", "{", "// Form: (model, callback)", "finish", "=", "options", ";", "}", "else", "if", "(", "options", ")", "{", "// Form: model(model, options)", "_", ".", "merge", "(", "settings", ",", "options", ")", ";", "}", "if", "(", "!", "finish", ")", "finish", "=", "function", "(", ")", "{", "}", ";", "next", "(", ")", ";", "}", ")", "// }}}", ".", "then", "(", "function", "(", "next", ")", "{", "// Sanity checks {{{", "if", "(", "!", "settings", ".", "connection", ")", "throw", "new", "Error", "(", "'Invalid connection to Mongoose'", ")", ";", "if", "(", "!", "_", ".", "isObject", "(", "model", ")", ")", "throw", "new", "Error", "(", "'Invalid scenario invoke style - scenario('", "+", "typeof", "model", "+", "')'", ")", ";", "next", "(", ")", ";", "}", ")", "// }}}", ".", "then", "(", "function", "(", "next", ")", "{", "// Reset all state variables {{{", "settings", ".", "progress", ".", "created", "=", "{", "}", ";", "if", "(", "settings", ".", "reset", ")", "settings", ".", "refs", "=", "{", "}", ";", "next", "(", ")", ";", "}", ")", "/// }}}", ".", "then", "(", "function", "(", "next", ")", "{", "// Optionally Nuke existing models {{{", "if", "(", "!", "settings", ".", "nuke", ")", "return", "next", "(", ")", ";", "async", "(", ")", ".", "set", "(", "'models'", ",", "_", ".", "isArray", "(", "settings", ".", "nuke", ")", "?", "settings", ".", "nuke", ":", "settings", ".", "getModels", "(", ")", ")", ".", "forEach", "(", "'models'", ",", "function", "(", "next", ",", "model", ")", "{", "var", "collection", "=", "settings", ".", "getCollection", "(", "model", ")", ";", "if", "(", "!", "collection", ")", "return", "next", "(", "'Model \"'", "+", "model", "+", "'\" is present in the Scenario schema but no model can be found matching that name, did you forget to load it?'", ")", ";", "collection", ".", "remove", "(", "{", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "next", "(", "err", ")", ";", "settings", ".", "progress", ".", "nuked", ".", "push", "(", "model", ")", ";", "next", "(", ")", ";", "}", ")", ";", "}", ")", ".", "end", "(", "next", ")", ";", "}", ")", "// }}}", ".", "forEach", "(", "model", ",", "function", "(", "next", ",", "rows", ",", "collection", ")", "{", "// Compute FKs for each model {{{", "if", "(", "settings", ".", "knownFK", "[", "collection", "]", ")", "return", "next", "(", ")", ";", "// Already computed the FKs for this collection", "settings", ".", "knownFK", "[", "collection", "]", "=", "{", "}", ";", "var", "collectionSchema", "=", "settings", ".", "getCollectionSchema", "(", "collection", ")", ";", "if", "(", "!", "collectionSchema", ")", "throw", "new", "Error", "(", "'Collection \"'", "+", "collection", "+", "'\" not found in Mongoose schema. Did you forget to load its model?'", ")", ";", "// Merge extracted keys into knownFKs storage", "settings", ".", "knownFK", "[", "collection", "]", "=", "extractFKs", "(", "collectionSchema", ")", ";", "next", "(", ")", ";", "}", ")", "// }}}", ".", "forEach", "(", "model", ",", "function", "(", "next", ",", "rows", ",", "collection", ")", "{", "// Process the Scenario profile {{{", "async", "(", ")", ".", "forEach", "(", "rows", ",", "function", "(", "next", ",", "row", ")", "{", "// Split all incomming items into defered tasks {{{", "var", "rowFlattened", "=", "flatten", "(", "row", ")", ";", "var", "id", "=", "row", "[", "settings", ".", "keys", ".", "ref", "]", "?", "row", "[", "settings", ".", "keys", ".", "ref", "]", ":", "'anon-'", "+", "settings", ".", "idVal", "++", ";", "var", "dependents", "=", "determineFKs", "(", "rowFlattened", ",", "settings", ".", "knownFK", "[", "collection", "]", ")", ";", "var", "rowUnflattened", "=", "unflatten", "(", "rowFlattened", ")", ";", "asyncCreator", ".", "defer", "(", "dependents", ",", "id", ",", "function", "(", "next", ")", "{", "createRow", "(", "collection", ",", "id", ",", "rowUnflattened", ",", "next", ")", ";", "}", ")", ";", "next", "(", ")", ";", "}", ")", "// }}}", ".", "end", "(", "next", ")", ";", "}", ")", "// }}}", ".", "then", "(", "function", "(", "next", ")", "{", "// Run all tasks {{{", "asyncCreator", ".", "await", "(", ")", ".", "end", "(", "next", ")", ";", "}", ")", "// }}}", "// End {{{", ".", "end", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "finish", "(", "err", ")", ";", "finish", "(", "null", ",", "settings", ".", "progress", ")", ";", "}", ")", ";", "// }}}", "return", "scenarioImport", ";", "}" ]
Import a scenario file into a Mongo database A scenario must be complete - i.e. have no dangling references for it to suceed @param {Object} model The scenario to create - expected format is a hash of collection names each containing a collection of records (e.g. `{users: [{name: 'user1'}, {name: 'user2'}] }`) @param {Object} settings Optional Settings array to import @param {function} finish(err, data) Optional callback fired when scenario finishes creating records
[ "Import", "a", "scenario", "file", "into", "a", "Mongo", "database", "A", "scenario", "must", "be", "complete", "-", "i", ".", "e", ".", "have", "no", "dangling", "references", "for", "it", "to", "suceed" ]
e50ed7f2f420fb0df317c1ef1b5262fd354c4b78
https://github.com/hash-bang/Node-Mongoose-Scenario/blob/e50ed7f2f420fb0df317c1ef1b5262fd354c4b78/index.js#L63-L206
49,050
hash-bang/Node-Mongoose-Scenario
index.js
extractFKs
function extractFKs(schema) { var FKs = {}; _.forEach(schema.paths, function(path, id) { if (id == 'id' || id == '_id') { // Pass } else if (path.instance && path.instance == 'ObjectID') { FKs[id] = {type: FK_OBJECTID}; } else if (path.caster && path.caster.instance == 'ObjectID') { // Array of ObjectIDs FKs[id] = {type: FK_OBJECTID_ARRAY}; } else if (path.schema) { FKs[id] = { type: FK_SUBDOC, fks: extractFKs(path.schema), }; } }); return FKs; }
javascript
function extractFKs(schema) { var FKs = {}; _.forEach(schema.paths, function(path, id) { if (id == 'id' || id == '_id') { // Pass } else if (path.instance && path.instance == 'ObjectID') { FKs[id] = {type: FK_OBJECTID}; } else if (path.caster && path.caster.instance == 'ObjectID') { // Array of ObjectIDs FKs[id] = {type: FK_OBJECTID_ARRAY}; } else if (path.schema) { FKs[id] = { type: FK_SUBDOC, fks: extractFKs(path.schema), }; } }); return FKs; }
[ "function", "extractFKs", "(", "schema", ")", "{", "var", "FKs", "=", "{", "}", ";", "_", ".", "forEach", "(", "schema", ".", "paths", ",", "function", "(", "path", ",", "id", ")", "{", "if", "(", "id", "==", "'id'", "||", "id", "==", "'_id'", ")", "{", "// Pass", "}", "else", "if", "(", "path", ".", "instance", "&&", "path", ".", "instance", "==", "'ObjectID'", ")", "{", "FKs", "[", "id", "]", "=", "{", "type", ":", "FK_OBJECTID", "}", ";", "}", "else", "if", "(", "path", ".", "caster", "&&", "path", ".", "caster", ".", "instance", "==", "'ObjectID'", ")", "{", "// Array of ObjectIDs", "FKs", "[", "id", "]", "=", "{", "type", ":", "FK_OBJECTID_ARRAY", "}", ";", "}", "else", "if", "(", "path", ".", "schema", ")", "{", "FKs", "[", "id", "]", "=", "{", "type", ":", "FK_SUBDOC", ",", "fks", ":", "extractFKs", "(", "path", ".", "schema", ")", ",", "}", ";", "}", "}", ")", ";", "return", "FKs", ";", "}" ]
Extract the FK relationship from a Mongo document @param {Object} schema The schema object to examine (usually connection.base.models[model].schema) @return {Object} A dictionary of foreign keys for the schema
[ "Extract", "the", "FK", "relationship", "from", "a", "Mongo", "document" ]
e50ed7f2f420fb0df317c1ef1b5262fd354c4b78
https://github.com/hash-bang/Node-Mongoose-Scenario/blob/e50ed7f2f420fb0df317c1ef1b5262fd354c4b78/index.js#L214-L233
49,051
hash-bang/Node-Mongoose-Scenario
index.js
injectFKs
function injectFKs(row, fks) { _.forEach(fks, function(fk, id) { if (!_.has(row, id)) return; // Skip omitted FK refs var lookupKey = _.get(row, id); switch (fk.type) { case FK_OBJECTID: // 1:1 relationship if (!settings.refs[lookupKey]) throw new Error('Attempting to inject non-existant reference "' + row[lookupKey] + '" (from lookup ref "' + lookupKey + '") into field path "' + id + '" before its been created!'); _.set(row, id, settings.refs[lookupKey]); break; case FK_OBJECTID_ARRAY: // 1:M array based relationship _.set(row, id, _.map(lookupKey, function(fieldValueArr) { // Resolve each item in the array if (!settings.refs[fieldValueArr]) throw new Error('Attempting to use reference "' + fieldValueArr + '" in 1:M field path "' + id + '" before its been created!'); return settings.refs[fieldValueArr]; })); break; case FK_SUBDOC: // Mongo subdocument _.forEach(_.get(row, id), function(subdocItem, subdocIndex) { injectFKs(subdocItem, fks[id].fks); }); break; } }); }
javascript
function injectFKs(row, fks) { _.forEach(fks, function(fk, id) { if (!_.has(row, id)) return; // Skip omitted FK refs var lookupKey = _.get(row, id); switch (fk.type) { case FK_OBJECTID: // 1:1 relationship if (!settings.refs[lookupKey]) throw new Error('Attempting to inject non-existant reference "' + row[lookupKey] + '" (from lookup ref "' + lookupKey + '") into field path "' + id + '" before its been created!'); _.set(row, id, settings.refs[lookupKey]); break; case FK_OBJECTID_ARRAY: // 1:M array based relationship _.set(row, id, _.map(lookupKey, function(fieldValueArr) { // Resolve each item in the array if (!settings.refs[fieldValueArr]) throw new Error('Attempting to use reference "' + fieldValueArr + '" in 1:M field path "' + id + '" before its been created!'); return settings.refs[fieldValueArr]; })); break; case FK_SUBDOC: // Mongo subdocument _.forEach(_.get(row, id), function(subdocItem, subdocIndex) { injectFKs(subdocItem, fks[id].fks); }); break; } }); }
[ "function", "injectFKs", "(", "row", ",", "fks", ")", "{", "_", ".", "forEach", "(", "fks", ",", "function", "(", "fk", ",", "id", ")", "{", "if", "(", "!", "_", ".", "has", "(", "row", ",", "id", ")", ")", "return", ";", "// Skip omitted FK refs", "var", "lookupKey", "=", "_", ".", "get", "(", "row", ",", "id", ")", ";", "switch", "(", "fk", ".", "type", ")", "{", "case", "FK_OBJECTID", ":", "// 1:1 relationship", "if", "(", "!", "settings", ".", "refs", "[", "lookupKey", "]", ")", "throw", "new", "Error", "(", "'Attempting to inject non-existant reference \"'", "+", "row", "[", "lookupKey", "]", "+", "'\" (from lookup ref \"'", "+", "lookupKey", "+", "'\") into field path \"'", "+", "id", "+", "'\" before its been created!'", ")", ";", "_", ".", "set", "(", "row", ",", "id", ",", "settings", ".", "refs", "[", "lookupKey", "]", ")", ";", "break", ";", "case", "FK_OBJECTID_ARRAY", ":", "// 1:M array based relationship", "_", ".", "set", "(", "row", ",", "id", ",", "_", ".", "map", "(", "lookupKey", ",", "function", "(", "fieldValueArr", ")", "{", "// Resolve each item in the array", "if", "(", "!", "settings", ".", "refs", "[", "fieldValueArr", "]", ")", "throw", "new", "Error", "(", "'Attempting to use reference \"'", "+", "fieldValueArr", "+", "'\" in 1:M field path \"'", "+", "id", "+", "'\" before its been created!'", ")", ";", "return", "settings", ".", "refs", "[", "fieldValueArr", "]", ";", "}", ")", ")", ";", "break", ";", "case", "FK_SUBDOC", ":", "// Mongo subdocument", "_", ".", "forEach", "(", "_", ".", "get", "(", "row", ",", "id", ")", ",", "function", "(", "subdocItem", ",", "subdocIndex", ")", "{", "injectFKs", "(", "subdocItem", ",", "fks", "[", "id", "]", ".", "fks", ")", ";", "}", ")", ";", "break", ";", "}", "}", ")", ";", "}" ]
Inject foreign keys into a row before it gets passed to Mongo for insert @param {Object} row The row that will be inserted - values will be replaced inline @param {Object} fks The foreign keys for the given row (extacted via extractFKs) @see extractFKs()
[ "Inject", "foreign", "keys", "into", "a", "row", "before", "it", "gets", "passed", "to", "Mongo", "for", "insert" ]
e50ed7f2f420fb0df317c1ef1b5262fd354c4b78
https://github.com/hash-bang/Node-Mongoose-Scenario/blob/e50ed7f2f420fb0df317c1ef1b5262fd354c4b78/index.js#L241-L266
49,052
hash-bang/Node-Mongoose-Scenario
index.js
determineFKs
function determineFKs(row, fks) { var refs = []; _.forEach(fks, function(fk, id) { if (row[id] === undefined) return; // Skip omitted FK refs switch (fk.type) { case FK_OBJECTID: // 1:1 relationship refs.push(row[id]); break; case FK_OBJECTID_ARRAY: // 1:M array based relationship _.forEach(row[id], function(v) { refs.push(v); }); break; case FK_SUBDOC: // Mongo subdocument _.forEach(row[id], function(v) { determineFKs(v, fks[id].fks).forEach(function(dep) { refs.push(dep); }); }); break; } }); return refs; }
javascript
function determineFKs(row, fks) { var refs = []; _.forEach(fks, function(fk, id) { if (row[id] === undefined) return; // Skip omitted FK refs switch (fk.type) { case FK_OBJECTID: // 1:1 relationship refs.push(row[id]); break; case FK_OBJECTID_ARRAY: // 1:M array based relationship _.forEach(row[id], function(v) { refs.push(v); }); break; case FK_SUBDOC: // Mongo subdocument _.forEach(row[id], function(v) { determineFKs(v, fks[id].fks).forEach(function(dep) { refs.push(dep); }); }); break; } }); return refs; }
[ "function", "determineFKs", "(", "row", ",", "fks", ")", "{", "var", "refs", "=", "[", "]", ";", "_", ".", "forEach", "(", "fks", ",", "function", "(", "fk", ",", "id", ")", "{", "if", "(", "row", "[", "id", "]", "===", "undefined", ")", "return", ";", "// Skip omitted FK refs", "switch", "(", "fk", ".", "type", ")", "{", "case", "FK_OBJECTID", ":", "// 1:1 relationship", "refs", ".", "push", "(", "row", "[", "id", "]", ")", ";", "break", ";", "case", "FK_OBJECTID_ARRAY", ":", "// 1:M array based relationship", "_", ".", "forEach", "(", "row", "[", "id", "]", ",", "function", "(", "v", ")", "{", "refs", ".", "push", "(", "v", ")", ";", "}", ")", ";", "break", ";", "case", "FK_SUBDOC", ":", "// Mongo subdocument", "_", ".", "forEach", "(", "row", "[", "id", "]", ",", "function", "(", "v", ")", "{", "determineFKs", "(", "v", ",", "fks", "[", "id", "]", ".", "fks", ")", ".", "forEach", "(", "function", "(", "dep", ")", "{", "refs", ".", "push", "(", "dep", ")", ";", "}", ")", ";", "}", ")", ";", "break", ";", "}", "}", ")", ";", "return", "refs", ";", "}" ]
Get an array of required foreign keys values so we can calculate the dependency tree @param {Object} row The row that will be inserted @param {Object} fks The foreign keys for the given row (extacted via extractFKs) @see extractFKs() @return {array} An array of required references
[ "Get", "an", "array", "of", "required", "foreign", "keys", "values", "so", "we", "can", "calculate", "the", "dependency", "tree" ]
e50ed7f2f420fb0df317c1ef1b5262fd354c4b78
https://github.com/hash-bang/Node-Mongoose-Scenario/blob/e50ed7f2f420fb0df317c1ef1b5262fd354c4b78/index.js#L275-L301
49,053
hash-bang/Node-Mongoose-Scenario
index.js
unflatten
function unflatten(obj) { var out = {}; _.forEach(obj, function(v, k) { _.set(out, k, v); }); return out; }
javascript
function unflatten(obj) { var out = {}; _.forEach(obj, function(v, k) { _.set(out, k, v); }); return out; }
[ "function", "unflatten", "(", "obj", ")", "{", "var", "out", "=", "{", "}", ";", "_", ".", "forEach", "(", "obj", ",", "function", "(", "v", ",", "k", ")", "{", "_", ".", "set", "(", "out", ",", "k", ",", "v", ")", ";", "}", ")", ";", "return", "out", ";", "}" ]
Take a flattened object and return a nested object @param {Object} obj The flattened object @return {Object} The unflattened object
[ "Take", "a", "flattened", "object", "and", "return", "a", "nested", "object" ]
e50ed7f2f420fb0df317c1ef1b5262fd354c4b78
https://github.com/hash-bang/Node-Mongoose-Scenario/blob/e50ed7f2f420fb0df317c1ef1b5262fd354c4b78/index.js#L332-L338
49,054
hash-bang/Node-Mongoose-Scenario
index.js
createRow
function createRow(collection, id, row, callback) { injectFKs(row, settings.knownFK[collection]); // build up list of all sub-document _ref's that we need to find in the newly saved document // this is to ensure we capture _id from inside nested array documents that do not exist at root level var refsMeta = []; traverse(row).forEach(function (value) { var path; if ('_ref' === this.key) { path = this.path.concat(); path[path.length - 1] = '_id'; refsMeta.push({ ref: value, path: path }); } }); row = _.omit(row, settings.omitFields); settings.getCollection(collection).create(row, function(err, newItem) { if (err) return callback(err); var newItemAsObject = newItem.toObject(); for(var i = 0; i < refsMeta.length; i++) { if (traverse(newItemAsObject).has(refsMeta[i].path)) { settings.refs[refsMeta[i].ref] = traverse(newItemAsObject).get(refsMeta[i].path).toString(); } } if (id) { // This unit has its own reference - add it to the stack settings.refs[id] = newItem._id.toString(); } if (!settings.progress.created[collection]) settings.progress.created[collection] = 0; settings.progress.created[collection]++; callback(null, newItem._id); }); }
javascript
function createRow(collection, id, row, callback) { injectFKs(row, settings.knownFK[collection]); // build up list of all sub-document _ref's that we need to find in the newly saved document // this is to ensure we capture _id from inside nested array documents that do not exist at root level var refsMeta = []; traverse(row).forEach(function (value) { var path; if ('_ref' === this.key) { path = this.path.concat(); path[path.length - 1] = '_id'; refsMeta.push({ ref: value, path: path }); } }); row = _.omit(row, settings.omitFields); settings.getCollection(collection).create(row, function(err, newItem) { if (err) return callback(err); var newItemAsObject = newItem.toObject(); for(var i = 0; i < refsMeta.length; i++) { if (traverse(newItemAsObject).has(refsMeta[i].path)) { settings.refs[refsMeta[i].ref] = traverse(newItemAsObject).get(refsMeta[i].path).toString(); } } if (id) { // This unit has its own reference - add it to the stack settings.refs[id] = newItem._id.toString(); } if (!settings.progress.created[collection]) settings.progress.created[collection] = 0; settings.progress.created[collection]++; callback(null, newItem._id); }); }
[ "function", "createRow", "(", "collection", ",", "id", ",", "row", ",", "callback", ")", "{", "injectFKs", "(", "row", ",", "settings", ".", "knownFK", "[", "collection", "]", ")", ";", "// build up list of all sub-document _ref's that we need to find in the newly saved document", "// this is to ensure we capture _id from inside nested array documents that do not exist at root level", "var", "refsMeta", "=", "[", "]", ";", "traverse", "(", "row", ")", ".", "forEach", "(", "function", "(", "value", ")", "{", "var", "path", ";", "if", "(", "'_ref'", "===", "this", ".", "key", ")", "{", "path", "=", "this", ".", "path", ".", "concat", "(", ")", ";", "path", "[", "path", ".", "length", "-", "1", "]", "=", "'_id'", ";", "refsMeta", ".", "push", "(", "{", "ref", ":", "value", ",", "path", ":", "path", "}", ")", ";", "}", "}", ")", ";", "row", "=", "_", ".", "omit", "(", "row", ",", "settings", ".", "omitFields", ")", ";", "settings", ".", "getCollection", "(", "collection", ")", ".", "create", "(", "row", ",", "function", "(", "err", ",", "newItem", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "var", "newItemAsObject", "=", "newItem", ".", "toObject", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "refsMeta", ".", "length", ";", "i", "++", ")", "{", "if", "(", "traverse", "(", "newItemAsObject", ")", ".", "has", "(", "refsMeta", "[", "i", "]", ".", "path", ")", ")", "{", "settings", ".", "refs", "[", "refsMeta", "[", "i", "]", ".", "ref", "]", "=", "traverse", "(", "newItemAsObject", ")", ".", "get", "(", "refsMeta", "[", "i", "]", ".", "path", ")", ".", "toString", "(", ")", ";", "}", "}", "if", "(", "id", ")", "{", "// This unit has its own reference - add it to the stack", "settings", ".", "refs", "[", "id", "]", "=", "newItem", ".", "_id", ".", "toString", "(", ")", ";", "}", "if", "(", "!", "settings", ".", "progress", ".", "created", "[", "collection", "]", ")", "settings", ".", "progress", ".", "created", "[", "collection", "]", "=", "0", ";", "settings", ".", "progress", ".", "created", "[", "collection", "]", "++", ";", "callback", "(", "null", ",", "newItem", ".", "_id", ")", ";", "}", ")", ";", "}" ]
Create a single row in a collection @param {string} collection The collection where to create the row @param {string} id The ID of the row (if any) @param {Object} row The (flattened) row contents to create @param {function} callback(err) Callback to chainable async function
[ "Create", "a", "single", "row", "in", "a", "collection" ]
e50ed7f2f420fb0df317c1ef1b5262fd354c4b78
https://github.com/hash-bang/Node-Mongoose-Scenario/blob/e50ed7f2f420fb0df317c1ef1b5262fd354c4b78/index.js#L348-L387
49,055
overlookmotel/bluebird-extra
lib/extensions.js
function(arr, iterator) { if (typeof iterator !== 'function') return apiRejection('iterator must be a function'); var self = this; var i = 0; return Promise.resolve().then(function iterate() { if (i == arr.length) return; return Promise.resolve(iterator.call(self, arr[i])) .then(function(result) { if (result !== undefined) return result; i++; return iterate(); }); }); }
javascript
function(arr, iterator) { if (typeof iterator !== 'function') return apiRejection('iterator must be a function'); var self = this; var i = 0; return Promise.resolve().then(function iterate() { if (i == arr.length) return; return Promise.resolve(iterator.call(self, arr[i])) .then(function(result) { if (result !== undefined) return result; i++; return iterate(); }); }); }
[ "function", "(", "arr", ",", "iterator", ")", "{", "if", "(", "typeof", "iterator", "!==", "'function'", ")", "return", "apiRejection", "(", "'iterator must be a function'", ")", ";", "var", "self", "=", "this", ";", "var", "i", "=", "0", ";", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "function", "iterate", "(", ")", "{", "if", "(", "i", "==", "arr", ".", "length", ")", "return", ";", "return", "Promise", ".", "resolve", "(", "iterator", ".", "call", "(", "self", ",", "arr", "[", "i", "]", ")", ")", ".", "then", "(", "function", "(", "result", ")", "{", "if", "(", "result", "!==", "undefined", ")", "return", "result", ";", "i", "++", ";", "return", "iterate", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
run iterator on each item in array in series return first result from iterator that is not undefined
[ "run", "iterator", "on", "each", "item", "in", "array", "in", "series", "return", "first", "result", "from", "iterator", "that", "is", "not", "undefined" ]
b6b1aa8e8a72edab34364e2059cf2ec270b8b455
https://github.com/overlookmotel/bluebird-extra/blob/b6b1aa8e8a72edab34364e2059cf2ec270b8b455/lib/extensions.js#L74-L90
49,056
overlookmotel/bluebird-extra
lib/extensions.js
function(value, ifFn, elseFn) { if ((ifFn && typeof ifFn !== 'function') || (elseFn && typeof elseFn !== 'function')) return apiRejection('ifFn and elseFn must be functions'); var fn = value ? ifFn : elseFn; if (!fn) return Promise.resolve(value); return Promise.resolve(fn.call(this, value)); }
javascript
function(value, ifFn, elseFn) { if ((ifFn && typeof ifFn !== 'function') || (elseFn && typeof elseFn !== 'function')) return apiRejection('ifFn and elseFn must be functions'); var fn = value ? ifFn : elseFn; if (!fn) return Promise.resolve(value); return Promise.resolve(fn.call(this, value)); }
[ "function", "(", "value", ",", "ifFn", ",", "elseFn", ")", "{", "if", "(", "(", "ifFn", "&&", "typeof", "ifFn", "!==", "'function'", ")", "||", "(", "elseFn", "&&", "typeof", "elseFn", "!==", "'function'", ")", ")", "return", "apiRejection", "(", "'ifFn and elseFn must be functions'", ")", ";", "var", "fn", "=", "value", "?", "ifFn", ":", "elseFn", ";", "if", "(", "!", "fn", ")", "return", "Promise", ".", "resolve", "(", "value", ")", ";", "return", "Promise", ".", "resolve", "(", "fn", ".", "call", "(", "this", ",", "value", ")", ")", ";", "}" ]
if value is truthy, run ifFn, otherwise run elseFn returns value for whichever function is run
[ "if", "value", "is", "truthy", "run", "ifFn", "otherwise", "run", "elseFn", "returns", "value", "for", "whichever", "function", "is", "run" ]
b6b1aa8e8a72edab34364e2059cf2ec270b8b455
https://github.com/overlookmotel/bluebird-extra/blob/b6b1aa8e8a72edab34364e2059cf2ec270b8b455/lib/extensions.js#L94-L101
49,057
owstack/ows-common
lib/buffer.js
fill
function fill(buffer, value) { $.checkArgumentType(buffer, 'Buffer', 'buffer'); $.checkArgumentType(value, 'number', 'value'); var length = buffer.length; for (var i = 0; i < length; i++) { buffer[i] = value; } return buffer; }
javascript
function fill(buffer, value) { $.checkArgumentType(buffer, 'Buffer', 'buffer'); $.checkArgumentType(value, 'number', 'value'); var length = buffer.length; for (var i = 0; i < length; i++) { buffer[i] = value; } return buffer; }
[ "function", "fill", "(", "buffer", ",", "value", ")", "{", "$", ".", "checkArgumentType", "(", "buffer", ",", "'Buffer'", ",", "'buffer'", ")", ";", "$", ".", "checkArgumentType", "(", "value", ",", "'number'", ",", "'value'", ")", ";", "var", "length", "=", "buffer", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "buffer", "[", "i", "]", "=", "value", ";", "}", "return", "buffer", ";", "}" ]
Fill a buffer with a value. @param {Buffer} buffer @param {number} value @return {Buffer}
[ "Fill", "a", "buffer", "with", "a", "value", "." ]
aa2a7970547cf451c06e528472ee965d3b4cac36
https://github.com/owstack/ows-common/blob/aa2a7970547cf451c06e528472ee965d3b4cac36/lib/buffer.js#L30-L38
49,058
owstack/ows-common
lib/buffer.js
emptyBuffer
function emptyBuffer(bytes) { $.checkArgumentType(bytes, 'number', 'bytes'); var result = new buffer.Buffer(bytes); for (var i = 0; i < bytes; i++) { result.write('\0', i); } return result; }
javascript
function emptyBuffer(bytes) { $.checkArgumentType(bytes, 'number', 'bytes'); var result = new buffer.Buffer(bytes); for (var i = 0; i < bytes; i++) { result.write('\0', i); } return result; }
[ "function", "emptyBuffer", "(", "bytes", ")", "{", "$", ".", "checkArgumentType", "(", "bytes", ",", "'number'", ",", "'bytes'", ")", ";", "var", "result", "=", "new", "buffer", ".", "Buffer", "(", "bytes", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "bytes", ";", "i", "++", ")", "{", "result", ".", "write", "(", "'\\0'", ",", "i", ")", ";", "}", "return", "result", ";", "}" ]
Returns a zero-filled byte array @param {number} bytes @return {Buffer}
[ "Returns", "a", "zero", "-", "filled", "byte", "array" ]
aa2a7970547cf451c06e528472ee965d3b4cac36
https://github.com/owstack/ows-common/blob/aa2a7970547cf451c06e528472ee965d3b4cac36/lib/buffer.js#L69-L76
49,059
owstack/ows-common
lib/buffer.js
integerAsBuffer
function integerAsBuffer(integer) { $.checkArgumentType(integer, 'number', 'integer'); var bytes = []; bytes.push((integer >> 24) & 0xff); bytes.push((integer >> 16) & 0xff); bytes.push((integer >> 8) & 0xff); bytes.push(integer & 0xff); return new Buffer(bytes); }
javascript
function integerAsBuffer(integer) { $.checkArgumentType(integer, 'number', 'integer'); var bytes = []; bytes.push((integer >> 24) & 0xff); bytes.push((integer >> 16) & 0xff); bytes.push((integer >> 8) & 0xff); bytes.push(integer & 0xff); return new Buffer(bytes); }
[ "function", "integerAsBuffer", "(", "integer", ")", "{", "$", ".", "checkArgumentType", "(", "integer", ",", "'number'", ",", "'integer'", ")", ";", "var", "bytes", "=", "[", "]", ";", "bytes", ".", "push", "(", "(", "integer", ">>", "24", ")", "&", "0xff", ")", ";", "bytes", ".", "push", "(", "(", "integer", ">>", "16", ")", "&", "0xff", ")", ";", "bytes", ".", "push", "(", "(", "integer", ">>", "8", ")", "&", "0xff", ")", ";", "bytes", ".", "push", "(", "integer", "&", "0xff", ")", ";", "return", "new", "Buffer", "(", "bytes", ")", ";", "}" ]
Transform a 4-byte integer into a Buffer of length 4. @param {number} integer @return {Buffer}
[ "Transform", "a", "4", "-", "byte", "integer", "into", "a", "Buffer", "of", "length", "4", "." ]
aa2a7970547cf451c06e528472ee965d3b4cac36
https://github.com/owstack/ows-common/blob/aa2a7970547cf451c06e528472ee965d3b4cac36/lib/buffer.js#L105-L113
49,060
owstack/ows-common
lib/buffer.js
reverse
function reverse(param) { var ret = new buffer.Buffer(param.length); for (var i = 0; i < param.length; i++) { ret[i] = param[param.length - i - 1]; } return ret; }
javascript
function reverse(param) { var ret = new buffer.Buffer(param.length); for (var i = 0; i < param.length; i++) { ret[i] = param[param.length - i - 1]; } return ret; }
[ "function", "reverse", "(", "param", ")", "{", "var", "ret", "=", "new", "buffer", ".", "Buffer", "(", "param", ".", "length", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "param", ".", "length", ";", "i", "++", ")", "{", "ret", "[", "i", "]", "=", "param", "[", "param", ".", "length", "-", "i", "-", "1", "]", ";", "}", "return", "ret", ";", "}" ]
Reverse a buffer @param {Buffer} param @return {Buffer}
[ "Reverse", "a", "buffer" ]
aa2a7970547cf451c06e528472ee965d3b4cac36
https://github.com/owstack/ows-common/blob/aa2a7970547cf451c06e528472ee965d3b4cac36/lib/buffer.js#L154-L160
49,061
solidusjs/gulp-filerev-replace
index.js
transformAllFiles
function transformAllFiles(transform, flush) { var files = []; return through.obj( function(file, enc, cb) { if (file.isStream()) { this.emit('error', new gutil.PluginError(PLUGIN_NAME, 'Streams are not supported!')); return cb(); } if (file.isBuffer()) { if (transform) transform.call(this, file, enc); } files.push(file); cb(); }, function(cb) { if (flush) files = flush.call(this, files); for (var i = 0; i < files.length; ++i) { this.push(files[i]); } cb(); } ); }
javascript
function transformAllFiles(transform, flush) { var files = []; return through.obj( function(file, enc, cb) { if (file.isStream()) { this.emit('error', new gutil.PluginError(PLUGIN_NAME, 'Streams are not supported!')); return cb(); } if (file.isBuffer()) { if (transform) transform.call(this, file, enc); } files.push(file); cb(); }, function(cb) { if (flush) files = flush.call(this, files); for (var i = 0; i < files.length; ++i) { this.push(files[i]); } cb(); } ); }
[ "function", "transformAllFiles", "(", "transform", ",", "flush", ")", "{", "var", "files", "=", "[", "]", ";", "return", "through", ".", "obj", "(", "function", "(", "file", ",", "enc", ",", "cb", ")", "{", "if", "(", "file", ".", "isStream", "(", ")", ")", "{", "this", ".", "emit", "(", "'error'", ",", "new", "gutil", ".", "PluginError", "(", "PLUGIN_NAME", ",", "'Streams are not supported!'", ")", ")", ";", "return", "cb", "(", ")", ";", "}", "if", "(", "file", ".", "isBuffer", "(", ")", ")", "{", "if", "(", "transform", ")", "transform", ".", "call", "(", "this", ",", "file", ",", "enc", ")", ";", "}", "files", ".", "push", "(", "file", ")", ";", "cb", "(", ")", ";", "}", ",", "function", "(", "cb", ")", "{", "if", "(", "flush", ")", "files", "=", "flush", ".", "call", "(", "this", ",", "files", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "files", ".", "length", ";", "++", "i", ")", "{", "this", ".", "push", "(", "files", "[", "i", "]", ")", ";", "}", "cb", "(", ")", ";", "}", ")", ";", "}" ]
Transform all files in the stream but wait until all files are handled before emitting events
[ "Transform", "all", "files", "in", "the", "stream", "but", "wait", "until", "all", "files", "are", "handled", "before", "emitting", "events" ]
9e64bd70b7993776943312fd03ef7a32546d50a7
https://github.com/solidusjs/gulp-filerev-replace/blob/9e64bd70b7993776943312fd03ef7a32546d50a7/index.js#L151-L176
49,062
ThatDevCompany/that-build-library
src/utils/exec.js
exec
function exec(cmd, args = [], silent = false) { return __awaiter(this, void 0, void 0, function* () { const response = []; return new Promise((resolve, reject) => { const exe = child_process_1.spawn(cmd, args, { env: process.env }); exe.stdout.on('data', data => { response.push(data.toString()); if (!silent) { console.log(data.toString()); } }); exe.stderr.on('data', data => { if (!silent) { console.error(data.toString()); } }); exe.on('exit', code => { if (code === 0) { return resolve(response); } else { if (!silent) { console.error('Problem executing ' + cmd); } return reject(); } }); }); }); }
javascript
function exec(cmd, args = [], silent = false) { return __awaiter(this, void 0, void 0, function* () { const response = []; return new Promise((resolve, reject) => { const exe = child_process_1.spawn(cmd, args, { env: process.env }); exe.stdout.on('data', data => { response.push(data.toString()); if (!silent) { console.log(data.toString()); } }); exe.stderr.on('data', data => { if (!silent) { console.error(data.toString()); } }); exe.on('exit', code => { if (code === 0) { return resolve(response); } else { if (!silent) { console.error('Problem executing ' + cmd); } return reject(); } }); }); }); }
[ "function", "exec", "(", "cmd", ",", "args", "=", "[", "]", ",", "silent", "=", "false", ")", "{", "return", "__awaiter", "(", "this", ",", "void", "0", ",", "void", "0", ",", "function", "*", "(", ")", "{", "const", "response", "=", "[", "]", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "exe", "=", "child_process_1", ".", "spawn", "(", "cmd", ",", "args", ",", "{", "env", ":", "process", ".", "env", "}", ")", ";", "exe", ".", "stdout", ".", "on", "(", "'data'", ",", "data", "=>", "{", "response", ".", "push", "(", "data", ".", "toString", "(", ")", ")", ";", "if", "(", "!", "silent", ")", "{", "console", ".", "log", "(", "data", ".", "toString", "(", ")", ")", ";", "}", "}", ")", ";", "exe", ".", "stderr", ".", "on", "(", "'data'", ",", "data", "=>", "{", "if", "(", "!", "silent", ")", "{", "console", ".", "error", "(", "data", ".", "toString", "(", ")", ")", ";", "}", "}", ")", ";", "exe", ".", "on", "(", "'exit'", ",", "code", "=>", "{", "if", "(", "code", "===", "0", ")", "{", "return", "resolve", "(", "response", ")", ";", "}", "else", "{", "if", "(", "!", "silent", ")", "{", "console", ".", "error", "(", "'Problem executing '", "+", "cmd", ")", ";", "}", "return", "reject", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Execute a CMD line process
[ "Execute", "a", "CMD", "line", "process" ]
865aaac49531fa9793a055a4df8e9b1b41e71753
https://github.com/ThatDevCompany/that-build-library/blob/865aaac49531fa9793a055a4df8e9b1b41e71753/src/utils/exec.js#L15-L46
49,063
apigrate/mysqlutils
index.js
DbEntity
function DbEntity(table, entity, opts, pool, logger){ LOGGER = logger; this.pool = pool; this.table = table; this.entity = entity; if(_.isNil(opts)||_.isNil(opts.plural)){ if(_.endsWith(entity,'y')){ this.plural = entity.substr(0, entity.lastIndexOf('y')) + 'ies'; } else if (_.endsWith(entity,'s')) { this.plural = entity.substr(0, entity.lastIndexOf('s')) + 'es'; } else { this.plural = entity + 's'; } } else { this.plural = opts.plural; } this.options = (opts || { created_timestamp_column: 'created', updated_timestamp_column: 'updated', version_number_column: 'version', log_category: 'db' }); if(logger && LOGGER.info){ LOGGER = logger; } else { //use winston LOGGER = {error: console.log, warn: console.log, info: function(){}, debug: function(){}, silly: function(){} } } this.metadata = null;//initialized to empty. }
javascript
function DbEntity(table, entity, opts, pool, logger){ LOGGER = logger; this.pool = pool; this.table = table; this.entity = entity; if(_.isNil(opts)||_.isNil(opts.plural)){ if(_.endsWith(entity,'y')){ this.plural = entity.substr(0, entity.lastIndexOf('y')) + 'ies'; } else if (_.endsWith(entity,'s')) { this.plural = entity.substr(0, entity.lastIndexOf('s')) + 'es'; } else { this.plural = entity + 's'; } } else { this.plural = opts.plural; } this.options = (opts || { created_timestamp_column: 'created', updated_timestamp_column: 'updated', version_number_column: 'version', log_category: 'db' }); if(logger && LOGGER.info){ LOGGER = logger; } else { //use winston LOGGER = {error: console.log, warn: console.log, info: function(){}, debug: function(){}, silly: function(){} } } this.metadata = null;//initialized to empty. }
[ "function", "DbEntity", "(", "table", ",", "entity", ",", "opts", ",", "pool", ",", "logger", ")", "{", "LOGGER", "=", "logger", ";", "this", ".", "pool", "=", "pool", ";", "this", ".", "table", "=", "table", ";", "this", ".", "entity", "=", "entity", ";", "if", "(", "_", ".", "isNil", "(", "opts", ")", "||", "_", ".", "isNil", "(", "opts", ".", "plural", ")", ")", "{", "if", "(", "_", ".", "endsWith", "(", "entity", ",", "'y'", ")", ")", "{", "this", ".", "plural", "=", "entity", ".", "substr", "(", "0", ",", "entity", ".", "lastIndexOf", "(", "'y'", ")", ")", "+", "'ies'", ";", "}", "else", "if", "(", "_", ".", "endsWith", "(", "entity", ",", "'s'", ")", ")", "{", "this", ".", "plural", "=", "entity", ".", "substr", "(", "0", ",", "entity", ".", "lastIndexOf", "(", "'s'", ")", ")", "+", "'es'", ";", "}", "else", "{", "this", ".", "plural", "=", "entity", "+", "'s'", ";", "}", "}", "else", "{", "this", ".", "plural", "=", "opts", ".", "plural", ";", "}", "this", ".", "options", "=", "(", "opts", "||", "{", "created_timestamp_column", ":", "'created'", ",", "updated_timestamp_column", ":", "'updated'", ",", "version_number_column", ":", "'version'", ",", "log_category", ":", "'db'", "}", ")", ";", "if", "(", "logger", "&&", "LOGGER", ".", "info", ")", "{", "LOGGER", "=", "logger", ";", "}", "else", "{", "//use winston", "LOGGER", "=", "{", "error", ":", "console", ".", "log", ",", "warn", ":", "console", ".", "log", ",", "info", ":", "function", "(", ")", "{", "}", ",", "debug", ":", "function", "(", ")", "{", "}", ",", "silly", ":", "function", "(", ")", "{", "}", "}", "}", "this", ".", "metadata", "=", "null", ";", "//initialized to empty.", "}" ]
Class to provide basic SQL persistence operations. @version 2.2.0 @param {string} table required db table name @param {string} entity required logical entity name (singular form) @param {object} opts optional options settings to override defaults, shown below @example <caption>Default options</caption> { plural: 'string (derived from English plural rules)', created_timestamp_column: 'created', updated_timestamp_column: 'updated', version_number_column: 'version', log_category: 'db' } @param {object} pool required mysql db pool reference. @param {object} logger optional logger instance. @return an object to be used for model persistence. @example <caption>Note, internal metadata is stored in the the form</caption> [{ column: 'column name', sql_type: 'string' is_pk: true|false whether a primary key column, is_autoincrement: true|false whether it is an autoincrement id is_created_timestamp: true|false, is_updated_timestamp: true|false, is_version: true|false }]
[ "Class", "to", "provide", "basic", "SQL", "persistence", "operations", "." ]
1245cd4610585795f07d22290424c57b35fad7ca
https://github.com/apigrate/mysqlutils/blob/1245cd4610585795f07d22290424c57b35fad7ca/index.js#L47-L80
49,064
apigrate/mysqlutils
index.js
_transformToSafeValue
function _transformToSafeValue(input, column){ var out = input; var datatype = column.sql_type; var nullable = column.nullable; if( input === '' ){ //empty string. if(datatype==='datetime'|| datatype==='timestamp' ||_.startsWith(datatype, 'int') || _.startsWith(datatype, 'num') || _.startsWith(datatype, 'dec')){ if(nullable){ out = null; } else { throw new Error(column.column + ' is not permitted to be empty.') } } } else if( !_.isNil(input) ) { //not null, not undefined if(datatype==='datetime'|| datatype==='timestamp'){ out = moment(input).format('YYYY-MM-DD HH:mm:ss'); } } return out; }
javascript
function _transformToSafeValue(input, column){ var out = input; var datatype = column.sql_type; var nullable = column.nullable; if( input === '' ){ //empty string. if(datatype==='datetime'|| datatype==='timestamp' ||_.startsWith(datatype, 'int') || _.startsWith(datatype, 'num') || _.startsWith(datatype, 'dec')){ if(nullable){ out = null; } else { throw new Error(column.column + ' is not permitted to be empty.') } } } else if( !_.isNil(input) ) { //not null, not undefined if(datatype==='datetime'|| datatype==='timestamp'){ out = moment(input).format('YYYY-MM-DD HH:mm:ss'); } } return out; }
[ "function", "_transformToSafeValue", "(", "input", ",", "column", ")", "{", "var", "out", "=", "input", ";", "var", "datatype", "=", "column", ".", "sql_type", ";", "var", "nullable", "=", "column", ".", "nullable", ";", "if", "(", "input", "===", "''", ")", "{", "//empty string.", "if", "(", "datatype", "===", "'datetime'", "||", "datatype", "===", "'timestamp'", "||", "_", ".", "startsWith", "(", "datatype", ",", "'int'", ")", "||", "_", ".", "startsWith", "(", "datatype", ",", "'num'", ")", "||", "_", ".", "startsWith", "(", "datatype", ",", "'dec'", ")", ")", "{", "if", "(", "nullable", ")", "{", "out", "=", "null", ";", "}", "else", "{", "throw", "new", "Error", "(", "column", ".", "column", "+", "' is not permitted to be empty.'", ")", "}", "}", "}", "else", "if", "(", "!", "_", ".", "isNil", "(", "input", ")", ")", "{", "//not null, not undefined", "if", "(", "datatype", "===", "'datetime'", "||", "datatype", "===", "'timestamp'", ")", "{", "out", "=", "moment", "(", "input", ")", ".", "format", "(", "'YYYY-MM-DD HH:mm:ss'", ")", ";", "}", "}", "return", "out", ";", "}" ]
Helper that transforms input values to acceptable defaults for database columns.
[ "Helper", "that", "transforms", "input", "values", "to", "acceptable", "defaults", "for", "database", "columns", "." ]
1245cd4610585795f07d22290424c57b35fad7ca
https://github.com/apigrate/mysqlutils/blob/1245cd4610585795f07d22290424c57b35fad7ca/index.js#L961-L982
49,065
satchmorun/promeso
promeso.js
fulfill
function fulfill(promise, value) { if (promise.state !== PENDING) return; promise.value = value; promise.state = FULFILLED; return resolve(promise); }
javascript
function fulfill(promise, value) { if (promise.state !== PENDING) return; promise.value = value; promise.state = FULFILLED; return resolve(promise); }
[ "function", "fulfill", "(", "promise", ",", "value", ")", "{", "if", "(", "promise", ".", "state", "!==", "PENDING", ")", "return", ";", "promise", ".", "value", "=", "value", ";", "promise", ".", "state", "=", "FULFILLED", ";", "return", "resolve", "(", "promise", ")", ";", "}" ]
Fulfill a promise with the given `value`. Returns the promise.
[ "Fulfill", "a", "promise", "with", "the", "given", "value", ".", "Returns", "the", "promise", "." ]
c79156c8e103bed9f709a19e55be94824589433a
https://github.com/satchmorun/promeso/blob/c79156c8e103bed9f709a19e55be94824589433a/promeso.js#L47-L54
49,066
satchmorun/promeso
promeso.js
reject
function reject(promise, reason) { if (promise.state !== PENDING) return; promise.reason = reason; promise.state = REJECTED; return resolve(promise); }
javascript
function reject(promise, reason) { if (promise.state !== PENDING) return; promise.reason = reason; promise.state = REJECTED; return resolve(promise); }
[ "function", "reject", "(", "promise", ",", "reason", ")", "{", "if", "(", "promise", ".", "state", "!==", "PENDING", ")", "return", ";", "promise", ".", "reason", "=", "reason", ";", "promise", ".", "state", "=", "REJECTED", ";", "return", "resolve", "(", "promise", ")", ";", "}" ]
Reject a promise for the given `reason`. Returns the promise.
[ "Reject", "a", "promise", "for", "the", "given", "reason", ".", "Returns", "the", "promise", "." ]
c79156c8e103bed9f709a19e55be94824589433a
https://github.com/satchmorun/promeso/blob/c79156c8e103bed9f709a19e55be94824589433a/promeso.js#L57-L64
49,067
alexindigo/executioner
lib/execute.js
execute
function execute(collector, cmd, options, callback) { collector._process = exec(cmd, options, function(err, stdout, stderr) { var cmdPrefix = '' , child = collector._process ; // normalize stdout = (stdout || '').trim(); stderr = (stderr || '').trim(); // clean up finished process reference delete collector._process; if (err) { // clean up shell errors err.message = (err.message || '').trim(); err.stdout = stdout; err.stderr = stderr; // make it uniform across node versions (and platforms as side effect) // looking at you [email protected]+ if (err.cmd && (cmdPrefix = err.cmd.replace(cmd, '')) != err.cmd) { err.cmd = cmd; err.message = err.message.replace(cmdPrefix, ''); } // check if process has been willingly terminated if (child._executioner_killRequested && err.killed) { // mark job as properly terminated err.terminated = true; // it happen as supposed, so output might matter callback(err, stdout); return; } // just an error, no output matters callback(err); return; } // everything is good callback(null, stdout); }); }
javascript
function execute(collector, cmd, options, callback) { collector._process = exec(cmd, options, function(err, stdout, stderr) { var cmdPrefix = '' , child = collector._process ; // normalize stdout = (stdout || '').trim(); stderr = (stderr || '').trim(); // clean up finished process reference delete collector._process; if (err) { // clean up shell errors err.message = (err.message || '').trim(); err.stdout = stdout; err.stderr = stderr; // make it uniform across node versions (and platforms as side effect) // looking at you [email protected]+ if (err.cmd && (cmdPrefix = err.cmd.replace(cmd, '')) != err.cmd) { err.cmd = cmd; err.message = err.message.replace(cmdPrefix, ''); } // check if process has been willingly terminated if (child._executioner_killRequested && err.killed) { // mark job as properly terminated err.terminated = true; // it happen as supposed, so output might matter callback(err, stdout); return; } // just an error, no output matters callback(err); return; } // everything is good callback(null, stdout); }); }
[ "function", "execute", "(", "collector", ",", "cmd", ",", "options", ",", "callback", ")", "{", "collector", ".", "_process", "=", "exec", "(", "cmd", ",", "options", ",", "function", "(", "err", ",", "stdout", ",", "stderr", ")", "{", "var", "cmdPrefix", "=", "''", ",", "child", "=", "collector", ".", "_process", ";", "// normalize", "stdout", "=", "(", "stdout", "||", "''", ")", ".", "trim", "(", ")", ";", "stderr", "=", "(", "stderr", "||", "''", ")", ".", "trim", "(", ")", ";", "// clean up finished process reference", "delete", "collector", ".", "_process", ";", "if", "(", "err", ")", "{", "// clean up shell errors", "err", ".", "message", "=", "(", "err", ".", "message", "||", "''", ")", ".", "trim", "(", ")", ";", "err", ".", "stdout", "=", "stdout", ";", "err", ".", "stderr", "=", "stderr", ";", "// make it uniform across node versions (and platforms as side effect)", "// looking at you [email protected]+", "if", "(", "err", ".", "cmd", "&&", "(", "cmdPrefix", "=", "err", ".", "cmd", ".", "replace", "(", "cmd", ",", "''", ")", ")", "!=", "err", ".", "cmd", ")", "{", "err", ".", "cmd", "=", "cmd", ";", "err", ".", "message", "=", "err", ".", "message", ".", "replace", "(", "cmdPrefix", ",", "''", ")", ";", "}", "// check if process has been willingly terminated", "if", "(", "child", ".", "_executioner_killRequested", "&&", "err", ".", "killed", ")", "{", "// mark job as properly terminated", "err", ".", "terminated", "=", "true", ";", "// it happen as supposed, so output might matter", "callback", "(", "err", ",", "stdout", ")", ";", "return", ";", "}", "// just an error, no output matters", "callback", "(", "err", ")", ";", "return", ";", "}", "// everything is good", "callback", "(", "null", ",", "stdout", ")", ";", "}", ")", ";", "}" ]
Executes provided command and store process reference in the state object @param {array} collector - outputs storage @param {string} cmd - command itself @param {object} options - list of options for the command @param {function} callback - invoked when done @returns {void}
[ "Executes", "provided", "command", "and", "store", "process", "reference", "in", "the", "state", "object" ]
582f92897f47c13f4531e0b692aebb4a9f134eec
https://github.com/alexindigo/executioner/blob/582f92897f47c13f4531e0b692aebb4a9f134eec/lib/execute.js#L15-L64
49,068
Ivshti/node-subtitles-grouping
lib/heatmap.js
getHeatmap
function getHeatmap(tracks) { var heatmap = []; _.each(tracks, function(track) { var idxStart = Math.floor(track.startTime / HEATMAP_SEGMENT), idxEnd = Math.ceil(track.endTime / HEATMAP_SEGMENT); idxEnd = Math.min(MAX_HEATMAP_LEN, idxEnd); /* Protection - sometimes we have buggy tracks which end in Infinity */ for (var i=idxStart; i<idxEnd; i++) { if (i<0) continue; if (! heatmap[i]) heatmap[i] = 0; USE_BOOLEAN ? heatmap[i] = 1 : heatmap[i]++; } }); /* Heatmap: Fill in the blanks */ for (var i = 0; i!=heatmap.length; i++) if (! heatmap[i]) heatmap[i] = 0; return heatmap; }
javascript
function getHeatmap(tracks) { var heatmap = []; _.each(tracks, function(track) { var idxStart = Math.floor(track.startTime / HEATMAP_SEGMENT), idxEnd = Math.ceil(track.endTime / HEATMAP_SEGMENT); idxEnd = Math.min(MAX_HEATMAP_LEN, idxEnd); /* Protection - sometimes we have buggy tracks which end in Infinity */ for (var i=idxStart; i<idxEnd; i++) { if (i<0) continue; if (! heatmap[i]) heatmap[i] = 0; USE_BOOLEAN ? heatmap[i] = 1 : heatmap[i]++; } }); /* Heatmap: Fill in the blanks */ for (var i = 0; i!=heatmap.length; i++) if (! heatmap[i]) heatmap[i] = 0; return heatmap; }
[ "function", "getHeatmap", "(", "tracks", ")", "{", "var", "heatmap", "=", "[", "]", ";", "_", ".", "each", "(", "tracks", ",", "function", "(", "track", ")", "{", "var", "idxStart", "=", "Math", ".", "floor", "(", "track", ".", "startTime", "/", "HEATMAP_SEGMENT", ")", ",", "idxEnd", "=", "Math", ".", "ceil", "(", "track", ".", "endTime", "/", "HEATMAP_SEGMENT", ")", ";", "idxEnd", "=", "Math", ".", "min", "(", "MAX_HEATMAP_LEN", ",", "idxEnd", ")", ";", "/* Protection - sometimes we have buggy tracks which end in Infinity */", "for", "(", "var", "i", "=", "idxStart", ";", "i", "<", "idxEnd", ";", "i", "++", ")", "{", "if", "(", "i", "<", "0", ")", "continue", ";", "if", "(", "!", "heatmap", "[", "i", "]", ")", "heatmap", "[", "i", "]", "=", "0", ";", "USE_BOOLEAN", "?", "heatmap", "[", "i", "]", "=", "1", ":", "heatmap", "[", "i", "]", "++", ";", "}", "}", ")", ";", "/* Heatmap: Fill in the blanks */", "for", "(", "var", "i", "=", "0", ";", "i", "!=", "heatmap", ".", "length", ";", "i", "++", ")", "if", "(", "!", "heatmap", "[", "i", "]", ")", "heatmap", "[", "i", "]", "=", "0", ";", "return", "heatmap", ";", "}" ]
assume max is 5 hours
[ "assume", "max", "is", "5", "hours" ]
26284201817d1d200c1da28e4cf22f60a72ff0f0
https://github.com/Ivshti/node-subtitles-grouping/blob/26284201817d1d200c1da28e4cf22f60a72ff0f0/lib/heatmap.js#L7-L25
49,069
therror/therror
lib/therror.js
WithName
function WithName(name, Base) { let BaseClass = Base || Therror; return class extends BaseClass { constructor(err, msg, prop) { super(err, msg, prop); this.name = name; } }; }
javascript
function WithName(name, Base) { let BaseClass = Base || Therror; return class extends BaseClass { constructor(err, msg, prop) { super(err, msg, prop); this.name = name; } }; }
[ "function", "WithName", "(", "name", ",", "Base", ")", "{", "let", "BaseClass", "=", "Base", "||", "Therror", ";", "return", "class", "extends", "BaseClass", "{", "constructor", "(", "err", ",", "msg", ",", "prop", ")", "{", "super", "(", "err", ",", "msg", ",", "prop", ")", ";", "this", ".", "name", "=", "name", ";", "}", "}", ";", "}" ]
Hack to deal with Node8 BreakingChange about Error class name
[ "Hack", "to", "deal", "with", "Node8", "BreakingChange", "about", "Error", "class", "name" ]
de2460b68d82fed13b2b4a2daf01c6f451db17d5
https://github.com/therror/therror/blob/de2460b68d82fed13b2b4a2daf01c6f451db17d5/lib/therror.js#L480-L488
49,070
fmcarvalho/express-sitemap-html
lib/expressSitemapHtml.js
sitemap
function sitemap(app) { let html return (req, res) => { if(!html) html = view(parseRoutes(app)) res.set({ 'Content-Type': 'text/html', 'Content-Length': html.length }) res.send(html) } }
javascript
function sitemap(app) { let html return (req, res) => { if(!html) html = view(parseRoutes(app)) res.set({ 'Content-Type': 'text/html', 'Content-Length': html.length }) res.send(html) } }
[ "function", "sitemap", "(", "app", ")", "{", "let", "html", "return", "(", "req", ",", "res", ")", "=>", "{", "if", "(", "!", "html", ")", "html", "=", "view", "(", "parseRoutes", "(", "app", ")", ")", "res", ".", "set", "(", "{", "'Content-Type'", ":", "'text/html'", ",", "'Content-Length'", ":", "html", ".", "length", "}", ")", "res", ".", "send", "(", "html", ")", "}", "}" ]
Builds an express middleware that renders an HTML sitemap based on the routes of app parameter. @param {Express} app An express instance
[ "Builds", "an", "express", "middleware", "that", "renders", "an", "HTML", "sitemap", "based", "on", "the", "routes", "of", "app", "parameter", "." ]
6d60721e825882d47369f93020703f2f2e0e0693
https://github.com/fmcarvalho/express-sitemap-html/blob/6d60721e825882d47369f93020703f2f2e0e0693/lib/expressSitemapHtml.js#L25-L35
49,071
anseki/pointer-event
pointer-event.esm.js
getTouchById
function getTouchById(touches, id) { if (touches != null && id != null) { for (var i = 0; i < touches.length; i++) { if (touches[i].identifier === id) { return touches[i]; } } } return null; }
javascript
function getTouchById(touches, id) { if (touches != null && id != null) { for (var i = 0; i < touches.length; i++) { if (touches[i].identifier === id) { return touches[i]; } } } return null; }
[ "function", "getTouchById", "(", "touches", ",", "id", ")", "{", "if", "(", "touches", "!=", "null", "&&", "id", "!=", "null", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "touches", ".", "length", ";", "i", "++", ")", "{", "if", "(", "touches", "[", "i", "]", ".", "identifier", "===", "id", ")", "{", "return", "touches", "[", "i", "]", ";", "}", "}", "}", "return", "null", ";", "}" ]
Get Touch instance in list. @param {Touch[]} touches - An Array or TouchList instance. @param {number} id - Touch#identifier @returns {(Touch|null)} - A found Touch instance.
[ "Get", "Touch", "instance", "in", "list", "." ]
3caf9ca58c338bb42105a2504dfa9806185a2fee
https://github.com/anseki/pointer-event/blob/3caf9ca58c338bb42105a2504dfa9806185a2fee/pointer-event.esm.js#L52-L61
49,072
anseki/pointer-event
pointer-event.esm.js
PointerEvent
function PointerEvent(options) { var _this = this; _classCallCheck(this, PointerEvent); this.startHandlers = {}; this.lastHandlerId = 0; this.curPointerClass = null; this.curTouchId = null; this.lastPointerXY = { clientX: 0, clientY: 0 }; this.lastTouchTime = 0; // Options this.options = { // Default preventDefault: true, stopPropagation: true }; if (options) { ['preventDefault', 'stopPropagation'].forEach(function (option) { if (typeof options[option] === 'boolean') { _this.options[option] = options[option]; } }); } }
javascript
function PointerEvent(options) { var _this = this; _classCallCheck(this, PointerEvent); this.startHandlers = {}; this.lastHandlerId = 0; this.curPointerClass = null; this.curTouchId = null; this.lastPointerXY = { clientX: 0, clientY: 0 }; this.lastTouchTime = 0; // Options this.options = { // Default preventDefault: true, stopPropagation: true }; if (options) { ['preventDefault', 'stopPropagation'].forEach(function (option) { if (typeof options[option] === 'boolean') { _this.options[option] = options[option]; } }); } }
[ "function", "PointerEvent", "(", "options", ")", "{", "var", "_this", "=", "this", ";", "_classCallCheck", "(", "this", ",", "PointerEvent", ")", ";", "this", ".", "startHandlers", "=", "{", "}", ";", "this", ".", "lastHandlerId", "=", "0", ";", "this", ".", "curPointerClass", "=", "null", ";", "this", ".", "curTouchId", "=", "null", ";", "this", ".", "lastPointerXY", "=", "{", "clientX", ":", "0", ",", "clientY", ":", "0", "}", ";", "this", ".", "lastTouchTime", "=", "0", ";", "// Options", "this", ".", "options", "=", "{", "// Default", "preventDefault", ":", "true", ",", "stopPropagation", ":", "true", "}", ";", "if", "(", "options", ")", "{", "[", "'preventDefault'", ",", "'stopPropagation'", "]", ".", "forEach", "(", "function", "(", "option", ")", "{", "if", "(", "typeof", "options", "[", "option", "]", "===", "'boolean'", ")", "{", "_this", ".", "options", "[", "option", "]", "=", "options", "[", "option", "]", ";", "}", "}", ")", ";", "}", "}" ]
Create a `PointerEvent` instance. @param {Object} [options] - Options
[ "Create", "a", "PointerEvent", "instance", "." ]
3caf9ca58c338bb42105a2504dfa9806185a2fee
https://github.com/anseki/pointer-event/blob/3caf9ca58c338bb42105a2504dfa9806185a2fee/pointer-event.esm.js#L81-L105
49,073
kuno/neco
deps/npm/lib/install.js
findSatisfying
function findSatisfying (pkg, name, range, mustHave, reg) { if (mustHave) return null return semver.maxSatisfying ( Object.keys(reg[name] || {}) .concat(Object.keys(Object.getPrototypeOf(reg[name] || {}))) , range ) }
javascript
function findSatisfying (pkg, name, range, mustHave, reg) { if (mustHave) return null return semver.maxSatisfying ( Object.keys(reg[name] || {}) .concat(Object.keys(Object.getPrototypeOf(reg[name] || {}))) , range ) }
[ "function", "findSatisfying", "(", "pkg", ",", "name", ",", "range", ",", "mustHave", ",", "reg", ")", "{", "if", "(", "mustHave", ")", "return", "null", "return", "semver", ".", "maxSatisfying", "(", "Object", ".", "keys", "(", "reg", "[", "name", "]", "||", "{", "}", ")", ".", "concat", "(", "Object", ".", "keys", "(", "Object", ".", "getPrototypeOf", "(", "reg", "[", "name", "]", "||", "{", "}", ")", ")", ")", ",", "range", ")", "}" ]
see if there is a satisfying version already
[ "see", "if", "there", "is", "a", "satisfying", "version", "already" ]
cf6361c1fcb9466c6b2ab3b127b5d0160ca50735
https://github.com/kuno/neco/blob/cf6361c1fcb9466c6b2ab3b127b5d0160ca50735/deps/npm/lib/install.js#L182-L189
49,074
halfbakedsneed/chowdown
src/retrieve.js
withConfig
function withConfig(fn) { return (source, options={}) => { options.type = 'dom'; options.client = options.client || rp; return fn(source, options); } }
javascript
function withConfig(fn) { return (source, options={}) => { options.type = 'dom'; options.client = options.client || rp; return fn(source, options); } }
[ "function", "withConfig", "(", "fn", ")", "{", "return", "(", "source", ",", "options", "=", "{", "}", ")", "=>", "{", "options", ".", "type", "=", "'dom'", ";", "options", ".", "client", "=", "options", ".", "client", "||", "rp", ";", "return", "fn", "(", "source", ",", "options", ")", ";", "}", "}" ]
Wraps the given function such that its called with a configured options object. @param {function} fn The function to wrap. @return {function} The wrapped function.
[ "Wraps", "the", "given", "function", "such", "that", "its", "called", "with", "a", "configured", "options", "object", "." ]
b0e322c6070f82d557886afec9217b41f5214543
https://github.com/halfbakedsneed/chowdown/blob/b0e322c6070f82d557886afec9217b41f5214543/src/retrieve.js#L53-L60
49,075
confuser/save-json
json-engine.js
getNextId
function getNextId() { var dataIds = Object.keys(idIndexData) dataIds.sort(function (a, b) { return b - a }) if (dataIds && dataIds[0]) { var id = _.parseInt(dataIds[0]) + 1 return id } else { return 1 } }
javascript
function getNextId() { var dataIds = Object.keys(idIndexData) dataIds.sort(function (a, b) { return b - a }) if (dataIds && dataIds[0]) { var id = _.parseInt(dataIds[0]) + 1 return id } else { return 1 } }
[ "function", "getNextId", "(", ")", "{", "var", "dataIds", "=", "Object", ".", "keys", "(", "idIndexData", ")", "dataIds", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "b", "-", "a", "}", ")", "if", "(", "dataIds", "&&", "dataIds", "[", "0", "]", ")", "{", "var", "id", "=", "_", ".", "parseInt", "(", "dataIds", "[", "0", "]", ")", "+", "1", "return", "id", "}", "else", "{", "return", "1", "}", "}" ]
Handle id increment
[ "Handle", "id", "increment" ]
5e4c22a1a17151d60ffda1c30c68fbe0686e4e37
https://github.com/confuser/save-json/blob/5e4c22a1a17151d60ffda1c30c68fbe0686e4e37/json-engine.js#L34-L47
49,076
confuser/save-json
json-engine.js
del
function del(id, callback) { callback = callback || emptyFn if (typeof callback !== 'function') { throw new TypeError('callback must be a function or empty') } if (!idIndexData[id]) { return callback(new Error('No object found with \'' + options.idProperty + '\' = \'' + id + '\'')) } self.emit('delete', id) delete idIndexData[id] // Work around for dynamic property var find = {} find[options.idProperty] = id data.splice(_.findIndex(data, find), 1) saveFile('afterDelete', id, callback) }
javascript
function del(id, callback) { callback = callback || emptyFn if (typeof callback !== 'function') { throw new TypeError('callback must be a function or empty') } if (!idIndexData[id]) { return callback(new Error('No object found with \'' + options.idProperty + '\' = \'' + id + '\'')) } self.emit('delete', id) delete idIndexData[id] // Work around for dynamic property var find = {} find[options.idProperty] = id data.splice(_.findIndex(data, find), 1) saveFile('afterDelete', id, callback) }
[ "function", "del", "(", "id", ",", "callback", ")", "{", "callback", "=", "callback", "||", "emptyFn", "if", "(", "typeof", "callback", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "'callback must be a function or empty'", ")", "}", "if", "(", "!", "idIndexData", "[", "id", "]", ")", "{", "return", "callback", "(", "new", "Error", "(", "'No object found with \\''", "+", "options", ".", "idProperty", "+", "'\\' = \\''", "+", "id", "+", "'\\''", ")", ")", "}", "self", ".", "emit", "(", "'delete'", ",", "id", ")", "delete", "idIndexData", "[", "id", "]", "// Work around for dynamic property", "var", "find", "=", "{", "}", "find", "[", "options", ".", "idProperty", "]", "=", "id", "data", ".", "splice", "(", "_", ".", "findIndex", "(", "data", ",", "find", ")", ",", "1", ")", "saveFile", "(", "'afterDelete'", ",", "id", ",", "callback", ")", "}" ]
Deletes one object. Returns an error if the object can not be found or if the ID property is not present. @param {Object} object to delete @param {Function} callback @api public
[ "Deletes", "one", "object", ".", "Returns", "an", "error", "if", "the", "object", "can", "not", "be", "found", "or", "if", "the", "ID", "property", "is", "not", "present", "." ]
5e4c22a1a17151d60ffda1c30c68fbe0686e4e37
https://github.com/confuser/save-json/blob/5e4c22a1a17151d60ffda1c30c68fbe0686e4e37/json-engine.js#L165-L189
49,077
ev3-js/devices
lib/index.js
devices
function devices (port, paths) { paths = paths || {} var actualPath = defaults(paths, defaultPaths) var device = isNaN(port) ? motor() : sensor() if (device.prefix === motor().prefix) { port = port.toUpperCase() } if (device.available[device.prefix + port]) { return path.join(device.path, device.available[device.prefix + port]) } else { throw new Error('no device in port ' + port) } function motor () { motorCache = isEmpty(motorCache) ? getPaths(actualPath.motor) : motorCache return { path: actualPath.motor, available: motorCache, prefix: 'out' } } function sensor () { sensorCache = isEmpty(sensorCache) ? getPaths(actualPath.sensor) : sensorCache return { path: actualPath.sensor, available: sensorCache, prefix: 'in' } } }
javascript
function devices (port, paths) { paths = paths || {} var actualPath = defaults(paths, defaultPaths) var device = isNaN(port) ? motor() : sensor() if (device.prefix === motor().prefix) { port = port.toUpperCase() } if (device.available[device.prefix + port]) { return path.join(device.path, device.available[device.prefix + port]) } else { throw new Error('no device in port ' + port) } function motor () { motorCache = isEmpty(motorCache) ? getPaths(actualPath.motor) : motorCache return { path: actualPath.motor, available: motorCache, prefix: 'out' } } function sensor () { sensorCache = isEmpty(sensorCache) ? getPaths(actualPath.sensor) : sensorCache return { path: actualPath.sensor, available: sensorCache, prefix: 'in' } } }
[ "function", "devices", "(", "port", ",", "paths", ")", "{", "paths", "=", "paths", "||", "{", "}", "var", "actualPath", "=", "defaults", "(", "paths", ",", "defaultPaths", ")", "var", "device", "=", "isNaN", "(", "port", ")", "?", "motor", "(", ")", ":", "sensor", "(", ")", "if", "(", "device", ".", "prefix", "===", "motor", "(", ")", ".", "prefix", ")", "{", "port", "=", "port", ".", "toUpperCase", "(", ")", "}", "if", "(", "device", ".", "available", "[", "device", ".", "prefix", "+", "port", "]", ")", "{", "return", "path", ".", "join", "(", "device", ".", "path", ",", "device", ".", "available", "[", "device", ".", "prefix", "+", "port", "]", ")", "}", "else", "{", "throw", "new", "Error", "(", "'no device in port '", "+", "port", ")", "}", "function", "motor", "(", ")", "{", "motorCache", "=", "isEmpty", "(", "motorCache", ")", "?", "getPaths", "(", "actualPath", ".", "motor", ")", ":", "motorCache", "return", "{", "path", ":", "actualPath", ".", "motor", ",", "available", ":", "motorCache", ",", "prefix", ":", "'out'", "}", "}", "function", "sensor", "(", ")", "{", "sensorCache", "=", "isEmpty", "(", "sensorCache", ")", "?", "getPaths", "(", "actualPath", ".", "sensor", ")", ":", "sensorCache", "return", "{", "path", ":", "actualPath", ".", "sensor", ",", "available", ":", "sensorCache", ",", "prefix", ":", "'in'", "}", "}", "}" ]
Get a device @param {String} port @return {String} path
[ "Get", "a", "device" ]
d4d16ae74d1add6e1bda08f6251422b67384ff5f
https://github.com/ev3-js/devices/blob/d4d16ae74d1add6e1bda08f6251422b67384ff5f/lib/index.js#L44-L75
49,078
timoxley/ordered-set
ordered-set.js
SetArr
function SetArr() { let arr = {} let set = { size: 0, clear() { set.size = 0 }, add(item) { let index = arr.indexOf(item) if (index !== -1) return arr arr.push(item) set.size = arr.length return set }, delete(item) { let index = arr.indexOf(item) if (index === -1) return false arr.splice(index, 1) set.size = arr.length return true }, [Symbol.iterator]: () => arr[Symbol.iterator]() } return set }
javascript
function SetArr() { let arr = {} let set = { size: 0, clear() { set.size = 0 }, add(item) { let index = arr.indexOf(item) if (index !== -1) return arr arr.push(item) set.size = arr.length return set }, delete(item) { let index = arr.indexOf(item) if (index === -1) return false arr.splice(index, 1) set.size = arr.length return true }, [Symbol.iterator]: () => arr[Symbol.iterator]() } return set }
[ "function", "SetArr", "(", ")", "{", "let", "arr", "=", "{", "}", "let", "set", "=", "{", "size", ":", "0", ",", "clear", "(", ")", "{", "set", ".", "size", "=", "0", "}", ",", "add", "(", "item", ")", "{", "let", "index", "=", "arr", ".", "indexOf", "(", "item", ")", "if", "(", "index", "!==", "-", "1", ")", "return", "arr", "arr", ".", "push", "(", "item", ")", "set", ".", "size", "=", "arr", ".", "length", "return", "set", "}", ",", "delete", "(", "item", ")", "{", "let", "index", "=", "arr", ".", "indexOf", "(", "item", ")", "if", "(", "index", "===", "-", "1", ")", "return", "false", "arr", ".", "splice", "(", "index", ",", "1", ")", "set", ".", "size", "=", "arr", ".", "length", "return", "true", "}", ",", "[", "Symbol", ".", "iterator", "]", ":", "(", ")", "=>", "arr", "[", "Symbol", ".", "iterator", "]", "(", ")", "}", "return", "set", "}" ]
Set defining iteration ordering.
[ "Set", "defining", "iteration", "ordering", "." ]
8068335dbbaee823dc6aec2f3467fb0f490d7cdc
https://github.com/timoxley/ordered-set/blob/8068335dbbaee823dc6aec2f3467fb0f490d7cdc/ordered-set.js#L11-L35
49,079
AutocratJS/autocrat
autocrat.js
Autocrat
function Autocrat(options) { this.options = parseOptions(this, options); /** * A namespace to host members related to observing state/Autocrat activity * * @name surveillance * @namespace */ surveillance.serveAutocrat(this); this.surveillance = surveillance; /** * Has a dual nature as both an array and a namespace. The array members are * plugins, which are essentially mixins for the Autocrat singleton. * The namespace is used a general storage for plugin related methods and * information * * @name constitution * @namespace */ constitution.serveAutocrat(this); Ward.serveAutocrat(this); this.Ward = Ward; Advisor.serveAutocrat(this); this.Advisor = Advisor; Governor.serveAutocrat(this); this.Governor = Governor; Domain.serveAutocrat(this); this.Domain = Domain; Law.serveAutocrat(this); this.Law = Law; }
javascript
function Autocrat(options) { this.options = parseOptions(this, options); /** * A namespace to host members related to observing state/Autocrat activity * * @name surveillance * @namespace */ surveillance.serveAutocrat(this); this.surveillance = surveillance; /** * Has a dual nature as both an array and a namespace. The array members are * plugins, which are essentially mixins for the Autocrat singleton. * The namespace is used a general storage for plugin related methods and * information * * @name constitution * @namespace */ constitution.serveAutocrat(this); Ward.serveAutocrat(this); this.Ward = Ward; Advisor.serveAutocrat(this); this.Advisor = Advisor; Governor.serveAutocrat(this); this.Governor = Governor; Domain.serveAutocrat(this); this.Domain = Domain; Law.serveAutocrat(this); this.Law = Law; }
[ "function", "Autocrat", "(", "options", ")", "{", "this", ".", "options", "=", "parseOptions", "(", "this", ",", "options", ")", ";", "/**\n * A namespace to host members related to observing state/Autocrat activity\n *\n * @name surveillance\n * @namespace\n */", "surveillance", ".", "serveAutocrat", "(", "this", ")", ";", "this", ".", "surveillance", "=", "surveillance", ";", "/**\n * Has a dual nature as both an array and a namespace. The array members are\n * plugins, which are essentially mixins for the Autocrat singleton. \n * The namespace is used a general storage for plugin related methods and\n * information\n *\n * @name constitution\n * @namespace\n */", "constitution", ".", "serveAutocrat", "(", "this", ")", ";", "Ward", ".", "serveAutocrat", "(", "this", ")", ";", "this", ".", "Ward", "=", "Ward", ";", "Advisor", ".", "serveAutocrat", "(", "this", ")", ";", "this", ".", "Advisor", "=", "Advisor", ";", "Governor", ".", "serveAutocrat", "(", "this", ")", ";", "this", ".", "Governor", "=", "Governor", ";", "Domain", ".", "serveAutocrat", "(", "this", ")", ";", "this", ".", "Domain", "=", "Domain", ";", "Law", ".", "serveAutocrat", "(", "this", ")", ";", "this", ".", "Law", "=", "Law", ";", "}" ]
Constructs a singleton and namespace. All Autocrat plugins attach their functionality to the returned instance before the below listed aspects of the singleton are initialized. Plugins therefore have an early opportunity to augment the singleton. * [surveillance](https://github.com/AutocratJS/autocrat/wiki/Surveillance) — coordinates and provides methods for observation of state-related activity * [constitution](https://github.com/AutocratJS/autocrat/wiki/The-Autocrat-Constitution-\(aka-Plugins\)) — extra powers given to the Autocrat (plugins basically) * [wards](https://github.com/AutocratJS/autocrat/wiki/Wards) — have a bidirectional relationship to the Autocrat singleton, e.g. app.state.ward.router and router.autocrat * [advisors](https://github.com/AutocratJS/autocrat/wiki/Advisors) — produce Bacon event streams for coordination via laws within governors * [governors](https://github.com/AutocratJS/autocrat/wiki/Governors) — define laws and methods that mutate state members of domains * [domains](https://github.com/AutocratJS/autocrat/wiki/Domains) — define how to handle batched change events for given domains, e.g. re-render when the "view" domain changes * [laws](https://github.com/AutocratJS/autocrat/wiki/Laws) — define the side effects to occur in response to advisor events __More details__ about [the Autocrat singleton](https://github.com/AutocratJS/autocrat/wiki/The-Autocrat-Singleton)… @class @param {Object} options Configuration options @param {Object} options.wards Object key is used as the member name. Example: key "router" becomes app.state.wards.router @example // Instantiating the singleton // =========================== // Routers aren't unsually available at Autocrat definition time var router = new Router(); In order to have dev tools console access to the Autocrat instance export it to a global variable (not ideal) or as a member of an application global namespace (better). app.state = new Autocrat({ wards: { // This will add a .autocrat member to the router instance, as well // as making the router instance available at app.state.wards.router router: router } });
[ "Constructs", "a", "singleton", "and", "namespace", ".", "All", "Autocrat", "plugins", "attach", "their", "functionality", "to", "the", "returned", "instance", "before", "the", "below", "listed", "aspects", "of", "the", "singleton", "are", "initialized", ".", "Plugins", "therefore", "have", "an", "early", "opportunity", "to", "augment", "the", "singleton", "." ]
ca1466f851c4dbc5237fbbb2ee7caa1cff964f51
https://github.com/AutocratJS/autocrat/blob/ca1466f851c4dbc5237fbbb2ee7caa1cff964f51/autocrat.js#L52-L89
49,080
joy-web/perfect-css
_gh_pages/components/navigation/util.js
getTransformPropertyName
function getTransformPropertyName(globalObj, forceRefresh = false) { if (storedTransformPropertyName_ === undefined || forceRefresh) { const el = globalObj.document.createElement('div'); const transformPropertyName = ('transform' in el.style ? 'transform' : 'webkitTransform'); storedTransformPropertyName_ = transformPropertyName; } return storedTransformPropertyName_; }
javascript
function getTransformPropertyName(globalObj, forceRefresh = false) { if (storedTransformPropertyName_ === undefined || forceRefresh) { const el = globalObj.document.createElement('div'); const transformPropertyName = ('transform' in el.style ? 'transform' : 'webkitTransform'); storedTransformPropertyName_ = transformPropertyName; } return storedTransformPropertyName_; }
[ "function", "getTransformPropertyName", "(", "globalObj", ",", "forceRefresh", "=", "false", ")", "{", "if", "(", "storedTransformPropertyName_", "===", "undefined", "||", "forceRefresh", ")", "{", "const", "el", "=", "globalObj", ".", "document", ".", "createElement", "(", "'div'", ")", ";", "const", "transformPropertyName", "=", "(", "'transform'", "in", "el", ".", "style", "?", "'transform'", ":", "'webkitTransform'", ")", ";", "storedTransformPropertyName_", "=", "transformPropertyName", ";", "}", "return", "storedTransformPropertyName_", ";", "}" ]
Returns the name of the correct transform property to use on the current browser. @param {!Window} globalObj @param {boolean=} forceRefresh @return {string}
[ "Returns", "the", "name", "of", "the", "correct", "transform", "property", "to", "use", "on", "the", "current", "browser", "." ]
d2e209a270d2abd9830627e5bd0267454562c82c
https://github.com/joy-web/perfect-css/blob/d2e209a270d2abd9830627e5bd0267454562c82c/_gh_pages/components/navigation/util.js#L26-L34
49,081
kuno/neco
deps/npm/lib/update-dependents.js
updateDepsTo
function updateDepsTo (arg, cb) { asyncMap(arg._others, function (o, cb) { updateOtherVersionDeps(o, arg, cb) }, cb) }
javascript
function updateDepsTo (arg, cb) { asyncMap(arg._others, function (o, cb) { updateOtherVersionDeps(o, arg, cb) }, cb) }
[ "function", "updateDepsTo", "(", "arg", ",", "cb", ")", "{", "asyncMap", "(", "arg", ".", "_others", ",", "function", "(", "o", ",", "cb", ")", "{", "updateOtherVersionDeps", "(", "o", ",", "arg", ",", "cb", ")", "}", ",", "cb", ")", "}" ]
update the _others to this one.
[ "update", "the", "_others", "to", "this", "one", "." ]
cf6361c1fcb9466c6b2ab3b127b5d0160ca50735
https://github.com/kuno/neco/blob/cf6361c1fcb9466c6b2ab3b127b5d0160ca50735/deps/npm/lib/update-dependents.js#L81-L85
49,082
kuno/neco
deps/npm/lib/update-dependents.js
createDependencyLinks
function createDependencyLinks (dep, pkg, cb) { var depdir = path.join(npm.dir, dep.name, dep.version) , depsOn = path.join( depdir , "dependson" , pkg.name+"@"+pkg.version ) , deps = path.join(depdir, "node_modules", pkg.name) , targetRoot = path.join(npm.dir, pkg.name, pkg.version) , dependentLink = path.join( npm.dir , pkg.name , pkg.version , "dependents" , dep.name + "@" + dep.version ) asyncMap ( [ [ link, targetRoot, depsOn ] , [ link, depdir, dependentLink ] , [ linkBins, pkg, path.join(depdir, "dep-bin"), false ] , [ linkModules, pkg, deps ] ] , function (c, cb) { c.shift().apply(null, c.concat(cb)) } , cb ) }
javascript
function createDependencyLinks (dep, pkg, cb) { var depdir = path.join(npm.dir, dep.name, dep.version) , depsOn = path.join( depdir , "dependson" , pkg.name+"@"+pkg.version ) , deps = path.join(depdir, "node_modules", pkg.name) , targetRoot = path.join(npm.dir, pkg.name, pkg.version) , dependentLink = path.join( npm.dir , pkg.name , pkg.version , "dependents" , dep.name + "@" + dep.version ) asyncMap ( [ [ link, targetRoot, depsOn ] , [ link, depdir, dependentLink ] , [ linkBins, pkg, path.join(depdir, "dep-bin"), false ] , [ linkModules, pkg, deps ] ] , function (c, cb) { c.shift().apply(null, c.concat(cb)) } , cb ) }
[ "function", "createDependencyLinks", "(", "dep", ",", "pkg", ",", "cb", ")", "{", "var", "depdir", "=", "path", ".", "join", "(", "npm", ".", "dir", ",", "dep", ".", "name", ",", "dep", ".", "version", ")", ",", "depsOn", "=", "path", ".", "join", "(", "depdir", ",", "\"dependson\"", ",", "pkg", ".", "name", "+", "\"@\"", "+", "pkg", ".", "version", ")", ",", "deps", "=", "path", ".", "join", "(", "depdir", ",", "\"node_modules\"", ",", "pkg", ".", "name", ")", ",", "targetRoot", "=", "path", ".", "join", "(", "npm", ".", "dir", ",", "pkg", ".", "name", ",", "pkg", ".", "version", ")", ",", "dependentLink", "=", "path", ".", "join", "(", "npm", ".", "dir", ",", "pkg", ".", "name", ",", "pkg", ".", "version", ",", "\"dependents\"", ",", "dep", ".", "name", "+", "\"@\"", "+", "dep", ".", "version", ")", "asyncMap", "(", "[", "[", "link", ",", "targetRoot", ",", "depsOn", "]", ",", "[", "link", ",", "depdir", ",", "dependentLink", "]", ",", "[", "linkBins", ",", "pkg", ",", "path", ".", "join", "(", "depdir", ",", "\"dep-bin\"", ")", ",", "false", "]", ",", "[", "linkModules", ",", "pkg", ",", "deps", "]", "]", ",", "function", "(", "c", ",", "cb", ")", "{", "c", ".", "shift", "(", ")", ".", "apply", "(", "null", ",", "c", ".", "concat", "(", "cb", ")", ")", "}", ",", "cb", ")", "}" ]
dep depends on pkg
[ "dep", "depends", "on", "pkg" ]
cf6361c1fcb9466c6b2ab3b127b5d0160ca50735
https://github.com/kuno/neco/blob/cf6361c1fcb9466c6b2ab3b127b5d0160ca50735/deps/npm/lib/update-dependents.js#L193-L218
49,083
richardzyx/node-microservice
index.js
defer
function defer(timeout) { var resolve, reject; var promise = new Promise(function() { resolve = arguments[0]; reject = arguments[1]; setTimeout(reject, timeout, "Timeout"); }); return { resolve: resolve, reject: reject, promise: promise, timestamp:new Date().getTime() }; }
javascript
function defer(timeout) { var resolve, reject; var promise = new Promise(function() { resolve = arguments[0]; reject = arguments[1]; setTimeout(reject, timeout, "Timeout"); }); return { resolve: resolve, reject: reject, promise: promise, timestamp:new Date().getTime() }; }
[ "function", "defer", "(", "timeout", ")", "{", "var", "resolve", ",", "reject", ";", "var", "promise", "=", "new", "Promise", "(", "function", "(", ")", "{", "resolve", "=", "arguments", "[", "0", "]", ";", "reject", "=", "arguments", "[", "1", "]", ";", "setTimeout", "(", "reject", ",", "timeout", ",", "\"Timeout\"", ")", ";", "}", ")", ";", "return", "{", "resolve", ":", "resolve", ",", "reject", ":", "reject", ",", "promise", ":", "promise", ",", "timestamp", ":", "new", "Date", "(", ")", ".", "getTime", "(", ")", "}", ";", "}" ]
defer is discourage in most promise library so we define one for this particular situation
[ "defer", "is", "discourage", "in", "most", "promise", "library", "so", "we", "define", "one", "for", "this", "particular", "situation" ]
3390659fec06621ba05bd7e6716ace3223d52aa3
https://github.com/richardzyx/node-microservice/blob/3390659fec06621ba05bd7e6716ace3223d52aa3/index.js#L9-L22
49,084
creationix/repo-farm
one-shot.js
oneShot
function oneShot(callback) { var done = false; return function (err) { if (!done) { done = true; return callback.apply(this, arguments); } if (err) console.error(err.stack); } }
javascript
function oneShot(callback) { var done = false; return function (err) { if (!done) { done = true; return callback.apply(this, arguments); } if (err) console.error(err.stack); } }
[ "function", "oneShot", "(", "callback", ")", "{", "var", "done", "=", "false", ";", "return", "function", "(", "err", ")", "{", "if", "(", "!", "done", ")", "{", "done", "=", "true", ";", "return", "callback", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "if", "(", "err", ")", "console", ".", "error", "(", "err", ".", "stack", ")", ";", "}", "}" ]
Makes sure a callback is only called once.
[ "Makes", "sure", "a", "callback", "is", "only", "called", "once", "." ]
31d24a77070c6f8bc1e669149aecfa15f954c264
https://github.com/creationix/repo-farm/blob/31d24a77070c6f8bc1e669149aecfa15f954c264/one-shot.js#L5-L14
49,085
doowb/gulp-collection
examples/example.js
makeFile
function makeFile(idx) { var file = new Vinyl({ path: `source-file-${idx}.hbs`, contents: new Buffer(`this is source-file-${idx}`) }); file.data = { categories: pickCategories(), tags: pickTags() }; return file; }
javascript
function makeFile(idx) { var file = new Vinyl({ path: `source-file-${idx}.hbs`, contents: new Buffer(`this is source-file-${idx}`) }); file.data = { categories: pickCategories(), tags: pickTags() }; return file; }
[ "function", "makeFile", "(", "idx", ")", "{", "var", "file", "=", "new", "Vinyl", "(", "{", "path", ":", "`", "${", "idx", "}", "`", ",", "contents", ":", "new", "Buffer", "(", "`", "${", "idx", "}", "`", ")", "}", ")", ";", "file", ".", "data", "=", "{", "categories", ":", "pickCategories", "(", ")", ",", "tags", ":", "pickTags", "(", ")", "}", ";", "return", "file", ";", "}" ]
make a new file with randomly selected categories and tags
[ "make", "a", "new", "file", "with", "randomly", "selected", "categories", "and", "tags" ]
8469ee2e8e5f112f3fe11aab5a8565d653c65c85
https://github.com/doowb/gulp-collection/blob/8469ee2e8e5f112f3fe11aab5a8565d653c65c85/examples/example.js#L56-L66
49,086
doowb/gulp-collection
examples/example.js
pickTags
function pickTags() { var picked = []; var max = Math.floor(Math.random() * maxTags); while(picked.length < max) { var tag = pickTag(); if (picked.indexOf(tag) === -1) { picked.push(tag); } } return picked; }
javascript
function pickTags() { var picked = []; var max = Math.floor(Math.random() * maxTags); while(picked.length < max) { var tag = pickTag(); if (picked.indexOf(tag) === -1) { picked.push(tag); } } return picked; }
[ "function", "pickTags", "(", ")", "{", "var", "picked", "=", "[", "]", ";", "var", "max", "=", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "maxTags", ")", ";", "while", "(", "picked", ".", "length", "<", "max", ")", "{", "var", "tag", "=", "pickTag", "(", ")", ";", "if", "(", "picked", ".", "indexOf", "(", "tag", ")", "===", "-", "1", ")", "{", "picked", ".", "push", "(", "tag", ")", ";", "}", "}", "return", "picked", ";", "}" ]
pick random tags up to the `maxTags`
[ "pick", "random", "tags", "up", "to", "the", "maxTags" ]
8469ee2e8e5f112f3fe11aab5a8565d653c65c85
https://github.com/doowb/gulp-collection/blob/8469ee2e8e5f112f3fe11aab5a8565d653c65c85/examples/example.js#L74-L84
49,087
doowb/gulp-collection
examples/example.js
pickCategories
function pickCategories() { var picked = []; var max = Math.floor(Math.random() * maxCategories); while(picked.length < max) { var category = pickCategory(); if (picked.indexOf(category) === -1) { picked.push(category); } } return picked; }
javascript
function pickCategories() { var picked = []; var max = Math.floor(Math.random() * maxCategories); while(picked.length < max) { var category = pickCategory(); if (picked.indexOf(category) === -1) { picked.push(category); } } return picked; }
[ "function", "pickCategories", "(", ")", "{", "var", "picked", "=", "[", "]", ";", "var", "max", "=", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "maxCategories", ")", ";", "while", "(", "picked", ".", "length", "<", "max", ")", "{", "var", "category", "=", "pickCategory", "(", ")", ";", "if", "(", "picked", ".", "indexOf", "(", "category", ")", "===", "-", "1", ")", "{", "picked", ".", "push", "(", "category", ")", ";", "}", "}", "return", "picked", ";", "}" ]
pick random categories up to the `maxCategories`
[ "pick", "random", "categories", "up", "to", "the", "maxCategories" ]
8469ee2e8e5f112f3fe11aab5a8565d653c65c85
https://github.com/doowb/gulp-collection/blob/8469ee2e8e5f112f3fe11aab5a8565d653c65c85/examples/example.js#L92-L102
49,088
meetings/gearsloth
lib/daemon/injector.js
Injector
function Injector(conf) { component.Component.call(this, 'injector', conf); var that = this; this._default_controller = defaults.controllerfuncname(conf); this._dbconn = conf.dbconn; this.registerGearman(conf.servers, { worker: { func_name: 'submitJobDelayed', func: function(payload, worker) { var task; try { task = JSON.parse(payload); } catch (err) { that._err('Error:', err.message); worker.done(that.component_name + ': ' + err.message); return; } that._info('Received a task for', (task.controller || that._default_controller) + '/' + task.func_name); // TODO: Properly abstract date handling into lib/gearsloth.js and handle // invalid dates etc. if ('at' in task) { task.at = new Date(task.at); if (isNaN(task.at.getTime())) { worker.done(that.component_name + ': invalid date format.'); return; } } if ('after' in task && isNaN(task.after)) { worker.done(that.component_name + ': invalid \'after\' format.'); return; } if (! ('func_name' in task)) { worker.done(that.component_name + ': no function name (func_name) defined in task.'); return; } that.inject(task, worker); } } }); }
javascript
function Injector(conf) { component.Component.call(this, 'injector', conf); var that = this; this._default_controller = defaults.controllerfuncname(conf); this._dbconn = conf.dbconn; this.registerGearman(conf.servers, { worker: { func_name: 'submitJobDelayed', func: function(payload, worker) { var task; try { task = JSON.parse(payload); } catch (err) { that._err('Error:', err.message); worker.done(that.component_name + ': ' + err.message); return; } that._info('Received a task for', (task.controller || that._default_controller) + '/' + task.func_name); // TODO: Properly abstract date handling into lib/gearsloth.js and handle // invalid dates etc. if ('at' in task) { task.at = new Date(task.at); if (isNaN(task.at.getTime())) { worker.done(that.component_name + ': invalid date format.'); return; } } if ('after' in task && isNaN(task.after)) { worker.done(that.component_name + ': invalid \'after\' format.'); return; } if (! ('func_name' in task)) { worker.done(that.component_name + ': no function name (func_name) defined in task.'); return; } that.inject(task, worker); } } }); }
[ "function", "Injector", "(", "conf", ")", "{", "component", ".", "Component", ".", "call", "(", "this", ",", "'injector'", ",", "conf", ")", ";", "var", "that", "=", "this", ";", "this", ".", "_default_controller", "=", "defaults", ".", "controllerfuncname", "(", "conf", ")", ";", "this", ".", "_dbconn", "=", "conf", ".", "dbconn", ";", "this", ".", "registerGearman", "(", "conf", ".", "servers", ",", "{", "worker", ":", "{", "func_name", ":", "'submitJobDelayed'", ",", "func", ":", "function", "(", "payload", ",", "worker", ")", "{", "var", "task", ";", "try", "{", "task", "=", "JSON", ".", "parse", "(", "payload", ")", ";", "}", "catch", "(", "err", ")", "{", "that", ".", "_err", "(", "'Error:'", ",", "err", ".", "message", ")", ";", "worker", ".", "done", "(", "that", ".", "component_name", "+", "': '", "+", "err", ".", "message", ")", ";", "return", ";", "}", "that", ".", "_info", "(", "'Received a task for'", ",", "(", "task", ".", "controller", "||", "that", ".", "_default_controller", ")", "+", "'/'", "+", "task", ".", "func_name", ")", ";", "// TODO: Properly abstract date handling into lib/gearsloth.js and handle", "// invalid dates etc.", "if", "(", "'at'", "in", "task", ")", "{", "task", ".", "at", "=", "new", "Date", "(", "task", ".", "at", ")", ";", "if", "(", "isNaN", "(", "task", ".", "at", ".", "getTime", "(", ")", ")", ")", "{", "worker", ".", "done", "(", "that", ".", "component_name", "+", "': invalid date format.'", ")", ";", "return", ";", "}", "}", "if", "(", "'after'", "in", "task", "&&", "isNaN", "(", "task", ".", "after", ")", ")", "{", "worker", ".", "done", "(", "that", ".", "component_name", "+", "': invalid \\'after\\' format.'", ")", ";", "return", ";", "}", "if", "(", "!", "(", "'func_name'", "in", "task", ")", ")", "{", "worker", ".", "done", "(", "that", ".", "component_name", "+", "': no function name (func_name) defined in task.'", ")", ";", "return", ";", "}", "that", ".", "inject", "(", "task", ",", "worker", ")", ";", "}", "}", "}", ")", ";", "}" ]
Injector component. Emits 'connect' when at least one server is connected.
[ "Injector", "component", ".", "Emits", "connect", "when", "at", "least", "one", "server", "is", "connected", "." ]
21d07729d6197bdbea515f32922896e3ae485d46
https://github.com/meetings/gearsloth/blob/21d07729d6197bdbea515f32922896e3ae485d46/lib/daemon/injector.js#L9-L52
49,089
jackspaniel/yukon
plugins/parallel-api/api.js
getData
function getData(callArgs, req, res, next) { debug("getData called"); if (callArgs.useStub) readStub(callArgs, req, res, next); else callApi(callArgs, req, res, next); }
javascript
function getData(callArgs, req, res, next) { debug("getData called"); if (callArgs.useStub) readStub(callArgs, req, res, next); else callApi(callArgs, req, res, next); }
[ "function", "getData", "(", "callArgs", ",", "req", ",", "res", ",", "next", ")", "{", "debug", "(", "\"getData called\"", ")", ";", "if", "(", "callArgs", ".", "useStub", ")", "readStub", "(", "callArgs", ",", "req", ",", "res", ",", "next", ")", ";", "else", "callApi", "(", "callArgs", ",", "req", ",", "res", ",", "next", ")", ";", "}" ]
route call to get stub or use live API
[ "route", "call", "to", "get", "stub", "or", "use", "live", "API" ]
7e5259126751dc5b604c6156d470f0a9ca9e3966
https://github.com/jackspaniel/yukon/blob/7e5259126751dc5b604c6156d470f0a9ca9e3966/plugins/parallel-api/api.js#L17-L24
49,090
alexindigo/node-global-define
index.js
GlobalDefine
function GlobalDefine(options) { var globalDefine; if (!(this instanceof GlobalDefine)) { globalDefine = new GlobalDefine(options); return globalDefine.amdefineWorkaround(globalDefine.getCallerModule()); } this.basePath = options.basePath || process.cwd(); this.paths = options.paths || paths; this.pathsKeys = Object.keys(this.paths).sort(sortPaths); this.blackList = options.blackList || blackList; this.whiteList = options.whiteList || whiteList; this.disableCache = options.disableCache || disableCache; this.aliasRequire = options.aliasRequire || aliasRequire; // if flag provided override default value this.exposeAmdefine = ('exposeAmdefine' in options) ? options.exposeAmdefine : exposeAmdefine; // construct basePath regexp this.basePathRegexp = new RegExp(('^' + this.basePath + '/').replace('/', '\\/')); // propagate upstream to allow global-define on sibling branches this.propagateUpstream(this.getCallerModule(), options.forceUpstream); // being a little bit brutal // for things that go around normal module loading process // like `istanbul`, that reads (`fs.readFileSync(filename, 'utf8')`) // and runs `module._compile(code, filename);` compilation step // skipping loading extensions. // But do it only once, no need to step on itself if (options.invasiveMode && Module.prototype._compile._id != module.id) { originalModuleCompile = Module.prototype._compile; Module.prototype._compile = customModuleCompile; Module.prototype._compile._id = module.id; } }
javascript
function GlobalDefine(options) { var globalDefine; if (!(this instanceof GlobalDefine)) { globalDefine = new GlobalDefine(options); return globalDefine.amdefineWorkaround(globalDefine.getCallerModule()); } this.basePath = options.basePath || process.cwd(); this.paths = options.paths || paths; this.pathsKeys = Object.keys(this.paths).sort(sortPaths); this.blackList = options.blackList || blackList; this.whiteList = options.whiteList || whiteList; this.disableCache = options.disableCache || disableCache; this.aliasRequire = options.aliasRequire || aliasRequire; // if flag provided override default value this.exposeAmdefine = ('exposeAmdefine' in options) ? options.exposeAmdefine : exposeAmdefine; // construct basePath regexp this.basePathRegexp = new RegExp(('^' + this.basePath + '/').replace('/', '\\/')); // propagate upstream to allow global-define on sibling branches this.propagateUpstream(this.getCallerModule(), options.forceUpstream); // being a little bit brutal // for things that go around normal module loading process // like `istanbul`, that reads (`fs.readFileSync(filename, 'utf8')`) // and runs `module._compile(code, filename);` compilation step // skipping loading extensions. // But do it only once, no need to step on itself if (options.invasiveMode && Module.prototype._compile._id != module.id) { originalModuleCompile = Module.prototype._compile; Module.prototype._compile = customModuleCompile; Module.prototype._compile._id = module.id; } }
[ "function", "GlobalDefine", "(", "options", ")", "{", "var", "globalDefine", ";", "if", "(", "!", "(", "this", "instanceof", "GlobalDefine", ")", ")", "{", "globalDefine", "=", "new", "GlobalDefine", "(", "options", ")", ";", "return", "globalDefine", ".", "amdefineWorkaround", "(", "globalDefine", ".", "getCallerModule", "(", ")", ")", ";", "}", "this", ".", "basePath", "=", "options", ".", "basePath", "||", "process", ".", "cwd", "(", ")", ";", "this", ".", "paths", "=", "options", ".", "paths", "||", "paths", ";", "this", ".", "pathsKeys", "=", "Object", ".", "keys", "(", "this", ".", "paths", ")", ".", "sort", "(", "sortPaths", ")", ";", "this", ".", "blackList", "=", "options", ".", "blackList", "||", "blackList", ";", "this", ".", "whiteList", "=", "options", ".", "whiteList", "||", "whiteList", ";", "this", ".", "disableCache", "=", "options", ".", "disableCache", "||", "disableCache", ";", "this", ".", "aliasRequire", "=", "options", ".", "aliasRequire", "||", "aliasRequire", ";", "// if flag provided override default value", "this", ".", "exposeAmdefine", "=", "(", "'exposeAmdefine'", "in", "options", ")", "?", "options", ".", "exposeAmdefine", ":", "exposeAmdefine", ";", "// construct basePath regexp", "this", ".", "basePathRegexp", "=", "new", "RegExp", "(", "(", "'^'", "+", "this", ".", "basePath", "+", "'/'", ")", ".", "replace", "(", "'/'", ",", "'\\\\/'", ")", ")", ";", "// propagate upstream to allow global-define on sibling branches", "this", ".", "propagateUpstream", "(", "this", ".", "getCallerModule", "(", ")", ",", "options", ".", "forceUpstream", ")", ";", "// being a little bit brutal", "// for things that go around normal module loading process", "// like `istanbul`, that reads (`fs.readFileSync(filename, 'utf8')`)", "// and runs `module._compile(code, filename);` compilation step", "// skipping loading extensions.", "// But do it only once, no need to step on itself", "if", "(", "options", ".", "invasiveMode", "&&", "Module", ".", "prototype", ".", "_compile", ".", "_id", "!=", "module", ".", "id", ")", "{", "originalModuleCompile", "=", "Module", ".", "prototype", ".", "_compile", ";", "Module", ".", "prototype", ".", "_compile", "=", "customModuleCompile", ";", "Module", ".", "prototype", ".", "_compile", ".", "_id", "=", "module", ".", "id", ";", "}", "}" ]
export API function to update basePath
[ "export", "API", "function", "to", "update", "basePath" ]
2dba825053918d61d272aa31225d3a13a4088f75
https://github.com/alexindigo/node-global-define/blob/2dba825053918d61d272aa31225d3a13a4088f75/index.js#L48-L86
49,091
alexindigo/node-global-define
index.js
propagateUpstream
function propagateUpstream(parentModule, shouldPropagate) { // do not step on another global-define instance if (parentModule._globalDefine) return; // keep reference to the define instance parentModule._globalDefine = this; if (shouldPropagate && parentModule.parent) { this.propagateUpstream(parentModule.parent, shouldPropagate); } }
javascript
function propagateUpstream(parentModule, shouldPropagate) { // do not step on another global-define instance if (parentModule._globalDefine) return; // keep reference to the define instance parentModule._globalDefine = this; if (shouldPropagate && parentModule.parent) { this.propagateUpstream(parentModule.parent, shouldPropagate); } }
[ "function", "propagateUpstream", "(", "parentModule", ",", "shouldPropagate", ")", "{", "// do not step on another global-define instance", "if", "(", "parentModule", ".", "_globalDefine", ")", "return", ";", "// keep reference to the define instance", "parentModule", ".", "_globalDefine", "=", "this", ";", "if", "(", "shouldPropagate", "&&", "parentModule", ".", "parent", ")", "{", "this", ".", "propagateUpstream", "(", "parentModule", ".", "parent", ",", "shouldPropagate", ")", ";", "}", "}" ]
propagates global-define instance upstream until it bumps into another globalDefine instance
[ "propagates", "global", "-", "define", "instance", "upstream", "until", "it", "bumps", "into", "another", "globalDefine", "instance" ]
2dba825053918d61d272aa31225d3a13a4088f75
https://github.com/alexindigo/node-global-define/blob/2dba825053918d61d272aa31225d3a13a4088f75/index.js#L96-L108
49,092
alexindigo/node-global-define
index.js
checkPath
function checkPath(id) { var i; for (i = 0; i < this.pathsKeys.length; i++) { if (id.indexOf(this.pathsKeys[i]) == 0) { if (this.paths[this.pathsKeys[i]] == 'empty:') { id = 'empty:'; } else { id = id.replace(this.pathsKeys[i], this.paths[this.pathsKeys[i]]); } break; } } return id; }
javascript
function checkPath(id) { var i; for (i = 0; i < this.pathsKeys.length; i++) { if (id.indexOf(this.pathsKeys[i]) == 0) { if (this.paths[this.pathsKeys[i]] == 'empty:') { id = 'empty:'; } else { id = id.replace(this.pathsKeys[i], this.paths[this.pathsKeys[i]]); } break; } } return id; }
[ "function", "checkPath", "(", "id", ")", "{", "var", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "this", ".", "pathsKeys", ".", "length", ";", "i", "++", ")", "{", "if", "(", "id", ".", "indexOf", "(", "this", ".", "pathsKeys", "[", "i", "]", ")", "==", "0", ")", "{", "if", "(", "this", ".", "paths", "[", "this", ".", "pathsKeys", "[", "i", "]", "]", "==", "'empty:'", ")", "{", "id", "=", "'empty:'", ";", "}", "else", "{", "id", "=", "id", ".", "replace", "(", "this", ".", "pathsKeys", "[", "i", "]", ",", "this", ".", "paths", "[", "this", ".", "pathsKeys", "[", "i", "]", "]", ")", ";", "}", "break", ";", "}", "}", "return", "id", ";", "}" ]
check path aliases
[ "check", "path", "aliases" ]
2dba825053918d61d272aa31225d3a13a4088f75
https://github.com/alexindigo/node-global-define/blob/2dba825053918d61d272aa31225d3a13a4088f75/index.js#L202-L223
49,093
alexindigo/node-global-define
index.js
isBlacklisted
function isBlacklisted(moduleId) { var i; // strip basePath moduleId = moduleId.replace(this.basePathRegexp, ''); for (i = 0; i < this.blackList.length; i++) { if (minimatch(moduleId, this.blackList[i])) { return true; } } return false; }
javascript
function isBlacklisted(moduleId) { var i; // strip basePath moduleId = moduleId.replace(this.basePathRegexp, ''); for (i = 0; i < this.blackList.length; i++) { if (minimatch(moduleId, this.blackList[i])) { return true; } } return false; }
[ "function", "isBlacklisted", "(", "moduleId", ")", "{", "var", "i", ";", "// strip basePath", "moduleId", "=", "moduleId", ".", "replace", "(", "this", ".", "basePathRegexp", ",", "''", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "this", ".", "blackList", ".", "length", ";", "i", "++", ")", "{", "if", "(", "minimatch", "(", "moduleId", ",", "this", ".", "blackList", "[", "i", "]", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
checks blackList, using glob-like patterns
[ "checks", "blackList", "using", "glob", "-", "like", "patterns" ]
2dba825053918d61d272aa31225d3a13a4088f75
https://github.com/alexindigo/node-global-define/blob/2dba825053918d61d272aa31225d3a13a4088f75/index.js#L226-L242
49,094
alexindigo/node-global-define
index.js
isWhitelisted
function isWhitelisted(moduleId) { var i; // check if its empty if (!this.whiteList.length) { return true; } // strip basePath moduleId = moduleId.replace(this.basePathRegexp, ''); for (i = 0; i < this.whiteList.length; i++) { if (minimatch(moduleId, this.whiteList[i])) { return true; } } return false; }
javascript
function isWhitelisted(moduleId) { var i; // check if its empty if (!this.whiteList.length) { return true; } // strip basePath moduleId = moduleId.replace(this.basePathRegexp, ''); for (i = 0; i < this.whiteList.length; i++) { if (minimatch(moduleId, this.whiteList[i])) { return true; } } return false; }
[ "function", "isWhitelisted", "(", "moduleId", ")", "{", "var", "i", ";", "// check if its empty", "if", "(", "!", "this", ".", "whiteList", ".", "length", ")", "{", "return", "true", ";", "}", "// strip basePath", "moduleId", "=", "moduleId", ".", "replace", "(", "this", ".", "basePathRegexp", ",", "''", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "this", ".", "whiteList", ".", "length", ";", "i", "++", ")", "{", "if", "(", "minimatch", "(", "moduleId", ",", "this", ".", "whiteList", "[", "i", "]", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
checks whiteList, using glob-like patterns if white list is empty treat it as everything in white list
[ "checks", "whiteList", "using", "glob", "-", "like", "patterns", "if", "white", "list", "is", "empty", "treat", "it", "as", "everything", "in", "white", "list" ]
2dba825053918d61d272aa31225d3a13a4088f75
https://github.com/alexindigo/node-global-define/blob/2dba825053918d61d272aa31225d3a13a4088f75/index.js#L246-L268
49,095
alexindigo/node-global-define
index.js
customModuleCompile
function customModuleCompile(content, filename) { var moduleExceptions, parentDefine = global.define; if (!this._globalDefine) { setGlobalDefine(this); } moduleExceptions = originalModuleCompile.call(this, content, filename); global.define = parentDefine; return moduleExceptions; }
javascript
function customModuleCompile(content, filename) { var moduleExceptions, parentDefine = global.define; if (!this._globalDefine) { setGlobalDefine(this); } moduleExceptions = originalModuleCompile.call(this, content, filename); global.define = parentDefine; return moduleExceptions; }
[ "function", "customModuleCompile", "(", "content", ",", "filename", ")", "{", "var", "moduleExceptions", ",", "parentDefine", "=", "global", ".", "define", ";", "if", "(", "!", "this", ".", "_globalDefine", ")", "{", "setGlobalDefine", "(", "this", ")", ";", "}", "moduleExceptions", "=", "originalModuleCompile", ".", "call", "(", "this", ",", "content", ",", "filename", ")", ";", "global", ".", "define", "=", "parentDefine", ";", "return", "moduleExceptions", ";", "}" ]
replaces original `module._compile` for invasive mode but if this._globalDefine is present means our work here is done and reset global define back to the previous value
[ "replaces", "original", "module", ".", "_compile", "for", "invasive", "mode", "but", "if", "this", ".", "_globalDefine", "is", "present", "means", "our", "work", "here", "is", "done", "and", "reset", "global", "define", "back", "to", "the", "previous", "value" ]
2dba825053918d61d272aa31225d3a13a4088f75
https://github.com/alexindigo/node-global-define/blob/2dba825053918d61d272aa31225d3a13a4088f75/index.js#L275-L289
49,096
alexindigo/node-global-define
index.js
setGlobalDefine
function setGlobalDefine(requiredModule) { // pass globalDefine instance from parent to child module if (requiredModule.parent && requiredModule.parent._globalDefine) { // inherited instance requiredModule._globalDefine = requiredModule.parent._globalDefine; } // create global define specific to the module // but only if its whitelisted and not blacklisted if (requiredModule._globalDefine && requiredModule._globalDefine.isWhitelisted(requiredModule.id) && !requiredModule._globalDefine.isBlacklisted(requiredModule.id)) { global.define = requiredModule._globalDefine.amdefineWorkaround(requiredModule); // run required paths through alias substituion if (requiredModule._globalDefine.aliasRequire) { requiredModule._originalRequire = requiredModule.require; requiredModule.require = function(modulePath) { return requiredModule._originalRequire.call(this, requiredModule._globalDefine.checkPath(modulePath)); } } } else { // reset global define delete global.define; } }
javascript
function setGlobalDefine(requiredModule) { // pass globalDefine instance from parent to child module if (requiredModule.parent && requiredModule.parent._globalDefine) { // inherited instance requiredModule._globalDefine = requiredModule.parent._globalDefine; } // create global define specific to the module // but only if its whitelisted and not blacklisted if (requiredModule._globalDefine && requiredModule._globalDefine.isWhitelisted(requiredModule.id) && !requiredModule._globalDefine.isBlacklisted(requiredModule.id)) { global.define = requiredModule._globalDefine.amdefineWorkaround(requiredModule); // run required paths through alias substituion if (requiredModule._globalDefine.aliasRequire) { requiredModule._originalRequire = requiredModule.require; requiredModule.require = function(modulePath) { return requiredModule._originalRequire.call(this, requiredModule._globalDefine.checkPath(modulePath)); } } } else { // reset global define delete global.define; } }
[ "function", "setGlobalDefine", "(", "requiredModule", ")", "{", "// pass globalDefine instance from parent to child module", "if", "(", "requiredModule", ".", "parent", "&&", "requiredModule", ".", "parent", ".", "_globalDefine", ")", "{", "// inherited instance", "requiredModule", ".", "_globalDefine", "=", "requiredModule", ".", "parent", ".", "_globalDefine", ";", "}", "// create global define specific to the module", "// but only if its whitelisted and not blacklisted", "if", "(", "requiredModule", ".", "_globalDefine", "&&", "requiredModule", ".", "_globalDefine", ".", "isWhitelisted", "(", "requiredModule", ".", "id", ")", "&&", "!", "requiredModule", ".", "_globalDefine", ".", "isBlacklisted", "(", "requiredModule", ".", "id", ")", ")", "{", "global", ".", "define", "=", "requiredModule", ".", "_globalDefine", ".", "amdefineWorkaround", "(", "requiredModule", ")", ";", "// run required paths through alias substituion", "if", "(", "requiredModule", ".", "_globalDefine", ".", "aliasRequire", ")", "{", "requiredModule", ".", "_originalRequire", "=", "requiredModule", ".", "require", ";", "requiredModule", ".", "require", "=", "function", "(", "modulePath", ")", "{", "return", "requiredModule", ".", "_originalRequire", ".", "call", "(", "this", ",", "requiredModule", ".", "_globalDefine", ".", "checkPath", "(", "modulePath", ")", ")", ";", "}", "}", "}", "else", "{", "// reset global define", "delete", "global", ".", "define", ";", "}", "}" ]
sets _globalDefine and global.define if needed
[ "sets", "_globalDefine", "and", "global", ".", "define", "if", "needed" ]
2dba825053918d61d272aa31225d3a13a4088f75
https://github.com/alexindigo/node-global-define/blob/2dba825053918d61d272aa31225d3a13a4088f75/index.js#L309-L339
49,097
zertosh/pollen
BundlesModule.js
filesToPacks
function filesToPacks(files) { return files.map(function(id) { return { id: id, source: readFile(id), mtime: readMTime(id) }; }); }
javascript
function filesToPacks(files) { return files.map(function(id) { return { id: id, source: readFile(id), mtime: readMTime(id) }; }); }
[ "function", "filesToPacks", "(", "files", ")", "{", "return", "files", ".", "map", "(", "function", "(", "id", ")", "{", "return", "{", "id", ":", "id", ",", "source", ":", "readFile", "(", "id", ")", ",", "mtime", ":", "readMTime", "(", "id", ")", "}", ";", "}", ")", ";", "}" ]
Build the "packs" from an array of filenames
[ "Build", "the", "packs", "from", "an", "array", "of", "filenames" ]
c97b6168a56fc4a52f77242526dcd6a6cba3d6e5
https://github.com/zertosh/pollen/blob/c97b6168a56fc4a52f77242526dcd6a6cba3d6e5/BundlesModule.js#L130-L138
49,098
zertosh/pollen
BundlesModule.js
updatePacks
function updatePacks(packs) { var didUpdate = false; var updated = packs.map(function(pack) { var mtime_ = readMTime(pack.id); if (pack.mtime !== mtime_) { didUpdate = true; return { id: pack.id, source: readFile(pack.id), mtime: mtime_ }; } else { return pack; } }); return didUpdate ? updated : packs; }
javascript
function updatePacks(packs) { var didUpdate = false; var updated = packs.map(function(pack) { var mtime_ = readMTime(pack.id); if (pack.mtime !== mtime_) { didUpdate = true; return { id: pack.id, source: readFile(pack.id), mtime: mtime_ }; } else { return pack; } }); return didUpdate ? updated : packs; }
[ "function", "updatePacks", "(", "packs", ")", "{", "var", "didUpdate", "=", "false", ";", "var", "updated", "=", "packs", ".", "map", "(", "function", "(", "pack", ")", "{", "var", "mtime_", "=", "readMTime", "(", "pack", ".", "id", ")", ";", "if", "(", "pack", ".", "mtime", "!==", "mtime_", ")", "{", "didUpdate", "=", "true", ";", "return", "{", "id", ":", "pack", ".", "id", ",", "source", ":", "readFile", "(", "pack", ".", "id", ")", ",", "mtime", ":", "mtime_", "}", ";", "}", "else", "{", "return", "pack", ";", "}", "}", ")", ";", "return", "didUpdate", "?", "updated", ":", "packs", ";", "}" ]
Updated the "packs" if the mtime has changed
[ "Updated", "the", "packs", "if", "the", "mtime", "has", "changed" ]
c97b6168a56fc4a52f77242526dcd6a6cba3d6e5
https://github.com/zertosh/pollen/blob/c97b6168a56fc4a52f77242526dcd6a6cba3d6e5/BundlesModule.js#L143-L159
49,099
zertosh/pollen
BundlesModule.js
stitch
function stitch(name, packs) { var content = ';(function(require){\n'; packs.forEach(function(pack) { content += removeSourceMaps(pack.source); if (content[content.length-1] !== '\n') content += '\n'; }); content += '\nreturn require;}());\n'; return content; }
javascript
function stitch(name, packs) { var content = ';(function(require){\n'; packs.forEach(function(pack) { content += removeSourceMaps(pack.source); if (content[content.length-1] !== '\n') content += '\n'; }); content += '\nreturn require;}());\n'; return content; }
[ "function", "stitch", "(", "name", ",", "packs", ")", "{", "var", "content", "=", "';(function(require){\\n'", ";", "packs", ".", "forEach", "(", "function", "(", "pack", ")", "{", "content", "+=", "removeSourceMaps", "(", "pack", ".", "source", ")", ";", "if", "(", "content", "[", "content", ".", "length", "-", "1", "]", "!==", "'\\n'", ")", "content", "+=", "'\\n'", ";", "}", ")", ";", "content", "+=", "'\\nreturn require;}());\\n'", ";", "return", "content", ";", "}" ]
Turn the source from the "packs" into a single module to be run, while preserving the source maps. This assumes that the Browserify bundles included all expose whatever they need to via a `require` function. The bundle sources are wrapped in a function with it's own `require` variable so the Browserify one doesn't leak out into the global scope. TODO: Sourcemaps @param {string} name @param {packs} packs @return {string}
[ "Turn", "the", "source", "from", "the", "packs", "into", "a", "single", "module", "to", "be", "run", "while", "preserving", "the", "source", "maps", "." ]
c97b6168a56fc4a52f77242526dcd6a6cba3d6e5
https://github.com/zertosh/pollen/blob/c97b6168a56fc4a52f77242526dcd6a6cba3d6e5/BundlesModule.js#L176-L184