id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
25,800
begriffs/angular-paginate-anything
dist/paginate-anything.js
appendTransform
function appendTransform(defaults, transform) { defaults = angular.isArray(defaults) ? defaults : [defaults]; return (transform) ? defaults.concat(transform) : defaults; }
javascript
function appendTransform(defaults, transform) { defaults = angular.isArray(defaults) ? defaults : [defaults]; return (transform) ? defaults.concat(transform) : defaults; }
[ "function", "appendTransform", "(", "defaults", ",", "transform", ")", "{", "defaults", "=", "angular", ".", "isArray", "(", "defaults", ")", "?", "defaults", ":", "[", "defaults", "]", ";", "return", "(", "transform", ")", "?", "defaults", ".", "concat", "(", "transform", ")", ":", "defaults", ";", "}" ]
don't overwrite default response transforms
[ "don", "t", "overwrite", "default", "response", "transforms" ]
b9e3fddace64b53d8301a09a2490f32ff80ae554
https://github.com/begriffs/angular-paginate-anything/blob/b9e3fddace64b53d8301a09a2490f32ff80ae554/dist/paginate-anything.js#L28-L31
25,801
ember-data/active-model-adapter
addon/active-model-serializer.js
function(relationshipModelName, kind) { var key = decamelize(relationshipModelName); if (kind === "belongsTo") { return key + "_id"; } else if (kind === "hasMany") { return singularize(key) + "_ids"; } else { return key; } }
javascript
function(relationshipModelName, kind) { var key = decamelize(relationshipModelName); if (kind === "belongsTo") { return key + "_id"; } else if (kind === "hasMany") { return singularize(key) + "_ids"; } else { return key; } }
[ "function", "(", "relationshipModelName", ",", "kind", ")", "{", "var", "key", "=", "decamelize", "(", "relationshipModelName", ")", ";", "if", "(", "kind", "===", "\"belongsTo\"", ")", "{", "return", "key", "+", "\"_id\"", ";", "}", "else", "if", "(", "kind", "===", "\"hasMany\"", ")", "{", "return", "singularize", "(", "key", ")", "+", "\"_ids\"", ";", "}", "else", "{", "return", "key", ";", "}", "}" ]
Underscores relationship names and appends "_id" or "_ids" when serializing relationship keys. @method keyForRelationship @param {String} relationshipModelName @param {String} kind @return String
[ "Underscores", "relationship", "names", "and", "appends", "_id", "or", "_ids", "when", "serializing", "relationship", "keys", "." ]
967a47548a923dc3cac816c8dd971ad6f68e05e6
https://github.com/ember-data/active-model-adapter/blob/967a47548a923dc3cac816c8dd971ad6f68e05e6/addon/active-model-serializer.js#L131-L140
25,802
ember-data/active-model-adapter
addon/active-model-serializer.js
function(snapshot, json, relationship) { var key = relationship.key; var belongsTo = snapshot.belongsTo(key); var jsonKey = underscore(key + "_type"); if (Ember.isNone(belongsTo)) { json[jsonKey] = null; } else { json[jsonKey] = classify(belongsTo.modelName).replace('/', '::'); } }
javascript
function(snapshot, json, relationship) { var key = relationship.key; var belongsTo = snapshot.belongsTo(key); var jsonKey = underscore(key + "_type"); if (Ember.isNone(belongsTo)) { json[jsonKey] = null; } else { json[jsonKey] = classify(belongsTo.modelName).replace('/', '::'); } }
[ "function", "(", "snapshot", ",", "json", ",", "relationship", ")", "{", "var", "key", "=", "relationship", ".", "key", ";", "var", "belongsTo", "=", "snapshot", ".", "belongsTo", "(", "key", ")", ";", "var", "jsonKey", "=", "underscore", "(", "key", "+", "\"_type\"", ")", ";", "if", "(", "Ember", ".", "isNone", "(", "belongsTo", ")", ")", "{", "json", "[", "jsonKey", "]", "=", "null", ";", "}", "else", "{", "json", "[", "jsonKey", "]", "=", "classify", "(", "belongsTo", ".", "modelName", ")", ".", "replace", "(", "'/'", ",", "'::'", ")", ";", "}", "}" ]
Serializes a polymorphic type as a fully capitalized model name. @method serializePolymorphicType @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship
[ "Serializes", "a", "polymorphic", "type", "as", "a", "fully", "capitalized", "model", "name", "." ]
967a47548a923dc3cac816c8dd971ad6f68e05e6
https://github.com/ember-data/active-model-adapter/blob/967a47548a923dc3cac816c8dd971ad6f68e05e6/addon/active-model-serializer.js#L179-L189
25,803
ember-data/active-model-adapter
addon/active-model-serializer.js
function(data) { if (data.links) { var links = data.links; for (var link in links) { var camelizedLink = camelize(link); if (camelizedLink !== link) { links[camelizedLink] = links[link]; delete links[link]; } } } }
javascript
function(data) { if (data.links) { var links = data.links; for (var link in links) { var camelizedLink = camelize(link); if (camelizedLink !== link) { links[camelizedLink] = links[link]; delete links[link]; } } } }
[ "function", "(", "data", ")", "{", "if", "(", "data", ".", "links", ")", "{", "var", "links", "=", "data", ".", "links", ";", "for", "(", "var", "link", "in", "links", ")", "{", "var", "camelizedLink", "=", "camelize", "(", "link", ")", ";", "if", "(", "camelizedLink", "!==", "link", ")", "{", "links", "[", "camelizedLink", "]", "=", "links", "[", "link", "]", ";", "delete", "links", "[", "link", "]", ";", "}", "}", "}", "}" ]
Convert `snake_cased` links to `camelCase` @method normalizeLinks @param {Object} data
[ "Convert", "snake_cased", "links", "to", "camelCase" ]
967a47548a923dc3cac816c8dd971ad6f68e05e6
https://github.com/ember-data/active-model-adapter/blob/967a47548a923dc3cac816c8dd971ad6f68e05e6/addon/active-model-serializer.js#L236-L249
25,804
dcodeIO/ClosureCompiler.js
scripts/configure.js
platformPostfix
function platformPostfix() { if (/^win/.test(process.platform)) { return process.arch == 'x64' ? 'win64' : 'win32'; } else if (/^darwin/.test(process.platform)) { return 'osx64'; } // This might not be ideal, but we don't have anything else and there is always a chance that it will work return process.arch == 'x64' ? 'linux64' : 'linux32'; }
javascript
function platformPostfix() { if (/^win/.test(process.platform)) { return process.arch == 'x64' ? 'win64' : 'win32'; } else if (/^darwin/.test(process.platform)) { return 'osx64'; } // This might not be ideal, but we don't have anything else and there is always a chance that it will work return process.arch == 'x64' ? 'linux64' : 'linux32'; }
[ "function", "platformPostfix", "(", ")", "{", "if", "(", "/", "^win", "/", ".", "test", "(", "process", ".", "platform", ")", ")", "{", "return", "process", ".", "arch", "==", "'x64'", "?", "'win64'", ":", "'win32'", ";", "}", "else", "if", "(", "/", "^darwin", "/", ".", "test", "(", "process", ".", "platform", ")", ")", "{", "return", "'osx64'", ";", "}", "// This might not be ideal, but we don't have anything else and there is always a chance that it will work", "return", "process", ".", "arch", "==", "'x64'", "?", "'linux64'", ":", "'linux32'", ";", "}" ]
Gets the platform postfix for downloads
[ "Gets", "the", "platform", "postfix", "for", "downloads" ]
96fd199f24eaada9aa67c30164ffc720218f64a4
https://github.com/dcodeIO/ClosureCompiler.js/blob/96fd199f24eaada9aa67c30164ffc720218f64a4/scripts/configure.js#L40-L48
25,805
dcodeIO/ClosureCompiler.js
scripts/configure.js
unpack
function unpack(filename, callback, entryCallback) { var input = fs.createReadStream(filename, { flags: 'r', encoding: null }), files = {}, dir = path.dirname(filename), returned = false, to = null; // Finishs the unpack if all files are done function maybeFinish() { if (to !== null) clearTimeout(to); to = setTimeout(function() { var alldone = true; var names = Object.keys(files); for (var i=0; i<names.length; i++) { if (!files[names[i]]["done"]) { alldone = false; break; } } if (alldone && !returned) { returned = true; callback(null); } }, 1000); } input.pipe(zlib.createGunzip()).pipe(tar.Parse()).on("entry", function(entry) { if (entryCallback) entryCallback(entry); if (entry["type"] == 'File') { files[entry["path"]] = fs.createWriteStream(path.join(dir, entry["path"]), { flags: 'w', encoding: null }); entry.pipe(files[entry["path"]]); entry.on("end", function() { files[entry["path"]].end(); files[entry["path"]]["done"] = true; maybeFinish(); }); } else if (entry["type"] == "Directory") { try { fs.mkdirSync(path.join(dir, entry["path"])); } catch (e) { if (!fs.existsSync(path.join(dir, entry["path"]))) { if (!returned) { returned = true; callback(e); } } } } }).on("error", function(e) { if (!returned) { returned = true; callback(e); } }); }
javascript
function unpack(filename, callback, entryCallback) { var input = fs.createReadStream(filename, { flags: 'r', encoding: null }), files = {}, dir = path.dirname(filename), returned = false, to = null; // Finishs the unpack if all files are done function maybeFinish() { if (to !== null) clearTimeout(to); to = setTimeout(function() { var alldone = true; var names = Object.keys(files); for (var i=0; i<names.length; i++) { if (!files[names[i]]["done"]) { alldone = false; break; } } if (alldone && !returned) { returned = true; callback(null); } }, 1000); } input.pipe(zlib.createGunzip()).pipe(tar.Parse()).on("entry", function(entry) { if (entryCallback) entryCallback(entry); if (entry["type"] == 'File') { files[entry["path"]] = fs.createWriteStream(path.join(dir, entry["path"]), { flags: 'w', encoding: null }); entry.pipe(files[entry["path"]]); entry.on("end", function() { files[entry["path"]].end(); files[entry["path"]]["done"] = true; maybeFinish(); }); } else if (entry["type"] == "Directory") { try { fs.mkdirSync(path.join(dir, entry["path"])); } catch (e) { if (!fs.existsSync(path.join(dir, entry["path"]))) { if (!returned) { returned = true; callback(e); } } } } }).on("error", function(e) { if (!returned) { returned = true; callback(e); } }); }
[ "function", "unpack", "(", "filename", ",", "callback", ",", "entryCallback", ")", "{", "var", "input", "=", "fs", ".", "createReadStream", "(", "filename", ",", "{", "flags", ":", "'r'", ",", "encoding", ":", "null", "}", ")", ",", "files", "=", "{", "}", ",", "dir", "=", "path", ".", "dirname", "(", "filename", ")", ",", "returned", "=", "false", ",", "to", "=", "null", ";", "// Finishs the unpack if all files are done", "function", "maybeFinish", "(", ")", "{", "if", "(", "to", "!==", "null", ")", "clearTimeout", "(", "to", ")", ";", "to", "=", "setTimeout", "(", "function", "(", ")", "{", "var", "alldone", "=", "true", ";", "var", "names", "=", "Object", ".", "keys", "(", "files", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "names", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "files", "[", "names", "[", "i", "]", "]", "[", "\"done\"", "]", ")", "{", "alldone", "=", "false", ";", "break", ";", "}", "}", "if", "(", "alldone", "&&", "!", "returned", ")", "{", "returned", "=", "true", ";", "callback", "(", "null", ")", ";", "}", "}", ",", "1000", ")", ";", "}", "input", ".", "pipe", "(", "zlib", ".", "createGunzip", "(", ")", ")", ".", "pipe", "(", "tar", ".", "Parse", "(", ")", ")", ".", "on", "(", "\"entry\"", ",", "function", "(", "entry", ")", "{", "if", "(", "entryCallback", ")", "entryCallback", "(", "entry", ")", ";", "if", "(", "entry", "[", "\"type\"", "]", "==", "'File'", ")", "{", "files", "[", "entry", "[", "\"path\"", "]", "]", "=", "fs", ".", "createWriteStream", "(", "path", ".", "join", "(", "dir", ",", "entry", "[", "\"path\"", "]", ")", ",", "{", "flags", ":", "'w'", ",", "encoding", ":", "null", "}", ")", ";", "entry", ".", "pipe", "(", "files", "[", "entry", "[", "\"path\"", "]", "]", ")", ";", "entry", ".", "on", "(", "\"end\"", ",", "function", "(", ")", "{", "files", "[", "entry", "[", "\"path\"", "]", "]", ".", "end", "(", ")", ";", "files", "[", "entry", "[", "\"path\"", "]", "]", "[", "\"done\"", "]", "=", "true", ";", "maybeFinish", "(", ")", ";", "}", ")", ";", "}", "else", "if", "(", "entry", "[", "\"type\"", "]", "==", "\"Directory\"", ")", "{", "try", "{", "fs", ".", "mkdirSync", "(", "path", ".", "join", "(", "dir", ",", "entry", "[", "\"path\"", "]", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "path", ".", "join", "(", "dir", ",", "entry", "[", "\"path\"", "]", ")", ")", ")", "{", "if", "(", "!", "returned", ")", "{", "returned", "=", "true", ";", "callback", "(", "e", ")", ";", "}", "}", "}", "}", "}", ")", ".", "on", "(", "\"error\"", ",", "function", "(", "e", ")", "{", "if", "(", "!", "returned", ")", "{", "returned", "=", "true", ";", "callback", "(", "e", ")", ";", "}", "}", ")", ";", "}" ]
Unpacks a file in place. @param {string} filename File name @param {function(?Error)} callback @param {function(Object)=} entryCallback
[ "Unpacks", "a", "file", "in", "place", "." ]
96fd199f24eaada9aa67c30164ffc720218f64a4
https://github.com/dcodeIO/ClosureCompiler.js/blob/96fd199f24eaada9aa67c30164ffc720218f64a4/scripts/configure.js#L208-L262
25,806
dcodeIO/ClosureCompiler.js
scripts/configure.js
maybeFinish
function maybeFinish() { if (to !== null) clearTimeout(to); to = setTimeout(function() { var alldone = true; var names = Object.keys(files); for (var i=0; i<names.length; i++) { if (!files[names[i]]["done"]) { alldone = false; break; } } if (alldone && !returned) { returned = true; callback(null); } }, 1000); }
javascript
function maybeFinish() { if (to !== null) clearTimeout(to); to = setTimeout(function() { var alldone = true; var names = Object.keys(files); for (var i=0; i<names.length; i++) { if (!files[names[i]]["done"]) { alldone = false; break; } } if (alldone && !returned) { returned = true; callback(null); } }, 1000); }
[ "function", "maybeFinish", "(", ")", "{", "if", "(", "to", "!==", "null", ")", "clearTimeout", "(", "to", ")", ";", "to", "=", "setTimeout", "(", "function", "(", ")", "{", "var", "alldone", "=", "true", ";", "var", "names", "=", "Object", ".", "keys", "(", "files", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "names", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "files", "[", "names", "[", "i", "]", "]", "[", "\"done\"", "]", ")", "{", "alldone", "=", "false", ";", "break", ";", "}", "}", "if", "(", "alldone", "&&", "!", "returned", ")", "{", "returned", "=", "true", ";", "callback", "(", "null", ")", ";", "}", "}", ",", "1000", ")", ";", "}" ]
Finishs the unpack if all files are done
[ "Finishs", "the", "unpack", "if", "all", "files", "are", "done" ]
96fd199f24eaada9aa67c30164ffc720218f64a4
https://github.com/dcodeIO/ClosureCompiler.js/blob/96fd199f24eaada9aa67c30164ffc720218f64a4/scripts/configure.js#L216-L232
25,807
dcodeIO/ClosureCompiler.js
scripts/configure.js
configure
function configure() { var java = path.normalize(path.join(__dirname, "..", "jre", "bin", "java"+ClosureCompiler.JAVA_EXT)); console.log(" Configuring bundled JRE for platform '"+platformPostfix()+"' ..."); if (!/^win/.test(process.platform)) { var jre = path.normalize(path.join(__dirname, "..", "jre")); console.log(" | 0755 "+jre); fs.chmodSync(jre, 0755); console.log(" | 0755 "+path.join(jre, "bin")); fs.chmodSync(path.join(jre, "bin"), 0755); console.log(" | 0755 "+java); fs.chmodSync(java, 0755); console.log(" Complete.\n"); } else { console.log(" Complete (not necessary).\n"); } }
javascript
function configure() { var java = path.normalize(path.join(__dirname, "..", "jre", "bin", "java"+ClosureCompiler.JAVA_EXT)); console.log(" Configuring bundled JRE for platform '"+platformPostfix()+"' ..."); if (!/^win/.test(process.platform)) { var jre = path.normalize(path.join(__dirname, "..", "jre")); console.log(" | 0755 "+jre); fs.chmodSync(jre, 0755); console.log(" | 0755 "+path.join(jre, "bin")); fs.chmodSync(path.join(jre, "bin"), 0755); console.log(" | 0755 "+java); fs.chmodSync(java, 0755); console.log(" Complete.\n"); } else { console.log(" Complete (not necessary).\n"); } }
[ "function", "configure", "(", ")", "{", "var", "java", "=", "path", ".", "normalize", "(", "path", ".", "join", "(", "__dirname", ",", "\"..\"", ",", "\"jre\"", ",", "\"bin\"", ",", "\"java\"", "+", "ClosureCompiler", ".", "JAVA_EXT", ")", ")", ";", "console", ".", "log", "(", "\" Configuring bundled JRE for platform '\"", "+", "platformPostfix", "(", ")", "+", "\"' ...\"", ")", ";", "if", "(", "!", "/", "^win", "/", ".", "test", "(", "process", ".", "platform", ")", ")", "{", "var", "jre", "=", "path", ".", "normalize", "(", "path", ".", "join", "(", "__dirname", ",", "\"..\"", ",", "\"jre\"", ")", ")", ";", "console", ".", "log", "(", "\" | 0755 \"", "+", "jre", ")", ";", "fs", ".", "chmodSync", "(", "jre", ",", "0755", ")", ";", "console", ".", "log", "(", "\" | 0755 \"", "+", "path", ".", "join", "(", "jre", ",", "\"bin\"", ")", ")", ";", "fs", ".", "chmodSync", "(", "path", ".", "join", "(", "jre", ",", "\"bin\"", ")", ",", "0755", ")", ";", "console", ".", "log", "(", "\" | 0755 \"", "+", "java", ")", ";", "fs", ".", "chmodSync", "(", "java", ",", "0755", ")", ";", "console", ".", "log", "(", "\" Complete.\\n\"", ")", ";", "}", "else", "{", "console", ".", "log", "(", "\" Complete (not necessary).\\n\"", ")", ";", "}", "}" ]
Configures our bundled Java.
[ "Configures", "our", "bundled", "Java", "." ]
96fd199f24eaada9aa67c30164ffc720218f64a4
https://github.com/dcodeIO/ClosureCompiler.js/blob/96fd199f24eaada9aa67c30164ffc720218f64a4/scripts/configure.js#L267-L282
25,808
dcodeIO/ClosureCompiler.js
ClosureCompiler.js
exec
function exec(cmd, args, stdin, callback) { var stdout = concat(); var stderr = concat(); var process = child_process.spawn(cmd, args, { stdio: [stdin || 'ignore', 'pipe', 'pipe'] }); process.stdout.pipe(stdout); process.stderr.pipe(stderr); process.on('exit', function(code, signal) { var err; if (code) { err = new Error(code); err.code = code; err.signal = signal; } callback(err, stdout, stderr); }); process.on('error', function (err) { callback(err, stdout, stderr); }); }
javascript
function exec(cmd, args, stdin, callback) { var stdout = concat(); var stderr = concat(); var process = child_process.spawn(cmd, args, { stdio: [stdin || 'ignore', 'pipe', 'pipe'] }); process.stdout.pipe(stdout); process.stderr.pipe(stderr); process.on('exit', function(code, signal) { var err; if (code) { err = new Error(code); err.code = code; err.signal = signal; } callback(err, stdout, stderr); }); process.on('error', function (err) { callback(err, stdout, stderr); }); }
[ "function", "exec", "(", "cmd", ",", "args", ",", "stdin", ",", "callback", ")", "{", "var", "stdout", "=", "concat", "(", ")", ";", "var", "stderr", "=", "concat", "(", ")", ";", "var", "process", "=", "child_process", ".", "spawn", "(", "cmd", ",", "args", ",", "{", "stdio", ":", "[", "stdin", "||", "'ignore'", ",", "'pipe'", ",", "'pipe'", "]", "}", ")", ";", "process", ".", "stdout", ".", "pipe", "(", "stdout", ")", ";", "process", ".", "stderr", ".", "pipe", "(", "stderr", ")", ";", "process", ".", "on", "(", "'exit'", ",", "function", "(", "code", ",", "signal", ")", "{", "var", "err", ";", "if", "(", "code", ")", "{", "err", "=", "new", "Error", "(", "code", ")", ";", "err", ".", "code", "=", "code", ";", "err", ".", "signal", "=", "signal", ";", "}", "callback", "(", "err", ",", "stdout", ",", "stderr", ")", ";", "}", ")", ";", "process", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "callback", "(", "err", ",", "stdout", ",", "stderr", ")", ";", "}", ")", ";", "}" ]
Executes a command
[ "Executes", "a", "command" ]
96fd199f24eaada9aa67c30164ffc720218f64a4
https://github.com/dcodeIO/ClosureCompiler.js/blob/96fd199f24eaada9aa67c30164ffc720218f64a4/ClosureCompiler.js#L267-L288
25,809
XervoIO/demeteorizer
lib/find-node-version.js
fromBoot
function fromBoot (options) { var version var bootPath = Path.resolve( options.directory, 'bundle', 'programs', 'server', 'boot.js') try { version = Fs.readFileSync(bootPath, 'utf8') .split('\n') .find((line) => line.indexOf('MIN_NODE_VERSION') >= 0) .split(' ')[3] // eslint-disable no-magic-numbers .replace(/[v;']/g, '') } catch (err) { return false } return version }
javascript
function fromBoot (options) { var version var bootPath = Path.resolve( options.directory, 'bundle', 'programs', 'server', 'boot.js') try { version = Fs.readFileSync(bootPath, 'utf8') .split('\n') .find((line) => line.indexOf('MIN_NODE_VERSION') >= 0) .split(' ')[3] // eslint-disable no-magic-numbers .replace(/[v;']/g, '') } catch (err) { return false } return version }
[ "function", "fromBoot", "(", "options", ")", "{", "var", "version", "var", "bootPath", "=", "Path", ".", "resolve", "(", "options", ".", "directory", ",", "'bundle'", ",", "'programs'", ",", "'server'", ",", "'boot.js'", ")", "try", "{", "version", "=", "Fs", ".", "readFileSync", "(", "bootPath", ",", "'utf8'", ")", ".", "split", "(", "'\\n'", ")", ".", "find", "(", "(", "line", ")", "=>", "line", ".", "indexOf", "(", "'MIN_NODE_VERSION'", ")", ">=", "0", ")", ".", "split", "(", "' '", ")", "[", "3", "]", "// eslint-disable no-magic-numbers", ".", "replace", "(", "/", "[v;']", "/", "g", ",", "''", ")", "}", "catch", "(", "err", ")", "{", "return", "false", "}", "return", "version", "}" ]
Read boot.js to find the MIN_NODE_VERSION
[ "Read", "boot", ".", "js", "to", "find", "the", "MIN_NODE_VERSION" ]
2581c3f2064aa4779d44e737ab0793fa7cabbd43
https://github.com/XervoIO/demeteorizer/blob/2581c3f2064aa4779d44e737ab0793fa7cabbd43/lib/find-node-version.js#L20-L39
25,810
mozilla/dryice
lib/dryice/index.js
Location
function Location(base, somePath) { if (base == null) { throw new Error('base == null'); } this.base = base; this.path = somePath; }
javascript
function Location(base, somePath) { if (base == null) { throw new Error('base == null'); } this.base = base; this.path = somePath; }
[ "function", "Location", "(", "base", ",", "somePath", ")", "{", "if", "(", "base", "==", "null", ")", "{", "throw", "new", "Error", "(", "'base == null'", ")", ";", "}", "this", ".", "base", "=", "base", ";", "this", ".", "path", "=", "somePath", ";", "}" ]
A Location is a base and a path which together point to a file or directory. It's useful to be able to know in copy operations relative to some project root to be able to remember where in a destination the file should go
[ "A", "Location", "is", "a", "base", "and", "a", "path", "which", "together", "point", "to", "a", "file", "or", "directory", ".", "It", "s", "useful", "to", "be", "able", "to", "know", "in", "copy", "operations", "relative", "to", "some", "project", "root", "to", "be", "able", "to", "remember", "where", "in", "a", "destination", "the", "file", "should", "go" ]
836fa7533c90abc3a30dd08c721d271d578d7b46
https://github.com/mozilla/dryice/blob/836fa7533c90abc3a30dd08c721d271d578d7b46/lib/dryice/index.js#L40-L46
25,811
theasta/grunt-assets-versioning
tasks/versioners/abstractVersioner.js
AbstractVersioner
function AbstractVersioner(options, taskData) { this.options = options; this.taskData = taskData; /** * Map of versioned files * @type {Array.<{version, originalPath: string, versionedPath: string}>} */ this.versionsMap = []; /** * Get one of the tagger functions: hash or date * @type {function} */ this.versionTagger = taggers[this.options.tag]; // is task a post versioning task? this.isPostVersioningTask = grunt.config(this.getAssetsVersioningTaskConfigKey() + '.isPostVersioningTaskFor'); }
javascript
function AbstractVersioner(options, taskData) { this.options = options; this.taskData = taskData; /** * Map of versioned files * @type {Array.<{version, originalPath: string, versionedPath: string}>} */ this.versionsMap = []; /** * Get one of the tagger functions: hash or date * @type {function} */ this.versionTagger = taggers[this.options.tag]; // is task a post versioning task? this.isPostVersioningTask = grunt.config(this.getAssetsVersioningTaskConfigKey() + '.isPostVersioningTaskFor'); }
[ "function", "AbstractVersioner", "(", "options", ",", "taskData", ")", "{", "this", ".", "options", "=", "options", ";", "this", ".", "taskData", "=", "taskData", ";", "/**\n * Map of versioned files\n * @type {Array.<{version, originalPath: string, versionedPath: string}>}\n */", "this", ".", "versionsMap", "=", "[", "]", ";", "/**\n * Get one of the tagger functions: hash or date\n * @type {function}\n */", "this", ".", "versionTagger", "=", "taggers", "[", "this", ".", "options", ".", "tag", "]", ";", "// is task a post versioning task?", "this", ".", "isPostVersioningTask", "=", "grunt", ".", "config", "(", "this", ".", "getAssetsVersioningTaskConfigKey", "(", ")", "+", "'.isPostVersioningTaskFor'", ")", ";", "}" ]
A surrogate task - task with destination files tagged with a revision marker @typedef {(string|{files: Array})} surrogateTask Abstract Versioner @constructor @alias module:versioners/AbstractVersioner @param {object} options - Grunt options @param {object} taskData - Grunt Assets Versioning Task Object
[ "A", "surrogate", "task", "-", "task", "with", "destination", "files", "tagged", "with", "a", "revision", "marker" ]
5e2e62b90e3cc2b635582cce0e6598ce2bc8acab
https://github.com/theasta/grunt-assets-versioning/blob/5e2e62b90e3cc2b635582cce0e6598ce2bc8acab/tasks/versioners/abstractVersioner.js#L28-L46
25,812
bem-archive/image-optim
lib/modes.js
_minFile
function _minFile(rawFile, compressedFile) { if (compressedFile.size < rawFile.size) { return qfs.move(compressedFile.name, rawFile.name) .then(function () { return new File(rawFile.name, compressedFile.size); }); } return compressedFile.remove() .then(function () { return rawFile; }); }
javascript
function _minFile(rawFile, compressedFile) { if (compressedFile.size < rawFile.size) { return qfs.move(compressedFile.name, rawFile.name) .then(function () { return new File(rawFile.name, compressedFile.size); }); } return compressedFile.remove() .then(function () { return rawFile; }); }
[ "function", "_minFile", "(", "rawFile", ",", "compressedFile", ")", "{", "if", "(", "compressedFile", ".", "size", "<", "rawFile", ".", "size", ")", "{", "return", "qfs", ".", "move", "(", "compressedFile", ".", "name", ",", "rawFile", ".", "name", ")", ".", "then", "(", "function", "(", ")", "{", "return", "new", "File", "(", "rawFile", ".", "name", ",", "compressedFile", ".", "size", ")", ";", "}", ")", ";", "}", "return", "compressedFile", ".", "remove", "(", ")", ".", "then", "(", "function", "(", ")", "{", "return", "rawFile", ";", "}", ")", ";", "}" ]
Overwrites the raw file by the compressed one if it is smaller otherwise removes it @param {File} rawFile @param {File} compressedFile @returns {Promise * File}
[ "Overwrites", "the", "raw", "file", "by", "the", "compressed", "one", "if", "it", "is", "smaller", "otherwise", "removes", "it" ]
92dc730bcedf6f20713429c1c0843390377c8a24
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/modes.js#L14-L26
25,813
bem-archive/image-optim
lib/modes.js
_isSmallerAfterCompression
function _isSmallerAfterCompression(rawFile, compressedFile, opts) { return compressedFile.remove() .then(function () { var tolerance = opts.tolerance < 1 ? opts.tolerance * rawFile.size : opts.tolerance; return rawFile.size > compressedFile.size + tolerance; }); }
javascript
function _isSmallerAfterCompression(rawFile, compressedFile, opts) { return compressedFile.remove() .then(function () { var tolerance = opts.tolerance < 1 ? opts.tolerance * rawFile.size : opts.tolerance; return rawFile.size > compressedFile.size + tolerance; }); }
[ "function", "_isSmallerAfterCompression", "(", "rawFile", ",", "compressedFile", ",", "opts", ")", "{", "return", "compressedFile", ".", "remove", "(", ")", ".", "then", "(", "function", "(", ")", "{", "var", "tolerance", "=", "opts", ".", "tolerance", "<", "1", "?", "opts", ".", "tolerance", "*", "rawFile", ".", "size", ":", "opts", ".", "tolerance", ";", "return", "rawFile", ".", "size", ">", "compressedFile", ".", "size", "+", "tolerance", ";", "}", ")", ";", "}" ]
Checks whether the given raw file is smaller than the given compressed file Removes the compressed file @param {File} rawFile @param {File} compressedFile @param {Object} [opts] -> lib/defaults.js @param {Number} [opts.tolerance=0] @param {String[]} [opts.reporters=[]] @param {String} [opts._tmpDir=md5] @returns {Promise * Boolean}
[ "Checks", "whether", "the", "given", "raw", "file", "is", "smaller", "than", "the", "given", "compressed", "file", "Removes", "the", "compressed", "file" ]
92dc730bcedf6f20713429c1c0843390377c8a24
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/modes.js#L39-L48
25,814
bem-archive/image-optim
lib/modes.js
_getSavedBytes
function _getSavedBytes(rawFile, compressedFile) { var savedBytes = rawFile.size - compressedFile.size; if (savedBytes > 0) return savedBytes; return 0; }
javascript
function _getSavedBytes(rawFile, compressedFile) { var savedBytes = rawFile.size - compressedFile.size; if (savedBytes > 0) return savedBytes; return 0; }
[ "function", "_getSavedBytes", "(", "rawFile", ",", "compressedFile", ")", "{", "var", "savedBytes", "=", "rawFile", ".", "size", "-", "compressedFile", ".", "size", ";", "if", "(", "savedBytes", ">", "0", ")", "return", "savedBytes", ";", "return", "0", ";", "}" ]
Returns saved bytes between the raw and compressed files @param {File} rawFile @param {File} compressedFile @returns {Number}
[ "Returns", "saved", "bytes", "between", "the", "raw", "and", "compressed", "files" ]
92dc730bcedf6f20713429c1c0843390377c8a24
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/modes.js#L56-L62
25,815
bem-archive/image-optim
lib/modes.js
_initCompressedFile
function _initCompressedFile(filename, tmpDir) { return new File(path.join(tmpDir, path.basename(filename) + md5(filename) + path.extname(filename))); }
javascript
function _initCompressedFile(filename, tmpDir) { return new File(path.join(tmpDir, path.basename(filename) + md5(filename) + path.extname(filename))); }
[ "function", "_initCompressedFile", "(", "filename", ",", "tmpDir", ")", "{", "return", "new", "File", "(", "path", ".", "join", "(", "tmpDir", ",", "path", ".", "basename", "(", "filename", ")", "+", "md5", "(", "filename", ")", "+", "path", ".", "extname", "(", "filename", ")", ")", ")", ";", "}" ]
Initializes a compressed file @param {String} filename @param {String} tmpDir @returns {File}
[ "Initializes", "a", "compressed", "file" ]
92dc730bcedf6f20713429c1c0843390377c8a24
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/modes.js#L83-L85
25,816
bem-archive/image-optim
lib/modes.js
_imageOptim
function _imageOptim(rawFile, algorithms, reduceFunc, initVal) { return Q.all([rawFile.loadSize(), rawFile.loadType()]) .then(function () { return algorithms[rawFile.type].reduce(reduceFunc, initVal); }) .fail(function (err) { throw err; }); }
javascript
function _imageOptim(rawFile, algorithms, reduceFunc, initVal) { return Q.all([rawFile.loadSize(), rawFile.loadType()]) .then(function () { return algorithms[rawFile.type].reduce(reduceFunc, initVal); }) .fail(function (err) { throw err; }); }
[ "function", "_imageOptim", "(", "rawFile", ",", "algorithms", ",", "reduceFunc", ",", "initVal", ")", "{", "return", "Q", ".", "all", "(", "[", "rawFile", ".", "loadSize", "(", ")", ",", "rawFile", ".", "loadType", "(", ")", "]", ")", ".", "then", "(", "function", "(", ")", "{", "return", "algorithms", "[", "rawFile", ".", "type", "]", ".", "reduce", "(", "reduceFunc", ",", "initVal", ")", ";", "}", ")", ".", "fail", "(", "function", "(", "err", ")", "{", "throw", "err", ";", "}", ")", ";", "}" ]
Processes the file in the specifies mode @param {File} rawFile @param {Function[]} algorithms @param {reduceCallback} reduceFunc @param {Promise * File|Boolean} initVal @returns {Promise * File|Boolean}
[ "Processes", "the", "file", "in", "the", "specifies", "mode" ]
92dc730bcedf6f20713429c1c0843390377c8a24
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/modes.js#L95-L103
25,817
bem-archive/image-optim
lib/modes.js
function (rawFile, algorithms, opts) { return _imageOptim(rawFile, algorithms, function (prev, next) { return prev.then(function (res) { return next(rawFile, _initCompressedFile(rawFile.name, opts._tmpDir)) .then(function (compressed) { return _minFile(res, compressed); }); }); }, new Q(rawFile)) .then(function (minFile) { return { name: rawFile.name, savedBytes: _getSavedBytes(rawFile, minFile), exitCode: exit.SUCCESS }; }) .fail(function (err) { return _handleError(err, rawFile); }); }
javascript
function (rawFile, algorithms, opts) { return _imageOptim(rawFile, algorithms, function (prev, next) { return prev.then(function (res) { return next(rawFile, _initCompressedFile(rawFile.name, opts._tmpDir)) .then(function (compressed) { return _minFile(res, compressed); }); }); }, new Q(rawFile)) .then(function (minFile) { return { name: rawFile.name, savedBytes: _getSavedBytes(rawFile, minFile), exitCode: exit.SUCCESS }; }) .fail(function (err) { return _handleError(err, rawFile); }); }
[ "function", "(", "rawFile", ",", "algorithms", ",", "opts", ")", "{", "return", "_imageOptim", "(", "rawFile", ",", "algorithms", ",", "function", "(", "prev", ",", "next", ")", "{", "return", "prev", ".", "then", "(", "function", "(", "res", ")", "{", "return", "next", "(", "rawFile", ",", "_initCompressedFile", "(", "rawFile", ".", "name", ",", "opts", ".", "_tmpDir", ")", ")", ".", "then", "(", "function", "(", "compressed", ")", "{", "return", "_minFile", "(", "res", ",", "compressed", ")", ";", "}", ")", ";", "}", ")", ";", "}", ",", "new", "Q", "(", "rawFile", ")", ")", ".", "then", "(", "function", "(", "minFile", ")", "{", "return", "{", "name", ":", "rawFile", ".", "name", ",", "savedBytes", ":", "_getSavedBytes", "(", "rawFile", ",", "minFile", ")", ",", "exitCode", ":", "exit", ".", "SUCCESS", "}", ";", "}", ")", ".", "fail", "(", "function", "(", "err", ")", "{", "return", "_handleError", "(", "err", ",", "rawFile", ")", ";", "}", ")", ";", "}" ]
This callback is provided as a first argument for reduce function @callback reduceCallback @param {Promise * File|Boolean} prev @param {Promise * File|Boolean} next Optimizes the given file and returns the information about the compression @examples 1. { name: 'file.ext', savedBytes: 12345, exitCode: 0 } 2. { name: 'file.ext', exitCode: 1 } 3. { name: 'file.ext', exitCode: 2 } @param {File} rawFile @param {Function[]} algorithms @param {Object} [opts] -> lib/defaults.js @param {Number} [opts.tolerance=0] @param {String[]} [opts.reporters=[]] @param {String} [opts._tmpDir=md5] @returns {Promise * Object}
[ "This", "callback", "is", "provided", "as", "a", "first", "argument", "for", "reduce", "function" ]
92dc730bcedf6f20713429c1c0843390377c8a24
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/modes.js#L131-L150
25,818
bem-archive/image-optim
lib/modes.js
function (rawFile, algorithms, opts) { return _imageOptim(rawFile, algorithms, function (prev, next) { return prev.then(function (res) { return res || next(rawFile, _initCompressedFile(rawFile.name, opts._tmpDir)) .then(function (compressed) { return _isSmallerAfterCompression(rawFile, compressed, opts); }); }); }, new Q(false)) .then(function (isSmaller) { return { name: rawFile.name, isOptimized: !isSmaller, exitCode: 0 }; }) .fail(function (err) { return _handleError(err, rawFile); }); }
javascript
function (rawFile, algorithms, opts) { return _imageOptim(rawFile, algorithms, function (prev, next) { return prev.then(function (res) { return res || next(rawFile, _initCompressedFile(rawFile.name, opts._tmpDir)) .then(function (compressed) { return _isSmallerAfterCompression(rawFile, compressed, opts); }); }); }, new Q(false)) .then(function (isSmaller) { return { name: rawFile.name, isOptimized: !isSmaller, exitCode: 0 }; }) .fail(function (err) { return _handleError(err, rawFile); }); }
[ "function", "(", "rawFile", ",", "algorithms", ",", "opts", ")", "{", "return", "_imageOptim", "(", "rawFile", ",", "algorithms", ",", "function", "(", "prev", ",", "next", ")", "{", "return", "prev", ".", "then", "(", "function", "(", "res", ")", "{", "return", "res", "||", "next", "(", "rawFile", ",", "_initCompressedFile", "(", "rawFile", ".", "name", ",", "opts", ".", "_tmpDir", ")", ")", ".", "then", "(", "function", "(", "compressed", ")", "{", "return", "_isSmallerAfterCompression", "(", "rawFile", ",", "compressed", ",", "opts", ")", ";", "}", ")", ";", "}", ")", ";", "}", ",", "new", "Q", "(", "false", ")", ")", ".", "then", "(", "function", "(", "isSmaller", ")", "{", "return", "{", "name", ":", "rawFile", ".", "name", ",", "isOptimized", ":", "!", "isSmaller", ",", "exitCode", ":", "0", "}", ";", "}", ")", ".", "fail", "(", "function", "(", "err", ")", "{", "return", "_handleError", "(", "err", ",", "rawFile", ")", ";", "}", ")", ";", "}" ]
Checks whether the given file can be optimized further and return the information about the check @examples 1. { name: 'file.ext', isOptimized: true, exitCode: 0 } 2. { name: 'file.ext', isOptimized: false, exitCode: 0 } 3. { name: 'file.ext', exitCode: 1 } 4. { name: 'file.ext', exitCode: 2 } @param {File} rawFile @param {Function[]} algorithms @param {Object} [opts] -> lib/defaults.js @param {Number} [opts.tolerance=0] @param {String[]} [opts.reporters=[]] @param {String} [opts._tmpDir=md5] @returns {Promise * Object}
[ "Checks", "whether", "the", "given", "file", "can", "be", "optimized", "further", "and", "return", "the", "information", "about", "the", "check" ]
92dc730bcedf6f20713429c1c0843390377c8a24
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/modes.js#L167-L186
25,819
ripple/ripple-hashes
src/sha512half.js
sha512half
function sha512half(buffer) { var sha512 = createHash('sha512'); return sha512.update(buffer).digest('hex').toUpperCase().slice(0, 64); }
javascript
function sha512half(buffer) { var sha512 = createHash('sha512'); return sha512.update(buffer).digest('hex').toUpperCase().slice(0, 64); }
[ "function", "sha512half", "(", "buffer", ")", "{", "var", "sha512", "=", "createHash", "(", "'sha512'", ")", ";", "return", "sha512", ".", "update", "(", "buffer", ")", ".", "digest", "(", "'hex'", ")", ".", "toUpperCase", "(", ")", ".", "slice", "(", "0", ",", "64", ")", ";", "}" ]
For a hash function, rippled uses SHA-512 and then truncates the result to the first 256 bytes. This algorithm, informally called SHA-512Half, provides an output that has comparable security to SHA-256, but runs faster on 64-bit processors.
[ "For", "a", "hash", "function", "rippled", "uses", "SHA", "-", "512", "and", "then", "truncates", "the", "result", "to", "the", "first", "256", "bytes", ".", "This", "algorithm", "informally", "called", "SHA", "-", "512Half", "provides", "an", "output", "that", "has", "comparable", "security", "to", "SHA", "-", "256", "but", "runs", "faster", "on", "64", "-", "bit", "processors", "." ]
7512d0e0e835f3cf132dfb1f69d2f22c0554e409
https://github.com/ripple/ripple-hashes/blob/7512d0e0e835f3cf132dfb1f69d2f22c0554e409/src/sha512half.js#L8-L11
25,820
bem-archive/image-optim
lib/algorithms/png.js
_compress
function _compress(command, outputFile) { return qexec(command) .then(function () { return outputFile.loadSize(); }) .fail(function (err) { // Before using of 'advpng' a raw file has to be copied // This algorithm can not compress a file and write a result to another file return qfs.exists(outputFile.name) .then(function (exists) { if (exists) { outputFile.remove(); } throw err; }); }); }
javascript
function _compress(command, outputFile) { return qexec(command) .then(function () { return outputFile.loadSize(); }) .fail(function (err) { // Before using of 'advpng' a raw file has to be copied // This algorithm can not compress a file and write a result to another file return qfs.exists(outputFile.name) .then(function (exists) { if (exists) { outputFile.remove(); } throw err; }); }); }
[ "function", "_compress", "(", "command", ",", "outputFile", ")", "{", "return", "qexec", "(", "command", ")", ".", "then", "(", "function", "(", ")", "{", "return", "outputFile", ".", "loadSize", "(", ")", ";", "}", ")", ".", "fail", "(", "function", "(", "err", ")", "{", "// Before using of 'advpng' a raw file has to be copied", "// This algorithm can not compress a file and write a result to another file", "return", "qfs", ".", "exists", "(", "outputFile", ".", "name", ")", ".", "then", "(", "function", "(", "exists", ")", "{", "if", "(", "exists", ")", "{", "outputFile", ".", "remove", "(", ")", ";", "}", "throw", "err", ";", "}", ")", ";", "}", ")", ";", "}" ]
Executes the given compression command and returns the instace of the compressed file @param {String} command @param {File} outputFile @returns {Promise * File}
[ "Executes", "the", "given", "compression", "command", "and", "returns", "the", "instace", "of", "the", "compressed", "file" ]
92dc730bcedf6f20713429c1c0843390377c8a24
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/algorithms/png.js#L18-L35
25,821
bem-archive/image-optim
lib/image-optim.js
_splice
function _splice(files, length) { var spliced = []; while (files.length) { spliced.push(files.splice(0, length)); } return spliced; }
javascript
function _splice(files, length) { var spliced = []; while (files.length) { spliced.push(files.splice(0, length)); } return spliced; }
[ "function", "_splice", "(", "files", ",", "length", ")", "{", "var", "spliced", "=", "[", "]", ";", "while", "(", "files", ".", "length", ")", "{", "spliced", ".", "push", "(", "files", ".", "splice", "(", "0", ",", "length", ")", ")", ";", "}", "return", "spliced", ";", "}" ]
Divides the given array of files into groups of the given length @param {String[]} files @param {Number} length @returns {Object[]}
[ "Divides", "the", "given", "array", "of", "files", "into", "groups", "of", "the", "given", "length" ]
92dc730bcedf6f20713429c1c0843390377c8a24
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/image-optim.js#L15-L23
25,822
bem-archive/image-optim
lib/image-optim.js
_reduceImageOptimFunc
function _reduceImageOptimFunc(prev, next) { return prev.then(function (res) { return Q.all(next.map(function (filename) { return modes[mode](new File(filename), algorithms, opts); })) .then(function (stepRes) { return res.concat(stepRes); }); }); }
javascript
function _reduceImageOptimFunc(prev, next) { return prev.then(function (res) { return Q.all(next.map(function (filename) { return modes[mode](new File(filename), algorithms, opts); })) .then(function (stepRes) { return res.concat(stepRes); }); }); }
[ "function", "_reduceImageOptimFunc", "(", "prev", ",", "next", ")", "{", "return", "prev", ".", "then", "(", "function", "(", "res", ")", "{", "return", "Q", ".", "all", "(", "next", ".", "map", "(", "function", "(", "filename", ")", "{", "return", "modes", "[", "mode", "]", "(", "new", "File", "(", "filename", ")", ",", "algorithms", ",", "opts", ")", ";", "}", ")", ")", ".", "then", "(", "function", "(", "stepRes", ")", "{", "return", "res", ".", "concat", "(", "stepRes", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Helping reduce function @param {Promise * OptimResult[]|LintResult[]} prev @param {Promise * OptimResult[]|LintResult[]} next @returns {Promise * OptimResult[]|LintResult[]}
[ "Helping", "reduce", "function" ]
92dc730bcedf6f20713429c1c0843390377c8a24
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/image-optim.js#L56-L65
25,823
ripple/ripple-hashes
src/shamap.js
SHAMapTreeNodeLeaf
function SHAMapTreeNodeLeaf(tag, data, type) { SHAMapTreeNode.call(this); if (typeof tag !== 'string') { throw new Error('Tag is unexpected type.'); } this.tag = tag; this.type = type; this.data = data; }
javascript
function SHAMapTreeNodeLeaf(tag, data, type) { SHAMapTreeNode.call(this); if (typeof tag !== 'string') { throw new Error('Tag is unexpected type.'); } this.tag = tag; this.type = type; this.data = data; }
[ "function", "SHAMapTreeNodeLeaf", "(", "tag", ",", "data", ",", "type", ")", "{", "SHAMapTreeNode", ".", "call", "(", "this", ")", ";", "if", "(", "typeof", "tag", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'Tag is unexpected type.'", ")", ";", "}", "this", ".", "tag", "=", "tag", ";", "this", ".", "type", "=", "type", ";", "this", ".", "data", "=", "data", ";", "}" ]
Leaf node in a SHAMap tree. @param {String} tag (equates to a ledger entry `index`) @param {String} data (hex of account state, transaction etc) @param {Number} type (one of TYPE_ACCOUNT_STATE, TYPE_TRANSACTION_MD etc) @class
[ "Leaf", "node", "in", "a", "SHAMap", "tree", "." ]
7512d0e0e835f3cf132dfb1f69d2f22c0554e409
https://github.com/ripple/ripple-hashes/blob/7512d0e0e835f3cf132dfb1f69d2f22c0554e409/src/shamap.js#L253-L263
25,824
ripple/ripple-hashes
src/shamap.js
SHAMap
function SHAMap(version) { this.version = version === undefined ? 1 : version; this.root = this.version === 1 ? new SHAMapTreeNodeInner(0) : new SHAMapTreeNodeInnerV2(0); }
javascript
function SHAMap(version) { this.version = version === undefined ? 1 : version; this.root = this.version === 1 ? new SHAMapTreeNodeInner(0) : new SHAMapTreeNodeInnerV2(0); }
[ "function", "SHAMap", "(", "version", ")", "{", "this", ".", "version", "=", "version", "===", "undefined", "?", "1", ":", "version", ";", "this", ".", "root", "=", "this", ".", "version", "===", "1", "?", "new", "SHAMapTreeNodeInner", "(", "0", ")", ":", "new", "SHAMapTreeNodeInnerV2", "(", "0", ")", ";", "}" ]
SHAMap tree. @param {Number} version (inner node version number) @class
[ "SHAMap", "tree", "." ]
7512d0e0e835f3cf132dfb1f69d2f22c0554e409
https://github.com/ripple/ripple-hashes/blob/7512d0e0e835f3cf132dfb1f69d2f22c0554e409/src/shamap.js#L288-L292
25,825
theasta/grunt-assets-versioning
tasks/helpers/task.js
function (taskName, taskFiles) { grunt.log.writeln("Versioning files from " + taskName + " task."); this.taskName = taskName; this.taskConfig = this.getTaskConfig(); if (!this.taskConfig) { grunt.fail.warn("Task '" + this.taskName + "' doesn't exist or doesn't have any configuration.", 1); } this.taskFiles = taskFiles || this.getFiles(); if (!this.taskFiles || this.taskFiles.length === 0) { grunt.fail.warn("Task '" + this.taskName + "' doesn't have any src-dest file mappings.", 1); } }
javascript
function (taskName, taskFiles) { grunt.log.writeln("Versioning files from " + taskName + " task."); this.taskName = taskName; this.taskConfig = this.getTaskConfig(); if (!this.taskConfig) { grunt.fail.warn("Task '" + this.taskName + "' doesn't exist or doesn't have any configuration.", 1); } this.taskFiles = taskFiles || this.getFiles(); if (!this.taskFiles || this.taskFiles.length === 0) { grunt.fail.warn("Task '" + this.taskName + "' doesn't have any src-dest file mappings.", 1); } }
[ "function", "(", "taskName", ",", "taskFiles", ")", "{", "grunt", ".", "log", ".", "writeln", "(", "\"Versioning files from \"", "+", "taskName", "+", "\" task.\"", ")", ";", "this", ".", "taskName", "=", "taskName", ";", "this", ".", "taskConfig", "=", "this", ".", "getTaskConfig", "(", ")", ";", "if", "(", "!", "this", ".", "taskConfig", ")", "{", "grunt", ".", "fail", ".", "warn", "(", "\"Task '\"", "+", "this", ".", "taskName", "+", "\"' doesn't exist or doesn't have any configuration.\"", ",", "1", ")", ";", "}", "this", ".", "taskFiles", "=", "taskFiles", "||", "this", ".", "getFiles", "(", ")", ";", "if", "(", "!", "this", ".", "taskFiles", "||", "this", ".", "taskFiles", ".", "length", "===", "0", ")", "{", "grunt", ".", "fail", ".", "warn", "(", "\"Task '\"", "+", "this", ".", "taskName", "+", "\"' doesn't have any src-dest file mappings.\"", ",", "1", ")", ";", "}", "}" ]
Create a task instance @param {string} taskName @param {Array} [taskFiles] @constructor
[ "Create", "a", "task", "instance" ]
5e2e62b90e3cc2b635582cce0e6598ce2bc8acab
https://github.com/theasta/grunt-assets-versioning/blob/5e2e62b90e3cc2b635582cce0e6598ce2bc8acab/tasks/helpers/task.js#L15-L30
25,826
bpmn-io/bpmnlint
rules/helper.js
disallowNodeType
function disallowNodeType(type) { return function() { function check(node, reporter) { if (is(node, type)) { reporter.report(node.id, 'Element has disallowed type <' + type + '>'); } } return { check }; }; }
javascript
function disallowNodeType(type) { return function() { function check(node, reporter) { if (is(node, type)) { reporter.report(node.id, 'Element has disallowed type <' + type + '>'); } } return { check }; }; }
[ "function", "disallowNodeType", "(", "type", ")", "{", "return", "function", "(", ")", "{", "function", "check", "(", "node", ",", "reporter", ")", "{", "if", "(", "is", "(", "node", ",", "type", ")", ")", "{", "reporter", ".", "report", "(", "node", ".", "id", ",", "'Element has disallowed type <'", "+", "type", "+", "'>'", ")", ";", "}", "}", "return", "{", "check", "}", ";", "}", ";", "}" ]
Create a checker that disallows the given element type. @param {String} type @return {Function} ruleImpl
[ "Create", "a", "checker", "that", "disallows", "the", "given", "element", "type", "." ]
fb029d8064506b97a5f500a9760ae35a0d6e4ba9
https://github.com/bpmn-io/bpmnlint/blob/fb029d8064506b97a5f500a9760ae35a0d6e4ba9/rules/helper.js#L12-L29
25,827
bpmn-io/bpmnlint
bin/bpmnlint.js
parseDiagram
function parseDiagram(diagramXML) { return new Promise((resolve, reject) => { moddle.fromXML(diagramXML, (error, moddleElement, context) => { if (error) { return resolve({ error }); } const warnings = context.warnings || []; return resolve({ moddleElement, warnings }); }); }); }
javascript
function parseDiagram(diagramXML) { return new Promise((resolve, reject) => { moddle.fromXML(diagramXML, (error, moddleElement, context) => { if (error) { return resolve({ error }); } const warnings = context.warnings || []; return resolve({ moddleElement, warnings }); }); }); }
[ "function", "parseDiagram", "(", "diagramXML", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "moddle", ".", "fromXML", "(", "diagramXML", ",", "(", "error", ",", "moddleElement", ",", "context", ")", "=>", "{", "if", "(", "error", ")", "{", "return", "resolve", "(", "{", "error", "}", ")", ";", "}", "const", "warnings", "=", "context", ".", "warnings", "||", "[", "]", ";", "return", "resolve", "(", "{", "moddleElement", ",", "warnings", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Reads XML form path and return moddle object @param {*} sourcePath
[ "Reads", "XML", "form", "path", "and", "return", "moddle", "object" ]
fb029d8064506b97a5f500a9760ae35a0d6e4ba9
https://github.com/bpmn-io/bpmnlint/blob/fb029d8064506b97a5f500a9760ae35a0d6e4ba9/bin/bpmnlint.js#L34-L52
25,828
bpmn-io/bpmnlint
bin/bpmnlint.js
tableEntry
function tableEntry(report) { const category = report.category; const color = category === 'error' ? red : yellow; return [ report.id || '', color(categoryMap[category] || category), report.message, report.name || '' ]; }
javascript
function tableEntry(report) { const category = report.category; const color = category === 'error' ? red : yellow; return [ report.id || '', color(categoryMap[category] || category), report.message, report.name || '' ]; }
[ "function", "tableEntry", "(", "report", ")", "{", "const", "category", "=", "report", ".", "category", ";", "const", "color", "=", "category", "===", "'error'", "?", "red", ":", "yellow", ";", "return", "[", "report", ".", "id", "||", "''", ",", "color", "(", "categoryMap", "[", "category", "]", "||", "category", ")", ",", "report", ".", "message", ",", "report", ".", "name", "||", "''", "]", ";", "}" ]
Logs a formatted message
[ "Logs", "a", "formatted", "message" ]
fb029d8064506b97a5f500a9760ae35a0d6e4ba9
https://github.com/bpmn-io/bpmnlint/blob/fb029d8064506b97a5f500a9760ae35a0d6e4ba9/bin/bpmnlint.js#L61-L67
25,829
bpmn-io/bpmnlint
bin/bpmnlint.js
printReports
function printReports(filePath, results) { let errorCount = 0; let warningCount = 0; const table = createTable(); Object.entries(results).forEach(function([ name, reports ]) { reports.forEach(function(report) { const { category, id, message, name: reportName } = report; table.push(tableEntry({ category, id, message, name: reportName || name })); if (category === 'error') { errorCount++; } else { warningCount++; } }); }); const problemCount = warningCount + errorCount; if (problemCount) { console.log(); console.log(underline(path.resolve(filePath))); console.log(table.toString()); } return { errorCount, warningCount }; }
javascript
function printReports(filePath, results) { let errorCount = 0; let warningCount = 0; const table = createTable(); Object.entries(results).forEach(function([ name, reports ]) { reports.forEach(function(report) { const { category, id, message, name: reportName } = report; table.push(tableEntry({ category, id, message, name: reportName || name })); if (category === 'error') { errorCount++; } else { warningCount++; } }); }); const problemCount = warningCount + errorCount; if (problemCount) { console.log(); console.log(underline(path.resolve(filePath))); console.log(table.toString()); } return { errorCount, warningCount }; }
[ "function", "printReports", "(", "filePath", ",", "results", ")", "{", "let", "errorCount", "=", "0", ";", "let", "warningCount", "=", "0", ";", "const", "table", "=", "createTable", "(", ")", ";", "Object", ".", "entries", "(", "results", ")", ".", "forEach", "(", "function", "(", "[", "name", ",", "reports", "]", ")", "{", "reports", ".", "forEach", "(", "function", "(", "report", ")", "{", "const", "{", "category", ",", "id", ",", "message", ",", "name", ":", "reportName", "}", "=", "report", ";", "table", ".", "push", "(", "tableEntry", "(", "{", "category", ",", "id", ",", "message", ",", "name", ":", "reportName", "||", "name", "}", ")", ")", ";", "if", "(", "category", "===", "'error'", ")", "{", "errorCount", "++", ";", "}", "else", "{", "warningCount", "++", ";", "}", "}", ")", ";", "}", ")", ";", "const", "problemCount", "=", "warningCount", "+", "errorCount", ";", "if", "(", "problemCount", ")", "{", "console", ".", "log", "(", ")", ";", "console", ".", "log", "(", "underline", "(", "path", ".", "resolve", "(", "filePath", ")", ")", ")", ";", "console", ".", "log", "(", "table", ".", "toString", "(", ")", ")", ";", "}", "return", "{", "errorCount", ",", "warningCount", "}", ";", "}" ]
Prints lint results to the console @param {String} filePath @param {Object} results
[ "Prints", "lint", "results", "to", "the", "console" ]
fb029d8064506b97a5f500a9760ae35a0d6e4ba9
https://github.com/bpmn-io/bpmnlint/blob/fb029d8064506b97a5f500a9760ae35a0d6e4ba9/bin/bpmnlint.js#L102-L147
25,830
meteor/promise
promise_server.js
awaitPromise
function awaitPromise(promise) { var Promise = promise.constructor; var Fiber = Promise.Fiber; assert.strictEqual( typeof Fiber, "function", "Cannot await unless Promise.Fiber is defined" ); var fiber = Fiber.current; assert.ok( fiber instanceof Fiber, "Cannot await without a Fiber" ); var run = fiber.run; var throwInto = fiber.throwInto; if (process.domain) { run = process.domain.bind(run); throwInto = process.domain.bind(throwInto); } // The overridden es6PromiseThen function is adequate here because these // two callbacks do not need to run in a Fiber. es6PromiseThen.call(promise, function (result) { tryCatchNextTick(fiber, run, [result]); }, function (error) { tryCatchNextTick(fiber, throwInto, [error]); }); return stackSafeYield(Fiber, awaitPromise); }
javascript
function awaitPromise(promise) { var Promise = promise.constructor; var Fiber = Promise.Fiber; assert.strictEqual( typeof Fiber, "function", "Cannot await unless Promise.Fiber is defined" ); var fiber = Fiber.current; assert.ok( fiber instanceof Fiber, "Cannot await without a Fiber" ); var run = fiber.run; var throwInto = fiber.throwInto; if (process.domain) { run = process.domain.bind(run); throwInto = process.domain.bind(throwInto); } // The overridden es6PromiseThen function is adequate here because these // two callbacks do not need to run in a Fiber. es6PromiseThen.call(promise, function (result) { tryCatchNextTick(fiber, run, [result]); }, function (error) { tryCatchNextTick(fiber, throwInto, [error]); }); return stackSafeYield(Fiber, awaitPromise); }
[ "function", "awaitPromise", "(", "promise", ")", "{", "var", "Promise", "=", "promise", ".", "constructor", ";", "var", "Fiber", "=", "Promise", ".", "Fiber", ";", "assert", ".", "strictEqual", "(", "typeof", "Fiber", ",", "\"function\"", ",", "\"Cannot await unless Promise.Fiber is defined\"", ")", ";", "var", "fiber", "=", "Fiber", ".", "current", ";", "assert", ".", "ok", "(", "fiber", "instanceof", "Fiber", ",", "\"Cannot await without a Fiber\"", ")", ";", "var", "run", "=", "fiber", ".", "run", ";", "var", "throwInto", "=", "fiber", ".", "throwInto", ";", "if", "(", "process", ".", "domain", ")", "{", "run", "=", "process", ".", "domain", ".", "bind", "(", "run", ")", ";", "throwInto", "=", "process", ".", "domain", ".", "bind", "(", "throwInto", ")", ";", "}", "// The overridden es6PromiseThen function is adequate here because these", "// two callbacks do not need to run in a Fiber.", "es6PromiseThen", ".", "call", "(", "promise", ",", "function", "(", "result", ")", "{", "tryCatchNextTick", "(", "fiber", ",", "run", ",", "[", "result", "]", ")", ";", "}", ",", "function", "(", "error", ")", "{", "tryCatchNextTick", "(", "fiber", ",", "throwInto", ",", "[", "error", "]", ")", ";", "}", ")", ";", "return", "stackSafeYield", "(", "Fiber", ",", "awaitPromise", ")", ";", "}" ]
Yield the current Fiber until the given Promise has been fulfilled.
[ "Yield", "the", "current", "Fiber", "until", "the", "given", "Promise", "has", "been", "fulfilled", "." ]
cab087d69b8a7be4ae6b9aa45f0abae47d0778fa
https://github.com/meteor/promise/blob/cab087d69b8a7be4ae6b9aa45f0abae47d0778fa/promise_server.js#L64-L97
25,831
aurelia/pal-nodejs
dist/index.js
initialize
function initialize() { if (aurelia_pal_1.isInitialized) { return; } let pal = nodejs_pal_builder_1.buildPal(); aurelia_pal_1.initializePAL((platform, feature, dom) => { Object.assign(platform, pal.platform); Object.setPrototypeOf(platform, pal.platform.constructor.prototype); Object.assign(dom, pal.dom); Object.setPrototypeOf(dom, pal.dom.constructor.prototype); Object.assign(feature, pal.feature); Object.setPrototypeOf(feature, pal.feature.constructor.prototype); (function (global) { global.console = global.console || {}; let con = global.console; let prop; let method; let empty = {}; let dummy = function () { }; let properties = 'memory'.split(','); let methods = ('assert,clear,count,debug,dir,dirxml,error,exception,group,' + 'groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,' + 'show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn').split(','); while (prop = properties.pop()) if (!con[prop]) con[prop] = empty; while (method = methods.pop()) if (!con[method]) con[method] = dummy; })(platform.global); if (platform.global.console && typeof console.log === 'object') { if (typeof console['debug'] === 'undefined') { console['debug'] = this.bind(console['log'], console); } ['log', 'info', 'warn', 'error', 'assert', 'dir', 'clear', 'profile', 'profileEnd'].forEach(function (method) { console[method] = this.bind(console[method], console); }, Function.prototype.call); } Object.defineProperty(dom, 'title', { get: function () { return pal.global.document.title; }, set: function (value) { pal.global.document.title = value; } }); Object.defineProperty(dom, 'activeElement', { get: function () { return pal.global.document.activeElement; } }); Object.defineProperty(platform, 'XMLHttpRequest', { get: function () { return pal.global.XMLHttpRequest; } }); }); }
javascript
function initialize() { if (aurelia_pal_1.isInitialized) { return; } let pal = nodejs_pal_builder_1.buildPal(); aurelia_pal_1.initializePAL((platform, feature, dom) => { Object.assign(platform, pal.platform); Object.setPrototypeOf(platform, pal.platform.constructor.prototype); Object.assign(dom, pal.dom); Object.setPrototypeOf(dom, pal.dom.constructor.prototype); Object.assign(feature, pal.feature); Object.setPrototypeOf(feature, pal.feature.constructor.prototype); (function (global) { global.console = global.console || {}; let con = global.console; let prop; let method; let empty = {}; let dummy = function () { }; let properties = 'memory'.split(','); let methods = ('assert,clear,count,debug,dir,dirxml,error,exception,group,' + 'groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,' + 'show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn').split(','); while (prop = properties.pop()) if (!con[prop]) con[prop] = empty; while (method = methods.pop()) if (!con[method]) con[method] = dummy; })(platform.global); if (platform.global.console && typeof console.log === 'object') { if (typeof console['debug'] === 'undefined') { console['debug'] = this.bind(console['log'], console); } ['log', 'info', 'warn', 'error', 'assert', 'dir', 'clear', 'profile', 'profileEnd'].forEach(function (method) { console[method] = this.bind(console[method], console); }, Function.prototype.call); } Object.defineProperty(dom, 'title', { get: function () { return pal.global.document.title; }, set: function (value) { pal.global.document.title = value; } }); Object.defineProperty(dom, 'activeElement', { get: function () { return pal.global.document.activeElement; } }); Object.defineProperty(platform, 'XMLHttpRequest', { get: function () { return pal.global.XMLHttpRequest; } }); }); }
[ "function", "initialize", "(", ")", "{", "if", "(", "aurelia_pal_1", ".", "isInitialized", ")", "{", "return", ";", "}", "let", "pal", "=", "nodejs_pal_builder_1", ".", "buildPal", "(", ")", ";", "aurelia_pal_1", ".", "initializePAL", "(", "(", "platform", ",", "feature", ",", "dom", ")", "=>", "{", "Object", ".", "assign", "(", "platform", ",", "pal", ".", "platform", ")", ";", "Object", ".", "setPrototypeOf", "(", "platform", ",", "pal", ".", "platform", ".", "constructor", ".", "prototype", ")", ";", "Object", ".", "assign", "(", "dom", ",", "pal", ".", "dom", ")", ";", "Object", ".", "setPrototypeOf", "(", "dom", ",", "pal", ".", "dom", ".", "constructor", ".", "prototype", ")", ";", "Object", ".", "assign", "(", "feature", ",", "pal", ".", "feature", ")", ";", "Object", ".", "setPrototypeOf", "(", "feature", ",", "pal", ".", "feature", ".", "constructor", ".", "prototype", ")", ";", "(", "function", "(", "global", ")", "{", "global", ".", "console", "=", "global", ".", "console", "||", "{", "}", ";", "let", "con", "=", "global", ".", "console", ";", "let", "prop", ";", "let", "method", ";", "let", "empty", "=", "{", "}", ";", "let", "dummy", "=", "function", "(", ")", "{", "}", ";", "let", "properties", "=", "'memory'", ".", "split", "(", "','", ")", ";", "let", "methods", "=", "(", "'assert,clear,count,debug,dir,dirxml,error,exception,group,'", "+", "'groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,'", "+", "'show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn'", ")", ".", "split", "(", "','", ")", ";", "while", "(", "prop", "=", "properties", ".", "pop", "(", ")", ")", "if", "(", "!", "con", "[", "prop", "]", ")", "con", "[", "prop", "]", "=", "empty", ";", "while", "(", "method", "=", "methods", ".", "pop", "(", ")", ")", "if", "(", "!", "con", "[", "method", "]", ")", "con", "[", "method", "]", "=", "dummy", ";", "}", ")", "(", "platform", ".", "global", ")", ";", "if", "(", "platform", ".", "global", ".", "console", "&&", "typeof", "console", ".", "log", "===", "'object'", ")", "{", "if", "(", "typeof", "console", "[", "'debug'", "]", "===", "'undefined'", ")", "{", "console", "[", "'debug'", "]", "=", "this", ".", "bind", "(", "console", "[", "'log'", "]", ",", "console", ")", ";", "}", "[", "'log'", ",", "'info'", ",", "'warn'", ",", "'error'", ",", "'assert'", ",", "'dir'", ",", "'clear'", ",", "'profile'", ",", "'profileEnd'", "]", ".", "forEach", "(", "function", "(", "method", ")", "{", "console", "[", "method", "]", "=", "this", ".", "bind", "(", "console", "[", "method", "]", ",", "console", ")", ";", "}", ",", "Function", ".", "prototype", ".", "call", ")", ";", "}", "Object", ".", "defineProperty", "(", "dom", ",", "'title'", ",", "{", "get", ":", "function", "(", ")", "{", "return", "pal", ".", "global", ".", "document", ".", "title", ";", "}", ",", "set", ":", "function", "(", "value", ")", "{", "pal", ".", "global", ".", "document", ".", "title", "=", "value", ";", "}", "}", ")", ";", "Object", ".", "defineProperty", "(", "dom", ",", "'activeElement'", ",", "{", "get", ":", "function", "(", ")", "{", "return", "pal", ".", "global", ".", "document", ".", "activeElement", ";", "}", "}", ")", ";", "Object", ".", "defineProperty", "(", "platform", ",", "'XMLHttpRequest'", ",", "{", "get", ":", "function", "(", ")", "{", "return", "pal", ".", "global", ".", "XMLHttpRequest", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Initializes the PAL with the NodeJS-targeted implementation.
[ "Initializes", "the", "PAL", "with", "the", "NodeJS", "-", "targeted", "implementation", "." ]
711664e16486eac4c33a59cc633813aa316a8ad4
https://github.com/aurelia/pal-nodejs/blob/711664e16486eac4c33a59cc633813aa316a8ad4/dist/index.js#L12-L69
25,832
angularjs-oauth/oauth-ng
dist/oauth-ng.js
function (jws, pubKey, alg) { /* convert various public key format to RSAKey object see @KEYUTIL.getKey for a full list of supported input format */ var rsaKey = KEYUTIL.getKey(pubKey); return KJUR.jws.JWS.verify(jws, rsaKey, [alg]); }
javascript
function (jws, pubKey, alg) { /* convert various public key format to RSAKey object see @KEYUTIL.getKey for a full list of supported input format */ var rsaKey = KEYUTIL.getKey(pubKey); return KJUR.jws.JWS.verify(jws, rsaKey, [alg]); }
[ "function", "(", "jws", ",", "pubKey", ",", "alg", ")", "{", "/*\n convert various public key format to RSAKey object\n see @KEYUTIL.getKey for a full list of supported input format\n */", "var", "rsaKey", "=", "KEYUTIL", ".", "getKey", "(", "pubKey", ")", ";", "return", "KJUR", ".", "jws", ".", "JWS", ".", "verify", "(", "jws", ",", "rsaKey", ",", "[", "alg", "]", ")", ";", "}" ]
Verifies the JWS string using the JWK @param {string} jws The JWS string @param {object} pubKey The public key that will be used to verify the signature @param {string} alg The algorithm string. Expecting 'RS256', 'RS384', or 'RS512' @returns {boolean} Validity of the JWS signature @throws {OidcException}
[ "Verifies", "the", "JWS", "string", "using", "the", "JWK" ]
48aa4fa86fdd8d9c859be4206049ec0d7422c720
https://github.com/angularjs-oauth/oauth-ng/blob/48aa4fa86fdd8d9c859be4206049ec0d7422c720/dist/oauth-ng.js#L245-L253
25,833
angularjs-oauth/oauth-ng
dist/oauth-ng.js
function (id_token) { var jws = new KJUR.jws.JWS(); jws.parseJWS(id_token); return [jws.parsedJWS.headS, jws.parsedJWS.payloadS, jws.parsedJWS.si]; }
javascript
function (id_token) { var jws = new KJUR.jws.JWS(); jws.parseJWS(id_token); return [jws.parsedJWS.headS, jws.parsedJWS.payloadS, jws.parsedJWS.si]; }
[ "function", "(", "id_token", ")", "{", "var", "jws", "=", "new", "KJUR", ".", "jws", ".", "JWS", "(", ")", ";", "jws", ".", "parseJWS", "(", "id_token", ")", ";", "return", "[", "jws", ".", "parsedJWS", ".", "headS", ",", "jws", ".", "parsedJWS", ".", "payloadS", ",", "jws", ".", "parsedJWS", ".", "si", "]", ";", "}" ]
Splits the ID Token string into the individual JWS parts @param {string} id_token ID Token @returns {Array} An array of the JWS compact serialization components (header, payload, signature)
[ "Splits", "the", "ID", "Token", "string", "into", "the", "individual", "JWS", "parts" ]
48aa4fa86fdd8d9c859be4206049ec0d7422c720
https://github.com/angularjs-oauth/oauth-ng/blob/48aa4fa86fdd8d9c859be4206049ec0d7422c720/dist/oauth-ng.js#L260-L264
25,834
angularjs-oauth/oauth-ng
dist/oauth-ng.js
function (jsonS) { var jws = KJUR.jws.JWS; if(jws.isSafeJSONString(jsonS)) { return jws.readSafeJSONString(jsonS); } return null; }
javascript
function (jsonS) { var jws = KJUR.jws.JWS; if(jws.isSafeJSONString(jsonS)) { return jws.readSafeJSONString(jsonS); } return null; }
[ "function", "(", "jsonS", ")", "{", "var", "jws", "=", "KJUR", ".", "jws", ".", "JWS", ";", "if", "(", "jws", ".", "isSafeJSONString", "(", "jsonS", ")", ")", "{", "return", "jws", ".", "readSafeJSONString", "(", "jsonS", ")", ";", "}", "return", "null", ";", "}" ]
Get the JSON object from the JSON string @param {string} jsonS JSON string @returns {object|null} JSON object or null
[ "Get", "the", "JSON", "object", "from", "the", "JSON", "string" ]
48aa4fa86fdd8d9c859be4206049ec0d7422c720
https://github.com/angularjs-oauth/oauth-ng/blob/48aa4fa86fdd8d9c859be4206049ec0d7422c720/dist/oauth-ng.js#L282-L288
25,835
angularjs-oauth/oauth-ng
dist/oauth-ng.js
function(params){ service.token = service.token || {}; // init the token angular.extend(service.token, params); // set the access token params setTokenInSession(); // save the token into the session setExpiresAtEvent(); // event to fire when the token expires return service.token; }
javascript
function(params){ service.token = service.token || {}; // init the token angular.extend(service.token, params); // set the access token params setTokenInSession(); // save the token into the session setExpiresAtEvent(); // event to fire when the token expires return service.token; }
[ "function", "(", "params", ")", "{", "service", ".", "token", "=", "service", ".", "token", "||", "{", "}", ";", "// init the token", "angular", ".", "extend", "(", "service", ".", "token", ",", "params", ")", ";", "// set the access token params", "setTokenInSession", "(", ")", ";", "// save the token into the session", "setExpiresAtEvent", "(", ")", ";", "// event to fire when the token expires", "return", "service", ".", "token", ";", "}" ]
Set the access token. @param params @returns {*|{}}
[ "Set", "the", "access", "token", "." ]
48aa4fa86fdd8d9c859be4206049ec0d7422c720
https://github.com/angularjs-oauth/oauth-ng/blob/48aa4fa86fdd8d9c859be4206049ec0d7422c720/dist/oauth-ng.js#L469-L476
25,836
angularjs-oauth/oauth-ng
dist/oauth-ng.js
function(hash){ var params = {}, regex = /([^&=]+)=([^&]*)/g, m; while ((m = regex.exec(hash)) !== null) { params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); } // OpenID Connect if (params.id_token && !params.error) { IdToken.validateTokensAndPopulateClaims(params); return params; } // Oauth2 if(params.access_token || params.error){ return params; } }
javascript
function(hash){ var params = {}, regex = /([^&=]+)=([^&]*)/g, m; while ((m = regex.exec(hash)) !== null) { params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); } // OpenID Connect if (params.id_token && !params.error) { IdToken.validateTokensAndPopulateClaims(params); return params; } // Oauth2 if(params.access_token || params.error){ return params; } }
[ "function", "(", "hash", ")", "{", "var", "params", "=", "{", "}", ",", "regex", "=", "/", "([^&=]+)=([^&]*)", "/", "g", ",", "m", ";", "while", "(", "(", "m", "=", "regex", ".", "exec", "(", "hash", ")", ")", "!==", "null", ")", "{", "params", "[", "decodeURIComponent", "(", "m", "[", "1", "]", ")", "]", "=", "decodeURIComponent", "(", "m", "[", "2", "]", ")", ";", "}", "// OpenID Connect", "if", "(", "params", ".", "id_token", "&&", "!", "params", ".", "error", ")", "{", "IdToken", ".", "validateTokensAndPopulateClaims", "(", "params", ")", ";", "return", "params", ";", "}", "// Oauth2", "if", "(", "params", ".", "access_token", "||", "params", ".", "error", ")", "{", "return", "params", ";", "}", "}" ]
Parse the fragment URI and return an object @param hash @returns {{}}
[ "Parse", "the", "fragment", "URI", "and", "return", "an", "object" ]
48aa4fa86fdd8d9c859be4206049ec0d7422c720
https://github.com/angularjs-oauth/oauth-ng/blob/48aa4fa86fdd8d9c859be4206049ec0d7422c720/dist/oauth-ng.js#L483-L502
25,837
angularjs-oauth/oauth-ng
dist/oauth-ng.js
function(){ // Don't bother if there's no expires token if (typeof(service.token.expires_at) === 'undefined' || service.token.expires_at === null) { return; } cancelExpiresAtEvent(); var time = (new Date(service.token.expires_at))-(new Date()); if(time && time > 0 && time <= 2147483647){ expiresAtEvent = $interval(function(){ $rootScope.$broadcast('oauth:expired', service.token); }, time, 1); } }
javascript
function(){ // Don't bother if there's no expires token if (typeof(service.token.expires_at) === 'undefined' || service.token.expires_at === null) { return; } cancelExpiresAtEvent(); var time = (new Date(service.token.expires_at))-(new Date()); if(time && time > 0 && time <= 2147483647){ expiresAtEvent = $interval(function(){ $rootScope.$broadcast('oauth:expired', service.token); }, time, 1); } }
[ "function", "(", ")", "{", "// Don't bother if there's no expires token", "if", "(", "typeof", "(", "service", ".", "token", ".", "expires_at", ")", "===", "'undefined'", "||", "service", ".", "token", ".", "expires_at", "===", "null", ")", "{", "return", ";", "}", "cancelExpiresAtEvent", "(", ")", ";", "var", "time", "=", "(", "new", "Date", "(", "service", ".", "token", ".", "expires_at", ")", ")", "-", "(", "new", "Date", "(", ")", ")", ";", "if", "(", "time", "&&", "time", ">", "0", "&&", "time", "<=", "2147483647", ")", "{", "expiresAtEvent", "=", "$interval", "(", "function", "(", ")", "{", "$rootScope", ".", "$broadcast", "(", "'oauth:expired'", ",", "service", ".", "token", ")", ";", "}", ",", "time", ",", "1", ")", ";", "}", "}" ]
Set the timeout at which the expired event is fired
[ "Set", "the", "timeout", "at", "which", "the", "expired", "event", "is", "fired" ]
48aa4fa86fdd8d9c859be4206049ec0d7422c720
https://github.com/angularjs-oauth/oauth-ng/blob/48aa4fa86fdd8d9c859be4206049ec0d7422c720/dist/oauth-ng.js#L532-L544
25,838
angularjs-oauth/oauth-ng
dist/oauth-ng.js
function(){ var curHash = $location.hash(); angular.forEach(hashFragmentKeys,function(hashKey){ var re = new RegExp('&'+hashKey+'(=[^&]*)?|^'+hashKey+'(=[^&]*)?&?'); curHash = curHash.replace(re,''); }); $location.hash(curHash); }
javascript
function(){ var curHash = $location.hash(); angular.forEach(hashFragmentKeys,function(hashKey){ var re = new RegExp('&'+hashKey+'(=[^&]*)?|^'+hashKey+'(=[^&]*)?&?'); curHash = curHash.replace(re,''); }); $location.hash(curHash); }
[ "function", "(", ")", "{", "var", "curHash", "=", "$location", ".", "hash", "(", ")", ";", "angular", ".", "forEach", "(", "hashFragmentKeys", ",", "function", "(", "hashKey", ")", "{", "var", "re", "=", "new", "RegExp", "(", "'&'", "+", "hashKey", "+", "'(=[^&]*)?|^'", "+", "hashKey", "+", "'(=[^&]*)?&?'", ")", ";", "curHash", "=", "curHash", ".", "replace", "(", "re", ",", "''", ")", ";", "}", ")", ";", "$location", ".", "hash", "(", "curHash", ")", ";", "}" ]
Remove the oAuth2 pieces from the hash fragment
[ "Remove", "the", "oAuth2", "pieces", "from", "the", "hash", "fragment" ]
48aa4fa86fdd8d9c859be4206049ec0d7422c720
https://github.com/angularjs-oauth/oauth-ng/blob/48aa4fa86fdd8d9c859be4206049ec0d7422c720/dist/oauth-ng.js#L556-L564
25,839
joaquimserafim/json-web-token
index.js
JWTError
function JWTError (message) { Error.call(this) Error.captureStackTrace(this, this.constructor) this.name = this.constructor.name this.message = message }
javascript
function JWTError (message) { Error.call(this) Error.captureStackTrace(this, this.constructor) this.name = this.constructor.name this.message = message }
[ "function", "JWTError", "(", "message", ")", "{", "Error", ".", "call", "(", "this", ")", "Error", ".", "captureStackTrace", "(", "this", ",", "this", ".", "constructor", ")", "this", ".", "name", "=", "this", ".", "constructor", ".", "name", "this", ".", "message", "=", "message", "}" ]
JWT token error
[ "JWT", "token", "error" ]
b67038f7d9ee11b6c6ddef6e7203008a1e984667
https://github.com/joaquimserafim/json-web-token/blob/b67038f7d9ee11b6c6ddef6e7203008a1e984667/index.js#L119-L124
25,840
jankolkmeier/xbee-api
lib/frame-builder.js
appendData
function appendData(data, builder) { if(Array.isArray(data) || Buffer.isBuffer(data)) { data = Buffer.from(data); } else { data = Buffer.from(data, 'ascii'); } builder.appendBuffer(data); }
javascript
function appendData(data, builder) { if(Array.isArray(data) || Buffer.isBuffer(data)) { data = Buffer.from(data); } else { data = Buffer.from(data, 'ascii'); } builder.appendBuffer(data); }
[ "function", "appendData", "(", "data", ",", "builder", ")", "{", "if", "(", "Array", ".", "isArray", "(", "data", ")", "||", "Buffer", ".", "isBuffer", "(", "data", ")", ")", "{", "data", "=", "Buffer", ".", "from", "(", "data", ")", ";", "}", "else", "{", "data", "=", "Buffer", ".", "from", "(", "data", ",", "'ascii'", ")", ";", "}", "builder", ".", "appendBuffer", "(", "data", ")", ";", "}" ]
Appends data provided as Array, String, or Buffer
[ "Appends", "data", "provided", "as", "Array", "String", "or", "Buffer" ]
c79490b0e624d35137539ceef759a053b80eae0e
https://github.com/jankolkmeier/xbee-api/blob/c79490b0e624d35137539ceef759a053b80eae0e/lib/frame-builder.js#L31-L39
25,841
tecfu/tty-table
adapters/terminal-adapter.js
function(header,body){ //footer = [], let Table = require('../src/factory.js'); options.terminalAdapter = true; let t1 = Table(header, body,options); //hide cursor console.log('\u001b[?25l'); //wipe existing if already rendered if(alreadyRendered){ //move cursor up number to the top of the previous print //before deleting console.log('\u001b['+(previousHeight+3)+'A'); //delete to end of terminal console.log('\u001b[0J'); } else{ alreadyRendered = true; } console.log(t1.render()); //reset the previous height to the height of this output //for when we next clear the print previousHeight = t1.height; }
javascript
function(header,body){ //footer = [], let Table = require('../src/factory.js'); options.terminalAdapter = true; let t1 = Table(header, body,options); //hide cursor console.log('\u001b[?25l'); //wipe existing if already rendered if(alreadyRendered){ //move cursor up number to the top of the previous print //before deleting console.log('\u001b['+(previousHeight+3)+'A'); //delete to end of terminal console.log('\u001b[0J'); } else{ alreadyRendered = true; } console.log(t1.render()); //reset the previous height to the height of this output //for when we next clear the print previousHeight = t1.height; }
[ "function", "(", "header", ",", "body", ")", "{", "//footer = [], ", "let", "Table", "=", "require", "(", "'../src/factory.js'", ")", ";", "options", ".", "terminalAdapter", "=", "true", ";", "let", "t1", "=", "Table", "(", "header", ",", "body", ",", "options", ")", ";", "//hide cursor", "console", ".", "log", "(", "'\\u001b[?25l'", ")", ";", "//wipe existing if already rendered", "if", "(", "alreadyRendered", ")", "{", "//move cursor up number to the top of the previous print", "//before deleting", "console", ".", "log", "(", "'\\u001b['", "+", "(", "previousHeight", "+", "3", ")", "+", "'A'", ")", ";", "//delete to end of terminal", "console", ".", "log", "(", "'\\u001b[0J'", ")", ";", "}", "else", "{", "alreadyRendered", "=", "true", ";", "}", "console", ".", "log", "(", "t1", ".", "render", "(", ")", ")", ";", "//reset the previous height to the height of this output", "//for when we next clear the print", "previousHeight", "=", "t1", ".", "height", ";", "}" ]
because different dataFormats
[ "because", "different", "dataFormats" ]
d77380de60e9b7a0023592bfc19c987a4d71cb28
https://github.com/tecfu/tty-table/blob/d77380de60e9b7a0023592bfc19c987a4d71cb28/adapters/terminal-adapter.js#L83-L113
25,842
BrowserSync/browser-sync-client
cbfile.js
function () { var chunks = []; return through2.obj(function (file, enc, cb) { chunks.push(file); var string = file._contents.toString(); var regex = /\/\*\*debug:start\*\*\/[\s\S]*\/\*\*debug:end\*\*\//g; var stripped = string.replace(regex, ""); file.contents = new Buffer(stripped); this.push(file); cb(); }); }
javascript
function () { var chunks = []; return through2.obj(function (file, enc, cb) { chunks.push(file); var string = file._contents.toString(); var regex = /\/\*\*debug:start\*\*\/[\s\S]*\/\*\*debug:end\*\*\//g; var stripped = string.replace(regex, ""); file.contents = new Buffer(stripped); this.push(file); cb(); }); }
[ "function", "(", ")", "{", "var", "chunks", "=", "[", "]", ";", "return", "through2", ".", "obj", "(", "function", "(", "file", ",", "enc", ",", "cb", ")", "{", "chunks", ".", "push", "(", "file", ")", ";", "var", "string", "=", "file", ".", "_contents", ".", "toString", "(", ")", ";", "var", "regex", "=", "/", "\\/\\*\\*debug:start\\*\\*\\/[\\s\\S]*\\/\\*\\*debug:end\\*\\*\\/", "/", "g", ";", "var", "stripped", "=", "string", ".", "replace", "(", "regex", ",", "\"\"", ")", ";", "file", ".", "contents", "=", "new", "Buffer", "(", "stripped", ")", ";", "this", ".", "push", "(", "file", ")", ";", "cb", "(", ")", ";", "}", ")", ";", "}" ]
Strip debug statements @returns {*}
[ "Strip", "debug", "statements" ]
8ea3496a7af2f4b4674a5a56b08e206134dd2179
https://github.com/BrowserSync/browser-sync-client/blob/8ea3496a7af2f4b4674a5a56b08e206134dd2179/cbfile.js#L35-L46
25,843
C2FO/comb
lib/collections/HashTable.js
function (key, value) { var hash = hashFunction(key); var bucket = null; if ((bucket = this.__map[hash]) == null) { bucket = (this.__map[hash] = new Bucket()); } bucket.pushValue(key, value); return value; }
javascript
function (key, value) { var hash = hashFunction(key); var bucket = null; if ((bucket = this.__map[hash]) == null) { bucket = (this.__map[hash] = new Bucket()); } bucket.pushValue(key, value); return value; }
[ "function", "(", "key", ",", "value", ")", "{", "var", "hash", "=", "hashFunction", "(", "key", ")", ";", "var", "bucket", "=", "null", ";", "if", "(", "(", "bucket", "=", "this", ".", "__map", "[", "hash", "]", ")", "==", "null", ")", "{", "bucket", "=", "(", "this", ".", "__map", "[", "hash", "]", "=", "new", "Bucket", "(", ")", ")", ";", "}", "bucket", ".", "pushValue", "(", "key", ",", "value", ")", ";", "return", "value", ";", "}" ]
Put a key, value pair into the table <b>NOTE :</b> the collection will not check if the key previously existed. @param {Anything} key the key to look up the object. @param {Anything} value the value that corresponds to the key. @returns the value
[ "Put", "a", "key", "value", "pair", "into", "the", "table" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/HashTable.js#L156-L164
25,844
C2FO/comb
lib/collections/HashTable.js
function (cb, scope) { var es = this.__entrySet(), ret = new this._static(); es = es.filter.apply(es, arguments); for (var i = es.length - 1; i >= 0; i--) { var e = es[i]; ret.put(e.key, e.value); } return ret; }
javascript
function (cb, scope) { var es = this.__entrySet(), ret = new this._static(); es = es.filter.apply(es, arguments); for (var i = es.length - 1; i >= 0; i--) { var e = es[i]; ret.put(e.key, e.value); } return ret; }
[ "function", "(", "cb", ",", "scope", ")", "{", "var", "es", "=", "this", ".", "__entrySet", "(", ")", ",", "ret", "=", "new", "this", ".", "_static", "(", ")", ";", "es", "=", "es", ".", "filter", ".", "apply", "(", "es", ",", "arguments", ")", ";", "for", "(", "var", "i", "=", "es", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "var", "e", "=", "es", "[", "i", "]", ";", "ret", ".", "put", "(", "e", ".", "key", ",", "e", ".", "value", ")", ";", "}", "return", "ret", ";", "}" ]
Creates a new HashTable containg values that passed the filtering function. @param {Function} cb Function to callback with each item, the first aruguments is an object containing a key and value field @param {Object} scope the scope to call the function. @returns {comb.collections.HashTable} the HashTable containing the values that passed the filter.
[ "Creates", "a", "new", "HashTable", "containg", "values", "that", "passed", "the", "filtering", "function", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/HashTable.js#L261-L269
25,845
C2FO/comb
lib/collections/HashTable.js
function (cb, scope) { var es = this.__entrySet(), l = es.length, f = cb.bind(scope || this); es.forEach.apply(es, arguments); }
javascript
function (cb, scope) { var es = this.__entrySet(), l = es.length, f = cb.bind(scope || this); es.forEach.apply(es, arguments); }
[ "function", "(", "cb", ",", "scope", ")", "{", "var", "es", "=", "this", ".", "__entrySet", "(", ")", ",", "l", "=", "es", ".", "length", ",", "f", "=", "cb", ".", "bind", "(", "scope", "||", "this", ")", ";", "es", ".", "forEach", ".", "apply", "(", "es", ",", "arguments", ")", ";", "}" ]
Loop through each value in the hashtable @param {Function} cb the function to call with an object containing a key and value field @param {Object} scope the scope to call the funciton in
[ "Loop", "through", "each", "value", "in", "the", "hashtable" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/HashTable.js#L277-L280
25,846
C2FO/comb
lib/promise.js
function (cb) { if (cb) { if (isPromise(cb)) { cb = cb.callback; } if (this.__fired && this.__results) { this.__callNextTick(cb, this.__results); } else { this.__cbs.push(cb); } } return this; }
javascript
function (cb) { if (cb) { if (isPromise(cb)) { cb = cb.callback; } if (this.__fired && this.__results) { this.__callNextTick(cb, this.__results); } else { this.__cbs.push(cb); } } return this; }
[ "function", "(", "cb", ")", "{", "if", "(", "cb", ")", "{", "if", "(", "isPromise", "(", "cb", ")", ")", "{", "cb", "=", "cb", ".", "callback", ";", "}", "if", "(", "this", ".", "__fired", "&&", "this", ".", "__results", ")", "{", "this", ".", "__callNextTick", "(", "cb", ",", "this", ".", "__results", ")", ";", "}", "else", "{", "this", ".", "__cbs", ".", "push", "(", "cb", ")", ";", "}", "}", "return", "this", ";", "}" ]
Add a callback to the callback chain of the promise @param {Function|comb.Promise} cb the function or promise to callback when the promise is resolved. @return {comb.Promise} this promise for chaining
[ "Add", "a", "callback", "to", "the", "callback", "chain", "of", "the", "promise" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L124-L136
25,847
C2FO/comb
lib/promise.js
function (cb) { if (cb) { if (isPromise(cb)) { cb = cb.errback; } if (this.__fired && this.__error) { this.__callNextTick(cb, this.__error); } else { this.__errorCbs.push(cb); } } return this; }
javascript
function (cb) { if (cb) { if (isPromise(cb)) { cb = cb.errback; } if (this.__fired && this.__error) { this.__callNextTick(cb, this.__error); } else { this.__errorCbs.push(cb); } } return this; }
[ "function", "(", "cb", ")", "{", "if", "(", "cb", ")", "{", "if", "(", "isPromise", "(", "cb", ")", ")", "{", "cb", "=", "cb", ".", "errback", ";", "}", "if", "(", "this", ".", "__fired", "&&", "this", ".", "__error", ")", "{", "this", ".", "__callNextTick", "(", "cb", ",", "this", ".", "__error", ")", ";", "}", "else", "{", "this", ".", "__errorCbs", ".", "push", "(", "cb", ")", ";", "}", "}", "return", "this", ";", "}" ]
Add a callback to the errback chain of the promise @param {Function|comb.Promise} cb the function or promise to callback when the promise errors @return {comb.Promise} this promise for chaining
[ "Add", "a", "callback", "to", "the", "errback", "chain", "of", "the", "promise" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L146-L158
25,848
C2FO/comb
lib/promise.js
function (args) { args = argsToArray(arguments); if (this.__fired) { throw new Error("Already fired!"); } this.__results = args; this.__resolve(); return this.promise(); }
javascript
function (args) { args = argsToArray(arguments); if (this.__fired) { throw new Error("Already fired!"); } this.__results = args; this.__resolve(); return this.promise(); }
[ "function", "(", "args", ")", "{", "args", "=", "argsToArray", "(", "arguments", ")", ";", "if", "(", "this", ".", "__fired", ")", "{", "throw", "new", "Error", "(", "\"Already fired!\"", ")", ";", "}", "this", ".", "__results", "=", "args", ";", "this", ".", "__resolve", "(", ")", ";", "return", "this", ".", "promise", "(", ")", ";", "}" ]
When called all functions registered as callbacks are called with the passed in results. @param {*} args variable number of results to pass back to listeners of the promise
[ "When", "called", "all", "functions", "registered", "as", "callbacks", "are", "called", "with", "the", "passed", "in", "results", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L185-L193
25,849
C2FO/comb
lib/promise.js
function (callback, errback) { if (isPromise(callback)) { errback = callback.errback; callback = callback.callback; } this.addCallback(callback); this.addErrback(errback); return this; }
javascript
function (callback, errback) { if (isPromise(callback)) { errback = callback.errback; callback = callback.callback; } this.addCallback(callback); this.addErrback(errback); return this; }
[ "function", "(", "callback", ",", "errback", ")", "{", "if", "(", "isPromise", "(", "callback", ")", ")", "{", "errback", "=", "callback", ".", "errback", ";", "callback", "=", "callback", ".", "callback", ";", "}", "this", ".", "addCallback", "(", "callback", ")", ";", "this", ".", "addErrback", "(", "errback", ")", ";", "return", "this", ";", "}" ]
Call to specify action to take after promise completes or errors @param {Function} [callback=null] function to call after the promise completes successfully @param {Function} [errback=null] function to call if the promise errors @return {comb.Promise} this promise for chaining
[ "Call", "to", "specify", "action", "to", "take", "after", "promise", "completes", "or", "errors" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L243-L252
25,850
C2FO/comb
lib/promise.js
function (callback, errback) { var promise = new Promise(), self = this; function _errback(e) { if (isFunction(errback)) { try { var res = spreadArgs(errback, [e]); isPromiseLike(res) ? res.then(promise.callback, promise.errback) : promise.callback(res); } catch (e) { promise.errback(e); } } else { promise.errback(e); } } function _callback() { try { var res = isFunction(callback) ? spreadArgs(callback, arguments) : callback; if (isPromiseLike(res)) { res.then(promise.callback, _errback); } else { promise.callback(res); promise = null; } callback = res = null; } catch (e) { _errback(e); } } self.addCallback(_callback); self.addErrback(_errback); return promise.promise(); }
javascript
function (callback, errback) { var promise = new Promise(), self = this; function _errback(e) { if (isFunction(errback)) { try { var res = spreadArgs(errback, [e]); isPromiseLike(res) ? res.then(promise.callback, promise.errback) : promise.callback(res); } catch (e) { promise.errback(e); } } else { promise.errback(e); } } function _callback() { try { var res = isFunction(callback) ? spreadArgs(callback, arguments) : callback; if (isPromiseLike(res)) { res.then(promise.callback, _errback); } else { promise.callback(res); promise = null; } callback = res = null; } catch (e) { _errback(e); } } self.addCallback(_callback); self.addErrback(_errback); return promise.promise(); }
[ "function", "(", "callback", ",", "errback", ")", "{", "var", "promise", "=", "new", "Promise", "(", ")", ",", "self", "=", "this", ";", "function", "_errback", "(", "e", ")", "{", "if", "(", "isFunction", "(", "errback", ")", ")", "{", "try", "{", "var", "res", "=", "spreadArgs", "(", "errback", ",", "[", "e", "]", ")", ";", "isPromiseLike", "(", "res", ")", "?", "res", ".", "then", "(", "promise", ".", "callback", ",", "promise", ".", "errback", ")", ":", "promise", ".", "callback", "(", "res", ")", ";", "}", "catch", "(", "e", ")", "{", "promise", ".", "errback", "(", "e", ")", ";", "}", "}", "else", "{", "promise", ".", "errback", "(", "e", ")", ";", "}", "}", "function", "_callback", "(", ")", "{", "try", "{", "var", "res", "=", "isFunction", "(", "callback", ")", "?", "spreadArgs", "(", "callback", ",", "arguments", ")", ":", "callback", ";", "if", "(", "isPromiseLike", "(", "res", ")", ")", "{", "res", ".", "then", "(", "promise", ".", "callback", ",", "_errback", ")", ";", "}", "else", "{", "promise", ".", "callback", "(", "res", ")", ";", "promise", "=", "null", ";", "}", "callback", "=", "res", "=", "null", ";", "}", "catch", "(", "e", ")", "{", "_errback", "(", "e", ")", ";", "}", "}", "self", ".", "addCallback", "(", "_callback", ")", ";", "self", ".", "addErrback", "(", "_errback", ")", ";", "return", "promise", ".", "promise", "(", ")", ";", "}" ]
Call to chaining of promises ``` new Promise() .callback("hello") .chain(function(previousPromiseResults){ return previousPromiseResults + " world"; }, errorHandler) .chain(function(previousPromiseResults){ return when(dbCall()); }).classic(function(err, results){ //all promises are done }); ``` You can also use static values ``` new Promise().callback() .chain("hello") .chain(function(prev){ return prev + " world!" }).then(function(str){ console.log(str); //"hello world!" }); ``` If you do not provide an `errback` for each chain then it will be propogated to the final promise ``` new Promise() .chain(function(){ return new comb.Promise().errback(new Error("error")); }) .chain(function(){ return prev + " world!" }) .classic(function(err, str){ console.log(err.message); //"error" }); ``` @param callback method to call this one completes. If you return a promise the execution will delay until the returned promise has resolved. @param [errback=null] method to call if this promise errors. If errback is not specified then the returned promises errback method will be used. @return {comb.Promise} A new that wraps the promise for chaining
[ "Call", "to", "chaining", "of", "promises" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L334-L369
25,851
C2FO/comb
lib/promise.js
function (callback) { var promise = new Promise(); this.addCallback(function () { try { when(isFunction(callback) ? callback.apply(this, arguments) : callback).then(promise); } catch (e) { promise.errback(e); } }); this.addErrback(function () { try { when(isFunction(callback) ? callback.apply(this, arguments) : callback).then(promise); } catch (e) { promise.errback(e); } }); return promise.promise(); }
javascript
function (callback) { var promise = new Promise(); this.addCallback(function () { try { when(isFunction(callback) ? callback.apply(this, arguments) : callback).then(promise); } catch (e) { promise.errback(e); } }); this.addErrback(function () { try { when(isFunction(callback) ? callback.apply(this, arguments) : callback).then(promise); } catch (e) { promise.errback(e); } }); return promise.promise(); }
[ "function", "(", "callback", ")", "{", "var", "promise", "=", "new", "Promise", "(", ")", ";", "this", ".", "addCallback", "(", "function", "(", ")", "{", "try", "{", "when", "(", "isFunction", "(", "callback", ")", "?", "callback", ".", "apply", "(", "this", ",", "arguments", ")", ":", "callback", ")", ".", "then", "(", "promise", ")", ";", "}", "catch", "(", "e", ")", "{", "promise", ".", "errback", "(", "e", ")", ";", "}", "}", ")", ";", "this", ".", "addErrback", "(", "function", "(", ")", "{", "try", "{", "when", "(", "isFunction", "(", "callback", ")", "?", "callback", ".", "apply", "(", "this", ",", "arguments", ")", ":", "callback", ")", ".", "then", "(", "promise", ")", ";", "}", "catch", "(", "e", ")", "{", "promise", ".", "errback", "(", "e", ")", ";", "}", "}", ")", ";", "return", "promise", ".", "promise", "(", ")", ";", "}" ]
Applies the same function that returns a promise to both the callback and errback. @param {Function} callback function to call. This function must return a Promise @return {comb.Promise} a promise to continue chaining or to resolve with.
[ "Applies", "the", "same", "function", "that", "returns", "a", "promise", "to", "both", "the", "callback", "and", "errback", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L379-L397
25,852
C2FO/comb
lib/promise.js
function () { var ret = { promise: function () { return ret; } }; var self = this; ret["chain"] = function () { return spreadArgs(self["chain"], arguments, self); }; ret["chainBoth"] = function () { return spreadArgs(self["chainBoth"], arguments, self); }; ret["addCallback"] = function () { spreadArgs(self["addCallback"], arguments, self); return ret; }; ret["addErrback"] = function () { spreadArgs(self["addErrback"], arguments, self); return ret; }; ret["then"] = function () { spreadArgs(self["then"], arguments, self); return ret; }; ret["both"] = function () { spreadArgs(self["both"], arguments, self); return ret; }; ret["classic"] = function () { spreadArgs(self["classic"], arguments, self); return ret; }; return ret; }
javascript
function () { var ret = { promise: function () { return ret; } }; var self = this; ret["chain"] = function () { return spreadArgs(self["chain"], arguments, self); }; ret["chainBoth"] = function () { return spreadArgs(self["chainBoth"], arguments, self); }; ret["addCallback"] = function () { spreadArgs(self["addCallback"], arguments, self); return ret; }; ret["addErrback"] = function () { spreadArgs(self["addErrback"], arguments, self); return ret; }; ret["then"] = function () { spreadArgs(self["then"], arguments, self); return ret; }; ret["both"] = function () { spreadArgs(self["both"], arguments, self); return ret; }; ret["classic"] = function () { spreadArgs(self["classic"], arguments, self); return ret; }; return ret; }
[ "function", "(", ")", "{", "var", "ret", "=", "{", "promise", ":", "function", "(", ")", "{", "return", "ret", ";", "}", "}", ";", "var", "self", "=", "this", ";", "ret", "[", "\"chain\"", "]", "=", "function", "(", ")", "{", "return", "spreadArgs", "(", "self", "[", "\"chain\"", "]", ",", "arguments", ",", "self", ")", ";", "}", ";", "ret", "[", "\"chainBoth\"", "]", "=", "function", "(", ")", "{", "return", "spreadArgs", "(", "self", "[", "\"chainBoth\"", "]", ",", "arguments", ",", "self", ")", ";", "}", ";", "ret", "[", "\"addCallback\"", "]", "=", "function", "(", ")", "{", "spreadArgs", "(", "self", "[", "\"addCallback\"", "]", ",", "arguments", ",", "self", ")", ";", "return", "ret", ";", "}", ";", "ret", "[", "\"addErrback\"", "]", "=", "function", "(", ")", "{", "spreadArgs", "(", "self", "[", "\"addErrback\"", "]", ",", "arguments", ",", "self", ")", ";", "return", "ret", ";", "}", ";", "ret", "[", "\"then\"", "]", "=", "function", "(", ")", "{", "spreadArgs", "(", "self", "[", "\"then\"", "]", ",", "arguments", ",", "self", ")", ";", "return", "ret", ";", "}", ";", "ret", "[", "\"both\"", "]", "=", "function", "(", ")", "{", "spreadArgs", "(", "self", "[", "\"both\"", "]", ",", "arguments", ",", "self", ")", ";", "return", "ret", ";", "}", ";", "ret", "[", "\"classic\"", "]", "=", "function", "(", ")", "{", "spreadArgs", "(", "self", "[", "\"classic\"", "]", ",", "arguments", ",", "self", ")", ";", "return", "ret", ";", "}", ";", "return", "ret", ";", "}" ]
Creates an object to that contains methods to listen to resolution but not the "callback" or "errback" methods. @example var asyncMethod = function(){ var ret = new comb.Promise(); process.nextTick(ret.callback.bind(ret, "hello")); return ret.promise(); } asyncMethod().callback() //throws error @return {Object} an object containing "chain", "chainBoth", "promise", "addCallback", "addErrback", "then", "both".
[ "Creates", "an", "object", "to", "that", "contains", "methods", "to", "listen", "to", "resolution", "but", "not", "the", "callback", "or", "errback", "methods", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L414-L448
25,853
C2FO/comb
lib/promise.js
function (defs, normalizeResults) { this.__errors = []; this.__results = []; this.normalizeResults = base.isBoolean(normalizeResults) ? normalizeResults : false; this._super(arguments); if (defs && defs.length) { this.__defLength = defs.length; forEach(defs, this.__addPromise, this); } else { this.__resolve(); } }
javascript
function (defs, normalizeResults) { this.__errors = []; this.__results = []; this.normalizeResults = base.isBoolean(normalizeResults) ? normalizeResults : false; this._super(arguments); if (defs && defs.length) { this.__defLength = defs.length; forEach(defs, this.__addPromise, this); } else { this.__resolve(); } }
[ "function", "(", "defs", ",", "normalizeResults", ")", "{", "this", ".", "__errors", "=", "[", "]", ";", "this", ".", "__results", "=", "[", "]", ";", "this", ".", "normalizeResults", "=", "base", ".", "isBoolean", "(", "normalizeResults", ")", "?", "normalizeResults", ":", "false", ";", "this", ".", "_super", "(", "arguments", ")", ";", "if", "(", "defs", "&&", "defs", ".", "length", ")", "{", "this", ".", "__defLength", "=", "defs", ".", "length", ";", "forEach", "(", "defs", ",", "this", ".", "__addPromise", ",", "this", ")", ";", "}", "else", "{", "this", ".", "__resolve", "(", ")", ";", "}", "}" ]
PromiseList object used for handling a list of Promises @example var myFunc = function(){ var promise = new Promise(); //callback the promise after 10 Secs setTimeout(hitch(promise, "callback"), 10000); return promise.promise(); } var myFunc2 = function(){ var promises =[]; for(var i = 0; i < 10; i++){ promises.push(myFunc); } //create a new promise list with all 10 promises return new PromiseList(promises).promise(); } myFunc.then(function(success){}, function(error){}) //chain promise operations myFunc.chain(myfunc).then(function(success){}, function(error){}) myFunc2.then(function(success){}, function(error){}) //chain promise operations myFunc2.chain(myfunc).then(function(success){}, function(error){}) @param {comb.Promise[]} [defs=[]] the list of promises @constructs @augments comb.Promise @memberOf comb
[ "PromiseList", "object", "used", "for", "handling", "a", "list", "of", "Promises" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L508-L519
25,854
C2FO/comb
lib/promise.js
function (promise, i) { var self = this; promise.then( function () { var args = argsToArray(arguments); args.unshift(i); spreadArgs(self.callback, args, self); promise = i = self = null; }, function () { var args = argsToArray(arguments); args.unshift(i); spreadArgs(self.errback, args, self); promise = i = self = null; }); }
javascript
function (promise, i) { var self = this; promise.then( function () { var args = argsToArray(arguments); args.unshift(i); spreadArgs(self.callback, args, self); promise = i = self = null; }, function () { var args = argsToArray(arguments); args.unshift(i); spreadArgs(self.errback, args, self); promise = i = self = null; }); }
[ "function", "(", "promise", ",", "i", ")", "{", "var", "self", "=", "this", ";", "promise", ".", "then", "(", "function", "(", ")", "{", "var", "args", "=", "argsToArray", "(", "arguments", ")", ";", "args", ".", "unshift", "(", "i", ")", ";", "spreadArgs", "(", "self", ".", "callback", ",", "args", ",", "self", ")", ";", "promise", "=", "i", "=", "self", "=", "null", ";", "}", ",", "function", "(", ")", "{", "var", "args", "=", "argsToArray", "(", "arguments", ")", ";", "args", ".", "unshift", "(", "i", ")", ";", "spreadArgs", "(", "self", ".", "errback", ",", "args", ",", "self", ")", ";", "promise", "=", "i", "=", "self", "=", "null", ";", "}", ")", ";", "}" ]
Add a promise to our chain @private @param promise the promise to add to our chain @param i the index of the promise in our chain
[ "Add", "a", "promise", "to", "our", "chain" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L527-L542
25,855
C2FO/comb
lib/promise.js
function () { if (!this.__fired) { this.__fired = true; var self = this; nextTick(function () { var cbs = self.__errors.length ? self.__errorCbs : self.__cbs, len = cbs.length, i, results = self.__errors.length ? self.__errors : self.__results; for (i = 0; i < len; i++) { spreadArgs(cbs[i], [results]); } }); } }
javascript
function () { if (!this.__fired) { this.__fired = true; var self = this; nextTick(function () { var cbs = self.__errors.length ? self.__errorCbs : self.__cbs, len = cbs.length, i, results = self.__errors.length ? self.__errors : self.__results; for (i = 0; i < len; i++) { spreadArgs(cbs[i], [results]); } }); } }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "__fired", ")", "{", "this", ".", "__fired", "=", "true", ";", "var", "self", "=", "this", ";", "nextTick", "(", "function", "(", ")", "{", "var", "cbs", "=", "self", ".", "__errors", ".", "length", "?", "self", ".", "__errorCbs", ":", "self", ".", "__cbs", ",", "len", "=", "cbs", ".", "length", ",", "i", ",", "results", "=", "self", ".", "__errors", ".", "length", "?", "self", ".", "__errors", ":", "self", ".", "__results", ";", "for", "(", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "spreadArgs", "(", "cbs", "[", "i", "]", ",", "[", "results", "]", ")", ";", "}", "}", ")", ";", "}", "}" ]
Resolves the promise @private
[ "Resolves", "the", "promise" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L548-L561
25,856
C2FO/comb
lib/promise.js
callNext
function callNext(list, results, propogate) { var ret = new Promise().callback(); forEach(list, function (listItem) { ret = ret.chain(propogate ? listItem : bindIgnore(null, listItem)); if (!propogate) { ret.addCallback(function (res) { results.push(res); res = null; }); } }); return propogate ? ret.promise() : ret.chain(results); }
javascript
function callNext(list, results, propogate) { var ret = new Promise().callback(); forEach(list, function (listItem) { ret = ret.chain(propogate ? listItem : bindIgnore(null, listItem)); if (!propogate) { ret.addCallback(function (res) { results.push(res); res = null; }); } }); return propogate ? ret.promise() : ret.chain(results); }
[ "function", "callNext", "(", "list", ",", "results", ",", "propogate", ")", "{", "var", "ret", "=", "new", "Promise", "(", ")", ".", "callback", "(", ")", ";", "forEach", "(", "list", ",", "function", "(", "listItem", ")", "{", "ret", "=", "ret", ".", "chain", "(", "propogate", "?", "listItem", ":", "bindIgnore", "(", "null", ",", "listItem", ")", ")", ";", "if", "(", "!", "propogate", ")", "{", "ret", ".", "addCallback", "(", "function", "(", "res", ")", "{", "results", ".", "push", "(", "res", ")", ";", "res", "=", "null", ";", "}", ")", ";", "}", "}", ")", ";", "return", "propogate", "?", "ret", ".", "promise", "(", ")", ":", "ret", ".", "chain", "(", "results", ")", ";", "}" ]
Creates the promise chain @ignore @private
[ "Creates", "the", "promise", "chain" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L643-L655
25,857
C2FO/comb
lib/promise.js
when
function when(args, cb, eb) { var p; args = argsToArray(arguments); eb = base.isFunction(args[args.length - 1]) ? args.pop() : null; cb = base.isFunction(args[args.length - 1]) ? args.pop() : null; if (eb && !cb) { cb = eb; eb = null; } if (!args.length) { p = new Promise().callback(args); } else if (args.length === 1) { args = args.pop(); if (isPromiseLike(args)) { p = args; } else if (isArray(args) && array.every(args, isPromiseLike)) { p = new PromiseList(args, true); } else { p = new Promise().callback(args); } } else { p = new PromiseList(args.map(function (a) { return isPromiseLike(a) ? a : new Promise().callback(a); }), true); } if (cb) { p.addCallback(cb); } if (eb) { p.addErrback(eb); } return p.promise(); }
javascript
function when(args, cb, eb) { var p; args = argsToArray(arguments); eb = base.isFunction(args[args.length - 1]) ? args.pop() : null; cb = base.isFunction(args[args.length - 1]) ? args.pop() : null; if (eb && !cb) { cb = eb; eb = null; } if (!args.length) { p = new Promise().callback(args); } else if (args.length === 1) { args = args.pop(); if (isPromiseLike(args)) { p = args; } else if (isArray(args) && array.every(args, isPromiseLike)) { p = new PromiseList(args, true); } else { p = new Promise().callback(args); } } else { p = new PromiseList(args.map(function (a) { return isPromiseLike(a) ? a : new Promise().callback(a); }), true); } if (cb) { p.addCallback(cb); } if (eb) { p.addErrback(eb); } return p.promise(); }
[ "function", "when", "(", "args", ",", "cb", ",", "eb", ")", "{", "var", "p", ";", "args", "=", "argsToArray", "(", "arguments", ")", ";", "eb", "=", "base", ".", "isFunction", "(", "args", "[", "args", ".", "length", "-", "1", "]", ")", "?", "args", ".", "pop", "(", ")", ":", "null", ";", "cb", "=", "base", ".", "isFunction", "(", "args", "[", "args", ".", "length", "-", "1", "]", ")", "?", "args", ".", "pop", "(", ")", ":", "null", ";", "if", "(", "eb", "&&", "!", "cb", ")", "{", "cb", "=", "eb", ";", "eb", "=", "null", ";", "}", "if", "(", "!", "args", ".", "length", ")", "{", "p", "=", "new", "Promise", "(", ")", ".", "callback", "(", "args", ")", ";", "}", "else", "if", "(", "args", ".", "length", "===", "1", ")", "{", "args", "=", "args", ".", "pop", "(", ")", ";", "if", "(", "isPromiseLike", "(", "args", ")", ")", "{", "p", "=", "args", ";", "}", "else", "if", "(", "isArray", "(", "args", ")", "&&", "array", ".", "every", "(", "args", ",", "isPromiseLike", ")", ")", "{", "p", "=", "new", "PromiseList", "(", "args", ",", "true", ")", ";", "}", "else", "{", "p", "=", "new", "Promise", "(", ")", ".", "callback", "(", "args", ")", ";", "}", "}", "else", "{", "p", "=", "new", "PromiseList", "(", "args", ".", "map", "(", "function", "(", "a", ")", "{", "return", "isPromiseLike", "(", "a", ")", "?", "a", ":", "new", "Promise", "(", ")", ".", "callback", "(", "a", ")", ";", "}", ")", ",", "true", ")", ";", "}", "if", "(", "cb", ")", "{", "p", ".", "addCallback", "(", "cb", ")", ";", "}", "if", "(", "eb", ")", "{", "p", ".", "addErrback", "(", "eb", ")", ";", "}", "return", "p", ".", "promise", "(", ")", ";", "}" ]
Waits for promise and non promise values to resolve and fires callback or errback appropriately. If you pass in an array of promises then it will wait for all promises in the list to resolve. @example var a = "hello"; var b = new comb.Promise().callback(world); comb.when(a, b) => called back with ["hello", "world"]; @param {Anything...} args variable number of arguments to wait for. @param {Function} cb the callback function @param {Function} eb the errback function @returns {comb.Promise} a promise that is fired when all values have resolved @static @memberOf comb
[ "Waits", "for", "promise", "and", "non", "promise", "values", "to", "resolve", "and", "fires", "callback", "or", "errback", "appropriately", ".", "If", "you", "pass", "in", "an", "array", "of", "promises", "then", "it", "will", "wait", "for", "all", "promises", "in", "the", "list", "to", "resolve", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L688-L721
25,858
C2FO/comb
lib/promise.js
serial
function serial(list, callback, errback) { if (base.isArray(list)) { return callNext(list, [], false); } else { throw new Error("When calling comb.serial the first argument must be an array"); } }
javascript
function serial(list, callback, errback) { if (base.isArray(list)) { return callNext(list, [], false); } else { throw new Error("When calling comb.serial the first argument must be an array"); } }
[ "function", "serial", "(", "list", ",", "callback", ",", "errback", ")", "{", "if", "(", "base", ".", "isArray", "(", "list", ")", ")", "{", "return", "callNext", "(", "list", ",", "[", "]", ",", "false", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"When calling comb.serial the first argument must be an array\"", ")", ";", "}", "}" ]
Executes a list of items in a serial manner. If the list contains promises then each promise will be executed in a serial manner, if the list contains non async items then the next item in the list is called. @example var asyncAction = function(item, timeout){ var ret = new comb.Promise(); setTimeout(comb.hitchIgnore(ret, "callback", item), timeout); return ret.promise(); }; comb.serial([ comb.partial(asyncAction, 1, 1000), comb.partial(asyncAction, 2, 900), comb.partial(asyncAction, 3, 800), comb.partial(asyncAction, 4, 700), comb.partial(asyncAction, 5, 600), comb.partial(asyncAction, 6, 500) ]).then(function(results){ console.log(results); // [1,2,3,4,5,6]; }); @param list @param callback @param errback @static @memberOf comb
[ "Executes", "a", "list", "of", "items", "in", "a", "serial", "manner", ".", "If", "the", "list", "contains", "promises", "then", "each", "promise", "will", "be", "executed", "in", "a", "serial", "manner", "if", "the", "list", "contains", "non", "async", "items", "then", "the", "next", "item", "in", "the", "list", "is", "called", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L788-L794
25,859
C2FO/comb
lib/promise.js
wait
function wait(args, fn) { var resolved = false; args = argsToArray(arguments); fn = args.pop(); var p = when(args); return function waiter() { if (!resolved) { var args = arguments; return p.chain(function () { resolved = true; p = null; return fn.apply(this, args); }.bind(this)); } else { return when(fn.apply(this, arguments)); } }; }
javascript
function wait(args, fn) { var resolved = false; args = argsToArray(arguments); fn = args.pop(); var p = when(args); return function waiter() { if (!resolved) { var args = arguments; return p.chain(function () { resolved = true; p = null; return fn.apply(this, args); }.bind(this)); } else { return when(fn.apply(this, arguments)); } }; }
[ "function", "wait", "(", "args", ",", "fn", ")", "{", "var", "resolved", "=", "false", ";", "args", "=", "argsToArray", "(", "arguments", ")", ";", "fn", "=", "args", ".", "pop", "(", ")", ";", "var", "p", "=", "when", "(", "args", ")", ";", "return", "function", "waiter", "(", ")", "{", "if", "(", "!", "resolved", ")", "{", "var", "args", "=", "arguments", ";", "return", "p", ".", "chain", "(", "function", "(", ")", "{", "resolved", "=", "true", ";", "p", "=", "null", ";", "return", "fn", ".", "apply", "(", "this", ",", "args", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}", "else", "{", "return", "when", "(", "fn", ".", "apply", "(", "this", ",", "arguments", ")", ")", ";", "}", "}", ";", "}" ]
Ensures that a promise is resolved before a the function can be run. For example suppose you have to ensure that you are connected to a database before you execute a function. ``` var findUser = comb.wait(connect(), function findUser(id){ //this wont execute until we are connected return User.findById(id); }); comb.when(findUser(1), findUser(2)).then(function(users){ var user1 = users[0], user2 = users[1]; }); ``` @param args variable number of arguments to wait on. See {@link comb.when}. @param {Function} fn function that will wait. @return {Function} a function that will wait on the args to resolve. @memberOf comb @static
[ "Ensures", "that", "a", "promise", "is", "resolved", "before", "a", "the", "function", "can", "be", "run", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L862-L879
25,860
C2FO/comb
lib/promise.js
promisfyStream
function promisfyStream(stream) { var ret = new Promise(), called; function errorHandler() { if (!called) { called = true; spreadArgs(ret.errback, arguments, ret); stream.removeListener("error", endHandler); stream.removeListener("end", endHandler); stream = ret = null; } } function endHandler() { if (!called) { called = true; spreadArgs(ret.callback, arguments, ret); stream.removeListener("error", endHandler); stream.removeListener("end", endHandler); stream = ret = null; } } stream.on("error", errorHandler).on("end", endHandler); return ret.promise(); }
javascript
function promisfyStream(stream) { var ret = new Promise(), called; function errorHandler() { if (!called) { called = true; spreadArgs(ret.errback, arguments, ret); stream.removeListener("error", endHandler); stream.removeListener("end", endHandler); stream = ret = null; } } function endHandler() { if (!called) { called = true; spreadArgs(ret.callback, arguments, ret); stream.removeListener("error", endHandler); stream.removeListener("end", endHandler); stream = ret = null; } } stream.on("error", errorHandler).on("end", endHandler); return ret.promise(); }
[ "function", "promisfyStream", "(", "stream", ")", "{", "var", "ret", "=", "new", "Promise", "(", ")", ",", "called", ";", "function", "errorHandler", "(", ")", "{", "if", "(", "!", "called", ")", "{", "called", "=", "true", ";", "spreadArgs", "(", "ret", ".", "errback", ",", "arguments", ",", "ret", ")", ";", "stream", ".", "removeListener", "(", "\"error\"", ",", "endHandler", ")", ";", "stream", ".", "removeListener", "(", "\"end\"", ",", "endHandler", ")", ";", "stream", "=", "ret", "=", "null", ";", "}", "}", "function", "endHandler", "(", ")", "{", "if", "(", "!", "called", ")", "{", "called", "=", "true", ";", "spreadArgs", "(", "ret", ".", "callback", ",", "arguments", ",", "ret", ")", ";", "stream", ".", "removeListener", "(", "\"error\"", ",", "endHandler", ")", ";", "stream", ".", "removeListener", "(", "\"end\"", ",", "endHandler", ")", ";", "stream", "=", "ret", "=", "null", ";", "}", "}", "stream", ".", "on", "(", "\"error\"", ",", "errorHandler", ")", ".", "on", "(", "\"end\"", ",", "endHandler", ")", ";", "return", "ret", ".", "promise", "(", ")", ";", "}" ]
Wraps a stream in a promise waiting for either the `"end"` or `"error"` event to be triggered. ``` comb.promisfyStream(fs.createdReadStream("my.file")).chain(function(){ console.log("done reading!"); }); ``` @param stream stream to wrap @return {comb.Promise} a Promise is resolved if `"end"` is triggered before `"error"` or rejected if `"error"` is triggered. @memberOf comb @static
[ "Wraps", "a", "stream", "in", "a", "promise", "waiting", "for", "either", "the", "end", "or", "error", "event", "to", "be", "triggered", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L897-L922
25,861
C2FO/comb
lib/base/array.js
difference
function difference(arr1, arr2) { var ret = arr1, args = flatten(argsToArray(arguments, 1)); if (isArray(arr1)) { ret = filter(arr1, function (a) { return indexOf(args, a) === -1; }); } return ret; }
javascript
function difference(arr1, arr2) { var ret = arr1, args = flatten(argsToArray(arguments, 1)); if (isArray(arr1)) { ret = filter(arr1, function (a) { return indexOf(args, a) === -1; }); } return ret; }
[ "function", "difference", "(", "arr1", ",", "arr2", ")", "{", "var", "ret", "=", "arr1", ",", "args", "=", "flatten", "(", "argsToArray", "(", "arguments", ",", "1", ")", ")", ";", "if", "(", "isArray", "(", "arr1", ")", ")", "{", "ret", "=", "filter", "(", "arr1", ",", "function", "(", "a", ")", "{", "return", "indexOf", "(", "args", ",", "a", ")", "===", "-", "1", ";", "}", ")", ";", "}", "return", "ret", ";", "}" ]
Finds the difference of the two arrays. @example comb.array.difference([1,2,3], [2,3]); //[1] comb.array.difference(["a","b",3], [3]); //["a","b"] @param {Array} arr1 the array we are subtracting from @param {Array} arr2 the array we are subtracting from arr1 @return {*} the difference of the arrays. @static @memberOf comb.array
[ "Finds", "the", "difference", "of", "the", "two", "arrays", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/array.js#L468-L476
25,862
C2FO/comb
lib/base/array.js
removeDuplicates
function removeDuplicates(arr) { if (isArray(arr)) { return reduce(arr, function (a, b) { if (indexOf(a, b) === -1) { return a.concat(b); } else { return a; } }, []); } }
javascript
function removeDuplicates(arr) { if (isArray(arr)) { return reduce(arr, function (a, b) { if (indexOf(a, b) === -1) { return a.concat(b); } else { return a; } }, []); } }
[ "function", "removeDuplicates", "(", "arr", ")", "{", "if", "(", "isArray", "(", "arr", ")", ")", "{", "return", "reduce", "(", "arr", ",", "function", "(", "a", ",", "b", ")", "{", "if", "(", "indexOf", "(", "a", ",", "b", ")", "===", "-", "1", ")", "{", "return", "a", ".", "concat", "(", "b", ")", ";", "}", "else", "{", "return", "a", ";", "}", "}", ",", "[", "]", ")", ";", "}", "}" ]
Removes duplicates from an array @example comb.array.removeDuplicates([1,1,1]) => [1] comb.array.removeDuplicates([1,2,3,2]) => [1,2,3] @param {Aray} array the array of elements to remove duplicates from @static @memberOf comb.array
[ "Removes", "duplicates", "from", "an", "array" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/array.js#L492-L502
25,863
C2FO/comb
lib/base/array.js
partition
function partition(array, partitionSize) { partitionSize = partitionSize || array.length; var ret = []; for (var i = 0, l = array.length; i < l; i += partitionSize) { ret.push(array.slice(i, i + partitionSize)); } return ret; }
javascript
function partition(array, partitionSize) { partitionSize = partitionSize || array.length; var ret = []; for (var i = 0, l = array.length; i < l; i += partitionSize) { ret.push(array.slice(i, i + partitionSize)); } return ret; }
[ "function", "partition", "(", "array", ",", "partitionSize", ")", "{", "partitionSize", "=", "partitionSize", "||", "array", ".", "length", ";", "var", "ret", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "array", ".", "length", ";", "i", "<", "l", ";", "i", "+=", "partitionSize", ")", "{", "ret", ".", "push", "(", "array", ".", "slice", "(", "i", ",", "i", "+", "partitionSize", ")", ")", ";", "}", "return", "ret", ";", "}" ]
Paritition an array. ``` var arr = [1,2,3,4,5]; comb.array.partition(arr, 1); //[[1], [2], [3], [4], [5]] comb.array.partition(arr, 2); //[[1,2], [3,4], [5]] comb.array.partition(arr, 3); //[[1,2,3], [4,5]] comb.array.partition(arr); //[[1, 2, 3, 4, 5]] comb.array.partition(arr, 0); //[[1, 2, 3, 4, 5]] ``` @param array @param partitionSize @returns {Array} @static @memberOf comb.array
[ "Paritition", "an", "array", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/array.js#L1051-L1058
25,864
C2FO/comb
lib/collections/Tree.js
function (node, order, callback) { if (node) { order = order || Tree.PRE_ORDER; if (order === Tree.PRE_ORDER) { callback(node.data); this.traverse(node.left, order, callback); this.traverse(node.right, order, callback); } else if (order === Tree.IN_ORDER) { this.traverse(node.left, order, callback); callback(node.data); this.traverse(node.right, order, callback); } else if (order === Tree.POST_ORDER) { this.traverse(node.left, order, callback); this.traverse(node.right, order, callback); callback(node.data); } else if (order === Tree.REVERSE_ORDER) { this.traverseWithCondition(node.right, order, callback); callback(node.data); this.traverseWithCondition(node.left, order, callback); } } }
javascript
function (node, order, callback) { if (node) { order = order || Tree.PRE_ORDER; if (order === Tree.PRE_ORDER) { callback(node.data); this.traverse(node.left, order, callback); this.traverse(node.right, order, callback); } else if (order === Tree.IN_ORDER) { this.traverse(node.left, order, callback); callback(node.data); this.traverse(node.right, order, callback); } else if (order === Tree.POST_ORDER) { this.traverse(node.left, order, callback); this.traverse(node.right, order, callback); callback(node.data); } else if (order === Tree.REVERSE_ORDER) { this.traverseWithCondition(node.right, order, callback); callback(node.data); this.traverseWithCondition(node.left, order, callback); } } }
[ "function", "(", "node", ",", "order", ",", "callback", ")", "{", "if", "(", "node", ")", "{", "order", "=", "order", "||", "Tree", ".", "PRE_ORDER", ";", "if", "(", "order", "===", "Tree", ".", "PRE_ORDER", ")", "{", "callback", "(", "node", ".", "data", ")", ";", "this", ".", "traverse", "(", "node", ".", "left", ",", "order", ",", "callback", ")", ";", "this", ".", "traverse", "(", "node", ".", "right", ",", "order", ",", "callback", ")", ";", "}", "else", "if", "(", "order", "===", "Tree", ".", "IN_ORDER", ")", "{", "this", ".", "traverse", "(", "node", ".", "left", ",", "order", ",", "callback", ")", ";", "callback", "(", "node", ".", "data", ")", ";", "this", ".", "traverse", "(", "node", ".", "right", ",", "order", ",", "callback", ")", ";", "}", "else", "if", "(", "order", "===", "Tree", ".", "POST_ORDER", ")", "{", "this", ".", "traverse", "(", "node", ".", "left", ",", "order", ",", "callback", ")", ";", "this", ".", "traverse", "(", "node", ".", "right", ",", "order", ",", "callback", ")", ";", "callback", "(", "node", ".", "data", ")", ";", "}", "else", "if", "(", "order", "===", "Tree", ".", "REVERSE_ORDER", ")", "{", "this", ".", "traverseWithCondition", "(", "node", ".", "right", ",", "order", ",", "callback", ")", ";", "callback", "(", "node", ".", "data", ")", ";", "this", ".", "traverseWithCondition", "(", "node", ".", "left", ",", "order", ",", "callback", ")", ";", "}", "}", "}" ]
Traverse a tree <p><b>Not typically used directly</b></p> @param {Object} node the node to start at @param {Tree.PRE_ORDER|Tree.POST_ORDER|Tree.IN_ORDER|Tree.REVERSE_ORDER} [order=Tree.IN_ORDER] the traversal scheme @param {Function} callback called for each item
[ "Traverse", "a", "tree" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/Tree.js#L155-L177
25,865
C2FO/comb
lib/logging/index.js
function (timerFormat) { timerFormat = timerFormat || " [Duration: %dms]"; function timerLog(level, start) { return function (message) { var args = argsToArray(arguments, 1); message += timerFormat; args.push(new Date() - start); self.log.apply(self, [level, message].concat(args)); return ret; }; } var start = new Date(), self = this, ret = { info: timerLog(Level.INFO, start), debug: timerLog(Level.DEBUG, start), error: timerLog(Level.ERROR, start), warn: timerLog(Level.WARN, start), trace: timerLog(Level.TRACE, start), fatal: timerLog(Level.FATAL, start), log: function (level) { return timerLog(level, start).apply(this, argsToArray(arguments, 1)); }, end: function () { start = self = null; } }; return ret; }
javascript
function (timerFormat) { timerFormat = timerFormat || " [Duration: %dms]"; function timerLog(level, start) { return function (message) { var args = argsToArray(arguments, 1); message += timerFormat; args.push(new Date() - start); self.log.apply(self, [level, message].concat(args)); return ret; }; } var start = new Date(), self = this, ret = { info: timerLog(Level.INFO, start), debug: timerLog(Level.DEBUG, start), error: timerLog(Level.ERROR, start), warn: timerLog(Level.WARN, start), trace: timerLog(Level.TRACE, start), fatal: timerLog(Level.FATAL, start), log: function (level) { return timerLog(level, start).apply(this, argsToArray(arguments, 1)); }, end: function () { start = self = null; } }; return ret; }
[ "function", "(", "timerFormat", ")", "{", "timerFormat", "=", "timerFormat", "||", "\" [Duration: %dms]\"", ";", "function", "timerLog", "(", "level", ",", "start", ")", "{", "return", "function", "(", "message", ")", "{", "var", "args", "=", "argsToArray", "(", "arguments", ",", "1", ")", ";", "message", "+=", "timerFormat", ";", "args", ".", "push", "(", "new", "Date", "(", ")", "-", "start", ")", ";", "self", ".", "log", ".", "apply", "(", "self", ",", "[", "level", ",", "message", "]", ".", "concat", "(", "args", ")", ")", ";", "return", "ret", ";", "}", ";", "}", "var", "start", "=", "new", "Date", "(", ")", ",", "self", "=", "this", ",", "ret", "=", "{", "info", ":", "timerLog", "(", "Level", ".", "INFO", ",", "start", ")", ",", "debug", ":", "timerLog", "(", "Level", ".", "DEBUG", ",", "start", ")", ",", "error", ":", "timerLog", "(", "Level", ".", "ERROR", ",", "start", ")", ",", "warn", ":", "timerLog", "(", "Level", ".", "WARN", ",", "start", ")", ",", "trace", ":", "timerLog", "(", "Level", ".", "TRACE", ",", "start", ")", ",", "fatal", ":", "timerLog", "(", "Level", ".", "FATAL", ",", "start", ")", ",", "log", ":", "function", "(", "level", ")", "{", "return", "timerLog", "(", "level", ",", "start", ")", ".", "apply", "(", "this", ",", "argsToArray", "(", "arguments", ",", "1", ")", ")", ";", "}", ",", "end", ":", "function", "(", ")", "{", "start", "=", "self", "=", "null", ";", "}", "}", ";", "return", "ret", ";", "}" ]
Create a timer that can be used to log statements with a duration at the send. ``` var timer = LOGGER.timer(); setTimeout(function(){ timer.info("HELLO TIMERS!!!"); //HELLO TIMERS!!! [Duration: 5000ms] }, 5000); ``` @param timerFormat @returns {{info: Function, debug: Function, error: Function, warn: Function, trace: Function, fatal: Function, end: Function}}
[ "Create", "a", "timer", "that", "can", "be", "used", "to", "log", "statements", "with", "a", "duration", "at", "the", "send", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/logging/index.js#L335-L364
25,866
C2FO/comb
lib/logging/index.js
getLogEvent
function getLogEvent(level, message, rawMessage) { return { hostname: os.hostname(), pid: process.pid, gid: hasGetGid ? process.getgid() : null, processTitle: process.title, level: level, levelName: level.name, message: message, timeStamp: new Date(), name: this.fullName, rawMessage: rawMessage }; }
javascript
function getLogEvent(level, message, rawMessage) { return { hostname: os.hostname(), pid: process.pid, gid: hasGetGid ? process.getgid() : null, processTitle: process.title, level: level, levelName: level.name, message: message, timeStamp: new Date(), name: this.fullName, rawMessage: rawMessage }; }
[ "function", "getLogEvent", "(", "level", ",", "message", ",", "rawMessage", ")", "{", "return", "{", "hostname", ":", "os", ".", "hostname", "(", ")", ",", "pid", ":", "process", ".", "pid", ",", "gid", ":", "hasGetGid", "?", "process", ".", "getgid", "(", ")", ":", "null", ",", "processTitle", ":", "process", ".", "title", ",", "level", ":", "level", ",", "levelName", ":", "level", ".", "name", ",", "message", ":", "message", ",", "timeStamp", ":", "new", "Date", "(", ")", ",", "name", ":", "this", ".", "fullName", ",", "rawMessage", ":", "rawMessage", "}", ";", "}" ]
Creates a log event to be passed to appenders @param {comb.logging.Level} level the level of the logging event @param {String} message the message to be logged @return {Object} the logging event
[ "Creates", "a", "log", "event", "to", "be", "passed", "to", "appenders" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/logging/index.js#L373-L386
25,867
C2FO/comb
lib/logging/index.js
log
function log(level, message) { var rawMessage = message; level = Level.toLevel(level); if (this.hasLevelGt(level)) { var args = argsToArray(arguments, 1); if (args.length > 1) { message = format.apply(null, args); } if (Level.TRACE.equals(level)) { var err = new Error; err.name = "Trace"; err.message = message || ''; Error.captureStackTrace(err, log); message = err.stack; } else if (Level.ERROR.equals(level) && isInstanceOf(message, Error)) { message = message.stack; } var type = level.name.toLowerCase(), appenders = this.__appenders; var event = this.getLogEvent(level, message, rawMessage); Object.keys(appenders).forEach(function (i) { appenders[i].append(event); }); } return this; }
javascript
function log(level, message) { var rawMessage = message; level = Level.toLevel(level); if (this.hasLevelGt(level)) { var args = argsToArray(arguments, 1); if (args.length > 1) { message = format.apply(null, args); } if (Level.TRACE.equals(level)) { var err = new Error; err.name = "Trace"; err.message = message || ''; Error.captureStackTrace(err, log); message = err.stack; } else if (Level.ERROR.equals(level) && isInstanceOf(message, Error)) { message = message.stack; } var type = level.name.toLowerCase(), appenders = this.__appenders; var event = this.getLogEvent(level, message, rawMessage); Object.keys(appenders).forEach(function (i) { appenders[i].append(event); }); } return this; }
[ "function", "log", "(", "level", ",", "message", ")", "{", "var", "rawMessage", "=", "message", ";", "level", "=", "Level", ".", "toLevel", "(", "level", ")", ";", "if", "(", "this", ".", "hasLevelGt", "(", "level", ")", ")", "{", "var", "args", "=", "argsToArray", "(", "arguments", ",", "1", ")", ";", "if", "(", "args", ".", "length", ">", "1", ")", "{", "message", "=", "format", ".", "apply", "(", "null", ",", "args", ")", ";", "}", "if", "(", "Level", ".", "TRACE", ".", "equals", "(", "level", ")", ")", "{", "var", "err", "=", "new", "Error", ";", "err", ".", "name", "=", "\"Trace\"", ";", "err", ".", "message", "=", "message", "||", "''", ";", "Error", ".", "captureStackTrace", "(", "err", ",", "log", ")", ";", "message", "=", "err", ".", "stack", ";", "}", "else", "if", "(", "Level", ".", "ERROR", ".", "equals", "(", "level", ")", "&&", "isInstanceOf", "(", "message", ",", "Error", ")", ")", "{", "message", "=", "message", ".", "stack", ";", "}", "var", "type", "=", "level", ".", "name", ".", "toLowerCase", "(", ")", ",", "appenders", "=", "this", ".", "__appenders", ";", "var", "event", "=", "this", ".", "getLogEvent", "(", "level", ",", "message", ",", "rawMessage", ")", ";", "Object", ".", "keys", "(", "appenders", ")", ".", "forEach", "(", "function", "(", "i", ")", "{", "appenders", "[", "i", "]", ".", "append", "(", "event", ")", ";", "}", ")", ";", "}", "return", "this", ";", "}" ]
Log a message @param {comb.logging.Level} level the level the message is @param {String} message the message to log. @return {comb.logging.Logger} for chaining.
[ "Log", "a", "message" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/logging/index.js#L396-L421
25,868
C2FO/comb
lib/logging/index.js
function (appender, opts) { var args = argsToArray(arguments); if (isString(appender)) { this.addAppender(Appender.createAppender(appender, opts)); } else { if (!isUndefinedOrNull(appender)) { var name = appender.name; if (!(name in this.__appenders)) { this.__appenders[name] = appender; if (!appender.level) { appender.level = this.level; } this._tree.addAppender(appender); } } } return this; }
javascript
function (appender, opts) { var args = argsToArray(arguments); if (isString(appender)) { this.addAppender(Appender.createAppender(appender, opts)); } else { if (!isUndefinedOrNull(appender)) { var name = appender.name; if (!(name in this.__appenders)) { this.__appenders[name] = appender; if (!appender.level) { appender.level = this.level; } this._tree.addAppender(appender); } } } return this; }
[ "function", "(", "appender", ",", "opts", ")", "{", "var", "args", "=", "argsToArray", "(", "arguments", ")", ";", "if", "(", "isString", "(", "appender", ")", ")", "{", "this", ".", "addAppender", "(", "Appender", ".", "createAppender", "(", "appender", ",", "opts", ")", ")", ";", "}", "else", "{", "if", "(", "!", "isUndefinedOrNull", "(", "appender", ")", ")", "{", "var", "name", "=", "appender", ".", "name", ";", "if", "(", "!", "(", "name", "in", "this", ".", "__appenders", ")", ")", "{", "this", ".", "__appenders", "[", "name", "]", "=", "appender", ";", "if", "(", "!", "appender", ".", "level", ")", "{", "appender", ".", "level", "=", "this", ".", "level", ";", "}", "this", ".", "_tree", ".", "addAppender", "(", "appender", ")", ";", "}", "}", "}", "return", "this", ";", "}" ]
Add an appender to this logger. If this is additive then the appender is added to all subloggers. @example comb.logger("my.logger") .addAppender("ConsoleAppender") .addAppender("FileAppender", {file:'/var/log/my.log'}) .addAppender("RollingFileAppender", {file:'/var/log/myRolling.log'}) .addAppender("JSONAppender", {file:'/var/log/myJson.log'}); @param {comb.logging.Appender|String} If the appender is an {@link comb.logging.appenders.Appender} then it is added. If the appender is a string then {@link comb.logging.appenders.Appender.createAppender} will be called to create it. @param {Object} [opts = null] If the first argument is a string then the opts will be used as constructor arguments for creating the appender. @return {comb.logging.Logger} for chaining.
[ "Add", "an", "appender", "to", "this", "logger", ".", "If", "this", "is", "additive", "then", "the", "appender", "is", "added", "to", "all", "subloggers", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/logging/index.js#L441-L459
25,869
C2FO/comb
lib/collections/Heap.js
function (key, value) { if (!base.isString(key)) { var l = this.__heap.push(this.__makeNode(key, value)); this.__upHeap(l - 1); } else { throw new TypeError("Invalid key"); } }
javascript
function (key, value) { if (!base.isString(key)) { var l = this.__heap.push(this.__makeNode(key, value)); this.__upHeap(l - 1); } else { throw new TypeError("Invalid key"); } }
[ "function", "(", "key", ",", "value", ")", "{", "if", "(", "!", "base", ".", "isString", "(", "key", ")", ")", "{", "var", "l", "=", "this", ".", "__heap", ".", "push", "(", "this", ".", "__makeNode", "(", "key", ",", "value", ")", ")", ";", "this", ".", "__upHeap", "(", "l", "-", "1", ")", ";", "}", "else", "{", "throw", "new", "TypeError", "(", "\"Invalid key\"", ")", ";", "}", "}" ]
Insert a key value into the key @param key @param value
[ "Insert", "a", "key", "value", "into", "the", "key" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/Heap.js#L56-L63
25,870
C2FO/comb
lib/collections/Heap.js
function () { var heap = this.__heap, l = heap.length, ret; if (l) { ret = heap[0]; if (l === 1) { heap.length = 0; } else { heap[0] = heap.pop(); this.__downHeap(0); } } return ret ? ret.value : ret; }
javascript
function () { var heap = this.__heap, l = heap.length, ret; if (l) { ret = heap[0]; if (l === 1) { heap.length = 0; } else { heap[0] = heap.pop(); this.__downHeap(0); } } return ret ? ret.value : ret; }
[ "function", "(", ")", "{", "var", "heap", "=", "this", ".", "__heap", ",", "l", "=", "heap", ".", "length", ",", "ret", ";", "if", "(", "l", ")", "{", "ret", "=", "heap", "[", "0", "]", ";", "if", "(", "l", "===", "1", ")", "{", "heap", ".", "length", "=", "0", ";", "}", "else", "{", "heap", "[", "0", "]", "=", "heap", ".", "pop", "(", ")", ";", "this", ".", "__downHeap", "(", "0", ")", ";", "}", "}", "return", "ret", "?", "ret", ".", "value", ":", "ret", ";", "}" ]
Removes the root from the heap @returns the value of the root
[ "Removes", "the", "root", "from", "the", "heap" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/Heap.js#L70-L84
25,871
C2FO/comb
lib/collections/Heap.js
function () { var heap = this.__heap, l = heap.length, ret; if (l) { ret = heap[0]; } return ret ? ret.value : ret; }
javascript
function () { var heap = this.__heap, l = heap.length, ret; if (l) { ret = heap[0]; } return ret ? ret.value : ret; }
[ "function", "(", ")", "{", "var", "heap", "=", "this", ".", "__heap", ",", "l", "=", "heap", ".", "length", ",", "ret", ";", "if", "(", "l", ")", "{", "ret", "=", "heap", "[", "0", "]", ";", "}", "return", "ret", "?", "ret", ".", "value", ":", "ret", ";", "}" ]
Gets he value of the root node with out removing it. @returns the value of the root
[ "Gets", "he", "value", "of", "the", "root", "node", "with", "out", "removing", "it", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/Heap.js#L91-L99
25,872
C2FO/comb
lib/collections/Heap.js
function () { var heap = this.__heap, l = heap.length, ret; if (l) { ret = heap[0]; } return ret ? ret.key : ret; }
javascript
function () { var heap = this.__heap, l = heap.length, ret; if (l) { ret = heap[0]; } return ret ? ret.key : ret; }
[ "function", "(", ")", "{", "var", "heap", "=", "this", ".", "__heap", ",", "l", "=", "heap", ".", "length", ",", "ret", ";", "if", "(", "l", ")", "{", "ret", "=", "heap", "[", "0", "]", ";", "}", "return", "ret", "?", "ret", ".", "key", ":", "ret", ";", "}" ]
Gets the key of the root node without removing it. @returns the key of the root
[ "Gets", "the", "key", "of", "the", "root", "node", "without", "removing", "it", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/Heap.js#L106-L114
25,873
C2FO/comb
lib/base/number.js
roundCeil
function roundCeil(num, precision){ return Math.ceil(num * Math.pow(10, precision))/Math.pow(10, precision); }
javascript
function roundCeil(num, precision){ return Math.ceil(num * Math.pow(10, precision))/Math.pow(10, precision); }
[ "function", "roundCeil", "(", "num", ",", "precision", ")", "{", "return", "Math", ".", "ceil", "(", "num", "*", "Math", ".", "pow", "(", "10", ",", "precision", ")", ")", "/", "Math", ".", "pow", "(", "10", ",", "precision", ")", ";", "}" ]
Rounds a number to the specified places, rounding up. @example comb.number.roundCeil(10.000001, 2); //10.01 comb.number.roundCeil(10.000002, 5); //10.00001 comb.number.roundCeil(10.0003, 3); //10.001 comb.number.roundCeil(10.0004, 2); //10.01 comb.number.roundCeil(10.0005, 3); //10.001 comb.number.roundCeil(10.0002, 2); //10.01 @param {Number} num the number to round. @param {Number} precision the number of places to round to. @static @memberOf comb.number
[ "Rounds", "a", "number", "to", "the", "specified", "places", "rounding", "up", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/number.js#L38-L40
25,874
C2FO/comb
lib/base/broadcast.js
function (obj, method, cb, scope) { var index, listeners; if (typeof method !== "string") { throw new Error("When calling connect the method must be string"); } if (!func.isFunction(cb)) { throw new Error("When calling connect callback must be a string"); } scope = obj || global; if (typeof scope[method] === "function") { listeners = scope[method].__listeners; if (!listeners) { var newMethod = wrapper(); newMethod.func = obj[method]; listeners = (newMethod.__listeners = []); scope[method] = newMethod; } index = listeners.push(cb); } else { throw new Error("unknow method " + method + " in object " + obj); } return [obj, method, index]; }
javascript
function (obj, method, cb, scope) { var index, listeners; if (typeof method !== "string") { throw new Error("When calling connect the method must be string"); } if (!func.isFunction(cb)) { throw new Error("When calling connect callback must be a string"); } scope = obj || global; if (typeof scope[method] === "function") { listeners = scope[method].__listeners; if (!listeners) { var newMethod = wrapper(); newMethod.func = obj[method]; listeners = (newMethod.__listeners = []); scope[method] = newMethod; } index = listeners.push(cb); } else { throw new Error("unknow method " + method + " in object " + obj); } return [obj, method, index]; }
[ "function", "(", "obj", ",", "method", ",", "cb", ",", "scope", ")", "{", "var", "index", ",", "listeners", ";", "if", "(", "typeof", "method", "!==", "\"string\"", ")", "{", "throw", "new", "Error", "(", "\"When calling connect the method must be string\"", ")", ";", "}", "if", "(", "!", "func", ".", "isFunction", "(", "cb", ")", ")", "{", "throw", "new", "Error", "(", "\"When calling connect callback must be a string\"", ")", ";", "}", "scope", "=", "obj", "||", "global", ";", "if", "(", "typeof", "scope", "[", "method", "]", "===", "\"function\"", ")", "{", "listeners", "=", "scope", "[", "method", "]", ".", "__listeners", ";", "if", "(", "!", "listeners", ")", "{", "var", "newMethod", "=", "wrapper", "(", ")", ";", "newMethod", ".", "func", "=", "obj", "[", "method", "]", ";", "listeners", "=", "(", "newMethod", ".", "__listeners", "=", "[", "]", ")", ";", "scope", "[", "method", "]", "=", "newMethod", ";", "}", "index", "=", "listeners", ".", "push", "(", "cb", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"unknow method \"", "+", "method", "+", "\" in object \"", "+", "obj", ")", ";", "}", "return", "[", "obj", ",", "method", ",", "index", "]", ";", "}" ]
Function to listen when other functions are called @example comb.connect(obj, "event", myfunc); comb.connect(obj, "event", "log", console); @param {Object} obj the object in which the method you are connecting to resides @param {String} method the name of the method to connect to @param {Function} cb the function to callback @param {Object} [scope] the scope to call the specified cb in @returns {Array} handle to pass to {@link comb.disconnect}
[ "Function", "to", "listen", "when", "other", "functions", "are", "called" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/broadcast.js#L68-L91
25,875
C2FO/comb
lib/base/broadcast.js
function (topic, callback) { if (!func.isFunction(callback)) { throw new Error("callback must be a function"); } var handle = { topic: topic, cb: callback, pos: null }; var list = listeners[topic]; if (!list) { list = (listeners[topic] = []); } list.push(handle); handle.pos = list.length - 1; return handle; }
javascript
function (topic, callback) { if (!func.isFunction(callback)) { throw new Error("callback must be a function"); } var handle = { topic: topic, cb: callback, pos: null }; var list = listeners[topic]; if (!list) { list = (listeners[topic] = []); } list.push(handle); handle.pos = list.length - 1; return handle; }
[ "function", "(", "topic", ",", "callback", ")", "{", "if", "(", "!", "func", ".", "isFunction", "(", "callback", ")", ")", "{", "throw", "new", "Error", "(", "\"callback must be a function\"", ")", ";", "}", "var", "handle", "=", "{", "topic", ":", "topic", ",", "cb", ":", "callback", ",", "pos", ":", "null", "}", ";", "var", "list", "=", "listeners", "[", "topic", "]", ";", "if", "(", "!", "list", ")", "{", "list", "=", "(", "listeners", "[", "topic", "]", "=", "[", "]", ")", ";", "}", "list", ".", "push", "(", "handle", ")", ";", "handle", ".", "pos", "=", "list", ".", "length", "-", "1", ";", "return", "handle", ";", "}" ]
Listen for the broadcast of certain events @example comb.listen("hello", function(arg1, arg2){ console.log(arg1); console.log(arg2); }); @param {String} topic the topic to listen for @param {Function} callback the funciton to call when the topic is published @returns a handle to pass to {@link comb.unListen}
[ "Listen", "for", "the", "broadcast", "of", "certain", "events" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/broadcast.js#L140-L156
25,876
C2FO/comb
lib/base/broadcast.js
function (handle) { if (handle) { var topic = handle.topic, list = listeners[topic]; if (list) { for (var i = list.length - 1; i >= 0; i--) { if (list[i] === handle) { list.splice(i, 1); } } if (!list.length) { delete listeners[topic]; } } } }
javascript
function (handle) { if (handle) { var topic = handle.topic, list = listeners[topic]; if (list) { for (var i = list.length - 1; i >= 0; i--) { if (list[i] === handle) { list.splice(i, 1); } } if (!list.length) { delete listeners[topic]; } } } }
[ "function", "(", "handle", ")", "{", "if", "(", "handle", ")", "{", "var", "topic", "=", "handle", ".", "topic", ",", "list", "=", "listeners", "[", "topic", "]", ";", "if", "(", "list", ")", "{", "for", "(", "var", "i", "=", "list", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "list", "[", "i", "]", "===", "handle", ")", "{", "list", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "}", "if", "(", "!", "list", ".", "length", ")", "{", "delete", "listeners", "[", "topic", "]", ";", "}", "}", "}", "}" ]
Disconnects a listener @param handle a handle returned from {@link comb.listen}
[ "Disconnects", "a", "listener" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/broadcast.js#L163-L177
25,877
julesfern/spahql
doc-html/src/javascripts/pdoc/application.js
function() { var state = $H({ activeTab: PDoc.Sidebar.getActiveTab(), menuScrollOffset: $('menu_pane').scrollTop, searchScrollOffset: $('search_results').scrollTop, searchValue: $('search').getValue() }); return escape(state.toJSON()); }
javascript
function() { var state = $H({ activeTab: PDoc.Sidebar.getActiveTab(), menuScrollOffset: $('menu_pane').scrollTop, searchScrollOffset: $('search_results').scrollTop, searchValue: $('search').getValue() }); return escape(state.toJSON()); }
[ "function", "(", ")", "{", "var", "state", "=", "$H", "(", "{", "activeTab", ":", "PDoc", ".", "Sidebar", ".", "getActiveTab", "(", ")", ",", "menuScrollOffset", ":", "$", "(", "'menu_pane'", ")", ".", "scrollTop", ",", "searchScrollOffset", ":", "$", "(", "'search_results'", ")", ".", "scrollTop", ",", "searchValue", ":", "$", "(", "'search'", ")", ".", "getValue", "(", ")", "}", ")", ";", "return", "escape", "(", "state", ".", "toJSON", "(", ")", ")", ";", "}" ]
Remember the state of the sidebar so it can be restored on the next page.
[ "Remember", "the", "state", "of", "the", "sidebar", "so", "it", "can", "be", "restored", "on", "the", "next", "page", "." ]
f2eff34e59f5af2e6a48f11f59f99c223b4a2be8
https://github.com/julesfern/spahql/blob/f2eff34e59f5af2e6a48f11f59f99c223b4a2be8/doc-html/src/javascripts/pdoc/application.js#L137-L146
25,878
julesfern/spahql
doc-html/src/javascripts/pdoc/application.js
function(state) { try { state = unescape(state).evalJSON(); var filterer = $('search').retrieve('filterer'); filterer.setSearchValue(state.searchValue); (function() { $('menu_pane').scrollTop = state.menuScrollOffset; $('search_results').scrollTop = state.searchScrollOffset; }).defer(); } catch(error) { console.log(error); if (!(error instanceof SyntaxError)) throw error; } }
javascript
function(state) { try { state = unescape(state).evalJSON(); var filterer = $('search').retrieve('filterer'); filterer.setSearchValue(state.searchValue); (function() { $('menu_pane').scrollTop = state.menuScrollOffset; $('search_results').scrollTop = state.searchScrollOffset; }).defer(); } catch(error) { console.log(error); if (!(error instanceof SyntaxError)) throw error; } }
[ "function", "(", "state", ")", "{", "try", "{", "state", "=", "unescape", "(", "state", ")", ".", "evalJSON", "(", ")", ";", "var", "filterer", "=", "$", "(", "'search'", ")", ".", "retrieve", "(", "'filterer'", ")", ";", "filterer", ".", "setSearchValue", "(", "state", ".", "searchValue", ")", ";", "(", "function", "(", ")", "{", "$", "(", "'menu_pane'", ")", ".", "scrollTop", "=", "state", ".", "menuScrollOffset", ";", "$", "(", "'search_results'", ")", ".", "scrollTop", "=", "state", ".", "searchScrollOffset", ";", "}", ")", ".", "defer", "(", ")", ";", "}", "catch", "(", "error", ")", "{", "console", ".", "log", "(", "error", ")", ";", "if", "(", "!", "(", "error", "instanceof", "SyntaxError", ")", ")", "throw", "error", ";", "}", "}" ]
Restore the tree to a certain point based on a cookie.
[ "Restore", "the", "tree", "to", "a", "certain", "point", "based", "on", "a", "cookie", "." ]
f2eff34e59f5af2e6a48f11f59f99c223b4a2be8
https://github.com/julesfern/spahql/blob/f2eff34e59f5af2e6a48f11f59f99c223b4a2be8/doc-html/src/javascripts/pdoc/application.js#L149-L163
25,879
julesfern/spahql
doc-html/src/javascripts/pdoc/application.js
function(event) { // Clear the text box on ESC. if (event.keyCode && event.keyCode === Event.KEY_ESC) { this.element.setValue(''); } if (PDoc.Sidebar.Filterer.INTERCEPT_KEYS.include(event.keyCode)) return; // If there's nothing in the text box, clear the results list. var value = $F(this.element).strip().toLowerCase(); if (value === '') { this.emptyResults(); this.hideResults(); return; } var urls = this.findURLs(value); this.buildResults(urls); }
javascript
function(event) { // Clear the text box on ESC. if (event.keyCode && event.keyCode === Event.KEY_ESC) { this.element.setValue(''); } if (PDoc.Sidebar.Filterer.INTERCEPT_KEYS.include(event.keyCode)) return; // If there's nothing in the text box, clear the results list. var value = $F(this.element).strip().toLowerCase(); if (value === '') { this.emptyResults(); this.hideResults(); return; } var urls = this.findURLs(value); this.buildResults(urls); }
[ "function", "(", "event", ")", "{", "// Clear the text box on ESC.", "if", "(", "event", ".", "keyCode", "&&", "event", ".", "keyCode", "===", "Event", ".", "KEY_ESC", ")", "{", "this", ".", "element", ".", "setValue", "(", "''", ")", ";", "}", "if", "(", "PDoc", ".", "Sidebar", ".", "Filterer", ".", "INTERCEPT_KEYS", ".", "include", "(", "event", ".", "keyCode", ")", ")", "return", ";", "// If there's nothing in the text box, clear the results list.", "var", "value", "=", "$F", "(", "this", ".", "element", ")", ".", "strip", "(", ")", ".", "toLowerCase", "(", ")", ";", "if", "(", "value", "===", "''", ")", "{", "this", ".", "emptyResults", "(", ")", ";", "this", ".", "hideResults", "(", ")", ";", "return", ";", "}", "var", "urls", "=", "this", ".", "findURLs", "(", "value", ")", ";", "this", ".", "buildResults", "(", "urls", ")", ";", "}" ]
Called whenever the list of results needs to update as a result of a changed search key.
[ "Called", "whenever", "the", "list", "of", "results", "needs", "to", "update", "as", "a", "result", "of", "a", "changed", "search", "key", "." ]
f2eff34e59f5af2e6a48f11f59f99c223b4a2be8
https://github.com/julesfern/spahql/blob/f2eff34e59f5af2e6a48f11f59f99c223b4a2be8/doc-html/src/javascripts/pdoc/application.js#L205-L224
25,880
julesfern/spahql
doc-html/src/javascripts/pdoc/application.js
function(str) { var results = []; for (var name in PDoc.elements) { if (name.toLowerCase().include(str.toLowerCase())) results.push(PDoc.elements[name]); } return results; }
javascript
function(str) { var results = []; for (var name in PDoc.elements) { if (name.toLowerCase().include(str.toLowerCase())) results.push(PDoc.elements[name]); } return results; }
[ "function", "(", "str", ")", "{", "var", "results", "=", "[", "]", ";", "for", "(", "var", "name", "in", "PDoc", ".", "elements", ")", "{", "if", "(", "name", ".", "toLowerCase", "(", ")", ".", "include", "(", "str", ".", "toLowerCase", "(", ")", ")", ")", "results", ".", "push", "(", "PDoc", ".", "elements", "[", "name", "]", ")", ";", "}", "return", "results", ";", "}" ]
Given a key, finds all the PDoc objects that match.
[ "Given", "a", "key", "finds", "all", "the", "PDoc", "objects", "that", "match", "." ]
f2eff34e59f5af2e6a48f11f59f99c223b4a2be8
https://github.com/julesfern/spahql/blob/f2eff34e59f5af2e6a48f11f59f99c223b4a2be8/doc-html/src/javascripts/pdoc/application.js#L236-L243
25,881
C2FO/comb
lib/base/object.js
isHash
function isHash(obj) { var ret = comb.isObject(obj); return ret && obj.constructor === Object; }
javascript
function isHash(obj) { var ret = comb.isObject(obj); return ret && obj.constructor === Object; }
[ "function", "isHash", "(", "obj", ")", "{", "var", "ret", "=", "comb", ".", "isObject", "(", "obj", ")", ";", "return", "ret", "&&", "obj", ".", "constructor", "===", "Object", ";", "}" ]
Determines if an object is just a hash and not a qualified Object such as Number @example comb.isHash({}) => true comb.isHash({1 : 2, a : "b"}) => true comb.isHash(new Date()) => false comb.isHash(new String()) => false comb.isHash(new Number()) => false comb.isHash(new Boolean()) => false comb.isHash() => false comb.isHash("") => false comb.isHash(1) => false comb.isHash(false) => false comb.isHash(true) => false @param {Anything} obj the thing to test if it is a hash @returns {Boolean} true if it is a hash false otherwise @memberOf comb @static
[ "Determines", "if", "an", "object", "is", "just", "a", "hash", "and", "not", "a", "qualified", "Object", "such", "as", "Number" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/object.js#L161-L164
25,882
C2FO/comb
lib/base/object.js
extend
function extend(parent, ext) { var proto = parent.prototype || parent; merge(proto, ext); return parent; }
javascript
function extend(parent, ext) { var proto = parent.prototype || parent; merge(proto, ext); return parent; }
[ "function", "extend", "(", "parent", ",", "ext", ")", "{", "var", "proto", "=", "parent", ".", "prototype", "||", "parent", ";", "merge", "(", "proto", ",", "ext", ")", ";", "return", "parent", ";", "}" ]
Extends the prototype of an object if it exists otherwise it extends the object. @example var MyObj = function(){}; MyObj.prototype.test = true; comb.extend(MyObj, {test2 : false, test3 : "hello", test4 : "world"}); var myObj = new MyObj(); myObj.test => true myObj.test2 => false myObj.test3 => "hello" myObj.test4 => "world" var myObj2 = {}; myObj2.test = true; comb.extend(myObj2, {test2 : false, test3 : "hello", test4 : "world"}); myObj2.test => true myObj2.test2 => false myObj2.test3 => "hello" myObj2.test4 => "world" @param {Object} parent the parent object to extend @param {Object} extend the extension object to mixin to the parent @returns {Object} returns the extended object @memberOf comb @static
[ "Extends", "the", "prototype", "of", "an", "object", "if", "it", "exists", "otherwise", "it", "extends", "the", "object", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/object.js#L268-L272
25,883
C2FO/comb
lib/base/object.js
isEmpty
function isEmpty(object) { if (comb.isObject(object)) { for (var i in object) { if (object.hasOwnProperty(i)) { return false; } } } return true; }
javascript
function isEmpty(object) { if (comb.isObject(object)) { for (var i in object) { if (object.hasOwnProperty(i)) { return false; } } } return true; }
[ "function", "isEmpty", "(", "object", ")", "{", "if", "(", "comb", ".", "isObject", "(", "object", ")", ")", "{", "for", "(", "var", "i", "in", "object", ")", "{", "if", "(", "object", ".", "hasOwnProperty", "(", "i", ")", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}" ]
Determines if an object is empty @example comb.isEmpty({}) => true comb.isEmpty({a : 1}) => false @param object the object to test @returns {Boolean} true if the object is empty; @memberOf comb @static
[ "Determines", "if", "an", "object", "is", "empty" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/object.js#L302-L311
25,884
C2FO/comb
lib/base/object.js
values
function values(hash) { if (!isHash(hash)) { throw new TypeError(); } var keys = Object.keys(hash), ret = []; for (var i = 0, len = keys.length; i < len; ++i) { ret.push(hash[keys[i]]); } return ret; }
javascript
function values(hash) { if (!isHash(hash)) { throw new TypeError(); } var keys = Object.keys(hash), ret = []; for (var i = 0, len = keys.length; i < len; ++i) { ret.push(hash[keys[i]]); } return ret; }
[ "function", "values", "(", "hash", ")", "{", "if", "(", "!", "isHash", "(", "hash", ")", ")", "{", "throw", "new", "TypeError", "(", ")", ";", "}", "var", "keys", "=", "Object", ".", "keys", "(", "hash", ")", ",", "ret", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "keys", ".", "length", ";", "i", "<", "len", ";", "++", "i", ")", "{", "ret", ".", "push", "(", "hash", "[", "keys", "[", "i", "]", "]", ")", ";", "}", "return", "ret", ";", "}" ]
Returns the values of a hash. ``` var obj = {a : "b", c : "d", e : "f"}; comb(obj).values(); //["b", "d", "f"] comb.hash.values(obj); //["b", "d", "f"] ``` @param {Object} hash the object to retrieve the values of. @return {Array} array of values. @memberOf comb.hash
[ "Returns", "the", "values", "of", "a", "hash", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/object.js#L494-L503
25,885
C2FO/comb
lib/collections/Pool.js
function () { var ret; if (this.count <= this.__maxObjects && this.freeCount > 0) { ret = this.__freeObjects.dequeue(); this.__inUseObjects.push(ret); } else if (this.count < this.__maxObjects) { ret = this.createObject(); this.__inUseObjects.push(ret); } return ret; }
javascript
function () { var ret; if (this.count <= this.__maxObjects && this.freeCount > 0) { ret = this.__freeObjects.dequeue(); this.__inUseObjects.push(ret); } else if (this.count < this.__maxObjects) { ret = this.createObject(); this.__inUseObjects.push(ret); } return ret; }
[ "function", "(", ")", "{", "var", "ret", ";", "if", "(", "this", ".", "count", "<=", "this", ".", "__maxObjects", "&&", "this", ".", "freeCount", ">", "0", ")", "{", "ret", "=", "this", ".", "__freeObjects", ".", "dequeue", "(", ")", ";", "this", ".", "__inUseObjects", ".", "push", "(", "ret", ")", ";", "}", "else", "if", "(", "this", ".", "count", "<", "this", ".", "__maxObjects", ")", "{", "ret", "=", "this", ".", "createObject", "(", ")", ";", "this", ".", "__inUseObjects", ".", "push", "(", "ret", ")", ";", "}", "return", "ret", ";", "}" ]
Retrieves an object from this pool. ` @return {*} an object to contained in this pool
[ "Retrieves", "an", "object", "from", "this", "pool", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/Pool.js#L43-L53
25,886
C2FO/comb
lib/collections/Pool.js
function (obj) { var index; if (this.validate(obj) && this.count <= this.__maxObjects && (index = this.__inUseObjects.indexOf(obj)) > -1) { this.__freeObjects.enqueue(obj); this.__inUseObjects.splice(index, 1); } else { this.removeObject(obj); } }
javascript
function (obj) { var index; if (this.validate(obj) && this.count <= this.__maxObjects && (index = this.__inUseObjects.indexOf(obj)) > -1) { this.__freeObjects.enqueue(obj); this.__inUseObjects.splice(index, 1); } else { this.removeObject(obj); } }
[ "function", "(", "obj", ")", "{", "var", "index", ";", "if", "(", "this", ".", "validate", "(", "obj", ")", "&&", "this", ".", "count", "<=", "this", ".", "__maxObjects", "&&", "(", "index", "=", "this", ".", "__inUseObjects", ".", "indexOf", "(", "obj", ")", ")", ">", "-", "1", ")", "{", "this", ".", "__freeObjects", ".", "enqueue", "(", "obj", ")", ";", "this", ".", "__inUseObjects", ".", "splice", "(", "index", ",", "1", ")", ";", "}", "else", "{", "this", ".", "removeObject", "(", "obj", ")", ";", "}", "}" ]
Returns an object to this pool. The object is validated before it is returned to the pool, if the validation fails then it is removed from the pool; @param {*} obj the object to return to the pool
[ "Returns", "an", "object", "to", "this", "pool", ".", "The", "object", "is", "validated", "before", "it", "is", "returned", "to", "the", "pool", "if", "the", "validation", "fails", "then", "it", "is", "removed", "from", "the", "pool", ";" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/Pool.js#L60-L68
25,887
C2FO/comb
lib/collections/Pool.js
function (obj) { var index; if (this.__freeObjects.contains(obj)) { this.__freeObjects.remove(obj); } else if ((index = this.__inUseObjects.indexOf(obj)) > -1) { this.__inUseObjects.splice(index, 1); } //otherwise its not contained in this pool; return obj; }
javascript
function (obj) { var index; if (this.__freeObjects.contains(obj)) { this.__freeObjects.remove(obj); } else if ((index = this.__inUseObjects.indexOf(obj)) > -1) { this.__inUseObjects.splice(index, 1); } //otherwise its not contained in this pool; return obj; }
[ "function", "(", "obj", ")", "{", "var", "index", ";", "if", "(", "this", ".", "__freeObjects", ".", "contains", "(", "obj", ")", ")", "{", "this", ".", "__freeObjects", ".", "remove", "(", "obj", ")", ";", "}", "else", "if", "(", "(", "index", "=", "this", ".", "__inUseObjects", ".", "indexOf", "(", "obj", ")", ")", ">", "-", "1", ")", "{", "this", ".", "__inUseObjects", ".", "splice", "(", "index", ",", "1", ")", ";", "}", "//otherwise its not contained in this pool;", "return", "obj", ";", "}" ]
Removes an object from the pool, this can be overriden to provide any teardown of objects that needs to take place. @param {*} obj the object that needs to be removed. @return {*} the object removed.
[ "Removes", "an", "object", "from", "the", "pool", "this", "can", "be", "overriden", "to", "provide", "any", "teardown", "of", "objects", "that", "needs", "to", "take", "place", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/Pool.js#L78-L87
25,888
C2FO/comb
lib/base/date/index.js
function (/*Date*/date1, /*Date*/date2, /*String*/portion) { date1 = new Date(date1); date2 = new Date((date2 || new Date())); if (portion === "date") { // Ignore times and compare dates. date1.setHours(0, 0, 0, 0); date2.setHours(0, 0, 0, 0); } else if (portion === "time") { // Ignore dates and compare times. date1.setFullYear(0, 0, 0); date2.setFullYear(0, 0, 0); } return date1 > date2 ? 1 : date1 < date2 ? -1 : 0; }
javascript
function (/*Date*/date1, /*Date*/date2, /*String*/portion) { date1 = new Date(date1); date2 = new Date((date2 || new Date())); if (portion === "date") { // Ignore times and compare dates. date1.setHours(0, 0, 0, 0); date2.setHours(0, 0, 0, 0); } else if (portion === "time") { // Ignore dates and compare times. date1.setFullYear(0, 0, 0); date2.setFullYear(0, 0, 0); } return date1 > date2 ? 1 : date1 < date2 ? -1 : 0; }
[ "function", "(", "/*Date*/", "date1", ",", "/*Date*/", "date2", ",", "/*String*/", "portion", ")", "{", "date1", "=", "new", "Date", "(", "date1", ")", ";", "date2", "=", "new", "Date", "(", "(", "date2", "||", "new", "Date", "(", ")", ")", ")", ";", "if", "(", "portion", "===", "\"date\"", ")", "{", "// Ignore times and compare dates.", "date1", ".", "setHours", "(", "0", ",", "0", ",", "0", ",", "0", ")", ";", "date2", ".", "setHours", "(", "0", ",", "0", ",", "0", ",", "0", ")", ";", "}", "else", "if", "(", "portion", "===", "\"time\"", ")", "{", "// Ignore dates and compare times.", "date1", ".", "setFullYear", "(", "0", ",", "0", ",", "0", ")", ";", "date2", ".", "setFullYear", "(", "0", ",", "0", ",", "0", ")", ";", "}", "return", "date1", ">", "date2", "?", "1", ":", "date1", "<", "date2", "?", "-", "1", ":", "0", ";", "}" ]
Compares two dates @example var d1 = new Date(); d1.setHours(0); comb.date.compare(d1, d1); // 0 var d1 = new Date(); d1.setHours(0); var d2 = new Date(); d2.setFullYear(2005); d2.setHours(12); comb.date.compare(d1, d2, "date"); // 1 comb.date.compare(d1, d2, "datetime"); // 1 var d1 = new Date(); d1.setHours(0); var d2 = new Date(); d2.setFullYear(2005); d2.setHours(12); comb.date.compare(d2, d1, "date"); // -1 comb.date.compare(d1, d2, "time"); //-1 @param {Date|String} date1 the date to comapare @param {Date|String} [date2=new Date()] the date to compare date1 againse @param {"date"|"time"|"datetime"} portion compares the portion specified @returns -1 if date1 is < date2 0 if date1 === date2 1 if date1 > date2
[ "Compares", "two", "dates" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/date/index.js#L267-L281
25,889
C2FO/comb
lib/logging/appenders/appender.js
function (type, options) { var caseType = type.toLowerCase(); if (caseType in APPENDER_TYPES) { return new APPENDER_TYPES[caseType](options); } else { throw new Error(type + " appender is not registered!"); } }
javascript
function (type, options) { var caseType = type.toLowerCase(); if (caseType in APPENDER_TYPES) { return new APPENDER_TYPES[caseType](options); } else { throw new Error(type + " appender is not registered!"); } }
[ "function", "(", "type", ",", "options", ")", "{", "var", "caseType", "=", "type", ".", "toLowerCase", "(", ")", ";", "if", "(", "caseType", "in", "APPENDER_TYPES", ")", "{", "return", "new", "APPENDER_TYPES", "[", "caseType", "]", "(", "options", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "type", "+", "\" appender is not registered!\"", ")", ";", "}", "}" ]
Acts as a factory for appenders. @example var logging = comb.logging, Logger = logging.Logger, Appender = logging.appenders.Appender; var logger = comb.logging.Logger.getLogger("my.logger"); logger.addAppender(Appender.createAppender("consoleAppender")); @param {String} type the type of appender to create. @param {Object} [options={}] additional options to pass to the appender. @return {comb.logging.appenders.Appender} an appender to add to a logger.
[ "Acts", "as", "a", "factory", "for", "appenders", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/logging/appenders/appender.js#L159-L167
25,890
C2FO/comb
lib/logging/config.js
function (appender) { var rootLogger = Logger.getRootLogger(); rootLogger.removeAllAppenders(); if (base.isInstanceOf(appender, appenders.Appender)) { rootLogger.addAppender(appender); } else { rootLogger.addAppender(new appenders.ConsoleAppender()); } }
javascript
function (appender) { var rootLogger = Logger.getRootLogger(); rootLogger.removeAllAppenders(); if (base.isInstanceOf(appender, appenders.Appender)) { rootLogger.addAppender(appender); } else { rootLogger.addAppender(new appenders.ConsoleAppender()); } }
[ "function", "(", "appender", ")", "{", "var", "rootLogger", "=", "Logger", ".", "getRootLogger", "(", ")", ";", "rootLogger", ".", "removeAllAppenders", "(", ")", ";", "if", "(", "base", ".", "isInstanceOf", "(", "appender", ",", "appenders", ".", "Appender", ")", ")", "{", "rootLogger", ".", "addAppender", "(", "appender", ")", ";", "}", "else", "{", "rootLogger", ".", "addAppender", "(", "new", "appenders", ".", "ConsoleAppender", "(", ")", ")", ";", "}", "}" ]
Configure logging. @param {comb.logging.Appender} [appender=null] appender to add to the root logger, by default a console logger is added.
[ "Configure", "logging", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/logging/config.js#L59-L67
25,891
C2FO/comb
lib/base/string.js
format
function format(str, obj) { if (obj instanceof Array) { var i = 0, len = obj.length; //find the matches return str.replace(FORMAT_REGEX, function (m, format, type) { var replacer, ret; if (i < len) { replacer = obj[i++]; } else { //we are out of things to replace with so //just return the match? return m; } if (m === "%s" || m === "%d" || m === "%D") { //fast path! ret = replacer + ""; } else if (m === "%Z") { ret = replacer.toUTCString(); } else if (m === "%j") { try { ret = JSON.stringify(replacer); } catch (e) { throw new Error("comb.string.format : Unable to parse json from ", replacer); } } else { format = format.replace(/^\[|\]$/g, ""); switch (type) { case "s": ret = formatString(replacer, format); break; case "d": ret = formatNumber(replacer, format); break; case "j": ret = formatObject(replacer, format); break; case "D": ret = getDate().date.format(replacer, format); break; case "Z": ret = getDate().date.format(replacer, format, true); break; } } return ret; }); } else if (isHash(obj)) { return str.replace(INTERP_REGEX, function (m, format, value) { value = obj[value]; if (!misc.isUndefined(value)) { if (format) { if (comb.isString(value)) { return formatString(value, format); } else if (typeof value === "number") { return formatNumber(value, format); } else if (getDate().isDate(value)) { return getDate().date.format(value, format); } else if (typeof value === "object") { return formatObject(value, format); } } else { return "" + value; } } return m; }); } else { var args = pSlice.call(arguments).slice(1); return format(str, args); } }
javascript
function format(str, obj) { if (obj instanceof Array) { var i = 0, len = obj.length; //find the matches return str.replace(FORMAT_REGEX, function (m, format, type) { var replacer, ret; if (i < len) { replacer = obj[i++]; } else { //we are out of things to replace with so //just return the match? return m; } if (m === "%s" || m === "%d" || m === "%D") { //fast path! ret = replacer + ""; } else if (m === "%Z") { ret = replacer.toUTCString(); } else if (m === "%j") { try { ret = JSON.stringify(replacer); } catch (e) { throw new Error("comb.string.format : Unable to parse json from ", replacer); } } else { format = format.replace(/^\[|\]$/g, ""); switch (type) { case "s": ret = formatString(replacer, format); break; case "d": ret = formatNumber(replacer, format); break; case "j": ret = formatObject(replacer, format); break; case "D": ret = getDate().date.format(replacer, format); break; case "Z": ret = getDate().date.format(replacer, format, true); break; } } return ret; }); } else if (isHash(obj)) { return str.replace(INTERP_REGEX, function (m, format, value) { value = obj[value]; if (!misc.isUndefined(value)) { if (format) { if (comb.isString(value)) { return formatString(value, format); } else if (typeof value === "number") { return formatNumber(value, format); } else if (getDate().isDate(value)) { return getDate().date.format(value, format); } else if (typeof value === "object") { return formatObject(value, format); } } else { return "" + value; } } return m; }); } else { var args = pSlice.call(arguments).slice(1); return format(str, args); } }
[ "function", "format", "(", "str", ",", "obj", ")", "{", "if", "(", "obj", "instanceof", "Array", ")", "{", "var", "i", "=", "0", ",", "len", "=", "obj", ".", "length", ";", "//find the matches", "return", "str", ".", "replace", "(", "FORMAT_REGEX", ",", "function", "(", "m", ",", "format", ",", "type", ")", "{", "var", "replacer", ",", "ret", ";", "if", "(", "i", "<", "len", ")", "{", "replacer", "=", "obj", "[", "i", "++", "]", ";", "}", "else", "{", "//we are out of things to replace with so", "//just return the match?", "return", "m", ";", "}", "if", "(", "m", "===", "\"%s\"", "||", "m", "===", "\"%d\"", "||", "m", "===", "\"%D\"", ")", "{", "//fast path!", "ret", "=", "replacer", "+", "\"\"", ";", "}", "else", "if", "(", "m", "===", "\"%Z\"", ")", "{", "ret", "=", "replacer", ".", "toUTCString", "(", ")", ";", "}", "else", "if", "(", "m", "===", "\"%j\"", ")", "{", "try", "{", "ret", "=", "JSON", ".", "stringify", "(", "replacer", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "\"comb.string.format : Unable to parse json from \"", ",", "replacer", ")", ";", "}", "}", "else", "{", "format", "=", "format", ".", "replace", "(", "/", "^\\[|\\]$", "/", "g", ",", "\"\"", ")", ";", "switch", "(", "type", ")", "{", "case", "\"s\"", ":", "ret", "=", "formatString", "(", "replacer", ",", "format", ")", ";", "break", ";", "case", "\"d\"", ":", "ret", "=", "formatNumber", "(", "replacer", ",", "format", ")", ";", "break", ";", "case", "\"j\"", ":", "ret", "=", "formatObject", "(", "replacer", ",", "format", ")", ";", "break", ";", "case", "\"D\"", ":", "ret", "=", "getDate", "(", ")", ".", "date", ".", "format", "(", "replacer", ",", "format", ")", ";", "break", ";", "case", "\"Z\"", ":", "ret", "=", "getDate", "(", ")", ".", "date", ".", "format", "(", "replacer", ",", "format", ",", "true", ")", ";", "break", ";", "}", "}", "return", "ret", ";", "}", ")", ";", "}", "else", "if", "(", "isHash", "(", "obj", ")", ")", "{", "return", "str", ".", "replace", "(", "INTERP_REGEX", ",", "function", "(", "m", ",", "format", ",", "value", ")", "{", "value", "=", "obj", "[", "value", "]", ";", "if", "(", "!", "misc", ".", "isUndefined", "(", "value", ")", ")", "{", "if", "(", "format", ")", "{", "if", "(", "comb", ".", "isString", "(", "value", ")", ")", "{", "return", "formatString", "(", "value", ",", "format", ")", ";", "}", "else", "if", "(", "typeof", "value", "===", "\"number\"", ")", "{", "return", "formatNumber", "(", "value", ",", "format", ")", ";", "}", "else", "if", "(", "getDate", "(", ")", ".", "isDate", "(", "value", ")", ")", "{", "return", "getDate", "(", ")", ".", "date", ".", "format", "(", "value", ",", "format", ")", ";", "}", "else", "if", "(", "typeof", "value", "===", "\"object\"", ")", "{", "return", "formatObject", "(", "value", ",", "format", ")", ";", "}", "}", "else", "{", "return", "\"\"", "+", "value", ";", "}", "}", "return", "m", ";", "}", ")", ";", "}", "else", "{", "var", "args", "=", "pSlice", ".", "call", "(", "arguments", ")", ".", "slice", "(", "1", ")", ";", "return", "format", "(", "str", ",", "args", ")", ";", "}", "}" ]
Formats a string with the specified format Format `String`s ``` comb.string.format("%s", "Hello"); // "Hello" comb.string.format("%10s", "Hello"); // " Hello" comb.string.format("%-10s", "Hello"); // ""Hello "" comb.string.format('%.10s', "Hello"); //".....Hello" comb.string.format('%-!10s', "Hello"); //"Hello!!!!!" comb.string.format("%-.10s%s!", "Hello", "World"); //"Hello.....World!" ``` Formatting Numbers ``` comb.string.format('%d', 10); //"10" //setting precision comb.string.format('%.2d', 10); //"10.00" //specifying width comb.string.format('%5d', 10); //" 10" //Signed comb.string.format('%+d', 10); //"+10" comb.string.format('%+d', -10); //"-10" comb.string.format('% d', 10); //" 10" comb.string.format('% d', -10); //"-10" //width comb.string.format('%5d', 10); //" 10" //width and precision comb.string.format('%6.2d', 10); //" 10.00" //signed, width and precision comb.string.format('%+ 7.2d', 10); //" +10.00" comb.string.format('%+ 7.2d', -10); //" -10.00" comb.string.format('%+07.2d', 10); //"+010.00" comb.string.format('%+07.2d', -10); //"-010.00" comb.string.format('% 7.2d', 10); //" 10.00" comb.string.format('% 7.2d', -10); //" -10.00" comb.string.format('% 7.2d', 10); //" 10.00" comb.string.format('% 7.2d', -10); //" -10.00" //use a 0 as padding comb.string.format('%010d', 10); //"0000000010" //use an ! as padding comb.string.format('%!10d', 10); //"!!!!!!!!10" //left justify signed ! as padding and a width of 10 comb.string.format('%-+!10d', 10); //"+10!!!!!!!" ``` Formatting dates ``` comb.string.format("%[h:mm a]D", new Date(2014, 05, 04, 7,6,1)); // 7:06 AM - local - comb.string.format("%[h:mm a]Z", new Date(2014, 05, 04, 7,6,1)); //12:06 PM - UTC comb.string.format("%[yyyy-MM-dd]D", new Date(2014, 05, 04, 7,6,1)); // 2014-06-04 - local comb.string.format("%[yyyy-MM-dd]Z", new Date(2014, 05, 04, 7,6,1)); // 2014-06-04 - UTC ``` Formatting Objects ``` //When using object formats they must be in an array otherwise //format will try to interpolate the properties into the string. comb.string.format("%j", [{a : "b"}]) // '{"a":"b"}' //Specifying spacing comb.string.format("%4j", [{a : "b"}]) // '{\n "a": "b"\n}' ``` String interpolation ``` comb.string.format("{hello}, {world}", {hello : "Hello", world : "World"); //"Hello, World"; comb.string.format("{[.2]min}...{[.2]max}", {min: 1, max: 10}); //"1.00...10.00" ``` @param {String} str the string to format, if you want to use a spacing character as padding (other than \\s) then put your format in brackets. <ol> <li>String Formats %[options]s</li> <ul> <li>- : left justified</li> <li>Char : padding character <b>Excludes d,j,s</b></li> <li>Number : width</li> </ul> </li> <li>Number Formats %[options]d</li> <ul> <li>`-` : left justified</li> <li>`+` or `<space>` : signed number if space is used the number will use a extra `<space>` instead of a `+`</li> <li>`<Char>` : padding character <b>Excludes d,j,s</b></li> <li>`Number` : width</li> <li>`.Number`: specify the precision of the number</li> </ul> </li> <li>Object Formats %[options]j</li> <ul> <li>Number : spacing for object properties.</li> </ul> </li> </ol> @param {Object|Array|Arguments...} obj the parameters to replace in the string if an array is passed then the array is used sequentially if an object is passed then the object keys are used if a variable number of args are passed then they are used like an array @returns {String} the formatted string @memberOf comb.string @static
[ "Formats", "a", "string", "with", "the", "specified", "format" ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/string.js#L326-L397
25,892
C2FO/comb
lib/base/string.js
style
function style(str, options) { var ret = str; if (options) { if (ret instanceof Array) { ret = ret.map(function (s) { return style(s, options); }); } else if (options instanceof Array) { options.forEach(function (option) { ret = style(ret, option); }); } else if (options in styles) { ret = '\x1B[' + styles[options] + 'm' + str + '\x1B[0m'; } } return ret; }
javascript
function style(str, options) { var ret = str; if (options) { if (ret instanceof Array) { ret = ret.map(function (s) { return style(s, options); }); } else if (options instanceof Array) { options.forEach(function (option) { ret = style(ret, option); }); } else if (options in styles) { ret = '\x1B[' + styles[options] + 'm' + str + '\x1B[0m'; } } return ret; }
[ "function", "style", "(", "str", ",", "options", ")", "{", "var", "ret", "=", "str", ";", "if", "(", "options", ")", "{", "if", "(", "ret", "instanceof", "Array", ")", "{", "ret", "=", "ret", ".", "map", "(", "function", "(", "s", ")", "{", "return", "style", "(", "s", ",", "options", ")", ";", "}", ")", ";", "}", "else", "if", "(", "options", "instanceof", "Array", ")", "{", "options", ".", "forEach", "(", "function", "(", "option", ")", "{", "ret", "=", "style", "(", "ret", ",", "option", ")", ";", "}", ")", ";", "}", "else", "if", "(", "options", "in", "styles", ")", "{", "ret", "=", "'\\x1B['", "+", "styles", "[", "options", "]", "+", "'m'", "+", "str", "+", "'\\x1B[0m'", ";", "}", "}", "return", "ret", ";", "}" ]
Styles a string according to the specified styles. @example //style a string red comb.string.style('myStr', 'red'); //style a string red and bold comb.string.style('myStr', ['red', bold]); @param {String} str The string to style. @param {String|Array} styles the style or styles to apply to a string. options include : <ul> <li>bold</li> <li>bright</li> <li>italic</li> <li>underline</li> <li>inverse</li> <li>crossedOut</li> <li>blink</li> <li>red</li> <li>green</li> <li>yellow</li> <li>blue</li> <li>magenta</li> <li>cyan</li> <li>white</li> <li>redBackground</li> <li>greenBackground</li> <li>yellowBackground</li> <li>blueBackground</li> <li>magentaBackground</li> <li>cyanBackground</li> <li>whiteBackground</li> <li>grey</li> <li>black</li> </ul> @memberOf comb.string @static
[ "Styles", "a", "string", "according", "to", "the", "specified", "styles", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/string.js#L473-L489
25,893
C2FO/comb
lib/base/functions.js
applyFirst
function applyFirst(method, args) { args = Array.prototype.slice.call(arguments).slice(1); if (!isString(method) && !isFunction(method)) { throw new Error(method + " must be the name of a property or function to execute"); } if (isString(method)) { return function () { var scopeArgs = Array.prototype.slice.call(arguments), scope = scopeArgs.shift(); var func = scope[method]; if (isFunction(func)) { scopeArgs = args.concat(scopeArgs); return spreadArgs(func, scopeArgs, scope); } else { return func; } }; } else { return function () { var scopeArgs = Array.prototype.slice.call(arguments), scope = scopeArgs.shift(); scopeArgs = args.concat(scopeArgs); return spreadArgs(method, scopeArgs, scope); }; } }
javascript
function applyFirst(method, args) { args = Array.prototype.slice.call(arguments).slice(1); if (!isString(method) && !isFunction(method)) { throw new Error(method + " must be the name of a property or function to execute"); } if (isString(method)) { return function () { var scopeArgs = Array.prototype.slice.call(arguments), scope = scopeArgs.shift(); var func = scope[method]; if (isFunction(func)) { scopeArgs = args.concat(scopeArgs); return spreadArgs(func, scopeArgs, scope); } else { return func; } }; } else { return function () { var scopeArgs = Array.prototype.slice.call(arguments), scope = scopeArgs.shift(); scopeArgs = args.concat(scopeArgs); return spreadArgs(method, scopeArgs, scope); }; } }
[ "function", "applyFirst", "(", "method", ",", "args", ")", "{", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ".", "slice", "(", "1", ")", ";", "if", "(", "!", "isString", "(", "method", ")", "&&", "!", "isFunction", "(", "method", ")", ")", "{", "throw", "new", "Error", "(", "method", "+", "\" must be the name of a property or function to execute\"", ")", ";", "}", "if", "(", "isString", "(", "method", ")", ")", "{", "return", "function", "(", ")", "{", "var", "scopeArgs", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ",", "scope", "=", "scopeArgs", ".", "shift", "(", ")", ";", "var", "func", "=", "scope", "[", "method", "]", ";", "if", "(", "isFunction", "(", "func", ")", ")", "{", "scopeArgs", "=", "args", ".", "concat", "(", "scopeArgs", ")", ";", "return", "spreadArgs", "(", "func", ",", "scopeArgs", ",", "scope", ")", ";", "}", "else", "{", "return", "func", ";", "}", "}", ";", "}", "else", "{", "return", "function", "(", ")", "{", "var", "scopeArgs", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ",", "scope", "=", "scopeArgs", ".", "shift", "(", ")", ";", "scopeArgs", "=", "args", ".", "concat", "(", "scopeArgs", ")", ";", "return", "spreadArgs", "(", "method", ",", "scopeArgs", ",", "scope", ")", ";", "}", ";", "}", "}" ]
Binds a method to the scope of the first argument. This is useful if you have async actions and you just want to run a method or retrieve a property on the object. ``` var arr = [], push = comb.applyFirst("push"), length = comb.applyFirst("length"); push(arr, 1, 2,3,4); console.log(length(arr)); //4 console.log(arr); //1,2,3,4 ``` @static @memberOf comb @param {String|Function} method the method to invoke in the scope of the first arument. @param [args] optional args to pass to the callback @returns {Function} a function that will execute the method in the scope of the first argument.
[ "Binds", "a", "method", "to", "the", "scope", "of", "the", "first", "argument", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/functions.js#L97-L120
25,894
julesfern/spahql
doc-html/src/javascripts/pdoc/prototype.js
each
function each(iterator) { for (var i = 0, length = this.length; i < length; i++) iterator(this[i]); }
javascript
function each(iterator) { for (var i = 0, length = this.length; i < length; i++) iterator(this[i]); }
[ "function", "each", "(", "iterator", ")", "{", "for", "(", "var", "i", "=", "0", ",", "length", "=", "this", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "iterator", "(", "this", "[", "i", "]", ")", ";", "}" ]
use native browser JS 1.6 implementation if available
[ "use", "native", "browser", "JS", "1", ".", "6", "implementation", "if", "available" ]
f2eff34e59f5af2e6a48f11f59f99c223b4a2be8
https://github.com/julesfern/spahql/blob/f2eff34e59f5af2e6a48f11f59f99c223b4a2be8/doc-html/src/javascripts/pdoc/prototype.js#L968-L971
25,895
C2FO/comb
lib/async.js
asyncForEach
function asyncForEach(promise, iterator, scope, limit) { return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) { return results.arr; })); }
javascript
function asyncForEach(promise, iterator, scope, limit) { return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) { return results.arr; })); }
[ "function", "asyncForEach", "(", "promise", ",", "iterator", ",", "scope", ",", "limit", ")", "{", "return", "asyncArray", "(", "asyncLoop", "(", "promise", ",", "iterator", ",", "scope", ",", "limit", ")", ".", "chain", "(", "function", "(", "results", ")", "{", "return", "results", ".", "arr", ";", "}", ")", ")", ";", "}" ]
Loops through the results of an promise. The promise can return an array or just a single item. ``` function asyncArr(){ var ret = new comb.Promise(); process.nextTick(ret.callback.bind(ret, [1,2,3,4,5]); return ret.promise; } comb.async.forEach(asyncArr(), function(){ //do something with it }).then(function(arr){ console.log(arr); //[1,2,3,4,5]; }); ``` You may also return a promise from the iterator block. ``` var myNewArr = []; comb.async.forEach(asyncArr(), function(item, index){ var ret = new comb.Promise(); process.nextTick(function(){ myNewArr.push([item, index]); ret.callback(); }); return ret.promise(); }).then(function(){ console.log(myNewArr) //[[1,0], [2,1], [3,2], [4,3], [5,4]] }); ``` @param {comb.Promise|Array} promise the promise or array to loop through @param {Function} iterator a function to invoke for each item @param [scope] optional scope to execute the function in. @return {comb.Promise} a promise that is resolved with the original array. @static @memberof comb.async @name forEach
[ "Loops", "through", "the", "results", "of", "an", "promise", ".", "The", "promise", "can", "return", "an", "array", "or", "just", "a", "single", "item", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/async.js#L160-L164
25,896
C2FO/comb
lib/async.js
asyncMap
function asyncMap(promise, iterator, scope, limit) { return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) { return results.loopResults; })); }
javascript
function asyncMap(promise, iterator, scope, limit) { return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) { return results.loopResults; })); }
[ "function", "asyncMap", "(", "promise", ",", "iterator", ",", "scope", ",", "limit", ")", "{", "return", "asyncArray", "(", "asyncLoop", "(", "promise", ",", "iterator", ",", "scope", ",", "limit", ")", ".", "chain", "(", "function", "(", "results", ")", "{", "return", "results", ".", "loopResults", ";", "}", ")", ")", ";", "}" ]
Loops through the results of an promise resolving with the return value of the iterator function. The promise can return an array or just a single item. ``` function asyncArr(){ var ret = new comb.Promise(); process.nextTick(ret.callback.bind(ret, [1,2,3,4,5]); return ret.promise; } comb.async.map(asyncArr(), function(item){ return item * 2; }).then(function(arr){ console.log(arr); //[2,4,6,8,10]; }); ``` You may also return a promise from the iterator block. ``` comb.async.map(asyncArr(), function(item, index){ var ret = new comb.Promise(); process.nextTick(function(){ ret.callback(item * 2); }); return ret.promise(); }).then(function(){ console.log(myNewArr) //[2,4,6,8,10]; }); ``` @param {comb.Promise|Array} promise the promise or array to loop through @param {Function} iterator a function to invoke for each item @param [scope] optional scope to execute the function in. @return {comb.Promise} a promise that is resolved with the mapped array. @static @memberof comb.async @name map
[ "Loops", "through", "the", "results", "of", "an", "promise", "resolving", "with", "the", "return", "value", "of", "the", "iterator", "function", ".", "The", "promise", "can", "return", "an", "array", "or", "just", "a", "single", "item", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/async.js#L209-L213
25,897
C2FO/comb
lib/async.js
asyncFilter
function asyncFilter(promise, iterator, scope, limit) { return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) { var loopResults = results.loopResults, resultArr = results.arr; return (isArray(resultArr) ? resultArr : [resultArr]).filter(function (res, i) { return loopResults[i]; }); })); }
javascript
function asyncFilter(promise, iterator, scope, limit) { return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) { var loopResults = results.loopResults, resultArr = results.arr; return (isArray(resultArr) ? resultArr : [resultArr]).filter(function (res, i) { return loopResults[i]; }); })); }
[ "function", "asyncFilter", "(", "promise", ",", "iterator", ",", "scope", ",", "limit", ")", "{", "return", "asyncArray", "(", "asyncLoop", "(", "promise", ",", "iterator", ",", "scope", ",", "limit", ")", ".", "chain", "(", "function", "(", "results", ")", "{", "var", "loopResults", "=", "results", ".", "loopResults", ",", "resultArr", "=", "results", ".", "arr", ";", "return", "(", "isArray", "(", "resultArr", ")", "?", "resultArr", ":", "[", "resultArr", "]", ")", ".", "filter", "(", "function", "(", "res", ",", "i", ")", "{", "return", "loopResults", "[", "i", "]", ";", "}", ")", ";", "}", ")", ")", ";", "}" ]
Loops through the results of an promise resolving with the filtered array. The promise can return an array or just a single item. ``` function asyncArr(){ var ret = new comb.Promise(); process.nextTick(ret.callback.bind(ret, [1,2,3,4,5]); return ret.promise; } comb.async.filter(asyncArr(), function(item){ return item % 2; }).then(function(arr){ console.log(arr); //[1,3,5]; }); ``` You may also return a promise from the iterator block. ``` comb.async.filter(asyncArr(), function(item, index){ var ret = new comb.Promise(); process.nextTick(function(){ ret.callback(item % 2); }); return ret.promise(); }).then(function(){ console.log(myNewArr) //[1,3,5]; }) ``` @param {comb.Promise|Array} promise the promise or array to loop through @param {Function} iterator a function to invoke for each item @param [scope] optional scope to execute the function in. @return {comb.Promise} a promise that is resolved with the filtered array. @static @memberof comb.async @name filter
[ "Loops", "through", "the", "results", "of", "an", "promise", "resolving", "with", "the", "filtered", "array", ".", "The", "promise", "can", "return", "an", "array", "or", "just", "a", "single", "item", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/async.js#L258-L265
25,898
C2FO/comb
lib/async.js
asyncEvery
function asyncEvery(promise, iterator, scope, limit) { return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) { return results.loopResults.every(function (res) { return !!res; }); })); }
javascript
function asyncEvery(promise, iterator, scope, limit) { return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) { return results.loopResults.every(function (res) { return !!res; }); })); }
[ "function", "asyncEvery", "(", "promise", ",", "iterator", ",", "scope", ",", "limit", ")", "{", "return", "asyncArray", "(", "asyncLoop", "(", "promise", ",", "iterator", ",", "scope", ",", "limit", ")", ".", "chain", "(", "function", "(", "results", ")", "{", "return", "results", ".", "loopResults", ".", "every", "(", "function", "(", "res", ")", "{", "return", "!", "!", "res", ";", "}", ")", ";", "}", ")", ")", ";", "}" ]
Loops through the results of an promise resolving with true if every item passed, false otherwise. The promise can return an array or just a single item. ``` function asyncArr(){ var ret = new comb.Promise(); process.nextTick(ret.callback.bind(ret, [1,2,3,4,5]); return ret.promise; } comb.async.every(asyncArr(), function(item){ return item <= 5; }).then(function(every){ console.log(every); //true }); ``` You may also return a promise from the iterator block. ``` comb.async.every(asyncArr(), function(item, index){ var ret = new comb.Promise(); process.nextTick(function(){ ret.callback(item == 1); }); return ret.promise(); }).then(function(){ console.log(myNewArr) //false; }) ``` @param {comb.Promise|Array} promise the promise or array to loop through @param {Function} iterator a function to invoke for each item @param [scope] optional scope to execute the function in. @return {comb.Promise} a promise that is resolved true if every item passed false otherwise. @static @memberof comb.async @name every
[ "Loops", "through", "the", "results", "of", "an", "promise", "resolving", "with", "true", "if", "every", "item", "passed", "false", "otherwise", ".", "The", "promise", "can", "return", "an", "array", "or", "just", "a", "single", "item", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/async.js#L310-L316
25,899
C2FO/comb
lib/async.js
asyncSome
function asyncSome(promise, iterator, scope, limit) { return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) { return results.loopResults.some(function (res) { return !!res; }); })); }
javascript
function asyncSome(promise, iterator, scope, limit) { return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) { return results.loopResults.some(function (res) { return !!res; }); })); }
[ "function", "asyncSome", "(", "promise", ",", "iterator", ",", "scope", ",", "limit", ")", "{", "return", "asyncArray", "(", "asyncLoop", "(", "promise", ",", "iterator", ",", "scope", ",", "limit", ")", ".", "chain", "(", "function", "(", "results", ")", "{", "return", "results", ".", "loopResults", ".", "some", "(", "function", "(", "res", ")", "{", "return", "!", "!", "res", ";", "}", ")", ";", "}", ")", ")", ";", "}" ]
Loops through the results of an promise resolving with true if some items passed, false otherwise. The promise can return an array or just a single item. ``` function asyncArr(){ var ret = new comb.Promise(); process.nextTick(ret.callback.bind(ret, [1,2,3,4,5]); return ret.promise; } comb.async.some(asyncArr(), function(item){ return item == 1; }).then(function(every){ console.log(every); //true }); ``` You may also return a promise from the iterator block. ``` comb.async.some(asyncArr(), function(item, index){ var ret = new comb.Promise(); process.nextTick(function(){ ret.callback(item > 5); }); return ret.promise(); }).then(function(){ console.log(myNewArr) //false; }) ``` @param {comb.Promise|Array} promise the promise or array to loop through @param {Function} iterator a function to invoke for each item @param [scope] optional scope to execute the function in. @return {comb.Promise} a promise that is resolved with true if some items passed false otherwise. @static @memberof comb.async @name some
[ "Loops", "through", "the", "results", "of", "an", "promise", "resolving", "with", "true", "if", "some", "items", "passed", "false", "otherwise", ".", "The", "promise", "can", "return", "an", "array", "or", "just", "a", "single", "item", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/async.js#L360-L366