id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
19,100
lirown/graphql-custom-directives
src/custom.js
resolveWithDirective
function resolveWithDirective(resolve, source, directive, context, info) { source = source || ((info || {}).variableValues || {}).input_0 || {}; let directiveConfig = info.schema._directives.filter( d => directive.name.value === d.name, )[0]; let args = {}; for (let arg of directive.arguments) { args[arg.name.value] = arg.value.value; } return directiveConfig.resolve(resolve, source, args, context, info); }
javascript
function resolveWithDirective(resolve, source, directive, context, info) { source = source || ((info || {}).variableValues || {}).input_0 || {}; let directiveConfig = info.schema._directives.filter( d => directive.name.value === d.name, )[0]; let args = {}; for (let arg of directive.arguments) { args[arg.name.value] = arg.value.value; } return directiveConfig.resolve(resolve, source, args, context, info); }
[ "function", "resolveWithDirective", "(", "resolve", ",", "source", ",", "directive", ",", "context", ",", "info", ")", "{", "source", "=", "source", "||", "(", "(", "info", "||", "{", "}", ")", ".", "variableValues", "||", "{", "}", ")", ".", "input_0", "||", "{", "}", ";", "let", "directiveConfig", "=", "info", ".", "schema", ".", "_directives", ".", "filter", "(", "d", "=>", "directive", ".", "name", ".", "value", "===", "d", ".", "name", ",", ")", "[", "0", "]", ";", "let", "args", "=", "{", "}", ";", "for", "(", "let", "arg", "of", "directive", ".", "arguments", ")", "{", "args", "[", "arg", ".", "name", ".", "value", "]", "=", "arg", ".", "value", ".", "value", ";", "}", "return", "directiveConfig", ".", "resolve", "(", "resolve", ",", "source", ",", "args", ",", "context", ",", "info", ")", ";", "}" ]
resolving field using directive resolver
[ "resolving", "field", "using", "directive", "resolver" ]
a0709eaa07f264e3431ce91188e4ac30978644d6
https://github.com/lirown/graphql-custom-directives/blob/a0709eaa07f264e3431ce91188e4ac30978644d6/src/custom.js#L25-L38
19,101
lirown/graphql-custom-directives
src/custom.js
parseSchemaDirectives
function parseSchemaDirectives(directives) { let schemaDirectives = []; if ( !directives || !(directives instanceof Object) || Object.keys(directives).length === 0 ) { return []; } for (let directiveName in directives) { let argsList = [], args = ''; Object.keys(directives[directiveName]).map(key => { argsList.push(`${key}:"${directives[directiveName][key]}"`); }); if (argsList.length > 0) { args = `(${argsList.join(',')})`; } schemaDirectives.push(`@${directiveName}${args}`); } return parse(`{ a: String ${schemaDirectives.join(' ')} }`).definitions[0] .selectionSet.selections[0].directives; }
javascript
function parseSchemaDirectives(directives) { let schemaDirectives = []; if ( !directives || !(directives instanceof Object) || Object.keys(directives).length === 0 ) { return []; } for (let directiveName in directives) { let argsList = [], args = ''; Object.keys(directives[directiveName]).map(key => { argsList.push(`${key}:"${directives[directiveName][key]}"`); }); if (argsList.length > 0) { args = `(${argsList.join(',')})`; } schemaDirectives.push(`@${directiveName}${args}`); } return parse(`{ a: String ${schemaDirectives.join(' ')} }`).definitions[0] .selectionSet.selections[0].directives; }
[ "function", "parseSchemaDirectives", "(", "directives", ")", "{", "let", "schemaDirectives", "=", "[", "]", ";", "if", "(", "!", "directives", "||", "!", "(", "directives", "instanceof", "Object", ")", "||", "Object", ".", "keys", "(", "directives", ")", ".", "length", "===", "0", ")", "{", "return", "[", "]", ";", "}", "for", "(", "let", "directiveName", "in", "directives", ")", "{", "let", "argsList", "=", "[", "]", ",", "args", "=", "''", ";", "Object", ".", "keys", "(", "directives", "[", "directiveName", "]", ")", ".", "map", "(", "key", "=>", "{", "argsList", ".", "push", "(", "`", "${", "key", "}", "${", "directives", "[", "directiveName", "]", "[", "key", "]", "}", "`", ")", ";", "}", ")", ";", "if", "(", "argsList", ".", "length", ">", "0", ")", "{", "args", "=", "`", "${", "argsList", ".", "join", "(", "','", ")", "}", "`", ";", "}", "schemaDirectives", ".", "push", "(", "`", "${", "directiveName", "}", "${", "args", "}", "`", ")", ";", "}", "return", "parse", "(", "`", "${", "schemaDirectives", ".", "join", "(", "' '", ")", "}", "`", ")", ".", "definitions", "[", "0", "]", ".", "selectionSet", ".", "selections", "[", "0", "]", ".", "directives", ";", "}" ]
parse directives from a schema defenition form them as graphql directive structure
[ "parse", "directives", "from", "a", "schema", "defenition", "form", "them", "as", "graphql", "directive", "structure" ]
a0709eaa07f264e3431ce91188e4ac30978644d6
https://github.com/lirown/graphql-custom-directives/blob/a0709eaa07f264e3431ce91188e4ac30978644d6/src/custom.js#L43-L71
19,102
lirown/graphql-custom-directives
src/custom.js
resolveMiddlewareWrapper
function resolveMiddlewareWrapper(resolve = defaultResolveFn, directives = {}) { const serverDirectives = parseSchemaDirectives(directives); return (source, args, context, info) => { const directives = serverDirectives.concat( (info.fieldASTs || info.fieldNodes)[0].directives, ); const directive = directives.filter( d => DEFAULT_DIRECTIVES.indexOf(d.name.value) === -1, )[0]; if (!directive) { return resolve(source, args, context, info); } let defer = resolveWithDirective( () => Promise.resolve(resolve(source, args, context, info)), source, directive, context, info, ); defer.catch(e => resolveWithDirective( /* istanbul ignore next */ () => Promise.reject(e), source, directive, context, info, ), ); if (directives.length <= 1) { return defer; } for (let directiveNext of directives.slice(1)) { defer = defer.then(result => resolveWithDirective( () => Promise.resolve(result), source, directiveNext, context, info, ), ); defer.catch(e => resolveWithDirective( () => Promise.reject(e), source, directiveNext, context, info, ), ); } return defer; }; }
javascript
function resolveMiddlewareWrapper(resolve = defaultResolveFn, directives = {}) { const serverDirectives = parseSchemaDirectives(directives); return (source, args, context, info) => { const directives = serverDirectives.concat( (info.fieldASTs || info.fieldNodes)[0].directives, ); const directive = directives.filter( d => DEFAULT_DIRECTIVES.indexOf(d.name.value) === -1, )[0]; if (!directive) { return resolve(source, args, context, info); } let defer = resolveWithDirective( () => Promise.resolve(resolve(source, args, context, info)), source, directive, context, info, ); defer.catch(e => resolveWithDirective( /* istanbul ignore next */ () => Promise.reject(e), source, directive, context, info, ), ); if (directives.length <= 1) { return defer; } for (let directiveNext of directives.slice(1)) { defer = defer.then(result => resolveWithDirective( () => Promise.resolve(result), source, directiveNext, context, info, ), ); defer.catch(e => resolveWithDirective( () => Promise.reject(e), source, directiveNext, context, info, ), ); } return defer; }; }
[ "function", "resolveMiddlewareWrapper", "(", "resolve", "=", "defaultResolveFn", ",", "directives", "=", "{", "}", ")", "{", "const", "serverDirectives", "=", "parseSchemaDirectives", "(", "directives", ")", ";", "return", "(", "source", ",", "args", ",", "context", ",", "info", ")", "=>", "{", "const", "directives", "=", "serverDirectives", ".", "concat", "(", "(", "info", ".", "fieldASTs", "||", "info", ".", "fieldNodes", ")", "[", "0", "]", ".", "directives", ",", ")", ";", "const", "directive", "=", "directives", ".", "filter", "(", "d", "=>", "DEFAULT_DIRECTIVES", ".", "indexOf", "(", "d", ".", "name", ".", "value", ")", "===", "-", "1", ",", ")", "[", "0", "]", ";", "if", "(", "!", "directive", ")", "{", "return", "resolve", "(", "source", ",", "args", ",", "context", ",", "info", ")", ";", "}", "let", "defer", "=", "resolveWithDirective", "(", "(", ")", "=>", "Promise", ".", "resolve", "(", "resolve", "(", "source", ",", "args", ",", "context", ",", "info", ")", ")", ",", "source", ",", "directive", ",", "context", ",", "info", ",", ")", ";", "defer", ".", "catch", "(", "e", "=>", "resolveWithDirective", "(", "/* istanbul ignore next */", "(", ")", "=>", "Promise", ".", "reject", "(", "e", ")", ",", "source", ",", "directive", ",", "context", ",", "info", ",", ")", ",", ")", ";", "if", "(", "directives", ".", "length", "<=", "1", ")", "{", "return", "defer", ";", "}", "for", "(", "let", "directiveNext", "of", "directives", ".", "slice", "(", "1", ")", ")", "{", "defer", "=", "defer", ".", "then", "(", "result", "=>", "resolveWithDirective", "(", "(", ")", "=>", "Promise", ".", "resolve", "(", "result", ")", ",", "source", ",", "directiveNext", ",", "context", ",", "info", ",", ")", ",", ")", ";", "defer", ".", "catch", "(", "e", "=>", "resolveWithDirective", "(", "(", ")", "=>", "Promise", ".", "reject", "(", "e", ")", ",", "source", ",", "directiveNext", ",", "context", ",", "info", ",", ")", ",", ")", ";", "}", "return", "defer", ";", "}", ";", "}" ]
If the directive is defined on a field it will execute the custom directive resolve right after executing the resolve of the field otherwise it will execute the original resolve of the field
[ "If", "the", "directive", "is", "defined", "on", "a", "field", "it", "will", "execute", "the", "custom", "directive", "resolve", "right", "after", "executing", "the", "resolve", "of", "the", "field", "otherwise", "it", "will", "execute", "the", "original", "resolve", "of", "the", "field" ]
a0709eaa07f264e3431ce91188e4ac30978644d6
https://github.com/lirown/graphql-custom-directives/blob/a0709eaa07f264e3431ce91188e4ac30978644d6/src/custom.js#L78-L138
19,103
heavysixer/d4
d4.js
function(obj) { var accessors = obj.accessors; if (accessors) { createAccessorsFromArray(obj, obj.accessors, d3.keys(accessors)); } }
javascript
function(obj) { var accessors = obj.accessors; if (accessors) { createAccessorsFromArray(obj, obj.accessors, d3.keys(accessors)); } }
[ "function", "(", "obj", ")", "{", "var", "accessors", "=", "obj", ".", "accessors", ";", "if", "(", "accessors", ")", "{", "createAccessorsFromArray", "(", "obj", ",", "obj", ".", "accessors", ",", "d3", ".", "keys", "(", "accessors", ")", ")", ";", "}", "}" ]
In order to have a uniform API, objects with accessors, need to have wrapper functions created for them so that users may access them in the declarative nature we promote. This function will take an object, which contains an accessors key and create the wrapper function for each accessor item. This function is used internally by the feature mixin and axes objects.
[ "In", "order", "to", "have", "a", "uniform", "API", "objects", "with", "accessors", "need", "to", "have", "wrapper", "functions", "created", "for", "them", "so", "that", "users", "may", "access", "them", "in", "the", "declarative", "nature", "we", "promote", ".", "This", "function", "will", "take", "an", "object", "which", "contains", "an", "accessors", "key", "and", "create", "the", "wrapper", "function", "for", "each", "accessor", "item", ".", "This", "function", "is", "used", "internally", "by", "the", "feature", "mixin", "and", "axes", "objects", "." ]
04b8a71c8ddf99277ce6b07a5e0b3e81bfd1a899
https://github.com/heavysixer/d4/blob/04b8a71c8ddf99277ce6b07a5e0b3e81bfd1a899/d4.js#L155-L160
19,104
heavysixer/d4
d4.js
function(opts, data) { var parsed = d4.parsers.nestedGroup() .x(opts.x.$key) .y(opts.y.$key) .nestKey(opts.x.$key) .value(opts.valueKey)(data); return parsed.data; }
javascript
function(opts, data) { var parsed = d4.parsers.nestedGroup() .x(opts.x.$key) .y(opts.y.$key) .nestKey(opts.x.$key) .value(opts.valueKey)(data); return parsed.data; }
[ "function", "(", "opts", ",", "data", ")", "{", "var", "parsed", "=", "d4", ".", "parsers", ".", "nestedGroup", "(", ")", ".", "x", "(", "opts", ".", "x", ".", "$key", ")", ".", "y", "(", "opts", ".", "y", ".", "$key", ")", ".", "nestKey", "(", "opts", ".", "x", ".", "$key", ")", ".", "value", "(", "opts", ".", "valueKey", ")", "(", "data", ")", ";", "return", "parsed", ".", "data", ";", "}" ]
Normally d4 series elements inside the data array to be in a specific format, which is designed to support charts which require multiple data series. However, some charts can easily be used to display only a single data series in which case the default structure is overly verbose. In these cases d4 accepts the simplified objects in the array payload and silently parses them using the d4.nestedGroup parser. It will configure the parser's dimensions based on the configuration applied to the chart object itself.
[ "Normally", "d4", "series", "elements", "inside", "the", "data", "array", "to", "be", "in", "a", "specific", "format", "which", "is", "designed", "to", "support", "charts", "which", "require", "multiple", "data", "series", ".", "However", "some", "charts", "can", "easily", "be", "used", "to", "display", "only", "a", "single", "data", "series", "in", "which", "case", "the", "default", "structure", "is", "overly", "verbose", ".", "In", "these", "cases", "d4", "accepts", "the", "simplified", "objects", "in", "the", "array", "payload", "and", "silently", "parses", "them", "using", "the", "d4", ".", "nestedGroup", "parser", ".", "It", "will", "configure", "the", "parser", "s", "dimensions", "based", "on", "the", "configuration", "applied", "to", "the", "chart", "object", "itself", "." ]
04b8a71c8ddf99277ce6b07a5e0b3e81bfd1a899
https://github.com/heavysixer/d4/blob/04b8a71c8ddf99277ce6b07a5e0b3e81bfd1a899/d4.js#L396-L403
19,105
heavysixer/d4
d4.js
function(selector) { var soFar = selector, whitespace = '[\\x20\\t\\r\\n\\f]', characterEncoding = '(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+', identifier = characterEncoding.replace('w', 'w#'), attributes = '\\[' + whitespace + '*(' + characterEncoding + ')' + whitespace + '*(?:([*^$|!~]?=)' + whitespace + '*(?:([\'"])((?:\\\\.|[^\\\\])*?)\\3|(' + identifier + ')|)|)' + whitespace + '*\\]', order = ['TAG', 'ID', 'CLASS'], matchers = { 'ID': new RegExp('#(' + characterEncoding + ')'), 'CLASS': new RegExp('\\.(' + characterEncoding + ')'), 'TAG': new RegExp('^(' + characterEncoding.replace('w', 'w*') + ')'), 'ATTR': new RegExp('' + attributes) }, parse = function(exp) { matched = false; tokens[exp] = []; match = true; while (match) { match = matchers[exp].exec(soFar); if (match !== null) { matched = match.shift(); tokens[exp].push(match[0]); soFar = soFar.slice(matched.length); } } }, matched, match, tokens = {}; d4.each(order, parse); d4.each(order, function(exp) { while (soFar) { tokens[exp] = tokens[exp].join(' '); if (!matched) { break; } } }); return tokens; }
javascript
function(selector) { var soFar = selector, whitespace = '[\\x20\\t\\r\\n\\f]', characterEncoding = '(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+', identifier = characterEncoding.replace('w', 'w#'), attributes = '\\[' + whitespace + '*(' + characterEncoding + ')' + whitespace + '*(?:([*^$|!~]?=)' + whitespace + '*(?:([\'"])((?:\\\\.|[^\\\\])*?)\\3|(' + identifier + ')|)|)' + whitespace + '*\\]', order = ['TAG', 'ID', 'CLASS'], matchers = { 'ID': new RegExp('#(' + characterEncoding + ')'), 'CLASS': new RegExp('\\.(' + characterEncoding + ')'), 'TAG': new RegExp('^(' + characterEncoding.replace('w', 'w*') + ')'), 'ATTR': new RegExp('' + attributes) }, parse = function(exp) { matched = false; tokens[exp] = []; match = true; while (match) { match = matchers[exp].exec(soFar); if (match !== null) { matched = match.shift(); tokens[exp].push(match[0]); soFar = soFar.slice(matched.length); } } }, matched, match, tokens = {}; d4.each(order, parse); d4.each(order, function(exp) { while (soFar) { tokens[exp] = tokens[exp].join(' '); if (!matched) { break; } } }); return tokens; }
[ "function", "(", "selector", ")", "{", "var", "soFar", "=", "selector", ",", "whitespace", "=", "'[\\\\x20\\\\t\\\\r\\\\n\\\\f]'", ",", "characterEncoding", "=", "'(?:\\\\\\\\.|[\\\\w-]|[^\\\\x00-\\\\xa0])+'", ",", "identifier", "=", "characterEncoding", ".", "replace", "(", "'w'", ",", "'w#'", ")", ",", "attributes", "=", "'\\\\['", "+", "whitespace", "+", "'*('", "+", "characterEncoding", "+", "')'", "+", "whitespace", "+", "'*(?:([*^$|!~]?=)'", "+", "whitespace", "+", "'*(?:([\\'\"])((?:\\\\\\\\.|[^\\\\\\\\])*?)\\\\3|('", "+", "identifier", "+", "')|)|)'", "+", "whitespace", "+", "'*\\\\]'", ",", "order", "=", "[", "'TAG'", ",", "'ID'", ",", "'CLASS'", "]", ",", "matchers", "=", "{", "'ID'", ":", "new", "RegExp", "(", "'#('", "+", "characterEncoding", "+", "')'", ")", ",", "'CLASS'", ":", "new", "RegExp", "(", "'\\\\.('", "+", "characterEncoding", "+", "')'", ")", ",", "'TAG'", ":", "new", "RegExp", "(", "'^('", "+", "characterEncoding", ".", "replace", "(", "'w'", ",", "'w*'", ")", "+", "')'", ")", ",", "'ATTR'", ":", "new", "RegExp", "(", "''", "+", "attributes", ")", "}", ",", "parse", "=", "function", "(", "exp", ")", "{", "matched", "=", "false", ";", "tokens", "[", "exp", "]", "=", "[", "]", ";", "match", "=", "true", ";", "while", "(", "match", ")", "{", "match", "=", "matchers", "[", "exp", "]", ".", "exec", "(", "soFar", ")", ";", "if", "(", "match", "!==", "null", ")", "{", "matched", "=", "match", ".", "shift", "(", ")", ";", "tokens", "[", "exp", "]", ".", "push", "(", "match", "[", "0", "]", ")", ";", "soFar", "=", "soFar", ".", "slice", "(", "matched", ".", "length", ")", ";", "}", "}", "}", ",", "matched", ",", "match", ",", "tokens", "=", "{", "}", ";", "d4", ".", "each", "(", "order", ",", "parse", ")", ";", "d4", ".", "each", "(", "order", ",", "function", "(", "exp", ")", "{", "while", "(", "soFar", ")", "{", "tokens", "[", "exp", "]", "=", "tokens", "[", "exp", "]", ".", "join", "(", "' '", ")", ";", "if", "(", "!", "matched", ")", "{", "break", ";", "}", "}", "}", ")", ";", "return", "tokens", ";", "}" ]
This approach was inspired by SizzleJS. Most of the REGEX is based off their own expressions.
[ "This", "approach", "was", "inspired", "by", "SizzleJS", ".", "Most", "of", "the", "REGEX", "is", "based", "off", "their", "own", "expressions", "." ]
04b8a71c8ddf99277ce6b07a5e0b3e81bfd1a899
https://github.com/heavysixer/d4/blob/04b8a71c8ddf99277ce6b07a5e0b3e81bfd1a899/d4.js#L539-L579
19,106
heavysixer/d4
d4.js
function(key, items) { var offsets = {}; var stack = d3.layout.stack() .values(function(d) { return d.values; }) .x(function(d) { return d[key]; }) .y(function(d) { return +d[opts.value.key]; }) .out(function(d, y0, y) { d.y = y; if (d.y >= 0) { d.y0 = offsets[d[key] + 'Pos'] = offsets[d[key] + 'Pos'] || 0; offsets[d[key] + 'Pos'] += y; } else { d.y0 = offsets[d[key] + 'Neg'] = offsets[d[key] + 'Neg'] || 0; offsets[d[key] + 'Neg'] -= Math.abs(y); } }); stack(items.reverse()); }
javascript
function(key, items) { var offsets = {}; var stack = d3.layout.stack() .values(function(d) { return d.values; }) .x(function(d) { return d[key]; }) .y(function(d) { return +d[opts.value.key]; }) .out(function(d, y0, y) { d.y = y; if (d.y >= 0) { d.y0 = offsets[d[key] + 'Pos'] = offsets[d[key] + 'Pos'] || 0; offsets[d[key] + 'Pos'] += y; } else { d.y0 = offsets[d[key] + 'Neg'] = offsets[d[key] + 'Neg'] || 0; offsets[d[key] + 'Neg'] -= Math.abs(y); } }); stack(items.reverse()); }
[ "function", "(", "key", ",", "items", ")", "{", "var", "offsets", "=", "{", "}", ";", "var", "stack", "=", "d3", ".", "layout", ".", "stack", "(", ")", ".", "values", "(", "function", "(", "d", ")", "{", "return", "d", ".", "values", ";", "}", ")", ".", "x", "(", "function", "(", "d", ")", "{", "return", "d", "[", "key", "]", ";", "}", ")", ".", "y", "(", "function", "(", "d", ")", "{", "return", "+", "d", "[", "opts", ".", "value", ".", "key", "]", ";", "}", ")", ".", "out", "(", "function", "(", "d", ",", "y0", ",", "y", ")", "{", "d", ".", "y", "=", "y", ";", "if", "(", "d", ".", "y", ">=", "0", ")", "{", "d", ".", "y0", "=", "offsets", "[", "d", "[", "key", "]", "+", "'Pos'", "]", "=", "offsets", "[", "d", "[", "key", "]", "+", "'Pos'", "]", "||", "0", ";", "offsets", "[", "d", "[", "key", "]", "+", "'Pos'", "]", "+=", "y", ";", "}", "else", "{", "d", ".", "y0", "=", "offsets", "[", "d", "[", "key", "]", "+", "'Neg'", "]", "=", "offsets", "[", "d", "[", "key", "]", "+", "'Neg'", "]", "||", "0", ";", "offsets", "[", "d", "[", "key", "]", "+", "'Neg'", "]", "-=", "Math", ".", "abs", "(", "y", ")", ";", "}", "}", ")", ";", "stack", "(", "items", ".", "reverse", "(", ")", ")", ";", "}" ]
By default D3 doesn't handle stacks with negative values very well, we need to calulate or our y and y0 values for each group.
[ "By", "default", "D3", "doesn", "t", "handle", "stacks", "with", "negative", "values", "very", "well", "we", "need", "to", "calulate", "or", "our", "y", "and", "y0", "values", "for", "each", "group", "." ]
04b8a71c8ddf99277ce6b07a5e0b3e81bfd1a899
https://github.com/heavysixer/d4/blob/04b8a71c8ddf99277ce6b07a5e0b3e81bfd1a899/d4.js#L4778-L4802
19,107
aurelia/ux
packages/core/dist/commonjs/index.js
function () { var radius = Math.min(Math.sqrt(Math.pow(this.containerRect.width, 2) + Math.pow(this.containerRect.height, 2)), PaperWave.MAX_RADIUS) * 1.1 + 5; var elapsed = 1.1 - 0.2 * (radius / PaperWave.MAX_RADIUS); var currentTime = this.mouseInteractionSeconds / elapsed; var actualRadius = radius * (1 - Math.pow(80, -currentTime)); return Math.abs(actualRadius); }
javascript
function () { var radius = Math.min(Math.sqrt(Math.pow(this.containerRect.width, 2) + Math.pow(this.containerRect.height, 2)), PaperWave.MAX_RADIUS) * 1.1 + 5; var elapsed = 1.1 - 0.2 * (radius / PaperWave.MAX_RADIUS); var currentTime = this.mouseInteractionSeconds / elapsed; var actualRadius = radius * (1 - Math.pow(80, -currentTime)); return Math.abs(actualRadius); }
[ "function", "(", ")", "{", "var", "radius", "=", "Math", ".", "min", "(", "Math", ".", "sqrt", "(", "Math", ".", "pow", "(", "this", ".", "containerRect", ".", "width", ",", "2", ")", "+", "Math", ".", "pow", "(", "this", ".", "containerRect", ".", "height", ",", "2", ")", ")", ",", "PaperWave", ".", "MAX_RADIUS", ")", "*", "1.1", "+", "5", ";", "var", "elapsed", "=", "1.1", "-", "0.2", "*", "(", "radius", "/", "PaperWave", ".", "MAX_RADIUS", ")", ";", "var", "currentTime", "=", "this", ".", "mouseInteractionSeconds", "/", "elapsed", ";", "var", "actualRadius", "=", "radius", "*", "(", "1", "-", "Math", ".", "pow", "(", "80", ",", "-", "currentTime", ")", ")", ";", "return", "Math", ".", "abs", "(", "actualRadius", ")", ";", "}" ]
Gets the wave's radius at the current time. @returns {Number} The value of the wave's radius.
[ "Gets", "the", "wave", "s", "radius", "at", "the", "current", "time", "." ]
732935b9f26f0200753955fe87b52c93feaf4bdc
https://github.com/aurelia/ux/blob/732935b9f26f0200753955fe87b52c93feaf4bdc/packages/core/dist/commonjs/index.js#L998-L1004
19,108
aurelia/ux
packages/core/dist/commonjs/index.js
function () { var translateFraction = this.translationFraction; var x = this.startPosition.x; var y = this.startPosition.y; if (this.endPosition.x) { x = this.startPosition.x + translateFraction * (this.endPosition.x - this.startPosition.x); } if (this.endPosition.y) { y = this.startPosition.y + translateFraction * (this.endPosition.y - this.startPosition.y); } return { x: x, y: y }; }
javascript
function () { var translateFraction = this.translationFraction; var x = this.startPosition.x; var y = this.startPosition.y; if (this.endPosition.x) { x = this.startPosition.x + translateFraction * (this.endPosition.x - this.startPosition.x); } if (this.endPosition.y) { y = this.startPosition.y + translateFraction * (this.endPosition.y - this.startPosition.y); } return { x: x, y: y }; }
[ "function", "(", ")", "{", "var", "translateFraction", "=", "this", ".", "translationFraction", ";", "var", "x", "=", "this", ".", "startPosition", ".", "x", ";", "var", "y", "=", "this", ".", "startPosition", ".", "y", ";", "if", "(", "this", ".", "endPosition", ".", "x", ")", "{", "x", "=", "this", ".", "startPosition", ".", "x", "+", "translateFraction", "*", "(", "this", ".", "endPosition", ".", "x", "-", "this", ".", "startPosition", ".", "x", ")", ";", "}", "if", "(", "this", ".", "endPosition", ".", "y", ")", "{", "y", "=", "this", ".", "startPosition", ".", "y", "+", "translateFraction", "*", "(", "this", ".", "endPosition", ".", "y", "-", "this", ".", "startPosition", ".", "y", ")", ";", "}", "return", "{", "x", ":", "x", ",", "y", ":", "y", "}", ";", "}" ]
Gets the wave's current position. @returns {{x: Number, y: Number}} Object containing coordinates of the wave's current position.
[ "Gets", "the", "wave", "s", "current", "position", "." ]
732935b9f26f0200753955fe87b52c93feaf4bdc
https://github.com/aurelia/ux/blob/732935b9f26f0200753955fe87b52c93feaf4bdc/packages/core/dist/commonjs/index.js#L1082-L1093
19,109
optimizely/chord
chord.js
in_half_open_range
function in_half_open_range(key, low, high) { //return (low < high && key > low && key <= high) || // (low > high && (key > low || key <= high)) || // (low == high); return (less_than(low, high) && less_than(low, key) && less_than_or_equal(key, high)) || (less_than(high, low) && (less_than(low, key) || less_than_or_equal(key, high))) || (equal_to(low, high)); }
javascript
function in_half_open_range(key, low, high) { //return (low < high && key > low && key <= high) || // (low > high && (key > low || key <= high)) || // (low == high); return (less_than(low, high) && less_than(low, key) && less_than_or_equal(key, high)) || (less_than(high, low) && (less_than(low, key) || less_than_or_equal(key, high))) || (equal_to(low, high)); }
[ "function", "in_half_open_range", "(", "key", ",", "low", ",", "high", ")", "{", "//return (low < high && key > low && key <= high) ||", "// (low > high && (key > low || key <= high)) ||", "// (low == high);", "return", "(", "less_than", "(", "low", ",", "high", ")", "&&", "less_than", "(", "low", ",", "key", ")", "&&", "less_than_or_equal", "(", "key", ",", "high", ")", ")", "||", "(", "less_than", "(", "high", ",", "low", ")", "&&", "(", "less_than", "(", "low", ",", "key", ")", "||", "less_than_or_equal", "(", "key", ",", "high", ")", ")", ")", "||", "(", "equal_to", "(", "low", ",", "high", ")", ")", ";", "}" ]
Is key in (low, high]
[ "Is", "key", "in", "(", "low", "high", "]" ]
059a9402273412b73cdc8e37923a07ee9a168f3c
https://github.com/optimizely/chord/blob/059a9402273412b73cdc8e37923a07ee9a168f3c/chord.js#L27-L34
19,110
optimizely/chord
chord.js
add_exp
function add_exp(key, exponent) { var result = key.concat(); // copy array var index = key.length - Math.floor(exponent / 32) - 1; result[index] += 1 << (exponent % 32); var carry = 0; while (index >= 0) { result[index] += carry; carry = 0; if (result[index] > 0xffffffff) { result[index] -= 0x100000000; carry = 1; } --index; } return result; }
javascript
function add_exp(key, exponent) { var result = key.concat(); // copy array var index = key.length - Math.floor(exponent / 32) - 1; result[index] += 1 << (exponent % 32); var carry = 0; while (index >= 0) { result[index] += carry; carry = 0; if (result[index] > 0xffffffff) { result[index] -= 0x100000000; carry = 1; } --index; } return result; }
[ "function", "add_exp", "(", "key", ",", "exponent", ")", "{", "var", "result", "=", "key", ".", "concat", "(", ")", ";", "// copy array", "var", "index", "=", "key", ".", "length", "-", "Math", ".", "floor", "(", "exponent", "/", "32", ")", "-", "1", ";", "result", "[", "index", "]", "+=", "1", "<<", "(", "exponent", "%", "32", ")", ";", "var", "carry", "=", "0", ";", "while", "(", "index", ">=", "0", ")", "{", "result", "[", "index", "]", "+=", "carry", ";", "carry", "=", "0", ";", "if", "(", "result", "[", "index", "]", ">", "0xffffffff", ")", "{", "result", "[", "index", "]", "-=", "0x100000000", ";", "carry", "=", "1", ";", "}", "--", "index", ";", "}", "return", "result", ";", "}" ]
Computes a new key equal to key + 2 ^ exponent. Assumes key is a 4 element array of 32 bit words, most significant word first.
[ "Computes", "a", "new", "key", "equal", "to", "key", "+", "2", "^", "exponent", ".", "Assumes", "key", "is", "a", "4", "element", "array", "of", "32", "bit", "words", "most", "significant", "word", "first", "." ]
059a9402273412b73cdc8e37923a07ee9a168f3c
https://github.com/optimizely/chord/blob/059a9402273412b73cdc8e37923a07ee9a168f3c/chord.js#L91-L109
19,111
optimizely/chord
chord.js
chord_send_message
function chord_send_message(to, id, message, reply_to) { return last_node_send(to ? to : last_node, {type: MESSAGE, id: id, message: message}, reply_to); }
javascript
function chord_send_message(to, id, message, reply_to) { return last_node_send(to ? to : last_node, {type: MESSAGE, id: id, message: message}, reply_to); }
[ "function", "chord_send_message", "(", "to", ",", "id", ",", "message", ",", "reply_to", ")", "{", "return", "last_node_send", "(", "to", "?", "to", ":", "last_node", ",", "{", "type", ":", "MESSAGE", ",", "id", ":", "id", ",", "message", ":", "message", "}", ",", "reply_to", ")", ";", "}" ]
Returns a function for sending application messages over the Chord router.
[ "Returns", "a", "function", "for", "sending", "application", "messages", "over", "the", "Chord", "router", "." ]
059a9402273412b73cdc8e37923a07ee9a168f3c
https://github.com/optimizely/chord/blob/059a9402273412b73cdc8e37923a07ee9a168f3c/chord.js#L362-L364
19,112
jonschlinkert/data-store
index.js
mkdir
function mkdir(dirname, options = {}) { if (fs.existsSync(dirname)) return; assert.equal(typeof dirname, 'string', 'expected dirname to be a string'); let opts = Object.assign({ cwd: process.cwd(), fs }, options); let mode = opts.mode || 0o777 & ~process.umask(); let segs = path.relative(opts.cwd, dirname).split(path.sep); let make = dir => !exists(dir, opts) && fs.mkdirSync(dir, mode); for (let i = 0; i <= segs.length; i++) { try { make((dirname = path.join(opts.cwd, ...segs.slice(0, i)))); } catch (err) { handleError(dirname, opts)(err); } } return dirname; }
javascript
function mkdir(dirname, options = {}) { if (fs.existsSync(dirname)) return; assert.equal(typeof dirname, 'string', 'expected dirname to be a string'); let opts = Object.assign({ cwd: process.cwd(), fs }, options); let mode = opts.mode || 0o777 & ~process.umask(); let segs = path.relative(opts.cwd, dirname).split(path.sep); let make = dir => !exists(dir, opts) && fs.mkdirSync(dir, mode); for (let i = 0; i <= segs.length; i++) { try { make((dirname = path.join(opts.cwd, ...segs.slice(0, i)))); } catch (err) { handleError(dirname, opts)(err); } } return dirname; }
[ "function", "mkdir", "(", "dirname", ",", "options", "=", "{", "}", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "dirname", ")", ")", "return", ";", "assert", ".", "equal", "(", "typeof", "dirname", ",", "'string'", ",", "'expected dirname to be a string'", ")", ";", "let", "opts", "=", "Object", ".", "assign", "(", "{", "cwd", ":", "process", ".", "cwd", "(", ")", ",", "fs", "}", ",", "options", ")", ";", "let", "mode", "=", "opts", ".", "mode", "||", "0o777", "&", "~", "process", ".", "umask", "(", ")", ";", "let", "segs", "=", "path", ".", "relative", "(", "opts", ".", "cwd", ",", "dirname", ")", ".", "split", "(", "path", ".", "sep", ")", ";", "let", "make", "=", "dir", "=>", "!", "exists", "(", "dir", ",", "opts", ")", "&&", "fs", ".", "mkdirSync", "(", "dir", ",", "mode", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<=", "segs", ".", "length", ";", "i", "++", ")", "{", "try", "{", "make", "(", "(", "dirname", "=", "path", ".", "join", "(", "opts", ".", "cwd", ",", "...", "segs", ".", "slice", "(", "0", ",", "i", ")", ")", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "handleError", "(", "dirname", ",", "opts", ")", "(", "err", ")", ";", "}", "}", "return", "dirname", ";", "}" ]
Create a directory and any intermediate directories that might exist.
[ "Create", "a", "directory", "and", "any", "intermediate", "directories", "that", "might", "exist", "." ]
de38f1721ba21e63ec6d36aab60f13bfde2dacb4
https://github.com/jonschlinkert/data-store/blob/de38f1721ba21e63ec6d36aab60f13bfde2dacb4/index.js#L371-L386
19,113
jonschlinkert/data-store
index.js
cloneDeep
function cloneDeep(value) { let obj = {}; switch (typeOf(value)) { case 'object': for (let key of Object.keys(value)) { obj[key] = cloneDeep(value[key]); } return obj; case 'array': return value.map(ele => cloneDeep(ele)); default: { return value; } } }
javascript
function cloneDeep(value) { let obj = {}; switch (typeOf(value)) { case 'object': for (let key of Object.keys(value)) { obj[key] = cloneDeep(value[key]); } return obj; case 'array': return value.map(ele => cloneDeep(ele)); default: { return value; } } }
[ "function", "cloneDeep", "(", "value", ")", "{", "let", "obj", "=", "{", "}", ";", "switch", "(", "typeOf", "(", "value", ")", ")", "{", "case", "'object'", ":", "for", "(", "let", "key", "of", "Object", ".", "keys", "(", "value", ")", ")", "{", "obj", "[", "key", "]", "=", "cloneDeep", "(", "value", "[", "key", "]", ")", ";", "}", "return", "obj", ";", "case", "'array'", ":", "return", "value", ".", "map", "(", "ele", "=>", "cloneDeep", "(", "ele", ")", ")", ";", "default", ":", "{", "return", "value", ";", "}", "}", "}" ]
Deeply clone plain objects and arrays. We're only concerned with cloning values that are valid in JSON.
[ "Deeply", "clone", "plain", "objects", "and", "arrays", ".", "We", "re", "only", "concerned", "with", "cloning", "values", "that", "are", "valid", "in", "JSON", "." ]
de38f1721ba21e63ec6d36aab60f13bfde2dacb4
https://github.com/jonschlinkert/data-store/blob/de38f1721ba21e63ec6d36aab60f13bfde2dacb4/index.js#L466-L480
19,114
angular-ui/ui-mask
src/mask.js
getMaskComponents
function getMaskComponents() { var maskPlaceholderChars = maskPlaceholder.split(''), maskPlaceholderCopy, components; //maskCaretMap can have bad values if the input has the ui-mask attribute implemented as an obversable property, e.g. the demo page if (maskCaretMap && !isNaN(maskCaretMap[0])) { //Instead of trying to manipulate the RegEx based on the placeholder characters //we can simply replace the placeholder characters based on the already built //maskCaretMap to underscores and leave the original working RegEx to get the proper //mask components angular.forEach(maskCaretMap, function(value) { maskPlaceholderChars[value] = '_'; }); } maskPlaceholderCopy = maskPlaceholderChars.join(''); components = maskPlaceholderCopy.replace(/[_]+/g, '_').split('_'); components = components.filter(function(s) { return s !== ''; }); // need a string search offset in cases where the mask contains multiple identical components // E.g., a mask of 99.99.99-999.99 var offset = 0; return components.map(function(c) { var componentPosition = maskPlaceholderCopy.indexOf(c, offset); offset = componentPosition + 1; return { value: c, position: componentPosition }; }); }
javascript
function getMaskComponents() { var maskPlaceholderChars = maskPlaceholder.split(''), maskPlaceholderCopy, components; //maskCaretMap can have bad values if the input has the ui-mask attribute implemented as an obversable property, e.g. the demo page if (maskCaretMap && !isNaN(maskCaretMap[0])) { //Instead of trying to manipulate the RegEx based on the placeholder characters //we can simply replace the placeholder characters based on the already built //maskCaretMap to underscores and leave the original working RegEx to get the proper //mask components angular.forEach(maskCaretMap, function(value) { maskPlaceholderChars[value] = '_'; }); } maskPlaceholderCopy = maskPlaceholderChars.join(''); components = maskPlaceholderCopy.replace(/[_]+/g, '_').split('_'); components = components.filter(function(s) { return s !== ''; }); // need a string search offset in cases where the mask contains multiple identical components // E.g., a mask of 99.99.99-999.99 var offset = 0; return components.map(function(c) { var componentPosition = maskPlaceholderCopy.indexOf(c, offset); offset = componentPosition + 1; return { value: c, position: componentPosition }; }); }
[ "function", "getMaskComponents", "(", ")", "{", "var", "maskPlaceholderChars", "=", "maskPlaceholder", ".", "split", "(", "''", ")", ",", "maskPlaceholderCopy", ",", "components", ";", "//maskCaretMap can have bad values if the input has the ui-mask attribute implemented as an obversable property, e.g. the demo page", "if", "(", "maskCaretMap", "&&", "!", "isNaN", "(", "maskCaretMap", "[", "0", "]", ")", ")", "{", "//Instead of trying to manipulate the RegEx based on the placeholder characters", "//we can simply replace the placeholder characters based on the already built", "//maskCaretMap to underscores and leave the original working RegEx to get the proper", "//mask components", "angular", ".", "forEach", "(", "maskCaretMap", ",", "function", "(", "value", ")", "{", "maskPlaceholderChars", "[", "value", "]", "=", "'_'", ";", "}", ")", ";", "}", "maskPlaceholderCopy", "=", "maskPlaceholderChars", ".", "join", "(", "''", ")", ";", "components", "=", "maskPlaceholderCopy", ".", "replace", "(", "/", "[_]+", "/", "g", ",", "'_'", ")", ".", "split", "(", "'_'", ")", ";", "components", "=", "components", ".", "filter", "(", "function", "(", "s", ")", "{", "return", "s", "!==", "''", ";", "}", ")", ";", "// need a string search offset in cases where the mask contains multiple identical components", "// E.g., a mask of 99.99.99-999.99", "var", "offset", "=", "0", ";", "return", "components", ".", "map", "(", "function", "(", "c", ")", "{", "var", "componentPosition", "=", "maskPlaceholderCopy", ".", "indexOf", "(", "c", ",", "offset", ")", ";", "offset", "=", "componentPosition", "+", "1", ";", "return", "{", "value", ":", "c", ",", "position", ":", "componentPosition", "}", ";", "}", ")", ";", "}" ]
Generate array of mask components that will be stripped from a masked value before processing to prevent mask components from being added to the unmasked value. E.g., a mask pattern of '+7 9999' won't have the 7 bleed into the unmasked value.
[ "Generate", "array", "of", "mask", "components", "that", "will", "be", "stripped", "from", "a", "masked", "value", "before", "processing", "to", "prevent", "mask", "components", "from", "being", "added", "to", "the", "unmasked", "value", ".", "E", ".", "g", ".", "a", "mask", "pattern", "of", "+", "7", "9999", "won", "t", "have", "the", "7", "bleed", "into", "the", "unmasked", "value", "." ]
8a79a15f24838e8463ee795c11bd7d74f2e21c13
https://github.com/angular-ui/ui-mask/blob/8a79a15f24838e8463ee795c11bd7d74f2e21c13/src/mask.js#L352-L383
19,115
datavis-tech/graph-data-structure
index.js
removeNode
function removeNode(node){ // Remove incoming edges. Object.keys(edges).forEach(function (u){ edges[u].forEach(function (v){ if(v === node){ removeEdge(u, v); } }); }); // Remove outgoing edges (and signal that the node no longer exists). delete edges[node]; return graph; }
javascript
function removeNode(node){ // Remove incoming edges. Object.keys(edges).forEach(function (u){ edges[u].forEach(function (v){ if(v === node){ removeEdge(u, v); } }); }); // Remove outgoing edges (and signal that the node no longer exists). delete edges[node]; return graph; }
[ "function", "removeNode", "(", "node", ")", "{", "// Remove incoming edges.", "Object", ".", "keys", "(", "edges", ")", ".", "forEach", "(", "function", "(", "u", ")", "{", "edges", "[", "u", "]", ".", "forEach", "(", "function", "(", "v", ")", "{", "if", "(", "v", "===", "node", ")", "{", "removeEdge", "(", "u", ",", "v", ")", ";", "}", "}", ")", ";", "}", ")", ";", "// Remove outgoing edges (and signal that the node no longer exists).", "delete", "edges", "[", "node", "]", ";", "return", "graph", ";", "}" ]
Removes a node from the graph. Also removes incoming and outgoing edges.
[ "Removes", "a", "node", "from", "the", "graph", ".", "Also", "removes", "incoming", "and", "outgoing", "edges", "." ]
531622a4051438131703980b62f8d1c91d4ff147
https://github.com/datavis-tech/graph-data-structure/blob/531622a4051438131703980b62f8d1c91d4ff147/index.js#L48-L63
19,116
datavis-tech/graph-data-structure
index.js
nodes
function nodes(){ var nodeSet = {}; Object.keys(edges).forEach(function (u){ nodeSet[u] = true; edges[u].forEach(function (v){ nodeSet[v] = true; }); }); return Object.keys(nodeSet); }
javascript
function nodes(){ var nodeSet = {}; Object.keys(edges).forEach(function (u){ nodeSet[u] = true; edges[u].forEach(function (v){ nodeSet[v] = true; }); }); return Object.keys(nodeSet); }
[ "function", "nodes", "(", ")", "{", "var", "nodeSet", "=", "{", "}", ";", "Object", ".", "keys", "(", "edges", ")", ".", "forEach", "(", "function", "(", "u", ")", "{", "nodeSet", "[", "u", "]", "=", "true", ";", "edges", "[", "u", "]", ".", "forEach", "(", "function", "(", "v", ")", "{", "nodeSet", "[", "v", "]", "=", "true", ";", "}", ")", ";", "}", ")", ";", "return", "Object", ".", "keys", "(", "nodeSet", ")", ";", "}" ]
Gets the list of nodes that have been added to the graph.
[ "Gets", "the", "list", "of", "nodes", "that", "have", "been", "added", "to", "the", "graph", "." ]
531622a4051438131703980b62f8d1c91d4ff147
https://github.com/datavis-tech/graph-data-structure/blob/531622a4051438131703980b62f8d1c91d4ff147/index.js#L66-L75
19,117
datavis-tech/graph-data-structure
index.js
setEdgeWeight
function setEdgeWeight(u, v, weight){ edgeWeights[encodeEdge(u, v)] = weight; return graph; }
javascript
function setEdgeWeight(u, v, weight){ edgeWeights[encodeEdge(u, v)] = weight; return graph; }
[ "function", "setEdgeWeight", "(", "u", ",", "v", ",", "weight", ")", "{", "edgeWeights", "[", "encodeEdge", "(", "u", ",", "v", ")", "]", "=", "weight", ";", "return", "graph", ";", "}" ]
Sets the weight of the given edge.
[ "Sets", "the", "weight", "of", "the", "given", "edge", "." ]
531622a4051438131703980b62f8d1c91d4ff147
https://github.com/datavis-tech/graph-data-structure/blob/531622a4051438131703980b62f8d1c91d4ff147/index.js#L90-L93
19,118
datavis-tech/graph-data-structure
index.js
getEdgeWeight
function getEdgeWeight(u, v){ var weight = edgeWeights[encodeEdge(u, v)]; return weight === undefined ? 1 : weight; }
javascript
function getEdgeWeight(u, v){ var weight = edgeWeights[encodeEdge(u, v)]; return weight === undefined ? 1 : weight; }
[ "function", "getEdgeWeight", "(", "u", ",", "v", ")", "{", "var", "weight", "=", "edgeWeights", "[", "encodeEdge", "(", "u", ",", "v", ")", "]", ";", "return", "weight", "===", "undefined", "?", "1", ":", "weight", ";", "}" ]
Gets the weight of the given edge. Returns 1 if no weight was previously set.
[ "Gets", "the", "weight", "of", "the", "given", "edge", ".", "Returns", "1", "if", "no", "weight", "was", "previously", "set", "." ]
531622a4051438131703980b62f8d1c91d4ff147
https://github.com/datavis-tech/graph-data-structure/blob/531622a4051438131703980b62f8d1c91d4ff147/index.js#L97-L100
19,119
datavis-tech/graph-data-structure
index.js
addEdge
function addEdge(u, v, weight){ addNode(u); addNode(v); adjacent(u).push(v); if (weight !== undefined) { setEdgeWeight(u, v, weight); } return graph; }
javascript
function addEdge(u, v, weight){ addNode(u); addNode(v); adjacent(u).push(v); if (weight !== undefined) { setEdgeWeight(u, v, weight); } return graph; }
[ "function", "addEdge", "(", "u", ",", "v", ",", "weight", ")", "{", "addNode", "(", "u", ")", ";", "addNode", "(", "v", ")", ";", "adjacent", "(", "u", ")", ".", "push", "(", "v", ")", ";", "if", "(", "weight", "!==", "undefined", ")", "{", "setEdgeWeight", "(", "u", ",", "v", ",", "weight", ")", ";", "}", "return", "graph", ";", "}" ]
Adds an edge from node u to node v. Implicitly adds the nodes if they were not already added.
[ "Adds", "an", "edge", "from", "node", "u", "to", "node", "v", ".", "Implicitly", "adds", "the", "nodes", "if", "they", "were", "not", "already", "added", "." ]
531622a4051438131703980b62f8d1c91d4ff147
https://github.com/datavis-tech/graph-data-structure/blob/531622a4051438131703980b62f8d1c91d4ff147/index.js#L104-L114
19,120
datavis-tech/graph-data-structure
index.js
removeEdge
function removeEdge(u, v){ if(edges[u]){ edges[u] = adjacent(u).filter(function (_v){ return _v !== v; }); } return graph; }
javascript
function removeEdge(u, v){ if(edges[u]){ edges[u] = adjacent(u).filter(function (_v){ return _v !== v; }); } return graph; }
[ "function", "removeEdge", "(", "u", ",", "v", ")", "{", "if", "(", "edges", "[", "u", "]", ")", "{", "edges", "[", "u", "]", "=", "adjacent", "(", "u", ")", ".", "filter", "(", "function", "(", "_v", ")", "{", "return", "_v", "!==", "v", ";", "}", ")", ";", "}", "return", "graph", ";", "}" ]
Removes the edge from node u to node v. Does not remove the nodes. Does nothing if the edge does not exist.
[ "Removes", "the", "edge", "from", "node", "u", "to", "node", "v", ".", "Does", "not", "remove", "the", "nodes", ".", "Does", "nothing", "if", "the", "edge", "does", "not", "exist", "." ]
531622a4051438131703980b62f8d1c91d4ff147
https://github.com/datavis-tech/graph-data-structure/blob/531622a4051438131703980b62f8d1c91d4ff147/index.js#L119-L126
19,121
datavis-tech/graph-data-structure
index.js
path
function path(){ var nodeList = []; var weight = 0; var node = destination; while(p[node]){ nodeList.push(node); weight += getEdgeWeight(p[node], node); node = p[node]; } if (node !== source) { throw new Error("No path found"); } nodeList.push(node); nodeList.reverse(); nodeList.weight = weight; return nodeList; }
javascript
function path(){ var nodeList = []; var weight = 0; var node = destination; while(p[node]){ nodeList.push(node); weight += getEdgeWeight(p[node], node); node = p[node]; } if (node !== source) { throw new Error("No path found"); } nodeList.push(node); nodeList.reverse(); nodeList.weight = weight; return nodeList; }
[ "function", "path", "(", ")", "{", "var", "nodeList", "=", "[", "]", ";", "var", "weight", "=", "0", ";", "var", "node", "=", "destination", ";", "while", "(", "p", "[", "node", "]", ")", "{", "nodeList", ".", "push", "(", "node", ")", ";", "weight", "+=", "getEdgeWeight", "(", "p", "[", "node", "]", ",", "node", ")", ";", "node", "=", "p", "[", "node", "]", ";", "}", "if", "(", "node", "!==", "source", ")", "{", "throw", "new", "Error", "(", "\"No path found\"", ")", ";", "}", "nodeList", ".", "push", "(", "node", ")", ";", "nodeList", ".", "reverse", "(", ")", ";", "nodeList", ".", "weight", "=", "weight", ";", "return", "nodeList", ";", "}" ]
Assembles the shortest path by traversing the predecessor subgraph from destination to source.
[ "Assembles", "the", "shortest", "path", "by", "traversing", "the", "predecessor", "subgraph", "from", "destination", "to", "source", "." ]
531622a4051438131703980b62f8d1c91d4ff147
https://github.com/datavis-tech/graph-data-structure/blob/531622a4051438131703980b62f8d1c91d4ff147/index.js#L277-L293
19,122
datavis-tech/graph-data-structure
index.js
serialize
function serialize(){ var serialized = { nodes: nodes().map(function (id){ return { id: id }; }), links: [] }; serialized.nodes.forEach(function (node){ var source = node.id; adjacent(source).forEach(function (target){ serialized.links.push({ source: source, target: target, weight: getEdgeWeight(source, target) }); }); }); return serialized; }
javascript
function serialize(){ var serialized = { nodes: nodes().map(function (id){ return { id: id }; }), links: [] }; serialized.nodes.forEach(function (node){ var source = node.id; adjacent(source).forEach(function (target){ serialized.links.push({ source: source, target: target, weight: getEdgeWeight(source, target) }); }); }); return serialized; }
[ "function", "serialize", "(", ")", "{", "var", "serialized", "=", "{", "nodes", ":", "nodes", "(", ")", ".", "map", "(", "function", "(", "id", ")", "{", "return", "{", "id", ":", "id", "}", ";", "}", ")", ",", "links", ":", "[", "]", "}", ";", "serialized", ".", "nodes", ".", "forEach", "(", "function", "(", "node", ")", "{", "var", "source", "=", "node", ".", "id", ";", "adjacent", "(", "source", ")", ".", "forEach", "(", "function", "(", "target", ")", "{", "serialized", ".", "links", ".", "push", "(", "{", "source", ":", "source", ",", "target", ":", "target", ",", "weight", ":", "getEdgeWeight", "(", "source", ",", "target", ")", "}", ")", ";", "}", ")", ";", "}", ")", ";", "return", "serialized", ";", "}" ]
Serializes the graph.
[ "Serializes", "the", "graph", "." ]
531622a4051438131703980b62f8d1c91d4ff147
https://github.com/datavis-tech/graph-data-structure/blob/531622a4051438131703980b62f8d1c91d4ff147/index.js#L301-L321
19,123
datavis-tech/graph-data-structure
index.js
deserialize
function deserialize(serialized){ serialized.nodes.forEach(function (node){ addNode(node.id); }); serialized.links.forEach(function (link){ addEdge(link.source, link.target, link.weight); }); return graph; }
javascript
function deserialize(serialized){ serialized.nodes.forEach(function (node){ addNode(node.id); }); serialized.links.forEach(function (link){ addEdge(link.source, link.target, link.weight); }); return graph; }
[ "function", "deserialize", "(", "serialized", ")", "{", "serialized", ".", "nodes", ".", "forEach", "(", "function", "(", "node", ")", "{", "addNode", "(", "node", ".", "id", ")", ";", "}", ")", ";", "serialized", ".", "links", ".", "forEach", "(", "function", "(", "link", ")", "{", "addEdge", "(", "link", ".", "source", ",", "link", ".", "target", ",", "link", ".", "weight", ")", ";", "}", ")", ";", "return", "graph", ";", "}" ]
Deserializes the given serialized graph.
[ "Deserializes", "the", "given", "serialized", "graph", "." ]
531622a4051438131703980b62f8d1c91d4ff147
https://github.com/datavis-tech/graph-data-structure/blob/531622a4051438131703980b62f8d1c91d4ff147/index.js#L324-L328
19,124
Tixit/odiff
odiff.js
set
function set(changeList, property, value) { changeList.push({ type:'set', path: property, val: value }) }
javascript
function set(changeList, property, value) { changeList.push({ type:'set', path: property, val: value }) }
[ "function", "set", "(", "changeList", ",", "property", ",", "value", ")", "{", "changeList", ".", "push", "(", "{", "type", ":", "'set'", ",", "path", ":", "property", ",", "val", ":", "value", "}", ")", "}" ]
adds a 'set' type to the changeList
[ "adds", "a", "set", "type", "to", "the", "changeList" ]
d5fce4d77e50e28a5c5e4614ff80bffa89a107ba
https://github.com/Tixit/odiff/blob/d5fce4d77e50e28a5c5e4614ff80bffa89a107ba/odiff.js#L103-L109
19,125
Tixit/odiff
odiff.js
rm
function rm(changeList, property, index, count, a) { var finalIndex = index ? index - count + 1 : 0 changeList.push({ type:'rm', path: property, index: finalIndex, num: count, vals: a.slice(finalIndex, finalIndex+count) }) }
javascript
function rm(changeList, property, index, count, a) { var finalIndex = index ? index - count + 1 : 0 changeList.push({ type:'rm', path: property, index: finalIndex, num: count, vals: a.slice(finalIndex, finalIndex+count) }) }
[ "function", "rm", "(", "changeList", ",", "property", ",", "index", ",", "count", ",", "a", ")", "{", "var", "finalIndex", "=", "index", "?", "index", "-", "count", "+", "1", ":", "0", "changeList", ".", "push", "(", "{", "type", ":", "'rm'", ",", "path", ":", "property", ",", "index", ":", "finalIndex", ",", "num", ":", "count", ",", "vals", ":", "a", ".", "slice", "(", "finalIndex", ",", "finalIndex", "+", "count", ")", "}", ")", "}" ]
adds an 'rm' type to the changeList
[ "adds", "an", "rm", "type", "to", "the", "changeList" ]
d5fce4d77e50e28a5c5e4614ff80bffa89a107ba
https://github.com/Tixit/odiff/blob/d5fce4d77e50e28a5c5e4614ff80bffa89a107ba/odiff.js#L120-L129
19,126
Tixit/odiff
odiff.js
add
function add(changeList, property, index, values) { changeList.push({ type:'add', path: property, index: index, vals: values }) }
javascript
function add(changeList, property, index, values) { changeList.push({ type:'add', path: property, index: index, vals: values }) }
[ "function", "add", "(", "changeList", ",", "property", ",", "index", ",", "values", ")", "{", "changeList", ".", "push", "(", "{", "type", ":", "'add'", ",", "path", ":", "property", ",", "index", ":", "index", ",", "vals", ":", "values", "}", ")", "}" ]
adds an 'add' type to the changeList
[ "adds", "an", "add", "type", "to", "the", "changeList" ]
d5fce4d77e50e28a5c5e4614ff80bffa89a107ba
https://github.com/Tixit/odiff/blob/d5fce4d77e50e28a5c5e4614ff80bffa89a107ba/odiff.js#L132-L139
19,127
Tixit/odiff
odiff.js
arrayToMap
function arrayToMap(array) { var result = {} array.forEach(function(v) { result[v] = true }) return result }
javascript
function arrayToMap(array) { var result = {} array.forEach(function(v) { result[v] = true }) return result }
[ "function", "arrayToMap", "(", "array", ")", "{", "var", "result", "=", "{", "}", "array", ".", "forEach", "(", "function", "(", "v", ")", "{", "result", "[", "v", "]", "=", "true", "}", ")", "return", "result", "}" ]
turns an array of values into a an object where those values are all keys that point to 'true'
[ "turns", "an", "array", "of", "values", "into", "a", "an", "object", "where", "those", "values", "are", "all", "keys", "that", "point", "to", "true" ]
d5fce4d77e50e28a5c5e4614ff80bffa89a107ba
https://github.com/Tixit/odiff/blob/d5fce4d77e50e28a5c5e4614ff80bffa89a107ba/odiff.js#L277-L283
19,128
WebReflection/es6-collections
index.js
createCollection
function createCollection(proto, objectOnly){ function Collection(a){ if (!this || this.constructor !== Collection) return new Collection(a); this._keys = []; this._values = []; this._itp = []; // iteration pointers this.objectOnly = objectOnly; //parse initial iterable argument passed if (a) init.call(this, a); } //define size for non object-only collections if (!objectOnly) { defineProperty(proto, 'size', { get: sharedSize }); } //set prototype proto.constructor = Collection; Collection.prototype = proto; return Collection; }
javascript
function createCollection(proto, objectOnly){ function Collection(a){ if (!this || this.constructor !== Collection) return new Collection(a); this._keys = []; this._values = []; this._itp = []; // iteration pointers this.objectOnly = objectOnly; //parse initial iterable argument passed if (a) init.call(this, a); } //define size for non object-only collections if (!objectOnly) { defineProperty(proto, 'size', { get: sharedSize }); } //set prototype proto.constructor = Collection; Collection.prototype = proto; return Collection; }
[ "function", "createCollection", "(", "proto", ",", "objectOnly", ")", "{", "function", "Collection", "(", "a", ")", "{", "if", "(", "!", "this", "||", "this", ".", "constructor", "!==", "Collection", ")", "return", "new", "Collection", "(", "a", ")", ";", "this", ".", "_keys", "=", "[", "]", ";", "this", ".", "_values", "=", "[", "]", ";", "this", ".", "_itp", "=", "[", "]", ";", "// iteration pointers", "this", ".", "objectOnly", "=", "objectOnly", ";", "//parse initial iterable argument passed", "if", "(", "a", ")", "init", ".", "call", "(", "this", ",", "a", ")", ";", "}", "//define size for non object-only collections", "if", "(", "!", "objectOnly", ")", "{", "defineProperty", "(", "proto", ",", "'size'", ",", "{", "get", ":", "sharedSize", "}", ")", ";", "}", "//set prototype", "proto", ".", "constructor", "=", "Collection", ";", "Collection", ".", "prototype", "=", "proto", ";", "return", "Collection", ";", "}" ]
ES6 collection constructor @return {Function} a collection class
[ "ES6", "collection", "constructor" ]
bb96f2e469d96e94024623e3760efd551c33d4d5
https://github.com/WebReflection/es6-collections/blob/bb96f2e469d96e94024623e3760efd551c33d4d5/index.js#L87-L111
19,129
bpmn-io/moddle
lib/registry.js
traverseSuper
function traverseSuper(cls, trait) { var parentNs = parseNameNs(cls, isBuiltInType(cls) ? '' : nsName.prefix); self.mapTypes(parentNs, iterator, trait); }
javascript
function traverseSuper(cls, trait) { var parentNs = parseNameNs(cls, isBuiltInType(cls) ? '' : nsName.prefix); self.mapTypes(parentNs, iterator, trait); }
[ "function", "traverseSuper", "(", "cls", ",", "trait", ")", "{", "var", "parentNs", "=", "parseNameNs", "(", "cls", ",", "isBuiltInType", "(", "cls", ")", "?", "''", ":", "nsName", ".", "prefix", ")", ";", "self", ".", "mapTypes", "(", "parentNs", ",", "iterator", ",", "trait", ")", ";", "}" ]
Traverse the selected super type or trait @param {String} cls @param {Boolean} [trait=false]
[ "Traverse", "the", "selected", "super", "type", "or", "trait" ]
4ea5ccb639f21f981b1e44ea53c60faaaf8698be
https://github.com/bpmn-io/moddle/blob/4ea5ccb639f21f981b1e44ea53c60faaaf8698be/lib/registry.js#L153-L156
19,130
bpmn-io/moddle
lib/factory.js
ModdleElement
function ModdleElement(attrs) { props.define(this, '$type', { value: name, enumerable: true }); props.define(this, '$attrs', { value: {} }); props.define(this, '$parent', { writable: true }); forEach(attrs, bind(function(val, key) { this.set(key, val); }, this)); }
javascript
function ModdleElement(attrs) { props.define(this, '$type', { value: name, enumerable: true }); props.define(this, '$attrs', { value: {} }); props.define(this, '$parent', { writable: true }); forEach(attrs, bind(function(val, key) { this.set(key, val); }, this)); }
[ "function", "ModdleElement", "(", "attrs", ")", "{", "props", ".", "define", "(", "this", ",", "'$type'", ",", "{", "value", ":", "name", ",", "enumerable", ":", "true", "}", ")", ";", "props", ".", "define", "(", "this", ",", "'$attrs'", ",", "{", "value", ":", "{", "}", "}", ")", ";", "props", ".", "define", "(", "this", ",", "'$parent'", ",", "{", "writable", ":", "true", "}", ")", ";", "forEach", "(", "attrs", ",", "bind", "(", "function", "(", "val", ",", "key", ")", "{", "this", ".", "set", "(", "key", ",", "val", ")", ";", "}", ",", "this", ")", ")", ";", "}" ]
The new type constructor
[ "The", "new", "type", "constructor" ]
4ea5ccb639f21f981b1e44ea53c60faaaf8698be
https://github.com/bpmn-io/moddle/blob/4ea5ccb639f21f981b1e44ea53c60faaaf8698be/lib/factory.js#L42-L50
19,131
drudge/node-gpg
lib/spawnGPG.js
spawnIt
function spawnIt(args, fn) { var gpg = spawn('gpg', globalArgs.concat(args || []) ); gpg.on('error', fn); return gpg; }
javascript
function spawnIt(args, fn) { var gpg = spawn('gpg', globalArgs.concat(args || []) ); gpg.on('error', fn); return gpg; }
[ "function", "spawnIt", "(", "args", ",", "fn", ")", "{", "var", "gpg", "=", "spawn", "(", "'gpg'", ",", "globalArgs", ".", "concat", "(", "args", "||", "[", "]", ")", ")", ";", "gpg", ".", "on", "(", "'error'", ",", "fn", ")", ";", "return", "gpg", ";", "}" ]
Wrapper around spawn. Catches error events and passed global args.
[ "Wrapper", "around", "spawn", ".", "Catches", "error", "events", "and", "passed", "global", "args", "." ]
986cff9c66bc0e51b515d0d95c7eba663d93a16e
https://github.com/drudge/node-gpg/blob/986cff9c66bc0e51b515d0d95c7eba663d93a16e/lib/spawnGPG.js#L113-L117
19,132
williamngan/pt
demo/delaunay.generate.js
fibonacci
function fibonacci( num, scale, offset, smooth ) { if (!smooth) smooth = 0; var b = Math.round( smooth * Math.sqrt( num ) ); var phi = (Math.sqrt( 5 ) + 1) / 2; var pts = []; for (var i = 0; i < num; i++) { var r = (i > num - b) ? 1 : Math.sqrt( i - 0.5 ) / Math.sqrt( num - (b + 1) / 2 ); var theta = 2 * Math.PI * i / (phi * phi); pts.push( new Vector( r * scale * Math.cos( theta ), r * scale * Math.sin( theta ) ).add( offset ) ); } return pts; }
javascript
function fibonacci( num, scale, offset, smooth ) { if (!smooth) smooth = 0; var b = Math.round( smooth * Math.sqrt( num ) ); var phi = (Math.sqrt( 5 ) + 1) / 2; var pts = []; for (var i = 0; i < num; i++) { var r = (i > num - b) ? 1 : Math.sqrt( i - 0.5 ) / Math.sqrt( num - (b + 1) / 2 ); var theta = 2 * Math.PI * i / (phi * phi); pts.push( new Vector( r * scale * Math.cos( theta ), r * scale * Math.sin( theta ) ).add( offset ) ); } return pts; }
[ "function", "fibonacci", "(", "num", ",", "scale", ",", "offset", ",", "smooth", ")", "{", "if", "(", "!", "smooth", ")", "smooth", "=", "0", ";", "var", "b", "=", "Math", ".", "round", "(", "smooth", "*", "Math", ".", "sqrt", "(", "num", ")", ")", ";", "var", "phi", "=", "(", "Math", ".", "sqrt", "(", "5", ")", "+", "1", ")", "/", "2", ";", "var", "pts", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "num", ";", "i", "++", ")", "{", "var", "r", "=", "(", "i", ">", "num", "-", "b", ")", "?", "1", ":", "Math", ".", "sqrt", "(", "i", "-", "0.5", ")", "/", "Math", ".", "sqrt", "(", "num", "-", "(", "b", "+", "1", ")", "/", "2", ")", ";", "var", "theta", "=", "2", "*", "Math", ".", "PI", "*", "i", "/", "(", "phi", "*", "phi", ")", ";", "pts", ".", "push", "(", "new", "Vector", "(", "r", "*", "scale", "*", "Math", ".", "cos", "(", "theta", ")", ",", "r", "*", "scale", "*", "Math", ".", "sin", "(", "theta", ")", ")", ".", "add", "(", "offset", ")", ")", ";", "}", "return", "pts", ";", "}" ]
Generate fibonacci spiral points
[ "Generate", "fibonacci", "spiral", "points" ]
52fee535c10fd2e39dbef612c8a888e0b4c66a7d
https://github.com/williamngan/pt/blob/52fee535c10fd2e39dbef612c8a888e0b4c66a7d/demo/delaunay.generate.js#L22-L33
19,133
williamngan/pt
demo/samplepoints.poisson.js
init
function init() { shift++; samples = new SamplePoints(); samples.setBounds( new Rectangle( 25, 25 ).size( space.size.x - 25, space.size.y - 25 ), true ); samples.poissonSampler( 6 ); // target 6px radius }
javascript
function init() { shift++; samples = new SamplePoints(); samples.setBounds( new Rectangle( 25, 25 ).size( space.size.x - 25, space.size.y - 25 ), true ); samples.poissonSampler( 6 ); // target 6px radius }
[ "function", "init", "(", ")", "{", "shift", "++", ";", "samples", "=", "new", "SamplePoints", "(", ")", ";", "samples", ".", "setBounds", "(", "new", "Rectangle", "(", "25", ",", "25", ")", ".", "size", "(", "space", ".", "size", ".", "x", "-", "25", ",", "space", ".", "size", ".", "y", "-", "25", ")", ",", "true", ")", ";", "samples", ".", "poissonSampler", "(", "6", ")", ";", "// target 6px radius", "}" ]
when ready, initiate a new set of SamplePoints. SamplePoints is a kind of PointSet.
[ "when", "ready", "initiate", "a", "new", "set", "of", "SamplePoints", ".", "SamplePoints", "is", "a", "kind", "of", "PointSet", "." ]
52fee535c10fd2e39dbef612c8a888e0b4c66a7d
https://github.com/williamngan/pt/blob/52fee535c10fd2e39dbef612c8a888e0b4c66a7d/demo/samplepoints.poisson.js#L22-L27
19,134
williamngan/pt
demo/triangle.oppositeSide.js
Tri
function Tri() { Triangle.apply( this, arguments ); this.target = {vec: null, t: 0}; this.vertices = ["p0","p1","p2"]; this.colorId = 1 + (colorToggle % 3); }
javascript
function Tri() { Triangle.apply( this, arguments ); this.target = {vec: null, t: 0}; this.vertices = ["p0","p1","p2"]; this.colorId = 1 + (colorToggle % 3); }
[ "function", "Tri", "(", ")", "{", "Triangle", ".", "apply", "(", "this", ",", "arguments", ")", ";", "this", ".", "target", "=", "{", "vec", ":", "null", ",", "t", ":", "0", "}", ";", "this", ".", "vertices", "=", "[", "\"p0\"", ",", "\"p1\"", ",", "\"p2\"", "]", ";", "this", ".", "colorId", "=", "1", "+", "(", "colorToggle", "%", "3", ")", ";", "}" ]
Tri is a kind of Triangle which can generate new triangles by unfolding.
[ "Tri", "is", "a", "kind", "of", "Triangle", "which", "can", "generate", "new", "triangles", "by", "unfolding", "." ]
52fee535c10fd2e39dbef612c8a888e0b4c66a7d
https://github.com/williamngan/pt/blob/52fee535c10fd2e39dbef612c8a888e0b4c66a7d/demo/triangle.oppositeSide.js#L19-L24
19,135
williamngan/pt
demo/curve.bspline.js
repel
function repel( pt, i ) { if ( pt.distance(mouse) < threshold ) { // smaller than threshold distance, push it out var dir = pt.$subtract(mouse).normalize(); pt.set( dir.multiply(threshold).add( mouse ).min( space.size ).max(0, 0) ); } else { // bigger than threshold distance, pull it in var orig = origs[i]; pt.set ( orig.$add( pt.$subtract(orig).multiply(0.98) ) ); } }
javascript
function repel( pt, i ) { if ( pt.distance(mouse) < threshold ) { // smaller than threshold distance, push it out var dir = pt.$subtract(mouse).normalize(); pt.set( dir.multiply(threshold).add( mouse ).min( space.size ).max(0, 0) ); } else { // bigger than threshold distance, pull it in var orig = origs[i]; pt.set ( orig.$add( pt.$subtract(orig).multiply(0.98) ) ); } }
[ "function", "repel", "(", "pt", ",", "i", ")", "{", "if", "(", "pt", ".", "distance", "(", "mouse", ")", "<", "threshold", ")", "{", "// smaller than threshold distance, push it out", "var", "dir", "=", "pt", ".", "$subtract", "(", "mouse", ")", ".", "normalize", "(", ")", ";", "pt", ".", "set", "(", "dir", ".", "multiply", "(", "threshold", ")", ".", "add", "(", "mouse", ")", ".", "min", "(", "space", ".", "size", ")", ".", "max", "(", "0", ",", "0", ")", ")", ";", "}", "else", "{", "// bigger than threshold distance, pull it in", "var", "orig", "=", "origs", "[", "i", "]", ";", "pt", ".", "set", "(", "orig", ".", "$add", "(", "pt", ".", "$subtract", "(", "orig", ")", ".", "multiply", "(", "0.98", ")", ")", ")", ";", "}", "}" ]
Repel the control points when mouse is near i
[ "Repel", "the", "control", "points", "when", "mouse", "is", "near", "i" ]
52fee535c10fd2e39dbef612c8a888e0b4c66a7d
https://github.com/williamngan/pt/blob/52fee535c10fd2e39dbef612c8a888e0b4c66a7d/demo/curve.bspline.js#L39-L47
19,136
williamngan/pt
demo/canvasspace.resize.js
function(x, y, evt) { // center is at half size center.set(x/2, y/2); var shift = x/10; line1.set(x/2 + shift, 0); line1.p1.set(x/2 - shift, y); line2.set(0, y/2 - shift); line2.p1.set(x, y/2 + shift); rect.size( x/2, y/2 ); rect.setCenter( x/2, y/2 ); }
javascript
function(x, y, evt) { // center is at half size center.set(x/2, y/2); var shift = x/10; line1.set(x/2 + shift, 0); line1.p1.set(x/2 - shift, y); line2.set(0, y/2 - shift); line2.p1.set(x, y/2 + shift); rect.size( x/2, y/2 ); rect.setCenter( x/2, y/2 ); }
[ "function", "(", "x", ",", "y", ",", "evt", ")", "{", "// center is at half size", "center", ".", "set", "(", "x", "/", "2", ",", "y", "/", "2", ")", ";", "var", "shift", "=", "x", "/", "10", ";", "line1", ".", "set", "(", "x", "/", "2", "+", "shift", ",", "0", ")", ";", "line1", ".", "p1", ".", "set", "(", "x", "/", "2", "-", "shift", ",", "y", ")", ";", "line2", ".", "set", "(", "0", ",", "y", "/", "2", "-", "shift", ")", ";", "line2", ".", "p1", ".", "set", "(", "x", ",", "y", "/", "2", "+", "shift", ")", ";", "rect", ".", "size", "(", "x", "/", "2", ",", "y", "/", "2", ")", ";", "rect", ".", "setCenter", "(", "x", "/", "2", ",", "y", "/", "2", ")", ";", "}" ]
handler for Space resize
[ "handler", "for", "Space", "resize" ]
52fee535c10fd2e39dbef612c8a888e0b4c66a7d
https://github.com/williamngan/pt/blob/52fee535c10fd2e39dbef612c8a888e0b4c66a7d/demo/canvasspace.resize.js#L48-L62
19,137
williamngan/pt
demo/point.max.js
getMinMax
function getMinMax() { var minPt = pts[0]; var maxPt = pts[0]; for (var i=1; i<pts.length; i++) { minPt = minPt.$min( pts[i] ); } for (i=1; i<pts.length; i++) { maxPt = maxPt.$max( pts[i] ); } nextRect.set( minPt).to( maxPt ); }
javascript
function getMinMax() { var minPt = pts[0]; var maxPt = pts[0]; for (var i=1; i<pts.length; i++) { minPt = minPt.$min( pts[i] ); } for (i=1; i<pts.length; i++) { maxPt = maxPt.$max( pts[i] ); } nextRect.set( minPt).to( maxPt ); }
[ "function", "getMinMax", "(", ")", "{", "var", "minPt", "=", "pts", "[", "0", "]", ";", "var", "maxPt", "=", "pts", "[", "0", "]", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "pts", ".", "length", ";", "i", "++", ")", "{", "minPt", "=", "minPt", ".", "$min", "(", "pts", "[", "i", "]", ")", ";", "}", "for", "(", "i", "=", "1", ";", "i", "<", "pts", ".", "length", ";", "i", "++", ")", "{", "maxPt", "=", "maxPt", ".", "$max", "(", "pts", "[", "i", "]", ")", ";", "}", "nextRect", ".", "set", "(", "minPt", ")", ".", "to", "(", "maxPt", ")", ";", "}" ]
Calculate min and max points, and set the rectangular bound.
[ "Calculate", "min", "and", "max", "points", "and", "set", "the", "rectangular", "bound", "." ]
52fee535c10fd2e39dbef612c8a888e0b4c66a7d
https://github.com/williamngan/pt/blob/52fee535c10fd2e39dbef612c8a888e0b4c66a7d/demo/point.max.js#L25-L35
19,138
williamngan/pt
demo/point.quadrant.js
cornerLine
function cornerLine(p, quadrant, size) { switch (quadrant) { case Const.top_left: return new Pair(p).to(p.$add(size, size)); case Const.top_right: return new Pair(p).to(p.$add(-size, size)); case Const.bottom_left: return new Pair(p).to(p.$add(size, -size)); case Const.bottom_right: return new Pair(p).to(p.$add(-size, -size)); case Const.top: return new Pair(p).to(p.$add(0, size)); case Const.bottom: return new Pair(p).to(p.$add(0, -size)); case Const.left: return new Pair(p).to(p.$add(size, 0)); default: return new Pair(p).to(p.$add(-size, 0)); } }
javascript
function cornerLine(p, quadrant, size) { switch (quadrant) { case Const.top_left: return new Pair(p).to(p.$add(size, size)); case Const.top_right: return new Pair(p).to(p.$add(-size, size)); case Const.bottom_left: return new Pair(p).to(p.$add(size, -size)); case Const.bottom_right: return new Pair(p).to(p.$add(-size, -size)); case Const.top: return new Pair(p).to(p.$add(0, size)); case Const.bottom: return new Pair(p).to(p.$add(0, -size)); case Const.left: return new Pair(p).to(p.$add(size, 0)); default: return new Pair(p).to(p.$add(-size, 0)); } }
[ "function", "cornerLine", "(", "p", ",", "quadrant", ",", "size", ")", "{", "switch", "(", "quadrant", ")", "{", "case", "Const", ".", "top_left", ":", "return", "new", "Pair", "(", "p", ")", ".", "to", "(", "p", ".", "$add", "(", "size", ",", "size", ")", ")", ";", "case", "Const", ".", "top_right", ":", "return", "new", "Pair", "(", "p", ")", ".", "to", "(", "p", ".", "$add", "(", "-", "size", ",", "size", ")", ")", ";", "case", "Const", ".", "bottom_left", ":", "return", "new", "Pair", "(", "p", ")", ".", "to", "(", "p", ".", "$add", "(", "size", ",", "-", "size", ")", ")", ";", "case", "Const", ".", "bottom_right", ":", "return", "new", "Pair", "(", "p", ")", ".", "to", "(", "p", ".", "$add", "(", "-", "size", ",", "-", "size", ")", ")", ";", "case", "Const", ".", "top", ":", "return", "new", "Pair", "(", "p", ")", ".", "to", "(", "p", ".", "$add", "(", "0", ",", "size", ")", ")", ";", "case", "Const", ".", "bottom", ":", "return", "new", "Pair", "(", "p", ")", ".", "to", "(", "p", ".", "$add", "(", "0", ",", "-", "size", ")", ")", ";", "case", "Const", ".", "left", ":", "return", "new", "Pair", "(", "p", ")", ".", "to", "(", "p", ".", "$add", "(", "size", ",", "0", ")", ")", ";", "default", ":", "return", "new", "Pair", "(", "p", ")", ".", "to", "(", "p", ".", "$add", "(", "-", "size", ",", "0", ")", ")", ";", "}", "}" ]
Get a line indicating the quadrant
[ "Get", "a", "line", "indicating", "the", "quadrant" ]
52fee535c10fd2e39dbef612c8a888e0b4c66a7d
https://github.com/williamngan/pt/blob/52fee535c10fd2e39dbef612c8a888e0b4c66a7d/demo/point.quadrant.js#L27-L39
19,139
williamngan/pt
demo/point.quadrant.js
draw
function draw() { for (i=0; i<pts.length; i++) { // draw corners var q = mouseP.quadrant(pts[i], 2); var ln = cornerLine(pts[i], q, 12); form.stroke( colors["a"+(q%4+1)], 1.5); form.line( new Pair(ln.p1.x, ln.y).to( ln.x, ln.y) ); form.line( new Pair(ln.x, ln.y).to( ln.x, ln.p1.y) ); // draw point form.fill( colors.c4 ).stroke( false ); form.point( ln.p1, 3, true); } }
javascript
function draw() { for (i=0; i<pts.length; i++) { // draw corners var q = mouseP.quadrant(pts[i], 2); var ln = cornerLine(pts[i], q, 12); form.stroke( colors["a"+(q%4+1)], 1.5); form.line( new Pair(ln.p1.x, ln.y).to( ln.x, ln.y) ); form.line( new Pair(ln.x, ln.y).to( ln.x, ln.p1.y) ); // draw point form.fill( colors.c4 ).stroke( false ); form.point( ln.p1, 3, true); } }
[ "function", "draw", "(", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "pts", ".", "length", ";", "i", "++", ")", "{", "// draw corners", "var", "q", "=", "mouseP", ".", "quadrant", "(", "pts", "[", "i", "]", ",", "2", ")", ";", "var", "ln", "=", "cornerLine", "(", "pts", "[", "i", "]", ",", "q", ",", "12", ")", ";", "form", ".", "stroke", "(", "colors", "[", "\"a\"", "+", "(", "q", "%", "4", "+", "1", ")", "]", ",", "1.5", ")", ";", "form", ".", "line", "(", "new", "Pair", "(", "ln", ".", "p1", ".", "x", ",", "ln", ".", "y", ")", ".", "to", "(", "ln", ".", "x", ",", "ln", ".", "y", ")", ")", ";", "form", ".", "line", "(", "new", "Pair", "(", "ln", ".", "x", ",", "ln", ".", "y", ")", ".", "to", "(", "ln", ".", "x", ",", "ln", ".", "p1", ".", "y", ")", ")", ";", "// draw point", "form", ".", "fill", "(", "colors", ".", "c4", ")", ".", "stroke", "(", "false", ")", ";", "form", ".", "point", "(", "ln", ".", "p1", ",", "3", ",", "true", ")", ";", "}", "}" ]
Draw the points
[ "Draw", "the", "points" ]
52fee535c10fd2e39dbef612c8a888e0b4c66a7d
https://github.com/williamngan/pt/blob/52fee535c10fd2e39dbef612c8a888e0b4c66a7d/demo/point.quadrant.js#L42-L59
19,140
williamngan/pt
docs/js/demo.js
init
function init( shouldResize ) { if (stopped) return; rects = []; gap = space.size.$subtract( 100, 100 ).divide( steps*2, steps ); if (shouldResize) { var size = space.canvas.parentNode.getBoundingClientRect(); if (size.width && size.height) { space.resize( size.width, size.height ); } } for (var i = 0; i <= (steps * 2); i++) { for (var j = 0; j <= (steps); j++) { var rect = new Pt.Rectangle().to( 10, 10 ); rect.moveTo( 50 - 5.5 + gap.x * i, 50 - 5.5 + gap.y * j ); rect.setCenter(); rects.push( rect ); } } }
javascript
function init( shouldResize ) { if (stopped) return; rects = []; gap = space.size.$subtract( 100, 100 ).divide( steps*2, steps ); if (shouldResize) { var size = space.canvas.parentNode.getBoundingClientRect(); if (size.width && size.height) { space.resize( size.width, size.height ); } } for (var i = 0; i <= (steps * 2); i++) { for (var j = 0; j <= (steps); j++) { var rect = new Pt.Rectangle().to( 10, 10 ); rect.moveTo( 50 - 5.5 + gap.x * i, 50 - 5.5 + gap.y * j ); rect.setCenter(); rects.push( rect ); } } }
[ "function", "init", "(", "shouldResize", ")", "{", "if", "(", "stopped", ")", "return", ";", "rects", "=", "[", "]", ";", "gap", "=", "space", ".", "size", ".", "$subtract", "(", "100", ",", "100", ")", ".", "divide", "(", "steps", "*", "2", ",", "steps", ")", ";", "if", "(", "shouldResize", ")", "{", "var", "size", "=", "space", ".", "canvas", ".", "parentNode", ".", "getBoundingClientRect", "(", ")", ";", "if", "(", "size", ".", "width", "&&", "size", ".", "height", ")", "{", "space", ".", "resize", "(", "size", ".", "width", ",", "size", ".", "height", ")", ";", "}", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<=", "(", "steps", "*", "2", ")", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<=", "(", "steps", ")", ";", "j", "++", ")", "{", "var", "rect", "=", "new", "Pt", ".", "Rectangle", "(", ")", ".", "to", "(", "10", ",", "10", ")", ";", "rect", ".", "moveTo", "(", "50", "-", "5.5", "+", "gap", ".", "x", "*", "i", ",", "50", "-", "5.5", "+", "gap", ".", "y", "*", "j", ")", ";", "rect", ".", "setCenter", "(", ")", ";", "rects", ".", "push", "(", "rect", ")", ";", "}", "}", "}" ]
create grid of rectangles
[ "create", "grid", "of", "rectangles" ]
52fee535c10fd2e39dbef612c8a888e0b4c66a7d
https://github.com/williamngan/pt/blob/52fee535c10fd2e39dbef612c8a888e0b4c66a7d/docs/js/demo.js#L29-L50
19,141
williamngan/pt
demo/pair.interpolate.js
interpolatePairs
function interpolatePairs( _ps, t1, t2 ) { var pn = []; for (var i=0; i<_ps.length; i++) { var next = (i==_ps.length-1) ? 0 : i+1; pn.push( new Pair( _ps[i].interpolate( t1 ) ).to( _ps[next].interpolate( 1-t2 ) ) ); } return pn; }
javascript
function interpolatePairs( _ps, t1, t2 ) { var pn = []; for (var i=0; i<_ps.length; i++) { var next = (i==_ps.length-1) ? 0 : i+1; pn.push( new Pair( _ps[i].interpolate( t1 ) ).to( _ps[next].interpolate( 1-t2 ) ) ); } return pn; }
[ "function", "interpolatePairs", "(", "_ps", ",", "t1", ",", "t2", ")", "{", "var", "pn", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "_ps", ".", "length", ";", "i", "++", ")", "{", "var", "next", "=", "(", "i", "==", "_ps", ".", "length", "-", "1", ")", "?", "0", ":", "i", "+", "1", ";", "pn", ".", "push", "(", "new", "Pair", "(", "_ps", "[", "i", "]", ".", "interpolate", "(", "t1", ")", ")", ".", "to", "(", "_ps", "[", "next", "]", ".", "interpolate", "(", "1", "-", "t2", ")", ")", ")", ";", "}", "return", "pn", ";", "}" ]
create a list of interpolated pairs from a list of original pairs
[ "create", "a", "list", "of", "interpolated", "pairs", "from", "a", "list", "of", "original", "pairs" ]
52fee535c10fd2e39dbef612c8a888e0b4c66a7d
https://github.com/williamngan/pt/blob/52fee535c10fd2e39dbef612c8a888e0b4c66a7d/demo/pair.interpolate.js#L34-L41
19,142
williamngan/pt
demo/triangle.incenter.js
setTarget
function setTarget(p) { if (!p) p = space.size.$multiply( Math.random(), Math.random() ); timeInc++; target.p++; target.t = 0; target.vec = p; }
javascript
function setTarget(p) { if (!p) p = space.size.$multiply( Math.random(), Math.random() ); timeInc++; target.p++; target.t = 0; target.vec = p; }
[ "function", "setTarget", "(", "p", ")", "{", "if", "(", "!", "p", ")", "p", "=", "space", ".", "size", ".", "$multiply", "(", "Math", ".", "random", "(", ")", ",", "Math", ".", "random", "(", ")", ")", ";", "timeInc", "++", ";", "target", ".", "p", "++", ";", "target", ".", "t", "=", "0", ";", "target", ".", "vec", "=", "p", ";", "}" ]
move a triangle's point to new position
[ "move", "a", "triangle", "s", "point", "to", "new", "position" ]
52fee535c10fd2e39dbef612c8a888e0b4c66a7d
https://github.com/williamngan/pt/blob/52fee535c10fd2e39dbef612c8a888e0b4c66a7d/demo/triangle.incenter.js#L26-L32
19,143
williamngan/pt
demo/grid.canFit.js
gameOfLife
function gameOfLife() { for (var i=0; i<grid.columns; i++) { buffer[i] = []; // reset row for (var k=0; k<grid.rows; k++) { var cnt = 0; // counter for ( var m=i-1; m<i+2; m++) { // get the states of surrounding cells var mm = (m<0) ? grid.columns-1 : ( (m>=grid.columns) ? m-grid.columns : m ); for ( var n=k-1; n<k+2; n++) { var nn = (n<0) ? grid.rows-1 : ( (n>=grid.rows) ? n-grid.rows : n ); if (mm===i && nn===k) continue; else if ( !grid.canFit(mm, nn, 1, 1) ) cnt++; } } buffer[i][k] = (grid.canFit(i, k, 1, 1) && cnt==3) || (!grid.canFit(i, k, 1, 1) && cnt>=2 && cnt<=3); } } }
javascript
function gameOfLife() { for (var i=0; i<grid.columns; i++) { buffer[i] = []; // reset row for (var k=0; k<grid.rows; k++) { var cnt = 0; // counter for ( var m=i-1; m<i+2; m++) { // get the states of surrounding cells var mm = (m<0) ? grid.columns-1 : ( (m>=grid.columns) ? m-grid.columns : m ); for ( var n=k-1; n<k+2; n++) { var nn = (n<0) ? grid.rows-1 : ( (n>=grid.rows) ? n-grid.rows : n ); if (mm===i && nn===k) continue; else if ( !grid.canFit(mm, nn, 1, 1) ) cnt++; } } buffer[i][k] = (grid.canFit(i, k, 1, 1) && cnt==3) || (!grid.canFit(i, k, 1, 1) && cnt>=2 && cnt<=3); } } }
[ "function", "gameOfLife", "(", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "grid", ".", "columns", ";", "i", "++", ")", "{", "buffer", "[", "i", "]", "=", "[", "]", ";", "// reset row", "for", "(", "var", "k", "=", "0", ";", "k", "<", "grid", ".", "rows", ";", "k", "++", ")", "{", "var", "cnt", "=", "0", ";", "// counter", "for", "(", "var", "m", "=", "i", "-", "1", ";", "m", "<", "i", "+", "2", ";", "m", "++", ")", "{", "// get the states of surrounding cells", "var", "mm", "=", "(", "m", "<", "0", ")", "?", "grid", ".", "columns", "-", "1", ":", "(", "(", "m", ">=", "grid", ".", "columns", ")", "?", "m", "-", "grid", ".", "columns", ":", "m", ")", ";", "for", "(", "var", "n", "=", "k", "-", "1", ";", "n", "<", "k", "+", "2", ";", "n", "++", ")", "{", "var", "nn", "=", "(", "n", "<", "0", ")", "?", "grid", ".", "rows", "-", "1", ":", "(", "(", "n", ">=", "grid", ".", "rows", ")", "?", "n", "-", "grid", ".", "rows", ":", "n", ")", ";", "if", "(", "mm", "===", "i", "&&", "nn", "===", "k", ")", "continue", ";", "else", "if", "(", "!", "grid", ".", "canFit", "(", "mm", ",", "nn", ",", "1", ",", "1", ")", ")", "cnt", "++", ";", "}", "}", "buffer", "[", "i", "]", "[", "k", "]", "=", "(", "grid", ".", "canFit", "(", "i", ",", "k", ",", "1", ",", "1", ")", "&&", "cnt", "==", "3", ")", "||", "(", "!", "grid", ".", "canFit", "(", "i", ",", "k", ",", "1", ",", "1", ")", "&&", "cnt", ">=", "2", "&&", "cnt", "<=", "3", ")", ";", "}", "}", "}" ]
Conway's game of life
[ "Conway", "s", "game", "of", "life" ]
52fee535c10fd2e39dbef612c8a888e0b4c66a7d
https://github.com/williamngan/pt/blob/52fee535c10fd2e39dbef612c8a888e0b4c66a7d/demo/grid.canFit.js#L46-L65
19,144
fhqvst/avanza
scripts/generate-documentation.js
buildReturnTables
function buildReturnTables(res, name) { let tables = [] if (Array.isArray(res)) { if (res.length && res[0]) { tables = buildReturnTables(res[0], `${name}[i]`) } } else { const keys = Object.keys(res).map(k => ({ name: k, type: res[k].constructor.name })).sort((a, b) => a.name.localeCompare(b.name)) tables.push({ name, keys }) keys.filter(key => Array.isArray(res[key.name])).forEach((key) => { if (res[key.name].length) { tables = [...tables, ...buildReturnTables( res[key.name][0], `${name}.${key.name}[i]` )] } }) } return tables }
javascript
function buildReturnTables(res, name) { let tables = [] if (Array.isArray(res)) { if (res.length && res[0]) { tables = buildReturnTables(res[0], `${name}[i]`) } } else { const keys = Object.keys(res).map(k => ({ name: k, type: res[k].constructor.name })).sort((a, b) => a.name.localeCompare(b.name)) tables.push({ name, keys }) keys.filter(key => Array.isArray(res[key.name])).forEach((key) => { if (res[key.name].length) { tables = [...tables, ...buildReturnTables( res[key.name][0], `${name}.${key.name}[i]` )] } }) } return tables }
[ "function", "buildReturnTables", "(", "res", ",", "name", ")", "{", "let", "tables", "=", "[", "]", "if", "(", "Array", ".", "isArray", "(", "res", ")", ")", "{", "if", "(", "res", ".", "length", "&&", "res", "[", "0", "]", ")", "{", "tables", "=", "buildReturnTables", "(", "res", "[", "0", "]", ",", "`", "${", "name", "}", "`", ")", "}", "}", "else", "{", "const", "keys", "=", "Object", ".", "keys", "(", "res", ")", ".", "map", "(", "k", "=>", "(", "{", "name", ":", "k", ",", "type", ":", "res", "[", "k", "]", ".", "constructor", ".", "name", "}", ")", ")", ".", "sort", "(", "(", "a", ",", "b", ")", "=>", "a", ".", "name", ".", "localeCompare", "(", "b", ".", "name", ")", ")", "tables", ".", "push", "(", "{", "name", ",", "keys", "}", ")", "keys", ".", "filter", "(", "key", "=>", "Array", ".", "isArray", "(", "res", "[", "key", ".", "name", "]", ")", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "if", "(", "res", "[", "key", ".", "name", "]", ".", "length", ")", "{", "tables", "=", "[", "...", "tables", ",", "...", "buildReturnTables", "(", "res", "[", "key", ".", "name", "]", "[", "0", "]", ",", "`", "${", "name", "}", "${", "key", ".", "name", "}", "`", ")", "]", "}", "}", ")", "}", "return", "tables", "}" ]
Recursive function which builds an array of data about the endpoint return value. The information is then used to build Markdown tables. @param {Object|Array} res The value returned from the API endpoint. @param {String} name The name/header of the table to be built. @return {Array} An array of information about the endpoint return value.
[ "Recursive", "function", "which", "builds", "an", "array", "of", "data", "about", "the", "endpoint", "return", "value", ".", "The", "information", "is", "then", "used", "to", "build", "Markdown", "tables", "." ]
f37ab71b78086245cddc62c280774afd08c9803a
https://github.com/fhqvst/avanza/blob/f37ab71b78086245cddc62c280774afd08c9803a/scripts/generate-documentation.js#L35-L61
19,145
fhqvst/avanza
scripts/generate-documentation.js
buildMarkdown
async function buildMarkdown() { const docs = await documentation.build([filename], { shallow: true }) const functions = docs[0].members.instance.filter(x => x.kind === 'function') for (const fn of functions) { if (typeof calls[fn.name] === 'function') { const res = await calls[fn.name]() const tables = buildReturnTables(res, `${fn.name}()`) fn.description.children.push({ type: 'paragraph', children: [ { type: 'strong', children: [ { type: 'text', value: 'Returns' } ] } ] }) for (const table of tables) { // Add table title fn.description.children.push({ type: 'paragraph', children: [ { type: 'inlineCode', value: table.name } ] }) // Add table fn.description.children.push({ type: 'table', align: ['left', 'left'], children: [{ type: 'tableRow', children: [ { type: 'tableCell', children: [{ type: 'text', value: 'Property' }] }, { type: 'tableCell', children: [{ type: 'text', value: 'Type' }] }, { type: 'tableCell', children: [{ type: 'text', value: 'Note' }] } ] }, ...table.keys.map(key => ({ type: 'tableRow', children: [ { type: 'tableCell', children: [{ type: 'inlineCode', value: key.name }] }, { type: 'tableCell', children: [{ type: 'text', value: key.type }] }, { type: 'tableCell', children: [{ type: 'text', value: notes[key.name] || '' }] } ] }))] }) } } } const markdown = await documentation.formats.md(docs, { markdownToc: true }) fs.writeFileSync(path.join(process.cwd(), 'API.md'), markdown) process.exit() }
javascript
async function buildMarkdown() { const docs = await documentation.build([filename], { shallow: true }) const functions = docs[0].members.instance.filter(x => x.kind === 'function') for (const fn of functions) { if (typeof calls[fn.name] === 'function') { const res = await calls[fn.name]() const tables = buildReturnTables(res, `${fn.name}()`) fn.description.children.push({ type: 'paragraph', children: [ { type: 'strong', children: [ { type: 'text', value: 'Returns' } ] } ] }) for (const table of tables) { // Add table title fn.description.children.push({ type: 'paragraph', children: [ { type: 'inlineCode', value: table.name } ] }) // Add table fn.description.children.push({ type: 'table', align: ['left', 'left'], children: [{ type: 'tableRow', children: [ { type: 'tableCell', children: [{ type: 'text', value: 'Property' }] }, { type: 'tableCell', children: [{ type: 'text', value: 'Type' }] }, { type: 'tableCell', children: [{ type: 'text', value: 'Note' }] } ] }, ...table.keys.map(key => ({ type: 'tableRow', children: [ { type: 'tableCell', children: [{ type: 'inlineCode', value: key.name }] }, { type: 'tableCell', children: [{ type: 'text', value: key.type }] }, { type: 'tableCell', children: [{ type: 'text', value: notes[key.name] || '' }] } ] }))] }) } } } const markdown = await documentation.formats.md(docs, { markdownToc: true }) fs.writeFileSync(path.join(process.cwd(), 'API.md'), markdown) process.exit() }
[ "async", "function", "buildMarkdown", "(", ")", "{", "const", "docs", "=", "await", "documentation", ".", "build", "(", "[", "filename", "]", ",", "{", "shallow", ":", "true", "}", ")", "const", "functions", "=", "docs", "[", "0", "]", ".", "members", ".", "instance", ".", "filter", "(", "x", "=>", "x", ".", "kind", "===", "'function'", ")", "for", "(", "const", "fn", "of", "functions", ")", "{", "if", "(", "typeof", "calls", "[", "fn", ".", "name", "]", "===", "'function'", ")", "{", "const", "res", "=", "await", "calls", "[", "fn", ".", "name", "]", "(", ")", "const", "tables", "=", "buildReturnTables", "(", "res", ",", "`", "${", "fn", ".", "name", "}", "`", ")", "fn", ".", "description", ".", "children", ".", "push", "(", "{", "type", ":", "'paragraph'", ",", "children", ":", "[", "{", "type", ":", "'strong'", ",", "children", ":", "[", "{", "type", ":", "'text'", ",", "value", ":", "'Returns'", "}", "]", "}", "]", "}", ")", "for", "(", "const", "table", "of", "tables", ")", "{", "// Add table title", "fn", ".", "description", ".", "children", ".", "push", "(", "{", "type", ":", "'paragraph'", ",", "children", ":", "[", "{", "type", ":", "'inlineCode'", ",", "value", ":", "table", ".", "name", "}", "]", "}", ")", "// Add table", "fn", ".", "description", ".", "children", ".", "push", "(", "{", "type", ":", "'table'", ",", "align", ":", "[", "'left'", ",", "'left'", "]", ",", "children", ":", "[", "{", "type", ":", "'tableRow'", ",", "children", ":", "[", "{", "type", ":", "'tableCell'", ",", "children", ":", "[", "{", "type", ":", "'text'", ",", "value", ":", "'Property'", "}", "]", "}", ",", "{", "type", ":", "'tableCell'", ",", "children", ":", "[", "{", "type", ":", "'text'", ",", "value", ":", "'Type'", "}", "]", "}", ",", "{", "type", ":", "'tableCell'", ",", "children", ":", "[", "{", "type", ":", "'text'", ",", "value", ":", "'Note'", "}", "]", "}", "]", "}", ",", "...", "table", ".", "keys", ".", "map", "(", "key", "=>", "(", "{", "type", ":", "'tableRow'", ",", "children", ":", "[", "{", "type", ":", "'tableCell'", ",", "children", ":", "[", "{", "type", ":", "'inlineCode'", ",", "value", ":", "key", ".", "name", "}", "]", "}", ",", "{", "type", ":", "'tableCell'", ",", "children", ":", "[", "{", "type", ":", "'text'", ",", "value", ":", "key", ".", "type", "}", "]", "}", ",", "{", "type", ":", "'tableCell'", ",", "children", ":", "[", "{", "type", ":", "'text'", ",", "value", ":", "notes", "[", "key", ".", "name", "]", "||", "''", "}", "]", "}", "]", "}", ")", ")", "]", "}", ")", "}", "}", "}", "const", "markdown", "=", "await", "documentation", ".", "formats", ".", "md", "(", "docs", ",", "{", "markdownToc", ":", "true", "}", ")", "fs", ".", "writeFileSync", "(", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "'API.md'", ")", ",", "markdown", ")", "process", ".", "exit", "(", ")", "}" ]
Traverse through all functions inside in the wrapper and build Markdown tables describing each endpoint return value.
[ "Traverse", "through", "all", "functions", "inside", "in", "the", "wrapper", "and", "build", "Markdown", "tables", "describing", "each", "endpoint", "return", "value", "." ]
f37ab71b78086245cddc62c280774afd08c9803a
https://github.com/fhqvst/avanza/blob/f37ab71b78086245cddc62c280774afd08c9803a/scripts/generate-documentation.js#L67-L166
19,146
fhqvst/avanza
lib/index.js
request
function request(options) { if (!options) { return Promise.reject('Missing options.') } const data = JSON.stringify(options.data) return new Promise((resolve, reject) => { const req = https.request({ host: BASE_URL, port: 443, method: options.method, path: options.path, headers: Object.assign({ 'Accept': '*/*', 'Content-Type': 'application/json', 'User-Agent': USER_AGENT, 'Content-Length': data.length }, options.headers) }, (response) => { const body = [] response.on('data', chunk => body.push(chunk)) response.on('end', () => { let parsedBody = body.join('') try { parsedBody = JSON.parse(parsedBody) } catch (e) { debug('Received non-JSON data from API.', body) } const res = { statusCode: response.statusCode, statusMessage: response.statusMessage, headers: response.headers, body: parsedBody } if (response.statusCode < 200 || response.statusCode > 299) { reject(res) } else { resolve(res) } }) }) if (data) { req.write(data) } req.on('error', e => reject(e)) req.end() }) }
javascript
function request(options) { if (!options) { return Promise.reject('Missing options.') } const data = JSON.stringify(options.data) return new Promise((resolve, reject) => { const req = https.request({ host: BASE_URL, port: 443, method: options.method, path: options.path, headers: Object.assign({ 'Accept': '*/*', 'Content-Type': 'application/json', 'User-Agent': USER_AGENT, 'Content-Length': data.length }, options.headers) }, (response) => { const body = [] response.on('data', chunk => body.push(chunk)) response.on('end', () => { let parsedBody = body.join('') try { parsedBody = JSON.parse(parsedBody) } catch (e) { debug('Received non-JSON data from API.', body) } const res = { statusCode: response.statusCode, statusMessage: response.statusMessage, headers: response.headers, body: parsedBody } if (response.statusCode < 200 || response.statusCode > 299) { reject(res) } else { resolve(res) } }) }) if (data) { req.write(data) } req.on('error', e => reject(e)) req.end() }) }
[ "function", "request", "(", "options", ")", "{", "if", "(", "!", "options", ")", "{", "return", "Promise", ".", "reject", "(", "'Missing options.'", ")", "}", "const", "data", "=", "JSON", ".", "stringify", "(", "options", ".", "data", ")", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "req", "=", "https", ".", "request", "(", "{", "host", ":", "BASE_URL", ",", "port", ":", "443", ",", "method", ":", "options", ".", "method", ",", "path", ":", "options", ".", "path", ",", "headers", ":", "Object", ".", "assign", "(", "{", "'Accept'", ":", "'*/*'", ",", "'Content-Type'", ":", "'application/json'", ",", "'User-Agent'", ":", "USER_AGENT", ",", "'Content-Length'", ":", "data", ".", "length", "}", ",", "options", ".", "headers", ")", "}", ",", "(", "response", ")", "=>", "{", "const", "body", "=", "[", "]", "response", ".", "on", "(", "'data'", ",", "chunk", "=>", "body", ".", "push", "(", "chunk", ")", ")", "response", ".", "on", "(", "'end'", ",", "(", ")", "=>", "{", "let", "parsedBody", "=", "body", ".", "join", "(", "''", ")", "try", "{", "parsedBody", "=", "JSON", ".", "parse", "(", "parsedBody", ")", "}", "catch", "(", "e", ")", "{", "debug", "(", "'Received non-JSON data from API.'", ",", "body", ")", "}", "const", "res", "=", "{", "statusCode", ":", "response", ".", "statusCode", ",", "statusMessage", ":", "response", ".", "statusMessage", ",", "headers", ":", "response", ".", "headers", ",", "body", ":", "parsedBody", "}", "if", "(", "response", ".", "statusCode", "<", "200", "||", "response", ".", "statusCode", ">", "299", ")", "{", "reject", "(", "res", ")", "}", "else", "{", "resolve", "(", "res", ")", "}", "}", ")", "}", ")", "if", "(", "data", ")", "{", "req", ".", "write", "(", "data", ")", "}", "req", ".", "on", "(", "'error'", ",", "e", "=>", "reject", "(", "e", ")", ")", "req", ".", "end", "(", ")", "}", ")", "}" ]
Execute a request. @private @param {Object} options Request options. @return {Promise}
[ "Execute", "a", "request", "." ]
f37ab71b78086245cddc62c280774afd08c9803a
https://github.com/fhqvst/avanza/blob/f37ab71b78086245cddc62c280774afd08c9803a/lib/index.js#L38-L86
19,147
Stinkstudios/sono
src/core/sono.js
onHidden
function onHidden() { bus.sounds.forEach(sound => { if (sound.playing) { sound.pause(); pageHiddenPaused.push(sound); } }); }
javascript
function onHidden() { bus.sounds.forEach(sound => { if (sound.playing) { sound.pause(); pageHiddenPaused.push(sound); } }); }
[ "function", "onHidden", "(", ")", "{", "bus", ".", "sounds", ".", "forEach", "(", "sound", "=>", "{", "if", "(", "sound", ".", "playing", ")", "{", "sound", ".", "pause", "(", ")", ";", "pageHiddenPaused", ".", "push", "(", "sound", ")", ";", "}", "}", ")", ";", "}" ]
pause currently playing sounds and store refs
[ "pause", "currently", "playing", "sounds", "and", "store", "refs" ]
50fbea6b51d7015496539b27b3e568d08faef0e8
https://github.com/Stinkstudios/sono/blob/50fbea6b51d7015496539b27b3e568d08faef0e8/src/core/sono.js#L213-L220
19,148
Stinkstudios/sono
src/effects/panner.js
normalize
function normalize(vec3) { if (vec3.x === 0 && vec3.y === 0 && vec3.z === 0) { return vec3; } const length = Math.sqrt(vec3.x * vec3.x + vec3.y * vec3.y + vec3.z * vec3.z); const invScalar = 1 / length; vec3.x *= invScalar; vec3.y *= invScalar; vec3.z *= invScalar; return vec3; }
javascript
function normalize(vec3) { if (vec3.x === 0 && vec3.y === 0 && vec3.z === 0) { return vec3; } const length = Math.sqrt(vec3.x * vec3.x + vec3.y * vec3.y + vec3.z * vec3.z); const invScalar = 1 / length; vec3.x *= invScalar; vec3.y *= invScalar; vec3.z *= invScalar; return vec3; }
[ "function", "normalize", "(", "vec3", ")", "{", "if", "(", "vec3", ".", "x", "===", "0", "&&", "vec3", ".", "y", "===", "0", "&&", "vec3", ".", "z", "===", "0", ")", "{", "return", "vec3", ";", "}", "const", "length", "=", "Math", ".", "sqrt", "(", "vec3", ".", "x", "*", "vec3", ".", "x", "+", "vec3", ".", "y", "*", "vec3", ".", "y", "+", "vec3", ".", "z", "*", "vec3", ".", "z", ")", ";", "const", "invScalar", "=", "1", "/", "length", ";", "vec3", ".", "x", "*=", "invScalar", ";", "vec3", ".", "y", "*=", "invScalar", ";", "vec3", ".", "z", "*=", "invScalar", ";", "return", "vec3", ";", "}" ]
normalise to unit vector
[ "normalise", "to", "unit", "vector" ]
50fbea6b51d7015496539b27b3e568d08faef0e8
https://github.com/Stinkstudios/sono/blob/50fbea6b51d7015496539b27b3e568d08faef0e8/src/effects/panner.js#L38-L48
19,149
popeindustries/inline-source
lib/utils.js
isRelativeFilepath
function isRelativeFilepath(str) { if (str) { return ( isFilepath(str) && (str.indexOf('./') == 0 || str.indexOf('../') == 0) ); } return false; }
javascript
function isRelativeFilepath(str) { if (str) { return ( isFilepath(str) && (str.indexOf('./') == 0 || str.indexOf('../') == 0) ); } return false; }
[ "function", "isRelativeFilepath", "(", "str", ")", "{", "if", "(", "str", ")", "{", "return", "(", "isFilepath", "(", "str", ")", "&&", "(", "str", ".", "indexOf", "(", "'./'", ")", "==", "0", "||", "str", ".", "indexOf", "(", "'../'", ")", "==", "0", ")", ")", ";", "}", "return", "false", ";", "}" ]
Determine if 'str' is a relative filepath @param {String} str @returns {Boolean}
[ "Determine", "if", "str", "is", "a", "relative", "filepath" ]
7f9f6833d9ffee93cbf13d7e1183997904d055b6
https://github.com/popeindustries/inline-source/blob/7f9f6833d9ffee93cbf13d7e1183997904d055b6/lib/utils.js#L58-L65
19,150
popeindustries/inline-source
lib/utils.js
parseProps
function parseProps(attributes, prefix) { prefix += '-'; const props = {}; for (const prop in attributes) { // Strip 'inline-' and store if (prop.indexOf(prefix) == 0) { let value = attributes[prop]; if (value === 'false') { value = false; } if (value === 'true') { value = true; } props[prop.slice(prefix.length)] = value; } } return props; }
javascript
function parseProps(attributes, prefix) { prefix += '-'; const props = {}; for (const prop in attributes) { // Strip 'inline-' and store if (prop.indexOf(prefix) == 0) { let value = attributes[prop]; if (value === 'false') { value = false; } if (value === 'true') { value = true; } props[prop.slice(prefix.length)] = value; } } return props; }
[ "function", "parseProps", "(", "attributes", ",", "prefix", ")", "{", "prefix", "+=", "'-'", ";", "const", "props", "=", "{", "}", ";", "for", "(", "const", "prop", "in", "attributes", ")", "{", "// Strip 'inline-' and store", "if", "(", "prop", ".", "indexOf", "(", "prefix", ")", "==", "0", ")", "{", "let", "value", "=", "attributes", "[", "prop", "]", ";", "if", "(", "value", "===", "'false'", ")", "{", "value", "=", "false", ";", "}", "if", "(", "value", "===", "'true'", ")", "{", "value", "=", "true", ";", "}", "props", "[", "prop", ".", "slice", "(", "prefix", ".", "length", ")", "]", "=", "value", ";", "}", "}", "return", "props", ";", "}" ]
Parse props with 'prefix' from 'attributes' @param {Object} attributes @param {String} prefix @returns {Object}
[ "Parse", "props", "with", "prefix", "from", "attributes" ]
7f9f6833d9ffee93cbf13d7e1183997904d055b6
https://github.com/popeindustries/inline-source/blob/7f9f6833d9ffee93cbf13d7e1183997904d055b6/lib/utils.js#L125-L146
19,151
popeindustries/inline-source
lib/utils.js
getSourcepath
function getSourcepath(filepath, htmlpath, rootpath) { if (!filepath) { return ['', '']; } if (isRemoteFilepath(filepath)) { const url = new URL(filepath); filepath = `./${url.pathname.slice(1).replace(RE_FORWARD_SLASH, '_')}`; } // Strip query params filepath = filepath.replace(RE_QUERY, ''); // Relative path if (htmlpath && isRelativeFilepath(filepath)) { filepath = path.resolve(path.dirname(htmlpath), filepath); // Strip leading '/' } else if (filepath.indexOf('/') == 0) { filepath = filepath.slice(1); } if (filepath.includes('#')) { filepath = filepath.split('#'); } return Array.isArray(filepath) ? [path.resolve(rootpath, filepath[0]), filepath[1]] : [path.resolve(rootpath, filepath), '']; }
javascript
function getSourcepath(filepath, htmlpath, rootpath) { if (!filepath) { return ['', '']; } if (isRemoteFilepath(filepath)) { const url = new URL(filepath); filepath = `./${url.pathname.slice(1).replace(RE_FORWARD_SLASH, '_')}`; } // Strip query params filepath = filepath.replace(RE_QUERY, ''); // Relative path if (htmlpath && isRelativeFilepath(filepath)) { filepath = path.resolve(path.dirname(htmlpath), filepath); // Strip leading '/' } else if (filepath.indexOf('/') == 0) { filepath = filepath.slice(1); } if (filepath.includes('#')) { filepath = filepath.split('#'); } return Array.isArray(filepath) ? [path.resolve(rootpath, filepath[0]), filepath[1]] : [path.resolve(rootpath, filepath), '']; }
[ "function", "getSourcepath", "(", "filepath", ",", "htmlpath", ",", "rootpath", ")", "{", "if", "(", "!", "filepath", ")", "{", "return", "[", "''", ",", "''", "]", ";", "}", "if", "(", "isRemoteFilepath", "(", "filepath", ")", ")", "{", "const", "url", "=", "new", "URL", "(", "filepath", ")", ";", "filepath", "=", "`", "${", "url", ".", "pathname", ".", "slice", "(", "1", ")", ".", "replace", "(", "RE_FORWARD_SLASH", ",", "'_'", ")", "}", "`", ";", "}", "// Strip query params", "filepath", "=", "filepath", ".", "replace", "(", "RE_QUERY", ",", "''", ")", ";", "// Relative path", "if", "(", "htmlpath", "&&", "isRelativeFilepath", "(", "filepath", ")", ")", "{", "filepath", "=", "path", ".", "resolve", "(", "path", ".", "dirname", "(", "htmlpath", ")", ",", "filepath", ")", ";", "// Strip leading '/'", "}", "else", "if", "(", "filepath", ".", "indexOf", "(", "'/'", ")", "==", "0", ")", "{", "filepath", "=", "filepath", ".", "slice", "(", "1", ")", ";", "}", "if", "(", "filepath", ".", "includes", "(", "'#'", ")", ")", "{", "filepath", "=", "filepath", ".", "split", "(", "'#'", ")", ";", "}", "return", "Array", ".", "isArray", "(", "filepath", ")", "?", "[", "path", ".", "resolve", "(", "rootpath", ",", "filepath", "[", "0", "]", ")", ",", "filepath", "[", "1", "]", "]", ":", "[", "path", ".", "resolve", "(", "rootpath", ",", "filepath", ")", ",", "''", "]", ";", "}" ]
Retrieve resolved 'filepath' and optional anchor @param {String} filepath @param {String} htmlpath @param {String} rootpath @returns {Array}
[ "Retrieve", "resolved", "filepath", "and", "optional", "anchor" ]
7f9f6833d9ffee93cbf13d7e1183997904d055b6
https://github.com/popeindustries/inline-source/blob/7f9f6833d9ffee93cbf13d7e1183997904d055b6/lib/utils.js#L155-L181
19,152
popeindustries/inline-source
lib/utils.js
getPadding
function getPadding(source, html) { const re = new RegExp(`^([\\t ]+)${escape(source)}`, 'gm'); const match = re.exec(html); return match ? match[1] : ''; }
javascript
function getPadding(source, html) { const re = new RegExp(`^([\\t ]+)${escape(source)}`, 'gm'); const match = re.exec(html); return match ? match[1] : ''; }
[ "function", "getPadding", "(", "source", ",", "html", ")", "{", "const", "re", "=", "new", "RegExp", "(", "`", "\\\\", "${", "escape", "(", "source", ")", "}", "`", ",", "'gm'", ")", ";", "const", "match", "=", "re", ".", "exec", "(", "html", ")", ";", "return", "match", "?", "match", "[", "1", "]", ":", "''", ";", "}" ]
Retrieve leading whitespace for 'source' in 'html' @param {String} source @param {String} html @returns {String}
[ "Retrieve", "leading", "whitespace", "for", "source", "in", "html" ]
7f9f6833d9ffee93cbf13d7e1183997904d055b6
https://github.com/popeindustries/inline-source/blob/7f9f6833d9ffee93cbf13d7e1183997904d055b6/lib/utils.js#L282-L287
19,153
popeindustries/inline-source
lib/utils.js
isIgnored
function isIgnored(ignore, tag, type, format) { // Clean svg+xml ==> svg const formatAlt = format && format.indexOf('+') ? format.split('+')[0] : null; if (!Array.isArray(ignore)) { ignore = [ignore]; } return !!( ignore.includes(tag) || ignore.includes(type) || ignore.includes(format) || ignore.includes(formatAlt) ); }
javascript
function isIgnored(ignore, tag, type, format) { // Clean svg+xml ==> svg const formatAlt = format && format.indexOf('+') ? format.split('+')[0] : null; if (!Array.isArray(ignore)) { ignore = [ignore]; } return !!( ignore.includes(tag) || ignore.includes(type) || ignore.includes(format) || ignore.includes(formatAlt) ); }
[ "function", "isIgnored", "(", "ignore", ",", "tag", ",", "type", ",", "format", ")", "{", "// Clean svg+xml ==> svg", "const", "formatAlt", "=", "format", "&&", "format", ".", "indexOf", "(", "'+'", ")", "?", "format", ".", "split", "(", "'+'", ")", "[", "0", "]", ":", "null", ";", "if", "(", "!", "Array", ".", "isArray", "(", "ignore", ")", ")", "{", "ignore", "=", "[", "ignore", "]", ";", "}", "return", "!", "!", "(", "ignore", ".", "includes", "(", "tag", ")", "||", "ignore", ".", "includes", "(", "type", ")", "||", "ignore", ".", "includes", "(", "format", ")", "||", "ignore", ".", "includes", "(", "formatAlt", ")", ")", ";", "}" ]
Retrieve ignored state for 'tag' or 'type' or 'format' @param {String | Array} ignore @param {String} tag @param {String} type @param {String} format @returns {Boolean}
[ "Retrieve", "ignored", "state", "for", "tag", "or", "type", "or", "format" ]
7f9f6833d9ffee93cbf13d7e1183997904d055b6
https://github.com/popeindustries/inline-source/blob/7f9f6833d9ffee93cbf13d7e1183997904d055b6/lib/utils.js#L324-L338
19,154
mapbox/lambda-cfn
lib/artifacts/lambda.js
buildLambda
function buildLambda(options) { // crawl the module path to make sure the Lambda handler path is // set correctly: <functionDir>/function.fn let handlerPath = (module.parent.parent.parent.filename).split(path.sep).slice(-2).shift(); let fn = { Resources: {} }; // all function parameters available as environment variables fn.Resources[options.name] = { Type: 'AWS::Lambda::Function', Properties: { Code: { S3Bucket: cf.ref('CodeS3Bucket'), S3Key: cf.join([cf.ref('CodeS3Prefix'), cf.ref('GitSha'), '.zip']) }, Role: cf.if('HasDispatchSnsArn', cf.getAtt('LambdaCfnDispatchRole', 'Arn'), cf.getAtt('LambdaCfnRole', 'Arn')), Description: cf.stackName, Environment: { Variables: {} }, Handler: handlerPath + '/function.fn' } }; fn.Resources[options.name].Properties.Timeout = setLambdaTimeout(options.timeout); fn.Resources[options.name].Properties.MemorySize = setLambdaMemorySize(options.memorySize); fn.Resources[options.name].Properties.Runtime = setLambdaRuntine(options.runtime); return fn; }
javascript
function buildLambda(options) { // crawl the module path to make sure the Lambda handler path is // set correctly: <functionDir>/function.fn let handlerPath = (module.parent.parent.parent.filename).split(path.sep).slice(-2).shift(); let fn = { Resources: {} }; // all function parameters available as environment variables fn.Resources[options.name] = { Type: 'AWS::Lambda::Function', Properties: { Code: { S3Bucket: cf.ref('CodeS3Bucket'), S3Key: cf.join([cf.ref('CodeS3Prefix'), cf.ref('GitSha'), '.zip']) }, Role: cf.if('HasDispatchSnsArn', cf.getAtt('LambdaCfnDispatchRole', 'Arn'), cf.getAtt('LambdaCfnRole', 'Arn')), Description: cf.stackName, Environment: { Variables: {} }, Handler: handlerPath + '/function.fn' } }; fn.Resources[options.name].Properties.Timeout = setLambdaTimeout(options.timeout); fn.Resources[options.name].Properties.MemorySize = setLambdaMemorySize(options.memorySize); fn.Resources[options.name].Properties.Runtime = setLambdaRuntine(options.runtime); return fn; }
[ "function", "buildLambda", "(", "options", ")", "{", "// crawl the module path to make sure the Lambda handler path is", "// set correctly: <functionDir>/function.fn", "let", "handlerPath", "=", "(", "module", ".", "parent", ".", "parent", ".", "parent", ".", "filename", ")", ".", "split", "(", "path", ".", "sep", ")", ".", "slice", "(", "-", "2", ")", ".", "shift", "(", ")", ";", "let", "fn", "=", "{", "Resources", ":", "{", "}", "}", ";", "// all function parameters available as environment variables", "fn", ".", "Resources", "[", "options", ".", "name", "]", "=", "{", "Type", ":", "'AWS::Lambda::Function'", ",", "Properties", ":", "{", "Code", ":", "{", "S3Bucket", ":", "cf", ".", "ref", "(", "'CodeS3Bucket'", ")", ",", "S3Key", ":", "cf", ".", "join", "(", "[", "cf", ".", "ref", "(", "'CodeS3Prefix'", ")", ",", "cf", ".", "ref", "(", "'GitSha'", ")", ",", "'.zip'", "]", ")", "}", ",", "Role", ":", "cf", ".", "if", "(", "'HasDispatchSnsArn'", ",", "cf", ".", "getAtt", "(", "'LambdaCfnDispatchRole'", ",", "'Arn'", ")", ",", "cf", ".", "getAtt", "(", "'LambdaCfnRole'", ",", "'Arn'", ")", ")", ",", "Description", ":", "cf", ".", "stackName", ",", "Environment", ":", "{", "Variables", ":", "{", "}", "}", ",", "Handler", ":", "handlerPath", "+", "'/function.fn'", "}", "}", ";", "fn", ".", "Resources", "[", "options", ".", "name", "]", ".", "Properties", ".", "Timeout", "=", "setLambdaTimeout", "(", "options", ".", "timeout", ")", ";", "fn", ".", "Resources", "[", "options", ".", "name", "]", ".", "Properties", ".", "MemorySize", "=", "setLambdaMemorySize", "(", "options", ".", "memorySize", ")", ";", "fn", ".", "Resources", "[", "options", ".", "name", "]", ".", "Properties", ".", "Runtime", "=", "setLambdaRuntine", "(", "options", ".", "runtime", ")", ";", "return", "fn", ";", "}" ]
Build configuration for lambda This function creates - A lambda function @param options @returns {{Resources: {}}}
[ "Build", "configuration", "for", "lambda", "This", "function", "creates" ]
dcbc983625cf01c8d17f647a0066fe0a8fec24a1
https://github.com/mapbox/lambda-cfn/blob/dcbc983625cf01c8d17f647a0066fe0a8fec24a1/lib/artifacts/lambda.js#L19-L49
19,155
mapbox/lambda-cfn
lib/artifacts/destination.js
buildSnsDestination
function buildSnsDestination(options) { let sns = { Resources: {}, Parameters: {}, Variables: {}, Policies: [] }; if (options.destinations && options.destinations.sns) { for (let destination in options.destinations.sns) { sns.Parameters[destination + 'Email'] = { Type: 'String', Description: options.destinations.sns[destination].Description }; sns.Policies.push({ PolicyName: destination + 'TopicPermissions', PolicyDocument: { Statement: [ { Effect: 'Allow', Action: 'sns:Publish', Resource: cf.ref(options.name) } ] } }); sns.Resources[destination + 'Topic'] = { Type: 'AWS::SNS::Topic', Properties: { TopicName: cf.join('-', [cf.stackName, destination]), Subscription: [ { Endpoint: cf.ref(destination + 'Email'), Protocol: 'email' } ] } }; sns.Variables[destination + 'Topic'] = cf.ref(destination + 'Topic'); } return sns; } }
javascript
function buildSnsDestination(options) { let sns = { Resources: {}, Parameters: {}, Variables: {}, Policies: [] }; if (options.destinations && options.destinations.sns) { for (let destination in options.destinations.sns) { sns.Parameters[destination + 'Email'] = { Type: 'String', Description: options.destinations.sns[destination].Description }; sns.Policies.push({ PolicyName: destination + 'TopicPermissions', PolicyDocument: { Statement: [ { Effect: 'Allow', Action: 'sns:Publish', Resource: cf.ref(options.name) } ] } }); sns.Resources[destination + 'Topic'] = { Type: 'AWS::SNS::Topic', Properties: { TopicName: cf.join('-', [cf.stackName, destination]), Subscription: [ { Endpoint: cf.ref(destination + 'Email'), Protocol: 'email' } ] } }; sns.Variables[destination + 'Topic'] = cf.ref(destination + 'Topic'); } return sns; } }
[ "function", "buildSnsDestination", "(", "options", ")", "{", "let", "sns", "=", "{", "Resources", ":", "{", "}", ",", "Parameters", ":", "{", "}", ",", "Variables", ":", "{", "}", ",", "Policies", ":", "[", "]", "}", ";", "if", "(", "options", ".", "destinations", "&&", "options", ".", "destinations", ".", "sns", ")", "{", "for", "(", "let", "destination", "in", "options", ".", "destinations", ".", "sns", ")", "{", "sns", ".", "Parameters", "[", "destination", "+", "'Email'", "]", "=", "{", "Type", ":", "'String'", ",", "Description", ":", "options", ".", "destinations", ".", "sns", "[", "destination", "]", ".", "Description", "}", ";", "sns", ".", "Policies", ".", "push", "(", "{", "PolicyName", ":", "destination", "+", "'TopicPermissions'", ",", "PolicyDocument", ":", "{", "Statement", ":", "[", "{", "Effect", ":", "'Allow'", ",", "Action", ":", "'sns:Publish'", ",", "Resource", ":", "cf", ".", "ref", "(", "options", ".", "name", ")", "}", "]", "}", "}", ")", ";", "sns", ".", "Resources", "[", "destination", "+", "'Topic'", "]", "=", "{", "Type", ":", "'AWS::SNS::Topic'", ",", "Properties", ":", "{", "TopicName", ":", "cf", ".", "join", "(", "'-'", ",", "[", "cf", ".", "stackName", ",", "destination", "]", ")", ",", "Subscription", ":", "[", "{", "Endpoint", ":", "cf", ".", "ref", "(", "destination", "+", "'Email'", ")", ",", "Protocol", ":", "'email'", "}", "]", "}", "}", ";", "sns", ".", "Variables", "[", "destination", "+", "'Topic'", "]", "=", "cf", ".", "ref", "(", "destination", "+", "'Topic'", ")", ";", "}", "return", "sns", ";", "}", "}" ]
for porting existing lambda-cfn code over, if an SNS destination is defaulted, then use the ServiceAlarmEmail, else create a new Topic @param options
[ "for", "porting", "existing", "lambda", "-", "cfn", "code", "over", "if", "an", "SNS", "destination", "is", "defaulted", "then", "use", "the", "ServiceAlarmEmail", "else", "create", "a", "new", "Topic" ]
dcbc983625cf01c8d17f647a0066fe0a8fec24a1
https://github.com/mapbox/lambda-cfn/blob/dcbc983625cf01c8d17f647a0066fe0a8fec24a1/lib/artifacts/destination.js#L8-L54
19,156
mapbox/lambda-cfn
lib/artifacts/roles.js
buildRole
function buildRole(options, roleName='LambdaCfnRole') { let role = { Resources: {} }; role.Resources[roleName] = { Type: 'AWS::IAM::Role', Properties: { AssumeRolePolicyDocument: { Statement: [ { Sid: '', Effect: 'Allow', Principal: { Service: 'lambda.amazonaws.com' }, Action: 'sts:AssumeRole' }, { Sid: '', Effect: 'Allow', Principal: { Service: 'events.amazonaws.com' }, Action: 'sts:AssumeRole' } ] }, Path: '/', Policies: [ { PolicyName: 'basic', PolicyDocument: { Statement: [ { Effect: 'Allow', Action: [ 'logs:*' ], Resource: cf.join(['arn:aws:logs:*:', cf.accountId, ':*']) }, { Effect: 'Allow', Action: [ 'sns:Publish' ], Resource: cf.ref('ServiceAlarmSNSTopic') }, { Effect: 'Allow', Action: [ 'iam:SimulateCustomPolicy' ], Resource: '*' } ] } }, ] } }; if (options.eventSources && options.eventSources.webhook) { role.Resources[roleName].Properties.AssumeRolePolicyDocument.Statement.push({ Sid: '', Effect: 'Allow', Principal: { Service: 'apigateway.amazonaws.com' }, Action: 'sts:AssumeRole' }); } if (options.statements) { statementValidation(options); role.Resources[roleName].Properties.Policies.push({ PolicyName: options.name, PolicyDocument: { Statement: options.statements } }); } return role; }
javascript
function buildRole(options, roleName='LambdaCfnRole') { let role = { Resources: {} }; role.Resources[roleName] = { Type: 'AWS::IAM::Role', Properties: { AssumeRolePolicyDocument: { Statement: [ { Sid: '', Effect: 'Allow', Principal: { Service: 'lambda.amazonaws.com' }, Action: 'sts:AssumeRole' }, { Sid: '', Effect: 'Allow', Principal: { Service: 'events.amazonaws.com' }, Action: 'sts:AssumeRole' } ] }, Path: '/', Policies: [ { PolicyName: 'basic', PolicyDocument: { Statement: [ { Effect: 'Allow', Action: [ 'logs:*' ], Resource: cf.join(['arn:aws:logs:*:', cf.accountId, ':*']) }, { Effect: 'Allow', Action: [ 'sns:Publish' ], Resource: cf.ref('ServiceAlarmSNSTopic') }, { Effect: 'Allow', Action: [ 'iam:SimulateCustomPolicy' ], Resource: '*' } ] } }, ] } }; if (options.eventSources && options.eventSources.webhook) { role.Resources[roleName].Properties.AssumeRolePolicyDocument.Statement.push({ Sid: '', Effect: 'Allow', Principal: { Service: 'apigateway.amazonaws.com' }, Action: 'sts:AssumeRole' }); } if (options.statements) { statementValidation(options); role.Resources[roleName].Properties.Policies.push({ PolicyName: options.name, PolicyDocument: { Statement: options.statements } }); } return role; }
[ "function", "buildRole", "(", "options", ",", "roleName", "=", "'LambdaCfnRole'", ")", "{", "let", "role", "=", "{", "Resources", ":", "{", "}", "}", ";", "role", ".", "Resources", "[", "roleName", "]", "=", "{", "Type", ":", "'AWS::IAM::Role'", ",", "Properties", ":", "{", "AssumeRolePolicyDocument", ":", "{", "Statement", ":", "[", "{", "Sid", ":", "''", ",", "Effect", ":", "'Allow'", ",", "Principal", ":", "{", "Service", ":", "'lambda.amazonaws.com'", "}", ",", "Action", ":", "'sts:AssumeRole'", "}", ",", "{", "Sid", ":", "''", ",", "Effect", ":", "'Allow'", ",", "Principal", ":", "{", "Service", ":", "'events.amazonaws.com'", "}", ",", "Action", ":", "'sts:AssumeRole'", "}", "]", "}", ",", "Path", ":", "'/'", ",", "Policies", ":", "[", "{", "PolicyName", ":", "'basic'", ",", "PolicyDocument", ":", "{", "Statement", ":", "[", "{", "Effect", ":", "'Allow'", ",", "Action", ":", "[", "'logs:*'", "]", ",", "Resource", ":", "cf", ".", "join", "(", "[", "'arn:aws:logs:*:'", ",", "cf", ".", "accountId", ",", "':*'", "]", ")", "}", ",", "{", "Effect", ":", "'Allow'", ",", "Action", ":", "[", "'sns:Publish'", "]", ",", "Resource", ":", "cf", ".", "ref", "(", "'ServiceAlarmSNSTopic'", ")", "}", ",", "{", "Effect", ":", "'Allow'", ",", "Action", ":", "[", "'iam:SimulateCustomPolicy'", "]", ",", "Resource", ":", "'*'", "}", "]", "}", "}", ",", "]", "}", "}", ";", "if", "(", "options", ".", "eventSources", "&&", "options", ".", "eventSources", ".", "webhook", ")", "{", "role", ".", "Resources", "[", "roleName", "]", ".", "Properties", ".", "AssumeRolePolicyDocument", ".", "Statement", ".", "push", "(", "{", "Sid", ":", "''", ",", "Effect", ":", "'Allow'", ",", "Principal", ":", "{", "Service", ":", "'apigateway.amazonaws.com'", "}", ",", "Action", ":", "'sts:AssumeRole'", "}", ")", ";", "}", "if", "(", "options", ".", "statements", ")", "{", "statementValidation", "(", "options", ")", ";", "role", ".", "Resources", "[", "roleName", "]", ".", "Properties", ".", "Policies", ".", "push", "(", "{", "PolicyName", ":", "options", ".", "name", ",", "PolicyDocument", ":", "{", "Statement", ":", "options", ".", "statements", "}", "}", ")", ";", "}", "return", "role", ";", "}" ]
Build a role with permissions to lambda, CloudWatch events and API Gateways is needed.
[ "Build", "a", "role", "with", "permissions", "to", "lambda", "CloudWatch", "events", "and", "API", "Gateways", "is", "needed", "." ]
dcbc983625cf01c8d17f647a0066fe0a8fec24a1
https://github.com/mapbox/lambda-cfn/blob/dcbc983625cf01c8d17f647a0066fe0a8fec24a1/lib/artifacts/roles.js#L6-L91
19,157
mapbox/lambda-cfn
lib/artifacts/alarms.js
buildServiceAlarms
function buildServiceAlarms(options) { let alarms = { Parameters: {}, Resources: {}, Variables: {} }; let defaultAlarms = [ { AlarmName: 'Errors', MetricName: 'Errors', ComparisonOperator: 'GreaterThanThreshold' }, { AlarmName: 'NoInvocations', MetricName: 'Invocations', ComparisonOperator: 'LessThanThreshold' } ]; defaultAlarms.forEach(function(alarm) { alarms.Resources[options.name + 'Alarm' + alarm.AlarmName] = { Type: 'AWS::CloudWatch::Alarm', Properties: { EvaluationPeriods: `${setLambdaEvaluationPeriods(options.evaluationPeriods)}`, Statistic: 'Sum', Threshold: `${setLambdaThreshold(options.threshold)}`, AlarmDescription: 'https://github.com/mapbox/lambda-cfn/blob/master/alarms.md#' + alarm.AlarmName, Period: `${setLambdaPeriod(options.period)}`, AlarmActions: [cf.ref('ServiceAlarmSNSTopic')], Namespace: 'AWS/Lambda', Dimensions: [ { Name: 'FunctionName', Value: cf.ref(options.name) } ], ComparisonOperator: alarm.ComparisonOperator, MetricName: alarm.MetricName } }; }); alarms.Parameters = { ServiceAlarmEmail:{ Type: 'String', Description: 'Service alarm notifications will send to this email address' } }; alarms.Resources.ServiceAlarmSNSTopic = { Type: 'AWS::SNS::Topic', Properties: { TopicName: cf.join('-', [cf.stackName, 'ServiceAlarm']), Subscription: [ { Endpoint: cf.ref('ServiceAlarmEmail'), Protocol: 'email' } ] } }; alarms.Variables.ServiceAlarmSNSTopic = cf.ref('ServiceAlarmSNSTopic'); return alarms; }
javascript
function buildServiceAlarms(options) { let alarms = { Parameters: {}, Resources: {}, Variables: {} }; let defaultAlarms = [ { AlarmName: 'Errors', MetricName: 'Errors', ComparisonOperator: 'GreaterThanThreshold' }, { AlarmName: 'NoInvocations', MetricName: 'Invocations', ComparisonOperator: 'LessThanThreshold' } ]; defaultAlarms.forEach(function(alarm) { alarms.Resources[options.name + 'Alarm' + alarm.AlarmName] = { Type: 'AWS::CloudWatch::Alarm', Properties: { EvaluationPeriods: `${setLambdaEvaluationPeriods(options.evaluationPeriods)}`, Statistic: 'Sum', Threshold: `${setLambdaThreshold(options.threshold)}`, AlarmDescription: 'https://github.com/mapbox/lambda-cfn/blob/master/alarms.md#' + alarm.AlarmName, Period: `${setLambdaPeriod(options.period)}`, AlarmActions: [cf.ref('ServiceAlarmSNSTopic')], Namespace: 'AWS/Lambda', Dimensions: [ { Name: 'FunctionName', Value: cf.ref(options.name) } ], ComparisonOperator: alarm.ComparisonOperator, MetricName: alarm.MetricName } }; }); alarms.Parameters = { ServiceAlarmEmail:{ Type: 'String', Description: 'Service alarm notifications will send to this email address' } }; alarms.Resources.ServiceAlarmSNSTopic = { Type: 'AWS::SNS::Topic', Properties: { TopicName: cf.join('-', [cf.stackName, 'ServiceAlarm']), Subscription: [ { Endpoint: cf.ref('ServiceAlarmEmail'), Protocol: 'email' } ] } }; alarms.Variables.ServiceAlarmSNSTopic = cf.ref('ServiceAlarmSNSTopic'); return alarms; }
[ "function", "buildServiceAlarms", "(", "options", ")", "{", "let", "alarms", "=", "{", "Parameters", ":", "{", "}", ",", "Resources", ":", "{", "}", ",", "Variables", ":", "{", "}", "}", ";", "let", "defaultAlarms", "=", "[", "{", "AlarmName", ":", "'Errors'", ",", "MetricName", ":", "'Errors'", ",", "ComparisonOperator", ":", "'GreaterThanThreshold'", "}", ",", "{", "AlarmName", ":", "'NoInvocations'", ",", "MetricName", ":", "'Invocations'", ",", "ComparisonOperator", ":", "'LessThanThreshold'", "}", "]", ";", "defaultAlarms", ".", "forEach", "(", "function", "(", "alarm", ")", "{", "alarms", ".", "Resources", "[", "options", ".", "name", "+", "'Alarm'", "+", "alarm", ".", "AlarmName", "]", "=", "{", "Type", ":", "'AWS::CloudWatch::Alarm'", ",", "Properties", ":", "{", "EvaluationPeriods", ":", "`", "${", "setLambdaEvaluationPeriods", "(", "options", ".", "evaluationPeriods", ")", "}", "`", ",", "Statistic", ":", "'Sum'", ",", "Threshold", ":", "`", "${", "setLambdaThreshold", "(", "options", ".", "threshold", ")", "}", "`", ",", "AlarmDescription", ":", "'https://github.com/mapbox/lambda-cfn/blob/master/alarms.md#'", "+", "alarm", ".", "AlarmName", ",", "Period", ":", "`", "${", "setLambdaPeriod", "(", "options", ".", "period", ")", "}", "`", ",", "AlarmActions", ":", "[", "cf", ".", "ref", "(", "'ServiceAlarmSNSTopic'", ")", "]", ",", "Namespace", ":", "'AWS/Lambda'", ",", "Dimensions", ":", "[", "{", "Name", ":", "'FunctionName'", ",", "Value", ":", "cf", ".", "ref", "(", "options", ".", "name", ")", "}", "]", ",", "ComparisonOperator", ":", "alarm", ".", "ComparisonOperator", ",", "MetricName", ":", "alarm", ".", "MetricName", "}", "}", ";", "}", ")", ";", "alarms", ".", "Parameters", "=", "{", "ServiceAlarmEmail", ":", "{", "Type", ":", "'String'", ",", "Description", ":", "'Service alarm notifications will send to this email address'", "}", "}", ";", "alarms", ".", "Resources", ".", "ServiceAlarmSNSTopic", "=", "{", "Type", ":", "'AWS::SNS::Topic'", ",", "Properties", ":", "{", "TopicName", ":", "cf", ".", "join", "(", "'-'", ",", "[", "cf", ".", "stackName", ",", "'ServiceAlarm'", "]", ")", ",", "Subscription", ":", "[", "{", "Endpoint", ":", "cf", ".", "ref", "(", "'ServiceAlarmEmail'", ")", ",", "Protocol", ":", "'email'", "}", "]", "}", "}", ";", "alarms", ".", "Variables", ".", "ServiceAlarmSNSTopic", "=", "cf", ".", "ref", "(", "'ServiceAlarmSNSTopic'", ")", ";", "return", "alarms", ";", "}" ]
Create resources to send alarms on lambda errors and lambda no invocations. The resources which this function creates are: - Errors CloudWatch alarm - NoInvocations CloudWatch alarm - ServiceAlarmEmail parameter - Service Alarm SNS Topic @param options @returns An object with alarms artifacts
[ "Create", "resources", "to", "send", "alarms", "on", "lambda", "errors", "and", "lambda", "no", "invocations", "." ]
dcbc983625cf01c8d17f647a0066fe0a8fec24a1
https://github.com/mapbox/lambda-cfn/blob/dcbc983625cf01c8d17f647a0066fe0a8fec24a1/lib/artifacts/alarms.js#L22-L87
19,158
mapbox/lambda-cfn
lib/artifacts/cloudwatch.js
buildCloudwatchEvent
function buildCloudwatchEvent(options, functionType) { validateCloudWatchEvent(functionType, options.eventSources); let eventName = options.name + utils.capitalizeFirst(functionType); let event = { Resources: {} }; event.Resources[eventName + 'Permission'] = { Type: 'AWS::Lambda::Permission', Properties: { FunctionName: cf.getAtt(options.name, 'Arn'), Action: 'lambda:InvokeFunction', Principal: 'events.amazonaws.com', SourceArn: cf.getAtt(eventName + 'Rule', 'Arn') } }; event.Resources[eventName + 'Rule'] = { Type: 'AWS::Events::Rule', Properties: { RoleArn: cf.if('HasDispatchSnsArn', cf.getAtt('LambdaCfnDispatchRole', 'Arn'), cf.getAtt('LambdaCfnRole', 'Arn')), State: 'ENABLED', Targets: [ { Arn: cf.getAtt(options.name, 'Arn'), Id: options.name } ] } }; if (functionType === 'cloudwatchEvent') { event.Resources[eventName + 'Rule'].Properties.EventPattern = options.eventSources.cloudwatchEvent.eventPattern; } else { event.Resources[eventName + 'Rule'].Properties.ScheduleExpression = options.eventSources.schedule.expression; } return event; }
javascript
function buildCloudwatchEvent(options, functionType) { validateCloudWatchEvent(functionType, options.eventSources); let eventName = options.name + utils.capitalizeFirst(functionType); let event = { Resources: {} }; event.Resources[eventName + 'Permission'] = { Type: 'AWS::Lambda::Permission', Properties: { FunctionName: cf.getAtt(options.name, 'Arn'), Action: 'lambda:InvokeFunction', Principal: 'events.amazonaws.com', SourceArn: cf.getAtt(eventName + 'Rule', 'Arn') } }; event.Resources[eventName + 'Rule'] = { Type: 'AWS::Events::Rule', Properties: { RoleArn: cf.if('HasDispatchSnsArn', cf.getAtt('LambdaCfnDispatchRole', 'Arn'), cf.getAtt('LambdaCfnRole', 'Arn')), State: 'ENABLED', Targets: [ { Arn: cf.getAtt(options.name, 'Arn'), Id: options.name } ] } }; if (functionType === 'cloudwatchEvent') { event.Resources[eventName + 'Rule'].Properties.EventPattern = options.eventSources.cloudwatchEvent.eventPattern; } else { event.Resources[eventName + 'Rule'].Properties.ScheduleExpression = options.eventSources.schedule.expression; } return event; }
[ "function", "buildCloudwatchEvent", "(", "options", ",", "functionType", ")", "{", "validateCloudWatchEvent", "(", "functionType", ",", "options", ".", "eventSources", ")", ";", "let", "eventName", "=", "options", ".", "name", "+", "utils", ".", "capitalizeFirst", "(", "functionType", ")", ";", "let", "event", "=", "{", "Resources", ":", "{", "}", "}", ";", "event", ".", "Resources", "[", "eventName", "+", "'Permission'", "]", "=", "{", "Type", ":", "'AWS::Lambda::Permission'", ",", "Properties", ":", "{", "FunctionName", ":", "cf", ".", "getAtt", "(", "options", ".", "name", ",", "'Arn'", ")", ",", "Action", ":", "'lambda:InvokeFunction'", ",", "Principal", ":", "'events.amazonaws.com'", ",", "SourceArn", ":", "cf", ".", "getAtt", "(", "eventName", "+", "'Rule'", ",", "'Arn'", ")", "}", "}", ";", "event", ".", "Resources", "[", "eventName", "+", "'Rule'", "]", "=", "{", "Type", ":", "'AWS::Events::Rule'", ",", "Properties", ":", "{", "RoleArn", ":", "cf", ".", "if", "(", "'HasDispatchSnsArn'", ",", "cf", ".", "getAtt", "(", "'LambdaCfnDispatchRole'", ",", "'Arn'", ")", ",", "cf", ".", "getAtt", "(", "'LambdaCfnRole'", ",", "'Arn'", ")", ")", ",", "State", ":", "'ENABLED'", ",", "Targets", ":", "[", "{", "Arn", ":", "cf", ".", "getAtt", "(", "options", ".", "name", ",", "'Arn'", ")", ",", "Id", ":", "options", ".", "name", "}", "]", "}", "}", ";", "if", "(", "functionType", "===", "'cloudwatchEvent'", ")", "{", "event", ".", "Resources", "[", "eventName", "+", "'Rule'", "]", ".", "Properties", ".", "EventPattern", "=", "options", ".", "eventSources", ".", "cloudwatchEvent", ".", "eventPattern", ";", "}", "else", "{", "event", ".", "Resources", "[", "eventName", "+", "'Rule'", "]", ".", "Properties", ".", "ScheduleExpression", "=", "options", ".", "eventSources", ".", "schedule", ".", "expression", ";", "}", "return", "event", ";", "}" ]
Build CloudWatch events This function creates - A Permission to access lambda invokation events - A EventPattern rule in case of cloudwatchEvent function type - A Schedule Expression in case of schedule function type. @param options @param functionType
[ "Build", "CloudWatch", "events" ]
dcbc983625cf01c8d17f647a0066fe0a8fec24a1
https://github.com/mapbox/lambda-cfn/blob/dcbc983625cf01c8d17f647a0066fe0a8fec24a1/lib/artifacts/cloudwatch.js#L15-L54
19,159
mapbox/lambda-cfn
lib/cfn.js
compileFunction
function compileFunction() { let template = {}; if (arguments) { for (let arg of arguments) { mergeArgumentsTemplate(template, arg, 'Metadata'); mergeArgumentsTemplate(template, arg, 'Parameters'); mergeArgumentsTemplate(template, arg, 'Mappings'); mergeArgumentsTemplate(template, arg, 'Conditions'); mergeArgumentsTemplate(template, arg, 'Resources'); mergeArgumentsTemplate(template, arg, 'Outputs'); mergeArgumentsTemplate(template, arg, 'Variables'); let areValidPolicies = arg.Policies && Array.isArray(arg.Policies) && arg.Policies.length > 0; if (areValidPolicies) { if (!template.Policies) { template.Policies = []; } template.Policies = template.Policies.concat(arg.Policies); } } } return template; }
javascript
function compileFunction() { let template = {}; if (arguments) { for (let arg of arguments) { mergeArgumentsTemplate(template, arg, 'Metadata'); mergeArgumentsTemplate(template, arg, 'Parameters'); mergeArgumentsTemplate(template, arg, 'Mappings'); mergeArgumentsTemplate(template, arg, 'Conditions'); mergeArgumentsTemplate(template, arg, 'Resources'); mergeArgumentsTemplate(template, arg, 'Outputs'); mergeArgumentsTemplate(template, arg, 'Variables'); let areValidPolicies = arg.Policies && Array.isArray(arg.Policies) && arg.Policies.length > 0; if (areValidPolicies) { if (!template.Policies) { template.Policies = []; } template.Policies = template.Policies.concat(arg.Policies); } } } return template; }
[ "function", "compileFunction", "(", ")", "{", "let", "template", "=", "{", "}", ";", "if", "(", "arguments", ")", "{", "for", "(", "let", "arg", "of", "arguments", ")", "{", "mergeArgumentsTemplate", "(", "template", ",", "arg", ",", "'Metadata'", ")", ";", "mergeArgumentsTemplate", "(", "template", ",", "arg", ",", "'Parameters'", ")", ";", "mergeArgumentsTemplate", "(", "template", ",", "arg", ",", "'Mappings'", ")", ";", "mergeArgumentsTemplate", "(", "template", ",", "arg", ",", "'Conditions'", ")", ";", "mergeArgumentsTemplate", "(", "template", ",", "arg", ",", "'Resources'", ")", ";", "mergeArgumentsTemplate", "(", "template", ",", "arg", ",", "'Outputs'", ")", ";", "mergeArgumentsTemplate", "(", "template", ",", "arg", ",", "'Variables'", ")", ";", "let", "areValidPolicies", "=", "arg", ".", "Policies", "&&", "Array", ".", "isArray", "(", "arg", ".", "Policies", ")", "&&", "arg", ".", "Policies", ".", "length", ">", "0", ";", "if", "(", "areValidPolicies", ")", "{", "if", "(", "!", "template", ".", "Policies", ")", "{", "template", ".", "Policies", "=", "[", "]", ";", "}", "template", ".", "Policies", "=", "template", ".", "Policies", ".", "concat", "(", "arg", ".", "Policies", ")", ";", "}", "}", "}", "return", "template", ";", "}" ]
Takes a list of object and merges them into a template stub
[ "Takes", "a", "list", "of", "object", "and", "merges", "them", "into", "a", "template", "stub" ]
dcbc983625cf01c8d17f647a0066fe0a8fec24a1
https://github.com/mapbox/lambda-cfn/blob/dcbc983625cf01c8d17f647a0066fe0a8fec24a1/lib/cfn.js#L140-L163
19,160
mapbox/lambda-cfn
lib/cfn.js
mergeArgumentsTemplate
function mergeArgumentsTemplate(template, arg, propertyName) { if (!template.hasOwnProperty(propertyName)) { template[propertyName] = {}; } if (arg.hasOwnProperty(propertyName)) { if (!arg[propertyName]) { arg[propertyName] = {}; } Object.keys(arg[propertyName]).forEach((key) => { if (template[propertyName].hasOwnProperty(key)) { throw new Error(propertyName + ' name used more than once: ' + key); } template[propertyName][key] = JSON.parse(JSON.stringify(arg[propertyName][key])); }); } }
javascript
function mergeArgumentsTemplate(template, arg, propertyName) { if (!template.hasOwnProperty(propertyName)) { template[propertyName] = {}; } if (arg.hasOwnProperty(propertyName)) { if (!arg[propertyName]) { arg[propertyName] = {}; } Object.keys(arg[propertyName]).forEach((key) => { if (template[propertyName].hasOwnProperty(key)) { throw new Error(propertyName + ' name used more than once: ' + key); } template[propertyName][key] = JSON.parse(JSON.stringify(arg[propertyName][key])); }); } }
[ "function", "mergeArgumentsTemplate", "(", "template", ",", "arg", ",", "propertyName", ")", "{", "if", "(", "!", "template", ".", "hasOwnProperty", "(", "propertyName", ")", ")", "{", "template", "[", "propertyName", "]", "=", "{", "}", ";", "}", "if", "(", "arg", ".", "hasOwnProperty", "(", "propertyName", ")", ")", "{", "if", "(", "!", "arg", "[", "propertyName", "]", ")", "{", "arg", "[", "propertyName", "]", "=", "{", "}", ";", "}", "Object", ".", "keys", "(", "arg", "[", "propertyName", "]", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "if", "(", "template", "[", "propertyName", "]", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "throw", "new", "Error", "(", "propertyName", "+", "' name used more than once: '", "+", "key", ")", ";", "}", "template", "[", "propertyName", "]", "[", "key", "]", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "arg", "[", "propertyName", "]", "[", "key", "]", ")", ")", ";", "}", ")", ";", "}", "}" ]
Merge arguments with template arguments @param template @param arg @param propertyName
[ "Merge", "arguments", "with", "template", "arguments" ]
dcbc983625cf01c8d17f647a0066fe0a8fec24a1
https://github.com/mapbox/lambda-cfn/blob/dcbc983625cf01c8d17f647a0066fe0a8fec24a1/lib/cfn.js#L171-L190
19,161
mapbox/lambda-cfn
lib/artifacts/dispatch.js
addDispatchSupport
function addDispatchSupport(template, options) { if (!template.Conditions) { template.Conditions = {}; } if (!('HasDispatchSnsArn' in template.Conditions)) { template.Conditions['HasDispatchSnsArn'] = { 'Fn::Not': [ { 'Fn::Equals': [ '', cf.ref('DispatchSnsArn') ] } ] }; } template.Parameters.DispatchSnsArn = { Type: 'String', Description: 'Dispatch SNS ARN (Optional)' }; // Why we need other role for Dispatch? // We can not use conditionals at policy level. We create a new role with all the properties of the // default role plus the conditional and policy to send messages to DispatchSnsArn. let dispatchRole = role.buildRole(options, 'LambdaCfnDispatchRole'); template.Resources['LambdaCfnDispatchRole'] = dispatchRole.Resources['LambdaCfnDispatchRole']; template.Resources['LambdaCfnDispatchRole'].Condition = 'HasDispatchSnsArn'; template.Resources['LambdaCfnDispatchRole'].Properties.Policies[0].PolicyDocument.Statement.push( { Effect: 'Allow', Action: [ 'sns:Publish' ], Resource: cf.ref('DispatchSnsArn') } ); }
javascript
function addDispatchSupport(template, options) { if (!template.Conditions) { template.Conditions = {}; } if (!('HasDispatchSnsArn' in template.Conditions)) { template.Conditions['HasDispatchSnsArn'] = { 'Fn::Not': [ { 'Fn::Equals': [ '', cf.ref('DispatchSnsArn') ] } ] }; } template.Parameters.DispatchSnsArn = { Type: 'String', Description: 'Dispatch SNS ARN (Optional)' }; // Why we need other role for Dispatch? // We can not use conditionals at policy level. We create a new role with all the properties of the // default role plus the conditional and policy to send messages to DispatchSnsArn. let dispatchRole = role.buildRole(options, 'LambdaCfnDispatchRole'); template.Resources['LambdaCfnDispatchRole'] = dispatchRole.Resources['LambdaCfnDispatchRole']; template.Resources['LambdaCfnDispatchRole'].Condition = 'HasDispatchSnsArn'; template.Resources['LambdaCfnDispatchRole'].Properties.Policies[0].PolicyDocument.Statement.push( { Effect: 'Allow', Action: [ 'sns:Publish' ], Resource: cf.ref('DispatchSnsArn') } ); }
[ "function", "addDispatchSupport", "(", "template", ",", "options", ")", "{", "if", "(", "!", "template", ".", "Conditions", ")", "{", "template", ".", "Conditions", "=", "{", "}", ";", "}", "if", "(", "!", "(", "'HasDispatchSnsArn'", "in", "template", ".", "Conditions", ")", ")", "{", "template", ".", "Conditions", "[", "'HasDispatchSnsArn'", "]", "=", "{", "'Fn::Not'", ":", "[", "{", "'Fn::Equals'", ":", "[", "''", ",", "cf", ".", "ref", "(", "'DispatchSnsArn'", ")", "]", "}", "]", "}", ";", "}", "template", ".", "Parameters", ".", "DispatchSnsArn", "=", "{", "Type", ":", "'String'", ",", "Description", ":", "'Dispatch SNS ARN (Optional)'", "}", ";", "// Why we need other role for Dispatch?", "// We can not use conditionals at policy level. We create a new role with all the properties of the", "// default role plus the conditional and policy to send messages to DispatchSnsArn.", "let", "dispatchRole", "=", "role", ".", "buildRole", "(", "options", ",", "'LambdaCfnDispatchRole'", ")", ";", "template", ".", "Resources", "[", "'LambdaCfnDispatchRole'", "]", "=", "dispatchRole", ".", "Resources", "[", "'LambdaCfnDispatchRole'", "]", ";", "template", ".", "Resources", "[", "'LambdaCfnDispatchRole'", "]", ".", "Condition", "=", "'HasDispatchSnsArn'", ";", "template", ".", "Resources", "[", "'LambdaCfnDispatchRole'", "]", ".", "Properties", ".", "Policies", "[", "0", "]", ".", "PolicyDocument", ".", "Statement", ".", "push", "(", "{", "Effect", ":", "'Allow'", ",", "Action", ":", "[", "'sns:Publish'", "]", ",", "Resource", ":", "cf", ".", "ref", "(", "'DispatchSnsArn'", ")", "}", ")", ";", "}" ]
Create all that is need it to send messages to Dispatch SNS Resources created by this function are - HasDispatchSnsArn conditional - DispatchSnsArn parameter - LambdaCfnDispatchRole @param template @param options
[ "Create", "all", "that", "is", "need", "it", "to", "send", "messages", "to", "Dispatch", "SNS", "Resources", "created", "by", "this", "function", "are" ]
dcbc983625cf01c8d17f647a0066fe0a8fec24a1
https://github.com/mapbox/lambda-cfn/blob/dcbc983625cf01c8d17f647a0066fe0a8fec24a1/lib/artifacts/dispatch.js#L15-L53
19,162
nicdex/node-eventstore-client
src/eventData.js
EventData
function EventData(eventId, type, isJson, data, metadata) { if (!isValidId(eventId)) throw new TypeError("eventId must be a string containing a UUID."); if (typeof type !== 'string' || type === '') throw new TypeError("type must be a non-empty string."); if (isJson && typeof isJson !== 'boolean') throw new TypeError("isJson must be a boolean."); if (data && !Buffer.isBuffer(data)) throw new TypeError("data must be a Buffer."); if (metadata && !Buffer.isBuffer(metadata)) throw new TypeError("metadata must be a Buffer."); this.eventId = eventId; this.type = type; this.isJson = isJson || false; this.data = data || new Buffer(0); this.metadata = metadata || new Buffer(0); Object.freeze(this); }
javascript
function EventData(eventId, type, isJson, data, metadata) { if (!isValidId(eventId)) throw new TypeError("eventId must be a string containing a UUID."); if (typeof type !== 'string' || type === '') throw new TypeError("type must be a non-empty string."); if (isJson && typeof isJson !== 'boolean') throw new TypeError("isJson must be a boolean."); if (data && !Buffer.isBuffer(data)) throw new TypeError("data must be a Buffer."); if (metadata && !Buffer.isBuffer(metadata)) throw new TypeError("metadata must be a Buffer."); this.eventId = eventId; this.type = type; this.isJson = isJson || false; this.data = data || new Buffer(0); this.metadata = metadata || new Buffer(0); Object.freeze(this); }
[ "function", "EventData", "(", "eventId", ",", "type", ",", "isJson", ",", "data", ",", "metadata", ")", "{", "if", "(", "!", "isValidId", "(", "eventId", ")", ")", "throw", "new", "TypeError", "(", "\"eventId must be a string containing a UUID.\"", ")", ";", "if", "(", "typeof", "type", "!==", "'string'", "||", "type", "===", "''", ")", "throw", "new", "TypeError", "(", "\"type must be a non-empty string.\"", ")", ";", "if", "(", "isJson", "&&", "typeof", "isJson", "!==", "'boolean'", ")", "throw", "new", "TypeError", "(", "\"isJson must be a boolean.\"", ")", ";", "if", "(", "data", "&&", "!", "Buffer", ".", "isBuffer", "(", "data", ")", ")", "throw", "new", "TypeError", "(", "\"data must be a Buffer.\"", ")", ";", "if", "(", "metadata", "&&", "!", "Buffer", ".", "isBuffer", "(", "metadata", ")", ")", "throw", "new", "TypeError", "(", "\"metadata must be a Buffer.\"", ")", ";", "this", ".", "eventId", "=", "eventId", ";", "this", ".", "type", "=", "type", ";", "this", ".", "isJson", "=", "isJson", "||", "false", ";", "this", ".", "data", "=", "data", "||", "new", "Buffer", "(", "0", ")", ";", "this", ".", "metadata", "=", "metadata", "||", "new", "Buffer", "(", "0", ")", ";", "Object", ".", "freeze", "(", "this", ")", ";", "}" ]
Create an EventData @private @param {string} eventId @param {string} type @param {boolean} [isJson] @param {Buffer} [data] @param {Buffer} [metadata] @constructor
[ "Create", "an", "EventData" ]
7e5327c278729eeeddf8fe2f51b7d78cb0c3d4b5
https://github.com/nicdex/node-eventstore-client/blob/7e5327c278729eeeddf8fe2f51b7d78cb0c3d4b5/src/eventData.js#L17-L30
19,163
nicdex/node-eventstore-client
src/common/bufferSegment.js
BufferSegment
function BufferSegment(buf, offset, count) { if (!Buffer.isBuffer(buf)) throw new TypeError('buf must be a buffer'); this.buffer = buf; this.offset = offset || 0; this.count = count || buf.length; }
javascript
function BufferSegment(buf, offset, count) { if (!Buffer.isBuffer(buf)) throw new TypeError('buf must be a buffer'); this.buffer = buf; this.offset = offset || 0; this.count = count || buf.length; }
[ "function", "BufferSegment", "(", "buf", ",", "offset", ",", "count", ")", "{", "if", "(", "!", "Buffer", ".", "isBuffer", "(", "buf", ")", ")", "throw", "new", "TypeError", "(", "'buf must be a buffer'", ")", ";", "this", ".", "buffer", "=", "buf", ";", "this", ".", "offset", "=", "offset", "||", "0", ";", "this", ".", "count", "=", "count", "||", "buf", ".", "length", ";", "}" ]
Create a buffer segment @private @param {Buffer} buf @param {number} [offset] @param {number} [count] @constructor
[ "Create", "a", "buffer", "segment" ]
7e5327c278729eeeddf8fe2f51b7d78cb0c3d4b5
https://github.com/nicdex/node-eventstore-client/blob/7e5327c278729eeeddf8fe2f51b7d78cb0c3d4b5/src/common/bufferSegment.js#L9-L15
19,164
nicdex/node-eventstore-client
src/projections/projectionsManager.js
ProjectionsManager
function ProjectionsManager(log, httpEndPoint, operationTimeout) { ensure.notNull(log, "log"); ensure.notNull(httpEndPoint, "httpEndPoint"); this._client = new ProjectionsClient(log, operationTimeout); this._httpEndPoint = httpEndPoint; }
javascript
function ProjectionsManager(log, httpEndPoint, operationTimeout) { ensure.notNull(log, "log"); ensure.notNull(httpEndPoint, "httpEndPoint"); this._client = new ProjectionsClient(log, operationTimeout); this._httpEndPoint = httpEndPoint; }
[ "function", "ProjectionsManager", "(", "log", ",", "httpEndPoint", ",", "operationTimeout", ")", "{", "ensure", ".", "notNull", "(", "log", ",", "\"log\"", ")", ";", "ensure", ".", "notNull", "(", "httpEndPoint", ",", "\"httpEndPoint\"", ")", ";", "this", ".", "_client", "=", "new", "ProjectionsClient", "(", "log", ",", "operationTimeout", ")", ";", "this", ".", "_httpEndPoint", "=", "httpEndPoint", ";", "}" ]
Creates a new instance of ProjectionsManager. @param {Logger} log Instance of Logger to use for logging. @param {string} httpEndPoint HTTP endpoint of an Event Store server. @param {number} operationTimeout Operation timeout in milliseconds. @constructor
[ "Creates", "a", "new", "instance", "of", "ProjectionsManager", "." ]
7e5327c278729eeeddf8fe2f51b7d78cb0c3d4b5
https://github.com/nicdex/node-eventstore-client/blob/7e5327c278729eeeddf8fe2f51b7d78cb0c3d4b5/src/projections/projectionsManager.js#L11-L16
19,165
bradmartin/nativescript-drawingpad
demo/app/main-page.js
pageLoaded
function pageLoaded(args) { // Get the event sender var page = args.object; page.bindingContext = new main_view_model_1.HelloWorldModel(page); if (platform_1.isAndroid && platform_1.device.sdkVersion >= '21') { var window_1 = application_1.android.startActivity.getWindow(); window_1.setStatusBarColor(new color_1.Color('#336699').android); } }
javascript
function pageLoaded(args) { // Get the event sender var page = args.object; page.bindingContext = new main_view_model_1.HelloWorldModel(page); if (platform_1.isAndroid && platform_1.device.sdkVersion >= '21') { var window_1 = application_1.android.startActivity.getWindow(); window_1.setStatusBarColor(new color_1.Color('#336699').android); } }
[ "function", "pageLoaded", "(", "args", ")", "{", "// Get the event sender", "var", "page", "=", "args", ".", "object", ";", "page", ".", "bindingContext", "=", "new", "main_view_model_1", ".", "HelloWorldModel", "(", "page", ")", ";", "if", "(", "platform_1", ".", "isAndroid", "&&", "platform_1", ".", "device", ".", "sdkVersion", ">=", "'21'", ")", "{", "var", "window_1", "=", "application_1", ".", "android", ".", "startActivity", ".", "getWindow", "(", ")", ";", "window_1", ".", "setStatusBarColor", "(", "new", "color_1", ".", "Color", "(", "'#336699'", ")", ".", "android", ")", ";", "}", "}" ]
Event handler for Page "loaded" event attached in main-page.xml
[ "Event", "handler", "for", "Page", "loaded", "event", "attached", "in", "main", "-", "page", ".", "xml" ]
b84a3227a74100a78c3b1b0d0dad9041d984de45
https://github.com/bradmartin/nativescript-drawingpad/blob/b84a3227a74100a78c3b1b0d0dad9041d984de45/demo/app/main-page.js#L8-L16
19,166
tkadlec/grunt-perfbudget
tasks/perfbudget.js
function(data) { var budget = options.budget, summary = data.data.summary, median = options.repeatView ? data.data.median.repeatView : data.data.median.firstView, pass = true, str = ""; for (var item in budget) { // make sure this is objects own property and not inherited if (budget.hasOwnProperty(item)) { //make sure it exists if (budget[item] !== '' && median.hasOwnProperty(item)) { if (median[item] > budget[item]) { pass = false; str += item + ': ' + median[item] + ' [FAIL]. Budget is ' + budget[item] + '\n'; } else { str += item + ': ' + median[item] + ' [PASS]. Budget is ' + budget[item] + '\n'; } } } } //save the file before failing or passing var output = options.output; if (typeof output !== 'undefined') { grunt.log.ok('Writing file: ' + output); grunt.file.write(output, JSON.stringify(data)); } // //output our header and results if (!pass) { grunt.log.error('\n\n-----------------------------------------------' + '\nTest for ' + options.url + ' \t FAILED' + '\n-----------------------------------------------\n\n'); grunt.log.error(str); grunt.log.error('Summary: ' + summary); done(false); } else { grunt.log.ok('\n\n-----------------------------------------------' + '\nTest for ' + options.url + ' \t PASSED' + '\n-----------------------------------------------\n\n'); grunt.log.ok(str); grunt.log.ok('Summary: ' + summary); done(); } }
javascript
function(data) { var budget = options.budget, summary = data.data.summary, median = options.repeatView ? data.data.median.repeatView : data.data.median.firstView, pass = true, str = ""; for (var item in budget) { // make sure this is objects own property and not inherited if (budget.hasOwnProperty(item)) { //make sure it exists if (budget[item] !== '' && median.hasOwnProperty(item)) { if (median[item] > budget[item]) { pass = false; str += item + ': ' + median[item] + ' [FAIL]. Budget is ' + budget[item] + '\n'; } else { str += item + ': ' + median[item] + ' [PASS]. Budget is ' + budget[item] + '\n'; } } } } //save the file before failing or passing var output = options.output; if (typeof output !== 'undefined') { grunt.log.ok('Writing file: ' + output); grunt.file.write(output, JSON.stringify(data)); } // //output our header and results if (!pass) { grunt.log.error('\n\n-----------------------------------------------' + '\nTest for ' + options.url + ' \t FAILED' + '\n-----------------------------------------------\n\n'); grunt.log.error(str); grunt.log.error('Summary: ' + summary); done(false); } else { grunt.log.ok('\n\n-----------------------------------------------' + '\nTest for ' + options.url + ' \t PASSED' + '\n-----------------------------------------------\n\n'); grunt.log.ok(str); grunt.log.ok('Summary: ' + summary); done(); } }
[ "function", "(", "data", ")", "{", "var", "budget", "=", "options", ".", "budget", ",", "summary", "=", "data", ".", "data", ".", "summary", ",", "median", "=", "options", ".", "repeatView", "?", "data", ".", "data", ".", "median", ".", "repeatView", ":", "data", ".", "data", ".", "median", ".", "firstView", ",", "pass", "=", "true", ",", "str", "=", "\"\"", ";", "for", "(", "var", "item", "in", "budget", ")", "{", "// make sure this is objects own property and not inherited", "if", "(", "budget", ".", "hasOwnProperty", "(", "item", ")", ")", "{", "//make sure it exists", "if", "(", "budget", "[", "item", "]", "!==", "''", "&&", "median", ".", "hasOwnProperty", "(", "item", ")", ")", "{", "if", "(", "median", "[", "item", "]", ">", "budget", "[", "item", "]", ")", "{", "pass", "=", "false", ";", "str", "+=", "item", "+", "': '", "+", "median", "[", "item", "]", "+", "' [FAIL]. Budget is '", "+", "budget", "[", "item", "]", "+", "'\\n'", ";", "}", "else", "{", "str", "+=", "item", "+", "': '", "+", "median", "[", "item", "]", "+", "' [PASS]. Budget is '", "+", "budget", "[", "item", "]", "+", "'\\n'", ";", "}", "}", "}", "}", "//save the file before failing or passing", "var", "output", "=", "options", ".", "output", ";", "if", "(", "typeof", "output", "!==", "'undefined'", ")", "{", "grunt", ".", "log", ".", "ok", "(", "'Writing file: '", "+", "output", ")", ";", "grunt", ".", "file", ".", "write", "(", "output", ",", "JSON", ".", "stringify", "(", "data", ")", ")", ";", "}", "//", "//output our header and results", "if", "(", "!", "pass", ")", "{", "grunt", ".", "log", ".", "error", "(", "'\\n\\n-----------------------------------------------'", "+", "'\\nTest for '", "+", "options", ".", "url", "+", "' \\t FAILED'", "+", "'\\n-----------------------------------------------\\n\\n'", ")", ";", "grunt", ".", "log", ".", "error", "(", "str", ")", ";", "grunt", ".", "log", ".", "error", "(", "'Summary: '", "+", "summary", ")", ";", "done", "(", "false", ")", ";", "}", "else", "{", "grunt", ".", "log", ".", "ok", "(", "'\\n\\n-----------------------------------------------'", "+", "'\\nTest for '", "+", "options", ".", "url", "+", "' \\t PASSED'", "+", "'\\n-----------------------------------------------\\n\\n'", ")", ";", "grunt", ".", "log", ".", "ok", "(", "str", ")", ";", "grunt", ".", "log", ".", "ok", "(", "'Summary: '", "+", "summary", ")", ";", "done", "(", ")", ";", "}", "}" ]
takes the data returned by wpt.getTestResults and compares to our budget thresholds
[ "takes", "the", "data", "returned", "by", "wpt", ".", "getTestResults", "and", "compares", "to", "our", "budget", "thresholds" ]
a6198d42771c6a995d65b64205e584b78f686366
https://github.com/tkadlec/grunt-perfbudget/blob/a6198d42771c6a995d65b64205e584b78f686366/tasks/perfbudget.js#L60-L107
19,167
bitovi/documentjs
lib/stmd.js
function(re, s, offset) { var res = s.slice(offset).match(re); if (res) { return offset + res.index; } else { return null; } }
javascript
function(re, s, offset) { var res = s.slice(offset).match(re); if (res) { return offset + res.index; } else { return null; } }
[ "function", "(", "re", ",", "s", ",", "offset", ")", "{", "var", "res", "=", "s", ".", "slice", "(", "offset", ")", ".", "match", "(", "re", ")", ";", "if", "(", "res", ")", "{", "return", "offset", "+", "res", ".", "index", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Attempt to match a regex in string s at offset offset. Return index of match or null.
[ "Attempt", "to", "match", "a", "regex", "in", "string", "s", "at", "offset", "offset", ".", "Return", "index", "of", "match", "or", "null", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L98-L105
19,168
bitovi/documentjs
lib/stmd.js
function(text) { if (text.indexOf('\t') == -1) { return text; } else { var lastStop = 0; return text.replace(reAllTab, function(match, offset) { var result = ' '.slice((offset - lastStop) % 4); lastStop = offset + 1; return result; }); } }
javascript
function(text) { if (text.indexOf('\t') == -1) { return text; } else { var lastStop = 0; return text.replace(reAllTab, function(match, offset) { var result = ' '.slice((offset - lastStop) % 4); lastStop = offset + 1; return result; }); } }
[ "function", "(", "text", ")", "{", "if", "(", "text", ".", "indexOf", "(", "'\\t'", ")", "==", "-", "1", ")", "{", "return", "text", ";", "}", "else", "{", "var", "lastStop", "=", "0", ";", "return", "text", ".", "replace", "(", "reAllTab", ",", "function", "(", "match", ",", "offset", ")", "{", "var", "result", "=", "' '", ".", "slice", "(", "(", "offset", "-", "lastStop", ")", "%", "4", ")", ";", "lastStop", "=", "offset", "+", "1", ";", "return", "result", ";", "}", ")", ";", "}", "}" ]
Convert tabs to spaces on each line using a 4-space tab stop.
[ "Convert", "tabs", "to", "spaces", "on", "each", "line", "using", "a", "4", "-", "space", "tab", "stop", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L108-L119
19,169
bitovi/documentjs
lib/stmd.js
function(re) { var match = re.exec(this.subject.slice(this.pos)); if (match) { this.pos += match.index + match[0].length; return match[0]; } else { return null; } }
javascript
function(re) { var match = re.exec(this.subject.slice(this.pos)); if (match) { this.pos += match.index + match[0].length; return match[0]; } else { return null; } }
[ "function", "(", "re", ")", "{", "var", "match", "=", "re", ".", "exec", "(", "this", ".", "subject", ".", "slice", "(", "this", ".", "pos", ")", ")", ";", "if", "(", "match", ")", "{", "this", ".", "pos", "+=", "match", ".", "index", "+", "match", "[", "0", "]", ".", "length", ";", "return", "match", "[", "0", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
If re matches at current position in the subject, advance position in subject and return the match; otherwise return null.
[ "If", "re", "matches", "at", "current", "position", "in", "the", "subject", "advance", "position", "in", "subject", "and", "return", "the", "match", ";", "otherwise", "return", "null", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L129-L137
19,170
bitovi/documentjs
lib/stmd.js
function(inlines) { var startpos = this.pos; var ticks = this.match(/^`+/); if (!ticks) { return 0; } var afterOpenTicks = this.pos; var foundCode = false; var match; while (!foundCode && (match = this.match(/`+/m))) { if (match == ticks) { inlines.push({ t: 'Code', c: this.subject.slice(afterOpenTicks, this.pos - ticks.length) .replace(/[ \n]+/g,' ') .trim() }); return (this.pos - startpos); } } // If we got here, we didn't match a closing backtick sequence. inlines.push({ t: 'Str', c: ticks }); this.pos = afterOpenTicks; return (this.pos - startpos); }
javascript
function(inlines) { var startpos = this.pos; var ticks = this.match(/^`+/); if (!ticks) { return 0; } var afterOpenTicks = this.pos; var foundCode = false; var match; while (!foundCode && (match = this.match(/`+/m))) { if (match == ticks) { inlines.push({ t: 'Code', c: this.subject.slice(afterOpenTicks, this.pos - ticks.length) .replace(/[ \n]+/g,' ') .trim() }); return (this.pos - startpos); } } // If we got here, we didn't match a closing backtick sequence. inlines.push({ t: 'Str', c: ticks }); this.pos = afterOpenTicks; return (this.pos - startpos); }
[ "function", "(", "inlines", ")", "{", "var", "startpos", "=", "this", ".", "pos", ";", "var", "ticks", "=", "this", ".", "match", "(", "/", "^`+", "/", ")", ";", "if", "(", "!", "ticks", ")", "{", "return", "0", ";", "}", "var", "afterOpenTicks", "=", "this", ".", "pos", ";", "var", "foundCode", "=", "false", ";", "var", "match", ";", "while", "(", "!", "foundCode", "&&", "(", "match", "=", "this", ".", "match", "(", "/", "`+", "/", "m", ")", ")", ")", "{", "if", "(", "match", "==", "ticks", ")", "{", "inlines", ".", "push", "(", "{", "t", ":", "'Code'", ",", "c", ":", "this", ".", "subject", ".", "slice", "(", "afterOpenTicks", ",", "this", ".", "pos", "-", "ticks", ".", "length", ")", ".", "replace", "(", "/", "[ \\n]+", "/", "g", ",", "' '", ")", ".", "trim", "(", ")", "}", ")", ";", "return", "(", "this", ".", "pos", "-", "startpos", ")", ";", "}", "}", "// If we got here, we didn't match a closing backtick sequence.", "inlines", ".", "push", "(", "{", "t", ":", "'Str'", ",", "c", ":", "ticks", "}", ")", ";", "this", ".", "pos", "=", "afterOpenTicks", ";", "return", "(", "this", ".", "pos", "-", "startpos", ")", ";", "}" ]
Attempt to parse backticks, adding either a backtick code span or a literal sequence of backticks to the 'inlines' list.
[ "Attempt", "to", "parse", "backticks", "adding", "either", "a", "backtick", "code", "span", "or", "a", "literal", "sequence", "of", "backticks", "to", "the", "inlines", "list", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L158-L180
19,171
bitovi/documentjs
lib/stmd.js
function(inlines) { var m = this.match(reHtmlTag); if (m) { inlines.push({ t: 'Html', c: m }); return m.length; } else { return 0; } }
javascript
function(inlines) { var m = this.match(reHtmlTag); if (m) { inlines.push({ t: 'Html', c: m }); return m.length; } else { return 0; } }
[ "function", "(", "inlines", ")", "{", "var", "m", "=", "this", ".", "match", "(", "reHtmlTag", ")", ";", "if", "(", "m", ")", "{", "inlines", ".", "push", "(", "{", "t", ":", "'Html'", ",", "c", ":", "m", "}", ")", ";", "return", "m", ".", "length", ";", "}", "else", "{", "return", "0", ";", "}", "}" ]
Attempt to parse a raw HTML tag.
[ "Attempt", "to", "parse", "a", "raw", "HTML", "tag", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L227-L235
19,172
bitovi/documentjs
lib/stmd.js
function() { var res = this.match(reLinkDestinationBraces); if (res) { // chop off surrounding <..>: return unescape(res.substr(1, res.length - 2)); } else { res = this.match(reLinkDestination); if (res !== null) { return unescape(res); } else { return null; } } }
javascript
function() { var res = this.match(reLinkDestinationBraces); if (res) { // chop off surrounding <..>: return unescape(res.substr(1, res.length - 2)); } else { res = this.match(reLinkDestination); if (res !== null) { return unescape(res); } else { return null; } } }
[ "function", "(", ")", "{", "var", "res", "=", "this", ".", "match", "(", "reLinkDestinationBraces", ")", ";", "if", "(", "res", ")", "{", "// chop off surrounding <..>:", "return", "unescape", "(", "res", ".", "substr", "(", "1", ",", "res", ".", "length", "-", "2", ")", ")", ";", "}", "else", "{", "res", "=", "this", ".", "match", "(", "reLinkDestination", ")", ";", "if", "(", "res", "!==", "null", ")", "{", "return", "unescape", "(", "res", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}", "}" ]
Attempt to parse link destination, returning the string or null if no match.
[ "Attempt", "to", "parse", "link", "destination", "returning", "the", "string", "or", "null", "if", "no", "match", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L402-L414
19,173
bitovi/documentjs
lib/stmd.js
function() { if (this.peek() != '[') { return 0; } var startpos = this.pos; var nest_level = 0; if (this.label_nest_level > 0) { // If we've already checked to the end of this subject // for a label, even with a different starting [, we // know we won't find one here and we can just return. // This avoids lots of backtracking. // Note: nest level 1 would be: [foo [bar] // nest level 2 would be: [foo [bar [baz] this.label_nest_level--; return 0; } this.pos++; // advance past [ var c; while ((c = this.peek()) && (c != ']' || nest_level > 0)) { switch (c) { case '`': this.parseBackticks([]); break; case '<': this.parseAutolink([]) || this.parseHtmlTag([]) || this.parseString([]); break; case '[': // nested [] nest_level++; this.pos++; break; case ']': // nested [] nest_level--; this.pos++; break; case '\\': this.parseEscaped([]); break; default: this.parseString([]); } } if (c === ']') { this.label_nest_level = 0; this.pos++; // advance past ] return this.pos - startpos; } else { if (!c) { this.label_nest_level = nest_level; } this.pos = startpos; return 0; } }
javascript
function() { if (this.peek() != '[') { return 0; } var startpos = this.pos; var nest_level = 0; if (this.label_nest_level > 0) { // If we've already checked to the end of this subject // for a label, even with a different starting [, we // know we won't find one here and we can just return. // This avoids lots of backtracking. // Note: nest level 1 would be: [foo [bar] // nest level 2 would be: [foo [bar [baz] this.label_nest_level--; return 0; } this.pos++; // advance past [ var c; while ((c = this.peek()) && (c != ']' || nest_level > 0)) { switch (c) { case '`': this.parseBackticks([]); break; case '<': this.parseAutolink([]) || this.parseHtmlTag([]) || this.parseString([]); break; case '[': // nested [] nest_level++; this.pos++; break; case ']': // nested [] nest_level--; this.pos++; break; case '\\': this.parseEscaped([]); break; default: this.parseString([]); } } if (c === ']') { this.label_nest_level = 0; this.pos++; // advance past ] return this.pos - startpos; } else { if (!c) { this.label_nest_level = nest_level; } this.pos = startpos; return 0; } }
[ "function", "(", ")", "{", "if", "(", "this", ".", "peek", "(", ")", "!=", "'['", ")", "{", "return", "0", ";", "}", "var", "startpos", "=", "this", ".", "pos", ";", "var", "nest_level", "=", "0", ";", "if", "(", "this", ".", "label_nest_level", ">", "0", ")", "{", "// If we've already checked to the end of this subject", "// for a label, even with a different starting [, we", "// know we won't find one here and we can just return.", "// This avoids lots of backtracking.", "// Note: nest level 1 would be: [foo [bar]", "// nest level 2 would be: [foo [bar [baz]", "this", ".", "label_nest_level", "--", ";", "return", "0", ";", "}", "this", ".", "pos", "++", ";", "// advance past [", "var", "c", ";", "while", "(", "(", "c", "=", "this", ".", "peek", "(", ")", ")", "&&", "(", "c", "!=", "']'", "||", "nest_level", ">", "0", ")", ")", "{", "switch", "(", "c", ")", "{", "case", "'`'", ":", "this", ".", "parseBackticks", "(", "[", "]", ")", ";", "break", ";", "case", "'<'", ":", "this", ".", "parseAutolink", "(", "[", "]", ")", "||", "this", ".", "parseHtmlTag", "(", "[", "]", ")", "||", "this", ".", "parseString", "(", "[", "]", ")", ";", "break", ";", "case", "'['", ":", "// nested []", "nest_level", "++", ";", "this", ".", "pos", "++", ";", "break", ";", "case", "']'", ":", "// nested []", "nest_level", "--", ";", "this", ".", "pos", "++", ";", "break", ";", "case", "'\\\\'", ":", "this", ".", "parseEscaped", "(", "[", "]", ")", ";", "break", ";", "default", ":", "this", ".", "parseString", "(", "[", "]", ")", ";", "}", "}", "if", "(", "c", "===", "']'", ")", "{", "this", ".", "label_nest_level", "=", "0", ";", "this", ".", "pos", "++", ";", "// advance past ]", "return", "this", ".", "pos", "-", "startpos", ";", "}", "else", "{", "if", "(", "!", "c", ")", "{", "this", ".", "label_nest_level", "=", "nest_level", ";", "}", "this", ".", "pos", "=", "startpos", ";", "return", "0", ";", "}", "}" ]
Attempt to parse a link label, returning number of characters parsed.
[ "Attempt", "to", "parse", "a", "link", "label", "returning", "number", "of", "characters", "parsed", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L417-L469
19,174
bitovi/documentjs
lib/stmd.js
function(inlines) { var startpos = this.pos; var reflabel; var n; var dest; var title; n = this.parseLinkLabel(); if (n === 0) { return 0; } var afterlabel = this.pos; var rawlabel = this.subject.substr(startpos, n); // if we got this far, we've parsed a label. // Try to parse an explicit link: [label](url "title") if (this.peek() == '(') { this.pos++; if (this.spnl() && ((dest = this.parseLinkDestination()) !== null) && this.spnl() && // make sure there's a space before the title: (/^\s/.test(this.subject.charAt(this.pos - 1)) && (title = this.parseLinkTitle() || '') || true) && this.spnl() && this.match(/^\)/)) { inlines.push({ t: 'Link', destination: dest, title: title, label: parseRawLabel(rawlabel) }); return this.pos - startpos; } else { this.pos = startpos; return 0; } } // If we're here, it wasn't an explicit link. Try to parse a reference link. // first, see if there's another label var savepos = this.pos; this.spnl(); var beforelabel = this.pos; n = this.parseLinkLabel(); if (n == 2) { // empty second label reflabel = rawlabel; } else if (n > 0) { reflabel = this.subject.slice(beforelabel, beforelabel + n); } else { this.pos = savepos; reflabel = rawlabel; } // lookup rawlabel in refmap var link = this.refmap[normalizeReference(reflabel)]; if (link) { inlines.push({t: 'Link', destination: link.destination, title: link.title, label: parseRawLabel(rawlabel) }); return this.pos - startpos; } else { this.pos = startpos; return 0; } // Nothing worked, rewind: this.pos = startpos; return 0; }
javascript
function(inlines) { var startpos = this.pos; var reflabel; var n; var dest; var title; n = this.parseLinkLabel(); if (n === 0) { return 0; } var afterlabel = this.pos; var rawlabel = this.subject.substr(startpos, n); // if we got this far, we've parsed a label. // Try to parse an explicit link: [label](url "title") if (this.peek() == '(') { this.pos++; if (this.spnl() && ((dest = this.parseLinkDestination()) !== null) && this.spnl() && // make sure there's a space before the title: (/^\s/.test(this.subject.charAt(this.pos - 1)) && (title = this.parseLinkTitle() || '') || true) && this.spnl() && this.match(/^\)/)) { inlines.push({ t: 'Link', destination: dest, title: title, label: parseRawLabel(rawlabel) }); return this.pos - startpos; } else { this.pos = startpos; return 0; } } // If we're here, it wasn't an explicit link. Try to parse a reference link. // first, see if there's another label var savepos = this.pos; this.spnl(); var beforelabel = this.pos; n = this.parseLinkLabel(); if (n == 2) { // empty second label reflabel = rawlabel; } else if (n > 0) { reflabel = this.subject.slice(beforelabel, beforelabel + n); } else { this.pos = savepos; reflabel = rawlabel; } // lookup rawlabel in refmap var link = this.refmap[normalizeReference(reflabel)]; if (link) { inlines.push({t: 'Link', destination: link.destination, title: link.title, label: parseRawLabel(rawlabel) }); return this.pos - startpos; } else { this.pos = startpos; return 0; } // Nothing worked, rewind: this.pos = startpos; return 0; }
[ "function", "(", "inlines", ")", "{", "var", "startpos", "=", "this", ".", "pos", ";", "var", "reflabel", ";", "var", "n", ";", "var", "dest", ";", "var", "title", ";", "n", "=", "this", ".", "parseLinkLabel", "(", ")", ";", "if", "(", "n", "===", "0", ")", "{", "return", "0", ";", "}", "var", "afterlabel", "=", "this", ".", "pos", ";", "var", "rawlabel", "=", "this", ".", "subject", ".", "substr", "(", "startpos", ",", "n", ")", ";", "// if we got this far, we've parsed a label.", "// Try to parse an explicit link: [label](url \"title\")", "if", "(", "this", ".", "peek", "(", ")", "==", "'('", ")", "{", "this", ".", "pos", "++", ";", "if", "(", "this", ".", "spnl", "(", ")", "&&", "(", "(", "dest", "=", "this", ".", "parseLinkDestination", "(", ")", ")", "!==", "null", ")", "&&", "this", ".", "spnl", "(", ")", "&&", "// make sure there's a space before the title:", "(", "/", "^\\s", "/", ".", "test", "(", "this", ".", "subject", ".", "charAt", "(", "this", ".", "pos", "-", "1", ")", ")", "&&", "(", "title", "=", "this", ".", "parseLinkTitle", "(", ")", "||", "''", ")", "||", "true", ")", "&&", "this", ".", "spnl", "(", ")", "&&", "this", ".", "match", "(", "/", "^\\)", "/", ")", ")", "{", "inlines", ".", "push", "(", "{", "t", ":", "'Link'", ",", "destination", ":", "dest", ",", "title", ":", "title", ",", "label", ":", "parseRawLabel", "(", "rawlabel", ")", "}", ")", ";", "return", "this", ".", "pos", "-", "startpos", ";", "}", "else", "{", "this", ".", "pos", "=", "startpos", ";", "return", "0", ";", "}", "}", "// If we're here, it wasn't an explicit link. Try to parse a reference link.", "// first, see if there's another label", "var", "savepos", "=", "this", ".", "pos", ";", "this", ".", "spnl", "(", ")", ";", "var", "beforelabel", "=", "this", ".", "pos", ";", "n", "=", "this", ".", "parseLinkLabel", "(", ")", ";", "if", "(", "n", "==", "2", ")", "{", "// empty second label", "reflabel", "=", "rawlabel", ";", "}", "else", "if", "(", "n", ">", "0", ")", "{", "reflabel", "=", "this", ".", "subject", ".", "slice", "(", "beforelabel", ",", "beforelabel", "+", "n", ")", ";", "}", "else", "{", "this", ".", "pos", "=", "savepos", ";", "reflabel", "=", "rawlabel", ";", "}", "// lookup rawlabel in refmap", "var", "link", "=", "this", ".", "refmap", "[", "normalizeReference", "(", "reflabel", ")", "]", ";", "if", "(", "link", ")", "{", "inlines", ".", "push", "(", "{", "t", ":", "'Link'", ",", "destination", ":", "link", ".", "destination", ",", "title", ":", "link", ".", "title", ",", "label", ":", "parseRawLabel", "(", "rawlabel", ")", "}", ")", ";", "return", "this", ".", "pos", "-", "startpos", ";", "}", "else", "{", "this", ".", "pos", "=", "startpos", ";", "return", "0", ";", "}", "// Nothing worked, rewind:", "this", ".", "pos", "=", "startpos", ";", "return", "0", ";", "}" ]
Attempt to parse a link. If successful, add the link to inlines.
[ "Attempt", "to", "parse", "a", "link", ".", "If", "successful", "add", "the", "link", "to", "inlines", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L481-L547
19,175
bitovi/documentjs
lib/stmd.js
function(inlines) { var m; if ((m = this.match(/^&(?:#x[a-f0-9]{1,8}|#[0-9]{1,8}|[a-z][a-z0-9]{1,31});/i))) { inlines.push({ t: 'Entity', c: m }); return m.length; } else { return 0; } }
javascript
function(inlines) { var m; if ((m = this.match(/^&(?:#x[a-f0-9]{1,8}|#[0-9]{1,8}|[a-z][a-z0-9]{1,31});/i))) { inlines.push({ t: 'Entity', c: m }); return m.length; } else { return 0; } }
[ "function", "(", "inlines", ")", "{", "var", "m", ";", "if", "(", "(", "m", "=", "this", ".", "match", "(", "/", "^&(?:#x[a-f0-9]{1,8}|#[0-9]{1,8}|[a-z][a-z0-9]{1,31});", "/", "i", ")", ")", ")", "{", "inlines", ".", "push", "(", "{", "t", ":", "'Entity'", ",", "c", ":", "m", "}", ")", ";", "return", "m", ".", "length", ";", "}", "else", "{", "return", "0", ";", "}", "}" ]
Attempt to parse an entity, adding to inlines if successful.
[ "Attempt", "to", "parse", "an", "entity", "adding", "to", "inlines", "if", "successful", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L550-L558
19,176
bitovi/documentjs
lib/stmd.js
function(inlines) { var m; if ((m = this.match(reMain))) { inlines.push({ t: 'Str', c: m }); return m.length; } else { return 0; } }
javascript
function(inlines) { var m; if ((m = this.match(reMain))) { inlines.push({ t: 'Str', c: m }); return m.length; } else { return 0; } }
[ "function", "(", "inlines", ")", "{", "var", "m", ";", "if", "(", "(", "m", "=", "this", ".", "match", "(", "reMain", ")", ")", ")", "{", "inlines", ".", "push", "(", "{", "t", ":", "'Str'", ",", "c", ":", "m", "}", ")", ";", "return", "m", ".", "length", ";", "}", "else", "{", "return", "0", ";", "}", "}" ]
Parse a run of ordinary characters, or a single character with a special meaning in markdown, as a plain string, adding to inlines.
[ "Parse", "a", "run", "of", "ordinary", "characters", "or", "a", "single", "character", "with", "a", "special", "meaning", "in", "markdown", "as", "a", "plain", "string", "adding", "to", "inlines", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L562-L570
19,177
bitovi/documentjs
lib/stmd.js
function(inlines) { if (this.peek() == '\n') { this.pos++; var last = inlines[inlines.length - 1]; if (last && last.t == 'Str' && last.c.slice(-2) == ' ') { last.c = last.c.replace(/ *$/,''); inlines.push({ t: 'Hardbreak' }); } else { if (last && last.t == 'Str' && last.c.slice(-1) == ' ') { last.c = last.c.slice(0, -1); } inlines.push({ t: 'Softbreak' }); } return 1; } else { return 0; } }
javascript
function(inlines) { if (this.peek() == '\n') { this.pos++; var last = inlines[inlines.length - 1]; if (last && last.t == 'Str' && last.c.slice(-2) == ' ') { last.c = last.c.replace(/ *$/,''); inlines.push({ t: 'Hardbreak' }); } else { if (last && last.t == 'Str' && last.c.slice(-1) == ' ') { last.c = last.c.slice(0, -1); } inlines.push({ t: 'Softbreak' }); } return 1; } else { return 0; } }
[ "function", "(", "inlines", ")", "{", "if", "(", "this", ".", "peek", "(", ")", "==", "'\\n'", ")", "{", "this", ".", "pos", "++", ";", "var", "last", "=", "inlines", "[", "inlines", ".", "length", "-", "1", "]", ";", "if", "(", "last", "&&", "last", ".", "t", "==", "'Str'", "&&", "last", ".", "c", ".", "slice", "(", "-", "2", ")", "==", "' '", ")", "{", "last", ".", "c", "=", "last", ".", "c", ".", "replace", "(", "/", " *$", "/", ",", "''", ")", ";", "inlines", ".", "push", "(", "{", "t", ":", "'Hardbreak'", "}", ")", ";", "}", "else", "{", "if", "(", "last", "&&", "last", ".", "t", "==", "'Str'", "&&", "last", ".", "c", ".", "slice", "(", "-", "1", ")", "==", "' '", ")", "{", "last", ".", "c", "=", "last", ".", "c", ".", "slice", "(", "0", ",", "-", "1", ")", ";", "}", "inlines", ".", "push", "(", "{", "t", ":", "'Softbreak'", "}", ")", ";", "}", "return", "1", ";", "}", "else", "{", "return", "0", ";", "}", "}" ]
Parse a newline. If it was preceded by two spaces, return a hard line break; otherwise a soft line break.
[ "Parse", "a", "newline", ".", "If", "it", "was", "preceded", "by", "two", "spaces", "return", "a", "hard", "line", "break", ";", "otherwise", "a", "soft", "line", "break", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L574-L591
19,178
bitovi/documentjs
lib/stmd.js
function(inlines) { if (this.match(/^!/)) { var n = this.parseLink(inlines); if (n === 0) { inlines.push({ t: 'Str', c: '!' }); return 1; } else if (inlines[inlines.length - 1] && inlines[inlines.length - 1].t == 'Link') { inlines[inlines.length - 1].t = 'Image'; return n+1; } else { throw "Shouldn't happen"; } } else { return 0; } }
javascript
function(inlines) { if (this.match(/^!/)) { var n = this.parseLink(inlines); if (n === 0) { inlines.push({ t: 'Str', c: '!' }); return 1; } else if (inlines[inlines.length - 1] && inlines[inlines.length - 1].t == 'Link') { inlines[inlines.length - 1].t = 'Image'; return n+1; } else { throw "Shouldn't happen"; } } else { return 0; } }
[ "function", "(", "inlines", ")", "{", "if", "(", "this", ".", "match", "(", "/", "^!", "/", ")", ")", "{", "var", "n", "=", "this", ".", "parseLink", "(", "inlines", ")", ";", "if", "(", "n", "===", "0", ")", "{", "inlines", ".", "push", "(", "{", "t", ":", "'Str'", ",", "c", ":", "'!'", "}", ")", ";", "return", "1", ";", "}", "else", "if", "(", "inlines", "[", "inlines", ".", "length", "-", "1", "]", "&&", "inlines", "[", "inlines", ".", "length", "-", "1", "]", ".", "t", "==", "'Link'", ")", "{", "inlines", "[", "inlines", ".", "length", "-", "1", "]", ".", "t", "=", "'Image'", ";", "return", "n", "+", "1", ";", "}", "else", "{", "throw", "\"Shouldn't happen\"", ";", "}", "}", "else", "{", "return", "0", ";", "}", "}" ]
Attempt to parse an image. If the opening '!' is not followed by a link, add a literal '!' to inlines.
[ "Attempt", "to", "parse", "an", "image", ".", "If", "the", "opening", "!", "is", "not", "followed", "by", "a", "link", "add", "a", "literal", "!", "to", "inlines", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L595-L611
19,179
bitovi/documentjs
lib/stmd.js
function(s, refmap) { this.subject = s; this.pos = 0; var rawlabel; var dest; var title; var matchChars; var startpos = this.pos; var match; // label: matchChars = this.parseLinkLabel(); if (matchChars === 0) { return 0; } else { rawlabel = this.subject.substr(0, matchChars); } // colon: if (this.peek() === ':') { this.pos++; } else { this.pos = startpos; return 0; } // link url this.spnl(); dest = this.parseLinkDestination(); if (dest === null || dest.length === 0) { this.pos = startpos; return 0; } var beforetitle = this.pos; this.spnl(); title = this.parseLinkTitle(); if (title === null) { title = ''; // rewind before spaces this.pos = beforetitle; } // make sure we're at line end: if (this.match(/^ *(?:\n|$)/) === null) { this.pos = startpos; return 0; } var normlabel = normalizeReference(rawlabel); if (!refmap[normlabel]) { refmap[normlabel] = { destination: dest, title: title }; } return this.pos - startpos; }
javascript
function(s, refmap) { this.subject = s; this.pos = 0; var rawlabel; var dest; var title; var matchChars; var startpos = this.pos; var match; // label: matchChars = this.parseLinkLabel(); if (matchChars === 0) { return 0; } else { rawlabel = this.subject.substr(0, matchChars); } // colon: if (this.peek() === ':') { this.pos++; } else { this.pos = startpos; return 0; } // link url this.spnl(); dest = this.parseLinkDestination(); if (dest === null || dest.length === 0) { this.pos = startpos; return 0; } var beforetitle = this.pos; this.spnl(); title = this.parseLinkTitle(); if (title === null) { title = ''; // rewind before spaces this.pos = beforetitle; } // make sure we're at line end: if (this.match(/^ *(?:\n|$)/) === null) { this.pos = startpos; return 0; } var normlabel = normalizeReference(rawlabel); if (!refmap[normlabel]) { refmap[normlabel] = { destination: dest, title: title }; } return this.pos - startpos; }
[ "function", "(", "s", ",", "refmap", ")", "{", "this", ".", "subject", "=", "s", ";", "this", ".", "pos", "=", "0", ";", "var", "rawlabel", ";", "var", "dest", ";", "var", "title", ";", "var", "matchChars", ";", "var", "startpos", "=", "this", ".", "pos", ";", "var", "match", ";", "// label:", "matchChars", "=", "this", ".", "parseLinkLabel", "(", ")", ";", "if", "(", "matchChars", "===", "0", ")", "{", "return", "0", ";", "}", "else", "{", "rawlabel", "=", "this", ".", "subject", ".", "substr", "(", "0", ",", "matchChars", ")", ";", "}", "// colon:", "if", "(", "this", ".", "peek", "(", ")", "===", "':'", ")", "{", "this", ".", "pos", "++", ";", "}", "else", "{", "this", ".", "pos", "=", "startpos", ";", "return", "0", ";", "}", "// link url", "this", ".", "spnl", "(", ")", ";", "dest", "=", "this", ".", "parseLinkDestination", "(", ")", ";", "if", "(", "dest", "===", "null", "||", "dest", ".", "length", "===", "0", ")", "{", "this", ".", "pos", "=", "startpos", ";", "return", "0", ";", "}", "var", "beforetitle", "=", "this", ".", "pos", ";", "this", ".", "spnl", "(", ")", ";", "title", "=", "this", ".", "parseLinkTitle", "(", ")", ";", "if", "(", "title", "===", "null", ")", "{", "title", "=", "''", ";", "// rewind before spaces", "this", ".", "pos", "=", "beforetitle", ";", "}", "// make sure we're at line end:", "if", "(", "this", ".", "match", "(", "/", "^ *(?:\\n|$)", "/", ")", "===", "null", ")", "{", "this", ".", "pos", "=", "startpos", ";", "return", "0", ";", "}", "var", "normlabel", "=", "normalizeReference", "(", "rawlabel", ")", ";", "if", "(", "!", "refmap", "[", "normlabel", "]", ")", "{", "refmap", "[", "normlabel", "]", "=", "{", "destination", ":", "dest", ",", "title", ":", "title", "}", ";", "}", "return", "this", ".", "pos", "-", "startpos", ";", "}" ]
Attempt to parse a link reference, modifying refmap.
[ "Attempt", "to", "parse", "a", "link", "reference", "modifying", "refmap", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L614-L670
19,180
bitovi/documentjs
lib/stmd.js
function(inlines) { var c = this.peek(); var res; switch(c) { case '\n': res = this.parseNewline(inlines); break; case '\\': res = this.parseEscaped(inlines); break; case '`': res = this.parseBackticks(inlines); break; case '*': case '_': res = this.parseEmphasis(inlines); break; case '[': res = this.parseLink(inlines); break; case '!': res = this.parseImage(inlines); break; case '<': res = this.parseAutolink(inlines) || this.parseHtmlTag(inlines); break; case '&': res = this.parseEntity(inlines); break; default: } return res || this.parseString(inlines); }
javascript
function(inlines) { var c = this.peek(); var res; switch(c) { case '\n': res = this.parseNewline(inlines); break; case '\\': res = this.parseEscaped(inlines); break; case '`': res = this.parseBackticks(inlines); break; case '*': case '_': res = this.parseEmphasis(inlines); break; case '[': res = this.parseLink(inlines); break; case '!': res = this.parseImage(inlines); break; case '<': res = this.parseAutolink(inlines) || this.parseHtmlTag(inlines); break; case '&': res = this.parseEntity(inlines); break; default: } return res || this.parseString(inlines); }
[ "function", "(", "inlines", ")", "{", "var", "c", "=", "this", ".", "peek", "(", ")", ";", "var", "res", ";", "switch", "(", "c", ")", "{", "case", "'\\n'", ":", "res", "=", "this", ".", "parseNewline", "(", "inlines", ")", ";", "break", ";", "case", "'\\\\'", ":", "res", "=", "this", ".", "parseEscaped", "(", "inlines", ")", ";", "break", ";", "case", "'`'", ":", "res", "=", "this", ".", "parseBackticks", "(", "inlines", ")", ";", "break", ";", "case", "'*'", ":", "case", "'_'", ":", "res", "=", "this", ".", "parseEmphasis", "(", "inlines", ")", ";", "break", ";", "case", "'['", ":", "res", "=", "this", ".", "parseLink", "(", "inlines", ")", ";", "break", ";", "case", "'!'", ":", "res", "=", "this", ".", "parseImage", "(", "inlines", ")", ";", "break", ";", "case", "'<'", ":", "res", "=", "this", ".", "parseAutolink", "(", "inlines", ")", "||", "this", ".", "parseHtmlTag", "(", "inlines", ")", ";", "break", ";", "case", "'&'", ":", "res", "=", "this", ".", "parseEntity", "(", "inlines", ")", ";", "break", ";", "default", ":", "}", "return", "res", "||", "this", ".", "parseString", "(", "inlines", ")", ";", "}" ]
Parse the next inline element in subject, advancing subject position and adding the result to 'inlines'.
[ "Parse", "the", "next", "inline", "element", "in", "subject", "advancing", "subject", "position", "and", "adding", "the", "result", "to", "inlines", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L674-L707
19,181
bitovi/documentjs
lib/stmd.js
function(s, refmap) { this.subject = s; this.pos = 0; this.refmap = refmap || {}; var inlines = []; while (this.parseInline(inlines)) ; return inlines; }
javascript
function(s, refmap) { this.subject = s; this.pos = 0; this.refmap = refmap || {}; var inlines = []; while (this.parseInline(inlines)) ; return inlines; }
[ "function", "(", "s", ",", "refmap", ")", "{", "this", ".", "subject", "=", "s", ";", "this", ".", "pos", "=", "0", ";", "this", ".", "refmap", "=", "refmap", "||", "{", "}", ";", "var", "inlines", "=", "[", "]", ";", "while", "(", "this", ".", "parseInline", "(", "inlines", ")", ")", ";", "return", "inlines", ";", "}" ]
Parse s as a list of inlines, using refmap to resolve references.
[ "Parse", "s", "as", "a", "list", "of", "inlines", "using", "refmap", "to", "resolve", "references", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L710-L717
19,182
bitovi/documentjs
lib/stmd.js
InlineParser
function InlineParser(){ return { subject: '', label_nest_level: 0, // used by parseLinkLabel method pos: 0, refmap: {}, match: match, peek: peek, spnl: spnl, parseBackticks: parseBackticks, parseEscaped: parseEscaped, parseAutolink: parseAutolink, parseHtmlTag: parseHtmlTag, scanDelims: scanDelims, parseEmphasis: parseEmphasis, parseLinkTitle: parseLinkTitle, parseLinkDestination: parseLinkDestination, parseLinkLabel: parseLinkLabel, parseLink: parseLink, parseEntity: parseEntity, parseString: parseString, parseNewline: parseNewline, parseImage: parseImage, parseReference: parseReference, parseInline: parseInline, parse: parseInlines }; }
javascript
function InlineParser(){ return { subject: '', label_nest_level: 0, // used by parseLinkLabel method pos: 0, refmap: {}, match: match, peek: peek, spnl: spnl, parseBackticks: parseBackticks, parseEscaped: parseEscaped, parseAutolink: parseAutolink, parseHtmlTag: parseHtmlTag, scanDelims: scanDelims, parseEmphasis: parseEmphasis, parseLinkTitle: parseLinkTitle, parseLinkDestination: parseLinkDestination, parseLinkLabel: parseLinkLabel, parseLink: parseLink, parseEntity: parseEntity, parseString: parseString, parseNewline: parseNewline, parseImage: parseImage, parseReference: parseReference, parseInline: parseInline, parse: parseInlines }; }
[ "function", "InlineParser", "(", ")", "{", "return", "{", "subject", ":", "''", ",", "label_nest_level", ":", "0", ",", "// used by parseLinkLabel method", "pos", ":", "0", ",", "refmap", ":", "{", "}", ",", "match", ":", "match", ",", "peek", ":", "peek", ",", "spnl", ":", "spnl", ",", "parseBackticks", ":", "parseBackticks", ",", "parseEscaped", ":", "parseEscaped", ",", "parseAutolink", ":", "parseAutolink", ",", "parseHtmlTag", ":", "parseHtmlTag", ",", "scanDelims", ":", "scanDelims", ",", "parseEmphasis", ":", "parseEmphasis", ",", "parseLinkTitle", ":", "parseLinkTitle", ",", "parseLinkDestination", ":", "parseLinkDestination", ",", "parseLinkLabel", ":", "parseLinkLabel", ",", "parseLink", ":", "parseLink", ",", "parseEntity", ":", "parseEntity", ",", "parseString", ":", "parseString", ",", "parseNewline", ":", "parseNewline", ",", "parseImage", ":", "parseImage", ",", "parseReference", ":", "parseReference", ",", "parseInline", ":", "parseInline", ",", "parse", ":", "parseInlines", "}", ";", "}" ]
The InlineParser object.
[ "The", "InlineParser", "object", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L720-L747
19,183
bitovi/documentjs
lib/stmd.js
function(tag, start_line, start_column) { return { t: tag, open: true, last_line_blank: false, start_line: start_line, start_column: start_column, end_line: start_line, children: [], parent: null, // string_content is formed by concatenating strings, in finalize: string_content: "", strings: [], inline_content: [] }; }
javascript
function(tag, start_line, start_column) { return { t: tag, open: true, last_line_blank: false, start_line: start_line, start_column: start_column, end_line: start_line, children: [], parent: null, // string_content is formed by concatenating strings, in finalize: string_content: "", strings: [], inline_content: [] }; }
[ "function", "(", "tag", ",", "start_line", ",", "start_column", ")", "{", "return", "{", "t", ":", "tag", ",", "open", ":", "true", ",", "last_line_blank", ":", "false", ",", "start_line", ":", "start_line", ",", "start_column", ":", "start_column", ",", "end_line", ":", "start_line", ",", "children", ":", "[", "]", ",", "parent", ":", "null", ",", "// string_content is formed by concatenating strings, in finalize:", "string_content", ":", "\"\"", ",", "strings", ":", "[", "]", ",", "inline_content", ":", "[", "]", "}", ";", "}" ]
DOC PARSER These are methods of a DocParser object, defined below.
[ "DOC", "PARSER", "These", "are", "methods", "of", "a", "DocParser", "object", "defined", "below", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L753-L767
19,184
bitovi/documentjs
lib/stmd.js
function(block) { if (block.last_line_blank) { return true; } if ((block.t == 'List' || block.t == 'ListItem') && block.children.length > 0) { return endsWithBlankLine(block.children[block.children.length - 1]); } else { return false; } }
javascript
function(block) { if (block.last_line_blank) { return true; } if ((block.t == 'List' || block.t == 'ListItem') && block.children.length > 0) { return endsWithBlankLine(block.children[block.children.length - 1]); } else { return false; } }
[ "function", "(", "block", ")", "{", "if", "(", "block", ".", "last_line_blank", ")", "{", "return", "true", ";", "}", "if", "(", "(", "block", ".", "t", "==", "'List'", "||", "block", ".", "t", "==", "'ListItem'", ")", "&&", "block", ".", "children", ".", "length", ">", "0", ")", "{", "return", "endsWithBlankLine", "(", "block", ".", "children", "[", "block", ".", "children", ".", "length", "-", "1", "]", ")", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Returns true if block ends with a blank line, descending if needed into lists and sublists.
[ "Returns", "true", "if", "block", "ends", "with", "a", "blank", "line", "descending", "if", "needed", "into", "lists", "and", "sublists", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L786-L795
19,185
bitovi/documentjs
lib/stmd.js
function(tag, line_number, offset) { while (!canContain(this.tip.t, tag)) { this.finalize(this.tip, line_number); } var column_number = offset + 1; // offset 0 = column 1 var newBlock = makeBlock(tag, line_number, column_number); this.tip.children.push(newBlock); newBlock.parent = this.tip; this.tip = newBlock; return newBlock; }
javascript
function(tag, line_number, offset) { while (!canContain(this.tip.t, tag)) { this.finalize(this.tip, line_number); } var column_number = offset + 1; // offset 0 = column 1 var newBlock = makeBlock(tag, line_number, column_number); this.tip.children.push(newBlock); newBlock.parent = this.tip; this.tip = newBlock; return newBlock; }
[ "function", "(", "tag", ",", "line_number", ",", "offset", ")", "{", "while", "(", "!", "canContain", "(", "this", ".", "tip", ".", "t", ",", "tag", ")", ")", "{", "this", ".", "finalize", "(", "this", ".", "tip", ",", "line_number", ")", ";", "}", "var", "column_number", "=", "offset", "+", "1", ";", "// offset 0 = column 1", "var", "newBlock", "=", "makeBlock", "(", "tag", ",", "line_number", ",", "column_number", ")", ";", "this", ".", "tip", ".", "children", ".", "push", "(", "newBlock", ")", ";", "newBlock", ".", "parent", "=", "this", ".", "tip", ";", "this", ".", "tip", "=", "newBlock", ";", "return", "newBlock", ";", "}" ]
Add block of type tag as a child of the tip. If the tip can't accept children, close and finalize it and try its parent, and so on til we find a block that can accept children.
[ "Add", "block", "of", "type", "tag", "as", "a", "child", "of", "the", "tip", ".", "If", "the", "tip", "can", "t", "accept", "children", "close", "and", "finalize", "it", "and", "try", "its", "parent", "and", "so", "on", "til", "we", "find", "a", "block", "that", "can", "accept", "children", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L834-L845
19,186
bitovi/documentjs
lib/stmd.js
function(list_data, item_data) { return (list_data.type === item_data.type && list_data.delimiter === item_data.delimiter && list_data.bullet_char === item_data.bullet_char); }
javascript
function(list_data, item_data) { return (list_data.type === item_data.type && list_data.delimiter === item_data.delimiter && list_data.bullet_char === item_data.bullet_char); }
[ "function", "(", "list_data", ",", "item_data", ")", "{", "return", "(", "list_data", ".", "type", "===", "item_data", ".", "type", "&&", "list_data", ".", "delimiter", "===", "item_data", ".", "delimiter", "&&", "list_data", ".", "bullet_char", "===", "item_data", ".", "bullet_char", ")", ";", "}" ]
Returns true if the two list items are of the same type, with the same delimiter and bullet character. This is used in agglomerating list items into lists.
[ "Returns", "true", "if", "the", "two", "list", "items", "are", "of", "the", "same", "type", "with", "the", "same", "delimiter", "and", "bullet", "character", ".", "This", "is", "used", "in", "agglomerating", "list", "items", "into", "lists", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L884-L888
19,187
bitovi/documentjs
lib/stmd.js
function(mythis) { // finalize any blocks not matched while (!already_done && oldtip != last_matched_container) { mythis.finalize(oldtip, line_number); oldtip = oldtip.parent; } var already_done = true; }
javascript
function(mythis) { // finalize any blocks not matched while (!already_done && oldtip != last_matched_container) { mythis.finalize(oldtip, line_number); oldtip = oldtip.parent; } var already_done = true; }
[ "function", "(", "mythis", ")", "{", "// finalize any blocks not matched", "while", "(", "!", "already_done", "&&", "oldtip", "!=", "last_matched_container", ")", "{", "mythis", ".", "finalize", "(", "oldtip", ",", "line_number", ")", ";", "oldtip", "=", "oldtip", ".", "parent", ";", "}", "var", "already_done", "=", "true", ";", "}" ]
This function is used to finalize and close any unmatched blocks. We aren't ready to do this now, because we might have a lazy paragraph continuation, in which case we don't want to close unmatched blocks. So we store this closure for use later, when we have more information.
[ "This", "function", "is", "used", "to", "finalize", "and", "close", "any", "unmatched", "blocks", ".", "We", "aren", "t", "ready", "to", "do", "this", "now", "because", "we", "might", "have", "a", "lazy", "paragraph", "continuation", "in", "which", "case", "we", "don", "t", "want", "to", "close", "unmatched", "blocks", ".", "So", "we", "store", "this", "closure", "for", "use", "later", "when", "we", "have", "more", "information", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L1013-L1020
19,188
bitovi/documentjs
lib/stmd.js
function(block) { switch(block.t) { case 'Paragraph': case 'SetextHeader': case 'ATXHeader': block.inline_content = this.inlineParser.parse(block.string_content.trim(), this.refmap); block.string_content = ""; break; default: break; } if (block.children) { for (var i = 0; i < block.children.length; i++) { this.processInlines(block.children[i]); } } }
javascript
function(block) { switch(block.t) { case 'Paragraph': case 'SetextHeader': case 'ATXHeader': block.inline_content = this.inlineParser.parse(block.string_content.trim(), this.refmap); block.string_content = ""; break; default: break; } if (block.children) { for (var i = 0; i < block.children.length; i++) { this.processInlines(block.children[i]); } } }
[ "function", "(", "block", ")", "{", "switch", "(", "block", ".", "t", ")", "{", "case", "'Paragraph'", ":", "case", "'SetextHeader'", ":", "case", "'ATXHeader'", ":", "block", ".", "inline_content", "=", "this", ".", "inlineParser", ".", "parse", "(", "block", ".", "string_content", ".", "trim", "(", ")", ",", "this", ".", "refmap", ")", ";", "block", ".", "string_content", "=", "\"\"", ";", "break", ";", "default", ":", "break", ";", "}", "if", "(", "block", ".", "children", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "block", ".", "children", ".", "length", ";", "i", "++", ")", "{", "this", ".", "processInlines", "(", "block", ".", "children", "[", "i", "]", ")", ";", "}", "}", "}" ]
Walk through a block & children recursively, parsing string content into inline content where appropriate.
[ "Walk", "through", "a", "block", "&", "children", "recursively", "parsing", "string", "content", "into", "inline", "content", "where", "appropriate", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L1321-L1340
19,189
bitovi/documentjs
lib/stmd.js
function(input) { this.doc = makeBlock('Document', 1, 1); this.tip = this.doc; this.refmap = {}; var lines = input.replace(/\n$/,'').split(/\r\n|\n|\r/); var len = lines.length; for (var i = 0; i < len; i++) { this.incorporateLine(lines[i], i+1); } while (this.tip) { this.finalize(this.tip, len - 1); } this.processInlines(this.doc); return this.doc; }
javascript
function(input) { this.doc = makeBlock('Document', 1, 1); this.tip = this.doc; this.refmap = {}; var lines = input.replace(/\n$/,'').split(/\r\n|\n|\r/); var len = lines.length; for (var i = 0; i < len; i++) { this.incorporateLine(lines[i], i+1); } while (this.tip) { this.finalize(this.tip, len - 1); } this.processInlines(this.doc); return this.doc; }
[ "function", "(", "input", ")", "{", "this", ".", "doc", "=", "makeBlock", "(", "'Document'", ",", "1", ",", "1", ")", ";", "this", ".", "tip", "=", "this", ".", "doc", ";", "this", ".", "refmap", "=", "{", "}", ";", "var", "lines", "=", "input", ".", "replace", "(", "/", "\\n$", "/", ",", "''", ")", ".", "split", "(", "/", "\\r\\n|\\n|\\r", "/", ")", ";", "var", "len", "=", "lines", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "this", ".", "incorporateLine", "(", "lines", "[", "i", "]", ",", "i", "+", "1", ")", ";", "}", "while", "(", "this", ".", "tip", ")", "{", "this", ".", "finalize", "(", "this", ".", "tip", ",", "len", "-", "1", ")", ";", "}", "this", ".", "processInlines", "(", "this", ".", "doc", ")", ";", "return", "this", ".", "doc", ";", "}" ]
The main parsing function. Returns a parsed document AST.
[ "The", "main", "parsing", "function", ".", "Returns", "a", "parsed", "document", "AST", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L1343-L1357
19,190
bitovi/documentjs
lib/stmd.js
DocParser
function DocParser(){ return { doc: makeBlock('Document', 1, 1), tip: this.doc, refmap: {}, inlineParser: new InlineParser(), breakOutOfLists: breakOutOfLists, addLine: addLine, addChild: addChild, incorporateLine: incorporateLine, finalize: finalize, processInlines: processInlines, parse: parse }; }
javascript
function DocParser(){ return { doc: makeBlock('Document', 1, 1), tip: this.doc, refmap: {}, inlineParser: new InlineParser(), breakOutOfLists: breakOutOfLists, addLine: addLine, addChild: addChild, incorporateLine: incorporateLine, finalize: finalize, processInlines: processInlines, parse: parse }; }
[ "function", "DocParser", "(", ")", "{", "return", "{", "doc", ":", "makeBlock", "(", "'Document'", ",", "1", ",", "1", ")", ",", "tip", ":", "this", ".", "doc", ",", "refmap", ":", "{", "}", ",", "inlineParser", ":", "new", "InlineParser", "(", ")", ",", "breakOutOfLists", ":", "breakOutOfLists", ",", "addLine", ":", "addLine", ",", "addChild", ":", "addChild", ",", "incorporateLine", ":", "incorporateLine", ",", "finalize", ":", "finalize", ",", "processInlines", ":", "processInlines", ",", "parse", ":", "parse", "}", ";", "}" ]
The DocParser object.
[ "The", "DocParser", "object", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L1361-L1375
19,191
bitovi/documentjs
lib/stmd.js
function(tag, attribs, contents, selfclosing) { var result = '<' + tag; if (attribs) { var i = 0; var attrib; while ((attrib = attribs[i]) !== undefined) { result = result.concat(' ', attrib[0], '="', attrib[1], '"'); i++; } } if (contents) { result = result.concat('>', contents, '</', tag, '>'); } else if (selfclosing) { result = result + ' />'; } else { result = result.concat('></', tag, '>'); } return result; }
javascript
function(tag, attribs, contents, selfclosing) { var result = '<' + tag; if (attribs) { var i = 0; var attrib; while ((attrib = attribs[i]) !== undefined) { result = result.concat(' ', attrib[0], '="', attrib[1], '"'); i++; } } if (contents) { result = result.concat('>', contents, '</', tag, '>'); } else if (selfclosing) { result = result + ' />'; } else { result = result.concat('></', tag, '>'); } return result; }
[ "function", "(", "tag", ",", "attribs", ",", "contents", ",", "selfclosing", ")", "{", "var", "result", "=", "'<'", "+", "tag", ";", "if", "(", "attribs", ")", "{", "var", "i", "=", "0", ";", "var", "attrib", ";", "while", "(", "(", "attrib", "=", "attribs", "[", "i", "]", ")", "!==", "undefined", ")", "{", "result", "=", "result", ".", "concat", "(", "' '", ",", "attrib", "[", "0", "]", ",", "'=\"'", ",", "attrib", "[", "1", "]", ",", "'\"'", ")", ";", "i", "++", ";", "}", "}", "if", "(", "contents", ")", "{", "result", "=", "result", ".", "concat", "(", "'>'", ",", "contents", ",", "'</'", ",", "tag", ",", "'>'", ")", ";", "}", "else", "if", "(", "selfclosing", ")", "{", "result", "=", "result", "+", "' />'", ";", "}", "else", "{", "result", "=", "result", ".", "concat", "(", "'></'", ",", "tag", ",", "'>'", ")", ";", "}", "return", "result", ";", "}" ]
HTML RENDERER Helper function to produce content in a pair of HTML tags.
[ "HTML", "RENDERER", "Helper", "function", "to", "produce", "content", "in", "a", "pair", "of", "HTML", "tags", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L1380-L1398
19,192
bitovi/documentjs
lib/stmd.js
function(inline) { var attrs; switch (inline.t) { case 'Str': return this.escape(inline.c); case 'Softbreak': return this.softbreak; case 'Hardbreak': return inTags('br',[],"",true) + '\n'; case 'Emph': return inTags('em', [], this.renderInlines(inline.c)); case 'Strong': return inTags('strong', [], this.renderInlines(inline.c)); case 'Html': return inline.c; case 'Entity': return inline.c; case 'Link': attrs = [['href', this.escape(inline.destination, true)]]; if (inline.title) { attrs.push(['title', this.escape(inline.title, true)]); } return inTags('a', attrs, this.renderInlines(inline.label)); case 'Image': attrs = [['src', this.escape(inline.destination, true)], ['alt', this.escape(this.renderInlines(inline.label))]]; if (inline.title) { attrs.push(['title', this.escape(inline.title, true)]); } return inTags('img', attrs, "", true); case 'Code': return inTags('code', [], this.escape(inline.c)); default: console.log("Uknown inline type " + inline.t); return ""; } }
javascript
function(inline) { var attrs; switch (inline.t) { case 'Str': return this.escape(inline.c); case 'Softbreak': return this.softbreak; case 'Hardbreak': return inTags('br',[],"",true) + '\n'; case 'Emph': return inTags('em', [], this.renderInlines(inline.c)); case 'Strong': return inTags('strong', [], this.renderInlines(inline.c)); case 'Html': return inline.c; case 'Entity': return inline.c; case 'Link': attrs = [['href', this.escape(inline.destination, true)]]; if (inline.title) { attrs.push(['title', this.escape(inline.title, true)]); } return inTags('a', attrs, this.renderInlines(inline.label)); case 'Image': attrs = [['src', this.escape(inline.destination, true)], ['alt', this.escape(this.renderInlines(inline.label))]]; if (inline.title) { attrs.push(['title', this.escape(inline.title, true)]); } return inTags('img', attrs, "", true); case 'Code': return inTags('code', [], this.escape(inline.c)); default: console.log("Uknown inline type " + inline.t); return ""; } }
[ "function", "(", "inline", ")", "{", "var", "attrs", ";", "switch", "(", "inline", ".", "t", ")", "{", "case", "'Str'", ":", "return", "this", ".", "escape", "(", "inline", ".", "c", ")", ";", "case", "'Softbreak'", ":", "return", "this", ".", "softbreak", ";", "case", "'Hardbreak'", ":", "return", "inTags", "(", "'br'", ",", "[", "]", ",", "\"\"", ",", "true", ")", "+", "'\\n'", ";", "case", "'Emph'", ":", "return", "inTags", "(", "'em'", ",", "[", "]", ",", "this", ".", "renderInlines", "(", "inline", ".", "c", ")", ")", ";", "case", "'Strong'", ":", "return", "inTags", "(", "'strong'", ",", "[", "]", ",", "this", ".", "renderInlines", "(", "inline", ".", "c", ")", ")", ";", "case", "'Html'", ":", "return", "inline", ".", "c", ";", "case", "'Entity'", ":", "return", "inline", ".", "c", ";", "case", "'Link'", ":", "attrs", "=", "[", "[", "'href'", ",", "this", ".", "escape", "(", "inline", ".", "destination", ",", "true", ")", "]", "]", ";", "if", "(", "inline", ".", "title", ")", "{", "attrs", ".", "push", "(", "[", "'title'", ",", "this", ".", "escape", "(", "inline", ".", "title", ",", "true", ")", "]", ")", ";", "}", "return", "inTags", "(", "'a'", ",", "attrs", ",", "this", ".", "renderInlines", "(", "inline", ".", "label", ")", ")", ";", "case", "'Image'", ":", "attrs", "=", "[", "[", "'src'", ",", "this", ".", "escape", "(", "inline", ".", "destination", ",", "true", ")", "]", ",", "[", "'alt'", ",", "this", ".", "escape", "(", "this", ".", "renderInlines", "(", "inline", ".", "label", ")", ")", "]", "]", ";", "if", "(", "inline", ".", "title", ")", "{", "attrs", ".", "push", "(", "[", "'title'", ",", "this", ".", "escape", "(", "inline", ".", "title", ",", "true", ")", "]", ")", ";", "}", "return", "inTags", "(", "'img'", ",", "attrs", ",", "\"\"", ",", "true", ")", ";", "case", "'Code'", ":", "return", "inTags", "(", "'code'", ",", "[", "]", ",", "this", ".", "escape", "(", "inline", ".", "c", ")", ")", ";", "default", ":", "console", ".", "log", "(", "\"Uknown inline type \"", "+", "inline", ".", "t", ")", ";", "return", "\"\"", ";", "}", "}" ]
Render an inline element as HTML.
[ "Render", "an", "inline", "element", "as", "HTML", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L1401-L1437
19,193
bitovi/documentjs
lib/stmd.js
function(inlines) { var result = ''; for (var i=0; i < inlines.length; i++) { result = result + this.renderInline(inlines[i]); } return result; }
javascript
function(inlines) { var result = ''; for (var i=0; i < inlines.length; i++) { result = result + this.renderInline(inlines[i]); } return result; }
[ "function", "(", "inlines", ")", "{", "var", "result", "=", "''", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "inlines", ".", "length", ";", "i", "++", ")", "{", "result", "=", "result", "+", "this", ".", "renderInline", "(", "inlines", "[", "i", "]", ")", ";", "}", "return", "result", ";", "}" ]
Render a list of inlines.
[ "Render", "a", "list", "of", "inlines", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L1440-L1446
19,194
bitovi/documentjs
lib/stmd.js
function(block, in_tight_list) { var tag; var attr; var info_words; switch (block.t) { case 'Document': var whole_doc = this.renderBlocks(block.children); return (whole_doc === '' ? '' : whole_doc + '\n'); case 'Paragraph': if (in_tight_list) { return this.renderInlines(block.inline_content); } else { return inTags('p', [], this.renderInlines(block.inline_content)); } break; case 'BlockQuote': var filling = this.renderBlocks(block.children); return inTags('blockquote', [], filling === '' ? this.innersep : this.innersep + this.renderBlocks(block.children) + this.innersep); case 'ListItem': return inTags('li', [], this.renderBlocks(block.children, in_tight_list).trim()); case 'List': tag = block.list_data.type == 'Bullet' ? 'ul' : 'ol'; attr = (!block.list_data.start || block.list_data.start == 1) ? [] : [['start', block.list_data.start.toString()]]; return inTags(tag, attr, this.innersep + this.renderBlocks(block.children, block.tight) + this.innersep); case 'ATXHeader': case 'SetextHeader': tag = 'h' + block.level; return inTags(tag, [], this.renderInlines(block.inline_content)); case 'IndentedCode': return inTags('pre', [], inTags('code', [], this.escape(block.string_content))); case 'FencedCode': info_words = block.info.split(/ +/); attr = info_words.length === 0 || info_words[0].length === 0 ? [] : [['class','language-' + this.escape(info_words[0],true)]]; return inTags('pre', [], inTags('code', attr, this.escape(block.string_content))); case 'HtmlBlock': return block.string_content; case 'ReferenceDef': return ""; case 'HorizontalRule': return inTags('hr',[],"",true); default: console.log("Uknown block type " + block.t); return ""; } }
javascript
function(block, in_tight_list) { var tag; var attr; var info_words; switch (block.t) { case 'Document': var whole_doc = this.renderBlocks(block.children); return (whole_doc === '' ? '' : whole_doc + '\n'); case 'Paragraph': if (in_tight_list) { return this.renderInlines(block.inline_content); } else { return inTags('p', [], this.renderInlines(block.inline_content)); } break; case 'BlockQuote': var filling = this.renderBlocks(block.children); return inTags('blockquote', [], filling === '' ? this.innersep : this.innersep + this.renderBlocks(block.children) + this.innersep); case 'ListItem': return inTags('li', [], this.renderBlocks(block.children, in_tight_list).trim()); case 'List': tag = block.list_data.type == 'Bullet' ? 'ul' : 'ol'; attr = (!block.list_data.start || block.list_data.start == 1) ? [] : [['start', block.list_data.start.toString()]]; return inTags(tag, attr, this.innersep + this.renderBlocks(block.children, block.tight) + this.innersep); case 'ATXHeader': case 'SetextHeader': tag = 'h' + block.level; return inTags(tag, [], this.renderInlines(block.inline_content)); case 'IndentedCode': return inTags('pre', [], inTags('code', [], this.escape(block.string_content))); case 'FencedCode': info_words = block.info.split(/ +/); attr = info_words.length === 0 || info_words[0].length === 0 ? [] : [['class','language-' + this.escape(info_words[0],true)]]; return inTags('pre', [], inTags('code', attr, this.escape(block.string_content))); case 'HtmlBlock': return block.string_content; case 'ReferenceDef': return ""; case 'HorizontalRule': return inTags('hr',[],"",true); default: console.log("Uknown block type " + block.t); return ""; } }
[ "function", "(", "block", ",", "in_tight_list", ")", "{", "var", "tag", ";", "var", "attr", ";", "var", "info_words", ";", "switch", "(", "block", ".", "t", ")", "{", "case", "'Document'", ":", "var", "whole_doc", "=", "this", ".", "renderBlocks", "(", "block", ".", "children", ")", ";", "return", "(", "whole_doc", "===", "''", "?", "''", ":", "whole_doc", "+", "'\\n'", ")", ";", "case", "'Paragraph'", ":", "if", "(", "in_tight_list", ")", "{", "return", "this", ".", "renderInlines", "(", "block", ".", "inline_content", ")", ";", "}", "else", "{", "return", "inTags", "(", "'p'", ",", "[", "]", ",", "this", ".", "renderInlines", "(", "block", ".", "inline_content", ")", ")", ";", "}", "break", ";", "case", "'BlockQuote'", ":", "var", "filling", "=", "this", ".", "renderBlocks", "(", "block", ".", "children", ")", ";", "return", "inTags", "(", "'blockquote'", ",", "[", "]", ",", "filling", "===", "''", "?", "this", ".", "innersep", ":", "this", ".", "innersep", "+", "this", ".", "renderBlocks", "(", "block", ".", "children", ")", "+", "this", ".", "innersep", ")", ";", "case", "'ListItem'", ":", "return", "inTags", "(", "'li'", ",", "[", "]", ",", "this", ".", "renderBlocks", "(", "block", ".", "children", ",", "in_tight_list", ")", ".", "trim", "(", ")", ")", ";", "case", "'List'", ":", "tag", "=", "block", ".", "list_data", ".", "type", "==", "'Bullet'", "?", "'ul'", ":", "'ol'", ";", "attr", "=", "(", "!", "block", ".", "list_data", ".", "start", "||", "block", ".", "list_data", ".", "start", "==", "1", ")", "?", "[", "]", ":", "[", "[", "'start'", ",", "block", ".", "list_data", ".", "start", ".", "toString", "(", ")", "]", "]", ";", "return", "inTags", "(", "tag", ",", "attr", ",", "this", ".", "innersep", "+", "this", ".", "renderBlocks", "(", "block", ".", "children", ",", "block", ".", "tight", ")", "+", "this", ".", "innersep", ")", ";", "case", "'ATXHeader'", ":", "case", "'SetextHeader'", ":", "tag", "=", "'h'", "+", "block", ".", "level", ";", "return", "inTags", "(", "tag", ",", "[", "]", ",", "this", ".", "renderInlines", "(", "block", ".", "inline_content", ")", ")", ";", "case", "'IndentedCode'", ":", "return", "inTags", "(", "'pre'", ",", "[", "]", ",", "inTags", "(", "'code'", ",", "[", "]", ",", "this", ".", "escape", "(", "block", ".", "string_content", ")", ")", ")", ";", "case", "'FencedCode'", ":", "info_words", "=", "block", ".", "info", ".", "split", "(", "/", " +", "/", ")", ";", "attr", "=", "info_words", ".", "length", "===", "0", "||", "info_words", "[", "0", "]", ".", "length", "===", "0", "?", "[", "]", ":", "[", "[", "'class'", ",", "'language-'", "+", "this", ".", "escape", "(", "info_words", "[", "0", "]", ",", "true", ")", "]", "]", ";", "return", "inTags", "(", "'pre'", ",", "[", "]", ",", "inTags", "(", "'code'", ",", "attr", ",", "this", ".", "escape", "(", "block", ".", "string_content", ")", ")", ")", ";", "case", "'HtmlBlock'", ":", "return", "block", ".", "string_content", ";", "case", "'ReferenceDef'", ":", "return", "\"\"", ";", "case", "'HorizontalRule'", ":", "return", "inTags", "(", "'hr'", ",", "[", "]", ",", "\"\"", ",", "true", ")", ";", "default", ":", "console", ".", "log", "(", "\"Uknown block type \"", "+", "block", ".", "t", ")", ";", "return", "\"\"", ";", "}", "}" ]
Render a single block element.
[ "Render", "a", "single", "block", "element", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L1449-L1501
19,195
bitovi/documentjs
lib/stmd.js
function(blocks, in_tight_list) { var result = []; for (var i=0; i < blocks.length; i++) { if (blocks[i].t !== 'ReferenceDef') { result.push(this.renderBlock(blocks[i], in_tight_list)); } } return result.join(this.blocksep); }
javascript
function(blocks, in_tight_list) { var result = []; for (var i=0; i < blocks.length; i++) { if (blocks[i].t !== 'ReferenceDef') { result.push(this.renderBlock(blocks[i], in_tight_list)); } } return result.join(this.blocksep); }
[ "function", "(", "blocks", ",", "in_tight_list", ")", "{", "var", "result", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "blocks", ".", "length", ";", "i", "++", ")", "{", "if", "(", "blocks", "[", "i", "]", ".", "t", "!==", "'ReferenceDef'", ")", "{", "result", ".", "push", "(", "this", ".", "renderBlock", "(", "blocks", "[", "i", "]", ",", "in_tight_list", ")", ")", ";", "}", "}", "return", "result", ".", "join", "(", "this", ".", "blocksep", ")", ";", "}" ]
Render a list of block elements, separated by this.blocksep.
[ "Render", "a", "list", "of", "block", "elements", "separated", "by", "this", ".", "blocksep", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L1504-L1512
19,196
bitovi/documentjs
lib/stmd.js
HtmlRenderer
function HtmlRenderer(){ return { // default options: blocksep: '\n', // space between blocks innersep: '\n', // space between block container tag and contents softbreak: '\n', // by default, soft breaks are rendered as newlines in HTML // set to "<br />" to make them hard breaks // set to " " if you want to ignore line wrapping in source escape: function(s, preserve_entities) { if (preserve_entities) { return s.replace(/[&](?![#](x[a-f0-9]{1,8}|[0-9]{1,8});|[a-z][a-z0-9]{1,31};)/gi,'&amp;') .replace(/[<]/g,'&lt;') .replace(/[>]/g,'&gt;') .replace(/["]/g,'&quot;'); } else { return s.replace(/[&]/g,'&amp;') .replace(/[<]/g,'&lt;') .replace(/[>]/g,'&gt;') .replace(/["]/g,'&quot;'); } }, renderInline: renderInline, renderInlines: renderInlines, renderBlock: renderBlock, renderBlocks: renderBlocks, render: renderBlock }; }
javascript
function HtmlRenderer(){ return { // default options: blocksep: '\n', // space between blocks innersep: '\n', // space between block container tag and contents softbreak: '\n', // by default, soft breaks are rendered as newlines in HTML // set to "<br />" to make them hard breaks // set to " " if you want to ignore line wrapping in source escape: function(s, preserve_entities) { if (preserve_entities) { return s.replace(/[&](?![#](x[a-f0-9]{1,8}|[0-9]{1,8});|[a-z][a-z0-9]{1,31};)/gi,'&amp;') .replace(/[<]/g,'&lt;') .replace(/[>]/g,'&gt;') .replace(/["]/g,'&quot;'); } else { return s.replace(/[&]/g,'&amp;') .replace(/[<]/g,'&lt;') .replace(/[>]/g,'&gt;') .replace(/["]/g,'&quot;'); } }, renderInline: renderInline, renderInlines: renderInlines, renderBlock: renderBlock, renderBlocks: renderBlocks, render: renderBlock }; }
[ "function", "HtmlRenderer", "(", ")", "{", "return", "{", "// default options:", "blocksep", ":", "'\\n'", ",", "// space between blocks", "innersep", ":", "'\\n'", ",", "// space between block container tag and contents", "softbreak", ":", "'\\n'", ",", "// by default, soft breaks are rendered as newlines in HTML", "// set to \"<br />\" to make them hard breaks", "// set to \" \" if you want to ignore line wrapping in source", "escape", ":", "function", "(", "s", ",", "preserve_entities", ")", "{", "if", "(", "preserve_entities", ")", "{", "return", "s", ".", "replace", "(", "/", "[&](?![#](x[a-f0-9]{1,8}|[0-9]{1,8});|[a-z][a-z0-9]{1,31};)", "/", "gi", ",", "'&amp;'", ")", ".", "replace", "(", "/", "[<]", "/", "g", ",", "'&lt;'", ")", ".", "replace", "(", "/", "[>]", "/", "g", ",", "'&gt;'", ")", ".", "replace", "(", "/", "[\"]", "/", "g", ",", "'&quot;'", ")", ";", "}", "else", "{", "return", "s", ".", "replace", "(", "/", "[&]", "/", "g", ",", "'&amp;'", ")", ".", "replace", "(", "/", "[<]", "/", "g", ",", "'&lt;'", ")", ".", "replace", "(", "/", "[>]", "/", "g", ",", "'&gt;'", ")", ".", "replace", "(", "/", "[\"]", "/", "g", ",", "'&quot;'", ")", ";", "}", "}", ",", "renderInline", ":", "renderInline", ",", "renderInlines", ":", "renderInlines", ",", "renderBlock", ":", "renderBlock", ",", "renderBlocks", ":", "renderBlocks", ",", "render", ":", "renderBlock", "}", ";", "}" ]
The HtmlRenderer object.
[ "The", "HtmlRenderer", "object", "." ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/stmd.js#L1515-L1542
19,197
bitovi/documentjs
lib/process/file.js
typeCreateHandler
function typeCreateHandler(docObject, newScope) { docObject && addDocObjectToDocMap(docObject, docMap, filename, comment && comment.line); if (newScope) { scope = newScope; } }
javascript
function typeCreateHandler(docObject, newScope) { docObject && addDocObjectToDocMap(docObject, docMap, filename, comment && comment.line); if (newScope) { scope = newScope; } }
[ "function", "typeCreateHandler", "(", "docObject", ",", "newScope", ")", "{", "docObject", "&&", "addDocObjectToDocMap", "(", "docObject", ",", "docMap", ",", "filename", ",", "comment", "&&", "comment", ".", "line", ")", ";", "if", "(", "newScope", ")", "{", "scope", "=", "newScope", ";", "}", "}" ]
A callback that gets called with the docObject created and the scope
[ "A", "callback", "that", "gets", "called", "with", "the", "docObject", "created", "and", "the", "scope" ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/process/file.js#L64-L70
19,198
bitovi/documentjs
lib/process/file.js
makeDocObject
function makeDocObject(base, line, codeLine){ var docObject = _.extend({}, base); if(filename) { docObject.src = filename + ""; } if (typeof line === 'number') { docObject.line = line; } if (typeof codeLine === 'number') { docObject.codeLine = codeLine; } return docObject; }
javascript
function makeDocObject(base, line, codeLine){ var docObject = _.extend({}, base); if(filename) { docObject.src = filename + ""; } if (typeof line === 'number') { docObject.line = line; } if (typeof codeLine === 'number') { docObject.codeLine = codeLine; } return docObject; }
[ "function", "makeDocObject", "(", "base", ",", "line", ",", "codeLine", ")", "{", "var", "docObject", "=", "_", ".", "extend", "(", "{", "}", ",", "base", ")", ";", "if", "(", "filename", ")", "{", "docObject", ".", "src", "=", "filename", "+", "\"\"", ";", "}", "if", "(", "typeof", "line", "===", "'number'", ")", "{", "docObject", ".", "line", "=", "line", ";", "}", "if", "(", "typeof", "codeLine", "===", "'number'", ")", "{", "docObject", ".", "codeLine", "=", "codeLine", ";", "}", "return", "docObject", ";", "}" ]
makes a docObject with a src and line
[ "makes", "a", "docObject", "with", "a", "src", "and", "line" ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/process/file.js#L72-L84
19,199
bitovi/documentjs
lib/process/comment.js
function(indentationStack, indentation, docObject, keepStack ){ if(!keepStack) { while(indentationStack.length && _.last(indentationStack).indentation >= indentation) { var top = indentationStack.pop(); if(top.tag && top.tag.end) { top.tag.end.call(docObject, top.tagData); } } } return indentationStack.length ? _.last(indentationStack).tagData : docObject; }
javascript
function(indentationStack, indentation, docObject, keepStack ){ if(!keepStack) { while(indentationStack.length && _.last(indentationStack).indentation >= indentation) { var top = indentationStack.pop(); if(top.tag && top.tag.end) { top.tag.end.call(docObject, top.tagData); } } } return indentationStack.length ? _.last(indentationStack).tagData : docObject; }
[ "function", "(", "indentationStack", ",", "indentation", ",", "docObject", ",", "keepStack", ")", "{", "if", "(", "!", "keepStack", ")", "{", "while", "(", "indentationStack", ".", "length", "&&", "_", ".", "last", "(", "indentationStack", ")", ".", "indentation", ">=", "indentation", ")", "{", "var", "top", "=", "indentationStack", ".", "pop", "(", ")", ";", "if", "(", "top", ".", "tag", "&&", "top", ".", "tag", ".", "end", ")", "{", "top", ".", "tag", ".", "end", ".", "call", "(", "docObject", ",", "top", ".", "tagData", ")", ";", "}", "}", "}", "return", "indentationStack", ".", "length", "?", "_", ".", "last", "(", "indentationStack", ")", ".", "tagData", ":", "docObject", ";", "}" ]
pop off the stack until indentation matches
[ "pop", "off", "the", "stack", "until", "indentation", "matches" ]
5f6af5b213b840a0bfca1e146f1678db853f3b60
https://github.com/bitovi/documentjs/blob/5f6af5b213b840a0bfca1e146f1678db853f3b60/lib/process/comment.js#L144-L154