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
partition
stringclasses
1 value
FlorinDavid/node-math-precision
index.js
function(number, precision) { const multiplier = !!precision ? Math.pow(10, precision) : 1; return Math.round(number * multiplier) / multiplier; }
javascript
function(number, precision) { const multiplier = !!precision ? Math.pow(10, precision) : 1; return Math.round(number * multiplier) / multiplier; }
[ "function", "(", "number", ",", "precision", ")", "{", "const", "multiplier", "=", "!", "!", "precision", "?", "Math", ".", "pow", "(", "10", ",", "precision", ")", ":", "1", ";", "return", "Math", ".", "round", "(", "number", "*", "multiplier", ")", "/", "multiplier", ";", "}" ]
Math.round with 'precision' parameter @param {number} number @param {number} precision @return {number}
[ "Math", ".", "round", "with", "precision", "parameter" ]
d12af7a9a3044343145902b09bcf0a20225da3e2
https://github.com/FlorinDavid/node-math-precision/blob/d12af7a9a3044343145902b09bcf0a20225da3e2/index.js#L12-L17
train
FlorinDavid/node-math-precision
index.js
function(number, precision) { const multiplier = !!precision ? Math.pow(10, precision) : 1; return Math.ceil(number * multiplier) / multiplier; }
javascript
function(number, precision) { const multiplier = !!precision ? Math.pow(10, precision) : 1; return Math.ceil(number * multiplier) / multiplier; }
[ "function", "(", "number", ",", "precision", ")", "{", "const", "multiplier", "=", "!", "!", "precision", "?", "Math", ".", "pow", "(", "10", ",", "precision", ")", ":", "1", ";", "return", "Math", ".", "ceil", "(", "number", "*", "multiplier", ")", "/", "multiplier", ";", "}" ]
Math.ceil with 'precision' parameter @param {number} number @param {number} precision @return {number}
[ "Math", ".", "ceil", "with", "precision", "parameter" ]
d12af7a9a3044343145902b09bcf0a20225da3e2
https://github.com/FlorinDavid/node-math-precision/blob/d12af7a9a3044343145902b09bcf0a20225da3e2/index.js#L27-L32
train
FlorinDavid/node-math-precision
index.js
function(number, precision) { const multiplier = !!precision ? Math.pow(10, precision) : 1; return Math.floor(number * multiplier) / multiplier; }
javascript
function(number, precision) { const multiplier = !!precision ? Math.pow(10, precision) : 1; return Math.floor(number * multiplier) / multiplier; }
[ "function", "(", "number", ",", "precision", ")", "{", "const", "multiplier", "=", "!", "!", "precision", "?", "Math", ".", "pow", "(", "10", ",", "precision", ")", ":", "1", ";", "return", "Math", ".", "floor", "(", "number", "*", "multiplier", ")", "/", "multiplier", ";", "}" ]
Math.floor with 'precision' parameter @param {number} number @param {number} precision @return {number}
[ "Math", ".", "floor", "with", "precision", "parameter" ]
d12af7a9a3044343145902b09bcf0a20225da3e2
https://github.com/FlorinDavid/node-math-precision/blob/d12af7a9a3044343145902b09bcf0a20225da3e2/index.js#L42-L47
train
skerit/protoblast
lib/benchmark.js
getFunctionOverhead
function getFunctionOverhead(runs) { var result, dummy, start, i; // The dummy has to return something, // or it'll get insanely optimized dummy = Function('return 1'); // Call dummy now to get it jitted dummy(); start = Blast.performanceNow(); for (i = 0; i < runs; i++) { dummy(); } result = Blast.performanceNow() - start; // When doing coverage this can increase a lot, giving weird results if (result > 1) { result = 0.5; } return result; }
javascript
function getFunctionOverhead(runs) { var result, dummy, start, i; // The dummy has to return something, // or it'll get insanely optimized dummy = Function('return 1'); // Call dummy now to get it jitted dummy(); start = Blast.performanceNow(); for (i = 0; i < runs; i++) { dummy(); } result = Blast.performanceNow() - start; // When doing coverage this can increase a lot, giving weird results if (result > 1) { result = 0.5; } return result; }
[ "function", "getFunctionOverhead", "(", "runs", ")", "{", "var", "result", ",", "dummy", ",", "start", ",", "i", ";", "dummy", "=", "Function", "(", "'return 1'", ")", ";", "dummy", "(", ")", ";", "start", "=", "Blast", ".", "performanceNow", "(", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "runs", ";", "i", "++", ")", "{", "dummy", "(", ")", ";", "}", "result", "=", "Blast", ".", "performanceNow", "(", ")", "-", "start", ";", "if", "(", "result", ">", "1", ")", "{", "result", "=", "0.5", ";", "}", "return", "result", ";", "}" ]
This function determines the ms overhead cost of calling a function the given amount of time @author Jelle De Loecker <[email protected]> @since 0.1.2 @version 0.5.4 @param {Number} runs
[ "This", "function", "determines", "the", "ms", "overhead", "cost", "of", "calling", "a", "function", "the", "given", "amount", "of", "time" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/benchmark.js#L103-L131
train
skerit/protoblast
lib/benchmark.js
doSyncBench
function doSyncBench(fn, callback) { var start, fnOverhead, pretotal, result, runs, name; runs = 0; // For the initial test, to determine how many iterations we should // test later, we just use Date.now() start = Date.now(); // See how many times we can get it to run for 50ms // This doesn't need to be precise yet. We don't use these results // for the ops count because Date.now() takes time, too do { fn(); runs++; pretotal = Date.now() - start; } while (pretotal < 50); // See how long it takes to run an empty function fnOverhead = getFunctionOverhead(runs); result = syncTest(fn, runs, fnOverhead); if (callback) { result.name = fn.name || ''; callback(null, result); } else { name = fn.name || ''; if (name) name = 'for "' + name + '" '; console.log('Benchmark ' + name + 'did ' + Bound.Number.humanize(result.ops) + '/s (' + Bound.Number.humanize(result.iterations) + ' iterations)'); } return result; }
javascript
function doSyncBench(fn, callback) { var start, fnOverhead, pretotal, result, runs, name; runs = 0; // For the initial test, to determine how many iterations we should // test later, we just use Date.now() start = Date.now(); // See how many times we can get it to run for 50ms // This doesn't need to be precise yet. We don't use these results // for the ops count because Date.now() takes time, too do { fn(); runs++; pretotal = Date.now() - start; } while (pretotal < 50); // See how long it takes to run an empty function fnOverhead = getFunctionOverhead(runs); result = syncTest(fn, runs, fnOverhead); if (callback) { result.name = fn.name || ''; callback(null, result); } else { name = fn.name || ''; if (name) name = 'for "' + name + '" '; console.log('Benchmark ' + name + 'did ' + Bound.Number.humanize(result.ops) + '/s (' + Bound.Number.humanize(result.iterations) + ' iterations)'); } return result; }
[ "function", "doSyncBench", "(", "fn", ",", "callback", ")", "{", "var", "start", ",", "fnOverhead", ",", "pretotal", ",", "result", ",", "runs", ",", "name", ";", "runs", "=", "0", ";", "start", "=", "Date", ".", "now", "(", ")", ";", "do", "{", "fn", "(", ")", ";", "runs", "++", ";", "pretotal", "=", "Date", ".", "now", "(", ")", "-", "start", ";", "}", "while", "(", "pretotal", "<", "50", ")", ";", "fnOverhead", "=", "getFunctionOverhead", "(", "runs", ")", ";", "result", "=", "syncTest", "(", "fn", ",", "runs", ",", "fnOverhead", ")", ";", "if", "(", "callback", ")", "{", "result", ".", "name", "=", "fn", ".", "name", "||", "''", ";", "callback", "(", "null", ",", "result", ")", ";", "}", "else", "{", "name", "=", "fn", ".", "name", "||", "''", ";", "if", "(", "name", ")", "name", "=", "'for \"'", "+", "name", "+", "'\" '", ";", "console", ".", "log", "(", "'Benchmark '", "+", "name", "+", "'did '", "+", "Bound", ".", "Number", ".", "humanize", "(", "result", ".", "ops", ")", "+", "'/s ('", "+", "Bound", ".", "Number", ".", "humanize", "(", "result", ".", "iterations", ")", "+", "' iterations)'", ")", ";", "}", "return", "result", ";", "}" ]
Function that sets up the synchronous benchmark @author Jelle De Loecker <[email protected]> @since 0.1.2 @version 0.1.2 @param {Function} fn @param {Function} callback @return {Object}
[ "Function", "that", "sets", "up", "the", "synchronous", "benchmark" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/benchmark.js#L302-L342
train
skerit/protoblast
lib/benchmark.js
doAsyncBench
function doAsyncBench(fn, callback) { var fnOverhead, pretotal, result, args, i; if (benchRunning > 0) { // Keep function optimized by not leaking the `arguments` object args = new Array(arguments.length); for (i = 0; i < args.length; i++) args[i] = arguments[i]; benchQueue.push(args); return; } benchRunning++; // See how many times we can get it to run for 300ms Collection.Function.doTime(300, fn, function(err, runs, elapsed) { // See how the baseline latency is like Blast.getEventLatencyBaseline(function(err, median) { asyncTest(fn, runs, median+(getFunctionOverhead(runs)*8), function asyncDone(err, result) { var next, name; // Call the callback if (callback) { result.name = fn.name || ''; callback(err, result); } else { name = fn.name || ''; if (name) name = 'for "' + name + '" '; console.log('Benchmark ' + name + 'did ' + Bound.Number.humanize(result.ops) + '/s (' + Bound.Number.humanize(result.iterations) + ' iterations)'); } benchRunning--; // Schedule a next benchmark if (benchRunning == 0 && benchQueue.length > 0) { // Get the top of the queue next = benchQueue.shift(); Blast.setImmediate(function() { doAsyncBench.apply(null, next); }); } }); }); }); }
javascript
function doAsyncBench(fn, callback) { var fnOverhead, pretotal, result, args, i; if (benchRunning > 0) { // Keep function optimized by not leaking the `arguments` object args = new Array(arguments.length); for (i = 0; i < args.length; i++) args[i] = arguments[i]; benchQueue.push(args); return; } benchRunning++; // See how many times we can get it to run for 300ms Collection.Function.doTime(300, fn, function(err, runs, elapsed) { // See how the baseline latency is like Blast.getEventLatencyBaseline(function(err, median) { asyncTest(fn, runs, median+(getFunctionOverhead(runs)*8), function asyncDone(err, result) { var next, name; // Call the callback if (callback) { result.name = fn.name || ''; callback(err, result); } else { name = fn.name || ''; if (name) name = 'for "' + name + '" '; console.log('Benchmark ' + name + 'did ' + Bound.Number.humanize(result.ops) + '/s (' + Bound.Number.humanize(result.iterations) + ' iterations)'); } benchRunning--; // Schedule a next benchmark if (benchRunning == 0 && benchQueue.length > 0) { // Get the top of the queue next = benchQueue.shift(); Blast.setImmediate(function() { doAsyncBench.apply(null, next); }); } }); }); }); }
[ "function", "doAsyncBench", "(", "fn", ",", "callback", ")", "{", "var", "fnOverhead", ",", "pretotal", ",", "result", ",", "args", ",", "i", ";", "if", "(", "benchRunning", ">", "0", ")", "{", "args", "=", "new", "Array", "(", "arguments", ".", "length", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "args", ".", "length", ";", "i", "++", ")", "args", "[", "i", "]", "=", "arguments", "[", "i", "]", ";", "benchQueue", ".", "push", "(", "args", ")", ";", "return", ";", "}", "benchRunning", "++", ";", "Collection", ".", "Function", ".", "doTime", "(", "300", ",", "fn", ",", "function", "(", "err", ",", "runs", ",", "elapsed", ")", "{", "Blast", ".", "getEventLatencyBaseline", "(", "function", "(", "err", ",", "median", ")", "{", "asyncTest", "(", "fn", ",", "runs", ",", "median", "+", "(", "getFunctionOverhead", "(", "runs", ")", "*", "8", ")", ",", "function", "asyncDone", "(", "err", ",", "result", ")", "{", "var", "next", ",", "name", ";", "if", "(", "callback", ")", "{", "result", ".", "name", "=", "fn", ".", "name", "||", "''", ";", "callback", "(", "err", ",", "result", ")", ";", "}", "else", "{", "name", "=", "fn", ".", "name", "||", "''", ";", "if", "(", "name", ")", "name", "=", "'for \"'", "+", "name", "+", "'\" '", ";", "console", ".", "log", "(", "'Benchmark '", "+", "name", "+", "'did '", "+", "Bound", ".", "Number", ".", "humanize", "(", "result", ".", "ops", ")", "+", "'/s ('", "+", "Bound", ".", "Number", ".", "humanize", "(", "result", ".", "iterations", ")", "+", "' iterations)'", ")", ";", "}", "benchRunning", "--", ";", "if", "(", "benchRunning", "==", "0", "&&", "benchQueue", ".", "length", ">", "0", ")", "{", "next", "=", "benchQueue", ".", "shift", "(", ")", ";", "Blast", ".", "setImmediate", "(", "function", "(", ")", "{", "doAsyncBench", ".", "apply", "(", "null", ",", "next", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Function that sets up the asynchronous benchmark @author Jelle De Loecker <[email protected]> @since 0.1.2 @version 0.6.0 @param {Function} fn @param {Function} callback @return {Object}
[ "Function", "that", "sets", "up", "the", "asynchronous", "benchmark" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/benchmark.js#L359-L415
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/generators/statements.js
WhileStatement
function WhileStatement(node, print) { this.keyword("while"); this.push("("); print.plain(node.test); this.push(")"); print.block(node.body); }
javascript
function WhileStatement(node, print) { this.keyword("while"); this.push("("); print.plain(node.test); this.push(")"); print.block(node.body); }
[ "function", "WhileStatement", "(", "node", ",", "print", ")", "{", "this", ".", "keyword", "(", "\"while\"", ")", ";", "this", ".", "push", "(", "\"(\"", ")", ";", "print", ".", "plain", "(", "node", ".", "test", ")", ";", "this", ".", "push", "(", "\")\"", ")", ";", "print", ".", "block", "(", "node", ".", "body", ")", ";", "}" ]
Prints WhileStatement, prints test and body.
[ "Prints", "WhileStatement", "prints", "test", "and", "body", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/generators/statements.js#L99-L105
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/generators/statements.js
buildForXStatement
function buildForXStatement(op) { return function (node, print) { this.keyword("for"); this.push("("); print.plain(node.left); this.push(" " + op + " "); print.plain(node.right); this.push(")"); print.block(node.body); }; }
javascript
function buildForXStatement(op) { return function (node, print) { this.keyword("for"); this.push("("); print.plain(node.left); this.push(" " + op + " "); print.plain(node.right); this.push(")"); print.block(node.body); }; }
[ "function", "buildForXStatement", "(", "op", ")", "{", "return", "function", "(", "node", ",", "print", ")", "{", "this", ".", "keyword", "(", "\"for\"", ")", ";", "this", ".", "push", "(", "\"(\"", ")", ";", "print", ".", "plain", "(", "node", ".", "left", ")", ";", "this", ".", "push", "(", "\" \"", "+", "op", "+", "\" \"", ")", ";", "print", ".", "plain", "(", "node", ".", "right", ")", ";", "this", ".", "push", "(", "\")\"", ")", ";", "print", ".", "block", "(", "node", ".", "body", ")", ";", "}", ";", "}" ]
Builds ForIn or ForOf statement printers. Prints left, right, and body.
[ "Builds", "ForIn", "or", "ForOf", "statement", "printers", ".", "Prints", "left", "right", "and", "body", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/generators/statements.js#L112-L122
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/generators/statements.js
CatchClause
function CatchClause(node, print) { this.keyword("catch"); this.push("("); print.plain(node.param); this.push(") "); print.plain(node.body); }
javascript
function CatchClause(node, print) { this.keyword("catch"); this.push("("); print.plain(node.param); this.push(") "); print.plain(node.body); }
[ "function", "CatchClause", "(", "node", ",", "print", ")", "{", "this", ".", "keyword", "(", "\"catch\"", ")", ";", "this", ".", "push", "(", "\"(\"", ")", ";", "print", ".", "plain", "(", "node", ".", "param", ")", ";", "this", ".", "push", "(", "\") \"", ")", ";", "print", ".", "plain", "(", "node", ".", "body", ")", ";", "}" ]
Prints CatchClause, prints param and body.
[ "Prints", "CatchClause", "prints", "param", "and", "body", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/generators/statements.js#L222-L228
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/generators/statements.js
SwitchStatement
function SwitchStatement(node, print) { this.keyword("switch"); this.push("("); print.plain(node.discriminant); this.push(")"); this.space(); this.push("{"); print.sequence(node.cases, { indent: true, addNewlines: function addNewlines(leading, cas) { if (!leading && node.cases[node.cases.length - 1] === cas) return -1; } }); this.push("}"); }
javascript
function SwitchStatement(node, print) { this.keyword("switch"); this.push("("); print.plain(node.discriminant); this.push(")"); this.space(); this.push("{"); print.sequence(node.cases, { indent: true, addNewlines: function addNewlines(leading, cas) { if (!leading && node.cases[node.cases.length - 1] === cas) return -1; } }); this.push("}"); }
[ "function", "SwitchStatement", "(", "node", ",", "print", ")", "{", "this", ".", "keyword", "(", "\"switch\"", ")", ";", "this", ".", "push", "(", "\"(\"", ")", ";", "print", ".", "plain", "(", "node", ".", "discriminant", ")", ";", "this", ".", "push", "(", "\")\"", ")", ";", "this", ".", "space", "(", ")", ";", "this", ".", "push", "(", "\"{\"", ")", ";", "print", ".", "sequence", "(", "node", ".", "cases", ",", "{", "indent", ":", "true", ",", "addNewlines", ":", "function", "addNewlines", "(", "leading", ",", "cas", ")", "{", "if", "(", "!", "leading", "&&", "node", ".", "cases", "[", "node", ".", "cases", ".", "length", "-", "1", "]", "===", "cas", ")", "return", "-", "1", ";", "}", "}", ")", ";", "this", ".", "push", "(", "\"}\"", ")", ";", "}" ]
Prints SwitchStatement, prints discriminant and cases.
[ "Prints", "SwitchStatement", "prints", "discriminant", "and", "cases", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/generators/statements.js#L234-L250
train
EikosPartners/scalejs
dist/scalejs.base.object.js
has
function has(object) { // The intent of this method is to replace unsafe tests relying on type // coercion for optional arguments or obj properties: // | function on(event,options){ // | options = options || {}; // type coercion // | if (!event || !event.data || !event.data.value){ // | // unsafe due to type coercion: all falsy values '', false, 0 // | // are discarded, not just null and undefined // | return; // | } // | // ... // | } // with a safer test without type coercion: // | function on(event,options){ // | options = has(options)? options : {}; // no type coercion // | if (!has(event,'data','value'){ // | // safe check: only null/undefined values are rejected; // | return; // | } // | // ... // | } // // Returns: // * false if no argument is provided or if the obj is null or // undefined, whatever the number of arguments // * true if the full chain of nested properties is found in the obj // and the corresponding value is neither null nor undefined // * false otherwise var i, // iterative variable length, o = object, property; if (!is(o)) { return false; } for (i = 1, length = arguments.length; i < length; i += 1) { property = arguments[i]; o = o[property]; if (!is(o)) { return false; } } return true; }
javascript
function has(object) { // The intent of this method is to replace unsafe tests relying on type // coercion for optional arguments or obj properties: // | function on(event,options){ // | options = options || {}; // type coercion // | if (!event || !event.data || !event.data.value){ // | // unsafe due to type coercion: all falsy values '', false, 0 // | // are discarded, not just null and undefined // | return; // | } // | // ... // | } // with a safer test without type coercion: // | function on(event,options){ // | options = has(options)? options : {}; // no type coercion // | if (!has(event,'data','value'){ // | // safe check: only null/undefined values are rejected; // | return; // | } // | // ... // | } // // Returns: // * false if no argument is provided or if the obj is null or // undefined, whatever the number of arguments // * true if the full chain of nested properties is found in the obj // and the corresponding value is neither null nor undefined // * false otherwise var i, // iterative variable length, o = object, property; if (!is(o)) { return false; } for (i = 1, length = arguments.length; i < length; i += 1) { property = arguments[i]; o = o[property]; if (!is(o)) { return false; } } return true; }
[ "function", "has", "(", "object", ")", "{", "var", "i", ",", "length", ",", "o", "=", "object", ",", "property", ";", "if", "(", "!", "is", "(", "o", ")", ")", "{", "return", "false", ";", "}", "for", "(", "i", "=", "1", ",", "length", "=", "arguments", ".", "length", ";", "i", "<", "length", ";", "i", "+=", "1", ")", "{", "property", "=", "arguments", "[", "i", "]", ";", "o", "=", "o", "[", "property", "]", ";", "if", "(", "!", "is", "(", "o", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Determines if an object exists and if it does checks that each in the chain of properties also exist @param {Object|Any} obj object to test @param {String} [prop...] property chain of the object to test @memberOf object @return {Boolean} if the object 'has' (see inline documentation)
[ "Determines", "if", "an", "object", "exists", "and", "if", "it", "does", "checks", "that", "each", "in", "the", "chain", "of", "properties", "also", "exist" ]
115d0eac1a90aebb54f50485ed92de25165f9c30
https://github.com/EikosPartners/scalejs/blob/115d0eac1a90aebb54f50485ed92de25165f9c30/dist/scalejs.base.object.js#L33-L81
train
EikosPartners/scalejs
dist/scalejs.base.object.js
extend
function extend(receiver, extension, path) { var props = has(path) ? path.split('.') : [], target = receiver, i; // iterative variable for (i = 0; i < props.length; i += 1) { if (!has(target, props[i])) { target[props[i]] = {}; } target = target[props[i]]; } mix(target, extension); return target; }
javascript
function extend(receiver, extension, path) { var props = has(path) ? path.split('.') : [], target = receiver, i; // iterative variable for (i = 0; i < props.length; i += 1) { if (!has(target, props[i])) { target[props[i]] = {}; } target = target[props[i]]; } mix(target, extension); return target; }
[ "function", "extend", "(", "receiver", ",", "extension", ",", "path", ")", "{", "var", "props", "=", "has", "(", "path", ")", "?", "path", ".", "split", "(", "'.'", ")", ":", "[", "]", ",", "target", "=", "receiver", ",", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "props", ".", "length", ";", "i", "+=", "1", ")", "{", "if", "(", "!", "has", "(", "target", ",", "props", "[", "i", "]", ")", ")", "{", "target", "[", "props", "[", "i", "]", "]", "=", "{", "}", ";", "}", "target", "=", "target", "[", "props", "[", "i", "]", "]", ";", "}", "mix", "(", "target", ",", "extension", ")", ";", "return", "target", ";", "}" ]
Extends the extension into the reciever @param {Object} reciever object into which to extend @param {Object} extension object from which to extend @param {String} [path] followed on the reciever before executing the extend (form: "obj.obj.obj") @memberOf object @return the extended object (after having followed the path)
[ "Extends", "the", "extension", "into", "the", "reciever" ]
115d0eac1a90aebb54f50485ed92de25165f9c30
https://github.com/EikosPartners/scalejs/blob/115d0eac1a90aebb54f50485ed92de25165f9c30/dist/scalejs.base.object.js#L149-L164
train
EikosPartners/scalejs
dist/scalejs.base.object.js
get
function get(o, path, defaultValue) { var props = path.split('.'), i, // iterative variable p, // current property success = true; for (i = 0; i < props.length; i += 1) { p = props[i]; if (has(o, p)) { o = o[p]; } else { success = false; break; } } return success ? o : defaultValue; }
javascript
function get(o, path, defaultValue) { var props = path.split('.'), i, // iterative variable p, // current property success = true; for (i = 0; i < props.length; i += 1) { p = props[i]; if (has(o, p)) { o = o[p]; } else { success = false; break; } } return success ? o : defaultValue; }
[ "function", "get", "(", "o", ",", "path", ",", "defaultValue", ")", "{", "var", "props", "=", "path", ".", "split", "(", "'.'", ")", ",", "i", ",", "p", ",", "success", "=", "true", ";", "for", "(", "i", "=", "0", ";", "i", "<", "props", ".", "length", ";", "i", "+=", "1", ")", "{", "p", "=", "props", "[", "i", "]", ";", "if", "(", "has", "(", "o", ",", "p", ")", ")", "{", "o", "=", "o", "[", "p", "]", ";", "}", "else", "{", "success", "=", "false", ";", "break", ";", "}", "}", "return", "success", "?", "o", ":", "defaultValue", ";", "}" ]
Obtains a value from an object following a path with the option to return a default value if that object was not found @param {Object} o object in which to look for the specified path @param {String} path string representing the chain of properties to to be followed (form: "obj.obj.obj") @param {Any} [defaultValue] value to return if the path does not evaluate successfully: default undefined @memberOf object @return {Any} object evaluated by following the given path or the default value should that object not exist
[ "Obtains", "a", "value", "from", "an", "object", "following", "a", "path", "with", "the", "option", "to", "return", "a", "default", "value", "if", "that", "object", "was", "not", "found" ]
115d0eac1a90aebb54f50485ed92de25165f9c30
https://github.com/EikosPartners/scalejs/blob/115d0eac1a90aebb54f50485ed92de25165f9c30/dist/scalejs.base.object.js#L179-L198
train
EikosPartners/scalejs
dist/scalejs.base.object.js
stringify
function stringify(obj) { var cache = []; return JSON.stringify(obj, function (key, value) { if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value !== null) { if (cache.indexOf(value) !== -1) { return '[Circular]'; } cache.push(value); } return value; }); }
javascript
function stringify(obj) { var cache = []; return JSON.stringify(obj, function (key, value) { if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value !== null) { if (cache.indexOf(value) !== -1) { return '[Circular]'; } cache.push(value); } return value; }); }
[ "function", "stringify", "(", "obj", ")", "{", "var", "cache", "=", "[", "]", ";", "return", "JSON", ".", "stringify", "(", "obj", ",", "function", "(", "key", ",", "value", ")", "{", "if", "(", "(", "typeof", "value", "===", "'undefined'", "?", "'undefined'", ":", "_typeof", "(", "value", ")", ")", "===", "'object'", "&&", "value", "!==", "null", ")", "{", "if", "(", "cache", ".", "indexOf", "(", "value", ")", "!==", "-", "1", ")", "{", "return", "'[Circular]'", ";", "}", "cache", ".", "push", "(", "value", ")", ";", "}", "return", "value", ";", "}", ")", ";", "}" ]
Stringifies an object without the chance for circular error @param {Object} obj object to stringify @memberOf object @return {String} string form of the passed object
[ "Stringifies", "an", "object", "without", "the", "chance", "for", "circular", "error" ]
115d0eac1a90aebb54f50485ed92de25165f9c30
https://github.com/EikosPartners/scalejs/blob/115d0eac1a90aebb54f50485ed92de25165f9c30/dist/scalejs.base.object.js#L219-L231
train
SuperheroUI/shCore
src/util/get-class-names.js
getClassNames
function getClassNames(classObject) { var classNames = []; for (var key in classObject) { if (classObject.hasOwnProperty(key)) { let check = classObject[key]; let className = _.kebabCase(key); if (_.isFunction(check)) { if (check()) { classNames.push(className); } } else if (_.isString(check)) { if (className === 'include' || _.includes(check, ' ')) { classNames = _.concat(classNames, check.split(' ')); } else { classNames.push(className + '-' + _.kebabCase(check)); } } else if (check) { classNames.push(className); } } } classNames = _.uniq(classNames); return classNames.join(' '); }
javascript
function getClassNames(classObject) { var classNames = []; for (var key in classObject) { if (classObject.hasOwnProperty(key)) { let check = classObject[key]; let className = _.kebabCase(key); if (_.isFunction(check)) { if (check()) { classNames.push(className); } } else if (_.isString(check)) { if (className === 'include' || _.includes(check, ' ')) { classNames = _.concat(classNames, check.split(' ')); } else { classNames.push(className + '-' + _.kebabCase(check)); } } else if (check) { classNames.push(className); } } } classNames = _.uniq(classNames); return classNames.join(' '); }
[ "function", "getClassNames", "(", "classObject", ")", "{", "var", "classNames", "=", "[", "]", ";", "for", "(", "var", "key", "in", "classObject", ")", "{", "if", "(", "classObject", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "let", "check", "=", "classObject", "[", "key", "]", ";", "let", "className", "=", "_", ".", "kebabCase", "(", "key", ")", ";", "if", "(", "_", ".", "isFunction", "(", "check", ")", ")", "{", "if", "(", "check", "(", ")", ")", "{", "classNames", ".", "push", "(", "className", ")", ";", "}", "}", "else", "if", "(", "_", ".", "isString", "(", "check", ")", ")", "{", "if", "(", "className", "===", "'include'", "||", "_", ".", "includes", "(", "check", ",", "' '", ")", ")", "{", "classNames", "=", "_", ".", "concat", "(", "classNames", ",", "check", ".", "split", "(", "' '", ")", ")", ";", "}", "else", "{", "classNames", ".", "push", "(", "className", "+", "'-'", "+", "_", ".", "kebabCase", "(", "check", ")", ")", ";", "}", "}", "else", "if", "(", "check", ")", "{", "classNames", ".", "push", "(", "className", ")", ";", "}", "}", "}", "classNames", "=", "_", ".", "uniq", "(", "classNames", ")", ";", "return", "classNames", ".", "join", "(", "' '", ")", ";", "}" ]
Get a string of classNames from the object passed in. Uses the keys for class names and only adds them if the value is true. Value of keys can be boolean, function, or strings. Functions are evaluated on call. Strings are appended to end of key. @param {object} classObject Object containing keys of class names. @returns {string}
[ "Get", "a", "string", "of", "classNames", "from", "the", "object", "passed", "in", ".", "Uses", "the", "keys", "for", "class", "names", "and", "only", "adds", "them", "if", "the", "value", "is", "true", ".", "Value", "of", "keys", "can", "be", "boolean", "function", "or", "strings", ".", "Functions", "are", "evaluated", "on", "call", ".", "Strings", "are", "appended", "to", "end", "of", "key", "." ]
d92e2094a00e1148a5790cd928af70428524fb34
https://github.com/SuperheroUI/shCore/blob/d92e2094a00e1148a5790cd928af70428524fb34/src/util/get-class-names.js#L9-L35
train
dreampiggy/functional.js
Retroactive/lib/data_structures/double_linked_list.js
function (data){ //create a new item object, place data in var node = { data: data, next: null, prev: null }; //special case: no items in the list yet if (this._length == 0) { this._head = node; this._tail = node; } else { //attach to the tail node this._tail.next = node; node.prev = this._tail; this._tail = node; } //don't forget to update the count this._length++; }
javascript
function (data){ //create a new item object, place data in var node = { data: data, next: null, prev: null }; //special case: no items in the list yet if (this._length == 0) { this._head = node; this._tail = node; } else { //attach to the tail node this._tail.next = node; node.prev = this._tail; this._tail = node; } //don't forget to update the count this._length++; }
[ "function", "(", "data", ")", "{", "var", "node", "=", "{", "data", ":", "data", ",", "next", ":", "null", ",", "prev", ":", "null", "}", ";", "if", "(", "this", ".", "_length", "==", "0", ")", "{", "this", ".", "_head", "=", "node", ";", "this", ".", "_tail", "=", "node", ";", "}", "else", "{", "this", ".", "_tail", ".", "next", "=", "node", ";", "node", ".", "prev", "=", "this", ".", "_tail", ";", "this", ".", "_tail", "=", "node", ";", "}", "this", ".", "_length", "++", ";", "}" ]
Appends some data to the end of the list. This method traverses the existing list and places the value at the end in a new item. @param {variant} data The data to add to the list. @return {Void} @method add
[ "Appends", "some", "data", "to", "the", "end", "of", "the", "list", ".", "This", "method", "traverses", "the", "existing", "list", "and", "places", "the", "value", "at", "the", "end", "in", "a", "new", "item", "." ]
ec7b7213de7965659a8a1e8fa61438e3ae564260
https://github.com/dreampiggy/functional.js/blob/ec7b7213de7965659a8a1e8fa61438e3ae564260/Retroactive/lib/data_structures/double_linked_list.js#L40-L64
train
dreampiggy/functional.js
Retroactive/lib/data_structures/double_linked_list.js
function(index){ //check for out-of-bounds values if (index > -1 && index < this._length){ var current = this._head, i = 0; while(i++ < index){ current = current.next; } return current.data; } else { return null; } }
javascript
function(index){ //check for out-of-bounds values if (index > -1 && index < this._length){ var current = this._head, i = 0; while(i++ < index){ current = current.next; } return current.data; } else { return null; } }
[ "function", "(", "index", ")", "{", "if", "(", "index", ">", "-", "1", "&&", "index", "<", "this", ".", "_length", ")", "{", "var", "current", "=", "this", ".", "_head", ",", "i", "=", "0", ";", "while", "(", "i", "++", "<", "index", ")", "{", "current", "=", "current", ".", "next", ";", "}", "return", "current", ".", "data", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Retrieves the data in the given position in the list. @param {int} index The zero-based index of the item whose value should be returned. @return {variant} The value in the "data" portion of the given item or null if the item doesn't exist. @method item
[ "Retrieves", "the", "data", "in", "the", "given", "position", "in", "the", "list", "." ]
ec7b7213de7965659a8a1e8fa61438e3ae564260
https://github.com/dreampiggy/functional.js/blob/ec7b7213de7965659a8a1e8fa61438e3ae564260/Retroactive/lib/data_structures/double_linked_list.js#L74-L89
train
dreampiggy/functional.js
Retroactive/lib/data_structures/double_linked_list.js
function(start, end){ //subQueue to Array if(start >= 0 && start < end && end <= this._length) { var result = [], current = this._head, i = 0; while(i++ < start) { current = current.next; } while(start++ < end) { var value = current.data.value; if(value != null) { result.push(current.data.value); } current = current.next; } return result; } var result = [], current = this._head; while(current){ result.push(current.data); current = current.next; } return result; }
javascript
function(start, end){ //subQueue to Array if(start >= 0 && start < end && end <= this._length) { var result = [], current = this._head, i = 0; while(i++ < start) { current = current.next; } while(start++ < end) { var value = current.data.value; if(value != null) { result.push(current.data.value); } current = current.next; } return result; } var result = [], current = this._head; while(current){ result.push(current.data); current = current.next; } return result; }
[ "function", "(", "start", ",", "end", ")", "{", "if", "(", "start", ">=", "0", "&&", "start", "<", "end", "&&", "end", "<=", "this", ".", "_length", ")", "{", "var", "result", "=", "[", "]", ",", "current", "=", "this", ".", "_head", ",", "i", "=", "0", ";", "while", "(", "i", "++", "<", "start", ")", "{", "current", "=", "current", ".", "next", ";", "}", "while", "(", "start", "++", "<", "end", ")", "{", "var", "value", "=", "current", ".", "data", ".", "value", ";", "if", "(", "value", "!=", "null", ")", "{", "result", ".", "push", "(", "current", ".", "data", ".", "value", ")", ";", "}", "current", "=", "current", ".", "next", ";", "}", "return", "result", ";", "}", "var", "result", "=", "[", "]", ",", "current", "=", "this", ".", "_head", ";", "while", "(", "current", ")", "{", "result", ".", "push", "(", "current", ".", "data", ")", ";", "current", "=", "current", ".", "next", ";", "}", "return", "result", ";", "}" ]
Converts the list into an array. @return {Array} An array containing all of the data in the list. @method toArray
[ "Converts", "the", "list", "into", "an", "array", "." ]
ec7b7213de7965659a8a1e8fa61438e3ae564260
https://github.com/dreampiggy/functional.js/blob/ec7b7213de7965659a8a1e8fa61438e3ae564260/Retroactive/lib/data_structures/double_linked_list.js#L167-L197
train
noderaider/repackage
jspm_packages/system-polyfills.src.js
formatError
function formatError(e) { var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e); return e instanceof Error ? s : s + ' (WARNING: non-Error used)'; }
javascript
function formatError(e) { var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e); return e instanceof Error ? s : s + ' (WARNING: non-Error used)'; }
[ "function", "formatError", "(", "e", ")", "{", "var", "s", "=", "typeof", "e", "===", "'object'", "&&", "e", "!==", "null", "&&", "(", "e", ".", "stack", "||", "e", ".", "message", ")", "?", "e", ".", "stack", "||", "e", ".", "message", ":", "formatObject", "(", "e", ")", ";", "return", "e", "instanceof", "Error", "?", "s", ":", "s", "+", "' (WARNING: non-Error used)'", ";", "}" ]
Format an error into a string. If e is an Error and has a stack property, it's returned. Otherwise, e is formatted using formatObject, with a warning added about e not being a proper Error. @param {*} e @returns {String} formatted string, suitable for output to developers
[ "Format", "an", "error", "into", "a", "string", ".", "If", "e", "is", "an", "Error", "and", "has", "a", "stack", "property", "it", "s", "returned", ".", "Otherwise", "e", "is", "formatted", "using", "formatObject", "with", "a", "warning", "added", "about", "e", "not", "being", "a", "proper", "Error", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-polyfills.src.js#L306-L309
train
noderaider/repackage
jspm_packages/system-polyfills.src.js
formatObject
function formatObject(o) { var s = String(o); if(s === '[object Object]' && typeof JSON !== 'undefined') { s = tryStringify(o, s); } return s; }
javascript
function formatObject(o) { var s = String(o); if(s === '[object Object]' && typeof JSON !== 'undefined') { s = tryStringify(o, s); } return s; }
[ "function", "formatObject", "(", "o", ")", "{", "var", "s", "=", "String", "(", "o", ")", ";", "if", "(", "s", "===", "'[object Object]'", "&&", "typeof", "JSON", "!==", "'undefined'", ")", "{", "s", "=", "tryStringify", "(", "o", ",", "s", ")", ";", "}", "return", "s", ";", "}" ]
Format an object, detecting "plain" objects and running them through JSON.stringify if possible. @param {Object} o @returns {string}
[ "Format", "an", "object", "detecting", "plain", "objects", "and", "running", "them", "through", "JSON", ".", "stringify", "if", "possible", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-polyfills.src.js#L317-L323
train
noderaider/repackage
jspm_packages/system-polyfills.src.js
init
function init(resolver) { var handler = new Pending(); try { resolver(promiseResolve, promiseReject, promiseNotify); } catch (e) { promiseReject(e); } return handler; /** * Transition from pre-resolution state to post-resolution state, notifying * all listeners of the ultimate fulfillment or rejection * @param {*} x resolution value */ function promiseResolve (x) { handler.resolve(x); } /** * Reject this promise with reason, which will be used verbatim * @param {Error|*} reason rejection reason, strongly suggested * to be an Error type */ function promiseReject (reason) { handler.reject(reason); } /** * @deprecated * Issue a progress event, notifying all progress listeners * @param {*} x progress event payload to pass to all listeners */ function promiseNotify (x) { handler.notify(x); } }
javascript
function init(resolver) { var handler = new Pending(); try { resolver(promiseResolve, promiseReject, promiseNotify); } catch (e) { promiseReject(e); } return handler; /** * Transition from pre-resolution state to post-resolution state, notifying * all listeners of the ultimate fulfillment or rejection * @param {*} x resolution value */ function promiseResolve (x) { handler.resolve(x); } /** * Reject this promise with reason, which will be used verbatim * @param {Error|*} reason rejection reason, strongly suggested * to be an Error type */ function promiseReject (reason) { handler.reject(reason); } /** * @deprecated * Issue a progress event, notifying all progress listeners * @param {*} x progress event payload to pass to all listeners */ function promiseNotify (x) { handler.notify(x); } }
[ "function", "init", "(", "resolver", ")", "{", "var", "handler", "=", "new", "Pending", "(", ")", ";", "try", "{", "resolver", "(", "promiseResolve", ",", "promiseReject", ",", "promiseNotify", ")", ";", "}", "catch", "(", "e", ")", "{", "promiseReject", "(", "e", ")", ";", "}", "return", "handler", ";", "function", "promiseResolve", "(", "x", ")", "{", "handler", ".", "resolve", "(", "x", ")", ";", "}", "function", "promiseReject", "(", "reason", ")", "{", "handler", ".", "reject", "(", "reason", ")", ";", "}", "function", "promiseNotify", "(", "x", ")", "{", "handler", ".", "notify", "(", "x", ")", ";", "}", "}" ]
Run the supplied resolver @param resolver @returns {Pending}
[ "Run", "the", "supplied", "resolver" ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-polyfills.src.js#L378-L414
train
noderaider/repackage
jspm_packages/system-polyfills.src.js
resolve
function resolve(x) { return isPromise(x) ? x : new Promise(Handler, new Async(getHandler(x))); }
javascript
function resolve(x) { return isPromise(x) ? x : new Promise(Handler, new Async(getHandler(x))); }
[ "function", "resolve", "(", "x", ")", "{", "return", "isPromise", "(", "x", ")", "?", "x", ":", "new", "Promise", "(", "Handler", ",", "new", "Async", "(", "getHandler", "(", "x", ")", ")", ")", ";", "}" ]
Returns a trusted promise. If x is already a trusted promise, it is returned, otherwise returns a new trusted Promise which follows x. @param {*} x @return {Promise} promise
[ "Returns", "a", "trusted", "promise", ".", "If", "x", "is", "already", "a", "trusted", "promise", "it", "is", "returned", "otherwise", "returns", "a", "new", "trusted", "Promise", "which", "follows", "x", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-polyfills.src.js#L431-L434
train
noderaider/repackage
jspm_packages/system-polyfills.src.js
race
function race(promises) { if(typeof promises !== 'object' || promises === null) { return reject(new TypeError('non-iterable passed to race()')); } // Sigh, race([]) is untestable unless we return *something* // that is recognizable without calling .then() on it. return promises.length === 0 ? never() : promises.length === 1 ? resolve(promises[0]) : runRace(promises); }
javascript
function race(promises) { if(typeof promises !== 'object' || promises === null) { return reject(new TypeError('non-iterable passed to race()')); } // Sigh, race([]) is untestable unless we return *something* // that is recognizable without calling .then() on it. return promises.length === 0 ? never() : promises.length === 1 ? resolve(promises[0]) : runRace(promises); }
[ "function", "race", "(", "promises", ")", "{", "if", "(", "typeof", "promises", "!==", "'object'", "||", "promises", "===", "null", ")", "{", "return", "reject", "(", "new", "TypeError", "(", "'non-iterable passed to race()'", ")", ")", ";", "}", "return", "promises", ".", "length", "===", "0", "?", "never", "(", ")", ":", "promises", ".", "length", "===", "1", "?", "resolve", "(", "promises", "[", "0", "]", ")", ":", "runRace", "(", "promises", ")", ";", "}" ]
Fulfill-reject competitive race. Return a promise that will settle to the same state as the earliest input promise to settle. WARNING: The ES6 Promise spec requires that race()ing an empty array must return a promise that is pending forever. This implementation returns a singleton forever-pending promise, the same singleton that is returned by Promise.never(), thus can be checked with === @param {array} promises array of promises to race @returns {Promise} if input is non-empty, a promise that will settle to the same outcome as the earliest input promise to settle. if empty is empty, returns a promise that will never settle.
[ "Fulfill", "-", "reject", "competitive", "race", ".", "Return", "a", "promise", "that", "will", "settle", "to", "the", "same", "state", "as", "the", "earliest", "input", "promise", "to", "settle", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-polyfills.src.js#L634-L644
train
noderaider/repackage
jspm_packages/system-polyfills.src.js
getHandler
function getHandler(x) { if(isPromise(x)) { return x._handler.join(); } return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x); }
javascript
function getHandler(x) { if(isPromise(x)) { return x._handler.join(); } return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x); }
[ "function", "getHandler", "(", "x", ")", "{", "if", "(", "isPromise", "(", "x", ")", ")", "{", "return", "x", ".", "_handler", ".", "join", "(", ")", ";", "}", "return", "maybeThenable", "(", "x", ")", "?", "getHandlerUntrusted", "(", "x", ")", ":", "new", "Fulfilled", "(", "x", ")", ";", "}" ]
Promise internals Below this, everything is @private Get an appropriate handler for x, without checking for cycles @param {*} x @returns {object} handler
[ "Promise", "internals", "Below", "this", "everything", "is" ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-polyfills.src.js#L675-L680
train
noderaider/repackage
jspm_packages/system-polyfills.src.js
getHandlerUntrusted
function getHandlerUntrusted(x) { try { var untrustedThen = x.then; return typeof untrustedThen === 'function' ? new Thenable(untrustedThen, x) : new Fulfilled(x); } catch(e) { return new Rejected(e); } }
javascript
function getHandlerUntrusted(x) { try { var untrustedThen = x.then; return typeof untrustedThen === 'function' ? new Thenable(untrustedThen, x) : new Fulfilled(x); } catch(e) { return new Rejected(e); } }
[ "function", "getHandlerUntrusted", "(", "x", ")", "{", "try", "{", "var", "untrustedThen", "=", "x", ".", "then", ";", "return", "typeof", "untrustedThen", "===", "'function'", "?", "new", "Thenable", "(", "untrustedThen", ",", "x", ")", ":", "new", "Fulfilled", "(", "x", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "new", "Rejected", "(", "e", ")", ";", "}", "}" ]
Get a handler for potentially untrusted thenable x @param {*} x @returns {object} handler
[ "Get", "a", "handler", "for", "potentially", "untrusted", "thenable", "x" ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-polyfills.src.js#L697-L706
train
noderaider/repackage
jspm_packages/system-polyfills.src.js
Pending
function Pending(receiver, inheritedContext) { Promise.createContext(this, inheritedContext); this.consumers = void 0; this.receiver = receiver; this.handler = void 0; this.resolved = false; }
javascript
function Pending(receiver, inheritedContext) { Promise.createContext(this, inheritedContext); this.consumers = void 0; this.receiver = receiver; this.handler = void 0; this.resolved = false; }
[ "function", "Pending", "(", "receiver", ",", "inheritedContext", ")", "{", "Promise", ".", "createContext", "(", "this", ",", "inheritedContext", ")", ";", "this", ".", "consumers", "=", "void", "0", ";", "this", ".", "receiver", "=", "receiver", ";", "this", ".", "handler", "=", "void", "0", ";", "this", ".", "resolved", "=", "false", ";", "}" ]
Handler that manages a queue of consumers waiting on a pending promise @constructor
[ "Handler", "that", "manages", "a", "queue", "of", "consumers", "waiting", "on", "a", "pending", "promise" ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-polyfills.src.js#L777-L784
train
noderaider/repackage
jspm_packages/system-polyfills.src.js
Thenable
function Thenable(then, thenable) { Pending.call(this); tasks.enqueue(new AssimilateTask(then, thenable, this)); }
javascript
function Thenable(then, thenable) { Pending.call(this); tasks.enqueue(new AssimilateTask(then, thenable, this)); }
[ "function", "Thenable", "(", "then", ",", "thenable", ")", "{", "Pending", ".", "call", "(", "this", ")", ";", "tasks", ".", "enqueue", "(", "new", "AssimilateTask", "(", "then", ",", "thenable", ",", "this", ")", ")", ";", "}" ]
Handler that wraps an untrusted thenable and assimilates it in a future stack @param {function} then @param {{then: function}} thenable @constructor
[ "Handler", "that", "wraps", "an", "untrusted", "thenable", "and", "assimilates", "it", "in", "a", "future", "stack" ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-polyfills.src.js#L909-L912
train
noderaider/repackage
jspm_packages/system-polyfills.src.js
Rejected
function Rejected(x) { Promise.createContext(this); this.id = ++errorId; this.value = x; this.handled = false; this.reported = false; this._report(); }
javascript
function Rejected(x) { Promise.createContext(this); this.id = ++errorId; this.value = x; this.handled = false; this.reported = false; this._report(); }
[ "function", "Rejected", "(", "x", ")", "{", "Promise", ".", "createContext", "(", "this", ")", ";", "this", ".", "id", "=", "++", "errorId", ";", "this", ".", "value", "=", "x", ";", "this", ".", "handled", "=", "false", ";", "this", ".", "reported", "=", "false", ";", "this", ".", "_report", "(", ")", ";", "}" ]
Handler for a rejected promise @param {*} x rejection reason @constructor
[ "Handler", "for", "a", "rejected", "promise" ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-polyfills.src.js#L945-L954
train
noderaider/repackage
jspm_packages/system-polyfills.src.js
AssimilateTask
function AssimilateTask(then, thenable, resolver) { this._then = then; this.thenable = thenable; this.resolver = resolver; }
javascript
function AssimilateTask(then, thenable, resolver) { this._then = then; this.thenable = thenable; this.resolver = resolver; }
[ "function", "AssimilateTask", "(", "then", ",", "thenable", ",", "resolver", ")", "{", "this", ".", "_then", "=", "then", ";", "this", ".", "thenable", "=", "thenable", ";", "this", ".", "resolver", "=", "resolver", ";", "}" ]
Assimilate a thenable, sending it's value to resolver @param {function} then @param {object|function} thenable @param {object} resolver @constructor
[ "Assimilate", "a", "thenable", "sending", "it", "s", "value", "to", "resolver" ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-polyfills.src.js#L1076-L1080
train
noderaider/repackage
jspm_packages/system-polyfills.src.js
Fold
function Fold(f, z, c, to) { this.f = f; this.z = z; this.c = c; this.to = to; this.resolver = failIfRejected; this.receiver = this; }
javascript
function Fold(f, z, c, to) { this.f = f; this.z = z; this.c = c; this.to = to; this.resolver = failIfRejected; this.receiver = this; }
[ "function", "Fold", "(", "f", ",", "z", ",", "c", ",", "to", ")", "{", "this", ".", "f", "=", "f", ";", "this", ".", "z", "=", "z", ";", "this", ".", "c", "=", "c", ";", "this", ".", "to", "=", "to", ";", "this", ".", "resolver", "=", "failIfRejected", ";", "this", ".", "receiver", "=", "this", ";", "}" ]
Fold a handler value with z @constructor
[ "Fold", "a", "handler", "value", "with", "z" ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-polyfills.src.js#L1103-L1107
train
noderaider/repackage
jspm_packages/system-polyfills.src.js
tryCatchReject3
function tryCatchReject3(f, x, y, thisArg, next) { try { f.call(thisArg, x, y, next); } catch(e) { next.become(new Rejected(e)); } }
javascript
function tryCatchReject3(f, x, y, thisArg, next) { try { f.call(thisArg, x, y, next); } catch(e) { next.become(new Rejected(e)); } }
[ "function", "tryCatchReject3", "(", "f", ",", "x", ",", "y", ",", "thisArg", ",", "next", ")", "{", "try", "{", "f", ".", "call", "(", "thisArg", ",", "x", ",", "y", ",", "next", ")", ";", "}", "catch", "(", "e", ")", "{", "next", ".", "become", "(", "new", "Rejected", "(", "e", ")", ")", ";", "}", "}" ]
Same as above, but includes the extra argument parameter.
[ "Same", "as", "above", "but", "includes", "the", "extra", "argument", "parameter", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-polyfills.src.js#L1197-L1203
train
stackgl/gl-mat2
copy.js
copy
function copy(out, a) { out[0] = a[0] out[1] = a[1] out[2] = a[2] out[3] = a[3] return out }
javascript
function copy(out, a) { out[0] = a[0] out[1] = a[1] out[2] = a[2] out[3] = a[3] return out }
[ "function", "copy", "(", "out", ",", "a", ")", "{", "out", "[", "0", "]", "=", "a", "[", "0", "]", "out", "[", "1", "]", "=", "a", "[", "1", "]", "out", "[", "2", "]", "=", "a", "[", "2", "]", "out", "[", "3", "]", "=", "a", "[", "3", "]", "return", "out", "}" ]
Copy the values from one mat2 to another @alias mat2.copy @param {mat2} out the receiving matrix @param {mat2} a the source matrix @returns {mat2} out
[ "Copy", "the", "values", "from", "one", "mat2", "to", "another" ]
d6a04d55d605150240dc8e57ca7d2821aaa23c56
https://github.com/stackgl/gl-mat2/blob/d6a04d55d605150240dc8e57ca7d2821aaa23c56/copy.js#L11-L17
train
rm-rf-etc/encore
internal/e_controllers.js
RESTController
function RESTController(i,o,a,r){ var fn for (var j=0; j < RESTController.filters.length; j++) { fn = RESTController.filters[j] if (typeof fn === 'function') fn(i,o,a,r) } fn = RESTController[i.method.toLowerCase()] if (fn) fn(i,o,a,r) else r.error('404') }
javascript
function RESTController(i,o,a,r){ var fn for (var j=0; j < RESTController.filters.length; j++) { fn = RESTController.filters[j] if (typeof fn === 'function') fn(i,o,a,r) } fn = RESTController[i.method.toLowerCase()] if (fn) fn(i,o,a,r) else r.error('404') }
[ "function", "RESTController", "(", "i", ",", "o", ",", "a", ",", "r", ")", "{", "var", "fn", "for", "(", "var", "j", "=", "0", ";", "j", "<", "RESTController", ".", "filters", ".", "length", ";", "j", "++", ")", "{", "fn", "=", "RESTController", ".", "filters", "[", "j", "]", "if", "(", "typeof", "fn", "===", "'function'", ")", "fn", "(", "i", ",", "o", ",", "a", ",", "r", ")", "}", "fn", "=", "RESTController", "[", "i", ".", "method", ".", "toLowerCase", "(", ")", "]", "if", "(", "fn", ")", "fn", "(", "i", ",", "o", ",", "a", ",", "r", ")", "else", "r", ".", "error", "(", "'404'", ")", "}" ]
var self = this
[ "var", "self", "=", "this" ]
09262df0bd85dc3378c765d1d18e9621c248ccb4
https://github.com/rm-rf-etc/encore/blob/09262df0bd85dc3378c765d1d18e9621c248ccb4/internal/e_controllers.js#L5-L18
train
myelements/myelements.jquery
lib/client/myelements.jquery.js
function(element, options) { var $el = $(element); // React on every server/socket.io message. // If the element is defined with a data-react-on-event attribute // we take that as an eventType the user wants to be warned on this // element and we forward the event via jQuery events on $(this). this.initReactOnEveryMessage($el, options.reactOnMessage); // React on server message. // If the element is defined with a data-react-on-event attribute // we take that as an eventType the user wants to be warned on this // element and we forward the event via jQuery events on $(this). if (options.reactOnMessage) { this.initReactOnMessage($el, options.reactOnMessage); } // React on events originated from a data update in the backend // The user decides which object wants to be notified from with the // attribute data-react-on-dataupdate if (options.reactOnDataupdate) { this.initReactOnDataupdate($el, options.reactOnDataupdate); } if (options.reactOnUserinput) { // And make every form submit trigger the userinput message this.initReactOnUserInput($el, options.reactOnUserinput); } // react on routes updates using page.js // the attribute data-react-on-page holds the route // that is passed to page(...); if (options.onRoute) { this.initOnRoute($el, options.onRoute); } $myelements.attachDefaultEventHandlers(element); // Render first time. empty. passing data- attributes // as locals to the EJS engine. // TODO: Should load from localstorage. // Take the innerHTML as a template. $myelements.updateElementScope(element); // Init page routing using page.js // multiple calls to page() are ignored // so it's safe to callit on every element initialization page(); $(element).trigger("init"); }
javascript
function(element, options) { var $el = $(element); // React on every server/socket.io message. // If the element is defined with a data-react-on-event attribute // we take that as an eventType the user wants to be warned on this // element and we forward the event via jQuery events on $(this). this.initReactOnEveryMessage($el, options.reactOnMessage); // React on server message. // If the element is defined with a data-react-on-event attribute // we take that as an eventType the user wants to be warned on this // element and we forward the event via jQuery events on $(this). if (options.reactOnMessage) { this.initReactOnMessage($el, options.reactOnMessage); } // React on events originated from a data update in the backend // The user decides which object wants to be notified from with the // attribute data-react-on-dataupdate if (options.reactOnDataupdate) { this.initReactOnDataupdate($el, options.reactOnDataupdate); } if (options.reactOnUserinput) { // And make every form submit trigger the userinput message this.initReactOnUserInput($el, options.reactOnUserinput); } // react on routes updates using page.js // the attribute data-react-on-page holds the route // that is passed to page(...); if (options.onRoute) { this.initOnRoute($el, options.onRoute); } $myelements.attachDefaultEventHandlers(element); // Render first time. empty. passing data- attributes // as locals to the EJS engine. // TODO: Should load from localstorage. // Take the innerHTML as a template. $myelements.updateElementScope(element); // Init page routing using page.js // multiple calls to page() are ignored // so it's safe to callit on every element initialization page(); $(element).trigger("init"); }
[ "function", "(", "element", ",", "options", ")", "{", "var", "$el", "=", "$", "(", "element", ")", ";", "this", ".", "initReactOnEveryMessage", "(", "$el", ",", "options", ".", "reactOnMessage", ")", ";", "if", "(", "options", ".", "reactOnMessage", ")", "{", "this", ".", "initReactOnMessage", "(", "$el", ",", "options", ".", "reactOnMessage", ")", ";", "}", "if", "(", "options", ".", "reactOnDataupdate", ")", "{", "this", ".", "initReactOnDataupdate", "(", "$el", ",", "options", ".", "reactOnDataupdate", ")", ";", "}", "if", "(", "options", ".", "reactOnUserinput", ")", "{", "this", ".", "initReactOnUserInput", "(", "$el", ",", "options", ".", "reactOnUserinput", ")", ";", "}", "if", "(", "options", ".", "onRoute", ")", "{", "this", ".", "initOnRoute", "(", "$el", ",", "options", ".", "onRoute", ")", ";", "}", "$myelements", ".", "attachDefaultEventHandlers", "(", "element", ")", ";", "$myelements", ".", "updateElementScope", "(", "element", ")", ";", "page", "(", ")", ";", "$", "(", "element", ")", ".", "trigger", "(", "\"init\"", ")", ";", "}" ]
Initializes an element to give it the functionality provided by the myelements library @param {HTMLElement} element. the element to initialize @param {Object} options. options for initReactOnDataupdate, initReactOnUserInput and initReactOnMessage.
[ "Initializes", "an", "element", "to", "give", "it", "the", "functionality", "provided", "by", "the", "myelements", "library" ]
0123edec30fc70ea494611695b5b2593e4f23745
https://github.com/myelements/myelements.jquery/blob/0123edec30fc70ea494611695b5b2593e4f23745/lib/client/myelements.jquery.js#L111-L157
train
myelements/myelements.jquery
lib/client/myelements.jquery.js
function(el, data) { var dataupdateScope = $(el).data().reactOnDataupdate; var templateScope = $(el).data().templateScope; var userinputScope = $(el).data().reactOnUserinput; if (data) { $myelements.doRender(el, data); } else if (!data && templateScope) { $myelements.recoverTemplateScopeFromCache(el, templateScope); return; } else if (!data && dataupdateScope) { $myelements.recoverTemplateScopeFromCache(el, dataupdateScope); return; } else if (!data && userinputScope) { $myelements.recoverTemplateScopeFromCache(el, userinputScope); } }
javascript
function(el, data) { var dataupdateScope = $(el).data().reactOnDataupdate; var templateScope = $(el).data().templateScope; var userinputScope = $(el).data().reactOnUserinput; if (data) { $myelements.doRender(el, data); } else if (!data && templateScope) { $myelements.recoverTemplateScopeFromCache(el, templateScope); return; } else if (!data && dataupdateScope) { $myelements.recoverTemplateScopeFromCache(el, dataupdateScope); return; } else if (!data && userinputScope) { $myelements.recoverTemplateScopeFromCache(el, userinputScope); } }
[ "function", "(", "el", ",", "data", ")", "{", "var", "dataupdateScope", "=", "$", "(", "el", ")", ".", "data", "(", ")", ".", "reactOnDataupdate", ";", "var", "templateScope", "=", "$", "(", "el", ")", ".", "data", "(", ")", ".", "templateScope", ";", "var", "userinputScope", "=", "$", "(", "el", ")", ".", "data", "(", ")", ".", "reactOnUserinput", ";", "if", "(", "data", ")", "{", "$myelements", ".", "doRender", "(", "el", ",", "data", ")", ";", "}", "else", "if", "(", "!", "data", "&&", "templateScope", ")", "{", "$myelements", ".", "recoverTemplateScopeFromCache", "(", "el", ",", "templateScope", ")", ";", "return", ";", "}", "else", "if", "(", "!", "data", "&&", "dataupdateScope", ")", "{", "$myelements", ".", "recoverTemplateScopeFromCache", "(", "el", ",", "dataupdateScope", ")", ";", "return", ";", "}", "else", "if", "(", "!", "data", "&&", "userinputScope", ")", "{", "$myelements", ".", "recoverTemplateScopeFromCache", "(", "el", ",", "userinputScope", ")", ";", "}", "}" ]
Updates the data associated to an element trying to re-render the template associated to the element. with the values from 'data' as scope. If data is empty, it tries to load data for this element from browser storage (indexedDB/localStorage). @param {HTMLElement} el. The element the update affects. @param {Object} data. If not undefined, this object is used as the scope for rendering the innher html of the element as a template
[ "Updates", "the", "data", "associated", "to", "an", "element", "trying", "to", "re", "-", "render", "the", "template", "associated", "to", "the", "element", ".", "with", "the", "values", "from", "data", "as", "scope", "." ]
0123edec30fc70ea494611695b5b2593e4f23745
https://github.com/myelements/myelements.jquery/blob/0123edec30fc70ea494611695b5b2593e4f23745/lib/client/myelements.jquery.js#L170-L185
train
myelements/myelements.jquery
lib/client/myelements.jquery.js
function(el, scope) { var tplScopeObject = {}; $myelements.debug("Trying to update Element Scope without data from scope: %s", scope); // If no data is passed // we look up in localstorage $myelements.localDataForElement(el, scope, function onLocalDataForElement(err, data) { if (err) { // Maybe this is useless if there's no data to update. // If I don't do this, the element keeps its EJS tags untouched $myelements.debug("Updating element scope with empty object"); // Default to [] because it's an object and its iterable. // This way EJS templates cand use $().each to avoid 'undefined'errors data = []; } tplScopeObject[scope] = data; $myelements.doRender(el, tplScopeObject); }); }
javascript
function(el, scope) { var tplScopeObject = {}; $myelements.debug("Trying to update Element Scope without data from scope: %s", scope); // If no data is passed // we look up in localstorage $myelements.localDataForElement(el, scope, function onLocalDataForElement(err, data) { if (err) { // Maybe this is useless if there's no data to update. // If I don't do this, the element keeps its EJS tags untouched $myelements.debug("Updating element scope with empty object"); // Default to [] because it's an object and its iterable. // This way EJS templates cand use $().each to avoid 'undefined'errors data = []; } tplScopeObject[scope] = data; $myelements.doRender(el, tplScopeObject); }); }
[ "function", "(", "el", ",", "scope", ")", "{", "var", "tplScopeObject", "=", "{", "}", ";", "$myelements", ".", "debug", "(", "\"Trying to update Element Scope without data from scope: %s\"", ",", "scope", ")", ";", "$myelements", ".", "localDataForElement", "(", "el", ",", "scope", ",", "function", "onLocalDataForElement", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "$myelements", ".", "debug", "(", "\"Updating element scope with empty object\"", ")", ";", "data", "=", "[", "]", ";", "}", "tplScopeObject", "[", "scope", "]", "=", "data", ";", "$myelements", ".", "doRender", "(", "el", ",", "tplScopeObject", ")", ";", "}", ")", ";", "}" ]
Recovers and element's event scope from browser storage. @param {HTMLElement} el. The element you are trying to recover the scope from. @param {String} scope. The scope name to recover.
[ "Recovers", "and", "element", "s", "event", "scope", "from", "browser", "storage", "." ]
0123edec30fc70ea494611695b5b2593e4f23745
https://github.com/myelements/myelements.jquery/blob/0123edec30fc70ea494611695b5b2593e4f23745/lib/client/myelements.jquery.js#L192-L210
train
myelements/myelements.jquery
lib/client/myelements.jquery.js
function(el, data, done) { if (!el.template) { $myelements.debug("Creating EJS template from innerHTML for element: ", el); // Save the compiled template only once try { el.template = new EJS({ element: el }); } catch (e) { console.error("myelements.jquery: Error parsing element's innerHTML as an EJS template: ", e.toString(), "\nThis parsing error usually happens when there are syntax errors in your EJS code.", "\nThe elements that errored is ", el); el.template = undefined; return; } } try { // pass a locals variable as render scope` var html = el.template.render({ locals: data }); } catch (e) { console.error("myelements.jquery: Error rendering element's template: ", e.toString(), "\nThis rendering error usually happens when refering an undefined variable.", "\nThe elements that errored is ", el); return; } el.innerHTML = html; // $this.html(html); // Ensure every form in the element // is submitted via myelements. // Called after render because the original forms get dumped on render $myelements.handleFormSubmissions(el); if (typeof done === "function") { return done(html); } }
javascript
function(el, data, done) { if (!el.template) { $myelements.debug("Creating EJS template from innerHTML for element: ", el); // Save the compiled template only once try { el.template = new EJS({ element: el }); } catch (e) { console.error("myelements.jquery: Error parsing element's innerHTML as an EJS template: ", e.toString(), "\nThis parsing error usually happens when there are syntax errors in your EJS code.", "\nThe elements that errored is ", el); el.template = undefined; return; } } try { // pass a locals variable as render scope` var html = el.template.render({ locals: data }); } catch (e) { console.error("myelements.jquery: Error rendering element's template: ", e.toString(), "\nThis rendering error usually happens when refering an undefined variable.", "\nThe elements that errored is ", el); return; } el.innerHTML = html; // $this.html(html); // Ensure every form in the element // is submitted via myelements. // Called after render because the original forms get dumped on render $myelements.handleFormSubmissions(el); if (typeof done === "function") { return done(html); } }
[ "function", "(", "el", ",", "data", ",", "done", ")", "{", "if", "(", "!", "el", ".", "template", ")", "{", "$myelements", ".", "debug", "(", "\"Creating EJS template from innerHTML for element: \"", ",", "el", ")", ";", "try", "{", "el", ".", "template", "=", "new", "EJS", "(", "{", "element", ":", "el", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "\"myelements.jquery: Error parsing element's innerHTML as an EJS template: \"", ",", "e", ".", "toString", "(", ")", ",", "\"\\nThis parsing error usually happens when there are syntax errors in your EJS code.\"", ",", "\\n", ",", "\"\\nThe elements that errored is \"", ")", ";", "\\n", "el", "}", "}", "el", ".", "template", "=", "undefined", ";", "return", ";", "try", "{", "var", "html", "=", "el", ".", "template", ".", "render", "(", "{", "locals", ":", "data", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "\"myelements.jquery: Error rendering element's template: \"", ",", "e", ".", "toString", "(", ")", ",", "\"\\nThis rendering error usually happens when refering an undefined variable.\"", ",", "\\n", ",", "\"\\nThe elements that errored is \"", ")", ";", "\\n", "}", "el", "}" ]
Re render the element template. It saves it because on every render, the EJS tags get dumped, so we compile the template only once. @param {HTMLElement} el @param {Object} scope data to be passed to the EJS template render. @param {Function} done called when rendering is done - {Error} err. Null if nothing bad happened - {Jquery collection} $el. the element that was rendered. - {Object} data. scope data passed to doRender
[ "Re", "render", "the", "element", "template", ".", "It", "saves", "it", "because", "on", "every", "render", "the", "EJS", "tags", "get", "dumped", "so", "we", "compile", "the", "template", "only", "once", "." ]
0123edec30fc70ea494611695b5b2593e4f23745
https://github.com/myelements/myelements.jquery/blob/0123edec30fc70ea494611695b5b2593e4f23745/lib/client/myelements.jquery.js#L245-L284
train
myelements/myelements.jquery
lib/client/myelements.jquery.js
function(cb) { // If we're inside phonegap use its event. if (window.phonegap) { return document.addEventListener("offline", cb, false); } else if (window.addEventListener) { // With the offline HTML5 event from the window this.addLocalEventListener(window, "offline", cb); } else { /* Works in IE with the Work Offline option in the File menu and pulling the ethernet cable Ref: http://robertnyman.com/html5/offline/online-offline-events.html */ document.body.onoffline = cb; } }
javascript
function(cb) { // If we're inside phonegap use its event. if (window.phonegap) { return document.addEventListener("offline", cb, false); } else if (window.addEventListener) { // With the offline HTML5 event from the window this.addLocalEventListener(window, "offline", cb); } else { /* Works in IE with the Work Offline option in the File menu and pulling the ethernet cable Ref: http://robertnyman.com/html5/offline/online-offline-events.html */ document.body.onoffline = cb; } }
[ "function", "(", "cb", ")", "{", "if", "(", "window", ".", "phonegap", ")", "{", "return", "document", ".", "addEventListener", "(", "\"offline\"", ",", "cb", ",", "false", ")", ";", "}", "else", "if", "(", "window", ".", "addEventListener", ")", "{", "this", ".", "addLocalEventListener", "(", "window", ",", "\"offline\"", ",", "cb", ")", ";", "}", "else", "{", "document", ".", "body", ".", "onoffline", "=", "cb", ";", "}", "}" ]
Calls cb when the app is offline from the backend TODO: Find a kludge for this, for Firefox. Firefox only triggers offline when the user sets the browser to "Offline mode" @param {Function} cb.
[ "Calls", "cb", "when", "the", "app", "is", "offline", "from", "the", "backend" ]
0123edec30fc70ea494611695b5b2593e4f23745
https://github.com/myelements/myelements.jquery/blob/0123edec30fc70ea494611695b5b2593e4f23745/lib/client/myelements.jquery.js#L314-L329
train
myelements/myelements.jquery
lib/client/myelements.jquery.js
function($el) { // Reaction to socket.io messages $myelements.socket.on("message", function onMessage(message) { if ($el.data().templateScope === message.event) { // Update element scope (maybe re-render) var scope = {}; scope[message.event] = message.data; $myelements.updateElementScope($el.get(0), scope); } // we forward socket.io's message as a jQuery event on the $el. $myelements.debug("forwarding backend message '%s' as jQuery event '%s' to element %s with data: %j", message.event, message.event, $el.get(0), message.data); // Kludge: If jQuery's trigger received an array as second parameters // it assumes you're trying to send multiple parameters to the event handlers, // so we enclose message.data in another array if message.data is an array // sent from the backend if ($.isArray(message.data)) { $el.trigger(message.event, [message.data]); } else { $el.trigger(message.event, message.data); } }); // Reaction on local events triggered on the element by jQuery $el.on("message", function onElementMessageEvent(jQueryEvent, message) { if (message.event === undefined || message.data === undefined) { $myelements.debug("event key or data not present in second argument to trigger()", message.event, message.data); console.error("myelements.jquery: $.fn.trigger('message') must be called with an object having the keys 'event' and 'data' as second argument. "); return; } $myelements.debug("Sending message '%s' to backend with data: %j", message.event, message.data); $myelements.socket.send(message); }); }
javascript
function($el) { // Reaction to socket.io messages $myelements.socket.on("message", function onMessage(message) { if ($el.data().templateScope === message.event) { // Update element scope (maybe re-render) var scope = {}; scope[message.event] = message.data; $myelements.updateElementScope($el.get(0), scope); } // we forward socket.io's message as a jQuery event on the $el. $myelements.debug("forwarding backend message '%s' as jQuery event '%s' to element %s with data: %j", message.event, message.event, $el.get(0), message.data); // Kludge: If jQuery's trigger received an array as second parameters // it assumes you're trying to send multiple parameters to the event handlers, // so we enclose message.data in another array if message.data is an array // sent from the backend if ($.isArray(message.data)) { $el.trigger(message.event, [message.data]); } else { $el.trigger(message.event, message.data); } }); // Reaction on local events triggered on the element by jQuery $el.on("message", function onElementMessageEvent(jQueryEvent, message) { if (message.event === undefined || message.data === undefined) { $myelements.debug("event key or data not present in second argument to trigger()", message.event, message.data); console.error("myelements.jquery: $.fn.trigger('message') must be called with an object having the keys 'event' and 'data' as second argument. "); return; } $myelements.debug("Sending message '%s' to backend with data: %j", message.event, message.data); $myelements.socket.send(message); }); }
[ "function", "(", "$el", ")", "{", "$myelements", ".", "socket", ".", "on", "(", "\"message\"", ",", "function", "onMessage", "(", "message", ")", "{", "if", "(", "$el", ".", "data", "(", ")", ".", "templateScope", "===", "message", ".", "event", ")", "{", "var", "scope", "=", "{", "}", ";", "scope", "[", "message", ".", "event", "]", "=", "message", ".", "data", ";", "$myelements", ".", "updateElementScope", "(", "$el", ".", "get", "(", "0", ")", ",", "scope", ")", ";", "}", "$myelements", ".", "debug", "(", "\"forwarding backend message '%s' as jQuery event '%s' to element %s with data: %j\"", ",", "message", ".", "event", ",", "message", ".", "event", ",", "$el", ".", "get", "(", "0", ")", ",", "message", ".", "data", ")", ";", "if", "(", "$", ".", "isArray", "(", "message", ".", "data", ")", ")", "{", "$el", ".", "trigger", "(", "message", ".", "event", ",", "[", "message", ".", "data", "]", ")", ";", "}", "else", "{", "$el", ".", "trigger", "(", "message", ".", "event", ",", "message", ".", "data", ")", ";", "}", "}", ")", ";", "$el", ".", "on", "(", "\"message\"", ",", "function", "onElementMessageEvent", "(", "jQueryEvent", ",", "message", ")", "{", "if", "(", "message", ".", "event", "===", "undefined", "||", "message", ".", "data", "===", "undefined", ")", "{", "$myelements", ".", "debug", "(", "\"event key or data not present in second argument to trigger()\"", ",", "message", ".", "event", ",", "message", ".", "data", ")", ";", "console", ".", "error", "(", "\"myelements.jquery: $.fn.trigger('message') must be called with an object having the keys 'event' and 'data' as second argument. \"", ")", ";", "return", ";", "}", "$myelements", ".", "debug", "(", "\"Sending message '%s' to backend with data: %j\"", ",", "message", ".", "event", ",", "message", ".", "data", ")", ";", "$myelements", ".", "socket", ".", "send", "(", "message", ")", ";", "}", ")", ";", "}" ]
Prepares HTML elements for being able to receive socket.io's messages as jQuery events on the element
[ "Prepares", "HTML", "elements", "for", "being", "able", "to", "receive", "socket", ".", "io", "s", "messages", "as", "jQuery", "events", "on", "the", "element" ]
0123edec30fc70ea494611695b5b2593e4f23745
https://github.com/myelements/myelements.jquery/blob/0123edec30fc70ea494611695b5b2593e4f23745/lib/client/myelements.jquery.js#L433-L465
train
sonnym/node-elm-loader
src/index.js
execute
function execute() { var context = getDefaultContext(); var compiledOutput = fs.readFileSync(this.outputPath) vm.runInContext(compiledOutput, context, this.outputPath); var module = extractModule(this.moduleName, context); this.compiledModule = context.Elm.fullscreen(module, this.defaults); }
javascript
function execute() { var context = getDefaultContext(); var compiledOutput = fs.readFileSync(this.outputPath) vm.runInContext(compiledOutput, context, this.outputPath); var module = extractModule(this.moduleName, context); this.compiledModule = context.Elm.fullscreen(module, this.defaults); }
[ "function", "execute", "(", ")", "{", "var", "context", "=", "getDefaultContext", "(", ")", ";", "var", "compiledOutput", "=", "fs", ".", "readFileSync", "(", "this", ".", "outputPath", ")", "vm", ".", "runInContext", "(", "compiledOutput", ",", "context", ",", "this", ".", "outputPath", ")", ";", "var", "module", "=", "extractModule", "(", "this", ".", "moduleName", ",", "context", ")", ";", "this", ".", "compiledModule", "=", "context", ".", "Elm", ".", "fullscreen", "(", "module", ",", "this", ".", "defaults", ")", ";", "}" ]
execute script generated by elm-make in a vm context
[ "execute", "script", "generated", "by", "elm", "-", "make", "in", "a", "vm", "context" ]
e6a6fa4dd8c3352c65f338b6f2760b16687b760a
https://github.com/sonnym/node-elm-loader/blob/e6a6fa4dd8c3352c65f338b6f2760b16687b760a/src/index.js#L73-L82
train
sonnym/node-elm-loader
src/index.js
wrap
function wrap() { var ports = this.compiledModule.ports; var incomingEmitter = new EventEmitter(); var outgoingEmitter = new EventEmitter(); var emit = incomingEmitter.emit.bind(incomingEmitter); Object.keys(ports).forEach(function(key) { outgoingEmitter.addListener(key, function() { var args = Array.prototype.slice.call(arguments) ports[key].send.apply(ports[key], args); }); if (ports[key].subscribe) { ports[key].subscribe(function() { var args = Array.prototype.slice.call(arguments); args.unshift(key); emit.apply(incomingEmitter, args); }); } }); incomingEmitter.emit = outgoingEmitter.emit.bind(outgoingEmitter);; this.emitter = incomingEmitter; this.ports = this.compiledModule.ports; }
javascript
function wrap() { var ports = this.compiledModule.ports; var incomingEmitter = new EventEmitter(); var outgoingEmitter = new EventEmitter(); var emit = incomingEmitter.emit.bind(incomingEmitter); Object.keys(ports).forEach(function(key) { outgoingEmitter.addListener(key, function() { var args = Array.prototype.slice.call(arguments) ports[key].send.apply(ports[key], args); }); if (ports[key].subscribe) { ports[key].subscribe(function() { var args = Array.prototype.slice.call(arguments); args.unshift(key); emit.apply(incomingEmitter, args); }); } }); incomingEmitter.emit = outgoingEmitter.emit.bind(outgoingEmitter);; this.emitter = incomingEmitter; this.ports = this.compiledModule.ports; }
[ "function", "wrap", "(", ")", "{", "var", "ports", "=", "this", ".", "compiledModule", ".", "ports", ";", "var", "incomingEmitter", "=", "new", "EventEmitter", "(", ")", ";", "var", "outgoingEmitter", "=", "new", "EventEmitter", "(", ")", ";", "var", "emit", "=", "incomingEmitter", ".", "emit", ".", "bind", "(", "incomingEmitter", ")", ";", "Object", ".", "keys", "(", "ports", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "outgoingEmitter", ".", "addListener", "(", "key", ",", "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", "ports", "[", "key", "]", ".", "send", ".", "apply", "(", "ports", "[", "key", "]", ",", "args", ")", ";", "}", ")", ";", "if", "(", "ports", "[", "key", "]", ".", "subscribe", ")", "{", "ports", "[", "key", "]", ".", "subscribe", "(", "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "args", ".", "unshift", "(", "key", ")", ";", "emit", ".", "apply", "(", "incomingEmitter", ",", "args", ")", ";", "}", ")", ";", "}", "}", ")", ";", "incomingEmitter", ".", "emit", "=", "outgoingEmitter", ".", "emit", ".", "bind", "(", "outgoingEmitter", ")", ";", ";", "this", ".", "emitter", "=", "incomingEmitter", ";", "this", ".", "ports", "=", "this", ".", "compiledModule", ".", "ports", ";", "}" ]
wrap compiled and executed object in EventEmitters
[ "wrap", "compiled", "and", "executed", "object", "in", "EventEmitters" ]
e6a6fa4dd8c3352c65f338b6f2760b16687b760a
https://github.com/sonnym/node-elm-loader/blob/e6a6fa4dd8c3352c65f338b6f2760b16687b760a/src/index.js#L87-L116
train
joeyespo/gesso.js
gesso/bundler.js
mkdirsInner
function mkdirsInner(dirnames, currentPath, callback) { // Check for completion and call callback if (dirnames.length === 0) { return _callback(callback); } // Make next directory var dirname = dirnames.shift(); currentPath = path.join(currentPath, dirname); fs.mkdir(currentPath, function(err) { return mkdirsInner(dirnames, currentPath, callback); }); }
javascript
function mkdirsInner(dirnames, currentPath, callback) { // Check for completion and call callback if (dirnames.length === 0) { return _callback(callback); } // Make next directory var dirname = dirnames.shift(); currentPath = path.join(currentPath, dirname); fs.mkdir(currentPath, function(err) { return mkdirsInner(dirnames, currentPath, callback); }); }
[ "function", "mkdirsInner", "(", "dirnames", ",", "currentPath", ",", "callback", ")", "{", "if", "(", "dirnames", ".", "length", "===", "0", ")", "{", "return", "_callback", "(", "callback", ")", ";", "}", "var", "dirname", "=", "dirnames", ".", "shift", "(", ")", ";", "currentPath", "=", "path", ".", "join", "(", "currentPath", ",", "dirname", ")", ";", "fs", ".", "mkdir", "(", "currentPath", ",", "function", "(", "err", ")", "{", "return", "mkdirsInner", "(", "dirnames", ",", "currentPath", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Run async mkdir recursively
[ "Run", "async", "mkdir", "recursively" ]
b4858dfc607aab13342474930c174b5b82f98267
https://github.com/joeyespo/gesso.js/blob/b4858dfc607aab13342474930c174b5b82f98267/gesso/bundler.js#L38-L50
train
abrahamjagadeesh/npm-module-stats
lib/walk.js
pushResultsArray
function pushResultsArray(obj, size) { if (typeof obj === "string" && obj in stack) { stack[obj]["size"] = size; return; } if (!(obj.module in stack)) { stack[obj.module] = obj; } }
javascript
function pushResultsArray(obj, size) { if (typeof obj === "string" && obj in stack) { stack[obj]["size"] = size; return; } if (!(obj.module in stack)) { stack[obj.module] = obj; } }
[ "function", "pushResultsArray", "(", "obj", ",", "size", ")", "{", "if", "(", "typeof", "obj", "===", "\"string\"", "&&", "obj", "in", "stack", ")", "{", "stack", "[", "obj", "]", "[", "\"size\"", "]", "=", "size", ";", "return", ";", "}", "if", "(", "!", "(", "obj", ".", "module", "in", "stack", ")", ")", "{", "stack", "[", "obj", ".", "module", "]", "=", "obj", ";", "}", "}" ]
Fn to push new object into stack returned by each Walk function
[ "Fn", "to", "push", "new", "object", "into", "stack", "returned", "by", "each", "Walk", "function" ]
70efd2ddd0d184973acd2918811a46558a71b5f5
https://github.com/abrahamjagadeesh/npm-module-stats/blob/70efd2ddd0d184973acd2918811a46558a71b5f5/lib/walk.js#L19-L27
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/generators/classes.js
ClassBody
function ClassBody(node, print) { this.push("{"); if (node.body.length === 0) { print.printInnerComments(); this.push("}"); } else { this.newline(); this.indent(); print.sequence(node.body); this.dedent(); this.rightBrace(); } }
javascript
function ClassBody(node, print) { this.push("{"); if (node.body.length === 0) { print.printInnerComments(); this.push("}"); } else { this.newline(); this.indent(); print.sequence(node.body); this.dedent(); this.rightBrace(); } }
[ "function", "ClassBody", "(", "node", ",", "print", ")", "{", "this", ".", "push", "(", "\"{\"", ")", ";", "if", "(", "node", ".", "body", ".", "length", "===", "0", ")", "{", "print", ".", "printInnerComments", "(", ")", ";", "this", ".", "push", "(", "\"}\"", ")", ";", "}", "else", "{", "this", ".", "newline", "(", ")", ";", "this", ".", "indent", "(", ")", ";", "print", ".", "sequence", "(", "node", ".", "body", ")", ";", "this", ".", "dedent", "(", ")", ";", "this", ".", "rightBrace", "(", ")", ";", "}", "}" ]
Print ClassBody, collapses empty blocks, prints body.
[ "Print", "ClassBody", "collapses", "empty", "blocks", "prints", "body", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/generators/classes.js#L51-L65
train
noderaider/repackage
jspm_packages/system-csp-production.src.js
loadModule
function loadModule(loader, name, options) { return new Promise(asyncStartLoadPartwayThrough({ step: options.address ? 'fetch' : 'locate', loader: loader, moduleName: name, // allow metadata for import https://bugs.ecmascript.org/show_bug.cgi?id=3091 moduleMetadata: options && options.metadata || {}, moduleSource: options.source, moduleAddress: options.address })); }
javascript
function loadModule(loader, name, options) { return new Promise(asyncStartLoadPartwayThrough({ step: options.address ? 'fetch' : 'locate', loader: loader, moduleName: name, // allow metadata for import https://bugs.ecmascript.org/show_bug.cgi?id=3091 moduleMetadata: options && options.metadata || {}, moduleSource: options.source, moduleAddress: options.address })); }
[ "function", "loadModule", "(", "loader", ",", "name", ",", "options", ")", "{", "return", "new", "Promise", "(", "asyncStartLoadPartwayThrough", "(", "{", "step", ":", "options", ".", "address", "?", "'fetch'", ":", "'locate'", ",", "loader", ":", "loader", ",", "moduleName", ":", "name", ",", "moduleMetadata", ":", "options", "&&", "options", ".", "metadata", "||", "{", "}", ",", "moduleSource", ":", "options", ".", "source", ",", "moduleAddress", ":", "options", ".", "address", "}", ")", ")", ";", "}" ]
15.2.4 15.2.4.1
[ "15", ".", "2", ".", "4", "15", ".", "2", ".", "4", ".", "1" ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-csp-production.src.js#L346-L356
train
noderaider/repackage
jspm_packages/system-csp-production.src.js
requestLoad
function requestLoad(loader, request, refererName, refererAddress) { // 15.2.4.2.1 CallNormalize return new Promise(function(resolve, reject) { resolve(loader.loaderObj.normalize(request, refererName, refererAddress)); }) // 15.2.4.2.2 GetOrCreateLoad .then(function(name) { var load; if (loader.modules[name]) { load = createLoad(name); load.status = 'linked'; // https://bugs.ecmascript.org/show_bug.cgi?id=2795 load.module = loader.modules[name]; return load; } for (var i = 0, l = loader.loads.length; i < l; i++) { load = loader.loads[i]; if (load.name != name) continue; return load; } load = createLoad(name); loader.loads.push(load); proceedToLocate(loader, load); return load; }); }
javascript
function requestLoad(loader, request, refererName, refererAddress) { // 15.2.4.2.1 CallNormalize return new Promise(function(resolve, reject) { resolve(loader.loaderObj.normalize(request, refererName, refererAddress)); }) // 15.2.4.2.2 GetOrCreateLoad .then(function(name) { var load; if (loader.modules[name]) { load = createLoad(name); load.status = 'linked'; // https://bugs.ecmascript.org/show_bug.cgi?id=2795 load.module = loader.modules[name]; return load; } for (var i = 0, l = loader.loads.length; i < l; i++) { load = loader.loads[i]; if (load.name != name) continue; return load; } load = createLoad(name); loader.loads.push(load); proceedToLocate(loader, load); return load; }); }
[ "function", "requestLoad", "(", "loader", ",", "request", ",", "refererName", ",", "refererAddress", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "resolve", "(", "loader", ".", "loaderObj", ".", "normalize", "(", "request", ",", "refererName", ",", "refererAddress", ")", ")", ";", "}", ")", ".", "then", "(", "function", "(", "name", ")", "{", "var", "load", ";", "if", "(", "loader", ".", "modules", "[", "name", "]", ")", "{", "load", "=", "createLoad", "(", "name", ")", ";", "load", ".", "status", "=", "'linked'", ";", "load", ".", "module", "=", "loader", ".", "modules", "[", "name", "]", ";", "return", "load", ";", "}", "for", "(", "var", "i", "=", "0", ",", "l", "=", "loader", ".", "loads", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "load", "=", "loader", ".", "loads", "[", "i", "]", ";", "if", "(", "load", ".", "name", "!=", "name", ")", "continue", ";", "return", "load", ";", "}", "load", "=", "createLoad", "(", "name", ")", ";", "loader", ".", "loads", ".", "push", "(", "load", ")", ";", "proceedToLocate", "(", "loader", ",", "load", ")", ";", "return", "load", ";", "}", ")", ";", "}" ]
15.2.4.2
[ "15", ".", "2", ".", "4", ".", "2" ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-csp-production.src.js#L359-L389
train
noderaider/repackage
jspm_packages/system-csp-production.src.js
asyncStartLoadPartwayThrough
function asyncStartLoadPartwayThrough(stepState) { return function(resolve, reject) { var loader = stepState.loader; var name = stepState.moduleName; var step = stepState.step; if (loader.modules[name]) throw new TypeError('"' + name + '" already exists in the module table'); // adjusted to pick up existing loads var existingLoad; for (var i = 0, l = loader.loads.length; i < l; i++) { if (loader.loads[i].name == name) { existingLoad = loader.loads[i]; if (step == 'translate' && !existingLoad.source) { existingLoad.address = stepState.moduleAddress; proceedToTranslate(loader, existingLoad, Promise.resolve(stepState.moduleSource)); } // a primary load -> use that existing linkset if it is for the direct load here // otherwise create a new linkset unit if (existingLoad.linkSets.length && existingLoad.linkSets[0].loads[0].name == existingLoad.name) return existingLoad.linkSets[0].done.then(function() { resolve(existingLoad); }); } } var load = existingLoad || createLoad(name); load.metadata = stepState.moduleMetadata; var linkSet = createLinkSet(loader, load); loader.loads.push(load); resolve(linkSet.done); if (step == 'locate') proceedToLocate(loader, load); else if (step == 'fetch') proceedToFetch(loader, load, Promise.resolve(stepState.moduleAddress)); else { console.assert(step == 'translate', 'translate step'); load.address = stepState.moduleAddress; proceedToTranslate(loader, load, Promise.resolve(stepState.moduleSource)); } } }
javascript
function asyncStartLoadPartwayThrough(stepState) { return function(resolve, reject) { var loader = stepState.loader; var name = stepState.moduleName; var step = stepState.step; if (loader.modules[name]) throw new TypeError('"' + name + '" already exists in the module table'); // adjusted to pick up existing loads var existingLoad; for (var i = 0, l = loader.loads.length; i < l; i++) { if (loader.loads[i].name == name) { existingLoad = loader.loads[i]; if (step == 'translate' && !existingLoad.source) { existingLoad.address = stepState.moduleAddress; proceedToTranslate(loader, existingLoad, Promise.resolve(stepState.moduleSource)); } // a primary load -> use that existing linkset if it is for the direct load here // otherwise create a new linkset unit if (existingLoad.linkSets.length && existingLoad.linkSets[0].loads[0].name == existingLoad.name) return existingLoad.linkSets[0].done.then(function() { resolve(existingLoad); }); } } var load = existingLoad || createLoad(name); load.metadata = stepState.moduleMetadata; var linkSet = createLinkSet(loader, load); loader.loads.push(load); resolve(linkSet.done); if (step == 'locate') proceedToLocate(loader, load); else if (step == 'fetch') proceedToFetch(loader, load, Promise.resolve(stepState.moduleAddress)); else { console.assert(step == 'translate', 'translate step'); load.address = stepState.moduleAddress; proceedToTranslate(loader, load, Promise.resolve(stepState.moduleSource)); } } }
[ "function", "asyncStartLoadPartwayThrough", "(", "stepState", ")", "{", "return", "function", "(", "resolve", ",", "reject", ")", "{", "var", "loader", "=", "stepState", ".", "loader", ";", "var", "name", "=", "stepState", ".", "moduleName", ";", "var", "step", "=", "stepState", ".", "step", ";", "if", "(", "loader", ".", "modules", "[", "name", "]", ")", "throw", "new", "TypeError", "(", "'\"'", "+", "name", "+", "'\" already exists in the module table'", ")", ";", "var", "existingLoad", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "loader", ".", "loads", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "loader", ".", "loads", "[", "i", "]", ".", "name", "==", "name", ")", "{", "existingLoad", "=", "loader", ".", "loads", "[", "i", "]", ";", "if", "(", "step", "==", "'translate'", "&&", "!", "existingLoad", ".", "source", ")", "{", "existingLoad", ".", "address", "=", "stepState", ".", "moduleAddress", ";", "proceedToTranslate", "(", "loader", ",", "existingLoad", ",", "Promise", ".", "resolve", "(", "stepState", ".", "moduleSource", ")", ")", ";", "}", "if", "(", "existingLoad", ".", "linkSets", ".", "length", "&&", "existingLoad", ".", "linkSets", "[", "0", "]", ".", "loads", "[", "0", "]", ".", "name", "==", "existingLoad", ".", "name", ")", "return", "existingLoad", ".", "linkSets", "[", "0", "]", ".", "done", ".", "then", "(", "function", "(", ")", "{", "resolve", "(", "existingLoad", ")", ";", "}", ")", ";", "}", "}", "var", "load", "=", "existingLoad", "||", "createLoad", "(", "name", ")", ";", "load", ".", "metadata", "=", "stepState", ".", "moduleMetadata", ";", "var", "linkSet", "=", "createLinkSet", "(", "loader", ",", "load", ")", ";", "loader", ".", "loads", ".", "push", "(", "load", ")", ";", "resolve", "(", "linkSet", ".", "done", ")", ";", "if", "(", "step", "==", "'locate'", ")", "proceedToLocate", "(", "loader", ",", "load", ")", ";", "else", "if", "(", "step", "==", "'fetch'", ")", "proceedToFetch", "(", "loader", ",", "load", ",", "Promise", ".", "resolve", "(", "stepState", ".", "moduleAddress", ")", ")", ";", "else", "{", "console", ".", "assert", "(", "step", "==", "'translate'", ",", "'translate step'", ")", ";", "load", ".", "address", "=", "stepState", ".", "moduleAddress", ";", "proceedToTranslate", "(", "loader", ",", "load", ",", "Promise", ".", "resolve", "(", "stepState", ".", "moduleSource", ")", ")", ";", "}", "}", "}" ]
15.2.4.7 PromiseOfStartLoadPartwayThrough absorbed into calling functions 15.2.4.7.1
[ "15", ".", "2", ".", "4", ".", "7", "PromiseOfStartLoadPartwayThrough", "absorbed", "into", "calling", "functions", "15", ".", "2", ".", "4", ".", "7", ".", "1" ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-csp-production.src.js#L513-L564
train
noderaider/repackage
jspm_packages/system-csp-production.src.js
doLink
function doLink(linkSet) { var error = false; try { link(linkSet, function(load, exc) { linkSetFailed(linkSet, load, exc); error = true; }); } catch(e) { linkSetFailed(linkSet, null, e); error = true; } return error; }
javascript
function doLink(linkSet) { var error = false; try { link(linkSet, function(load, exc) { linkSetFailed(linkSet, load, exc); error = true; }); } catch(e) { linkSetFailed(linkSet, null, e); error = true; } return error; }
[ "function", "doLink", "(", "linkSet", ")", "{", "var", "error", "=", "false", ";", "try", "{", "link", "(", "linkSet", ",", "function", "(", "load", ",", "exc", ")", "{", "linkSetFailed", "(", "linkSet", ",", "load", ",", "exc", ")", ";", "error", "=", "true", ";", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "linkSetFailed", "(", "linkSet", ",", "null", ",", "e", ")", ";", "error", "=", "true", ";", "}", "return", "error", ";", "}" ]
linking errors can be generic or load-specific this is necessary for debugging info
[ "linking", "errors", "can", "be", "generic", "or", "load", "-", "specific", "this", "is", "necessary", "for", "debugging", "info" ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-csp-production.src.js#L628-L641
train
noderaider/repackage
jspm_packages/system-csp-production.src.js
function(name, source, options) { // check if already defined if (this._loader.importPromises[name]) throw new TypeError('Module is already loading.'); return createImportPromise(this, name, new Promise(asyncStartLoadPartwayThrough({ step: 'translate', loader: this._loader, moduleName: name, moduleMetadata: options && options.metadata || {}, moduleSource: source, moduleAddress: options && options.address }))); }
javascript
function(name, source, options) { // check if already defined if (this._loader.importPromises[name]) throw new TypeError('Module is already loading.'); return createImportPromise(this, name, new Promise(asyncStartLoadPartwayThrough({ step: 'translate', loader: this._loader, moduleName: name, moduleMetadata: options && options.metadata || {}, moduleSource: source, moduleAddress: options && options.address }))); }
[ "function", "(", "name", ",", "source", ",", "options", ")", "{", "if", "(", "this", ".", "_loader", ".", "importPromises", "[", "name", "]", ")", "throw", "new", "TypeError", "(", "'Module is already loading.'", ")", ";", "return", "createImportPromise", "(", "this", ",", "name", ",", "new", "Promise", "(", "asyncStartLoadPartwayThrough", "(", "{", "step", ":", "'translate'", ",", "loader", ":", "this", ".", "_loader", ",", "moduleName", ":", "name", ",", "moduleMetadata", ":", "options", "&&", "options", ".", "metadata", "||", "{", "}", ",", "moduleSource", ":", "source", ",", "moduleAddress", ":", "options", "&&", "options", ".", "address", "}", ")", ")", ")", ";", "}" ]
26.3.3.2
[ "26", ".", "3", ".", "3", ".", "2" ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-csp-production.src.js#L807-L819
train
noderaider/repackage
jspm_packages/system-csp-production.src.js
function(name) { var loader = this._loader; delete loader.importPromises[name]; delete loader.moduleRecords[name]; return loader.modules[name] ? delete loader.modules[name] : false; }
javascript
function(name) { var loader = this._loader; delete loader.importPromises[name]; delete loader.moduleRecords[name]; return loader.modules[name] ? delete loader.modules[name] : false; }
[ "function", "(", "name", ")", "{", "var", "loader", "=", "this", ".", "_loader", ";", "delete", "loader", ".", "importPromises", "[", "name", "]", ";", "delete", "loader", ".", "moduleRecords", "[", "name", "]", ";", "return", "loader", ".", "modules", "[", "name", "]", "?", "delete", "loader", ".", "modules", "[", "name", "]", ":", "false", ";", "}" ]
26.3.3.3
[ "26", ".", "3", ".", "3", ".", "3" ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-csp-production.src.js#L821-L826
train
noderaider/repackage
jspm_packages/system-csp-production.src.js
function(source, options) { var load = createLoad(); load.address = options && options.address; var linkSet = createLinkSet(this._loader, load); var sourcePromise = Promise.resolve(source); var loader = this._loader; var p = linkSet.done.then(function() { return load.module.module; }); proceedToTranslate(loader, load, sourcePromise); return p; }
javascript
function(source, options) { var load = createLoad(); load.address = options && options.address; var linkSet = createLinkSet(this._loader, load); var sourcePromise = Promise.resolve(source); var loader = this._loader; var p = linkSet.done.then(function() { return load.module.module; }); proceedToTranslate(loader, load, sourcePromise); return p; }
[ "function", "(", "source", ",", "options", ")", "{", "var", "load", "=", "createLoad", "(", ")", ";", "load", ".", "address", "=", "options", "&&", "options", ".", "address", ";", "var", "linkSet", "=", "createLinkSet", "(", "this", ".", "_loader", ",", "load", ")", ";", "var", "sourcePromise", "=", "Promise", ".", "resolve", "(", "source", ")", ";", "var", "loader", "=", "this", ".", "_loader", ";", "var", "p", "=", "linkSet", ".", "done", ".", "then", "(", "function", "(", ")", "{", "return", "load", ".", "module", ".", "module", ";", "}", ")", ";", "proceedToTranslate", "(", "loader", ",", "load", ",", "sourcePromise", ")", ";", "return", "p", ";", "}" ]
26.3.3.11
[ "26", ".", "3", ".", "3", ".", "11" ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-csp-production.src.js#L881-L892
train
noderaider/repackage
jspm_packages/system-csp-production.src.js
getESModule
function getESModule(exports) { var esModule = {}; // don't trigger getters/setters in environments that support them if ((typeof exports == 'object' || typeof exports == 'function') && exports !== __global) { if (getOwnPropertyDescriptor) { for (var p in exports) { // The default property is copied to esModule later on if (p === 'default') continue; defineOrCopyProperty(esModule, exports, p); } } else { extend(esModule, exports); } } esModule['default'] = exports; defineProperty(esModule, '__useDefault', { value: true }); return esModule; }
javascript
function getESModule(exports) { var esModule = {}; // don't trigger getters/setters in environments that support them if ((typeof exports == 'object' || typeof exports == 'function') && exports !== __global) { if (getOwnPropertyDescriptor) { for (var p in exports) { // The default property is copied to esModule later on if (p === 'default') continue; defineOrCopyProperty(esModule, exports, p); } } else { extend(esModule, exports); } } esModule['default'] = exports; defineProperty(esModule, '__useDefault', { value: true }); return esModule; }
[ "function", "getESModule", "(", "exports", ")", "{", "var", "esModule", "=", "{", "}", ";", "if", "(", "(", "typeof", "exports", "==", "'object'", "||", "typeof", "exports", "==", "'function'", ")", "&&", "exports", "!==", "__global", ")", "{", "if", "(", "getOwnPropertyDescriptor", ")", "{", "for", "(", "var", "p", "in", "exports", ")", "{", "if", "(", "p", "===", "'default'", ")", "continue", ";", "defineOrCopyProperty", "(", "esModule", ",", "exports", ",", "p", ")", ";", "}", "}", "else", "{", "extend", "(", "esModule", ",", "exports", ")", ";", "}", "}", "esModule", "[", "'default'", "]", "=", "exports", ";", "defineProperty", "(", "esModule", ",", "'__useDefault'", ",", "{", "value", ":", "true", "}", ")", ";", "return", "esModule", ";", "}" ]
converts any module.exports object into an object ready for SystemJS.newModule
[ "converts", "any", "module", ".", "exports", "object", "into", "an", "object", "ready", "for", "SystemJS", ".", "newModule" ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-csp-production.src.js#L1128-L1149
train
noderaider/repackage
jspm_packages/system-csp-production.src.js
getPackageConfigMatch
function getPackageConfigMatch(loader, normalized) { var pkgName, exactMatch = false, configPath; for (var i = 0; i < loader.packageConfigPaths.length; i++) { var packageConfigPath = loader.packageConfigPaths[i]; var p = packageConfigPaths[packageConfigPath] || (packageConfigPaths[packageConfigPath] = createPkgConfigPathObj(packageConfigPath)); if (normalized.length < p.length) continue; var match = normalized.match(p.regEx); if (match && (!pkgName || (!(exactMatch && p.wildcard) && pkgName.length < match[1].length))) { pkgName = match[1]; exactMatch = !p.wildcard; configPath = pkgName + packageConfigPath.substr(p.length); } } if (!pkgName) return; return { packageName: pkgName, configPath: configPath }; }
javascript
function getPackageConfigMatch(loader, normalized) { var pkgName, exactMatch = false, configPath; for (var i = 0; i < loader.packageConfigPaths.length; i++) { var packageConfigPath = loader.packageConfigPaths[i]; var p = packageConfigPaths[packageConfigPath] || (packageConfigPaths[packageConfigPath] = createPkgConfigPathObj(packageConfigPath)); if (normalized.length < p.length) continue; var match = normalized.match(p.regEx); if (match && (!pkgName || (!(exactMatch && p.wildcard) && pkgName.length < match[1].length))) { pkgName = match[1]; exactMatch = !p.wildcard; configPath = pkgName + packageConfigPath.substr(p.length); } } if (!pkgName) return; return { packageName: pkgName, configPath: configPath }; }
[ "function", "getPackageConfigMatch", "(", "loader", ",", "normalized", ")", "{", "var", "pkgName", ",", "exactMatch", "=", "false", ",", "configPath", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "loader", ".", "packageConfigPaths", ".", "length", ";", "i", "++", ")", "{", "var", "packageConfigPath", "=", "loader", ".", "packageConfigPaths", "[", "i", "]", ";", "var", "p", "=", "packageConfigPaths", "[", "packageConfigPath", "]", "||", "(", "packageConfigPaths", "[", "packageConfigPath", "]", "=", "createPkgConfigPathObj", "(", "packageConfigPath", ")", ")", ";", "if", "(", "normalized", ".", "length", "<", "p", ".", "length", ")", "continue", ";", "var", "match", "=", "normalized", ".", "match", "(", "p", ".", "regEx", ")", ";", "if", "(", "match", "&&", "(", "!", "pkgName", "||", "(", "!", "(", "exactMatch", "&&", "p", ".", "wildcard", ")", "&&", "pkgName", ".", "length", "<", "match", "[", "1", "]", ".", "length", ")", ")", ")", "{", "pkgName", "=", "match", "[", "1", "]", ";", "exactMatch", "=", "!", "p", ".", "wildcard", ";", "configPath", "=", "pkgName", "+", "packageConfigPath", ".", "substr", "(", "p", ".", "length", ")", ";", "}", "}", "if", "(", "!", "pkgName", ")", "return", ";", "return", "{", "packageName", ":", "pkgName", ",", "configPath", ":", "configPath", "}", ";", "}" ]
most specific match wins
[ "most", "specific", "match", "wins" ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-csp-production.src.js#L2366-L2388
train
noderaider/repackage
jspm_packages/system-csp-production.src.js
combinePluginParts
function combinePluginParts(loader, argumentName, pluginName, defaultExtension) { if (defaultExtension && argumentName.substr(argumentName.length - 3, 3) == '.js') argumentName = argumentName.substr(0, argumentName.length - 3); if (loader.pluginFirst) { return pluginName + '!' + argumentName; } else { return argumentName + '!' + pluginName; } }
javascript
function combinePluginParts(loader, argumentName, pluginName, defaultExtension) { if (defaultExtension && argumentName.substr(argumentName.length - 3, 3) == '.js') argumentName = argumentName.substr(0, argumentName.length - 3); if (loader.pluginFirst) { return pluginName + '!' + argumentName; } else { return argumentName + '!' + pluginName; } }
[ "function", "combinePluginParts", "(", "loader", ",", "argumentName", ",", "pluginName", ",", "defaultExtension", ")", "{", "if", "(", "defaultExtension", "&&", "argumentName", ".", "substr", "(", "argumentName", ".", "length", "-", "3", ",", "3", ")", "==", "'.js'", ")", "argumentName", "=", "argumentName", ".", "substr", "(", "0", ",", "argumentName", ".", "length", "-", "3", ")", ";", "if", "(", "loader", ".", "pluginFirst", ")", "{", "return", "pluginName", "+", "'!'", "+", "argumentName", ";", "}", "else", "{", "return", "argumentName", "+", "'!'", "+", "pluginName", ";", "}", "}" ]
put name back together after parts have been normalized
[ "put", "name", "back", "together", "after", "parts", "have", "been", "normalized" ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/system-csp-production.src.js#L3783-L3793
train
chirashijs/chirashi
dist/chirashi.common.js
getElements
function getElements(input) { if (typeof input === 'string') { return _getElements(document, input); } if (input instanceof window.NodeList || input instanceof window.HTMLCollection) { return _nodelistToArray(input); } if (input instanceof Array) { if (input['_chrsh-valid']) { return input; } var output = []; forEach(input, _pushRecursive.bind(null, output)); return _chirasizeArray(output); } return _chirasizeArray(isDomElement(input) ? [input] : []); }
javascript
function getElements(input) { if (typeof input === 'string') { return _getElements(document, input); } if (input instanceof window.NodeList || input instanceof window.HTMLCollection) { return _nodelistToArray(input); } if (input instanceof Array) { if (input['_chrsh-valid']) { return input; } var output = []; forEach(input, _pushRecursive.bind(null, output)); return _chirasizeArray(output); } return _chirasizeArray(isDomElement(input) ? [input] : []); }
[ "function", "getElements", "(", "input", ")", "{", "if", "(", "typeof", "input", "===", "'string'", ")", "{", "return", "_getElements", "(", "document", ",", "input", ")", ";", "}", "if", "(", "input", "instanceof", "window", ".", "NodeList", "||", "input", "instanceof", "window", ".", "HTMLCollection", ")", "{", "return", "_nodelistToArray", "(", "input", ")", ";", "}", "if", "(", "input", "instanceof", "Array", ")", "{", "if", "(", "input", "[", "'_chrsh-valid'", "]", ")", "{", "return", "input", ";", "}", "var", "output", "=", "[", "]", ";", "forEach", "(", "input", ",", "_pushRecursive", ".", "bind", "(", "null", ",", "output", ")", ")", ";", "return", "_chirasizeArray", "(", "output", ")", ";", "}", "return", "_chirasizeArray", "(", "isDomElement", "(", "input", ")", "?", "[", "input", "]", ":", "[", "]", ")", ";", "}" ]
Get dom element recursively from iterable or selector. @param {(string|Array|NodeList|HTMLCollection|Window|Node)} input - The iterable, selector or elements. @return {Array} domElements - The array of dom elements from input. @example //esnext import { createElement, append, getElements } from 'chirashi' const sushi = createElement('.sushi') const unagi = createElement('.unagi') const yakitori = createElement('.yakitori') const sashimi = createElement('.sashimi') append(document.body, [sushi, unagi, yakitori, sashimi]) getElements('div') //returns: [<div class="sushi"></div>, <div class="unagi"></div>, <div class="yakitori"></div>, <div class="sashimi"></div>] getElements('.yakitori, .sashimi') //returns: [<div class="yakitori"></div>, <div class="sashimi"></div>] getElements([sushi, unagi, '.sashimi', '.wasabi']) //returns: [<div class="sushi"></div>, <div class="unagi"></div>, <div class="sashimi"></div>] getElements('.wasabi') //returns: [] @example //es5 var sushi = Chirashi.createElement('.sushi') var unagi = Chirashi.createElement('.unagi') var yakitori = Chirashi.createElement('.yakitori') var sashimi = Chirashi.createElement('.sashimi') Chirashi.append(document.body, [sushi, unagi, yakitori, sashimi]) Chirashi.getElements('div') //returns: [<div class="sushi"></div>, <div class="unagi"></div>, <div class="yakitori"></div>, <div class="sashimi"></div>] Chirashi.getElements('.yakitori, .sashimi') //returns: [<div class="yakitori"></div>, <div class="sashimi"></div>] Chirashi.getElements([sushi, unagi, '.sashimi', '.wasabi']) //returns: [<div class="sushi"></div>, <div class="unagi"></div>, <div class="sashimi"></div>] Chirashi.getElements('.wasabi') //returns: []
[ "Get", "dom", "element", "recursively", "from", "iterable", "or", "selector", "." ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L204-L225
train
chirashijs/chirashi
dist/chirashi.common.js
forIn
function forIn(object, callback) { if ((typeof object === 'undefined' ? 'undefined' : _typeof(object)) !== 'object') return; forEach(Object.keys(object), _forKey.bind(null, object, callback)); return object; }
javascript
function forIn(object, callback) { if ((typeof object === 'undefined' ? 'undefined' : _typeof(object)) !== 'object') return; forEach(Object.keys(object), _forKey.bind(null, object, callback)); return object; }
[ "function", "forIn", "(", "object", ",", "callback", ")", "{", "if", "(", "(", "typeof", "object", "===", "'undefined'", "?", "'undefined'", ":", "_typeof", "(", "object", ")", ")", "!==", "'object'", ")", "return", ";", "forEach", "(", "Object", ".", "keys", "(", "object", ")", ",", "_forKey", ".", "bind", "(", "null", ",", "object", ",", "callback", ")", ")", ";", "return", "object", ";", "}" ]
Callback to apply on element. @callback forElementsCallback @param {Window | document | HTMLElement | SVGElement | Text} element @param {number} index - Index of element in elements. Iterates over object's keys and apply callback on each one. @param {Object} object - The iterable. @param {forInCallback} callback - The function to call for each key-value pair. @return {Object} object - The iterable for chaining. @example //esnext import { forIn } from 'chirashi' const californiaRoll = { name: 'California Roll', price: 4.25, recipe: ['avocado', 'cucumber', 'crab', 'mayonnaise', 'sushi rice', 'seaweed'] } forIn(californiaRoll, (key, value) => { console.log(`${key} -> ${value}`) }) //returns: { name: 'California Roll', price: 4.25, recipe: ['avocado', 'cucumber', 'crab', 'mayonnaise', 'sushi rice', 'seaweed'] } // LOGS: // name -> California Roll // price -> 4.25 // recipe -> ['avocado', 'cucumber', 'crab', 'mayonnaise', 'sushi rice', 'seaweed'] @example //es5 var californiaRoll = { name: 'California Roll', price: 4.25, recipe: ['avocado', 'cucumber', 'crab', 'mayonnaise', 'sushi rice', 'seaweed'] } Chirashi.forIn(californiaRoll, (key, value) => { console.log(key + ' -> ' + value) }) //returns: { name: 'California Roll', price: 4.25, recipe: ['avocado', 'cucumber', 'crab', 'mayonnaise', 'sushi rice', 'seaweed'] } // LOGS: // name -> California Roll // price -> 4.25 // recipe -> ['avocado', 'cucumber', 'crab', 'mayonnaise', 'sushi rice', 'seaweed']
[ "Callback", "to", "apply", "on", "element", "." ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L306-L312
train
chirashijs/chirashi
dist/chirashi.common.js
getElement
function getElement(input) { if (typeof input === 'string') { return _getElement(document, input); } if (input instanceof window.NodeList || input instanceof window.HTMLCollection) { return input[0]; } if (input instanceof Array) { return getElement(input[0]); } return isDomElement(input) && input; }
javascript
function getElement(input) { if (typeof input === 'string') { return _getElement(document, input); } if (input instanceof window.NodeList || input instanceof window.HTMLCollection) { return input[0]; } if (input instanceof Array) { return getElement(input[0]); } return isDomElement(input) && input; }
[ "function", "getElement", "(", "input", ")", "{", "if", "(", "typeof", "input", "===", "'string'", ")", "{", "return", "_getElement", "(", "document", ",", "input", ")", ";", "}", "if", "(", "input", "instanceof", "window", ".", "NodeList", "||", "input", "instanceof", "window", ".", "HTMLCollection", ")", "{", "return", "input", "[", "0", "]", ";", "}", "if", "(", "input", "instanceof", "Array", ")", "{", "return", "getElement", "(", "input", "[", "0", "]", ")", ";", "}", "return", "isDomElement", "(", "input", ")", "&&", "input", ";", "}" ]
Get first dom element from iterable or selector. @param {(string|Array|NodeList|HTMLCollection|Window|Node)} input - The iterable, selector or elements. @return {(Window|Node|boolean)} element - The dom element from input. @example //esnext import { createElement, append, getElement } from 'chirashi' const sushi = createElement('.sushi') const unagi = createElement('.unagi') const yakitori = createElement('.yakitori') const sashimi = createElement('.sashimi') append(document.body, [sushi, unagi, yakitori, sashimi]) getElement('div') //returns: <div class="sushi"></div> getElement('.yakitori, .sashimi') //returns: <div class="yakitori"></div> getElement([sushi, unagi, '.sashimi', '.unknown']) //returns: <div class="sushi"></div> getElement('.wasabi') //returns: undefined @example //es5 var sushi = Chirashi.createElement('.sushi') var unagi = Chirashi.createElement('.unagi') var yakitori = Chirashi.createElement('.yakitori') var sashimi = Chirashi.createElement('.sashimi') Chirashi.append(document.body, [sushi, unagi, yakitori, sashimi]) Chirashi.getElement('div') //returns: <div class="sushi"></div> Chirashi.getElement('.yakitori, .sashimi') //returns: <div class="yakitori"></div> Chirashi.getElement([sushi, unagi, '.sashimi', '.unknown']) //returns: <div class="sushi"></div> Chirashi.getElement('.wasabi') //returns: undefined
[ "Get", "first", "dom", "element", "from", "iterable", "or", "selector", "." ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L368-L382
train
chirashijs/chirashi
dist/chirashi.common.js
append
function append(element, nodes) { element = getElement(element); if (!element || !element.appendChild) return false; forEach(nodes, _appendOne.bind(null, element)); return element; }
javascript
function append(element, nodes) { element = getElement(element); if (!element || !element.appendChild) return false; forEach(nodes, _appendOne.bind(null, element)); return element; }
[ "function", "append", "(", "element", ",", "nodes", ")", "{", "element", "=", "getElement", "(", "element", ")", ";", "if", "(", "!", "element", "||", "!", "element", ".", "appendChild", ")", "return", "false", ";", "forEach", "(", "nodes", ",", "_appendOne", ".", "bind", "(", "null", ",", "element", ")", ")", ";", "return", "element", ";", "}" ]
Appends each node to a parent node. @param {(string|Array|NodeList|HTMLCollection|Node)} element - The parent node. Note that it'll be passed to getElement to ensure there's only one. @param {(string|Array.<(string|Node)>|Node)} nodes - String, node or array of nodes and/or strings. Each string will be passed to createElement then append. @return {(Node|boolean)} node - The node for chaining or false if nodes can't be appended. @example //esnext import { createElement, append } from 'chirashi' const maki = createElement('.maki') append(maki, '.salmon[data-fish="salmon"]') //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div></div> const avocado = createElement('.avocado') append(maki, [avocado, '.cheese[data-cheese="cream"]']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="avocado"></div><div class="cheese" data-cheese="cream"></div></div> @example //es5 var maki = Chirashi.createElement('.maki') Chirashi.append(maki, '.salmon[data-fish="salmon"]') //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div></div> var avocado = Chirashi.createElement('.avocado') Chirashi.append(maki, [avocado, '.cheese[data-cheese="cream"]']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="avocado"></div><div class="cheese" data-cheese="cream"></div></div>
[ "Appends", "each", "node", "to", "a", "parent", "node", "." ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L493-L501
train
chirashijs/chirashi
dist/chirashi.common.js
closest
function closest(element, tested) { var limit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : document; element = getElement(element); if (!element || (typeof limit === 'string' ? element.matches(limit) : element === limit)) { return false; } if (typeof tested === 'string' ? element.matches(tested) : element === tested) { return element; } return !!element.parentNode && closest(element.parentNode, tested, limit); }
javascript
function closest(element, tested) { var limit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : document; element = getElement(element); if (!element || (typeof limit === 'string' ? element.matches(limit) : element === limit)) { return false; } if (typeof tested === 'string' ? element.matches(tested) : element === tested) { return element; } return !!element.parentNode && closest(element.parentNode, tested, limit); }
[ "function", "closest", "(", "element", ",", "tested", ")", "{", "var", "limit", "=", "arguments", ".", "length", ">", "2", "&&", "arguments", "[", "2", "]", "!==", "undefined", "?", "arguments", "[", "2", "]", ":", "document", ";", "element", "=", "getElement", "(", "element", ")", ";", "if", "(", "!", "element", "||", "(", "typeof", "limit", "===", "'string'", "?", "element", ".", "matches", "(", "limit", ")", ":", "element", "===", "limit", ")", ")", "{", "return", "false", ";", "}", "if", "(", "typeof", "tested", "===", "'string'", "?", "element", ".", "matches", "(", "tested", ")", ":", "element", "===", "tested", ")", "{", "return", "element", ";", "}", "return", "!", "!", "element", ".", "parentNode", "&&", "closest", "(", "element", ".", "parentNode", ",", "tested", ",", "limit", ")", ";", "}" ]
Get closest element matching the tested selector or tested element traveling up the DOM tree from element to limit. @param {(string|Array|NodeList|HTMLCollection|Element)} element - First tested element. Note that it'll be passed to getElement to ensure there's only one. @param {(string|Element)} tested - The selector or dom element to match. @param {(string|Node)} [limit=document] - Returns false when this selector or element is reached. @return {(Element|boolean)} matchedElement - The matched element or false. @example //esnext import { createElement, append, closest } from 'chirashi' const maki = createElement('.maki') const cheese = createElement('.cheese') append(maki, cheese) append(cheese, '.avocado') append(document.body, maki) closest('.avocado', '.maki') //returns: <div class="maki"></div> closest('.avocado', '.maki', '.cheese') //returns: false @example //es5 var maki = Chirashi.createElement('.maki') var cheese = Chirashi.createElement('.cheese') Chirashi.append(maki, cheese) Chirashi.append(cheese, '.avocado') Chirashi.append(document.body, maki) Chirashi.closest('.avocado', '.maki') //returns: <div class="maki"></div> Chirashi.closest('.avocado', '.maki', '.cheese') //returns: false
[ "Get", "closest", "element", "matching", "the", "tested", "selector", "or", "tested", "element", "traveling", "up", "the", "DOM", "tree", "from", "element", "to", "limit", "." ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L614-L628
train
chirashijs/chirashi
dist/chirashi.common.js
findOne
function findOne(element, selector) { return (element = getElement(element)) ? _getElement(element, selector) : null; }
javascript
function findOne(element, selector) { return (element = getElement(element)) ? _getElement(element, selector) : null; }
[ "function", "findOne", "(", "element", ",", "selector", ")", "{", "return", "(", "element", "=", "getElement", "(", "element", ")", ")", "?", "_getElement", "(", "element", ",", "selector", ")", ":", "null", ";", "}" ]
Find the first element's child matching the selector. @param {(string|Array|NodeList|HTMLCollection|Element|Document|ParentNode)} element - The parent node. Note that it'll be passed to getElement to ensure there's only one. @param {string} selector - The selector to match. @return {(Element|null)} element - The first child of elements matching the selector or null. @example //esnext import { createElement, append, find } from 'chirashi' const maki = createElement('.maki') append(maki, ['.salmon[data-fish][data-inside]', '.avocado[data-inside]']) const roll = createElement('.roll') append(roll, '.tuna[data-fish][data-inside]') append(document.body, [maki, roll]) findOne('div', '[data-fish]') //returns: <div class="salmon" data-fish data-inside></div> findOne(maki, '[data-inside]') //returns: <div class="salmon" data-fish data-inside></div> @example //es5 var maki = Chirashi.createElement('.maki') Chirashi.append(maki, ['.salmon[data-fish][data-inside]', '.avocado[data-inside]']) var roll = Chirashi.createElement('.roll') Chirashi.append(roll, '.tuna[data-fish][data-inside]') Chirashi.append(document.body, [maki, roll]) Chirashi.findOne('div', '[data-fish]') //returns: <div class="salmon" data-fish data-inside></div> Chirashi.findOne(maki, '[data-inside]') //returns: <div class="salmon" data-fish data-inside></div>
[ "Find", "the", "first", "element", "s", "child", "matching", "the", "selector", "." ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L746-L748
train
chirashijs/chirashi
dist/chirashi.common.js
hasClass
function hasClass(element) { element = getElement(element); if (!element) return; var n = arguments.length <= 1 ? 0 : arguments.length - 1; var found = void 0; var i = 0; while (i < n && (found = element.classList.contains((_ref = i++ + 1, arguments.length <= _ref ? undefined : arguments[_ref])))) { var _ref; } return found; }
javascript
function hasClass(element) { element = getElement(element); if (!element) return; var n = arguments.length <= 1 ? 0 : arguments.length - 1; var found = void 0; var i = 0; while (i < n && (found = element.classList.contains((_ref = i++ + 1, arguments.length <= _ref ? undefined : arguments[_ref])))) { var _ref; } return found; }
[ "function", "hasClass", "(", "element", ")", "{", "element", "=", "getElement", "(", "element", ")", ";", "if", "(", "!", "element", ")", "return", ";", "var", "n", "=", "arguments", ".", "length", "<=", "1", "?", "0", ":", "arguments", ".", "length", "-", "1", ";", "var", "found", "=", "void", "0", ";", "var", "i", "=", "0", ";", "while", "(", "i", "<", "n", "&&", "(", "found", "=", "element", ".", "classList", ".", "contains", "(", "(", "_ref", "=", "i", "++", "+", "1", ",", "arguments", ".", "length", "<=", "_ref", "?", "undefined", ":", "arguments", "[", "_ref", "]", ")", ")", ")", ")", "{", "var", "_ref", ";", "}", "return", "found", ";", "}" ]
Iterates over classes and test if element has each. @param {(string|Array|NodeList|HTMLCollection|Element)} elements - The iterable, selector or elements. @param {...string} classes - Classes to test. @return {boolean} hasClass - Is true if element has all classes. @example //esnext import { createElement, hasClass } from 'chirashi' const maki = createElement('.salmon.cheese.maki') hasClass(maki, 'salmon', 'cheese') //returns: true hasClass(maki, 'salmon', 'avocado') //returns: false @example //es5 var maki = Chirashi.createElement('.salmon.cheese.maki') Chirashi.hasClass(maki, 'salmon', 'cheese') //returns: true Chirashi.hasClass(maki, 'salmon', 'avocado') //returns: false
[ "Iterates", "over", "classes", "and", "test", "if", "element", "has", "each", "." ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L819-L831
train
chirashijs/chirashi
dist/chirashi.common.js
removeClass
function removeClass(elements) { for (var _len = arguments.length, classes = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { classes[_key - 1] = arguments[_key]; } return _updateClassList(elements, 'remove', classes); }
javascript
function removeClass(elements) { for (var _len = arguments.length, classes = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { classes[_key - 1] = arguments[_key]; } return _updateClassList(elements, 'remove', classes); }
[ "function", "removeClass", "(", "elements", ")", "{", "for", "(", "var", "_len", "=", "arguments", ".", "length", ",", "classes", "=", "Array", "(", "_len", ">", "1", "?", "_len", "-", "1", ":", "0", ")", ",", "_key", "=", "1", ";", "_key", "<", "_len", ";", "_key", "++", ")", "{", "classes", "[", "_key", "-", "1", "]", "=", "arguments", "[", "_key", "]", ";", "}", "return", "_updateClassList", "(", "elements", ",", "'remove'", ",", "classes", ")", ";", "}" ]
Iterates over classes and remove it from each element of elements. @param {(string|Array|NodeList|HTMLCollection|Element)} elements - The iterable, selector or elements. @param {...string} classes - Classes to remove. @return {Array} iterable - The getElements' result for chaining. @example //esnext import { createElement, removeClass } from 'chirashi' const maki = createElement('.maki.salmon.cheese.wasabi') //returns: <div class="maki salmon cheese wasabi"></div> removeClass(maki, 'cheese', 'wasabi') //returns: [<div class="maki salmon"></div>] @example //es5 var maki = Chirashi.createElement('.maki.salmon.cheese.wasabi') //returns: <div class="maki salmon cheese wasabi"></div> Chirashi.removeClass(maki, 'cheese', 'wasabi') //returns: [<div class="maki salmon"></div>]
[ "Iterates", "over", "classes", "and", "remove", "it", "from", "each", "element", "of", "elements", "." ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L1098-L1104
train
chirashijs/chirashi
dist/chirashi.common.js
setData
function setData(elements, dataAttributes) { var attributes = {}; forIn(dataAttributes, _prefixAttribute.bind(null, attributes)); return setAttr(elements, attributes); }
javascript
function setData(elements, dataAttributes) { var attributes = {}; forIn(dataAttributes, _prefixAttribute.bind(null, attributes)); return setAttr(elements, attributes); }
[ "function", "setData", "(", "elements", ",", "dataAttributes", ")", "{", "var", "attributes", "=", "{", "}", ";", "forIn", "(", "dataAttributes", ",", "_prefixAttribute", ".", "bind", "(", "null", ",", "attributes", ")", ")", ";", "return", "setAttr", "(", "elements", ",", "attributes", ")", ";", "}" ]
Iterates over data-attributes as key value pairs and apply on each element of elements. @param {(string|Array|NodeList|HTMLCollection|Element)} elements - The iterable, selector or elements. @param {Object.<string, (number|string)>} dataAttributes - The data-attributes key value pairs @return {Array} iterable - The getElements' result for chaining. @example //esnext import { createElement, setData } from 'chirashi' const maki = createElement('.maki') setData(maki, { fish: 'salmon' }) //returns: [<div class="maki" data-fish="salmon">] @example //es5 var maki = Chirashi.createElement('.maki') Chirashi.setData(maki, { fish: 'salmon' }) //returns: [<div class="maki" data-fish="salmon">]
[ "Iterates", "over", "data", "-", "attributes", "as", "key", "value", "pairs", "and", "apply", "on", "each", "element", "of", "elements", "." ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L1188-L1194
train
chirashijs/chirashi
dist/chirashi.common.js
toggleClass
function toggleClass(elements) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } if (_typeof(args[0]) === 'object') { forIn(args[0], _toggleClassesWithForce.bind(null, elements)); } else { forEach(args, _toggleClassName.bind(null, elements)); } }
javascript
function toggleClass(elements) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } if (_typeof(args[0]) === 'object') { forIn(args[0], _toggleClassesWithForce.bind(null, elements)); } else { forEach(args, _toggleClassName.bind(null, elements)); } }
[ "function", "toggleClass", "(", "elements", ")", "{", "for", "(", "var", "_len", "=", "arguments", ".", "length", ",", "args", "=", "Array", "(", "_len", ">", "1", "?", "_len", "-", "1", ":", "0", ")", ",", "_key", "=", "1", ";", "_key", "<", "_len", ";", "_key", "++", ")", "{", "args", "[", "_key", "-", "1", "]", "=", "arguments", "[", "_key", "]", ";", "}", "if", "(", "_typeof", "(", "args", "[", "0", "]", ")", "===", "'object'", ")", "{", "forIn", "(", "args", "[", "0", "]", ",", "_toggleClassesWithForce", ".", "bind", "(", "null", ",", "elements", ")", ")", ";", "}", "else", "{", "forEach", "(", "args", ",", "_toggleClassName", ".", "bind", "(", "null", ",", "elements", ")", ")", ";", "}", "}" ]
Iterates over classes and toggle it on each element of elements. @param {(string|Array|NodeList|HTMLCollection|Element)} elements - The iterable, selector or elements. @param {(string|Array|Object)} classes - Array of classes or string of classes seperated with comma and/or spaces. Or object with keys being the string of classes seperated with comma and/or spaces and values function returning a booleanean. @return {Array} iterable - The getElements' result for chaining. @example //esnext import { createElement, toggleClass, clone, setData, getData } from 'chirashi' const maki = createElement('.wasabi.salmon.maki') //returns: <div class="maki salmon wasabi"></div> const sushi = createElement('.salmon.sushi') //returns: <div class="sushi salmon"></div> toggleClass([maki, sushi], 'wasabi') //returns: [<div class="maki salmon"></div>, <div class="sushi salmon wasabi"></div>] const scdMaki = clone(maki) setData(maki, { for: 'leonard' }) setData(scdMaki, { for: 'sheldon' }) toggleClass([maki, scdMaki], { cheese: element => { return getData(element, 'for') !== 'leonard' } }) //returns: [<div class="maki salmon cheese" data-for="sheldon"></div>, <div class="maki salmon" data-for="leonard"></div>] @example //es5 var maki = Chirashi.createElement('.wasabi.salmon.maki') //returns: <div class="wasabi salmon maki"></div> var sushi = Chirashi.createElement('.salmon.sushi') //returns: <div class="salmon sushi"></div> Chirashi.toggleClass([maki, sushi], 'wasabi') //returns: [<div class="maki salmon"></div>, <div class="sushi salmon wasabi"></div>] var scdMaki = Chirashi.clone(maki) Chirashi.setData(maki, { for: 'leonard' }) Chirashi.setData(scdMaki, { for: 'sheldon' }) Chirashi.toggleClass([maki, scdMaki], { cheese: function (element) { return Chirashi.getData(element, 'for') !== 'leonard' } }) //returns: [<div class="maki salmon cheese" data-for="sheldon"></div>, <div class="maki salmon" data-for="leonard"></div>]
[ "Iterates", "over", "classes", "and", "toggle", "it", "on", "each", "element", "of", "elements", "." ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L1284-L1294
train
chirashijs/chirashi
dist/chirashi.common.js
on
function on(elements, input) { elements = _setEvents(elements, 'add', input); return function (offElements, events) { _setEvents(offElements || elements, 'remove', events ? defineProperty({}, events, input[events]) : input); }; }
javascript
function on(elements, input) { elements = _setEvents(elements, 'add', input); return function (offElements, events) { _setEvents(offElements || elements, 'remove', events ? defineProperty({}, events, input[events]) : input); }; }
[ "function", "on", "(", "elements", ",", "input", ")", "{", "elements", "=", "_setEvents", "(", "elements", ",", "'add'", ",", "input", ")", ";", "return", "function", "(", "offElements", ",", "events", ")", "{", "_setEvents", "(", "offElements", "||", "elements", ",", "'remove'", ",", "events", "?", "defineProperty", "(", "{", "}", ",", "events", ",", "input", "[", "events", "]", ")", ":", "input", ")", ";", "}", ";", "}" ]
Bind events listener on each element of elements. @param {(string|Array|NodeList|HTMLCollection|EventTarget)} elements - The iterable, selector or elements. @param {Object.<string, (eventCallback|EventObject)>} input - An object in which keys are events to bind seperated with coma and/or spaces and values are eventCallbacks or EventObjects. @return {offCallback} off - The unbinding function. @example //esnext import { createElement, append, on, trigger } from 'chirashi' const maki = createElement('a.cheese.maki') const sushi = createElement('a.wasabi.sushi') append(document.body, [maki, sushi]) const off = on('.cheese, .wasabi', { click(e, target) { console.log('clicked', target) }, 'mouseenter mousemove': { handler: (e, target) => { console.log('mouse in', target) }, passive: true } }) trigger(maki, 'click') //simulate user's click // LOGS: "clicked" <a class="maki cheese"></a> trigger(sushi, 'click') //simulate user's click // LOGS: "clicked" <a class="sushi wasabi"></a> off(maki, 'click') //remove click event listener on maki off() //remove all listeners from all elements @example //es5 var off = Chirashi.bind('.cheese, .wasabi', { 'click': function (e, target) { console.log('clicked', target) }, 'mouseenter mousemove': { handler: (e, target) => { console.log('mouse in', target) }, passive: true } }) var maki = Chirashi.createElement('a.cheese.maki') var sushi = Chirashi.createElement('a.wasabi.sushi') Chirashi.append(document.body, [maki, sushi]) Chirashi.trigger(maki, 'click') //simulate user's click // LOGS: "clicked" <a class="maki cheese"></a> Chirashi.trigger(sushi, 'click') //simulate user's click // LOGS: "clicked" <a class="sushi wasabi"></a> off(maki, 'click') //remove click event listener on maki off() //remove all listeners from all elements
[ "Bind", "events", "listener", "on", "each", "element", "of", "elements", "." ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L1396-L1402
train
chirashijs/chirashi
dist/chirashi.common.js
delegate
function delegate(selector, input) { var target = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : document.body; target = getElement(target); var eventsObj = {}; forIn(input, _wrapOptions.bind(null, selector, target, eventsObj)); var off = on(target, eventsObj); return function (events) { off(target, events); }; }
javascript
function delegate(selector, input) { var target = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : document.body; target = getElement(target); var eventsObj = {}; forIn(input, _wrapOptions.bind(null, selector, target, eventsObj)); var off = on(target, eventsObj); return function (events) { off(target, events); }; }
[ "function", "delegate", "(", "selector", ",", "input", ")", "{", "var", "target", "=", "arguments", ".", "length", ">", "2", "&&", "arguments", "[", "2", "]", "!==", "undefined", "?", "arguments", "[", "2", "]", ":", "document", ".", "body", ";", "target", "=", "getElement", "(", "target", ")", ";", "var", "eventsObj", "=", "{", "}", ";", "forIn", "(", "input", ",", "_wrapOptions", ".", "bind", "(", "null", ",", "selector", ",", "target", ",", "eventsObj", ")", ")", ";", "var", "off", "=", "on", "(", "target", ",", "eventsObj", ")", ";", "return", "function", "(", "events", ")", "{", "off", "(", "target", ",", "events", ")", ";", "}", ";", "}" ]
Called to remove one or all events listeners of one or all elements. @callback offCallback @param {(string|Array|NodeList|HTMLCollection|EventTarget)} [offElements] - The iterable, selector or elements to unbind. @param {string} [events] - The events to unbind. Must be provided in the same syntax as in input. Delegate events listener on delegate and execute callback when target matches selector (targets doesn't have to be in the DOM). @param {string} selector - The selector to match. @param {Object.<string, delegateCallback>} input - An object in which keys are events to delegate seperated with coma and/or spaces and values are delegateCallbacks. @param {(string|Array|NodeList|HTMLCollection|EventTarget)} [target=document.body] - The event target. Note that it'll be passed to getElement to ensure there's only one. @return {offCallback} off - The unbind function. @example //esnext import { createElement, append, delegate, trigger } from 'chirashi' const off = delegate('.cheese, .wasabi', { click(e, target) => { console.log('clicked', target) }, 'mouseenter mousemove': (e, target) => { console.log('mouse in', target) } }) const maki = createElement('a.cheese.maki') const sushi = createElement('a.wasabi.sushi') append(document.body, [maki, sushi]) trigger(maki, 'click') //simulate user's click // LOGS: "clicked" <a class="maki cheese"></a> trigger(sushi, 'click') //simulate user's click // LOGS: "clicked" <a class="sushi wasabi"></a> off('mouseenter mousemove') //remove mouseenter and mousemove listeners off() //remove all listeners @example //es5 var off = Chirashi.delegate('.cheese, .wasabi', { 'click': function (e, target) { console.log('clicked', target) }, 'mouseenter mousemove': function(e, target) { console.log('mouse in', target) } }) var maki = Chirashi.createElement('a.cheese.maki') var sushi = Chirashi.createElement('a.wasabi.sushi') Chirashi.append(document.body, [maki, sushi]) Chirashi.trigger(maki, 'click') //simulate user's click // LOGS: "clicked" <a class="maki cheese"></a> Chirashi.trigger(sushi, 'click') //simulate user's click // LOGS: "clicked" <a class="sushi wasabi"></a> off('mouseenter mousemove') //remove mouseenter and mousemove listeners off() //remove all listeners
[ "Called", "to", "remove", "one", "or", "all", "events", "listeners", "of", "one", "or", "all", "elements", "." ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L1470-L1483
train
chirashijs/chirashi
dist/chirashi.common.js
once
function once(elements, input) { var eachElement = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var eachEvent = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; var off = void 0; var eventsObj = {}; forIn(input, function (events, callback) { eventsObj[events] = function (event) { callback(event); off(eachElement && event.currentTarget, eachEvent && events); }; }); return off = on(elements, eventsObj); }
javascript
function once(elements, input) { var eachElement = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var eachEvent = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; var off = void 0; var eventsObj = {}; forIn(input, function (events, callback) { eventsObj[events] = function (event) { callback(event); off(eachElement && event.currentTarget, eachEvent && events); }; }); return off = on(elements, eventsObj); }
[ "function", "once", "(", "elements", ",", "input", ")", "{", "var", "eachElement", "=", "arguments", ".", "length", ">", "2", "&&", "arguments", "[", "2", "]", "!==", "undefined", "?", "arguments", "[", "2", "]", ":", "false", ";", "var", "eachEvent", "=", "arguments", ".", "length", ">", "3", "&&", "arguments", "[", "3", "]", "!==", "undefined", "?", "arguments", "[", "3", "]", ":", "false", ";", "var", "off", "=", "void", "0", ";", "var", "eventsObj", "=", "{", "}", ";", "forIn", "(", "input", ",", "function", "(", "events", ",", "callback", ")", "{", "eventsObj", "[", "events", "]", "=", "function", "(", "event", ")", "{", "callback", "(", "event", ")", ";", "off", "(", "eachElement", "&&", "event", ".", "currentTarget", ",", "eachEvent", "&&", "events", ")", ";", "}", ";", "}", ")", ";", "return", "off", "=", "on", "(", "elements", ",", "eventsObj", ")", ";", "}" ]
Called to off one or all events. @callback offCallback @param {string} [events] - The events to off. Must be provided in the same syntax as in input. Bind events listener on each element of elements and unbind after first triggered. @param {(string|Array|NodeList|HTMLCollection|EventTarget)} elements - The iterable, selector or elements. @param {Object.<string, eventCallback>} input - An object in which keys are events to bind seperated with coma and/or spaces and values are eventCallbacks. @param {boolean} [eachElement=false] - If true only current target's events listeners will be removed after trigger. @param {boolean} [eachEvent=false] - If true only triggered event group of events listeners will be removed. @return {offCallback} cancel - cancel function for unbinding. @example //esnext import { createElement, append, once, trigger } from 'chirashi' const maki = createElement('a.cheese.maki') const sushi = createElement('a.wasabi.sushi') append(document.body, [maki, sushi]) const cancel = once('.cheese, .wasabi', { click(e, target) => { console.log('clicked', target) }, 'mouseenter mousemove': (e, target) => { console.log('mouse in', target) } }, true, true) trigger(maki, 'click') //simulate user's click // LOGS: "clicked" <a class="maki cheese"></a> // click event listener was auto-removed from maki trigger(sushi, 'click') //simulate user's click // LOGS: "clicked" <a class="sushi wasabi"></a> // click event listener was auto-removed from sushi cancel() //remove all listeners from all elements once('.cheese, .wasabi', { click(e, target) => { console.log('clicked', target) } }) trigger(maki, 'click') //simulate user's click // LOGS: "clicked" <a class="maki cheese"></a> // all events listeners were auto-removed from all elements trigger(sushi, 'click') //simulate user's click // won't log anything @example //es5 var maki = Chirashi.createElement('a.cheese.maki') var sushi = Chirashi.createElement('a.wasabi.sushi') Chirashi.append(document.body, [maki, sushi]) var cancel = Chirashi.once('.cheese, .wasabi', { click: function (e, target) { console.log('clicked', target) }, 'mouseenter mousemove': function (e, target) { console.log('mouse in', target) } }, true, true) Chirashi.trigger(maki, 'click') //simulate user's click // LOGS: "clicked" <a class="maki cheese"></a> // click event listener was auto-removed from maki Chirashi.trigger(sushi, 'click') //simulate user's click // LOGS: "clicked" <a class="sushi wasabi"></a> // click event listener was auto-removed from sushi cancel() //remove all listeners from all elements Chirashi.once('.cheese, .wasabi', { click: function (e, target) { console.log('clicked', target) } }) Chirashi.trigger(maki, 'click') //simulate user's click // LOGS: "clicked" <a class="maki cheese"></a> // all events listeners were auto-removed from all elements Chirashi.trigger(sushi, 'click') //simulate user's click // won't log anything
[ "Called", "to", "off", "one", "or", "all", "events", "." ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L1582-L1598
train
chirashijs/chirashi
dist/chirashi.common.js
trigger
function trigger(elements, events) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; elements = getElements(elements); if (!elements.length) return; options = _extends({}, options, defaults$1); forEach(_stringToArray(events), _createEvent.bind(null, elements, options)); return elements; }
javascript
function trigger(elements, events) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; elements = getElements(elements); if (!elements.length) return; options = _extends({}, options, defaults$1); forEach(_stringToArray(events), _createEvent.bind(null, elements, options)); return elements; }
[ "function", "trigger", "(", "elements", ",", "events", ")", "{", "var", "options", "=", "arguments", ".", "length", ">", "2", "&&", "arguments", "[", "2", "]", "!==", "undefined", "?", "arguments", "[", "2", "]", ":", "{", "}", ";", "elements", "=", "getElements", "(", "elements", ")", ";", "if", "(", "!", "elements", ".", "length", ")", "return", ";", "options", "=", "_extends", "(", "{", "}", ",", "options", ",", "defaults$1", ")", ";", "forEach", "(", "_stringToArray", "(", "events", ")", ",", "_createEvent", ".", "bind", "(", "null", ",", "elements", ",", "options", ")", ")", ";", "return", "elements", ";", "}" ]
Trigger events on elements with data @param {(string|Array|NodeList|HTMLCollection|EventTarget)} elements - The iterable, selector or elements. @param {string} events - The events that should be tiggered seperated with spaces @param {Object} data - The events' data @return {Array} iterable - The getElements' result for chaining. @example //esnext import { createElement, append, on, trigger } from 'chirashi' const maki = createElement('a.cheese.maki') const sushi = createElement('a.wasabi.sushi') append(document.body, [maki, sushi]) const listener = on('.cheese, .wasabi', { click(e, target) => { console.log('clicked', target) } }) trigger(maki, 'click') //simulate user's click // LOGS: "clicked" <a class="maki cheese"></a> trigger(sushi, 'click') //simulate user's click // LOGS: "clicked" <a class="sushi wasabi"></a> @example //es5 var listener = Chirashi.bind('.cheese, .wasabi', { 'click': function (e, target) { console.log('clicked', target) } }) var maki = Chirashi.createElement('a.cheese.maki') var sushi = Chirashi.createElement('a.wasabi.sushi') Chirashi.append(document.body, [maki, sushi]) Chirashi.trigger(maki, 'click') //simulate user's click // LOGS: "clicked" <a class="maki cheese"></a> Chirashi.trigger(sushi, 'click') //simulate user's click // LOGS: "clicked" <a class="sushi wasabi"></a>
[ "Trigger", "events", "on", "elements", "with", "data" ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L1667-L1679
train
chirashijs/chirashi
dist/chirashi.common.js
clearStyle
function clearStyle(elements) { var style = {}; for (var _len = arguments.length, props = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { props[_key - 1] = arguments[_key]; } forEach(props, _resetProp.bind(null, style)); return setStyleProp(elements, style); }
javascript
function clearStyle(elements) { var style = {}; for (var _len = arguments.length, props = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { props[_key - 1] = arguments[_key]; } forEach(props, _resetProp.bind(null, style)); return setStyleProp(elements, style); }
[ "function", "clearStyle", "(", "elements", ")", "{", "var", "style", "=", "{", "}", ";", "for", "(", "var", "_len", "=", "arguments", ".", "length", ",", "props", "=", "Array", "(", "_len", ">", "1", "?", "_len", "-", "1", ":", "0", ")", ",", "_key", "=", "1", ";", "_key", "<", "_len", ";", "_key", "++", ")", "{", "props", "[", "_key", "-", "1", "]", "=", "arguments", "[", "_key", "]", ";", "}", "forEach", "(", "props", ",", "_resetProp", ".", "bind", "(", "null", ",", "style", ")", ")", ";", "return", "setStyleProp", "(", "elements", ",", "style", ")", ";", "}" ]
Clear inline style properties from elements. @param {(string|Array|NodeList|HTMLCollection|HTMLElement)} elements - The iterable, selector or elements. @param {...string} props - The style properties to clear. @return {Array} iterable - The getElements' result for chaining. @example //esnext import { createElement, setStyle, clearStyle } from 'chirashi' const maki = createElement('a.cheese.maki') setStyleProp(maki, { position: 'absolute', top: 10, width: 200, height: 200, background: 'red' }) // returns: [<a class="cheese maki" style="position: 'absolute'; top: '10px'; width: '200px'; height: '200px'; background: 'red';"></a>] clearStyle(maki, 'width', 'height', 'background') // returns: [<a class="cheese maki" style="position: 'absolute'; top: '10px';"></a>] @example //es5 var maki = Chirashi.createElement('a.cheese.maki') Chirashi.setStyleProp(maki, { position: 'absolute', top: 10, width: 200, height: 200, background: 'red' }) // returns: [<a class="cheese maki" style="position: 'absolute'; top: '10px'; width: '200px'; height: '200px'; background: 'red';"></a>] Chirashi.clearStyle(maki, 'width', 'height', 'background') // returns: [<a class="cheese maki" style="position: 'absolute'; top: '10px';"></a>]
[ "Clear", "inline", "style", "properties", "from", "elements", "." ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L1804-L1814
train
chirashijs/chirashi
dist/chirashi.common.js
getHeight
function getHeight(element) { var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return _getLength(element, 'Height', offset); }
javascript
function getHeight(element) { var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return _getLength(element, 'Height', offset); }
[ "function", "getHeight", "(", "element", ")", "{", "var", "offset", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "false", ";", "return", "_getLength", "(", "element", ",", "'Height'", ",", "offset", ")", ";", "}" ]
Get element's height in pixels. @param {(string|Array|NodeList|HTMLCollection|Element|HTMLElement)} element - The element. Note that it'll be passed to getElement to ensure there's only one. @param {boolean} [offset=false] - If true height will include scrollbar and borders to size. @return {number} height - The height in pixels. @example //esnext import { append, setStyleProp, getHeight } from 'chirashi' append(document.body, '.maki') const maki = setStyleProp('.maki', { display: 'block', border: '20px solid red', padding: 10, height: 200, width: 200 }) getHeight(maki, true) //returns: 260 getHeight(maki) //returns: 220 @example //es5 Chirashi.append(document.body, '.maki') var maki = Chirashi.setStyleProp('.maki', { display: 'block', border: '20px solid red', padding: 10, height: 200, width: 200 }) Chirashi.getHeight(maki, true) //returns: 260 Chirashi.getHeight(maki) //returns: 220
[ "Get", "element", "s", "height", "in", "pixels", "." ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L1950-L1954
train
chirashijs/chirashi
dist/chirashi.common.js
getWidth
function getWidth(element) { var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return _getLength(element, 'Width', offset); }
javascript
function getWidth(element) { var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return _getLength(element, 'Width', offset); }
[ "function", "getWidth", "(", "element", ")", "{", "var", "offset", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "false", ";", "return", "_getLength", "(", "element", ",", "'Width'", ",", "offset", ")", ";", "}" ]
Get element's width in pixels. @param {(string|Array|NodeList|HTMLCollection|Element|HTMLElement)} element - The element. Note that it'll be passed to getElement to ensure there's only one. @param {boolean} [offset=false] - If true width will include scrollbar and borders to size. @return {number} width - The width in pixels. @example //esnext import { append, setStyleProp, getWidth } from 'chirashi' append(document.body, '.maki') const maki = setStyleProp('.maki', { display: 'block', border: '20px solid red', padding: 10, height: 200, width: 200 }) getWidth(maki, true) //returns: 260 getWidth(maki) //returns: 220 @example //es5 Chirashi.append(document.body, '.maki') var maki = Chirashi.setStyleProp('.maki', { display: 'block', border: '20px solid red', padding: 10, height: 200, width: 200 }) Chirashi.getWidth(maki, true) //returns: 260 Chirashi.getWidth(maki) //returns: 220
[ "Get", "element", "s", "width", "in", "pixels", "." ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L1985-L1989
train
chirashijs/chirashi
dist/chirashi.common.js
getSize
function getSize(element) { var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return { width: getWidth(element, offset), height: getHeight(element, offset) }; }
javascript
function getSize(element) { var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return { width: getWidth(element, offset), height: getHeight(element, offset) }; }
[ "function", "getSize", "(", "element", ")", "{", "var", "offset", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "false", ";", "return", "{", "width", ":", "getWidth", "(", "element", ",", "offset", ")", ",", "height", ":", "getHeight", "(", "element", ",", "offset", ")", "}", ";", "}" ]
Get element's size in pixels. @param {(string|Array|NodeList|HTMLCollection|Element|HTMLElement)} element - The element. Note that it'll be passed to getElement to ensure there's only one. @param {boolean} [offset=false] - If true size will include scrollbar and borders. @return {number} size - The size in pixels. @example //esnext import { append, setStyleProp, getSize } from 'chirashi' append(document.body, '.maki') const maki = setStyleProp('.maki', { display: 'block', border: '20px solid red', padding: 10, height: 200, width: 200 }) getSize(maki, true) //returns: { width: 260, height: 260 } getSize(maki) //returns: { width: 220, height: 220 } @example //es5 Chirashi.append(document.body, '.maki') var maki = Chirashi.setStyleProp('.maki', { display: 'block', border: '20px solid red', padding: 10, height: 200, width: 200 }) Chirashi.getSize(maki, true) //returns: { width: 260, height: 260 } Chirashi.getSize(maki) //returns: { width: 220, height: 220 }
[ "Get", "element", "s", "size", "in", "pixels", "." ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L2020-L2027
train
chirashijs/chirashi
dist/chirashi.common.js
getStyleProp
function getStyleProp(element) { var computedStyle = getComputedStyle(element); if (!computedStyle) return false; for (var _len = arguments.length, props = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { props[_key - 1] = arguments[_key]; } return _getOneOrMore(props, _parseProp.bind(null, computedStyle)); }
javascript
function getStyleProp(element) { var computedStyle = getComputedStyle(element); if (!computedStyle) return false; for (var _len = arguments.length, props = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { props[_key - 1] = arguments[_key]; } return _getOneOrMore(props, _parseProp.bind(null, computedStyle)); }
[ "function", "getStyleProp", "(", "element", ")", "{", "var", "computedStyle", "=", "getComputedStyle", "(", "element", ")", ";", "if", "(", "!", "computedStyle", ")", "return", "false", ";", "for", "(", "var", "_len", "=", "arguments", ".", "length", ",", "props", "=", "Array", "(", "_len", ">", "1", "?", "_len", "-", "1", ":", "0", ")", ",", "_key", "=", "1", ";", "_key", "<", "_len", ";", "_key", "++", ")", "{", "props", "[", "_key", "-", "1", "]", "=", "arguments", "[", "_key", "]", ";", "}", "return", "_getOneOrMore", "(", "props", ",", "_parseProp", ".", "bind", "(", "null", ",", "computedStyle", ")", ")", ";", "}" ]
Get computed style props of an element. While getComputedStyle returns all properties, getStyleProp returns only needed and convert unitless numeric values or pixels values into numbers. @param {(string|Array|NodeList|HTMLCollection|Element)} element - The element. Note that it'll be passed to getElement to ensure there's only one. @return {(string|number|Object<string, (string|number)>)} computedStyle - Value of computed for provided prop if only one or parsed copy of element's computed style if several. @example //esnext import { append, setStyleProp, getStyleProp } from 'chirashi' append(document.body, '.maki') const maki = setStyleProp('.maki', { display: 'block', position: 'relative', top: 10 }) getStyleProp(maki, 'display', 'top') //returns: { display: "block", top: 10 } @example //es5 Chirashi.append(document.body, '.maki') var maki = Chirashi.setStyleProp('.maki', { display: 'block', position: 'relative', top: 10 }) Chirashi.getStyleProp(maki, 'display', 'top') //returns: { display: "block", top: 10 }
[ "Get", "computed", "style", "props", "of", "an", "element", ".", "While", "getComputedStyle", "returns", "all", "properties", "getStyleProp", "returns", "only", "needed", "and", "convert", "unitless", "numeric", "values", "or", "pixels", "values", "into", "numbers", "." ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L2051-L2061
train
chirashijs/chirashi
dist/chirashi.common.js
offset
function offset(element) { var screenPos = screenPosition(element); return screenPos && { top: screenPos.top + window.scrollY, left: screenPos.left + window.scrollX }; }
javascript
function offset(element) { var screenPos = screenPosition(element); return screenPos && { top: screenPos.top + window.scrollY, left: screenPos.left + window.scrollX }; }
[ "function", "offset", "(", "element", ")", "{", "var", "screenPos", "=", "screenPosition", "(", "element", ")", ";", "return", "screenPos", "&&", "{", "top", ":", "screenPos", ".", "top", "+", "window", ".", "scrollY", ",", "left", ":", "screenPos", ".", "left", "+", "window", ".", "scrollX", "}", ";", "}" ]
Returns the top and left offset of an element. Offset is relative to web page. @param {(string|Array|NodeList|HTMLCollection|Element)} element - The element. Note that it'll be passed to getElement to ensure there's only one. @return {(Object|boolean)} offset - Offset object or false if no element found. @return {Object.top} top - Top offset in pixels. @return {Object.left} left - Left offset in pixels. @example //esnext import { setStyleProp, append, offset } setStyleProp([document.documentElement, document.body], { position: 'relative', margin: 0, padding: 0 }) append(document.body, '.sushi') const sushi = setStyleProp('.sushi', { display: 'block', width: 100, height: 100, position: 'absolute', top: 200, left: 240, background: 'red' }) offset(sushi) // returns: { top: 200, left: 240 } @example //es5 Chirashi.setStyleProp([document.documentElement, document.body], { position: 'relative', margin: 0, padding: 0 }) Chirashi.append(document.body, '.sushi') var sushi = Chirashi.setStyleProp('.sushi', { display: 'block', width: 100, height: 100, position: 'absolute', top: 200, left: 240, background: 'red' }) Chirashi.offset(sushi) // returns: { top: 200, left: 240 }
[ "Returns", "the", "top", "and", "left", "offset", "of", "an", "element", ".", "Offset", "is", "relative", "to", "web", "page", "." ]
9efdbccd2f618e1484b0b605e4b7179ddf93fa16
https://github.com/chirashijs/chirashi/blob/9efdbccd2f618e1484b0b605e4b7179ddf93fa16/dist/chirashi.common.js#L2186-L2193
train
socialally/zephyr
lib/zephyr.js
plugin
function plugin(plugins) { var z, method, conf; for(z in plugins) { if(typeof plugins[z] === 'function') { method = plugins[z]; }else{ method = plugins[z].plugin; conf = plugins[z].conf; } if(opts.field && typeof method[opts.field] === 'function') { method = method[opts.field]; } method.call(proto, conf); } return main; }
javascript
function plugin(plugins) { var z, method, conf; for(z in plugins) { if(typeof plugins[z] === 'function') { method = plugins[z]; }else{ method = plugins[z].plugin; conf = plugins[z].conf; } if(opts.field && typeof method[opts.field] === 'function') { method = method[opts.field]; } method.call(proto, conf); } return main; }
[ "function", "plugin", "(", "plugins", ")", "{", "var", "z", ",", "method", ",", "conf", ";", "for", "(", "z", "in", "plugins", ")", "{", "if", "(", "typeof", "plugins", "[", "z", "]", "===", "'function'", ")", "{", "method", "=", "plugins", "[", "z", "]", ";", "}", "else", "{", "method", "=", "plugins", "[", "z", "]", ".", "plugin", ";", "conf", "=", "plugins", "[", "z", "]", ".", "conf", ";", "}", "if", "(", "opts", ".", "field", "&&", "typeof", "method", "[", "opts", ".", "field", "]", "===", "'function'", ")", "{", "method", "=", "method", "[", "opts", ".", "field", "]", ";", "}", "method", ".", "call", "(", "proto", ",", "conf", ")", ";", "}", "return", "main", ";", "}" ]
Plugin method. @param plugins Array of plugin functions.
[ "Plugin", "method", "." ]
47b0bc31b813001bf9e88e023f04ab3616eb0fa9
https://github.com/socialally/zephyr/blob/47b0bc31b813001bf9e88e023f04ab3616eb0fa9/lib/zephyr.js#L21-L36
train
socialally/zephyr
lib/zephyr.js
hook
function hook() { var comp = hook.proxy.apply(null, arguments); for(var i = 0;i < hooks.length;i++) { hooks[i].apply(comp, arguments); } return comp; }
javascript
function hook() { var comp = hook.proxy.apply(null, arguments); for(var i = 0;i < hooks.length;i++) { hooks[i].apply(comp, arguments); } return comp; }
[ "function", "hook", "(", ")", "{", "var", "comp", "=", "hook", ".", "proxy", ".", "apply", "(", "null", ",", "arguments", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "hooks", ".", "length", ";", "i", "++", ")", "{", "hooks", "[", "i", "]", ".", "apply", "(", "comp", ",", "arguments", ")", ";", "}", "return", "comp", ";", "}" ]
Invoke constructor hooks by proxying to the main construct function and invoking registered hook functions in the scope of the created component.
[ "Invoke", "constructor", "hooks", "by", "proxying", "to", "the", "main", "construct", "function", "and", "invoking", "registered", "hook", "functions", "in", "the", "scope", "of", "the", "created", "component", "." ]
47b0bc31b813001bf9e88e023f04ab3616eb0fa9
https://github.com/socialally/zephyr/blob/47b0bc31b813001bf9e88e023f04ab3616eb0fa9/lib/zephyr.js#L56-L62
train
ssbc/graphreduce
traverse.js
widthTraverse
function widthTraverse (graph, reachable, start, depth, hops, iter) { if(!start) throw new Error('Graphmitter#traverse: start must be provided') //var nodes = 1 reachable[start] = reachable[start] == null ? 0 : reachable[start] var queue = [start] //{key: start, hops: depth}] iter = iter || function () {} while(queue.length) { var o = queue.shift() var h = reachable[o] var node = graph[o] if(node && (!hops || (h + 1 <= hops))) for(var k in node) { // If we have already been to this node by a shorter path, // then skip this node (this only happens when processing // a realtime edge) if(!(reachable[k] != null && reachable[k] < h + 1)) { if(false === iter(o, k, h + 1, reachable[k])) return reachable reachable[k] = h + 1 // nodes ++ queue.push(k) } } } return reachable }
javascript
function widthTraverse (graph, reachable, start, depth, hops, iter) { if(!start) throw new Error('Graphmitter#traverse: start must be provided') //var nodes = 1 reachable[start] = reachable[start] == null ? 0 : reachable[start] var queue = [start] //{key: start, hops: depth}] iter = iter || function () {} while(queue.length) { var o = queue.shift() var h = reachable[o] var node = graph[o] if(node && (!hops || (h + 1 <= hops))) for(var k in node) { // If we have already been to this node by a shorter path, // then skip this node (this only happens when processing // a realtime edge) if(!(reachable[k] != null && reachable[k] < h + 1)) { if(false === iter(o, k, h + 1, reachable[k])) return reachable reachable[k] = h + 1 // nodes ++ queue.push(k) } } } return reachable }
[ "function", "widthTraverse", "(", "graph", ",", "reachable", ",", "start", ",", "depth", ",", "hops", ",", "iter", ")", "{", "if", "(", "!", "start", ")", "throw", "new", "Error", "(", "'Graphmitter#traverse: start must be provided'", ")", "reachable", "[", "start", "]", "=", "reachable", "[", "start", "]", "==", "null", "?", "0", ":", "reachable", "[", "start", "]", "var", "queue", "=", "[", "start", "]", "iter", "=", "iter", "||", "function", "(", ")", "{", "}", "while", "(", "queue", ".", "length", ")", "{", "var", "o", "=", "queue", ".", "shift", "(", ")", "var", "h", "=", "reachable", "[", "o", "]", "var", "node", "=", "graph", "[", "o", "]", "if", "(", "node", "&&", "(", "!", "hops", "||", "(", "h", "+", "1", "<=", "hops", ")", ")", ")", "for", "(", "var", "k", "in", "node", ")", "{", "if", "(", "!", "(", "reachable", "[", "k", "]", "!=", "null", "&&", "reachable", "[", "k", "]", "<", "h", "+", "1", ")", ")", "{", "if", "(", "false", "===", "iter", "(", "o", ",", "k", ",", "h", "+", "1", ",", "reachable", "[", "k", "]", ")", ")", "return", "reachable", "reachable", "[", "k", "]", "=", "h", "+", "1", "queue", ".", "push", "(", "k", ")", "}", "}", "}", "return", "reachable", "}" ]
mutates `reachable`, btw
[ "mutates", "reachable", "btw" ]
a553abbb95a2237e98fcebe91fdcd92cc6cb6ea0
https://github.com/ssbc/graphreduce/blob/a553abbb95a2237e98fcebe91fdcd92cc6cb6ea0/traverse.js#L33-L64
train
ssbc/graphreduce
traverse.js
toArray
function toArray (span, root) { if(!span[root]) return null var a = [root] while(span[root]) a.push(root = span[root]) return a.reverse() }
javascript
function toArray (span, root) { if(!span[root]) return null var a = [root] while(span[root]) a.push(root = span[root]) return a.reverse() }
[ "function", "toArray", "(", "span", ",", "root", ")", "{", "if", "(", "!", "span", "[", "root", "]", ")", "return", "null", "var", "a", "=", "[", "root", "]", "while", "(", "span", "[", "root", "]", ")", "a", ".", "push", "(", "root", "=", "span", "[", "root", "]", ")", "return", "a", ".", "reverse", "(", ")", "}" ]
find the shortest path between two nodes. if there was no path within max hops, return null. convert a spanning tree to an array.
[ "find", "the", "shortest", "path", "between", "two", "nodes", ".", "if", "there", "was", "no", "path", "within", "max", "hops", "return", "null", ".", "convert", "a", "spanning", "tree", "to", "an", "array", "." ]
a553abbb95a2237e98fcebe91fdcd92cc6cb6ea0
https://github.com/ssbc/graphreduce/blob/a553abbb95a2237e98fcebe91fdcd92cc6cb6ea0/traverse.js#L116-L122
train
myelements/myelements.jquery
lib/client/lib/can.view/can.custom.js
function(oldObserved, newObserveSet, onchanged) { for (var name in newObserveSet) { bindOrPreventUnbinding(oldObserved, newObserveSet, name, onchanged); } }
javascript
function(oldObserved, newObserveSet, onchanged) { for (var name in newObserveSet) { bindOrPreventUnbinding(oldObserved, newObserveSet, name, onchanged); } }
[ "function", "(", "oldObserved", ",", "newObserveSet", ",", "onchanged", ")", "{", "for", "(", "var", "name", "in", "newObserveSet", ")", "{", "bindOrPreventUnbinding", "(", "oldObserved", ",", "newObserveSet", ",", "name", ",", "onchanged", ")", ";", "}", "}" ]
This will not be optimized.
[ "This", "will", "not", "be", "optimized", "." ]
0123edec30fc70ea494611695b5b2593e4f23745
https://github.com/myelements/myelements.jquery/blob/0123edec30fc70ea494611695b5b2593e4f23745/lib/client/lib/can.view/can.custom.js#L1066-L1070
train
myelements/myelements.jquery
lib/client/lib/can.view/can.custom.js
function(oldObserved, newObserveSet, name, onchanged) { if (oldObserved[name]) { // After binding is set up, values // in `oldObserved` will be unbound. So if a name // has already be observed, remove from `oldObserved` // to prevent this. delete oldObserved[name]; } else { // If current name has not been observed, listen to it. var obEv = newObserveSet[name]; obEv.obj.bind(obEv.event, onchanged); } }
javascript
function(oldObserved, newObserveSet, name, onchanged) { if (oldObserved[name]) { // After binding is set up, values // in `oldObserved` will be unbound. So if a name // has already be observed, remove from `oldObserved` // to prevent this. delete oldObserved[name]; } else { // If current name has not been observed, listen to it. var obEv = newObserveSet[name]; obEv.obj.bind(obEv.event, onchanged); } }
[ "function", "(", "oldObserved", ",", "newObserveSet", ",", "name", ",", "onchanged", ")", "{", "if", "(", "oldObserved", "[", "name", "]", ")", "{", "delete", "oldObserved", "[", "name", "]", ";", "}", "else", "{", "var", "obEv", "=", "newObserveSet", "[", "name", "]", ";", "obEv", ".", "obj", ".", "bind", "(", "obEv", ".", "event", ",", "onchanged", ")", ";", "}", "}" ]
This will be optimized.
[ "This", "will", "be", "optimized", "." ]
0123edec30fc70ea494611695b5b2593e4f23745
https://github.com/myelements/myelements.jquery/blob/0123edec30fc70ea494611695b5b2593e4f23745/lib/client/lib/can.view/can.custom.js#L1072-L1084
train
caleb/broccoli-fast-browserify
index.js
function() { bundle.browserify.pipeline.get('deps').push(through.obj(function(row, enc, next) { var file = row.expose ? bundle.browserify._expose[row.id] : row.file; if (self.cache) { bundle.browserifyOptions.cache[file] = { source: row.source, deps: xtend({}, row.deps) }; } this.push(row); next(); })); }
javascript
function() { bundle.browserify.pipeline.get('deps').push(through.obj(function(row, enc, next) { var file = row.expose ? bundle.browserify._expose[row.id] : row.file; if (self.cache) { bundle.browserifyOptions.cache[file] = { source: row.source, deps: xtend({}, row.deps) }; } this.push(row); next(); })); }
[ "function", "(", ")", "{", "bundle", ".", "browserify", ".", "pipeline", ".", "get", "(", "'deps'", ")", ".", "push", "(", "through", ".", "obj", "(", "function", "(", "row", ",", "enc", ",", "next", ")", "{", "var", "file", "=", "row", ".", "expose", "?", "bundle", ".", "browserify", ".", "_expose", "[", "row", ".", "id", "]", ":", "row", ".", "file", ";", "if", "(", "self", ".", "cache", ")", "{", "bundle", ".", "browserifyOptions", ".", "cache", "[", "file", "]", "=", "{", "source", ":", "row", ".", "source", ",", "deps", ":", "xtend", "(", "{", "}", ",", "row", ".", "deps", ")", "}", ";", "}", "this", ".", "push", "(", "row", ")", ";", "next", "(", ")", ";", "}", ")", ")", ";", "}" ]
Watch dependencies for changes and invalidate the cache when needed
[ "Watch", "dependencies", "for", "changes", "and", "invalidate", "the", "cache", "when", "needed" ]
01c358827a49ec4f02cb363825a5e2661473c121
https://github.com/caleb/broccoli-fast-browserify/blob/01c358827a49ec4f02cb363825a5e2661473c121/index.js#L220-L234
train
localvoid/iko
packages/karma-iko/lib/reporter.js
IkoReporter
function IkoReporter(baseReporterDecorator, config, loggerFactory, formatError) { // extend the base reporter baseReporterDecorator(this); const logger = loggerFactory.create("reporter.iko"); const divider = "=".repeat(process.stdout.columns || 80); let slow = 0; let totalTime = 0; let netTime = 0; let failedTests = []; let firstRun = true; let isRunCompleted = false; // disable chalk when colors is set to false chalk.enabled = config.colors !== false; const self = this; const write = function () { for (let i = 0; i < arguments.length; i++) { self.write(arguments[i]); } } this.onSpecComplete = (browser, result) => { const suite = result.suite; const description = result.description; write(Colors.browserName(`${browser.name} `)); if (result.skipped) { write(Colors.testSkip(`${Symbols.info} ${suiteName(suite)}${description}\n`)); } else if (result.success) { write(Colors.testPass(`${Symbols.success} ${suiteName(suite)}${description}`)); if (config.reportSlowerThan && result.time > config.reportSlowerThan) { write(Colors.testSlow(" (slow: " + formatTime(result.time) + ")")); slow++; } write("\n"); } else { failedTests.push({ browser: browser, result: result }); write(Colors.testFail(`${Symbols.error} ${suiteName(suite)}${description}\n`)); } }; this.onRunStart = () => { if (!firstRun && divider) { write(Colors.divider(`${divider}\n\n`)); } failedTests = []; firstRun = false; isRunCompleted = false; totalTime = 0; netTime = 0; slow = 0; }; this.onBrowserStart = () => { }; this.onRunComplete = (browsers, results) => { browsers.forEach(function (browser) { totalTime += browser.lastResult.totalTime; }); // print extra error message for some special cases, e.g. when having the error "Some of your tests did a full page // reload!" the onRunComplete() method is called twice if (results.error && isRunCompleted) { write("\n"); write(colors.error(`${Symbols.error} Error while running the tests! Exit code: ${results.exitCode}\n\n`)); return; } isRunCompleted = true; const currentTime = new Date().toTimeString(); write(Colors.duration(`\n Finished in ${formatTime(totalTime)} / ${formatTime(netTime)} @ ${currentTime}\n\n`)); if (browsers.length > 0 && !results.disconnected) { write(Colors.testPass(` ${Symbols.success} ${results.success} ${getTestNounFor(results.success)} completed\n`)); if (slow) { write(Colors.testSlow(` ${Symbols.warning} ${slow} ${getTestNounFor(slow)} slow\n`)); } if (results.failed) { write(Colors.testFail(` ${Symbols.error} ${results.failed} ${getTestNounFor(results.failed)} failed\n\n`)); write(Colors.sectionTitle("FAILED TESTS:\n\n")); failedTests.forEach(function (failedTest) { const browser = failedTest.browser; const result = failedTest.result; const logs = result.log; const assertionErrors = result.assertionErrors; write(Colors.browserName(browser.name), "\n"); write(Colors.errorTitle(` ${Symbols.error} ${suiteName(result.suite)}${result.description}\n\n`)); if (assertionErrors.length > 0) { for (let i = 0; i < assertionErrors.length; i++) { const error = assertionErrors[i]; const rawMessage = error.message; const message = renderAssertionError({ text: rawMessage, annotations: error.annotations }); let stack = error.stack; if (rawMessage) { const index = stack.indexOf(rawMessage); if (index !== -1) { stack = stack.slice(index + rawMessage.length + 1); } } stack = leftPad(" ", stack); write(leftPad(" ", message), "\n"); write(Colors.errorStack(formatError(stack)), "\n"); } } else if (logs.length > 0) { for (let i = 0; i < logs.length; i++) { write(Colors.errorMessage(leftPad(" ", formatError(logs[i]))), "\n"); } } }); } } write("\n"); }; }
javascript
function IkoReporter(baseReporterDecorator, config, loggerFactory, formatError) { // extend the base reporter baseReporterDecorator(this); const logger = loggerFactory.create("reporter.iko"); const divider = "=".repeat(process.stdout.columns || 80); let slow = 0; let totalTime = 0; let netTime = 0; let failedTests = []; let firstRun = true; let isRunCompleted = false; // disable chalk when colors is set to false chalk.enabled = config.colors !== false; const self = this; const write = function () { for (let i = 0; i < arguments.length; i++) { self.write(arguments[i]); } } this.onSpecComplete = (browser, result) => { const suite = result.suite; const description = result.description; write(Colors.browserName(`${browser.name} `)); if (result.skipped) { write(Colors.testSkip(`${Symbols.info} ${suiteName(suite)}${description}\n`)); } else if (result.success) { write(Colors.testPass(`${Symbols.success} ${suiteName(suite)}${description}`)); if (config.reportSlowerThan && result.time > config.reportSlowerThan) { write(Colors.testSlow(" (slow: " + formatTime(result.time) + ")")); slow++; } write("\n"); } else { failedTests.push({ browser: browser, result: result }); write(Colors.testFail(`${Symbols.error} ${suiteName(suite)}${description}\n`)); } }; this.onRunStart = () => { if (!firstRun && divider) { write(Colors.divider(`${divider}\n\n`)); } failedTests = []; firstRun = false; isRunCompleted = false; totalTime = 0; netTime = 0; slow = 0; }; this.onBrowserStart = () => { }; this.onRunComplete = (browsers, results) => { browsers.forEach(function (browser) { totalTime += browser.lastResult.totalTime; }); // print extra error message for some special cases, e.g. when having the error "Some of your tests did a full page // reload!" the onRunComplete() method is called twice if (results.error && isRunCompleted) { write("\n"); write(colors.error(`${Symbols.error} Error while running the tests! Exit code: ${results.exitCode}\n\n`)); return; } isRunCompleted = true; const currentTime = new Date().toTimeString(); write(Colors.duration(`\n Finished in ${formatTime(totalTime)} / ${formatTime(netTime)} @ ${currentTime}\n\n`)); if (browsers.length > 0 && !results.disconnected) { write(Colors.testPass(` ${Symbols.success} ${results.success} ${getTestNounFor(results.success)} completed\n`)); if (slow) { write(Colors.testSlow(` ${Symbols.warning} ${slow} ${getTestNounFor(slow)} slow\n`)); } if (results.failed) { write(Colors.testFail(` ${Symbols.error} ${results.failed} ${getTestNounFor(results.failed)} failed\n\n`)); write(Colors.sectionTitle("FAILED TESTS:\n\n")); failedTests.forEach(function (failedTest) { const browser = failedTest.browser; const result = failedTest.result; const logs = result.log; const assertionErrors = result.assertionErrors; write(Colors.browserName(browser.name), "\n"); write(Colors.errorTitle(` ${Symbols.error} ${suiteName(result.suite)}${result.description}\n\n`)); if (assertionErrors.length > 0) { for (let i = 0; i < assertionErrors.length; i++) { const error = assertionErrors[i]; const rawMessage = error.message; const message = renderAssertionError({ text: rawMessage, annotations: error.annotations }); let stack = error.stack; if (rawMessage) { const index = stack.indexOf(rawMessage); if (index !== -1) { stack = stack.slice(index + rawMessage.length + 1); } } stack = leftPad(" ", stack); write(leftPad(" ", message), "\n"); write(Colors.errorStack(formatError(stack)), "\n"); } } else if (logs.length > 0) { for (let i = 0; i < logs.length; i++) { write(Colors.errorMessage(leftPad(" ", formatError(logs[i]))), "\n"); } } }); } } write("\n"); }; }
[ "function", "IkoReporter", "(", "baseReporterDecorator", ",", "config", ",", "loggerFactory", ",", "formatError", ")", "{", "baseReporterDecorator", "(", "this", ")", ";", "const", "logger", "=", "loggerFactory", ".", "create", "(", "\"reporter.iko\"", ")", ";", "const", "divider", "=", "\"=\"", ".", "repeat", "(", "process", ".", "stdout", ".", "columns", "||", "80", ")", ";", "let", "slow", "=", "0", ";", "let", "totalTime", "=", "0", ";", "let", "netTime", "=", "0", ";", "let", "failedTests", "=", "[", "]", ";", "let", "firstRun", "=", "true", ";", "let", "isRunCompleted", "=", "false", ";", "chalk", ".", "enabled", "=", "config", ".", "colors", "!==", "false", ";", "const", "self", "=", "this", ";", "const", "write", "=", "function", "(", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "self", ".", "write", "(", "arguments", "[", "i", "]", ")", ";", "}", "}", "this", ".", "onSpecComplete", "=", "(", "browser", ",", "result", ")", "=>", "{", "const", "suite", "=", "result", ".", "suite", ";", "const", "description", "=", "result", ".", "description", ";", "write", "(", "Colors", ".", "browserName", "(", "`", "${", "browser", ".", "name", "}", "`", ")", ")", ";", "if", "(", "result", ".", "skipped", ")", "{", "write", "(", "Colors", ".", "testSkip", "(", "`", "${", "Symbols", ".", "info", "}", "${", "suiteName", "(", "suite", ")", "}", "${", "description", "}", "\\n", "`", ")", ")", ";", "}", "else", "if", "(", "result", ".", "success", ")", "{", "write", "(", "Colors", ".", "testPass", "(", "`", "${", "Symbols", ".", "success", "}", "${", "suiteName", "(", "suite", ")", "}", "${", "description", "}", "`", ")", ")", ";", "if", "(", "config", ".", "reportSlowerThan", "&&", "result", ".", "time", ">", "config", ".", "reportSlowerThan", ")", "{", "write", "(", "Colors", ".", "testSlow", "(", "\" (slow: \"", "+", "formatTime", "(", "result", ".", "time", ")", "+", "\")\"", ")", ")", ";", "slow", "++", ";", "}", "write", "(", "\"\\n\"", ")", ";", "}", "else", "\\n", "}", ";", "{", "failedTests", ".", "push", "(", "{", "browser", ":", "browser", ",", "result", ":", "result", "}", ")", ";", "write", "(", "Colors", ".", "testFail", "(", "`", "${", "Symbols", ".", "error", "}", "${", "suiteName", "(", "suite", ")", "}", "${", "description", "}", "\\n", "`", ")", ")", ";", "}", "this", ".", "onRunStart", "=", "(", ")", "=>", "{", "if", "(", "!", "firstRun", "&&", "divider", ")", "{", "write", "(", "Colors", ".", "divider", "(", "`", "${", "divider", "}", "\\n", "\\n", "`", ")", ")", ";", "}", "failedTests", "=", "[", "]", ";", "firstRun", "=", "false", ";", "isRunCompleted", "=", "false", ";", "totalTime", "=", "0", ";", "netTime", "=", "0", ";", "slow", "=", "0", ";", "}", ";", "this", ".", "onBrowserStart", "=", "(", ")", "=>", "{", "}", ";", "}" ]
The IkoReporter. @param {!object} baseReporterDecorator The karma base reporter. @param {!object} config The karma config. @param {!object} loggerFactory The karma logger factory. @constructor
[ "The", "IkoReporter", "." ]
640cb45fefacfff20da449d74b9de2f4e7baf15e
https://github.com/localvoid/iko/blob/640cb45fefacfff20da449d74b9de2f4e7baf15e/packages/karma-iko/lib/reporter.js#L82-L211
train
thehivecorporation/git-command-line
index.js
function(options){ if (!options) { options = { cwd: workingDirectory }; return options; } else { workingDirectory = options.cwd; return options; } }
javascript
function(options){ if (!options) { options = { cwd: workingDirectory }; return options; } else { workingDirectory = options.cwd; return options; } }
[ "function", "(", "options", ")", "{", "if", "(", "!", "options", ")", "{", "options", "=", "{", "cwd", ":", "workingDirectory", "}", ";", "return", "options", ";", "}", "else", "{", "workingDirectory", "=", "options", ".", "cwd", ";", "return", "options", ";", "}", "}" ]
Prepare options to use the set working directory in the following commands @param options @returns {*}
[ "Prepare", "options", "to", "use", "the", "set", "working", "directory", "in", "the", "following", "commands" ]
8af0fb07332696f7f85a4a30b312f3e6b27e2d5d
https://github.com/thehivecorporation/git-command-line/blob/8af0fb07332696f7f85a4a30b312f3e6b27e2d5d/index.js#L341-L352
train
thehivecorporation/git-command-line
index.js
function (command, options) { var exec = require('child_process').exec; var defer = Q.defer(); //Prepare the options object to be valid options = prepareOptions(options); //Activate-Deactivate command logging execution printCommandExecution(command, options); exec('git ' + prepareCommand(command), options, function (err, stdout, stderr) { //Activate-deactivate err and out logging printCommandResponse({err:err, stdout:stdout, stderr:stderr}); if (err) { defer.reject({err: err, stderr: stderr}); } else { defer.resolve({res:stdout, out:stderr}); } }); return defer.promise; }
javascript
function (command, options) { var exec = require('child_process').exec; var defer = Q.defer(); //Prepare the options object to be valid options = prepareOptions(options); //Activate-Deactivate command logging execution printCommandExecution(command, options); exec('git ' + prepareCommand(command), options, function (err, stdout, stderr) { //Activate-deactivate err and out logging printCommandResponse({err:err, stdout:stdout, stderr:stderr}); if (err) { defer.reject({err: err, stderr: stderr}); } else { defer.resolve({res:stdout, out:stderr}); } }); return defer.promise; }
[ "function", "(", "command", ",", "options", ")", "{", "var", "exec", "=", "require", "(", "'child_process'", ")", ".", "exec", ";", "var", "defer", "=", "Q", ".", "defer", "(", ")", ";", "options", "=", "prepareOptions", "(", "options", ")", ";", "printCommandExecution", "(", "command", ",", "options", ")", ";", "exec", "(", "'git '", "+", "prepareCommand", "(", "command", ")", ",", "options", ",", "function", "(", "err", ",", "stdout", ",", "stderr", ")", "{", "printCommandResponse", "(", "{", "err", ":", "err", ",", "stdout", ":", "stdout", ",", "stderr", ":", "stderr", "}", ")", ";", "if", "(", "err", ")", "{", "defer", ".", "reject", "(", "{", "err", ":", "err", ",", "stderr", ":", "stderr", "}", ")", ";", "}", "else", "{", "defer", ".", "resolve", "(", "{", "res", ":", "stdout", ",", "out", ":", "stderr", "}", ")", ";", "}", "}", ")", ";", "return", "defer", ".", "promise", ";", "}" ]
Main function to use the command line tools to execute git commands @param command Command to execute. Do not include 'git ' prefix @param options Options available in exec command https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback @returns {promise|*|Q.promise}
[ "Main", "function", "to", "use", "the", "command", "line", "tools", "to", "execute", "git", "commands" ]
8af0fb07332696f7f85a4a30b312f3e6b27e2d5d
https://github.com/thehivecorporation/git-command-line/blob/8af0fb07332696f7f85a4a30b312f3e6b27e2d5d/index.js#L380-L402
train
jscheel/metalsmith-encode-html
lib/index.js
plugin
function plugin(options){ options = options || {}; var keys = options.keys || []; return function(files, metalsmith, done){ setImmediate(done); Object.keys(files).forEach(function(file){ debug('checking file: %s', file); if (!isHtml(file)) return; var data = files[file]; var dir = dirname(file); var html = basename(file, extname(file)) + '.html'; if ('.' != dir) html = dir + '/' + html; debug('Encoding html entities in file: %s', file); var reg = /\`\`\`([\s\S]+?)\`\`\`/gi; var rep = function(match, group) { if (group) { return he.encode(group, {useNamedReferences: true}); } else { return ""; } }; var encoded = data.contents.toString().replace(reg, rep); data.contents = new Buffer(encoded); keys.forEach(function(key) { data[key] = data[key].replace(reg, rep); }); delete files[file]; files[html] = data; }); }; }
javascript
function plugin(options){ options = options || {}; var keys = options.keys || []; return function(files, metalsmith, done){ setImmediate(done); Object.keys(files).forEach(function(file){ debug('checking file: %s', file); if (!isHtml(file)) return; var data = files[file]; var dir = dirname(file); var html = basename(file, extname(file)) + '.html'; if ('.' != dir) html = dir + '/' + html; debug('Encoding html entities in file: %s', file); var reg = /\`\`\`([\s\S]+?)\`\`\`/gi; var rep = function(match, group) { if (group) { return he.encode(group, {useNamedReferences: true}); } else { return ""; } }; var encoded = data.contents.toString().replace(reg, rep); data.contents = new Buffer(encoded); keys.forEach(function(key) { data[key] = data[key].replace(reg, rep); }); delete files[file]; files[html] = data; }); }; }
[ "function", "plugin", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "keys", "=", "options", ".", "keys", "||", "[", "]", ";", "return", "function", "(", "files", ",", "metalsmith", ",", "done", ")", "{", "setImmediate", "(", "done", ")", ";", "Object", ".", "keys", "(", "files", ")", ".", "forEach", "(", "function", "(", "file", ")", "{", "debug", "(", "'checking file: %s'", ",", "file", ")", ";", "if", "(", "!", "isHtml", "(", "file", ")", ")", "return", ";", "var", "data", "=", "files", "[", "file", "]", ";", "var", "dir", "=", "dirname", "(", "file", ")", ";", "var", "html", "=", "basename", "(", "file", ",", "extname", "(", "file", ")", ")", "+", "'.html'", ";", "if", "(", "'.'", "!=", "dir", ")", "html", "=", "dir", "+", "'/'", "+", "html", ";", "debug", "(", "'Encoding html entities in file: %s'", ",", "file", ")", ";", "var", "reg", "=", "/", "\\`\\`\\`([\\s\\S]+?)\\`\\`\\`", "/", "gi", ";", "var", "rep", "=", "function", "(", "match", ",", "group", ")", "{", "if", "(", "group", ")", "{", "return", "he", ".", "encode", "(", "group", ",", "{", "useNamedReferences", ":", "true", "}", ")", ";", "}", "else", "{", "return", "\"\"", ";", "}", "}", ";", "var", "encoded", "=", "data", ".", "contents", ".", "toString", "(", ")", ".", "replace", "(", "reg", ",", "rep", ")", ";", "data", ".", "contents", "=", "new", "Buffer", "(", "encoded", ")", ";", "keys", ".", "forEach", "(", "function", "(", "key", ")", "{", "data", "[", "key", "]", "=", "data", "[", "key", "]", ".", "replace", "(", "reg", ",", "rep", ")", ";", "}", ")", ";", "delete", "files", "[", "file", "]", ";", "files", "[", "html", "]", "=", "data", ";", "}", ")", ";", "}", ";", "}" ]
Metalsmith plugin to encode html entities in html files. @param {Object} options (optional) @property {Array} keys @return {Function}
[ "Metalsmith", "plugin", "to", "encode", "html", "entities", "in", "html", "files", "." ]
f3d728a776aef1702b0dcb9810908dbe7d19ce81
https://github.com/jscheel/metalsmith-encode-html/blob/f3d728a776aef1702b0dcb9810908dbe7d19ce81/lib/index.js#L22-L58
train
PAI-Tech/PAI-BOT-JS
src/pai-bot/src/module-ext/learn.js
npmInstall
function npmInstall(packageName) { return new Promise((resolve,reject) => { npm.load({ save:false, progress: false, force:true }, function (er) { if (er) { PAILogger.error(er); return reject(er); } npm.commands.install([packageName], function (er, data) { if (er) { PAILogger.error(er); return reject(er); } resolve(data); // command succeeded, and data might have some info }); }); }); }
javascript
function npmInstall(packageName) { return new Promise((resolve,reject) => { npm.load({ save:false, progress: false, force:true }, function (er) { if (er) { PAILogger.error(er); return reject(er); } npm.commands.install([packageName], function (er, data) { if (er) { PAILogger.error(er); return reject(er); } resolve(data); // command succeeded, and data might have some info }); }); }); }
[ "function", "npmInstall", "(", "packageName", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "npm", ".", "load", "(", "{", "save", ":", "false", ",", "progress", ":", "false", ",", "force", ":", "true", "}", ",", "function", "(", "er", ")", "{", "if", "(", "er", ")", "{", "PAILogger", ".", "error", "(", "er", ")", ";", "return", "reject", "(", "er", ")", ";", "}", "npm", ".", "commands", ".", "install", "(", "[", "packageName", "]", ",", "function", "(", "er", ",", "data", ")", "{", "if", "(", "er", ")", "{", "PAILogger", ".", "error", "(", "er", ")", ";", "return", "reject", "(", "er", ")", ";", "}", "resolve", "(", "data", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Install new NPM package @param {String} packageName @return {Promise<any>}
[ "Install", "new", "NPM", "package" ]
7744e54f580e18264861e33f2c05aac58b5ad1d9
https://github.com/PAI-Tech/PAI-BOT-JS/blob/7744e54f580e18264861e33f2c05aac58b5ad1d9/src/pai-bot/src/module-ext/learn.js#L56-L83
train
bartve/dot-view
index.js
function(filePath, currentPath){ if(/^(?:\/|[a-zA-Z]:(?:\/|\\))/.test(filePath)){ // Is the path absolute? filePath = path.normalize(filePath); }else{ // Relative paths need to be resolved first filePath = path.resolve(currentPath, filePath); } return filePath; }
javascript
function(filePath, currentPath){ if(/^(?:\/|[a-zA-Z]:(?:\/|\\))/.test(filePath)){ // Is the path absolute? filePath = path.normalize(filePath); }else{ // Relative paths need to be resolved first filePath = path.resolve(currentPath, filePath); } return filePath; }
[ "function", "(", "filePath", ",", "currentPath", ")", "{", "if", "(", "/", "^(?:\\/|[a-zA-Z]:(?:\\/|\\\\))", "/", ".", "test", "(", "filePath", ")", ")", "{", "filePath", "=", "path", ".", "normalize", "(", "filePath", ")", ";", "}", "else", "{", "filePath", "=", "path", ".", "resolve", "(", "currentPath", ",", "filePath", ")", ";", "}", "return", "filePath", ";", "}" ]
Parse absolute and relative path strings to a full path @param {string} filePath @param {string} currentPath @returns {string}
[ "Parse", "absolute", "and", "relative", "path", "strings", "to", "a", "full", "path" ]
580af6937c179d5b9ae05e6f6cd9d61a886f4fc5
https://github.com/bartve/dot-view/blob/580af6937c179d5b9ae05e6f6cd9d61a886f4fc5/index.js#L16-L23
train
bartve/dot-view
index.js
View
function View(tplPath, tplFile, data){ this.data = data||{}; this.defines = {}; this.enabled = true; // Default settings this.settings = doT.templateSettings; this.settings.varname = 'it,helpers'; // Add the helpers as a second data param for the parser this.settings.cache = true; // Use memory cache for compiled template functions this.settings.layout = /\{\{##\s*(?:def\.)?_layout\s*(?:\:|=)\s*([\s\S]+?)\s*#\}\}/; // Layout regex if(tplPath){ this.path = tplPath; } if(tplFile){ this.file = tplFile; this.layout(); } }
javascript
function View(tplPath, tplFile, data){ this.data = data||{}; this.defines = {}; this.enabled = true; // Default settings this.settings = doT.templateSettings; this.settings.varname = 'it,helpers'; // Add the helpers as a second data param for the parser this.settings.cache = true; // Use memory cache for compiled template functions this.settings.layout = /\{\{##\s*(?:def\.)?_layout\s*(?:\:|=)\s*([\s\S]+?)\s*#\}\}/; // Layout regex if(tplPath){ this.path = tplPath; } if(tplFile){ this.file = tplFile; this.layout(); } }
[ "function", "View", "(", "tplPath", ",", "tplFile", ",", "data", ")", "{", "this", ".", "data", "=", "data", "||", "{", "}", ";", "this", ".", "defines", "=", "{", "}", ";", "this", ".", "enabled", "=", "true", ";", "this", ".", "settings", "=", "doT", ".", "templateSettings", ";", "this", ".", "settings", ".", "varname", "=", "'it,helpers'", ";", "this", ".", "settings", ".", "cache", "=", "true", ";", "this", ".", "settings", ".", "layout", "=", "/", "\\{\\{##\\s*(?:def\\.)?_layout\\s*(?:\\:|=)\\s*([\\s\\S]+?)\\s*#\\}\\}", "/", ";", "if", "(", "tplPath", ")", "{", "this", ".", "path", "=", "tplPath", ";", "}", "if", "(", "tplFile", ")", "{", "this", ".", "file", "=", "tplFile", ";", "this", ".", "layout", "(", ")", ";", "}", "}" ]
Object constructor. For quick use, the most important properties can be set in the constructor. @constructor @param {string} [tplPath] - The path of the template file @param {string} [tplFile] - The filename of the template file @param {object} [data={}] - The template data @return {View}
[ "Object", "constructor", ".", "For", "quick", "use", "the", "most", "important", "properties", "can", "be", "set", "in", "the", "constructor", "." ]
580af6937c179d5b9ae05e6f6cd9d61a886f4fc5
https://github.com/bartve/dot-view/blob/580af6937c179d5b9ae05e6f6cd9d61a886f4fc5/index.js#L48-L62
train
Cerealkillerway/versionUpdater
lib/version.js
fullWidth
function fullWidth(text, param) { let cols = process.stdout.columns; let lines = text.split('\n'); for (i = 0; i < lines.length; i++) { let size = cols; if (i === 0) size = size - 15; if ((lines[i].indexOf('%') > 0) && (param !== undefined)) size = size - param.length + 2; while (lines[i].length < size) { lines[i] = lines[i] + ' '; } } text = lines.join('\n'); return text; }
javascript
function fullWidth(text, param) { let cols = process.stdout.columns; let lines = text.split('\n'); for (i = 0; i < lines.length; i++) { let size = cols; if (i === 0) size = size - 15; if ((lines[i].indexOf('%') > 0) && (param !== undefined)) size = size - param.length + 2; while (lines[i].length < size) { lines[i] = lines[i] + ' '; } } text = lines.join('\n'); return text; }
[ "function", "fullWidth", "(", "text", ",", "param", ")", "{", "let", "cols", "=", "process", ".", "stdout", ".", "columns", ";", "let", "lines", "=", "text", ".", "split", "(", "'\\n'", ")", ";", "\\n", "for", "(", "i", "=", "0", ";", "i", "<", "lines", ".", "length", ";", "i", "++", ")", "{", "let", "size", "=", "cols", ";", "if", "(", "i", "===", "0", ")", "size", "=", "size", "-", "15", ";", "if", "(", "(", "lines", "[", "i", "]", ".", "indexOf", "(", "'%'", ")", ">", "0", ")", "&&", "(", "param", "!==", "undefined", ")", ")", "size", "=", "size", "-", "param", ".", "length", "+", "2", ";", "while", "(", "lines", "[", "i", "]", ".", "length", "<", "size", ")", "{", "lines", "[", "i", "]", "=", "lines", "[", "i", "]", "+", "' '", ";", "}", "}", "text", "=", "lines", ".", "join", "(", "'\\n'", ")", ";", "}" ]
make all the lines of a text as long as terminal's width
[ "make", "all", "the", "lines", "of", "a", "text", "as", "long", "as", "terminal", "s", "width" ]
977ef78d990ad6dd9bfd716f860bd05790c442d2
https://github.com/Cerealkillerway/versionUpdater/blob/977ef78d990ad6dd9bfd716f860bd05790c442d2/lib/version.js#L101-L116
train
Cerealkillerway/versionUpdater
lib/version.js
revertInit
function revertInit(reinit, list, prefix, name, currentVersion) { exec('rm -Rf ./.versionFilesList.json', function(error, stdout, stderr) { if (error) sendProcessError(stdout, stderr); print('Deleted previous .versionFilesList.json', 'important', 'date'); if (reinit) init(list, prefix, name, currentVersion); }); }
javascript
function revertInit(reinit, list, prefix, name, currentVersion) { exec('rm -Rf ./.versionFilesList.json', function(error, stdout, stderr) { if (error) sendProcessError(stdout, stderr); print('Deleted previous .versionFilesList.json', 'important', 'date'); if (reinit) init(list, prefix, name, currentVersion); }); }
[ "function", "revertInit", "(", "reinit", ",", "list", ",", "prefix", ",", "name", ",", "currentVersion", ")", "{", "exec", "(", "'rm -Rf ./.versionFilesList.json'", ",", "function", "(", "error", ",", "stdout", ",", "stderr", ")", "{", "if", "(", "error", ")", "sendProcessError", "(", "stdout", ",", "stderr", ")", ";", "print", "(", "'Deleted previous .versionFilesList.json'", ",", "'important'", ",", "'date'", ")", ";", "if", "(", "reinit", ")", "init", "(", "list", ",", "prefix", ",", "name", ",", "currentVersion", ")", ";", "}", ")", ";", "}" ]
delete files list
[ "delete", "files", "list" ]
977ef78d990ad6dd9bfd716f860bd05790c442d2
https://github.com/Cerealkillerway/versionUpdater/blob/977ef78d990ad6dd9bfd716f860bd05790c442d2/lib/version.js#L200-L207
train
Cerealkillerway/versionUpdater
lib/version.js
loadConfiguration
function loadConfiguration() { let configuration; if (isInit()) { configuration = jsonReader('./.versionFilesList.json'); // check configuration file's integrity if (!configuration.name || !configuration.currentVersion || !configuration.filesList || !configuration.versionPrefix) { sendError('E002'); } // check .versionFilesList.json for missing informations if (configuration.name.length === 0 || configuration.currentVersion.length === 0) { sendError('E001'); } } return configuration; }
javascript
function loadConfiguration() { let configuration; if (isInit()) { configuration = jsonReader('./.versionFilesList.json'); // check configuration file's integrity if (!configuration.name || !configuration.currentVersion || !configuration.filesList || !configuration.versionPrefix) { sendError('E002'); } // check .versionFilesList.json for missing informations if (configuration.name.length === 0 || configuration.currentVersion.length === 0) { sendError('E001'); } } return configuration; }
[ "function", "loadConfiguration", "(", ")", "{", "let", "configuration", ";", "if", "(", "isInit", "(", ")", ")", "{", "configuration", "=", "jsonReader", "(", "'./.versionFilesList.json'", ")", ";", "if", "(", "!", "configuration", ".", "name", "||", "!", "configuration", ".", "currentVersion", "||", "!", "configuration", ".", "filesList", "||", "!", "configuration", ".", "versionPrefix", ")", "{", "sendError", "(", "'E002'", ")", ";", "}", "if", "(", "configuration", ".", "name", ".", "length", "===", "0", "||", "configuration", ".", "currentVersion", ".", "length", "===", "0", ")", "{", "sendError", "(", "'E001'", ")", ";", "}", "}", "return", "configuration", ";", "}" ]
load configuration file; fallback to global if is not an initialized folder
[ "load", "configuration", "file", ";", "fallback", "to", "global", "if", "is", "not", "an", "initialized", "folder" ]
977ef78d990ad6dd9bfd716f860bd05790c442d2
https://github.com/Cerealkillerway/versionUpdater/blob/977ef78d990ad6dd9bfd716f860bd05790c442d2/lib/version.js#L211-L228
train
Cerealkillerway/versionUpdater
lib/version.js
discoverVersion
function discoverVersion() { // try to understand package name and current version // from package.json or bower.json let packageFile; let packageFileExtension; let packageType; let results = { name: '', currentVersion: '' }; let possiblePackageFiles = ['package.json', 'bower.json', 'package.js']; for (possiblePackageFile of possiblePackageFiles) { if (fs.existsSync(possiblePackageFile)) { packageFile = possiblePackageFile; break; } } packageFileExtension = packageFile.substr(packageFile.lastIndexOf('.') + 1); if (packageFile) { let packageData; if (packageFileExtension === 'json') { packageData = jsonReader(packageFile); } if (packageFileExtension === 'js') { let tmpData = fs.readFileSync(packageFile).toString().split('\n'); let nameFound = false; let versionFound = false; packageData = {}; for (line of tmpData) { if (line.indexOf('name:') >= 0) { nameFound = true; packageData.name = line.split(' ').pop().replace(/'/g, '').replace(/,/g, ''); } if (line.indexOf('version:') >= 0) { versionFound = true; packageData.version = line.split(' ').pop().replace(/'/g, '').replace(/,/g, ''); } if (nameFound && versionFound) { break; } } } debugLog('Reading packageFile for init:'); debugLog('Discovered pacakge name: ' + packageData.name + ' - discovered package version ' + packageData.version); if (packageData.name) { results.name = packageData.name; } else { print('Can\'t discover package name automatically', 'msgWarning', 'spaced22'); } if (packageData.version) { results.currentVersion = packageData.version; } else { print('Can\'t discover package\'s currentVersion automatically', 'msgWarning', 'spaced22'); } } else { print('Can\'t discover package name and/or currentVersion automatically', 'msgWarning', 'spaced22'); print('Please fill .versionFilesList.json with the missing informations', 'msgWarning', 'spaced22'); } return results; }
javascript
function discoverVersion() { // try to understand package name and current version // from package.json or bower.json let packageFile; let packageFileExtension; let packageType; let results = { name: '', currentVersion: '' }; let possiblePackageFiles = ['package.json', 'bower.json', 'package.js']; for (possiblePackageFile of possiblePackageFiles) { if (fs.existsSync(possiblePackageFile)) { packageFile = possiblePackageFile; break; } } packageFileExtension = packageFile.substr(packageFile.lastIndexOf('.') + 1); if (packageFile) { let packageData; if (packageFileExtension === 'json') { packageData = jsonReader(packageFile); } if (packageFileExtension === 'js') { let tmpData = fs.readFileSync(packageFile).toString().split('\n'); let nameFound = false; let versionFound = false; packageData = {}; for (line of tmpData) { if (line.indexOf('name:') >= 0) { nameFound = true; packageData.name = line.split(' ').pop().replace(/'/g, '').replace(/,/g, ''); } if (line.indexOf('version:') >= 0) { versionFound = true; packageData.version = line.split(' ').pop().replace(/'/g, '').replace(/,/g, ''); } if (nameFound && versionFound) { break; } } } debugLog('Reading packageFile for init:'); debugLog('Discovered pacakge name: ' + packageData.name + ' - discovered package version ' + packageData.version); if (packageData.name) { results.name = packageData.name; } else { print('Can\'t discover package name automatically', 'msgWarning', 'spaced22'); } if (packageData.version) { results.currentVersion = packageData.version; } else { print('Can\'t discover package\'s currentVersion automatically', 'msgWarning', 'spaced22'); } } else { print('Can\'t discover package name and/or currentVersion automatically', 'msgWarning', 'spaced22'); print('Please fill .versionFilesList.json with the missing informations', 'msgWarning', 'spaced22'); } return results; }
[ "function", "discoverVersion", "(", ")", "{", "let", "packageFile", ";", "let", "packageFileExtension", ";", "let", "packageType", ";", "let", "results", "=", "{", "name", ":", "''", ",", "currentVersion", ":", "''", "}", ";", "let", "possiblePackageFiles", "=", "[", "'package.json'", ",", "'bower.json'", ",", "'package.js'", "]", ";", "for", "(", "possiblePackageFile", "of", "possiblePackageFiles", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "possiblePackageFile", ")", ")", "{", "packageFile", "=", "possiblePackageFile", ";", "break", ";", "}", "}", "packageFileExtension", "=", "packageFile", ".", "substr", "(", "packageFile", ".", "lastIndexOf", "(", "'.'", ")", "+", "1", ")", ";", "if", "(", "packageFile", ")", "{", "let", "packageData", ";", "if", "(", "packageFileExtension", "===", "'json'", ")", "{", "packageData", "=", "jsonReader", "(", "packageFile", ")", ";", "}", "if", "(", "packageFileExtension", "===", "'js'", ")", "{", "let", "tmpData", "=", "fs", ".", "readFileSync", "(", "packageFile", ")", ".", "toString", "(", ")", ".", "split", "(", "'\\n'", ")", ";", "\\n", "let", "nameFound", "=", "false", ";", "let", "versionFound", "=", "false", ";", "packageData", "=", "{", "}", ";", "}", "for", "(", "line", "of", "tmpData", ")", "{", "if", "(", "line", ".", "indexOf", "(", "'name:'", ")", ">=", "0", ")", "{", "nameFound", "=", "true", ";", "packageData", ".", "name", "=", "line", ".", "split", "(", "' '", ")", ".", "pop", "(", ")", ".", "replace", "(", "/", "'", "/", "g", ",", "''", ")", ".", "replace", "(", "/", ",", "/", "g", ",", "''", ")", ";", "}", "if", "(", "line", ".", "indexOf", "(", "'version:'", ")", ">=", "0", ")", "{", "versionFound", "=", "true", ";", "packageData", ".", "version", "=", "line", ".", "split", "(", "' '", ")", ".", "pop", "(", ")", ".", "replace", "(", "/", "'", "/", "g", ",", "''", ")", ".", "replace", "(", "/", ",", "/", "g", ",", "''", ")", ";", "}", "if", "(", "nameFound", "&&", "versionFound", ")", "{", "break", ";", "}", "}", "debugLog", "(", "'Reading packageFile for init:'", ")", ";", "debugLog", "(", "'Discovered pacakge name: '", "+", "packageData", ".", "name", "+", "' - discovered package version '", "+", "packageData", ".", "version", ")", ";", "if", "(", "packageData", ".", "name", ")", "{", "results", ".", "name", "=", "packageData", ".", "name", ";", "}", "else", "{", "print", "(", "'Can\\'t discover package name automatically'", ",", "\\'", ",", "'msgWarning'", ")", ";", "}", "}", "else", "'spaced22'", "if", "(", "packageData", ".", "version", ")", "{", "results", ".", "currentVersion", "=", "packageData", ".", "version", ";", "}", "else", "{", "print", "(", "'Can\\'t discover package\\'s currentVersion automatically'", ",", "\\'", ",", "\\'", ")", ";", "}", "}" ]
discover project version
[ "discover", "project", "version" ]
977ef78d990ad6dd9bfd716f860bd05790c442d2
https://github.com/Cerealkillerway/versionUpdater/blob/977ef78d990ad6dd9bfd716f860bd05790c442d2/lib/version.js#L278-L351
train
wooorm/retext-language
index.js
patch
function patch(node, languages) { var data = node.data || {}; var primary = languages[0][0]; data.language = primary === 'und' ? null : primary; data.languages = languages; node.data = data; }
javascript
function patch(node, languages) { var data = node.data || {}; var primary = languages[0][0]; data.language = primary === 'und' ? null : primary; data.languages = languages; node.data = data; }
[ "function", "patch", "(", "node", ",", "languages", ")", "{", "var", "data", "=", "node", ".", "data", "||", "{", "}", ";", "var", "primary", "=", "languages", "[", "0", "]", "[", "0", "]", ";", "data", ".", "language", "=", "primary", "===", "'und'", "?", "null", ":", "primary", ";", "data", ".", "languages", "=", "languages", ";", "node", ".", "data", "=", "data", ";", "}" ]
Patch a `language` and `languages` properties on `node`. @param {NLCSTNode} node - Node. @param {Array.<Array.<string, number>>} languages - Languages.
[ "Patch", "a", "language", "and", "languages", "properties", "on", "node", "." ]
bc2a5b36f7a8e17161f86f0ed78d5e9794942340
https://github.com/wooorm/retext-language/blob/bc2a5b36f7a8e17161f86f0ed78d5e9794942340/index.js#L25-L33
train
wooorm/retext-language
index.js
concatenateFactory
function concatenateFactory() { var queue = []; /** * Gather a parent if not already gathered. * * @param {NLCSTChildNode} node - Child. * @param {number} index - Position of `node` in * `parent`. * @param {NLCSTParentNode} parent - Parent of `child`. */ function concatenate(node, index, parent) { if ( parent && (parent.type === 'ParagraphNode' || parent.type === 'RootNode') && queue.indexOf(parent) === -1 ) { queue.push(parent); } } /** * Patch one parent. * * @param {NLCSTParentNode} node - Parent * @return {Array.<Array.<string, number>>} - Language * map. */ function one(node) { var children = node.children; var length = children.length; var index = -1; var languages; var child; var dictionary = {}; var tuple; while (++index < length) { child = children[index]; languages = child.data && child.data.languages; if (languages) { tuple = languages[0]; if (tuple[0] in dictionary) { dictionary[tuple[0]] += tuple[1]; } else { dictionary[tuple[0]] = tuple[1]; } } } return sortDistanceObject(dictionary); } /** * Patch all parents in reverse order: this means * that first the last and deepest parent is invoked * up to the first and highest parent. */ function done() { var index = queue.length; while (index--) { patch(queue[index], one(queue[index])); } } concatenate.done = done; return concatenate; }
javascript
function concatenateFactory() { var queue = []; /** * Gather a parent if not already gathered. * * @param {NLCSTChildNode} node - Child. * @param {number} index - Position of `node` in * `parent`. * @param {NLCSTParentNode} parent - Parent of `child`. */ function concatenate(node, index, parent) { if ( parent && (parent.type === 'ParagraphNode' || parent.type === 'RootNode') && queue.indexOf(parent) === -1 ) { queue.push(parent); } } /** * Patch one parent. * * @param {NLCSTParentNode} node - Parent * @return {Array.<Array.<string, number>>} - Language * map. */ function one(node) { var children = node.children; var length = children.length; var index = -1; var languages; var child; var dictionary = {}; var tuple; while (++index < length) { child = children[index]; languages = child.data && child.data.languages; if (languages) { tuple = languages[0]; if (tuple[0] in dictionary) { dictionary[tuple[0]] += tuple[1]; } else { dictionary[tuple[0]] = tuple[1]; } } } return sortDistanceObject(dictionary); } /** * Patch all parents in reverse order: this means * that first the last and deepest parent is invoked * up to the first and highest parent. */ function done() { var index = queue.length; while (index--) { patch(queue[index], one(queue[index])); } } concatenate.done = done; return concatenate; }
[ "function", "concatenateFactory", "(", ")", "{", "var", "queue", "=", "[", "]", ";", "function", "concatenate", "(", "node", ",", "index", ",", "parent", ")", "{", "if", "(", "parent", "&&", "(", "parent", ".", "type", "===", "'ParagraphNode'", "||", "parent", ".", "type", "===", "'RootNode'", ")", "&&", "queue", ".", "indexOf", "(", "parent", ")", "===", "-", "1", ")", "{", "queue", ".", "push", "(", "parent", ")", ";", "}", "}", "function", "one", "(", "node", ")", "{", "var", "children", "=", "node", ".", "children", ";", "var", "length", "=", "children", ".", "length", ";", "var", "index", "=", "-", "1", ";", "var", "languages", ";", "var", "child", ";", "var", "dictionary", "=", "{", "}", ";", "var", "tuple", ";", "while", "(", "++", "index", "<", "length", ")", "{", "child", "=", "children", "[", "index", "]", ";", "languages", "=", "child", ".", "data", "&&", "child", ".", "data", ".", "languages", ";", "if", "(", "languages", ")", "{", "tuple", "=", "languages", "[", "0", "]", ";", "if", "(", "tuple", "[", "0", "]", "in", "dictionary", ")", "{", "dictionary", "[", "tuple", "[", "0", "]", "]", "+=", "tuple", "[", "1", "]", ";", "}", "else", "{", "dictionary", "[", "tuple", "[", "0", "]", "]", "=", "tuple", "[", "1", "]", ";", "}", "}", "}", "return", "sortDistanceObject", "(", "dictionary", ")", ";", "}", "function", "done", "(", ")", "{", "var", "index", "=", "queue", ".", "length", ";", "while", "(", "index", "--", ")", "{", "patch", "(", "queue", "[", "index", "]", ",", "one", "(", "queue", "[", "index", "]", ")", ")", ";", "}", "}", "concatenate", ".", "done", "=", "done", ";", "return", "concatenate", ";", "}" ]
Factory to gather parents and patch them based on their childrens directionality. @return {function(node, index, parent)} - Can be passed to `visit`.
[ "Factory", "to", "gather", "parents", "and", "patch", "them", "based", "on", "their", "childrens", "directionality", "." ]
bc2a5b36f7a8e17161f86f0ed78d5e9794942340
https://github.com/wooorm/retext-language/blob/bc2a5b36f7a8e17161f86f0ed78d5e9794942340/index.js#L90-L161
train
wooorm/retext-language
index.js
concatenate
function concatenate(node, index, parent) { if ( parent && (parent.type === 'ParagraphNode' || parent.type === 'RootNode') && queue.indexOf(parent) === -1 ) { queue.push(parent); } }
javascript
function concatenate(node, index, parent) { if ( parent && (parent.type === 'ParagraphNode' || parent.type === 'RootNode') && queue.indexOf(parent) === -1 ) { queue.push(parent); } }
[ "function", "concatenate", "(", "node", ",", "index", ",", "parent", ")", "{", "if", "(", "parent", "&&", "(", "parent", ".", "type", "===", "'ParagraphNode'", "||", "parent", ".", "type", "===", "'RootNode'", ")", "&&", "queue", ".", "indexOf", "(", "parent", ")", "===", "-", "1", ")", "{", "queue", ".", "push", "(", "parent", ")", ";", "}", "}" ]
Gather a parent if not already gathered. @param {NLCSTChildNode} node - Child. @param {number} index - Position of `node` in `parent`. @param {NLCSTParentNode} parent - Parent of `child`.
[ "Gather", "a", "parent", "if", "not", "already", "gathered", "." ]
bc2a5b36f7a8e17161f86f0ed78d5e9794942340
https://github.com/wooorm/retext-language/blob/bc2a5b36f7a8e17161f86f0ed78d5e9794942340/index.js#L101-L109
train
wooorm/retext-language
index.js
one
function one(node) { var children = node.children; var length = children.length; var index = -1; var languages; var child; var dictionary = {}; var tuple; while (++index < length) { child = children[index]; languages = child.data && child.data.languages; if (languages) { tuple = languages[0]; if (tuple[0] in dictionary) { dictionary[tuple[0]] += tuple[1]; } else { dictionary[tuple[0]] = tuple[1]; } } } return sortDistanceObject(dictionary); }
javascript
function one(node) { var children = node.children; var length = children.length; var index = -1; var languages; var child; var dictionary = {}; var tuple; while (++index < length) { child = children[index]; languages = child.data && child.data.languages; if (languages) { tuple = languages[0]; if (tuple[0] in dictionary) { dictionary[tuple[0]] += tuple[1]; } else { dictionary[tuple[0]] = tuple[1]; } } } return sortDistanceObject(dictionary); }
[ "function", "one", "(", "node", ")", "{", "var", "children", "=", "node", ".", "children", ";", "var", "length", "=", "children", ".", "length", ";", "var", "index", "=", "-", "1", ";", "var", "languages", ";", "var", "child", ";", "var", "dictionary", "=", "{", "}", ";", "var", "tuple", ";", "while", "(", "++", "index", "<", "length", ")", "{", "child", "=", "children", "[", "index", "]", ";", "languages", "=", "child", ".", "data", "&&", "child", ".", "data", ".", "languages", ";", "if", "(", "languages", ")", "{", "tuple", "=", "languages", "[", "0", "]", ";", "if", "(", "tuple", "[", "0", "]", "in", "dictionary", ")", "{", "dictionary", "[", "tuple", "[", "0", "]", "]", "+=", "tuple", "[", "1", "]", ";", "}", "else", "{", "dictionary", "[", "tuple", "[", "0", "]", "]", "=", "tuple", "[", "1", "]", ";", "}", "}", "}", "return", "sortDistanceObject", "(", "dictionary", ")", ";", "}" ]
Patch one parent. @param {NLCSTParentNode} node - Parent @return {Array.<Array.<string, number>>} - Language map.
[ "Patch", "one", "parent", "." ]
bc2a5b36f7a8e17161f86f0ed78d5e9794942340
https://github.com/wooorm/retext-language/blob/bc2a5b36f7a8e17161f86f0ed78d5e9794942340/index.js#L118-L143
train
stezu/node-stream
lib/creators/fromCallback.js
fromCallback
function fromCallback(source) { var callCount = 0; // Throw an error if the source is not a function if (typeof source !== 'function') { throw new TypeError('Expected `source` to be a function.'); } return new Readable({ objectMode: true, read: function () { var self = this; // Increment the number of calls so we know when to push null callCount += 1; // Call the method and push results if this is the first call if (callCount === 1) { source(_.rest(function (err, parameters) { if (err) { process.nextTick(function () { self.emit('error', err); }); return; } // Push all parameters of the callback to the stream as an array self.push(parameters); })); return; } // End the stream self.push(null); } }); }
javascript
function fromCallback(source) { var callCount = 0; // Throw an error if the source is not a function if (typeof source !== 'function') { throw new TypeError('Expected `source` to be a function.'); } return new Readable({ objectMode: true, read: function () { var self = this; // Increment the number of calls so we know when to push null callCount += 1; // Call the method and push results if this is the first call if (callCount === 1) { source(_.rest(function (err, parameters) { if (err) { process.nextTick(function () { self.emit('error', err); }); return; } // Push all parameters of the callback to the stream as an array self.push(parameters); })); return; } // End the stream self.push(null); } }); }
[ "function", "fromCallback", "(", "source", ")", "{", "var", "callCount", "=", "0", ";", "if", "(", "typeof", "source", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "'Expected `source` to be a function.'", ")", ";", "}", "return", "new", "Readable", "(", "{", "objectMode", ":", "true", ",", "read", ":", "function", "(", ")", "{", "var", "self", "=", "this", ";", "callCount", "+=", "1", ";", "if", "(", "callCount", "===", "1", ")", "{", "source", "(", "_", ".", "rest", "(", "function", "(", "err", ",", "parameters", ")", "{", "if", "(", "err", ")", "{", "process", ".", "nextTick", "(", "function", "(", ")", "{", "self", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", ")", ";", "return", ";", "}", "self", ".", "push", "(", "parameters", ")", ";", "}", ")", ")", ";", "return", ";", "}", "self", ".", "push", "(", "null", ")", ";", "}", "}", ")", ";", "}" ]
Creates a new readable stream from a function which accepts a node-style callback. This is primarily useful for piping into additional node-stream methods like map, reduce and filter. @static @since 1.6.0 @category Creators @param {Function} source - A function to call which accepts a node-style callback as the last argument. When that callback is called, this stream will emit all arguments as a single array. @returns {Stream.Readable} - Readable stream. @throws {TypeError} - If `source` is not a function. @example // Create a stream from a function callback which is then piped to another node-stream method nodeStream.fromCallback(fs.readdir.bind(this, path.resolve('.'))) .pipe(nodeStream.map(fs.readFile)); // => ['contents of file1.txt', 'contents of file2.js', 'contents of file3.pdf']
[ "Creates", "a", "new", "readable", "stream", "from", "a", "function", "which", "accepts", "a", "node", "-", "style", "callback", ".", "This", "is", "primarily", "useful", "for", "piping", "into", "additional", "node", "-", "stream", "methods", "like", "map", "reduce", "and", "filter", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/creators/fromCallback.js#L28-L67
train
kevoree/kevoree-js
libraries/group/ws/lib/ClientHandler.js
function() { Object.keys(this.name2Ws).forEach(function(name) { delete this.name2Ws[name]; }.bind(this)); Object.keys(this.ws2Name).forEach(function(wsId) { delete this.ws2Name[wsId]; }.bind(this)); }
javascript
function() { Object.keys(this.name2Ws).forEach(function(name) { delete this.name2Ws[name]; }.bind(this)); Object.keys(this.ws2Name).forEach(function(wsId) { delete this.ws2Name[wsId]; }.bind(this)); }
[ "function", "(", ")", "{", "Object", ".", "keys", "(", "this", ".", "name2Ws", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "delete", "this", ".", "name2Ws", "[", "name", "]", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "Object", ".", "keys", "(", "this", ".", "ws2Name", ")", ".", "forEach", "(", "function", "(", "wsId", ")", "{", "delete", "this", ".", "ws2Name", "[", "wsId", "]", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Clear server caches
[ "Clear", "server", "caches" ]
7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd
https://github.com/kevoree/kevoree-js/blob/7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd/libraries/group/ws/lib/ClientHandler.js#L197-L205
train
ivitivan/yandex-dictionary
lib/yandex-dictionary.js
function(text, lang, callback) { if (arguments.length == 4) { var options = callback; callback = arguments[arguments.length - 1]; } var uri = url.format({ pathname: url.resolve(baseAddress, 'lookup'), query: { key: dis.APIkey, lang: lang, text: text, ui: options ? options.ui : null, flags: options ? options.flags : null, } }); makeRequest(uri, callback); }
javascript
function(text, lang, callback) { if (arguments.length == 4) { var options = callback; callback = arguments[arguments.length - 1]; } var uri = url.format({ pathname: url.resolve(baseAddress, 'lookup'), query: { key: dis.APIkey, lang: lang, text: text, ui: options ? options.ui : null, flags: options ? options.flags : null, } }); makeRequest(uri, callback); }
[ "function", "(", "text", ",", "lang", ",", "callback", ")", "{", "if", "(", "arguments", ".", "length", "==", "4", ")", "{", "var", "options", "=", "callback", ";", "callback", "=", "arguments", "[", "arguments", ".", "length", "-", "1", "]", ";", "}", "var", "uri", "=", "url", ".", "format", "(", "{", "pathname", ":", "url", ".", "resolve", "(", "baseAddress", ",", "'lookup'", ")", ",", "query", ":", "{", "key", ":", "dis", ".", "APIkey", ",", "lang", ":", "lang", ",", "text", ":", "text", ",", "ui", ":", "options", "?", "options", ".", "ui", ":", "null", ",", "flags", ":", "options", "?", "options", ".", "flags", ":", "null", ",", "}", "}", ")", ";", "makeRequest", "(", "uri", ",", "callback", ")", ";", "}" ]
The first two parameters are text and lang, next pararameter, options, is optional; the last parameter is callback function
[ "The", "first", "two", "parameters", "are", "text", "and", "lang", "next", "pararameter", "options", "is", "optional", ";", "the", "last", "parameter", "is", "callback", "function" ]
9865dbc376ec566f67bb8f97c756ba31b2e60fd1
https://github.com/ivitivan/yandex-dictionary/blob/9865dbc376ec566f67bb8f97c756ba31b2e60fd1/lib/yandex-dictionary.js#L16-L35
train
kevoree/kevoree-js
tools/kevoree-kevscript/lib/util/model-helper.js
getPlatforms
function getPlatforms(tdef) { const platforms = []; if (tdef) { tdef.deployUnits.array.forEach((du) => { const platform = du.findFiltersByID('platform'); if (platform && platforms.indexOf(platform.value) === -1) { platforms.push(platform.value); } }); } return platforms; }
javascript
function getPlatforms(tdef) { const platforms = []; if (tdef) { tdef.deployUnits.array.forEach((du) => { const platform = du.findFiltersByID('platform'); if (platform && platforms.indexOf(platform.value) === -1) { platforms.push(platform.value); } }); } return platforms; }
[ "function", "getPlatforms", "(", "tdef", ")", "{", "const", "platforms", "=", "[", "]", ";", "if", "(", "tdef", ")", "{", "tdef", ".", "deployUnits", ".", "array", ".", "forEach", "(", "(", "du", ")", "=>", "{", "const", "platform", "=", "du", ".", "findFiltersByID", "(", "'platform'", ")", ";", "if", "(", "platform", "&&", "platforms", ".", "indexOf", "(", "platform", ".", "value", ")", "===", "-", "1", ")", "{", "platforms", ".", "push", "(", "platform", ".", "value", ")", ";", "}", "}", ")", ";", "}", "return", "platforms", ";", "}" ]
Returns the platforms related to that TypeDefinition @param tdef @returns {Array}
[ "Returns", "the", "platforms", "related", "to", "that", "TypeDefinition" ]
7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd
https://github.com/kevoree/kevoree-js/blob/7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd/tools/kevoree-kevscript/lib/util/model-helper.js#L38-L51
train