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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
12,900
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(indentation)
{
this.moveToNextLine();
var newIndent = null;
var indent = null;
if ( !this.isDefined(indentation) )
{
newIndent = this.getCurrentLineIndentation();
var unindentedEmbedBlock = this.isStringUnIndentedCollectionItem(this.currentLine);
if ( !this.isCurrentLineEmpty() && 0 == newIndent && !unindentedEmbedBlock )
{
throw new YamlParseException('Indentation problem A', this.getRealCurrentLineNb() + 1, this.currentLine);
}
}
else
{
newIndent = indentation;
}
var data = [this.currentLine.substr(newIndent)];
var isUnindentedCollection = this.isStringUnIndentedCollectionItem(this.currentLine);
var continuationIndent = -1;
if (isUnindentedCollection === true) {
continuationIndent = 1 + /^\-((\s+)(.+?))?\s*$/.exec(this.currentLine)[2].length;
}
while ( this.moveToNextLine() )
{
if (isUnindentedCollection && !this.isStringUnIndentedCollectionItem(this.currentLine) && this.getCurrentLineIndentation() != continuationIndent) {
this.moveToPreviousLine();
break;
}
if ( this.isCurrentLineEmpty() )
{
if ( this.isCurrentLineBlank() )
{
data.push(this.currentLine.substr(newIndent));
}
continue;
}
indent = this.getCurrentLineIndentation();
var matches;
if ( matches = /^( *)$/.exec(this.currentLine) )
{
// empty line
data.push(matches[1]);
}
else if ( indent >= newIndent )
{
data.push(this.currentLine.substr(newIndent));
}
else if ( 0 == indent )
{
this.moveToPreviousLine();
break;
}
else
{
throw new YamlParseException('Indentation problem B', this.getRealCurrentLineNb() + 1, this.currentLine);
}
}
return data.join("\n");
}
|
javascript
|
function(indentation)
{
this.moveToNextLine();
var newIndent = null;
var indent = null;
if ( !this.isDefined(indentation) )
{
newIndent = this.getCurrentLineIndentation();
var unindentedEmbedBlock = this.isStringUnIndentedCollectionItem(this.currentLine);
if ( !this.isCurrentLineEmpty() && 0 == newIndent && !unindentedEmbedBlock )
{
throw new YamlParseException('Indentation problem A', this.getRealCurrentLineNb() + 1, this.currentLine);
}
}
else
{
newIndent = indentation;
}
var data = [this.currentLine.substr(newIndent)];
var isUnindentedCollection = this.isStringUnIndentedCollectionItem(this.currentLine);
var continuationIndent = -1;
if (isUnindentedCollection === true) {
continuationIndent = 1 + /^\-((\s+)(.+?))?\s*$/.exec(this.currentLine)[2].length;
}
while ( this.moveToNextLine() )
{
if (isUnindentedCollection && !this.isStringUnIndentedCollectionItem(this.currentLine) && this.getCurrentLineIndentation() != continuationIndent) {
this.moveToPreviousLine();
break;
}
if ( this.isCurrentLineEmpty() )
{
if ( this.isCurrentLineBlank() )
{
data.push(this.currentLine.substr(newIndent));
}
continue;
}
indent = this.getCurrentLineIndentation();
var matches;
if ( matches = /^( *)$/.exec(this.currentLine) )
{
// empty line
data.push(matches[1]);
}
else if ( indent >= newIndent )
{
data.push(this.currentLine.substr(newIndent));
}
else if ( 0 == indent )
{
this.moveToPreviousLine();
break;
}
else
{
throw new YamlParseException('Indentation problem B', this.getRealCurrentLineNb() + 1, this.currentLine);
}
}
return data.join("\n");
}
|
[
"function",
"(",
"indentation",
")",
"{",
"this",
".",
"moveToNextLine",
"(",
")",
";",
"var",
"newIndent",
"=",
"null",
";",
"var",
"indent",
"=",
"null",
";",
"if",
"(",
"!",
"this",
".",
"isDefined",
"(",
"indentation",
")",
")",
"{",
"newIndent",
"=",
"this",
".",
"getCurrentLineIndentation",
"(",
")",
";",
"var",
"unindentedEmbedBlock",
"=",
"this",
".",
"isStringUnIndentedCollectionItem",
"(",
"this",
".",
"currentLine",
")",
";",
"if",
"(",
"!",
"this",
".",
"isCurrentLineEmpty",
"(",
")",
"&&",
"0",
"==",
"newIndent",
"&&",
"!",
"unindentedEmbedBlock",
")",
"{",
"throw",
"new",
"YamlParseException",
"(",
"'Indentation problem A'",
",",
"this",
".",
"getRealCurrentLineNb",
"(",
")",
"+",
"1",
",",
"this",
".",
"currentLine",
")",
";",
"}",
"}",
"else",
"{",
"newIndent",
"=",
"indentation",
";",
"}",
"var",
"data",
"=",
"[",
"this",
".",
"currentLine",
".",
"substr",
"(",
"newIndent",
")",
"]",
";",
"var",
"isUnindentedCollection",
"=",
"this",
".",
"isStringUnIndentedCollectionItem",
"(",
"this",
".",
"currentLine",
")",
";",
"var",
"continuationIndent",
"=",
"-",
"1",
";",
"if",
"(",
"isUnindentedCollection",
"===",
"true",
")",
"{",
"continuationIndent",
"=",
"1",
"+",
"/",
"^\\-((\\s+)(.+?))?\\s*$",
"/",
".",
"exec",
"(",
"this",
".",
"currentLine",
")",
"[",
"2",
"]",
".",
"length",
";",
"}",
"while",
"(",
"this",
".",
"moveToNextLine",
"(",
")",
")",
"{",
"if",
"(",
"isUnindentedCollection",
"&&",
"!",
"this",
".",
"isStringUnIndentedCollectionItem",
"(",
"this",
".",
"currentLine",
")",
"&&",
"this",
".",
"getCurrentLineIndentation",
"(",
")",
"!=",
"continuationIndent",
")",
"{",
"this",
".",
"moveToPreviousLine",
"(",
")",
";",
"break",
";",
"}",
"if",
"(",
"this",
".",
"isCurrentLineEmpty",
"(",
")",
")",
"{",
"if",
"(",
"this",
".",
"isCurrentLineBlank",
"(",
")",
")",
"{",
"data",
".",
"push",
"(",
"this",
".",
"currentLine",
".",
"substr",
"(",
"newIndent",
")",
")",
";",
"}",
"continue",
";",
"}",
"indent",
"=",
"this",
".",
"getCurrentLineIndentation",
"(",
")",
";",
"var",
"matches",
";",
"if",
"(",
"matches",
"=",
"/",
"^( *)$",
"/",
".",
"exec",
"(",
"this",
".",
"currentLine",
")",
")",
"{",
"// empty line",
"data",
".",
"push",
"(",
"matches",
"[",
"1",
"]",
")",
";",
"}",
"else",
"if",
"(",
"indent",
">=",
"newIndent",
")",
"{",
"data",
".",
"push",
"(",
"this",
".",
"currentLine",
".",
"substr",
"(",
"newIndent",
")",
")",
";",
"}",
"else",
"if",
"(",
"0",
"==",
"indent",
")",
"{",
"this",
".",
"moveToPreviousLine",
"(",
")",
";",
"break",
";",
"}",
"else",
"{",
"throw",
"new",
"YamlParseException",
"(",
"'Indentation problem B'",
",",
"this",
".",
"getRealCurrentLineNb",
"(",
")",
"+",
"1",
",",
"this",
".",
"currentLine",
")",
";",
"}",
"}",
"return",
"data",
".",
"join",
"(",
"\"\\n\"",
")",
";",
"}"
] |
Returns the next embed block of YAML.
@param integer indentation The indent level at which the block is to be read, or null for default
@return string A YAML string
@throws YamlParseException When indentation problem are detected
|
[
"Returns",
"the",
"next",
"embed",
"block",
"of",
"YAML",
"."
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L1270-L1343
|
|
12,901
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(value)
{
if ( '*' == (value+'').charAt(0) )
{
if ( this.trim(value).charAt(0) == '#' )
{
value = (value+'').substr(1, value.indexOf('#') - 2);
}
else
{
value = (value+'').substr(1);
}
if ( this.refs[value] == undefined )
{
throw new YamlParseException('Reference "'+value+'" does not exist', this.getRealCurrentLineNb() + 1, this.currentLine);
}
return this.refs[value];
}
var matches = null;
if ( matches = /^(\||>)(\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?( +#.*)?$/.exec(value) )
{
matches = {separator: matches[1], modifiers: matches[2], comments: matches[3]};
var modifiers = this.isDefined(matches.modifiers) ? matches.modifiers : '';
return this.parseFoldedScalar(matches.separator, modifiers.replace(/\d+/g, ''), Math.abs(parseInt(modifiers)));
}
try {
return new YamlInline().parse(value);
} catch (e) {
if ( e instanceof YamlParseException ) {
e.setParsedLine(this.getRealCurrentLineNb() + 1);
e.setSnippet(this.currentLine);
}
throw e;
}
}
|
javascript
|
function(value)
{
if ( '*' == (value+'').charAt(0) )
{
if ( this.trim(value).charAt(0) == '#' )
{
value = (value+'').substr(1, value.indexOf('#') - 2);
}
else
{
value = (value+'').substr(1);
}
if ( this.refs[value] == undefined )
{
throw new YamlParseException('Reference "'+value+'" does not exist', this.getRealCurrentLineNb() + 1, this.currentLine);
}
return this.refs[value];
}
var matches = null;
if ( matches = /^(\||>)(\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?( +#.*)?$/.exec(value) )
{
matches = {separator: matches[1], modifiers: matches[2], comments: matches[3]};
var modifiers = this.isDefined(matches.modifiers) ? matches.modifiers : '';
return this.parseFoldedScalar(matches.separator, modifiers.replace(/\d+/g, ''), Math.abs(parseInt(modifiers)));
}
try {
return new YamlInline().parse(value);
} catch (e) {
if ( e instanceof YamlParseException ) {
e.setParsedLine(this.getRealCurrentLineNb() + 1);
e.setSnippet(this.currentLine);
}
throw e;
}
}
|
[
"function",
"(",
"value",
")",
"{",
"if",
"(",
"'*'",
"==",
"(",
"value",
"+",
"''",
")",
".",
"charAt",
"(",
"0",
")",
")",
"{",
"if",
"(",
"this",
".",
"trim",
"(",
"value",
")",
".",
"charAt",
"(",
"0",
")",
"==",
"'#'",
")",
"{",
"value",
"=",
"(",
"value",
"+",
"''",
")",
".",
"substr",
"(",
"1",
",",
"value",
".",
"indexOf",
"(",
"'#'",
")",
"-",
"2",
")",
";",
"}",
"else",
"{",
"value",
"=",
"(",
"value",
"+",
"''",
")",
".",
"substr",
"(",
"1",
")",
";",
"}",
"if",
"(",
"this",
".",
"refs",
"[",
"value",
"]",
"==",
"undefined",
")",
"{",
"throw",
"new",
"YamlParseException",
"(",
"'Reference \"'",
"+",
"value",
"+",
"'\" does not exist'",
",",
"this",
".",
"getRealCurrentLineNb",
"(",
")",
"+",
"1",
",",
"this",
".",
"currentLine",
")",
";",
"}",
"return",
"this",
".",
"refs",
"[",
"value",
"]",
";",
"}",
"var",
"matches",
"=",
"null",
";",
"if",
"(",
"matches",
"=",
"/",
"^(\\||>)(\\+|\\-|\\d+|\\+\\d+|\\-\\d+|\\d+\\+|\\d+\\-)?( +#.*)?$",
"/",
".",
"exec",
"(",
"value",
")",
")",
"{",
"matches",
"=",
"{",
"separator",
":",
"matches",
"[",
"1",
"]",
",",
"modifiers",
":",
"matches",
"[",
"2",
"]",
",",
"comments",
":",
"matches",
"[",
"3",
"]",
"}",
";",
"var",
"modifiers",
"=",
"this",
".",
"isDefined",
"(",
"matches",
".",
"modifiers",
")",
"?",
"matches",
".",
"modifiers",
":",
"''",
";",
"return",
"this",
".",
"parseFoldedScalar",
"(",
"matches",
".",
"separator",
",",
"modifiers",
".",
"replace",
"(",
"/",
"\\d+",
"/",
"g",
",",
"''",
")",
",",
"Math",
".",
"abs",
"(",
"parseInt",
"(",
"modifiers",
")",
")",
")",
";",
"}",
"try",
"{",
"return",
"new",
"YamlInline",
"(",
")",
".",
"parse",
"(",
"value",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"e",
"instanceof",
"YamlParseException",
")",
"{",
"e",
".",
"setParsedLine",
"(",
"this",
".",
"getRealCurrentLineNb",
"(",
")",
"+",
"1",
")",
";",
"e",
".",
"setSnippet",
"(",
"this",
".",
"currentLine",
")",
";",
"}",
"throw",
"e",
";",
"}",
"}"
] |
Parses a YAML value.
@param string value A YAML value
@return mixed A JS value
@throws YamlParseException When reference does not exist
|
[
"Parses",
"a",
"YAML",
"value",
"."
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L1381-L1418
|
|
12,902
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(separator, indicator, indentation)
{
if ( indicator == undefined ) indicator = '';
if ( indentation == undefined ) indentation = 0;
separator = '|' == separator ? "\n" : ' ';
var text = '';
var diff = null;
var notEOF = this.moveToNextLine();
while ( notEOF && this.isCurrentLineBlank() )
{
text += "\n";
notEOF = this.moveToNextLine();
}
if ( !notEOF )
{
return '';
}
var matches = null;
if ( !(matches = new RegExp('^('+(indentation ? this.strRepeat(' ', indentation) : ' +')+')(.*)$').exec(this.currentLine)) )
{
this.moveToPreviousLine();
return '';
}
matches = {indent: matches[1], text: matches[2]};
var textIndent = matches.indent;
var previousIndent = 0;
text += matches.text + separator;
while ( this.currentLineNb + 1 < this.lines.length )
{
this.moveToNextLine();
if ( matches = new RegExp('^( {'+textIndent.length+',})(.+)$').exec(this.currentLine) )
{
matches = {indent: matches[1], text: matches[2]};
if ( ' ' == separator && previousIndent != matches.indent )
{
text = text.substr(0, text.length - 1)+"\n";
}
previousIndent = matches.indent;
diff = matches.indent.length - textIndent.length;
text += this.strRepeat(' ', diff) + matches.text + (diff != 0 ? "\n" : separator);
}
else if ( matches = /^( *)$/.exec(this.currentLine) )
{
text += matches[1].replace(new RegExp('^ {1,'+textIndent.length+'}','g'), '')+"\n";
}
else
{
this.moveToPreviousLine();
break;
}
}
if ( ' ' == separator )
{
// replace last separator by a newline
text = text.replace(/ (\n*)$/g, "\n$1");
}
switch ( indicator )
{
case '':
text = text.replace(/\n+$/g, "\n");
break;
case '+':
break;
case '-':
text = text.replace(/\n+$/g, '');
break;
}
return text;
}
|
javascript
|
function(separator, indicator, indentation)
{
if ( indicator == undefined ) indicator = '';
if ( indentation == undefined ) indentation = 0;
separator = '|' == separator ? "\n" : ' ';
var text = '';
var diff = null;
var notEOF = this.moveToNextLine();
while ( notEOF && this.isCurrentLineBlank() )
{
text += "\n";
notEOF = this.moveToNextLine();
}
if ( !notEOF )
{
return '';
}
var matches = null;
if ( !(matches = new RegExp('^('+(indentation ? this.strRepeat(' ', indentation) : ' +')+')(.*)$').exec(this.currentLine)) )
{
this.moveToPreviousLine();
return '';
}
matches = {indent: matches[1], text: matches[2]};
var textIndent = matches.indent;
var previousIndent = 0;
text += matches.text + separator;
while ( this.currentLineNb + 1 < this.lines.length )
{
this.moveToNextLine();
if ( matches = new RegExp('^( {'+textIndent.length+',})(.+)$').exec(this.currentLine) )
{
matches = {indent: matches[1], text: matches[2]};
if ( ' ' == separator && previousIndent != matches.indent )
{
text = text.substr(0, text.length - 1)+"\n";
}
previousIndent = matches.indent;
diff = matches.indent.length - textIndent.length;
text += this.strRepeat(' ', diff) + matches.text + (diff != 0 ? "\n" : separator);
}
else if ( matches = /^( *)$/.exec(this.currentLine) )
{
text += matches[1].replace(new RegExp('^ {1,'+textIndent.length+'}','g'), '')+"\n";
}
else
{
this.moveToPreviousLine();
break;
}
}
if ( ' ' == separator )
{
// replace last separator by a newline
text = text.replace(/ (\n*)$/g, "\n$1");
}
switch ( indicator )
{
case '':
text = text.replace(/\n+$/g, "\n");
break;
case '+':
break;
case '-':
text = text.replace(/\n+$/g, '');
break;
}
return text;
}
|
[
"function",
"(",
"separator",
",",
"indicator",
",",
"indentation",
")",
"{",
"if",
"(",
"indicator",
"==",
"undefined",
")",
"indicator",
"=",
"''",
";",
"if",
"(",
"indentation",
"==",
"undefined",
")",
"indentation",
"=",
"0",
";",
"separator",
"=",
"'|'",
"==",
"separator",
"?",
"\"\\n\"",
":",
"' '",
";",
"var",
"text",
"=",
"''",
";",
"var",
"diff",
"=",
"null",
";",
"var",
"notEOF",
"=",
"this",
".",
"moveToNextLine",
"(",
")",
";",
"while",
"(",
"notEOF",
"&&",
"this",
".",
"isCurrentLineBlank",
"(",
")",
")",
"{",
"text",
"+=",
"\"\\n\"",
";",
"notEOF",
"=",
"this",
".",
"moveToNextLine",
"(",
")",
";",
"}",
"if",
"(",
"!",
"notEOF",
")",
"{",
"return",
"''",
";",
"}",
"var",
"matches",
"=",
"null",
";",
"if",
"(",
"!",
"(",
"matches",
"=",
"new",
"RegExp",
"(",
"'^('",
"+",
"(",
"indentation",
"?",
"this",
".",
"strRepeat",
"(",
"' '",
",",
"indentation",
")",
":",
"' +'",
")",
"+",
"')(.*)$'",
")",
".",
"exec",
"(",
"this",
".",
"currentLine",
")",
")",
")",
"{",
"this",
".",
"moveToPreviousLine",
"(",
")",
";",
"return",
"''",
";",
"}",
"matches",
"=",
"{",
"indent",
":",
"matches",
"[",
"1",
"]",
",",
"text",
":",
"matches",
"[",
"2",
"]",
"}",
";",
"var",
"textIndent",
"=",
"matches",
".",
"indent",
";",
"var",
"previousIndent",
"=",
"0",
";",
"text",
"+=",
"matches",
".",
"text",
"+",
"separator",
";",
"while",
"(",
"this",
".",
"currentLineNb",
"+",
"1",
"<",
"this",
".",
"lines",
".",
"length",
")",
"{",
"this",
".",
"moveToNextLine",
"(",
")",
";",
"if",
"(",
"matches",
"=",
"new",
"RegExp",
"(",
"'^( {'",
"+",
"textIndent",
".",
"length",
"+",
"',})(.+)$'",
")",
".",
"exec",
"(",
"this",
".",
"currentLine",
")",
")",
"{",
"matches",
"=",
"{",
"indent",
":",
"matches",
"[",
"1",
"]",
",",
"text",
":",
"matches",
"[",
"2",
"]",
"}",
";",
"if",
"(",
"' '",
"==",
"separator",
"&&",
"previousIndent",
"!=",
"matches",
".",
"indent",
")",
"{",
"text",
"=",
"text",
".",
"substr",
"(",
"0",
",",
"text",
".",
"length",
"-",
"1",
")",
"+",
"\"\\n\"",
";",
"}",
"previousIndent",
"=",
"matches",
".",
"indent",
";",
"diff",
"=",
"matches",
".",
"indent",
".",
"length",
"-",
"textIndent",
".",
"length",
";",
"text",
"+=",
"this",
".",
"strRepeat",
"(",
"' '",
",",
"diff",
")",
"+",
"matches",
".",
"text",
"+",
"(",
"diff",
"!=",
"0",
"?",
"\"\\n\"",
":",
"separator",
")",
";",
"}",
"else",
"if",
"(",
"matches",
"=",
"/",
"^( *)$",
"/",
".",
"exec",
"(",
"this",
".",
"currentLine",
")",
")",
"{",
"text",
"+=",
"matches",
"[",
"1",
"]",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"'^ {1,'",
"+",
"textIndent",
".",
"length",
"+",
"'}'",
",",
"'g'",
")",
",",
"''",
")",
"+",
"\"\\n\"",
";",
"}",
"else",
"{",
"this",
".",
"moveToPreviousLine",
"(",
")",
";",
"break",
";",
"}",
"}",
"if",
"(",
"' '",
"==",
"separator",
")",
"{",
"// replace last separator by a newline",
"text",
"=",
"text",
".",
"replace",
"(",
"/",
" (\\n*)$",
"/",
"g",
",",
"\"\\n$1\"",
")",
";",
"}",
"switch",
"(",
"indicator",
")",
"{",
"case",
"''",
":",
"text",
"=",
"text",
".",
"replace",
"(",
"/",
"\\n+$",
"/",
"g",
",",
"\"\\n\"",
")",
";",
"break",
";",
"case",
"'+'",
":",
"break",
";",
"case",
"'-'",
":",
"text",
"=",
"text",
".",
"replace",
"(",
"/",
"\\n+$",
"/",
"g",
",",
"''",
")",
";",
"break",
";",
"}",
"return",
"text",
";",
"}"
] |
Parses a folded scalar.
@param string separator The separator that was used to begin this folded scalar (| or >)
@param string indicator The indicator that was used to begin this folded scalar (+ or -)
@param integer indentation The indentation that was used to begin this folded scalar
@return string The text value
|
[
"Parses",
"a",
"folded",
"scalar",
"."
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L1429-L1515
|
|
12,903
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(value)
{
value = value.split("\r\n").join("\n").split("\r").join("\n");
if ( !/\n$/.test(value) )
{
value += "\n";
}
// strip YAML header
var count = 0;
var regex = /^\%YAML[: ][\d\.]+.*\n/;
while ( regex.test(value) )
{
value = value.replace(regex, '');
count++;
}
this.offset += count;
// remove leading comments
regex = /^(#.*?\n)+/;
if ( regex.test(value) )
{
var trimmedValue = value.replace(regex, '');
// items have been removed, update the offset
this.offset += this.subStrCount(value, "\n") - this.subStrCount(trimmedValue, "\n");
value = trimmedValue;
}
// remove start of the document marker (---)
regex = /^\-\-\-.*?\n/;
if ( regex.test(value) )
{
trimmedValue = value.replace(regex, '');
// items have been removed, update the offset
this.offset += this.subStrCount(value, "\n") - this.subStrCount(trimmedValue, "\n");
value = trimmedValue;
// remove end of the document marker (...)
value = value.replace(/\.\.\.\s*$/g, '');
}
return value;
}
|
javascript
|
function(value)
{
value = value.split("\r\n").join("\n").split("\r").join("\n");
if ( !/\n$/.test(value) )
{
value += "\n";
}
// strip YAML header
var count = 0;
var regex = /^\%YAML[: ][\d\.]+.*\n/;
while ( regex.test(value) )
{
value = value.replace(regex, '');
count++;
}
this.offset += count;
// remove leading comments
regex = /^(#.*?\n)+/;
if ( regex.test(value) )
{
var trimmedValue = value.replace(regex, '');
// items have been removed, update the offset
this.offset += this.subStrCount(value, "\n") - this.subStrCount(trimmedValue, "\n");
value = trimmedValue;
}
// remove start of the document marker (---)
regex = /^\-\-\-.*?\n/;
if ( regex.test(value) )
{
trimmedValue = value.replace(regex, '');
// items have been removed, update the offset
this.offset += this.subStrCount(value, "\n") - this.subStrCount(trimmedValue, "\n");
value = trimmedValue;
// remove end of the document marker (...)
value = value.replace(/\.\.\.\s*$/g, '');
}
return value;
}
|
[
"function",
"(",
"value",
")",
"{",
"value",
"=",
"value",
".",
"split",
"(",
"\"\\r\\n\"",
")",
".",
"join",
"(",
"\"\\n\"",
")",
".",
"split",
"(",
"\"\\r\"",
")",
".",
"join",
"(",
"\"\\n\"",
")",
";",
"if",
"(",
"!",
"/",
"\\n$",
"/",
".",
"test",
"(",
"value",
")",
")",
"{",
"value",
"+=",
"\"\\n\"",
";",
"}",
"// strip YAML header",
"var",
"count",
"=",
"0",
";",
"var",
"regex",
"=",
"/",
"^\\%YAML[: ][\\d\\.]+.*\\n",
"/",
";",
"while",
"(",
"regex",
".",
"test",
"(",
"value",
")",
")",
"{",
"value",
"=",
"value",
".",
"replace",
"(",
"regex",
",",
"''",
")",
";",
"count",
"++",
";",
"}",
"this",
".",
"offset",
"+=",
"count",
";",
"// remove leading comments",
"regex",
"=",
"/",
"^(#.*?\\n)+",
"/",
";",
"if",
"(",
"regex",
".",
"test",
"(",
"value",
")",
")",
"{",
"var",
"trimmedValue",
"=",
"value",
".",
"replace",
"(",
"regex",
",",
"''",
")",
";",
"// items have been removed, update the offset",
"this",
".",
"offset",
"+=",
"this",
".",
"subStrCount",
"(",
"value",
",",
"\"\\n\"",
")",
"-",
"this",
".",
"subStrCount",
"(",
"trimmedValue",
",",
"\"\\n\"",
")",
";",
"value",
"=",
"trimmedValue",
";",
"}",
"// remove start of the document marker (---)",
"regex",
"=",
"/",
"^\\-\\-\\-.*?\\n",
"/",
";",
"if",
"(",
"regex",
".",
"test",
"(",
"value",
")",
")",
"{",
"trimmedValue",
"=",
"value",
".",
"replace",
"(",
"regex",
",",
"''",
")",
";",
"// items have been removed, update the offset",
"this",
".",
"offset",
"+=",
"this",
".",
"subStrCount",
"(",
"value",
",",
"\"\\n\"",
")",
"-",
"this",
".",
"subStrCount",
"(",
"trimmedValue",
",",
"\"\\n\"",
")",
";",
"value",
"=",
"trimmedValue",
";",
"// remove end of the document marker (...)",
"value",
"=",
"value",
".",
"replace",
"(",
"/",
"\\.\\.\\.\\s*$",
"/",
"g",
",",
"''",
")",
";",
"}",
"return",
"value",
";",
"}"
] |
Cleanups a YAML string to be parsed.
@param string value The input YAML string
@return string A cleaned up YAML string
|
[
"Cleanups",
"a",
"YAML",
"string",
"to",
"be",
"parsed",
"."
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L1587-L1632
|
|
12,904
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(value)
{
value = value + '';
var len = YamlEscaper.escapees.length;
var maxlen = YamlEscaper.escaped.length;
var esc = YamlEscaper.escaped;
for (var i = 0; i < len; ++i)
if ( i >= maxlen ) esc.push('');
var ret = '';
ret = value.replace(new RegExp(YamlEscaper.escapees.join('|'),'g'), function(str){
for(var i = 0; i < len; ++i){
if( str == YamlEscaper.escapees[i] )
return esc[i];
}
});
return '"' + ret + '"';
}
|
javascript
|
function(value)
{
value = value + '';
var len = YamlEscaper.escapees.length;
var maxlen = YamlEscaper.escaped.length;
var esc = YamlEscaper.escaped;
for (var i = 0; i < len; ++i)
if ( i >= maxlen ) esc.push('');
var ret = '';
ret = value.replace(new RegExp(YamlEscaper.escapees.join('|'),'g'), function(str){
for(var i = 0; i < len; ++i){
if( str == YamlEscaper.escapees[i] )
return esc[i];
}
});
return '"' + ret + '"';
}
|
[
"function",
"(",
"value",
")",
"{",
"value",
"=",
"value",
"+",
"''",
";",
"var",
"len",
"=",
"YamlEscaper",
".",
"escapees",
".",
"length",
";",
"var",
"maxlen",
"=",
"YamlEscaper",
".",
"escaped",
".",
"length",
";",
"var",
"esc",
"=",
"YamlEscaper",
".",
"escaped",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"++",
"i",
")",
"if",
"(",
"i",
">=",
"maxlen",
")",
"esc",
".",
"push",
"(",
"''",
")",
";",
"var",
"ret",
"=",
"''",
";",
"ret",
"=",
"value",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"YamlEscaper",
".",
"escapees",
".",
"join",
"(",
"'|'",
")",
",",
"'g'",
")",
",",
"function",
"(",
"str",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"++",
"i",
")",
"{",
"if",
"(",
"str",
"==",
"YamlEscaper",
".",
"escapees",
"[",
"i",
"]",
")",
"return",
"esc",
"[",
"i",
"]",
";",
"}",
"}",
")",
";",
"return",
"'\"'",
"+",
"ret",
"+",
"'\"'",
";",
"}"
] |
Escapes and surrounds a JS value with double quotes.
@param string value A JS value
@return string The quoted, escaped string
|
[
"Escapes",
"and",
"surrounds",
"a",
"JS",
"value",
"with",
"double",
"quotes",
"."
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L1787-L1804
|
|
12,905
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(value)
{
var callback = function(m) {
return new YamlUnescaper().unescapeCharacter(m);
};
// evaluate the string
return value.replace(new RegExp(YamlUnescaper.REGEX_ESCAPED_CHARACTER, 'g'), callback);
}
|
javascript
|
function(value)
{
var callback = function(m) {
return new YamlUnescaper().unescapeCharacter(m);
};
// evaluate the string
return value.replace(new RegExp(YamlUnescaper.REGEX_ESCAPED_CHARACTER, 'g'), callback);
}
|
[
"function",
"(",
"value",
")",
"{",
"var",
"callback",
"=",
"function",
"(",
"m",
")",
"{",
"return",
"new",
"YamlUnescaper",
"(",
")",
".",
"unescapeCharacter",
"(",
"m",
")",
";",
"}",
";",
"// evaluate the string",
"return",
"value",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"YamlUnescaper",
".",
"REGEX_ESCAPED_CHARACTER",
",",
"'g'",
")",
",",
"callback",
")",
";",
"}"
] |
Unescapes a double quoted string.
@param string value A double quoted string.
@return string The unescaped string.
|
[
"Unescapes",
"a",
"double",
"quoted",
"string",
"."
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L1876-L1884
|
|
12,906
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(value)
{
switch (value.charAt(1)) {
case '0':
return String.fromCharCode(0);
case 'a':
return String.fromCharCode(7);
case 'b':
return String.fromCharCode(8);
case 't':
return "\t";
case "\t":
return "\t";
case 'n':
return "\n";
case 'v':
return String.fromCharCode(11);
case 'f':
return String.fromCharCode(12);
case 'r':
return String.fromCharCode(13);
case 'e':
return "\x1b";
case ' ':
return ' ';
case '"':
return '"';
case '/':
return '/';
case '\\':
return '\\';
case 'N':
// U+0085 NEXT LINE
return "\x00\x85";
case '_':
// U+00A0 NO-BREAK SPACE
return "\x00\xA0";
case 'L':
// U+2028 LINE SEPARATOR
return "\x20\x28";
case 'P':
// U+2029 PARAGRAPH SEPARATOR
return "\x20\x29";
case 'x':
return this.pack('n', new YamlInline().hexdec(value.substr(2, 2)));
case 'u':
return this.pack('n', new YamlInline().hexdec(value.substr(2, 4)));
case 'U':
return this.pack('N', new YamlInline().hexdec(value.substr(2, 8)));
}
}
|
javascript
|
function(value)
{
switch (value.charAt(1)) {
case '0':
return String.fromCharCode(0);
case 'a':
return String.fromCharCode(7);
case 'b':
return String.fromCharCode(8);
case 't':
return "\t";
case "\t":
return "\t";
case 'n':
return "\n";
case 'v':
return String.fromCharCode(11);
case 'f':
return String.fromCharCode(12);
case 'r':
return String.fromCharCode(13);
case 'e':
return "\x1b";
case ' ':
return ' ';
case '"':
return '"';
case '/':
return '/';
case '\\':
return '\\';
case 'N':
// U+0085 NEXT LINE
return "\x00\x85";
case '_':
// U+00A0 NO-BREAK SPACE
return "\x00\xA0";
case 'L':
// U+2028 LINE SEPARATOR
return "\x20\x28";
case 'P':
// U+2029 PARAGRAPH SEPARATOR
return "\x20\x29";
case 'x':
return this.pack('n', new YamlInline().hexdec(value.substr(2, 2)));
case 'u':
return this.pack('n', new YamlInline().hexdec(value.substr(2, 4)));
case 'U':
return this.pack('N', new YamlInline().hexdec(value.substr(2, 8)));
}
}
|
[
"function",
"(",
"value",
")",
"{",
"switch",
"(",
"value",
".",
"charAt",
"(",
"1",
")",
")",
"{",
"case",
"'0'",
":",
"return",
"String",
".",
"fromCharCode",
"(",
"0",
")",
";",
"case",
"'a'",
":",
"return",
"String",
".",
"fromCharCode",
"(",
"7",
")",
";",
"case",
"'b'",
":",
"return",
"String",
".",
"fromCharCode",
"(",
"8",
")",
";",
"case",
"'t'",
":",
"return",
"\"\\t\"",
";",
"case",
"\"\\t\"",
":",
"return",
"\"\\t\"",
";",
"case",
"'n'",
":",
"return",
"\"\\n\"",
";",
"case",
"'v'",
":",
"return",
"String",
".",
"fromCharCode",
"(",
"11",
")",
";",
"case",
"'f'",
":",
"return",
"String",
".",
"fromCharCode",
"(",
"12",
")",
";",
"case",
"'r'",
":",
"return",
"String",
".",
"fromCharCode",
"(",
"13",
")",
";",
"case",
"'e'",
":",
"return",
"\"\\x1b\"",
";",
"case",
"' '",
":",
"return",
"' '",
";",
"case",
"'\"'",
":",
"return",
"'\"'",
";",
"case",
"'/'",
":",
"return",
"'/'",
";",
"case",
"'\\\\'",
":",
"return",
"'\\\\'",
";",
"case",
"'N'",
":",
"// U+0085 NEXT LINE",
"return",
"\"\\x00\\x85\"",
";",
"case",
"'_'",
":",
"// U+00A0 NO-BREAK SPACE",
"return",
"\"\\x00\\xA0\"",
";",
"case",
"'L'",
":",
"// U+2028 LINE SEPARATOR",
"return",
"\"\\x20\\x28\"",
";",
"case",
"'P'",
":",
"// U+2029 PARAGRAPH SEPARATOR",
"return",
"\"\\x20\\x29\"",
";",
"case",
"'x'",
":",
"return",
"this",
".",
"pack",
"(",
"'n'",
",",
"new",
"YamlInline",
"(",
")",
".",
"hexdec",
"(",
"value",
".",
"substr",
"(",
"2",
",",
"2",
")",
")",
")",
";",
"case",
"'u'",
":",
"return",
"this",
".",
"pack",
"(",
"'n'",
",",
"new",
"YamlInline",
"(",
")",
".",
"hexdec",
"(",
"value",
".",
"substr",
"(",
"2",
",",
"4",
")",
")",
")",
";",
"case",
"'U'",
":",
"return",
"this",
".",
"pack",
"(",
"'N'",
",",
"new",
"YamlInline",
"(",
")",
".",
"hexdec",
"(",
"value",
".",
"substr",
"(",
"2",
",",
"8",
")",
")",
")",
";",
"}",
"}"
] |
Unescapes a character that was found in a double-quoted string
@param string value An escaped character
@return string The unescaped character
|
[
"Unescapes",
"a",
"character",
"that",
"was",
"found",
"in",
"a",
"double",
"-",
"quoted",
"string"
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L1893-L1943
|
|
12,907
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(input, inline, indent)
{
if ( inline == null ) inline = 0;
if ( indent == null ) indent = 0;
var output = '';
var prefix = indent ? this.strRepeat(' ', indent) : '';
var yaml;
if (!this.numSpacesForIndentation) this.numSpacesForIndentation = 2;
if ( inline <= 0 || !this.isObject(input) || this.isEmpty(input) )
{
yaml = new YamlInline();
output += prefix + yaml.dump(input);
}
else
{
var isAHash = !this.arrayEquals(this.getKeys(input), this.range(0,input.length - 1));
var willBeInlined;
for ( var key in input )
{
if ( input.hasOwnProperty(key) )
{
willBeInlined = inline - 1 <= 0 || !this.isObject(input[key]) || this.isEmpty(input[key]);
if ( isAHash ) yaml = new YamlInline();
output +=
prefix + '' +
(isAHash ? yaml.dump(key)+':' : '-') + '' +
(willBeInlined ? ' ' : "\n") + '' +
this.dump(input[key], inline - 1, (willBeInlined ? 0 : indent + this.numSpacesForIndentation)) + '' +
(willBeInlined ? "\n" : '');
}
}
}
return output;
}
|
javascript
|
function(input, inline, indent)
{
if ( inline == null ) inline = 0;
if ( indent == null ) indent = 0;
var output = '';
var prefix = indent ? this.strRepeat(' ', indent) : '';
var yaml;
if (!this.numSpacesForIndentation) this.numSpacesForIndentation = 2;
if ( inline <= 0 || !this.isObject(input) || this.isEmpty(input) )
{
yaml = new YamlInline();
output += prefix + yaml.dump(input);
}
else
{
var isAHash = !this.arrayEquals(this.getKeys(input), this.range(0,input.length - 1));
var willBeInlined;
for ( var key in input )
{
if ( input.hasOwnProperty(key) )
{
willBeInlined = inline - 1 <= 0 || !this.isObject(input[key]) || this.isEmpty(input[key]);
if ( isAHash ) yaml = new YamlInline();
output +=
prefix + '' +
(isAHash ? yaml.dump(key)+':' : '-') + '' +
(willBeInlined ? ' ' : "\n") + '' +
this.dump(input[key], inline - 1, (willBeInlined ? 0 : indent + this.numSpacesForIndentation)) + '' +
(willBeInlined ? "\n" : '');
}
}
}
return output;
}
|
[
"function",
"(",
"input",
",",
"inline",
",",
"indent",
")",
"{",
"if",
"(",
"inline",
"==",
"null",
")",
"inline",
"=",
"0",
";",
"if",
"(",
"indent",
"==",
"null",
")",
"indent",
"=",
"0",
";",
"var",
"output",
"=",
"''",
";",
"var",
"prefix",
"=",
"indent",
"?",
"this",
".",
"strRepeat",
"(",
"' '",
",",
"indent",
")",
":",
"''",
";",
"var",
"yaml",
";",
"if",
"(",
"!",
"this",
".",
"numSpacesForIndentation",
")",
"this",
".",
"numSpacesForIndentation",
"=",
"2",
";",
"if",
"(",
"inline",
"<=",
"0",
"||",
"!",
"this",
".",
"isObject",
"(",
"input",
")",
"||",
"this",
".",
"isEmpty",
"(",
"input",
")",
")",
"{",
"yaml",
"=",
"new",
"YamlInline",
"(",
")",
";",
"output",
"+=",
"prefix",
"+",
"yaml",
".",
"dump",
"(",
"input",
")",
";",
"}",
"else",
"{",
"var",
"isAHash",
"=",
"!",
"this",
".",
"arrayEquals",
"(",
"this",
".",
"getKeys",
"(",
"input",
")",
",",
"this",
".",
"range",
"(",
"0",
",",
"input",
".",
"length",
"-",
"1",
")",
")",
";",
"var",
"willBeInlined",
";",
"for",
"(",
"var",
"key",
"in",
"input",
")",
"{",
"if",
"(",
"input",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"willBeInlined",
"=",
"inline",
"-",
"1",
"<=",
"0",
"||",
"!",
"this",
".",
"isObject",
"(",
"input",
"[",
"key",
"]",
")",
"||",
"this",
".",
"isEmpty",
"(",
"input",
"[",
"key",
"]",
")",
";",
"if",
"(",
"isAHash",
")",
"yaml",
"=",
"new",
"YamlInline",
"(",
")",
";",
"output",
"+=",
"prefix",
"+",
"''",
"+",
"(",
"isAHash",
"?",
"yaml",
".",
"dump",
"(",
"key",
")",
"+",
"':'",
":",
"'-'",
")",
"+",
"''",
"+",
"(",
"willBeInlined",
"?",
"' '",
":",
"\"\\n\"",
")",
"+",
"''",
"+",
"this",
".",
"dump",
"(",
"input",
"[",
"key",
"]",
",",
"inline",
"-",
"1",
",",
"(",
"willBeInlined",
"?",
"0",
":",
"indent",
"+",
"this",
".",
"numSpacesForIndentation",
")",
")",
"+",
"''",
"+",
"(",
"willBeInlined",
"?",
"\"\\n\"",
":",
"''",
")",
";",
"}",
"}",
"}",
"return",
"output",
";",
"}"
] |
Dumps a JS value to YAML.
@param mixed input The JS value
@param integer inline The level where you switch to inline YAML
@param integer indent The level o indentation indentation (used internally)
@return string The YAML representation of the JS value
|
[
"Dumps",
"a",
"JS",
"value",
"to",
"YAML",
"."
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L1974-L2012
|
|
12,908
|
d3fc/d3fc
|
packages/d3fc-site/builder/handlebars-helpers/escape.js
|
register
|
function register(handlebars) {
handlebars.registerHelper('escape', function(variable) {
return variable.replace(/['"]/g, '\\"').replace(/[\n]/g, '\\n');
});
}
|
javascript
|
function register(handlebars) {
handlebars.registerHelper('escape', function(variable) {
return variable.replace(/['"]/g, '\\"').replace(/[\n]/g, '\\n');
});
}
|
[
"function",
"register",
"(",
"handlebars",
")",
"{",
"handlebars",
".",
"registerHelper",
"(",
"'escape'",
",",
"function",
"(",
"variable",
")",
"{",
"return",
"variable",
".",
"replace",
"(",
"/",
"['\"]",
"/",
"g",
",",
"'\\\\\"'",
")",
".",
"replace",
"(",
"/",
"[\\n]",
"/",
"g",
",",
"'\\\\n'",
")",
";",
"}",
")",
";",
"}"
] |
escapes quotes and newline characters using a backslash
|
[
"escapes",
"quotes",
"and",
"newline",
"characters",
"using",
"a",
"backslash"
] |
170b25711ef1fedb3adbee5dbff94e66114b17ff
|
https://github.com/d3fc/d3fc/blob/170b25711ef1fedb3adbee5dbff94e66114b17ff/packages/d3fc-site/builder/handlebars-helpers/escape.js#L2-L6
|
12,909
|
d3fc/d3fc
|
packages/d3fc-sample/site/demo.js
|
strategyInterceptor
|
function strategyInterceptor(strategy) {
var interceptor = function(layout) {
var start = new Date().getMilliseconds();
var finalLayout = strategy(data);
var time = new Date().getMilliseconds() - start;
// record some statistics on this strategy
if (!interceptor.time) {
Object.defineProperty(interceptor, 'time', { enumerable: false, writable: true });
}
interceptor.time = time;
return finalLayout;
};
interceptor.bucketSize = function() {
return strategy.bucketSize.apply(this, arguments);
};
return interceptor;
}
|
javascript
|
function strategyInterceptor(strategy) {
var interceptor = function(layout) {
var start = new Date().getMilliseconds();
var finalLayout = strategy(data);
var time = new Date().getMilliseconds() - start;
// record some statistics on this strategy
if (!interceptor.time) {
Object.defineProperty(interceptor, 'time', { enumerable: false, writable: true });
}
interceptor.time = time;
return finalLayout;
};
interceptor.bucketSize = function() {
return strategy.bucketSize.apply(this, arguments);
};
return interceptor;
}
|
[
"function",
"strategyInterceptor",
"(",
"strategy",
")",
"{",
"var",
"interceptor",
"=",
"function",
"(",
"layout",
")",
"{",
"var",
"start",
"=",
"new",
"Date",
"(",
")",
".",
"getMilliseconds",
"(",
")",
";",
"var",
"finalLayout",
"=",
"strategy",
"(",
"data",
")",
";",
"var",
"time",
"=",
"new",
"Date",
"(",
")",
".",
"getMilliseconds",
"(",
")",
"-",
"start",
";",
"// record some statistics on this strategy",
"if",
"(",
"!",
"interceptor",
".",
"time",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"interceptor",
",",
"'time'",
",",
"{",
"enumerable",
":",
"false",
",",
"writable",
":",
"true",
"}",
")",
";",
"}",
"interceptor",
".",
"time",
"=",
"time",
";",
"return",
"finalLayout",
";",
"}",
";",
"interceptor",
".",
"bucketSize",
"=",
"function",
"(",
")",
"{",
"return",
"strategy",
".",
"bucketSize",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
";",
"return",
"interceptor",
";",
"}"
] |
we intercept the strategy in order to capture the final layout and compute statistics
|
[
"we",
"intercept",
"the",
"strategy",
"in",
"order",
"to",
"capture",
"the",
"final",
"layout",
"and",
"compute",
"statistics"
] |
170b25711ef1fedb3adbee5dbff94e66114b17ff
|
https://github.com/d3fc/d3fc/blob/170b25711ef1fedb3adbee5dbff94e66114b17ff/packages/d3fc-sample/site/demo.js#L23-L42
|
12,910
|
mesosphere/reactjs-components
|
src/Util/Util.js
|
basePick
|
function basePick(object, props) {
object = Object(object);
const { length } = props;
const result = {};
let index = -1;
while (++index < length) {
const key = props[index];
if (key in object) {
result[key] = object[key];
}
}
return result;
}
|
javascript
|
function basePick(object, props) {
object = Object(object);
const { length } = props;
const result = {};
let index = -1;
while (++index < length) {
const key = props[index];
if (key in object) {
result[key] = object[key];
}
}
return result;
}
|
[
"function",
"basePick",
"(",
"object",
",",
"props",
")",
"{",
"object",
"=",
"Object",
"(",
"object",
")",
";",
"const",
"{",
"length",
"}",
"=",
"props",
";",
"const",
"result",
"=",
"{",
"}",
";",
"let",
"index",
"=",
"-",
"1",
";",
"while",
"(",
"++",
"index",
"<",
"length",
")",
"{",
"const",
"key",
"=",
"props",
"[",
"index",
"]",
";",
"if",
"(",
"key",
"in",
"object",
")",
"{",
"result",
"[",
"key",
"]",
"=",
"object",
"[",
"key",
"]",
";",
"}",
"}",
"return",
"result",
";",
"}"
] |
Functions from lodash 4.0.0-pre
The base implementation of `_.pick` without support for individual
property names.
@private
@param {Object} object The source object.
@param {string[]} props The property names to pick.
@returns {Object} Returns the new object.
|
[
"Functions",
"from",
"lodash",
"4",
".",
"0",
".",
"0",
"-",
"pre",
"The",
"base",
"implementation",
"of",
"_",
".",
"pick",
"without",
"support",
"for",
"individual",
"property",
"names",
"."
] |
363b189f17ce7891d3581a76a90cc39346f96cda
|
https://github.com/mesosphere/reactjs-components/blob/363b189f17ce7891d3581a76a90cc39346f96cda/src/Util/Util.js#L14-L29
|
12,911
|
mesosphere/reactjs-components
|
src/Util/Util.js
|
baseValues
|
function baseValues(object, props) {
const { length } = props;
const result = Array(length);
let index = -1;
while (++index < length) {
result[index] = object[props[index]];
}
return result;
}
|
javascript
|
function baseValues(object, props) {
const { length } = props;
const result = Array(length);
let index = -1;
while (++index < length) {
result[index] = object[props[index]];
}
return result;
}
|
[
"function",
"baseValues",
"(",
"object",
",",
"props",
")",
"{",
"const",
"{",
"length",
"}",
"=",
"props",
";",
"const",
"result",
"=",
"Array",
"(",
"length",
")",
";",
"let",
"index",
"=",
"-",
"1",
";",
"while",
"(",
"++",
"index",
"<",
"length",
")",
"{",
"result",
"[",
"index",
"]",
"=",
"object",
"[",
"props",
"[",
"index",
"]",
"]",
";",
"}",
"return",
"result",
";",
"}"
] |
The base implementation of `_.values` and `_.valuesIn` which creates an
array of `object` property values corresponding to the property names
of `props`.
@private
@param {Object} object The object to query.
@param {Array} props The property names to get values for.
@returns {Object} Returns the array of property values.
|
[
"The",
"base",
"implementation",
"of",
"_",
".",
"values",
"and",
"_",
".",
"valuesIn",
"which",
"creates",
"an",
"array",
"of",
"object",
"property",
"values",
"corresponding",
"to",
"the",
"property",
"names",
"of",
"props",
"."
] |
363b189f17ce7891d3581a76a90cc39346f96cda
|
https://github.com/mesosphere/reactjs-components/blob/363b189f17ce7891d3581a76a90cc39346f96cda/src/Util/Util.js#L41-L51
|
12,912
|
mesosphere/reactjs-components
|
src/Util/Util.js
|
isArrayLike
|
function isArrayLike(value) {
return (
value != null &&
value.length &&
!(
typeof value === "function" &&
Object.prototype.toString.call(value) === "[object Function]"
) &&
typeof value === "object"
);
}
|
javascript
|
function isArrayLike(value) {
return (
value != null &&
value.length &&
!(
typeof value === "function" &&
Object.prototype.toString.call(value) === "[object Function]"
) &&
typeof value === "object"
);
}
|
[
"function",
"isArrayLike",
"(",
"value",
")",
"{",
"return",
"(",
"value",
"!=",
"null",
"&&",
"value",
".",
"length",
"&&",
"!",
"(",
"typeof",
"value",
"===",
"\"function\"",
"&&",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"value",
")",
"===",
"\"[object Function]\"",
")",
"&&",
"typeof",
"value",
"===",
"\"object\"",
")",
";",
"}"
] |
Checks if `value` is array-like. A value is considered array-like if it's
not a function and has a `value.length` that's an integer greater than or
equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
@static
@category Lang
@param {*} value The value to check.
@return {Boolean} Returns `true` if `value` is array-like, else `false`.
@example
_.isArrayLike([1, 2, 3]);
// => true
_.isArrayLike(document.body.children);
// => true
_.isArrayLike('abc');
// => true
_.isArrayLike(_.noop);
// => false
|
[
"Checks",
"if",
"value",
"is",
"array",
"-",
"like",
".",
"A",
"value",
"is",
"considered",
"array",
"-",
"like",
"if",
"it",
"s",
"not",
"a",
"function",
"and",
"has",
"a",
"value",
".",
"length",
"that",
"s",
"an",
"integer",
"greater",
"than",
"or",
"equal",
"to",
"0",
"and",
"less",
"than",
"or",
"equal",
"to",
"Number",
".",
"MAX_SAFE_INTEGER",
"."
] |
363b189f17ce7891d3581a76a90cc39346f96cda
|
https://github.com/mesosphere/reactjs-components/blob/363b189f17ce7891d3581a76a90cc39346f96cda/src/Util/Util.js#L100-L110
|
12,913
|
mesosphere/reactjs-components
|
src/Util/Util.js
|
deepEq
|
function deepEq(a, b, aStack, bStack) {
// Compare `[[Class]]` names.
var className = Object.prototype.toString.call(a);
if (className !== Object.prototype.toString.call(b)) {
return false;
}
/* eslint-disable no-fallthrough */
switch (className) {
// Strings, numbers, regular expressions, dates, and booleans are compared by value.
case "[object RegExp]":
// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
case "[object String]":
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return "" + a === "" + b;
case "[object Number]":
// `NaN`s are equivalent, but non-reflexive.
// Object(NaN) is equivalent to NaN
if (+a !== +a) {
return +b !== +b;
}
// An `egal` comparison is performed for other numeric values.
return +a === 0 ? 1 / +a === 1 / b : +a === +b;
case "[object Date]":
case "[object Boolean]":
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a === +b;
/* eslint-enable no-fallthrough */
}
var areArrays = className === "[object Array]";
if (!areArrays) {
if (typeof a != "object" || typeof b != "object") {
return false;
}
// Objects with different constructors are not equivalent, but `Object`s or `Array`s
// from different frames are.
var aCtor = a.constructor,
bCtor = b.constructor;
if (
aCtor !== bCtor &&
!(
isFunction(aCtor) &&
aCtor instanceof aCtor &&
isFunction(bCtor) &&
bCtor instanceof bCtor
) &&
("constructor" in a && "constructor" in b)
) {
return false;
}
}
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
// Initializing stack of traversed objects.
// It's done here since we only need them for objects and arrays comparison.
aStack = aStack || [];
bStack = bStack || [];
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] === a) {
return bStack[length] === b;
}
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
// Recursively compare objects and arrays.
if (areArrays) {
// Compare array lengths to determine if a deep comparison is necessary.
length = a.length;
if (length !== b.length) {
return false;
}
// Deep compare the contents, ignoring non-numeric properties.
while (length--) {
if (!eq(a[length], b[length], aStack, bStack)) {
return false;
}
}
} else {
// Deep compare objects.
var keys = Object.keys(a),
key;
length = keys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
if (Object.keys(b).length !== length) {
return false;
}
while (length--) {
// Deep compare each member
key = keys[length];
if (!(has(b, key) && eq(a[key], b[key], aStack, bStack))) {
return false;
}
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return true;
}
|
javascript
|
function deepEq(a, b, aStack, bStack) {
// Compare `[[Class]]` names.
var className = Object.prototype.toString.call(a);
if (className !== Object.prototype.toString.call(b)) {
return false;
}
/* eslint-disable no-fallthrough */
switch (className) {
// Strings, numbers, regular expressions, dates, and booleans are compared by value.
case "[object RegExp]":
// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
case "[object String]":
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return "" + a === "" + b;
case "[object Number]":
// `NaN`s are equivalent, but non-reflexive.
// Object(NaN) is equivalent to NaN
if (+a !== +a) {
return +b !== +b;
}
// An `egal` comparison is performed for other numeric values.
return +a === 0 ? 1 / +a === 1 / b : +a === +b;
case "[object Date]":
case "[object Boolean]":
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a === +b;
/* eslint-enable no-fallthrough */
}
var areArrays = className === "[object Array]";
if (!areArrays) {
if (typeof a != "object" || typeof b != "object") {
return false;
}
// Objects with different constructors are not equivalent, but `Object`s or `Array`s
// from different frames are.
var aCtor = a.constructor,
bCtor = b.constructor;
if (
aCtor !== bCtor &&
!(
isFunction(aCtor) &&
aCtor instanceof aCtor &&
isFunction(bCtor) &&
bCtor instanceof bCtor
) &&
("constructor" in a && "constructor" in b)
) {
return false;
}
}
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
// Initializing stack of traversed objects.
// It's done here since we only need them for objects and arrays comparison.
aStack = aStack || [];
bStack = bStack || [];
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] === a) {
return bStack[length] === b;
}
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
// Recursively compare objects and arrays.
if (areArrays) {
// Compare array lengths to determine if a deep comparison is necessary.
length = a.length;
if (length !== b.length) {
return false;
}
// Deep compare the contents, ignoring non-numeric properties.
while (length--) {
if (!eq(a[length], b[length], aStack, bStack)) {
return false;
}
}
} else {
// Deep compare objects.
var keys = Object.keys(a),
key;
length = keys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
if (Object.keys(b).length !== length) {
return false;
}
while (length--) {
// Deep compare each member
key = keys[length];
if (!(has(b, key) && eq(a[key], b[key], aStack, bStack))) {
return false;
}
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return true;
}
|
[
"function",
"deepEq",
"(",
"a",
",",
"b",
",",
"aStack",
",",
"bStack",
")",
"{",
"// Compare `[[Class]]` names.",
"var",
"className",
"=",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"a",
")",
";",
"if",
"(",
"className",
"!==",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"b",
")",
")",
"{",
"return",
"false",
";",
"}",
"/* eslint-disable no-fallthrough */",
"switch",
"(",
"className",
")",
"{",
"// Strings, numbers, regular expressions, dates, and booleans are compared by value.",
"case",
"\"[object RegExp]\"",
":",
"// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')",
"case",
"\"[object String]\"",
":",
"// Primitives and their corresponding object wrappers are equivalent; thus, `\"5\"` is",
"// equivalent to `new String(\"5\")`.",
"return",
"\"\"",
"+",
"a",
"===",
"\"\"",
"+",
"b",
";",
"case",
"\"[object Number]\"",
":",
"// `NaN`s are equivalent, but non-reflexive.",
"// Object(NaN) is equivalent to NaN",
"if",
"(",
"+",
"a",
"!==",
"+",
"a",
")",
"{",
"return",
"+",
"b",
"!==",
"+",
"b",
";",
"}",
"// An `egal` comparison is performed for other numeric values.",
"return",
"+",
"a",
"===",
"0",
"?",
"1",
"/",
"+",
"a",
"===",
"1",
"/",
"b",
":",
"+",
"a",
"===",
"+",
"b",
";",
"case",
"\"[object Date]\"",
":",
"case",
"\"[object Boolean]\"",
":",
"// Coerce dates and booleans to numeric primitive values. Dates are compared by their",
"// millisecond representations. Note that invalid dates with millisecond representations",
"// of `NaN` are not equivalent.",
"return",
"+",
"a",
"===",
"+",
"b",
";",
"/* eslint-enable no-fallthrough */",
"}",
"var",
"areArrays",
"=",
"className",
"===",
"\"[object Array]\"",
";",
"if",
"(",
"!",
"areArrays",
")",
"{",
"if",
"(",
"typeof",
"a",
"!=",
"\"object\"",
"||",
"typeof",
"b",
"!=",
"\"object\"",
")",
"{",
"return",
"false",
";",
"}",
"// Objects with different constructors are not equivalent, but `Object`s or `Array`s",
"// from different frames are.",
"var",
"aCtor",
"=",
"a",
".",
"constructor",
",",
"bCtor",
"=",
"b",
".",
"constructor",
";",
"if",
"(",
"aCtor",
"!==",
"bCtor",
"&&",
"!",
"(",
"isFunction",
"(",
"aCtor",
")",
"&&",
"aCtor",
"instanceof",
"aCtor",
"&&",
"isFunction",
"(",
"bCtor",
")",
"&&",
"bCtor",
"instanceof",
"bCtor",
")",
"&&",
"(",
"\"constructor\"",
"in",
"a",
"&&",
"\"constructor\"",
"in",
"b",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"// Assume equality for cyclic structures. The algorithm for detecting cyclic",
"// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.",
"// Initializing stack of traversed objects.",
"// It's done here since we only need them for objects and arrays comparison.",
"aStack",
"=",
"aStack",
"||",
"[",
"]",
";",
"bStack",
"=",
"bStack",
"||",
"[",
"]",
";",
"var",
"length",
"=",
"aStack",
".",
"length",
";",
"while",
"(",
"length",
"--",
")",
"{",
"// Linear search. Performance is inversely proportional to the number of",
"// unique nested structures.",
"if",
"(",
"aStack",
"[",
"length",
"]",
"===",
"a",
")",
"{",
"return",
"bStack",
"[",
"length",
"]",
"===",
"b",
";",
"}",
"}",
"// Add the first object to the stack of traversed objects.",
"aStack",
".",
"push",
"(",
"a",
")",
";",
"bStack",
".",
"push",
"(",
"b",
")",
";",
"// Recursively compare objects and arrays.",
"if",
"(",
"areArrays",
")",
"{",
"// Compare array lengths to determine if a deep comparison is necessary.",
"length",
"=",
"a",
".",
"length",
";",
"if",
"(",
"length",
"!==",
"b",
".",
"length",
")",
"{",
"return",
"false",
";",
"}",
"// Deep compare the contents, ignoring non-numeric properties.",
"while",
"(",
"length",
"--",
")",
"{",
"if",
"(",
"!",
"eq",
"(",
"a",
"[",
"length",
"]",
",",
"b",
"[",
"length",
"]",
",",
"aStack",
",",
"bStack",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"}",
"else",
"{",
"// Deep compare objects.",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"a",
")",
",",
"key",
";",
"length",
"=",
"keys",
".",
"length",
";",
"// Ensure that both objects contain the same number of properties before comparing deep equality.",
"if",
"(",
"Object",
".",
"keys",
"(",
"b",
")",
".",
"length",
"!==",
"length",
")",
"{",
"return",
"false",
";",
"}",
"while",
"(",
"length",
"--",
")",
"{",
"// Deep compare each member",
"key",
"=",
"keys",
"[",
"length",
"]",
";",
"if",
"(",
"!",
"(",
"has",
"(",
"b",
",",
"key",
")",
"&&",
"eq",
"(",
"a",
"[",
"key",
"]",
",",
"b",
"[",
"key",
"]",
",",
"aStack",
",",
"bStack",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"}",
"// Remove the first object from the stack of traversed objects.",
"aStack",
".",
"pop",
"(",
")",
";",
"bStack",
".",
"pop",
"(",
")",
";",
"return",
"true",
";",
"}"
] |
Internal recursive comparison function for `isEqual`.
|
[
"Internal",
"recursive",
"comparison",
"function",
"for",
"isEqual",
"."
] |
363b189f17ce7891d3581a76a90cc39346f96cda
|
https://github.com/mesosphere/reactjs-components/blob/363b189f17ce7891d3581a76a90cc39346f96cda/src/Util/Util.js#L237-L349
|
12,914
|
mesosphere/reactjs-components
|
src/Util/Util.js
|
clone
|
function clone(object) {
if (object === null || typeof object != "object") {
return object;
}
const copy = object.constructor();
for (const attr in object) {
if (Object.prototype.hasOwnProperty.call(object, attr)) {
copy[attr] = object[attr];
}
}
return copy;
}
|
javascript
|
function clone(object) {
if (object === null || typeof object != "object") {
return object;
}
const copy = object.constructor();
for (const attr in object) {
if (Object.prototype.hasOwnProperty.call(object, attr)) {
copy[attr] = object[attr];
}
}
return copy;
}
|
[
"function",
"clone",
"(",
"object",
")",
"{",
"if",
"(",
"object",
"===",
"null",
"||",
"typeof",
"object",
"!=",
"\"object\"",
")",
"{",
"return",
"object",
";",
"}",
"const",
"copy",
"=",
"object",
".",
"constructor",
"(",
")",
";",
"for",
"(",
"const",
"attr",
"in",
"object",
")",
"{",
"if",
"(",
"Object",
".",
"prototype",
".",
"hasOwnProperty",
".",
"call",
"(",
"object",
",",
"attr",
")",
")",
"{",
"copy",
"[",
"attr",
"]",
"=",
"object",
"[",
"attr",
"]",
";",
"}",
"}",
"return",
"copy",
";",
"}"
] |
Custom functions created for reactjs-components
|
[
"Custom",
"functions",
"created",
"for",
"reactjs",
"-",
"components"
] |
363b189f17ce7891d3581a76a90cc39346f96cda
|
https://github.com/mesosphere/reactjs-components/blob/363b189f17ce7891d3581a76a90cc39346f96cda/src/Util/Util.js#L407-L419
|
12,915
|
mesosphere/reactjs-components
|
src/Util/Util.js
|
exclude
|
function exclude(object, props) {
const newObject = {};
Object.keys(object).forEach(function(prop) {
if (props.indexOf(prop) === -1) {
newObject[prop] = object[prop];
}
});
return newObject;
}
|
javascript
|
function exclude(object, props) {
const newObject = {};
Object.keys(object).forEach(function(prop) {
if (props.indexOf(prop) === -1) {
newObject[prop] = object[prop];
}
});
return newObject;
}
|
[
"function",
"exclude",
"(",
"object",
",",
"props",
")",
"{",
"const",
"newObject",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"object",
")",
".",
"forEach",
"(",
"function",
"(",
"prop",
")",
"{",
"if",
"(",
"props",
".",
"indexOf",
"(",
"prop",
")",
"===",
"-",
"1",
")",
"{",
"newObject",
"[",
"prop",
"]",
"=",
"object",
"[",
"prop",
"]",
";",
"}",
"}",
")",
";",
"return",
"newObject",
";",
"}"
] |
Excludes given properties from object
@param {Object} object
@param {Array} props Array of properties to remove
@return {Object} New object without given props
|
[
"Excludes",
"given",
"properties",
"from",
"object"
] |
363b189f17ce7891d3581a76a90cc39346f96cda
|
https://github.com/mesosphere/reactjs-components/blob/363b189f17ce7891d3581a76a90cc39346f96cda/src/Util/Util.js#L428-L438
|
12,916
|
mesosphere/reactjs-components
|
src/Form/Form.js
|
findFieldOption
|
function findFieldOption(options, field) {
const flattenedOptions = Util.flatten(options);
return Util.find(flattenedOptions, function(fieldOption) {
var isField = fieldOption.name === field;
if (fieldOption.fieldType === "object" && !isField) {
return findFieldOption(fieldOption.definition, field);
}
return isField;
});
}
|
javascript
|
function findFieldOption(options, field) {
const flattenedOptions = Util.flatten(options);
return Util.find(flattenedOptions, function(fieldOption) {
var isField = fieldOption.name === field;
if (fieldOption.fieldType === "object" && !isField) {
return findFieldOption(fieldOption.definition, field);
}
return isField;
});
}
|
[
"function",
"findFieldOption",
"(",
"options",
",",
"field",
")",
"{",
"const",
"flattenedOptions",
"=",
"Util",
".",
"flatten",
"(",
"options",
")",
";",
"return",
"Util",
".",
"find",
"(",
"flattenedOptions",
",",
"function",
"(",
"fieldOption",
")",
"{",
"var",
"isField",
"=",
"fieldOption",
".",
"name",
"===",
"field",
";",
"if",
"(",
"fieldOption",
".",
"fieldType",
"===",
"\"object\"",
"&&",
"!",
"isField",
")",
"{",
"return",
"findFieldOption",
"(",
"fieldOption",
".",
"definition",
",",
"field",
")",
";",
"}",
"return",
"isField",
";",
"}",
")",
";",
"}"
] |
Find a the options for a particular field in the form.
|
[
"Find",
"a",
"the",
"options",
"for",
"a",
"particular",
"field",
"in",
"the",
"form",
"."
] |
363b189f17ce7891d3581a76a90cc39346f96cda
|
https://github.com/mesosphere/reactjs-components/blob/363b189f17ce7891d3581a76a90cc39346f96cda/src/Form/Form.js#L10-L21
|
12,917
|
mesosphere/reactjs-components
|
docs/gulpTasks.js
|
eslintFn
|
function eslintFn() {
return gulp
.src([config.files.docs.srcJS])
.pipe(eslint())
.pipe(eslint.formatEach("stylish", process.stderr));
}
|
javascript
|
function eslintFn() {
return gulp
.src([config.files.docs.srcJS])
.pipe(eslint())
.pipe(eslint.formatEach("stylish", process.stderr));
}
|
[
"function",
"eslintFn",
"(",
")",
"{",
"return",
"gulp",
".",
"src",
"(",
"[",
"config",
".",
"files",
".",
"docs",
".",
"srcJS",
"]",
")",
".",
"pipe",
"(",
"eslint",
"(",
")",
")",
".",
"pipe",
"(",
"eslint",
".",
"formatEach",
"(",
"\"stylish\"",
",",
"process",
".",
"stderr",
")",
")",
";",
"}"
] |
Create a function so we can use it inside of webpack's watch function.
|
[
"Create",
"a",
"function",
"so",
"we",
"can",
"use",
"it",
"inside",
"of",
"webpack",
"s",
"watch",
"function",
"."
] |
363b189f17ce7891d3581a76a90cc39346f96cda
|
https://github.com/mesosphere/reactjs-components/blob/363b189f17ce7891d3581a76a90cc39346f96cda/docs/gulpTasks.js#L44-L49
|
12,918
|
bradzacher/eslint-plugin-typescript
|
lib/rules/no-inferrable-types.js
|
isInferrable
|
function isInferrable(node, init) {
if (node.type !== "TSTypeAnnotation" || !node.typeAnnotation) {
return false;
}
if (!init) {
return false;
}
const annotation = node.typeAnnotation;
if (annotation.type === "TSStringKeyword") {
return (
(init.type === "Literal" &&
typeof init.value === "string") ||
(init.type === "TemplateElement" &&
(!init.expressions || init.expressions.length === 0))
);
}
if (annotation.type === "TSBooleanKeyword") {
return init.type === "Literal";
}
if (annotation.type === "TSNumberKeyword") {
// Infinity is special
if (
(init.type === "UnaryExpression" &&
init.operator === "-" &&
init.argument.type === "Identifier" &&
init.argument.name === "Infinity") ||
(init.type === "Identifier" && init.name === "Infinity")
) {
return true;
}
return (
init.type === "Literal" && typeof init.value === "number"
);
}
return false;
}
|
javascript
|
function isInferrable(node, init) {
if (node.type !== "TSTypeAnnotation" || !node.typeAnnotation) {
return false;
}
if (!init) {
return false;
}
const annotation = node.typeAnnotation;
if (annotation.type === "TSStringKeyword") {
return (
(init.type === "Literal" &&
typeof init.value === "string") ||
(init.type === "TemplateElement" &&
(!init.expressions || init.expressions.length === 0))
);
}
if (annotation.type === "TSBooleanKeyword") {
return init.type === "Literal";
}
if (annotation.type === "TSNumberKeyword") {
// Infinity is special
if (
(init.type === "UnaryExpression" &&
init.operator === "-" &&
init.argument.type === "Identifier" &&
init.argument.name === "Infinity") ||
(init.type === "Identifier" && init.name === "Infinity")
) {
return true;
}
return (
init.type === "Literal" && typeof init.value === "number"
);
}
return false;
}
|
[
"function",
"isInferrable",
"(",
"node",
",",
"init",
")",
"{",
"if",
"(",
"node",
".",
"type",
"!==",
"\"TSTypeAnnotation\"",
"||",
"!",
"node",
".",
"typeAnnotation",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"init",
")",
"{",
"return",
"false",
";",
"}",
"const",
"annotation",
"=",
"node",
".",
"typeAnnotation",
";",
"if",
"(",
"annotation",
".",
"type",
"===",
"\"TSStringKeyword\"",
")",
"{",
"return",
"(",
"(",
"init",
".",
"type",
"===",
"\"Literal\"",
"&&",
"typeof",
"init",
".",
"value",
"===",
"\"string\"",
")",
"||",
"(",
"init",
".",
"type",
"===",
"\"TemplateElement\"",
"&&",
"(",
"!",
"init",
".",
"expressions",
"||",
"init",
".",
"expressions",
".",
"length",
"===",
"0",
")",
")",
")",
";",
"}",
"if",
"(",
"annotation",
".",
"type",
"===",
"\"TSBooleanKeyword\"",
")",
"{",
"return",
"init",
".",
"type",
"===",
"\"Literal\"",
";",
"}",
"if",
"(",
"annotation",
".",
"type",
"===",
"\"TSNumberKeyword\"",
")",
"{",
"// Infinity is special",
"if",
"(",
"(",
"init",
".",
"type",
"===",
"\"UnaryExpression\"",
"&&",
"init",
".",
"operator",
"===",
"\"-\"",
"&&",
"init",
".",
"argument",
".",
"type",
"===",
"\"Identifier\"",
"&&",
"init",
".",
"argument",
".",
"name",
"===",
"\"Infinity\"",
")",
"||",
"(",
"init",
".",
"type",
"===",
"\"Identifier\"",
"&&",
"init",
".",
"name",
"===",
"\"Infinity\"",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"(",
"init",
".",
"type",
"===",
"\"Literal\"",
"&&",
"typeof",
"init",
".",
"value",
"===",
"\"number\"",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
Returns whether a node has an inferrable value or not
@param {ASTNode} node the node to check
@param {ASTNode} init the initializer
@returns {boolean} whether the node has an inferrable type
|
[
"Returns",
"whether",
"a",
"node",
"has",
"an",
"inferrable",
"value",
"or",
"not"
] |
f689a73c171f33501aa11cd9f77bec2fc10128ae
|
https://github.com/bradzacher/eslint-plugin-typescript/blob/f689a73c171f33501aa11cd9f77bec2fc10128ae/lib/rules/no-inferrable-types.js#L60-L102
|
12,919
|
bradzacher/eslint-plugin-typescript
|
lib/rules/no-inferrable-types.js
|
reportInferrableType
|
function reportInferrableType(node, typeNode, initNode) {
if (!typeNode || !initNode || !typeNode.typeAnnotation) {
return;
}
if (!isInferrable(typeNode, initNode)) {
return;
}
const typeMap = {
TSBooleanKeyword: "boolean",
TSNumberKeyword: "number",
TSStringKeyword: "string",
};
const type = typeMap[typeNode.typeAnnotation.type];
context.report({
node,
message:
"Type {{type}} trivially inferred from a {{type}} literal, remove type annotation.",
data: {
type,
},
fix: fixer => fixer.remove(typeNode),
});
}
|
javascript
|
function reportInferrableType(node, typeNode, initNode) {
if (!typeNode || !initNode || !typeNode.typeAnnotation) {
return;
}
if (!isInferrable(typeNode, initNode)) {
return;
}
const typeMap = {
TSBooleanKeyword: "boolean",
TSNumberKeyword: "number",
TSStringKeyword: "string",
};
const type = typeMap[typeNode.typeAnnotation.type];
context.report({
node,
message:
"Type {{type}} trivially inferred from a {{type}} literal, remove type annotation.",
data: {
type,
},
fix: fixer => fixer.remove(typeNode),
});
}
|
[
"function",
"reportInferrableType",
"(",
"node",
",",
"typeNode",
",",
"initNode",
")",
"{",
"if",
"(",
"!",
"typeNode",
"||",
"!",
"initNode",
"||",
"!",
"typeNode",
".",
"typeAnnotation",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"isInferrable",
"(",
"typeNode",
",",
"initNode",
")",
")",
"{",
"return",
";",
"}",
"const",
"typeMap",
"=",
"{",
"TSBooleanKeyword",
":",
"\"boolean\"",
",",
"TSNumberKeyword",
":",
"\"number\"",
",",
"TSStringKeyword",
":",
"\"string\"",
",",
"}",
";",
"const",
"type",
"=",
"typeMap",
"[",
"typeNode",
".",
"typeAnnotation",
".",
"type",
"]",
";",
"context",
".",
"report",
"(",
"{",
"node",
",",
"message",
":",
"\"Type {{type}} trivially inferred from a {{type}} literal, remove type annotation.\"",
",",
"data",
":",
"{",
"type",
",",
"}",
",",
"fix",
":",
"fixer",
"=>",
"fixer",
".",
"remove",
"(",
"typeNode",
")",
",",
"}",
")",
";",
"}"
] |
Reports an inferrable type declaration, if any
@param {ASTNode} node the node being visited
@param {ASTNode} typeNode the type annotation node
@param {ASTNode} initNode the initializer node
@returns {void}
|
[
"Reports",
"an",
"inferrable",
"type",
"declaration",
"if",
"any"
] |
f689a73c171f33501aa11cd9f77bec2fc10128ae
|
https://github.com/bradzacher/eslint-plugin-typescript/blob/f689a73c171f33501aa11cd9f77bec2fc10128ae/lib/rules/no-inferrable-types.js#L111-L137
|
12,920
|
bradzacher/eslint-plugin-typescript
|
lib/rules/member-delimiter-style.js
|
checkMemberSeparatorStyle
|
function checkMemberSeparatorStyle(node) {
const isInterface = node.type === "TSInterfaceBody";
const isSingleLine = node.loc.start.line === node.loc.end.line;
const members = isInterface ? node.body : node.members;
const typeOpts = isInterface
? interfaceOptions
: typeLiteralOptions;
const opts = isSingleLine
? typeOpts.singleline
: typeOpts.multiline;
members.forEach((member, index) => {
checkLastToken(member, opts, index === members.length - 1);
});
}
|
javascript
|
function checkMemberSeparatorStyle(node) {
const isInterface = node.type === "TSInterfaceBody";
const isSingleLine = node.loc.start.line === node.loc.end.line;
const members = isInterface ? node.body : node.members;
const typeOpts = isInterface
? interfaceOptions
: typeLiteralOptions;
const opts = isSingleLine
? typeOpts.singleline
: typeOpts.multiline;
members.forEach((member, index) => {
checkLastToken(member, opts, index === members.length - 1);
});
}
|
[
"function",
"checkMemberSeparatorStyle",
"(",
"node",
")",
"{",
"const",
"isInterface",
"=",
"node",
".",
"type",
"===",
"\"TSInterfaceBody\"",
";",
"const",
"isSingleLine",
"=",
"node",
".",
"loc",
".",
"start",
".",
"line",
"===",
"node",
".",
"loc",
".",
"end",
".",
"line",
";",
"const",
"members",
"=",
"isInterface",
"?",
"node",
".",
"body",
":",
"node",
".",
"members",
";",
"const",
"typeOpts",
"=",
"isInterface",
"?",
"interfaceOptions",
":",
"typeLiteralOptions",
";",
"const",
"opts",
"=",
"isSingleLine",
"?",
"typeOpts",
".",
"singleline",
":",
"typeOpts",
".",
"multiline",
";",
"members",
".",
"forEach",
"(",
"(",
"member",
",",
"index",
")",
"=>",
"{",
"checkLastToken",
"(",
"member",
",",
"opts",
",",
"index",
"===",
"members",
".",
"length",
"-",
"1",
")",
";",
"}",
")",
";",
"}"
] |
Check the member separator being used matches the delimiter.
@param {ASTNode} node the node to be evaluated.
@returns {void}
@private
|
[
"Check",
"the",
"member",
"separator",
"being",
"used",
"matches",
"the",
"delimiter",
"."
] |
f689a73c171f33501aa11cd9f77bec2fc10128ae
|
https://github.com/bradzacher/eslint-plugin-typescript/blob/f689a73c171f33501aa11cd9f77bec2fc10128ae/lib/rules/member-delimiter-style.js#L200-L216
|
12,921
|
bradzacher/eslint-plugin-typescript
|
lib/util.js
|
deepMerge
|
function deepMerge(first = {}, second = {}) {
// get the unique set of keys across both objects
const keys = new Set(Object.keys(first).concat(Object.keys(second)));
return Array.from(keys).reduce((acc, key) => {
const firstHasKey = key in first;
const secondHasKey = key in second;
if (firstHasKey && secondHasKey) {
if (isObjectNotArray(first[key]) && isObjectNotArray(second[key])) {
// object type
acc[key] = deepMerge(first[key], second[key]);
} else {
// value type
acc[key] = second[key];
}
} else if (firstHasKey) {
acc[key] = first[key];
} else {
acc[key] = second[key];
}
return acc;
}, {});
}
|
javascript
|
function deepMerge(first = {}, second = {}) {
// get the unique set of keys across both objects
const keys = new Set(Object.keys(first).concat(Object.keys(second)));
return Array.from(keys).reduce((acc, key) => {
const firstHasKey = key in first;
const secondHasKey = key in second;
if (firstHasKey && secondHasKey) {
if (isObjectNotArray(first[key]) && isObjectNotArray(second[key])) {
// object type
acc[key] = deepMerge(first[key], second[key]);
} else {
// value type
acc[key] = second[key];
}
} else if (firstHasKey) {
acc[key] = first[key];
} else {
acc[key] = second[key];
}
return acc;
}, {});
}
|
[
"function",
"deepMerge",
"(",
"first",
"=",
"{",
"}",
",",
"second",
"=",
"{",
"}",
")",
"{",
"// get the unique set of keys across both objects",
"const",
"keys",
"=",
"new",
"Set",
"(",
"Object",
".",
"keys",
"(",
"first",
")",
".",
"concat",
"(",
"Object",
".",
"keys",
"(",
"second",
")",
")",
")",
";",
"return",
"Array",
".",
"from",
"(",
"keys",
")",
".",
"reduce",
"(",
"(",
"acc",
",",
"key",
")",
"=>",
"{",
"const",
"firstHasKey",
"=",
"key",
"in",
"first",
";",
"const",
"secondHasKey",
"=",
"key",
"in",
"second",
";",
"if",
"(",
"firstHasKey",
"&&",
"secondHasKey",
")",
"{",
"if",
"(",
"isObjectNotArray",
"(",
"first",
"[",
"key",
"]",
")",
"&&",
"isObjectNotArray",
"(",
"second",
"[",
"key",
"]",
")",
")",
"{",
"// object type",
"acc",
"[",
"key",
"]",
"=",
"deepMerge",
"(",
"first",
"[",
"key",
"]",
",",
"second",
"[",
"key",
"]",
")",
";",
"}",
"else",
"{",
"// value type",
"acc",
"[",
"key",
"]",
"=",
"second",
"[",
"key",
"]",
";",
"}",
"}",
"else",
"if",
"(",
"firstHasKey",
")",
"{",
"acc",
"[",
"key",
"]",
"=",
"first",
"[",
"key",
"]",
";",
"}",
"else",
"{",
"acc",
"[",
"key",
"]",
"=",
"second",
"[",
"key",
"]",
";",
"}",
"return",
"acc",
";",
"}",
",",
"{",
"}",
")",
";",
"}"
] |
Pure function - doesn't mutate either parameter!
Merges two objects together deeply, overwriting the properties in first with the properties in second
@template TFirst,TSecond
@param {TFirst} first The first object
@param {TSecond} second The second object
@returns {Record<string, any>} a new object
|
[
"Pure",
"function",
"-",
"doesn",
"t",
"mutate",
"either",
"parameter!",
"Merges",
"two",
"objects",
"together",
"deeply",
"overwriting",
"the",
"properties",
"in",
"first",
"with",
"the",
"properties",
"in",
"second"
] |
f689a73c171f33501aa11cd9f77bec2fc10128ae
|
https://github.com/bradzacher/eslint-plugin-typescript/blob/f689a73c171f33501aa11cd9f77bec2fc10128ae/lib/util.js#L43-L67
|
12,922
|
bradzacher/eslint-plugin-typescript
|
tools/update-recommended.js
|
generate
|
function generate() {
// replace this with Object.entries when node > 8
const allRules = requireIndex(path.resolve(__dirname, "../lib/rules"));
const rules = Object.keys(allRules)
.filter(key => !!allRules[key].meta.docs.recommended)
.reduce((config, key) => {
// having this here is just for output niceness (the keys will be ordered)
if (bannedRecommendedRules.has(key)) {
console.log(key.padEnd(MAX_RULE_NAME_LENGTH), "= off");
config[key] = "off";
}
const ruleName = `typescript/${key}`;
const setting = allRules[key].meta.docs.recommended;
if (!["error", "warn"].includes(setting)) {
console.log(`ERR! Invalid level for rule ${key}: "${setting}"`);
// Don't want to throw an error since ^ explains what happened.
// eslint-disable-next-line no-process-exit
process.exit(1);
}
console.log(ruleName.padEnd(MAX_RULE_NAME_LENGTH), "=", setting);
config[ruleName] = setting;
return config;
}, {});
const filePath = path.resolve(__dirname, "../lib/configs/recommended.json");
const recommendedConfig = {
parser: "eslint-plugin-typescript/parser",
parserOptions: {
sourceType: "module",
},
plugins: ["typescript"],
rules,
};
fs.writeFileSync(
filePath,
`${JSON.stringify(recommendedConfig, null, 4)}\n`
);
}
|
javascript
|
function generate() {
// replace this with Object.entries when node > 8
const allRules = requireIndex(path.resolve(__dirname, "../lib/rules"));
const rules = Object.keys(allRules)
.filter(key => !!allRules[key].meta.docs.recommended)
.reduce((config, key) => {
// having this here is just for output niceness (the keys will be ordered)
if (bannedRecommendedRules.has(key)) {
console.log(key.padEnd(MAX_RULE_NAME_LENGTH), "= off");
config[key] = "off";
}
const ruleName = `typescript/${key}`;
const setting = allRules[key].meta.docs.recommended;
if (!["error", "warn"].includes(setting)) {
console.log(`ERR! Invalid level for rule ${key}: "${setting}"`);
// Don't want to throw an error since ^ explains what happened.
// eslint-disable-next-line no-process-exit
process.exit(1);
}
console.log(ruleName.padEnd(MAX_RULE_NAME_LENGTH), "=", setting);
config[ruleName] = setting;
return config;
}, {});
const filePath = path.resolve(__dirname, "../lib/configs/recommended.json");
const recommendedConfig = {
parser: "eslint-plugin-typescript/parser",
parserOptions: {
sourceType: "module",
},
plugins: ["typescript"],
rules,
};
fs.writeFileSync(
filePath,
`${JSON.stringify(recommendedConfig, null, 4)}\n`
);
}
|
[
"function",
"generate",
"(",
")",
"{",
"// replace this with Object.entries when node > 8",
"const",
"allRules",
"=",
"requireIndex",
"(",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"\"../lib/rules\"",
")",
")",
";",
"const",
"rules",
"=",
"Object",
".",
"keys",
"(",
"allRules",
")",
".",
"filter",
"(",
"key",
"=>",
"!",
"!",
"allRules",
"[",
"key",
"]",
".",
"meta",
".",
"docs",
".",
"recommended",
")",
".",
"reduce",
"(",
"(",
"config",
",",
"key",
")",
"=>",
"{",
"// having this here is just for output niceness (the keys will be ordered)",
"if",
"(",
"bannedRecommendedRules",
".",
"has",
"(",
"key",
")",
")",
"{",
"console",
".",
"log",
"(",
"key",
".",
"padEnd",
"(",
"MAX_RULE_NAME_LENGTH",
")",
",",
"\"= off\"",
")",
";",
"config",
"[",
"key",
"]",
"=",
"\"off\"",
";",
"}",
"const",
"ruleName",
"=",
"`",
"${",
"key",
"}",
"`",
";",
"const",
"setting",
"=",
"allRules",
"[",
"key",
"]",
".",
"meta",
".",
"docs",
".",
"recommended",
";",
"if",
"(",
"!",
"[",
"\"error\"",
",",
"\"warn\"",
"]",
".",
"includes",
"(",
"setting",
")",
")",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"key",
"}",
"${",
"setting",
"}",
"`",
")",
";",
"// Don't want to throw an error since ^ explains what happened.",
"// eslint-disable-next-line no-process-exit",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"console",
".",
"log",
"(",
"ruleName",
".",
"padEnd",
"(",
"MAX_RULE_NAME_LENGTH",
")",
",",
"\"=\"",
",",
"setting",
")",
";",
"config",
"[",
"ruleName",
"]",
"=",
"setting",
";",
"return",
"config",
";",
"}",
",",
"{",
"}",
")",
";",
"const",
"filePath",
"=",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"\"../lib/configs/recommended.json\"",
")",
";",
"const",
"recommendedConfig",
"=",
"{",
"parser",
":",
"\"eslint-plugin-typescript/parser\"",
",",
"parserOptions",
":",
"{",
"sourceType",
":",
"\"module\"",
",",
"}",
",",
"plugins",
":",
"[",
"\"typescript\"",
"]",
",",
"rules",
",",
"}",
";",
"fs",
".",
"writeFileSync",
"(",
"filePath",
",",
"`",
"${",
"JSON",
".",
"stringify",
"(",
"recommendedConfig",
",",
"null",
",",
"4",
")",
"}",
"\\n",
"`",
")",
";",
"}"
] |
Generate recommended configuration
@returns {void}
|
[
"Generate",
"recommended",
"configuration"
] |
f689a73c171f33501aa11cd9f77bec2fc10128ae
|
https://github.com/bradzacher/eslint-plugin-typescript/blob/f689a73c171f33501aa11cd9f77bec2fc10128ae/tools/update-recommended.js#L20-L64
|
12,923
|
bradzacher/eslint-plugin-typescript
|
lib/rules/adjacent-overload-signatures.js
|
checkBodyForOverloadMethods
|
function checkBodyForOverloadMethods(node) {
const members = node.body || node.members;
if (members) {
let name;
let index;
let lastName;
const seen = [];
members.forEach(member => {
name = getMemberName(member);
index = seen.indexOf(name);
if (index > -1 && lastName !== name) {
context.report({
node: member,
messageId: "adjacentSignature",
data: {
name,
},
});
} else if (name && index === -1) {
seen.push(name);
}
lastName = name;
});
}
}
|
javascript
|
function checkBodyForOverloadMethods(node) {
const members = node.body || node.members;
if (members) {
let name;
let index;
let lastName;
const seen = [];
members.forEach(member => {
name = getMemberName(member);
index = seen.indexOf(name);
if (index > -1 && lastName !== name) {
context.report({
node: member,
messageId: "adjacentSignature",
data: {
name,
},
});
} else if (name && index === -1) {
seen.push(name);
}
lastName = name;
});
}
}
|
[
"function",
"checkBodyForOverloadMethods",
"(",
"node",
")",
"{",
"const",
"members",
"=",
"node",
".",
"body",
"||",
"node",
".",
"members",
";",
"if",
"(",
"members",
")",
"{",
"let",
"name",
";",
"let",
"index",
";",
"let",
"lastName",
";",
"const",
"seen",
"=",
"[",
"]",
";",
"members",
".",
"forEach",
"(",
"member",
"=>",
"{",
"name",
"=",
"getMemberName",
"(",
"member",
")",
";",
"index",
"=",
"seen",
".",
"indexOf",
"(",
"name",
")",
";",
"if",
"(",
"index",
">",
"-",
"1",
"&&",
"lastName",
"!==",
"name",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
":",
"member",
",",
"messageId",
":",
"\"adjacentSignature\"",
",",
"data",
":",
"{",
"name",
",",
"}",
",",
"}",
")",
";",
"}",
"else",
"if",
"(",
"name",
"&&",
"index",
"===",
"-",
"1",
")",
"{",
"seen",
".",
"push",
"(",
"name",
")",
";",
"}",
"lastName",
"=",
"name",
";",
"}",
")",
";",
"}",
"}"
] |
Check the body for overload methods.
@param {ASTNode} node the body to be inspected.
@returns {void}
@private
|
[
"Check",
"the",
"body",
"for",
"overload",
"methods",
"."
] |
f689a73c171f33501aa11cd9f77bec2fc10128ae
|
https://github.com/bradzacher/eslint-plugin-typescript/blob/f689a73c171f33501aa11cd9f77bec2fc10128ae/lib/rules/adjacent-overload-signatures.js#L86-L114
|
12,924
|
bradzacher/eslint-plugin-typescript
|
lib/rules/no-unused-vars.js
|
markThisParameterAsUsed
|
function markThisParameterAsUsed(node) {
if (node.name) {
const variable = context
.getScope()
.variables.find(scopeVar => scopeVar.name === node.name);
if (variable) {
variable.eslintUsed = true;
}
}
}
|
javascript
|
function markThisParameterAsUsed(node) {
if (node.name) {
const variable = context
.getScope()
.variables.find(scopeVar => scopeVar.name === node.name);
if (variable) {
variable.eslintUsed = true;
}
}
}
|
[
"function",
"markThisParameterAsUsed",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"name",
")",
"{",
"const",
"variable",
"=",
"context",
".",
"getScope",
"(",
")",
".",
"variables",
".",
"find",
"(",
"scopeVar",
"=>",
"scopeVar",
".",
"name",
"===",
"node",
".",
"name",
")",
";",
"if",
"(",
"variable",
")",
"{",
"variable",
".",
"eslintUsed",
"=",
"true",
";",
"}",
"}",
"}"
] |
Mark this function parameter as used
@param {Identifier} node The node currently being traversed
@returns {void}
|
[
"Mark",
"this",
"function",
"parameter",
"as",
"used"
] |
f689a73c171f33501aa11cd9f77bec2fc10128ae
|
https://github.com/bradzacher/eslint-plugin-typescript/blob/f689a73c171f33501aa11cd9f77bec2fc10128ae/lib/rules/no-unused-vars.js#L35-L45
|
12,925
|
bradzacher/eslint-plugin-typescript
|
lib/rules/indent.js
|
TSPropertySignatureToProperty
|
function TSPropertySignatureToProperty(node, type = "Property") {
return {
type,
key: node.key,
value: node.value || node.typeAnnotation,
// Property flags
computed: false,
method: false,
kind: "init",
// this will stop eslint from interrogating the type literal
shorthand: true,
// location data
parent: node.parent,
range: node.range,
loc: node.loc,
};
}
|
javascript
|
function TSPropertySignatureToProperty(node, type = "Property") {
return {
type,
key: node.key,
value: node.value || node.typeAnnotation,
// Property flags
computed: false,
method: false,
kind: "init",
// this will stop eslint from interrogating the type literal
shorthand: true,
// location data
parent: node.parent,
range: node.range,
loc: node.loc,
};
}
|
[
"function",
"TSPropertySignatureToProperty",
"(",
"node",
",",
"type",
"=",
"\"Property\"",
")",
"{",
"return",
"{",
"type",
",",
"key",
":",
"node",
".",
"key",
",",
"value",
":",
"node",
".",
"value",
"||",
"node",
".",
"typeAnnotation",
",",
"// Property flags",
"computed",
":",
"false",
",",
"method",
":",
"false",
",",
"kind",
":",
"\"init\"",
",",
"// this will stop eslint from interrogating the type literal",
"shorthand",
":",
"true",
",",
"// location data",
"parent",
":",
"node",
".",
"parent",
",",
"range",
":",
"node",
".",
"range",
",",
"loc",
":",
"node",
".",
"loc",
",",
"}",
";",
"}"
] |
Converts from a TSPropertySignature to a Property
@param {Object} node a TSPropertySignature node
@param {string} [type] the type to give the new node
@returns {Object} a Property node
|
[
"Converts",
"from",
"a",
"TSPropertySignature",
"to",
"a",
"Property"
] |
f689a73c171f33501aa11cd9f77bec2fc10128ae
|
https://github.com/bradzacher/eslint-plugin-typescript/blob/f689a73c171f33501aa11cd9f77bec2fc10128ae/lib/rules/indent.js#L126-L144
|
12,926
|
bradzacher/eslint-plugin-typescript
|
lib/rules/explicit-member-accessibility.js
|
checkPropertyAccessibilityModifier
|
function checkPropertyAccessibilityModifier(classProperty) {
if (
!classProperty.accessibility &&
util.isTypescript(context.getFilename())
) {
context.report({
node: classProperty,
message:
"Missing accessibility modifier on class property {{name}}.",
data: {
name: classProperty.key.name,
},
});
}
}
|
javascript
|
function checkPropertyAccessibilityModifier(classProperty) {
if (
!classProperty.accessibility &&
util.isTypescript(context.getFilename())
) {
context.report({
node: classProperty,
message:
"Missing accessibility modifier on class property {{name}}.",
data: {
name: classProperty.key.name,
},
});
}
}
|
[
"function",
"checkPropertyAccessibilityModifier",
"(",
"classProperty",
")",
"{",
"if",
"(",
"!",
"classProperty",
".",
"accessibility",
"&&",
"util",
".",
"isTypescript",
"(",
"context",
".",
"getFilename",
"(",
")",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
":",
"classProperty",
",",
"message",
":",
"\"Missing accessibility modifier on class property {{name}}.\"",
",",
"data",
":",
"{",
"name",
":",
"classProperty",
".",
"key",
".",
"name",
",",
"}",
",",
"}",
")",
";",
"}",
"}"
] |
Checks if property has an accessibility modifier.
@param {ASTNode} classProperty The node representing a ClassProperty.
@returns {void}
@private
|
[
"Checks",
"if",
"property",
"has",
"an",
"accessibility",
"modifier",
"."
] |
f689a73c171f33501aa11cd9f77bec2fc10128ae
|
https://github.com/bradzacher/eslint-plugin-typescript/blob/f689a73c171f33501aa11cd9f77bec2fc10128ae/lib/rules/explicit-member-accessibility.js#L60-L74
|
12,927
|
bradzacher/eslint-plugin-typescript
|
lib/rules/array-type.js
|
isSimpleType
|
function isSimpleType(node) {
switch (node.type) {
case "Identifier":
case "TSAnyKeyword":
case "TSBooleanKeyword":
case "TSNeverKeyword":
case "TSNumberKeyword":
case "TSObjectKeyword":
case "TSStringKeyword":
case "TSSymbolKeyword":
case "TSUnknownKeyword":
case "TSVoidKeyword":
case "TSNullKeyword":
case "TSArrayType":
case "TSUndefinedKeyword":
case "TSThisType":
case "TSQualifiedName":
return true;
case "TSTypeReference":
if (
node.typeName &&
node.typeName.type === "Identifier" &&
node.typeName.name === "Array"
) {
if (!node.typeParameters) {
return true;
}
if (node.typeParameters.params.length === 1) {
return isSimpleType(node.typeParameters.params[0]);
}
} else {
if (node.typeParameters) {
return false;
}
return isSimpleType(node.typeName);
}
return false;
default:
return false;
}
}
|
javascript
|
function isSimpleType(node) {
switch (node.type) {
case "Identifier":
case "TSAnyKeyword":
case "TSBooleanKeyword":
case "TSNeverKeyword":
case "TSNumberKeyword":
case "TSObjectKeyword":
case "TSStringKeyword":
case "TSSymbolKeyword":
case "TSUnknownKeyword":
case "TSVoidKeyword":
case "TSNullKeyword":
case "TSArrayType":
case "TSUndefinedKeyword":
case "TSThisType":
case "TSQualifiedName":
return true;
case "TSTypeReference":
if (
node.typeName &&
node.typeName.type === "Identifier" &&
node.typeName.name === "Array"
) {
if (!node.typeParameters) {
return true;
}
if (node.typeParameters.params.length === 1) {
return isSimpleType(node.typeParameters.params[0]);
}
} else {
if (node.typeParameters) {
return false;
}
return isSimpleType(node.typeName);
}
return false;
default:
return false;
}
}
|
[
"function",
"isSimpleType",
"(",
"node",
")",
"{",
"switch",
"(",
"node",
".",
"type",
")",
"{",
"case",
"\"Identifier\"",
":",
"case",
"\"TSAnyKeyword\"",
":",
"case",
"\"TSBooleanKeyword\"",
":",
"case",
"\"TSNeverKeyword\"",
":",
"case",
"\"TSNumberKeyword\"",
":",
"case",
"\"TSObjectKeyword\"",
":",
"case",
"\"TSStringKeyword\"",
":",
"case",
"\"TSSymbolKeyword\"",
":",
"case",
"\"TSUnknownKeyword\"",
":",
"case",
"\"TSVoidKeyword\"",
":",
"case",
"\"TSNullKeyword\"",
":",
"case",
"\"TSArrayType\"",
":",
"case",
"\"TSUndefinedKeyword\"",
":",
"case",
"\"TSThisType\"",
":",
"case",
"\"TSQualifiedName\"",
":",
"return",
"true",
";",
"case",
"\"TSTypeReference\"",
":",
"if",
"(",
"node",
".",
"typeName",
"&&",
"node",
".",
"typeName",
".",
"type",
"===",
"\"Identifier\"",
"&&",
"node",
".",
"typeName",
".",
"name",
"===",
"\"Array\"",
")",
"{",
"if",
"(",
"!",
"node",
".",
"typeParameters",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"node",
".",
"typeParameters",
".",
"params",
".",
"length",
"===",
"1",
")",
"{",
"return",
"isSimpleType",
"(",
"node",
".",
"typeParameters",
".",
"params",
"[",
"0",
"]",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"node",
".",
"typeParameters",
")",
"{",
"return",
"false",
";",
"}",
"return",
"isSimpleType",
"(",
"node",
".",
"typeName",
")",
";",
"}",
"return",
"false",
";",
"default",
":",
"return",
"false",
";",
"}",
"}"
] |
Check whatever node can be considered as simple
@param {ASTNode} node the node to be evaluated.
@returns {*} true or false
|
[
"Check",
"whatever",
"node",
"can",
"be",
"considered",
"as",
"simple"
] |
f689a73c171f33501aa11cd9f77bec2fc10128ae
|
https://github.com/bradzacher/eslint-plugin-typescript/blob/f689a73c171f33501aa11cd9f77bec2fc10128ae/lib/rules/array-type.js#L15-L55
|
12,928
|
bradzacher/eslint-plugin-typescript
|
lib/rules/array-type.js
|
typeNeedsParentheses
|
function typeNeedsParentheses(node) {
if (node.type === "TSTypeReference") {
switch (node.typeName.type) {
case "TSUnionType":
case "TSFunctionType":
case "TSIntersectionType":
case "TSTypeOperator":
return true;
default:
return false;
}
}
return false;
}
|
javascript
|
function typeNeedsParentheses(node) {
if (node.type === "TSTypeReference") {
switch (node.typeName.type) {
case "TSUnionType":
case "TSFunctionType":
case "TSIntersectionType":
case "TSTypeOperator":
return true;
default:
return false;
}
}
return false;
}
|
[
"function",
"typeNeedsParentheses",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"type",
"===",
"\"TSTypeReference\"",
")",
"{",
"switch",
"(",
"node",
".",
"typeName",
".",
"type",
")",
"{",
"case",
"\"TSUnionType\"",
":",
"case",
"\"TSFunctionType\"",
":",
"case",
"\"TSIntersectionType\"",
":",
"case",
"\"TSTypeOperator\"",
":",
"return",
"true",
";",
"default",
":",
"return",
"false",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Check if node needs parentheses
@param {ASTNode} node the node to be evaluated.
@returns {*} true or false
|
[
"Check",
"if",
"node",
"needs",
"parentheses"
] |
f689a73c171f33501aa11cd9f77bec2fc10128ae
|
https://github.com/bradzacher/eslint-plugin-typescript/blob/f689a73c171f33501aa11cd9f77bec2fc10128ae/lib/rules/array-type.js#L62-L75
|
12,929
|
bradzacher/eslint-plugin-typescript
|
lib/rules/array-type.js
|
requireWhitespaceBefore
|
function requireWhitespaceBefore(node) {
const prevToken = sourceCode.getTokenBefore(node);
if (node.range[0] - prevToken.range[1] > 0) {
return false;
}
return prevToken.type === "Identifier";
}
|
javascript
|
function requireWhitespaceBefore(node) {
const prevToken = sourceCode.getTokenBefore(node);
if (node.range[0] - prevToken.range[1] > 0) {
return false;
}
return prevToken.type === "Identifier";
}
|
[
"function",
"requireWhitespaceBefore",
"(",
"node",
")",
"{",
"const",
"prevToken",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"node",
")",
";",
"if",
"(",
"node",
".",
"range",
"[",
"0",
"]",
"-",
"prevToken",
".",
"range",
"[",
"1",
"]",
">",
"0",
")",
"{",
"return",
"false",
";",
"}",
"return",
"prevToken",
".",
"type",
"===",
"\"Identifier\"",
";",
"}"
] |
Check if whitespace is needed before this node
@param {ASTNode} node the node to be evaluated.
@returns {boolean} true of false
|
[
"Check",
"if",
"whitespace",
"is",
"needed",
"before",
"this",
"node"
] |
f689a73c171f33501aa11cd9f77bec2fc10128ae
|
https://github.com/bradzacher/eslint-plugin-typescript/blob/f689a73c171f33501aa11cd9f77bec2fc10128ae/lib/rules/array-type.js#L119-L127
|
12,930
|
bradzacher/eslint-plugin-typescript
|
lib/rules/no-use-before-define.js
|
parseOptions
|
function parseOptions(options) {
let functions = true;
let classes = true;
let variables = true;
let typedefs = true;
if (typeof options === "string") {
functions = options !== "nofunc";
} else if (typeof options === "object" && options !== null) {
functions = options.functions !== false;
classes = options.classes !== false;
variables = options.variables !== false;
typedefs = options.typedefs !== false;
}
return { functions, classes, variables, typedefs };
}
|
javascript
|
function parseOptions(options) {
let functions = true;
let classes = true;
let variables = true;
let typedefs = true;
if (typeof options === "string") {
functions = options !== "nofunc";
} else if (typeof options === "object" && options !== null) {
functions = options.functions !== false;
classes = options.classes !== false;
variables = options.variables !== false;
typedefs = options.typedefs !== false;
}
return { functions, classes, variables, typedefs };
}
|
[
"function",
"parseOptions",
"(",
"options",
")",
"{",
"let",
"functions",
"=",
"true",
";",
"let",
"classes",
"=",
"true",
";",
"let",
"variables",
"=",
"true",
";",
"let",
"typedefs",
"=",
"true",
";",
"if",
"(",
"typeof",
"options",
"===",
"\"string\"",
")",
"{",
"functions",
"=",
"options",
"!==",
"\"nofunc\"",
";",
"}",
"else",
"if",
"(",
"typeof",
"options",
"===",
"\"object\"",
"&&",
"options",
"!==",
"null",
")",
"{",
"functions",
"=",
"options",
".",
"functions",
"!==",
"false",
";",
"classes",
"=",
"options",
".",
"classes",
"!==",
"false",
";",
"variables",
"=",
"options",
".",
"variables",
"!==",
"false",
";",
"typedefs",
"=",
"options",
".",
"typedefs",
"!==",
"false",
";",
"}",
"return",
"{",
"functions",
",",
"classes",
",",
"variables",
",",
"typedefs",
"}",
";",
"}"
] |
Parses a given value as options.
@param {any} options - A value to parse.
@returns {Object} The parsed options.
|
[
"Parses",
"a",
"given",
"value",
"as",
"options",
"."
] |
f689a73c171f33501aa11cd9f77bec2fc10128ae
|
https://github.com/bradzacher/eslint-plugin-typescript/blob/f689a73c171f33501aa11cd9f77bec2fc10128ae/lib/rules/no-use-before-define.js#L26-L42
|
12,931
|
wy-ei/vue-filter
|
src/string/split.js
|
split
|
function split(str, separator) {
separator = separator || '';
if (_.isString(str)) {
return str.split(separator);
} else {
return str;
}
}
|
javascript
|
function split(str, separator) {
separator = separator || '';
if (_.isString(str)) {
return str.split(separator);
} else {
return str;
}
}
|
[
"function",
"split",
"(",
"str",
",",
"separator",
")",
"{",
"separator",
"=",
"separator",
"||",
"''",
";",
"if",
"(",
"_",
".",
"isString",
"(",
"str",
")",
")",
"{",
"return",
"str",
".",
"split",
"(",
"separator",
")",
";",
"}",
"else",
"{",
"return",
"str",
";",
"}",
"}"
] |
The split filter takes on a substring as a parameter.
The substring is used as a delimiter to divide a string into an array.
{{ 'a-b-c-d' | split '-' }} => [a,b,c,d]
|
[
"The",
"split",
"filter",
"takes",
"on",
"a",
"substring",
"as",
"a",
"parameter",
".",
"The",
"substring",
"is",
"used",
"as",
"a",
"delimiter",
"to",
"divide",
"a",
"string",
"into",
"an",
"array",
"."
] |
13a40a8d47c489e73ffc0ed739ab10fb27ad1a9a
|
https://github.com/wy-ei/vue-filter/blob/13a40a8d47c489e73ffc0ed739ab10fb27ad1a9a/src/string/split.js#L9-L16
|
12,932
|
wy-ei/vue-filter
|
src/string/xpad.js
|
padding
|
function padding(size,ch){
var str = '';
if(!ch && ch !== 0){
ch = ' ';
}
while(size !== 0){
if(size & 1 === 1){
str += ch;
}
ch += ch;
size >>>= 1;
}
return str;
}
|
javascript
|
function padding(size,ch){
var str = '';
if(!ch && ch !== 0){
ch = ' ';
}
while(size !== 0){
if(size & 1 === 1){
str += ch;
}
ch += ch;
size >>>= 1;
}
return str;
}
|
[
"function",
"padding",
"(",
"size",
",",
"ch",
")",
"{",
"var",
"str",
"=",
"''",
";",
"if",
"(",
"!",
"ch",
"&&",
"ch",
"!==",
"0",
")",
"{",
"ch",
"=",
"' '",
";",
"}",
"while",
"(",
"size",
"!==",
"0",
")",
"{",
"if",
"(",
"size",
"&",
"1",
"===",
"1",
")",
"{",
"str",
"+=",
"ch",
";",
"}",
"ch",
"+=",
"ch",
";",
"size",
">>>=",
"1",
";",
"}",
"return",
"str",
";",
"}"
] |
return a string by repeat a char n times
|
[
"return",
"a",
"string",
"by",
"repeat",
"a",
"char",
"n",
"times"
] |
13a40a8d47c489e73ffc0ed739ab10fb27ad1a9a
|
https://github.com/wy-ei/vue-filter/blob/13a40a8d47c489e73ffc0ed739ab10fb27ad1a9a/src/string/xpad.js#L6-L19
|
12,933
|
wy-ei/vue-filter
|
src/other/debounce.js
|
debounce
|
function debounce(handler, delay) {
if (!handler){
return;
}
if (!delay) {
delay = 300;
}
return _.debounce(handler, delay);
}
|
javascript
|
function debounce(handler, delay) {
if (!handler){
return;
}
if (!delay) {
delay = 300;
}
return _.debounce(handler, delay);
}
|
[
"function",
"debounce",
"(",
"handler",
",",
"delay",
")",
"{",
"if",
"(",
"!",
"handler",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"delay",
")",
"{",
"delay",
"=",
"300",
";",
"}",
"return",
"_",
".",
"debounce",
"(",
"handler",
",",
"delay",
")",
";",
"}"
] |
debounce a function, the default dalay is 300ms
{{ func | debounce(300) }}
|
[
"debounce",
"a",
"function",
"the",
"default",
"dalay",
"is",
"300ms"
] |
13a40a8d47c489e73ffc0ed739ab10fb27ad1a9a
|
https://github.com/wy-ei/vue-filter/blob/13a40a8d47c489e73ffc0ed739ab10fb27ad1a9a/src/other/debounce.js#L9-L17
|
12,934
|
wy-ei/vue-filter
|
src/string/append.js
|
append
|
function append(str, postfix) {
if (!str && str !== 0) {
str = '';
} else {
str = str.toString();
}
return str + postfix;
}
|
javascript
|
function append(str, postfix) {
if (!str && str !== 0) {
str = '';
} else {
str = str.toString();
}
return str + postfix;
}
|
[
"function",
"append",
"(",
"str",
",",
"postfix",
")",
"{",
"if",
"(",
"!",
"str",
"&&",
"str",
"!==",
"0",
")",
"{",
"str",
"=",
"''",
";",
"}",
"else",
"{",
"str",
"=",
"str",
".",
"toString",
"(",
")",
";",
"}",
"return",
"str",
"+",
"postfix",
";",
"}"
] |
Appends characters to a string.
{{ 'sky' | append '.jpg' }} => 'sky.jpg'
|
[
"Appends",
"characters",
"to",
"a",
"string",
"."
] |
13a40a8d47c489e73ffc0ed739ab10fb27ad1a9a
|
https://github.com/wy-ei/vue-filter/blob/13a40a8d47c489e73ffc0ed739ab10fb27ad1a9a/src/string/append.js#L7-L14
|
12,935
|
wy-ei/vue-filter
|
src/string/prepend.js
|
prepend
|
function prepend(str, prefix) {
if (!str && str !== 0) {
str = '';
} else {
str = str.toString();
}
return prefix + str;
}
|
javascript
|
function prepend(str, prefix) {
if (!str && str !== 0) {
str = '';
} else {
str = str.toString();
}
return prefix + str;
}
|
[
"function",
"prepend",
"(",
"str",
",",
"prefix",
")",
"{",
"if",
"(",
"!",
"str",
"&&",
"str",
"!==",
"0",
")",
"{",
"str",
"=",
"''",
";",
"}",
"else",
"{",
"str",
"=",
"str",
".",
"toString",
"(",
")",
";",
"}",
"return",
"prefix",
"+",
"str",
";",
"}"
] |
Prepends characters to a string.
{{ 'world' | prepend 'hello ' }} => 'hello world'
|
[
"Prepends",
"characters",
"to",
"a",
"string",
"."
] |
13a40a8d47c489e73ffc0ed739ab10fb27ad1a9a
|
https://github.com/wy-ei/vue-filter/blob/13a40a8d47c489e73ffc0ed739ab10fb27ad1a9a/src/string/prepend.js#L7-L14
|
12,936
|
wy-ei/vue-filter
|
src/collection/reverse.js
|
reverse
|
function reverse(collection) {
if (typeof collection === 'string') {
return collection.split('').reverse().join('');
}
if(_.isArray(collection)){
return collection.concat().reverse();
}
return collection;
}
|
javascript
|
function reverse(collection) {
if (typeof collection === 'string') {
return collection.split('').reverse().join('');
}
if(_.isArray(collection)){
return collection.concat().reverse();
}
return collection;
}
|
[
"function",
"reverse",
"(",
"collection",
")",
"{",
"if",
"(",
"typeof",
"collection",
"===",
"'string'",
")",
"{",
"return",
"collection",
".",
"split",
"(",
"''",
")",
".",
"reverse",
"(",
")",
".",
"join",
"(",
"''",
")",
";",
"}",
"if",
"(",
"_",
".",
"isArray",
"(",
"collection",
")",
")",
"{",
"return",
"collection",
".",
"concat",
"(",
")",
".",
"reverse",
"(",
")",
";",
"}",
"return",
"collection",
";",
"}"
] |
reverse an array or a string
{{ 'abc' | reverse }} => 'cba'
{{ [1,2,3] | reverse }} => [3,2,1]
|
[
"reverse",
"an",
"array",
"or",
"a",
"string"
] |
13a40a8d47c489e73ffc0ed739ab10fb27ad1a9a
|
https://github.com/wy-ei/vue-filter/blob/13a40a8d47c489e73ffc0ed739ab10fb27ad1a9a/src/collection/reverse.js#L11-L19
|
12,937
|
alexk111/SVG-Morpheus
|
source/js/deps/helpers.js
|
transCalc
|
function transCalc(transFrom, transTo, progress) {
var res={};
for(var i in transFrom) {
switch(i) {
case 'rotate':
res[i]=[0,0,0];
for(var j=0;j<3;j++) {
res[i][j]=transFrom[i][j]+(transTo[i][j]-transFrom[i][j])*progress;
}
break;
}
}
return res;
}
|
javascript
|
function transCalc(transFrom, transTo, progress) {
var res={};
for(var i in transFrom) {
switch(i) {
case 'rotate':
res[i]=[0,0,0];
for(var j=0;j<3;j++) {
res[i][j]=transFrom[i][j]+(transTo[i][j]-transFrom[i][j])*progress;
}
break;
}
}
return res;
}
|
[
"function",
"transCalc",
"(",
"transFrom",
",",
"transTo",
",",
"progress",
")",
"{",
"var",
"res",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"in",
"transFrom",
")",
"{",
"switch",
"(",
"i",
")",
"{",
"case",
"'rotate'",
":",
"res",
"[",
"i",
"]",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"3",
";",
"j",
"++",
")",
"{",
"res",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"transFrom",
"[",
"i",
"]",
"[",
"j",
"]",
"+",
"(",
"transTo",
"[",
"i",
"]",
"[",
"j",
"]",
"-",
"transFrom",
"[",
"i",
"]",
"[",
"j",
"]",
")",
"*",
"progress",
";",
"}",
"break",
";",
"}",
"}",
"return",
"res",
";",
"}"
] |
Calculate transform progress
|
[
"Calculate",
"transform",
"progress"
] |
b0619353a6d80f3a8cf8dfff94f6ae1bbc344b77
|
https://github.com/alexk111/SVG-Morpheus/blob/b0619353a6d80f3a8cf8dfff94f6ae1bbc344b77/source/js/deps/helpers.js#L104-L117
|
12,938
|
alexk111/SVG-Morpheus
|
source/js/deps/helpers.js
|
curveCalc
|
function curveCalc(curveFrom, curveTo, progress) {
var curve=[];
for(var i=0,len1=curveFrom.length;i<len1;i++) {
curve.push([curveFrom[i][0]]);
for(var j=1,len2=curveFrom[i].length;j<len2;j++) {
curve[i].push(curveFrom[i][j]+(curveTo[i][j]-curveFrom[i][j])*progress);
}
}
return curve;
}
|
javascript
|
function curveCalc(curveFrom, curveTo, progress) {
var curve=[];
for(var i=0,len1=curveFrom.length;i<len1;i++) {
curve.push([curveFrom[i][0]]);
for(var j=1,len2=curveFrom[i].length;j<len2;j++) {
curve[i].push(curveFrom[i][j]+(curveTo[i][j]-curveFrom[i][j])*progress);
}
}
return curve;
}
|
[
"function",
"curveCalc",
"(",
"curveFrom",
",",
"curveTo",
",",
"progress",
")",
"{",
"var",
"curve",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len1",
"=",
"curveFrom",
".",
"length",
";",
"i",
"<",
"len1",
";",
"i",
"++",
")",
"{",
"curve",
".",
"push",
"(",
"[",
"curveFrom",
"[",
"i",
"]",
"[",
"0",
"]",
"]",
")",
";",
"for",
"(",
"var",
"j",
"=",
"1",
",",
"len2",
"=",
"curveFrom",
"[",
"i",
"]",
".",
"length",
";",
"j",
"<",
"len2",
";",
"j",
"++",
")",
"{",
"curve",
"[",
"i",
"]",
".",
"push",
"(",
"curveFrom",
"[",
"i",
"]",
"[",
"j",
"]",
"+",
"(",
"curveTo",
"[",
"i",
"]",
"[",
"j",
"]",
"-",
"curveFrom",
"[",
"i",
"]",
"[",
"j",
"]",
")",
"*",
"progress",
")",
";",
"}",
"}",
"return",
"curve",
";",
"}"
] |
Calculate curve progress
|
[
"Calculate",
"curve",
"progress"
] |
b0619353a6d80f3a8cf8dfff94f6ae1bbc344b77
|
https://github.com/alexk111/SVG-Morpheus/blob/b0619353a6d80f3a8cf8dfff94f6ae1bbc344b77/source/js/deps/helpers.js#L128-L137
|
12,939
|
rkusa/koa-passport
|
lib/framework/koa.js
|
initialize
|
function initialize(passport) {
const middleware = promisify(_initialize(passport))
return function passportInitialize(ctx, next) {
// koa <-> connect compatibility:
const userProperty = passport._userProperty || 'user'
// check ctx.req has the userProperty
if (!ctx.req.hasOwnProperty(userProperty)) {
Object.defineProperty(ctx.req, userProperty, {
enumerable: true,
get: function() {
return ctx.state[userProperty]
},
set: function(val) {
ctx.state[userProperty] = val
}
})
}
// create mock object for express' req object
const req = createReqMock(ctx, userProperty)
// add Promise-based login method
const login = req.login
ctx.login = ctx.logIn = function(user, options) {
return new Promise((resolve, reject) => {
login.call(req, user, options, err => {
if (err) reject(err)
else resolve()
})
})
}
// add aliases for passport's request extensions to Koa's context
ctx.logout = ctx.logOut = req.logout.bind(req)
ctx.isAuthenticated = req.isAuthenticated.bind(req)
ctx.isUnauthenticated = req.isUnauthenticated.bind(req)
return middleware(req, ctx).then(function() {
return next()
})
}
}
|
javascript
|
function initialize(passport) {
const middleware = promisify(_initialize(passport))
return function passportInitialize(ctx, next) {
// koa <-> connect compatibility:
const userProperty = passport._userProperty || 'user'
// check ctx.req has the userProperty
if (!ctx.req.hasOwnProperty(userProperty)) {
Object.defineProperty(ctx.req, userProperty, {
enumerable: true,
get: function() {
return ctx.state[userProperty]
},
set: function(val) {
ctx.state[userProperty] = val
}
})
}
// create mock object for express' req object
const req = createReqMock(ctx, userProperty)
// add Promise-based login method
const login = req.login
ctx.login = ctx.logIn = function(user, options) {
return new Promise((resolve, reject) => {
login.call(req, user, options, err => {
if (err) reject(err)
else resolve()
})
})
}
// add aliases for passport's request extensions to Koa's context
ctx.logout = ctx.logOut = req.logout.bind(req)
ctx.isAuthenticated = req.isAuthenticated.bind(req)
ctx.isUnauthenticated = req.isUnauthenticated.bind(req)
return middleware(req, ctx).then(function() {
return next()
})
}
}
|
[
"function",
"initialize",
"(",
"passport",
")",
"{",
"const",
"middleware",
"=",
"promisify",
"(",
"_initialize",
"(",
"passport",
")",
")",
"return",
"function",
"passportInitialize",
"(",
"ctx",
",",
"next",
")",
"{",
"// koa <-> connect compatibility:",
"const",
"userProperty",
"=",
"passport",
".",
"_userProperty",
"||",
"'user'",
"// check ctx.req has the userProperty",
"if",
"(",
"!",
"ctx",
".",
"req",
".",
"hasOwnProperty",
"(",
"userProperty",
")",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"ctx",
".",
"req",
",",
"userProperty",
",",
"{",
"enumerable",
":",
"true",
",",
"get",
":",
"function",
"(",
")",
"{",
"return",
"ctx",
".",
"state",
"[",
"userProperty",
"]",
"}",
",",
"set",
":",
"function",
"(",
"val",
")",
"{",
"ctx",
".",
"state",
"[",
"userProperty",
"]",
"=",
"val",
"}",
"}",
")",
"}",
"// create mock object for express' req object",
"const",
"req",
"=",
"createReqMock",
"(",
"ctx",
",",
"userProperty",
")",
"// add Promise-based login method",
"const",
"login",
"=",
"req",
".",
"login",
"ctx",
".",
"login",
"=",
"ctx",
".",
"logIn",
"=",
"function",
"(",
"user",
",",
"options",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"login",
".",
"call",
"(",
"req",
",",
"user",
",",
"options",
",",
"err",
"=>",
"{",
"if",
"(",
"err",
")",
"reject",
"(",
"err",
")",
"else",
"resolve",
"(",
")",
"}",
")",
"}",
")",
"}",
"// add aliases for passport's request extensions to Koa's context",
"ctx",
".",
"logout",
"=",
"ctx",
".",
"logOut",
"=",
"req",
".",
"logout",
".",
"bind",
"(",
"req",
")",
"ctx",
".",
"isAuthenticated",
"=",
"req",
".",
"isAuthenticated",
".",
"bind",
"(",
"req",
")",
"ctx",
".",
"isUnauthenticated",
"=",
"req",
".",
"isUnauthenticated",
".",
"bind",
"(",
"req",
")",
"return",
"middleware",
"(",
"req",
",",
"ctx",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"next",
"(",
")",
"}",
")",
"}",
"}"
] |
Passport's initialization middleware for Koa.
@return {GeneratorFunction}
@api private
|
[
"Passport",
"s",
"initialization",
"middleware",
"for",
"Koa",
"."
] |
89c131476ce8919b9c3f2ce749e84487e2caf799
|
https://github.com/rkusa/koa-passport/blob/89c131476ce8919b9c3f2ce749e84487e2caf799/lib/framework/koa.js#L21-L63
|
12,940
|
rkusa/koa-passport
|
lib/framework/koa.js
|
authenticate
|
function authenticate(passport, name, options, callback) {
// normalize arguments
if (typeof options === 'function') {
callback = options
options = {}
}
options = options || {}
if (callback) {
// When the callback is set, neither `next`, `res.redirect` or `res.end`
// are called. That is, a workaround to catch the `callback` is required.
// The `passportAuthenticate()` method below will therefore set
// `callback.resolve` and `callback.reject`. Then, once the authentication
// finishes, the modified callback calls the original one and afterwards
// triggers either `callback.resolve` or `callback.reject` to inform
// `passportAuthenticate()` that we are ready.
const _callback = callback
callback = function(err, user, info, status) {
try {
Promise.resolve(_callback(err, user, info, status))
.then(() => callback.resolve(false))
.catch(err => callback.reject(err))
} catch (err) {
callback.reject(err)
}
}
}
const middleware = promisify(_authenticate(passport, name, options, callback))
return function passportAuthenticate(ctx, next) {
// this functions wraps the connect middleware
// to catch `next`, `res.redirect` and `res.end` calls
const p = new Promise((resolve, reject) => {
// mock the `req` object
const req = createReqMock(ctx, options.assignProperty || passport._userProperty || 'user')
function setBodyAndResolve(content) {
if (content) ctx.body = content
resolve(false)
}
// mock the `res` object
const res = {
redirect: function(url) {
ctx.redirect(url)
resolve(false)
},
set: ctx.set.bind(ctx),
setHeader: ctx.set.bind(ctx),
end: setBodyAndResolve,
send: setBodyAndResolve,
set statusCode(status) {
ctx.status = status
},
get statusCode() {
return ctx.status
}
}
req.res = res
// update the custom callback above
if (callback) {
callback.resolve = resolve
callback.reject = reject
}
// call the connect middleware
middleware(req, res).then(resolve, reject)
})
return p.then(cont => {
// cont equals `false` when `res.redirect` or `res.end` got called
// in this case, call next to continue through Koa's middleware stack
if (cont !== false) {
return next()
}
})
}
}
|
javascript
|
function authenticate(passport, name, options, callback) {
// normalize arguments
if (typeof options === 'function') {
callback = options
options = {}
}
options = options || {}
if (callback) {
// When the callback is set, neither `next`, `res.redirect` or `res.end`
// are called. That is, a workaround to catch the `callback` is required.
// The `passportAuthenticate()` method below will therefore set
// `callback.resolve` and `callback.reject`. Then, once the authentication
// finishes, the modified callback calls the original one and afterwards
// triggers either `callback.resolve` or `callback.reject` to inform
// `passportAuthenticate()` that we are ready.
const _callback = callback
callback = function(err, user, info, status) {
try {
Promise.resolve(_callback(err, user, info, status))
.then(() => callback.resolve(false))
.catch(err => callback.reject(err))
} catch (err) {
callback.reject(err)
}
}
}
const middleware = promisify(_authenticate(passport, name, options, callback))
return function passportAuthenticate(ctx, next) {
// this functions wraps the connect middleware
// to catch `next`, `res.redirect` and `res.end` calls
const p = new Promise((resolve, reject) => {
// mock the `req` object
const req = createReqMock(ctx, options.assignProperty || passport._userProperty || 'user')
function setBodyAndResolve(content) {
if (content) ctx.body = content
resolve(false)
}
// mock the `res` object
const res = {
redirect: function(url) {
ctx.redirect(url)
resolve(false)
},
set: ctx.set.bind(ctx),
setHeader: ctx.set.bind(ctx),
end: setBodyAndResolve,
send: setBodyAndResolve,
set statusCode(status) {
ctx.status = status
},
get statusCode() {
return ctx.status
}
}
req.res = res
// update the custom callback above
if (callback) {
callback.resolve = resolve
callback.reject = reject
}
// call the connect middleware
middleware(req, res).then(resolve, reject)
})
return p.then(cont => {
// cont equals `false` when `res.redirect` or `res.end` got called
// in this case, call next to continue through Koa's middleware stack
if (cont !== false) {
return next()
}
})
}
}
|
[
"function",
"authenticate",
"(",
"passport",
",",
"name",
",",
"options",
",",
"callback",
")",
"{",
"// normalize arguments",
"if",
"(",
"typeof",
"options",
"===",
"'function'",
")",
"{",
"callback",
"=",
"options",
"options",
"=",
"{",
"}",
"}",
"options",
"=",
"options",
"||",
"{",
"}",
"if",
"(",
"callback",
")",
"{",
"// When the callback is set, neither `next`, `res.redirect` or `res.end`",
"// are called. That is, a workaround to catch the `callback` is required.",
"// The `passportAuthenticate()` method below will therefore set",
"// `callback.resolve` and `callback.reject`. Then, once the authentication",
"// finishes, the modified callback calls the original one and afterwards",
"// triggers either `callback.resolve` or `callback.reject` to inform",
"// `passportAuthenticate()` that we are ready.",
"const",
"_callback",
"=",
"callback",
"callback",
"=",
"function",
"(",
"err",
",",
"user",
",",
"info",
",",
"status",
")",
"{",
"try",
"{",
"Promise",
".",
"resolve",
"(",
"_callback",
"(",
"err",
",",
"user",
",",
"info",
",",
"status",
")",
")",
".",
"then",
"(",
"(",
")",
"=>",
"callback",
".",
"resolve",
"(",
"false",
")",
")",
".",
"catch",
"(",
"err",
"=>",
"callback",
".",
"reject",
"(",
"err",
")",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"callback",
".",
"reject",
"(",
"err",
")",
"}",
"}",
"}",
"const",
"middleware",
"=",
"promisify",
"(",
"_authenticate",
"(",
"passport",
",",
"name",
",",
"options",
",",
"callback",
")",
")",
"return",
"function",
"passportAuthenticate",
"(",
"ctx",
",",
"next",
")",
"{",
"// this functions wraps the connect middleware",
"// to catch `next`, `res.redirect` and `res.end` calls",
"const",
"p",
"=",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"// mock the `req` object",
"const",
"req",
"=",
"createReqMock",
"(",
"ctx",
",",
"options",
".",
"assignProperty",
"||",
"passport",
".",
"_userProperty",
"||",
"'user'",
")",
"function",
"setBodyAndResolve",
"(",
"content",
")",
"{",
"if",
"(",
"content",
")",
"ctx",
".",
"body",
"=",
"content",
"resolve",
"(",
"false",
")",
"}",
"// mock the `res` object",
"const",
"res",
"=",
"{",
"redirect",
":",
"function",
"(",
"url",
")",
"{",
"ctx",
".",
"redirect",
"(",
"url",
")",
"resolve",
"(",
"false",
")",
"}",
",",
"set",
":",
"ctx",
".",
"set",
".",
"bind",
"(",
"ctx",
")",
",",
"setHeader",
":",
"ctx",
".",
"set",
".",
"bind",
"(",
"ctx",
")",
",",
"end",
":",
"setBodyAndResolve",
",",
"send",
":",
"setBodyAndResolve",
",",
"set",
"statusCode",
"(",
"status",
")",
"{",
"ctx",
".",
"status",
"=",
"status",
"}",
",",
"get",
"statusCode",
"(",
")",
"{",
"return",
"ctx",
".",
"status",
"}",
"}",
"req",
".",
"res",
"=",
"res",
"// update the custom callback above",
"if",
"(",
"callback",
")",
"{",
"callback",
".",
"resolve",
"=",
"resolve",
"callback",
".",
"reject",
"=",
"reject",
"}",
"// call the connect middleware",
"middleware",
"(",
"req",
",",
"res",
")",
".",
"then",
"(",
"resolve",
",",
"reject",
")",
"}",
")",
"return",
"p",
".",
"then",
"(",
"cont",
"=>",
"{",
"// cont equals `false` when `res.redirect` or `res.end` got called",
"// in this case, call next to continue through Koa's middleware stack",
"if",
"(",
"cont",
"!==",
"false",
")",
"{",
"return",
"next",
"(",
")",
"}",
"}",
")",
"}",
"}"
] |
Passport's authenticate middleware for Koa.
@param {String|Array} name
@param {Object} options
@param {GeneratorFunction} callback
@return {GeneratorFunction}
@api private
|
[
"Passport",
"s",
"authenticate",
"middleware",
"for",
"Koa",
"."
] |
89c131476ce8919b9c3f2ce749e84487e2caf799
|
https://github.com/rkusa/koa-passport/blob/89c131476ce8919b9c3f2ce749e84487e2caf799/lib/framework/koa.js#L74-L154
|
12,941
|
rkusa/koa-passport
|
lib/framework/koa.js
|
authorize
|
function authorize(passport, name, options, callback) {
options = options || {}
options.assignProperty = 'account'
return authenticate(passport, name, options, callback)
}
|
javascript
|
function authorize(passport, name, options, callback) {
options = options || {}
options.assignProperty = 'account'
return authenticate(passport, name, options, callback)
}
|
[
"function",
"authorize",
"(",
"passport",
",",
"name",
",",
"options",
",",
"callback",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
"options",
".",
"assignProperty",
"=",
"'account'",
"return",
"authenticate",
"(",
"passport",
",",
"name",
",",
"options",
",",
"callback",
")",
"}"
] |
Passport's authorize middleware for Koa.
@param {String|Array} name
@param {Object} options
@param {GeneratorFunction} callback
@return {GeneratorFunction}
@api private
|
[
"Passport",
"s",
"authorize",
"middleware",
"for",
"Koa",
"."
] |
89c131476ce8919b9c3f2ce749e84487e2caf799
|
https://github.com/rkusa/koa-passport/blob/89c131476ce8919b9c3f2ce749e84487e2caf799/lib/framework/koa.js#L165-L170
|
12,942
|
rkusa/koa-passport
|
lib/framework/request.js
|
getObject
|
function getObject(ctx, key) {
if (ctx.state && (key in ctx.state)) {
return ctx.state
}
if (key in ctx.request) {
return ctx.request
}
if (key in ctx.req) {
return ctx.req
}
if (key in ctx) {
return ctx
}
return undefined
}
|
javascript
|
function getObject(ctx, key) {
if (ctx.state && (key in ctx.state)) {
return ctx.state
}
if (key in ctx.request) {
return ctx.request
}
if (key in ctx.req) {
return ctx.req
}
if (key in ctx) {
return ctx
}
return undefined
}
|
[
"function",
"getObject",
"(",
"ctx",
",",
"key",
")",
"{",
"if",
"(",
"ctx",
".",
"state",
"&&",
"(",
"key",
"in",
"ctx",
".",
"state",
")",
")",
"{",
"return",
"ctx",
".",
"state",
"}",
"if",
"(",
"key",
"in",
"ctx",
".",
"request",
")",
"{",
"return",
"ctx",
".",
"request",
"}",
"if",
"(",
"key",
"in",
"ctx",
".",
"req",
")",
"{",
"return",
"ctx",
".",
"req",
"}",
"if",
"(",
"key",
"in",
"ctx",
")",
"{",
"return",
"ctx",
"}",
"return",
"undefined",
"}"
] |
test where the key is available, either in `ctx.state`, Node's request, Koa's request or Koa's context
|
[
"test",
"where",
"the",
"key",
"is",
"available",
"either",
"in",
"ctx",
".",
"state",
"Node",
"s",
"request",
"Koa",
"s",
"request",
"or",
"Koa",
"s",
"context"
] |
89c131476ce8919b9c3f2ce749e84487e2caf799
|
https://github.com/rkusa/koa-passport/blob/89c131476ce8919b9c3f2ce749e84487e2caf799/lib/framework/request.js#L114-L132
|
12,943
|
orthes/medium-editor-insert-plugin
|
dist/js/medium-editor-insert-plugin.js
|
Core
|
function Core(el, options) {
var editor;
this.el = el;
this.$el = $(el);
this.templates = window.MediumInsert.Templates;
if (options) {
// Fix #142
// Avoid deep copying editor object, because since v2.3.0 it contains circular references which causes jQuery.extend to break
// Instead copy editor object to this.options manually
editor = options.editor;
options.editor = null;
}
this.options = $.extend(true, {}, defaults, options);
this.options.editor = editor;
if (options) {
options.editor = editor; // Restore original object definition
}
this._defaults = defaults;
this._name = pluginName;
// Extend editor's functions
if (this.options && this.options.editor) {
if (this.options.editor._serialize === undefined) {
this.options.editor._serialize = this.options.editor.serialize;
}
if (this.options.editor._destroy === undefined) {
this.options.editor._destroy = this.options.editor.destroy;
}
if (this.options.editor._setup === undefined) {
this.options.editor._setup = this.options.editor.setup;
}
this.options.editor._hideInsertButtons = this.hideButtons;
this.options.editor.serialize = this.editorSerialize;
this.options.editor.destroy = this.editorDestroy;
this.options.editor.setup = this.editorSetup;
if (this.options.editor.getExtensionByName('placeholder') !== undefined) {
this.options.editor.getExtensionByName('placeholder').updatePlaceholder = this.editorUpdatePlaceholder;
}
}
}
|
javascript
|
function Core(el, options) {
var editor;
this.el = el;
this.$el = $(el);
this.templates = window.MediumInsert.Templates;
if (options) {
// Fix #142
// Avoid deep copying editor object, because since v2.3.0 it contains circular references which causes jQuery.extend to break
// Instead copy editor object to this.options manually
editor = options.editor;
options.editor = null;
}
this.options = $.extend(true, {}, defaults, options);
this.options.editor = editor;
if (options) {
options.editor = editor; // Restore original object definition
}
this._defaults = defaults;
this._name = pluginName;
// Extend editor's functions
if (this.options && this.options.editor) {
if (this.options.editor._serialize === undefined) {
this.options.editor._serialize = this.options.editor.serialize;
}
if (this.options.editor._destroy === undefined) {
this.options.editor._destroy = this.options.editor.destroy;
}
if (this.options.editor._setup === undefined) {
this.options.editor._setup = this.options.editor.setup;
}
this.options.editor._hideInsertButtons = this.hideButtons;
this.options.editor.serialize = this.editorSerialize;
this.options.editor.destroy = this.editorDestroy;
this.options.editor.setup = this.editorSetup;
if (this.options.editor.getExtensionByName('placeholder') !== undefined) {
this.options.editor.getExtensionByName('placeholder').updatePlaceholder = this.editorUpdatePlaceholder;
}
}
}
|
[
"function",
"Core",
"(",
"el",
",",
"options",
")",
"{",
"var",
"editor",
";",
"this",
".",
"el",
"=",
"el",
";",
"this",
".",
"$el",
"=",
"$",
"(",
"el",
")",
";",
"this",
".",
"templates",
"=",
"window",
".",
"MediumInsert",
".",
"Templates",
";",
"if",
"(",
"options",
")",
"{",
"// Fix #142",
"// Avoid deep copying editor object, because since v2.3.0 it contains circular references which causes jQuery.extend to break",
"// Instead copy editor object to this.options manually",
"editor",
"=",
"options",
".",
"editor",
";",
"options",
".",
"editor",
"=",
"null",
";",
"}",
"this",
".",
"options",
"=",
"$",
".",
"extend",
"(",
"true",
",",
"{",
"}",
",",
"defaults",
",",
"options",
")",
";",
"this",
".",
"options",
".",
"editor",
"=",
"editor",
";",
"if",
"(",
"options",
")",
"{",
"options",
".",
"editor",
"=",
"editor",
";",
"// Restore original object definition",
"}",
"this",
".",
"_defaults",
"=",
"defaults",
";",
"this",
".",
"_name",
"=",
"pluginName",
";",
"// Extend editor's functions",
"if",
"(",
"this",
".",
"options",
"&&",
"this",
".",
"options",
".",
"editor",
")",
"{",
"if",
"(",
"this",
".",
"options",
".",
"editor",
".",
"_serialize",
"===",
"undefined",
")",
"{",
"this",
".",
"options",
".",
"editor",
".",
"_serialize",
"=",
"this",
".",
"options",
".",
"editor",
".",
"serialize",
";",
"}",
"if",
"(",
"this",
".",
"options",
".",
"editor",
".",
"_destroy",
"===",
"undefined",
")",
"{",
"this",
".",
"options",
".",
"editor",
".",
"_destroy",
"=",
"this",
".",
"options",
".",
"editor",
".",
"destroy",
";",
"}",
"if",
"(",
"this",
".",
"options",
".",
"editor",
".",
"_setup",
"===",
"undefined",
")",
"{",
"this",
".",
"options",
".",
"editor",
".",
"_setup",
"=",
"this",
".",
"options",
".",
"editor",
".",
"setup",
";",
"}",
"this",
".",
"options",
".",
"editor",
".",
"_hideInsertButtons",
"=",
"this",
".",
"hideButtons",
";",
"this",
".",
"options",
".",
"editor",
".",
"serialize",
"=",
"this",
".",
"editorSerialize",
";",
"this",
".",
"options",
".",
"editor",
".",
"destroy",
"=",
"this",
".",
"editorDestroy",
";",
"this",
".",
"options",
".",
"editor",
".",
"setup",
"=",
"this",
".",
"editorSetup",
";",
"if",
"(",
"this",
".",
"options",
".",
"editor",
".",
"getExtensionByName",
"(",
"'placeholder'",
")",
"!==",
"undefined",
")",
"{",
"this",
".",
"options",
".",
"editor",
".",
"getExtensionByName",
"(",
"'placeholder'",
")",
".",
"updatePlaceholder",
"=",
"this",
".",
"editorUpdatePlaceholder",
";",
"}",
"}",
"}"
] |
Core plugin's object
Sets options, variables and calls init() function
@constructor
@param {DOM} el - DOM element to init the plugin on
@param {object} options - Options to override defaults
@return {void}
|
[
"Core",
"plugin",
"s",
"object"
] |
276e680e49bdd965eed50e4f6ed67d660e5ca518
|
https://github.com/orthes/medium-editor-insert-plugin/blob/276e680e49bdd965eed50e4f6ed67d660e5ca518/dist/js/medium-editor-insert-plugin.js#L203-L247
|
12,944
|
orthes/medium-editor-insert-plugin
|
spec/helpers/util.js
|
placeCaret
|
function placeCaret(el, position) {
var range, sel;
range = document.createRange();
sel = window.getSelection();
range.setStart(el.childNodes[0], position);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
|
javascript
|
function placeCaret(el, position) {
var range, sel;
range = document.createRange();
sel = window.getSelection();
range.setStart(el.childNodes[0], position);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
|
[
"function",
"placeCaret",
"(",
"el",
",",
"position",
")",
"{",
"var",
"range",
",",
"sel",
";",
"range",
"=",
"document",
".",
"createRange",
"(",
")",
";",
"sel",
"=",
"window",
".",
"getSelection",
"(",
")",
";",
"range",
".",
"setStart",
"(",
"el",
".",
"childNodes",
"[",
"0",
"]",
",",
"position",
")",
";",
"range",
".",
"collapse",
"(",
"true",
")",
";",
"sel",
".",
"removeAllRanges",
"(",
")",
";",
"sel",
".",
"addRange",
"(",
"range",
")",
";",
"}"
] |
Placing caret to element and selected position
@param {Element} el
@param {integer} position
@return {void}
|
[
"Placing",
"caret",
"to",
"element",
"and",
"selected",
"position"
] |
276e680e49bdd965eed50e4f6ed67d660e5ca518
|
https://github.com/orthes/medium-editor-insert-plugin/blob/276e680e49bdd965eed50e4f6ed67d660e5ca518/spec/helpers/util.js#L9-L18
|
12,945
|
chieffancypants/angular-loading-bar
|
build/loading-bar.js
|
isCached
|
function isCached(config) {
var cache;
var defaultCache = $cacheFactory.get('$http');
var defaults = $httpProvider.defaults;
// Choose the proper cache source. Borrowed from angular: $http service
if ((config.cache || defaults.cache) && config.cache !== false &&
(config.method === 'GET' || config.method === 'JSONP')) {
cache = angular.isObject(config.cache) ? config.cache
: angular.isObject(defaults.cache) ? defaults.cache
: defaultCache;
}
var cached = cache !== undefined ?
cache.get(config.url) !== undefined : false;
if (config.cached !== undefined && cached !== config.cached) {
return config.cached;
}
config.cached = cached;
return cached;
}
|
javascript
|
function isCached(config) {
var cache;
var defaultCache = $cacheFactory.get('$http');
var defaults = $httpProvider.defaults;
// Choose the proper cache source. Borrowed from angular: $http service
if ((config.cache || defaults.cache) && config.cache !== false &&
(config.method === 'GET' || config.method === 'JSONP')) {
cache = angular.isObject(config.cache) ? config.cache
: angular.isObject(defaults.cache) ? defaults.cache
: defaultCache;
}
var cached = cache !== undefined ?
cache.get(config.url) !== undefined : false;
if (config.cached !== undefined && cached !== config.cached) {
return config.cached;
}
config.cached = cached;
return cached;
}
|
[
"function",
"isCached",
"(",
"config",
")",
"{",
"var",
"cache",
";",
"var",
"defaultCache",
"=",
"$cacheFactory",
".",
"get",
"(",
"'$http'",
")",
";",
"var",
"defaults",
"=",
"$httpProvider",
".",
"defaults",
";",
"// Choose the proper cache source. Borrowed from angular: $http service",
"if",
"(",
"(",
"config",
".",
"cache",
"||",
"defaults",
".",
"cache",
")",
"&&",
"config",
".",
"cache",
"!==",
"false",
"&&",
"(",
"config",
".",
"method",
"===",
"'GET'",
"||",
"config",
".",
"method",
"===",
"'JSONP'",
")",
")",
"{",
"cache",
"=",
"angular",
".",
"isObject",
"(",
"config",
".",
"cache",
")",
"?",
"config",
".",
"cache",
":",
"angular",
".",
"isObject",
"(",
"defaults",
".",
"cache",
")",
"?",
"defaults",
".",
"cache",
":",
"defaultCache",
";",
"}",
"var",
"cached",
"=",
"cache",
"!==",
"undefined",
"?",
"cache",
".",
"get",
"(",
"config",
".",
"url",
")",
"!==",
"undefined",
":",
"false",
";",
"if",
"(",
"config",
".",
"cached",
"!==",
"undefined",
"&&",
"cached",
"!==",
"config",
".",
"cached",
")",
"{",
"return",
"config",
".",
"cached",
";",
"}",
"config",
".",
"cached",
"=",
"cached",
";",
"return",
"cached",
";",
"}"
] |
Determine if the response has already been cached
@param {Object} config the config option from the request
@return {Boolean} retrns true if cached, otherwise false
|
[
"Determine",
"if",
"the",
"response",
"has",
"already",
"been",
"cached"
] |
73ff0d9b13b6baa58da28a8376d464353b0b236a
|
https://github.com/chieffancypants/angular-loading-bar/blob/73ff0d9b13b6baa58da28a8376d464353b0b236a/build/loading-bar.js#L74-L95
|
12,946
|
chieffancypants/angular-loading-bar
|
build/loading-bar.js
|
_start
|
function _start() {
if (!$animate) {
$animate = $injector.get('$animate');
}
$timeout.cancel(completeTimeout);
// do not continually broadcast the started event:
if (started) {
return;
}
var document = $document[0];
var parent = document.querySelector ?
document.querySelector($parentSelector)
: $document.find($parentSelector)[0]
;
if (! parent) {
parent = document.getElementsByTagName('body')[0];
}
var $parent = angular.element(parent);
var $after = parent.lastChild && angular.element(parent.lastChild);
$rootScope.$broadcast('cfpLoadingBar:started');
started = true;
if (includeBar) {
$animate.enter(loadingBarContainer, $parent, $after);
}
if (includeSpinner) {
$animate.enter(spinner, $parent, loadingBarContainer);
}
_set(startSize);
}
|
javascript
|
function _start() {
if (!$animate) {
$animate = $injector.get('$animate');
}
$timeout.cancel(completeTimeout);
// do not continually broadcast the started event:
if (started) {
return;
}
var document = $document[0];
var parent = document.querySelector ?
document.querySelector($parentSelector)
: $document.find($parentSelector)[0]
;
if (! parent) {
parent = document.getElementsByTagName('body')[0];
}
var $parent = angular.element(parent);
var $after = parent.lastChild && angular.element(parent.lastChild);
$rootScope.$broadcast('cfpLoadingBar:started');
started = true;
if (includeBar) {
$animate.enter(loadingBarContainer, $parent, $after);
}
if (includeSpinner) {
$animate.enter(spinner, $parent, loadingBarContainer);
}
_set(startSize);
}
|
[
"function",
"_start",
"(",
")",
"{",
"if",
"(",
"!",
"$animate",
")",
"{",
"$animate",
"=",
"$injector",
".",
"get",
"(",
"'$animate'",
")",
";",
"}",
"$timeout",
".",
"cancel",
"(",
"completeTimeout",
")",
";",
"// do not continually broadcast the started event:",
"if",
"(",
"started",
")",
"{",
"return",
";",
"}",
"var",
"document",
"=",
"$document",
"[",
"0",
"]",
";",
"var",
"parent",
"=",
"document",
".",
"querySelector",
"?",
"document",
".",
"querySelector",
"(",
"$parentSelector",
")",
":",
"$document",
".",
"find",
"(",
"$parentSelector",
")",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"parent",
")",
"{",
"parent",
"=",
"document",
".",
"getElementsByTagName",
"(",
"'body'",
")",
"[",
"0",
"]",
";",
"}",
"var",
"$parent",
"=",
"angular",
".",
"element",
"(",
"parent",
")",
";",
"var",
"$after",
"=",
"parent",
".",
"lastChild",
"&&",
"angular",
".",
"element",
"(",
"parent",
".",
"lastChild",
")",
";",
"$rootScope",
".",
"$broadcast",
"(",
"'cfpLoadingBar:started'",
")",
";",
"started",
"=",
"true",
";",
"if",
"(",
"includeBar",
")",
"{",
"$animate",
".",
"enter",
"(",
"loadingBarContainer",
",",
"$parent",
",",
"$after",
")",
";",
"}",
"if",
"(",
"includeSpinner",
")",
"{",
"$animate",
".",
"enter",
"(",
"spinner",
",",
"$parent",
",",
"loadingBarContainer",
")",
";",
"}",
"_set",
"(",
"startSize",
")",
";",
"}"
] |
Inserts the loading bar element into the dom, and sets it to 2%
|
[
"Inserts",
"the",
"loading",
"bar",
"element",
"into",
"the",
"dom",
"and",
"sets",
"it",
"to",
"2%"
] |
73ff0d9b13b6baa58da28a8376d464353b0b236a
|
https://github.com/chieffancypants/angular-loading-bar/blob/73ff0d9b13b6baa58da28a8376d464353b0b236a/build/loading-bar.js#L198-L235
|
12,947
|
chieffancypants/angular-loading-bar
|
build/loading-bar.js
|
_set
|
function _set(n) {
if (!started) {
return;
}
var pct = (n * 100) + '%';
loadingBar.css('width', pct);
status = n;
// increment loadingbar to give the illusion that there is always
// progress but make sure to cancel the previous timeouts so we don't
// have multiple incs running at the same time.
if (autoIncrement) {
$timeout.cancel(incTimeout);
incTimeout = $timeout(function() {
_inc();
}, 250);
}
}
|
javascript
|
function _set(n) {
if (!started) {
return;
}
var pct = (n * 100) + '%';
loadingBar.css('width', pct);
status = n;
// increment loadingbar to give the illusion that there is always
// progress but make sure to cancel the previous timeouts so we don't
// have multiple incs running at the same time.
if (autoIncrement) {
$timeout.cancel(incTimeout);
incTimeout = $timeout(function() {
_inc();
}, 250);
}
}
|
[
"function",
"_set",
"(",
"n",
")",
"{",
"if",
"(",
"!",
"started",
")",
"{",
"return",
";",
"}",
"var",
"pct",
"=",
"(",
"n",
"*",
"100",
")",
"+",
"'%'",
";",
"loadingBar",
".",
"css",
"(",
"'width'",
",",
"pct",
")",
";",
"status",
"=",
"n",
";",
"// increment loadingbar to give the illusion that there is always",
"// progress but make sure to cancel the previous timeouts so we don't",
"// have multiple incs running at the same time.",
"if",
"(",
"autoIncrement",
")",
"{",
"$timeout",
".",
"cancel",
"(",
"incTimeout",
")",
";",
"incTimeout",
"=",
"$timeout",
"(",
"function",
"(",
")",
"{",
"_inc",
"(",
")",
";",
"}",
",",
"250",
")",
";",
"}",
"}"
] |
Set the loading bar's width to a certain percent.
@param n any value between 0 and 1
|
[
"Set",
"the",
"loading",
"bar",
"s",
"width",
"to",
"a",
"certain",
"percent",
"."
] |
73ff0d9b13b6baa58da28a8376d464353b0b236a
|
https://github.com/chieffancypants/angular-loading-bar/blob/73ff0d9b13b6baa58da28a8376d464353b0b236a/build/loading-bar.js#L242-L259
|
12,948
|
chieffancypants/angular-loading-bar
|
build/loading-bar.js
|
_inc
|
function _inc() {
if (_status() >= 1) {
return;
}
var rnd = 0;
// TODO: do this mathmatically instead of through conditions
var stat = _status();
if (stat >= 0 && stat < 0.25) {
// Start out between 3 - 6% increments
rnd = (Math.random() * (5 - 3 + 1) + 3) / 100;
} else if (stat >= 0.25 && stat < 0.65) {
// increment between 0 - 3%
rnd = (Math.random() * 3) / 100;
} else if (stat >= 0.65 && stat < 0.9) {
// increment between 0 - 2%
rnd = (Math.random() * 2) / 100;
} else if (stat >= 0.9 && stat < 0.99) {
// finally, increment it .5 %
rnd = 0.005;
} else {
// after 99%, don't increment:
rnd = 0;
}
var pct = _status() + rnd;
_set(pct);
}
|
javascript
|
function _inc() {
if (_status() >= 1) {
return;
}
var rnd = 0;
// TODO: do this mathmatically instead of through conditions
var stat = _status();
if (stat >= 0 && stat < 0.25) {
// Start out between 3 - 6% increments
rnd = (Math.random() * (5 - 3 + 1) + 3) / 100;
} else if (stat >= 0.25 && stat < 0.65) {
// increment between 0 - 3%
rnd = (Math.random() * 3) / 100;
} else if (stat >= 0.65 && stat < 0.9) {
// increment between 0 - 2%
rnd = (Math.random() * 2) / 100;
} else if (stat >= 0.9 && stat < 0.99) {
// finally, increment it .5 %
rnd = 0.005;
} else {
// after 99%, don't increment:
rnd = 0;
}
var pct = _status() + rnd;
_set(pct);
}
|
[
"function",
"_inc",
"(",
")",
"{",
"if",
"(",
"_status",
"(",
")",
">=",
"1",
")",
"{",
"return",
";",
"}",
"var",
"rnd",
"=",
"0",
";",
"// TODO: do this mathmatically instead of through conditions",
"var",
"stat",
"=",
"_status",
"(",
")",
";",
"if",
"(",
"stat",
">=",
"0",
"&&",
"stat",
"<",
"0.25",
")",
"{",
"// Start out between 3 - 6% increments",
"rnd",
"=",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"(",
"5",
"-",
"3",
"+",
"1",
")",
"+",
"3",
")",
"/",
"100",
";",
"}",
"else",
"if",
"(",
"stat",
">=",
"0.25",
"&&",
"stat",
"<",
"0.65",
")",
"{",
"// increment between 0 - 3%",
"rnd",
"=",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"3",
")",
"/",
"100",
";",
"}",
"else",
"if",
"(",
"stat",
">=",
"0.65",
"&&",
"stat",
"<",
"0.9",
")",
"{",
"// increment between 0 - 2%",
"rnd",
"=",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"2",
")",
"/",
"100",
";",
"}",
"else",
"if",
"(",
"stat",
">=",
"0.9",
"&&",
"stat",
"<",
"0.99",
")",
"{",
"// finally, increment it .5 %",
"rnd",
"=",
"0.005",
";",
"}",
"else",
"{",
"// after 99%, don't increment:",
"rnd",
"=",
"0",
";",
"}",
"var",
"pct",
"=",
"_status",
"(",
")",
"+",
"rnd",
";",
"_set",
"(",
"pct",
")",
";",
"}"
] |
Increments the loading bar by a random amount
but slows down as it progresses
|
[
"Increments",
"the",
"loading",
"bar",
"by",
"a",
"random",
"amount",
"but",
"slows",
"down",
"as",
"it",
"progresses"
] |
73ff0d9b13b6baa58da28a8376d464353b0b236a
|
https://github.com/chieffancypants/angular-loading-bar/blob/73ff0d9b13b6baa58da28a8376d464353b0b236a/build/loading-bar.js#L265-L294
|
12,949
|
yargs/yargs-parser
|
index.js
|
eatNargs
|
function eatNargs (i, key, args) {
var ii
const toEat = checkAllAliases(key, flags.nargs)
// nargs will not consume flag arguments, e.g., -abc, --foo,
// and terminates when one is observed.
var available = 0
for (ii = i + 1; ii < args.length; ii++) {
if (!args[ii].match(/^-[^0-9]/)) available++
else break
}
if (available < toEat) error = Error(__('Not enough arguments following: %s', key))
const consumed = Math.min(available, toEat)
for (ii = i + 1; ii < (consumed + i + 1); ii++) {
setArg(key, args[ii])
}
return (i + consumed)
}
|
javascript
|
function eatNargs (i, key, args) {
var ii
const toEat = checkAllAliases(key, flags.nargs)
// nargs will not consume flag arguments, e.g., -abc, --foo,
// and terminates when one is observed.
var available = 0
for (ii = i + 1; ii < args.length; ii++) {
if (!args[ii].match(/^-[^0-9]/)) available++
else break
}
if (available < toEat) error = Error(__('Not enough arguments following: %s', key))
const consumed = Math.min(available, toEat)
for (ii = i + 1; ii < (consumed + i + 1); ii++) {
setArg(key, args[ii])
}
return (i + consumed)
}
|
[
"function",
"eatNargs",
"(",
"i",
",",
"key",
",",
"args",
")",
"{",
"var",
"ii",
"const",
"toEat",
"=",
"checkAllAliases",
"(",
"key",
",",
"flags",
".",
"nargs",
")",
"// nargs will not consume flag arguments, e.g., -abc, --foo,",
"// and terminates when one is observed.",
"var",
"available",
"=",
"0",
"for",
"(",
"ii",
"=",
"i",
"+",
"1",
";",
"ii",
"<",
"args",
".",
"length",
";",
"ii",
"++",
")",
"{",
"if",
"(",
"!",
"args",
"[",
"ii",
"]",
".",
"match",
"(",
"/",
"^-[^0-9]",
"/",
")",
")",
"available",
"++",
"else",
"break",
"}",
"if",
"(",
"available",
"<",
"toEat",
")",
"error",
"=",
"Error",
"(",
"__",
"(",
"'Not enough arguments following: %s'",
",",
"key",
")",
")",
"const",
"consumed",
"=",
"Math",
".",
"min",
"(",
"available",
",",
"toEat",
")",
"for",
"(",
"ii",
"=",
"i",
"+",
"1",
";",
"ii",
"<",
"(",
"consumed",
"+",
"i",
"+",
"1",
")",
";",
"ii",
"++",
")",
"{",
"setArg",
"(",
"key",
",",
"args",
"[",
"ii",
"]",
")",
"}",
"return",
"(",
"i",
"+",
"consumed",
")",
"}"
] |
how many arguments should we consume, based on the nargs option?
|
[
"how",
"many",
"arguments",
"should",
"we",
"consume",
"based",
"on",
"the",
"nargs",
"option?"
] |
981e1512d15a0af757a74a9cd75c448259aa8efa
|
https://github.com/yargs/yargs-parser/blob/981e1512d15a0af757a74a9cd75c448259aa8efa/index.js#L355-L375
|
12,950
|
yargs/yargs-parser
|
index.js
|
setConfig
|
function setConfig (argv) {
var configLookup = {}
// expand defaults/aliases, in-case any happen to reference
// the config.json file.
applyDefaultsAndAliases(configLookup, flags.aliases, defaults)
Object.keys(flags.configs).forEach(function (configKey) {
var configPath = argv[configKey] || configLookup[configKey]
if (configPath) {
try {
var config = null
var resolvedConfigPath = path.resolve(process.cwd(), configPath)
if (typeof flags.configs[configKey] === 'function') {
try {
config = flags.configs[configKey](resolvedConfigPath)
} catch (e) {
config = e
}
if (config instanceof Error) {
error = config
return
}
} else {
config = require(resolvedConfigPath)
}
setConfigObject(config)
} catch (ex) {
if (argv[configKey]) error = Error(__('Invalid JSON config file: %s', configPath))
}
}
})
}
|
javascript
|
function setConfig (argv) {
var configLookup = {}
// expand defaults/aliases, in-case any happen to reference
// the config.json file.
applyDefaultsAndAliases(configLookup, flags.aliases, defaults)
Object.keys(flags.configs).forEach(function (configKey) {
var configPath = argv[configKey] || configLookup[configKey]
if (configPath) {
try {
var config = null
var resolvedConfigPath = path.resolve(process.cwd(), configPath)
if (typeof flags.configs[configKey] === 'function') {
try {
config = flags.configs[configKey](resolvedConfigPath)
} catch (e) {
config = e
}
if (config instanceof Error) {
error = config
return
}
} else {
config = require(resolvedConfigPath)
}
setConfigObject(config)
} catch (ex) {
if (argv[configKey]) error = Error(__('Invalid JSON config file: %s', configPath))
}
}
})
}
|
[
"function",
"setConfig",
"(",
"argv",
")",
"{",
"var",
"configLookup",
"=",
"{",
"}",
"// expand defaults/aliases, in-case any happen to reference",
"// the config.json file.",
"applyDefaultsAndAliases",
"(",
"configLookup",
",",
"flags",
".",
"aliases",
",",
"defaults",
")",
"Object",
".",
"keys",
"(",
"flags",
".",
"configs",
")",
".",
"forEach",
"(",
"function",
"(",
"configKey",
")",
"{",
"var",
"configPath",
"=",
"argv",
"[",
"configKey",
"]",
"||",
"configLookup",
"[",
"configKey",
"]",
"if",
"(",
"configPath",
")",
"{",
"try",
"{",
"var",
"config",
"=",
"null",
"var",
"resolvedConfigPath",
"=",
"path",
".",
"resolve",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"configPath",
")",
"if",
"(",
"typeof",
"flags",
".",
"configs",
"[",
"configKey",
"]",
"===",
"'function'",
")",
"{",
"try",
"{",
"config",
"=",
"flags",
".",
"configs",
"[",
"configKey",
"]",
"(",
"resolvedConfigPath",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"config",
"=",
"e",
"}",
"if",
"(",
"config",
"instanceof",
"Error",
")",
"{",
"error",
"=",
"config",
"return",
"}",
"}",
"else",
"{",
"config",
"=",
"require",
"(",
"resolvedConfigPath",
")",
"}",
"setConfigObject",
"(",
"config",
")",
"}",
"catch",
"(",
"ex",
")",
"{",
"if",
"(",
"argv",
"[",
"configKey",
"]",
")",
"error",
"=",
"Error",
"(",
"__",
"(",
"'Invalid JSON config file: %s'",
",",
"configPath",
")",
")",
"}",
"}",
"}",
")",
"}"
] |
set args from config.json file, this should be applied last so that defaults can be applied.
|
[
"set",
"args",
"from",
"config",
".",
"json",
"file",
"this",
"should",
"be",
"applied",
"last",
"so",
"that",
"defaults",
"can",
"be",
"applied",
"."
] |
981e1512d15a0af757a74a9cd75c448259aa8efa
|
https://github.com/yargs/yargs-parser/blob/981e1512d15a0af757a74a9cd75c448259aa8efa/index.js#L511-L545
|
12,951
|
yargs/yargs-parser
|
index.js
|
setConfigObject
|
function setConfigObject (config, prev) {
Object.keys(config).forEach(function (key) {
var value = config[key]
var fullKey = prev ? prev + '.' + key : key
// if the value is an inner object and we have dot-notation
// enabled, treat inner objects in config the same as
// heavily nested dot notations (foo.bar.apple).
if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) {
// if the value is an object but not an array, check nested object
setConfigObject(value, fullKey)
} else {
// setting arguments via CLI takes precedence over
// values within the config file.
if (!hasKey(argv, fullKey.split('.')) || (flags.defaulted[fullKey]) || (flags.arrays[fullKey] && configuration['combine-arrays'])) {
setArg(fullKey, value)
}
}
})
}
|
javascript
|
function setConfigObject (config, prev) {
Object.keys(config).forEach(function (key) {
var value = config[key]
var fullKey = prev ? prev + '.' + key : key
// if the value is an inner object and we have dot-notation
// enabled, treat inner objects in config the same as
// heavily nested dot notations (foo.bar.apple).
if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) {
// if the value is an object but not an array, check nested object
setConfigObject(value, fullKey)
} else {
// setting arguments via CLI takes precedence over
// values within the config file.
if (!hasKey(argv, fullKey.split('.')) || (flags.defaulted[fullKey]) || (flags.arrays[fullKey] && configuration['combine-arrays'])) {
setArg(fullKey, value)
}
}
})
}
|
[
"function",
"setConfigObject",
"(",
"config",
",",
"prev",
")",
"{",
"Object",
".",
"keys",
"(",
"config",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"var",
"value",
"=",
"config",
"[",
"key",
"]",
"var",
"fullKey",
"=",
"prev",
"?",
"prev",
"+",
"'.'",
"+",
"key",
":",
"key",
"// if the value is an inner object and we have dot-notation",
"// enabled, treat inner objects in config the same as",
"// heavily nested dot notations (foo.bar.apple).",
"if",
"(",
"typeof",
"value",
"===",
"'object'",
"&&",
"value",
"!==",
"null",
"&&",
"!",
"Array",
".",
"isArray",
"(",
"value",
")",
"&&",
"configuration",
"[",
"'dot-notation'",
"]",
")",
"{",
"// if the value is an object but not an array, check nested object",
"setConfigObject",
"(",
"value",
",",
"fullKey",
")",
"}",
"else",
"{",
"// setting arguments via CLI takes precedence over",
"// values within the config file.",
"if",
"(",
"!",
"hasKey",
"(",
"argv",
",",
"fullKey",
".",
"split",
"(",
"'.'",
")",
")",
"||",
"(",
"flags",
".",
"defaulted",
"[",
"fullKey",
"]",
")",
"||",
"(",
"flags",
".",
"arrays",
"[",
"fullKey",
"]",
"&&",
"configuration",
"[",
"'combine-arrays'",
"]",
")",
")",
"{",
"setArg",
"(",
"fullKey",
",",
"value",
")",
"}",
"}",
"}",
")",
"}"
] |
set args from config object. it recursively checks nested objects.
|
[
"set",
"args",
"from",
"config",
"object",
".",
"it",
"recursively",
"checks",
"nested",
"objects",
"."
] |
981e1512d15a0af757a74a9cd75c448259aa8efa
|
https://github.com/yargs/yargs-parser/blob/981e1512d15a0af757a74a9cd75c448259aa8efa/index.js#L549-L568
|
12,952
|
yargs/yargs-parser
|
index.js
|
defaultValue
|
function defaultValue (key) {
if (!checkAllAliases(key, flags.bools) &&
!checkAllAliases(key, flags.counts) &&
`${key}` in defaults) {
return defaults[key]
} else {
return defaultForType(guessType(key))
}
}
|
javascript
|
function defaultValue (key) {
if (!checkAllAliases(key, flags.bools) &&
!checkAllAliases(key, flags.counts) &&
`${key}` in defaults) {
return defaults[key]
} else {
return defaultForType(guessType(key))
}
}
|
[
"function",
"defaultValue",
"(",
"key",
")",
"{",
"if",
"(",
"!",
"checkAllAliases",
"(",
"key",
",",
"flags",
".",
"bools",
")",
"&&",
"!",
"checkAllAliases",
"(",
"key",
",",
"flags",
".",
"counts",
")",
"&&",
"`",
"${",
"key",
"}",
"`",
"in",
"defaults",
")",
"{",
"return",
"defaults",
"[",
"key",
"]",
"}",
"else",
"{",
"return",
"defaultForType",
"(",
"guessType",
"(",
"key",
")",
")",
"}",
"}"
] |
make a best effor to pick a default value for an option based on name and type.
|
[
"make",
"a",
"best",
"effor",
"to",
"pick",
"a",
"default",
"value",
"for",
"an",
"option",
"based",
"on",
"name",
"and",
"type",
"."
] |
981e1512d15a0af757a74a9cd75c448259aa8efa
|
https://github.com/yargs/yargs-parser/blob/981e1512d15a0af757a74a9cd75c448259aa8efa/index.js#L771-L779
|
12,953
|
yargs/yargs-parser
|
index.js
|
guessType
|
function guessType (key) {
var type = 'boolean'
if (checkAllAliases(key, flags.strings)) type = 'string'
else if (checkAllAliases(key, flags.numbers)) type = 'number'
else if (checkAllAliases(key, flags.arrays)) type = 'array'
return type
}
|
javascript
|
function guessType (key) {
var type = 'boolean'
if (checkAllAliases(key, flags.strings)) type = 'string'
else if (checkAllAliases(key, flags.numbers)) type = 'number'
else if (checkAllAliases(key, flags.arrays)) type = 'array'
return type
}
|
[
"function",
"guessType",
"(",
"key",
")",
"{",
"var",
"type",
"=",
"'boolean'",
"if",
"(",
"checkAllAliases",
"(",
"key",
",",
"flags",
".",
"strings",
")",
")",
"type",
"=",
"'string'",
"else",
"if",
"(",
"checkAllAliases",
"(",
"key",
",",
"flags",
".",
"numbers",
")",
")",
"type",
"=",
"'number'",
"else",
"if",
"(",
"checkAllAliases",
"(",
"key",
",",
"flags",
".",
"arrays",
")",
")",
"type",
"=",
"'array'",
"return",
"type",
"}"
] |
given a flag, enforce a default type.
|
[
"given",
"a",
"flag",
"enforce",
"a",
"default",
"type",
"."
] |
981e1512d15a0af757a74a9cd75c448259aa8efa
|
https://github.com/yargs/yargs-parser/blob/981e1512d15a0af757a74a9cd75c448259aa8efa/index.js#L795-L803
|
12,954
|
yargs/yargs-parser
|
index.js
|
combineAliases
|
function combineAliases (aliases) {
var aliasArrays = []
var change = true
var combined = {}
// turn alias lookup hash {key: ['alias1', 'alias2']} into
// a simple array ['key', 'alias1', 'alias2']
Object.keys(aliases).forEach(function (key) {
aliasArrays.push(
[].concat(aliases[key], key)
)
})
// combine arrays until zero changes are
// made in an iteration.
while (change) {
change = false
for (var i = 0; i < aliasArrays.length; i++) {
for (var ii = i + 1; ii < aliasArrays.length; ii++) {
var intersect = aliasArrays[i].filter(function (v) {
return aliasArrays[ii].indexOf(v) !== -1
})
if (intersect.length) {
aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii])
aliasArrays.splice(ii, 1)
change = true
break
}
}
}
}
// map arrays back to the hash-lookup (de-dupe while
// we're at it).
aliasArrays.forEach(function (aliasArray) {
aliasArray = aliasArray.filter(function (v, i, self) {
return self.indexOf(v) === i
})
combined[aliasArray.pop()] = aliasArray
})
return combined
}
|
javascript
|
function combineAliases (aliases) {
var aliasArrays = []
var change = true
var combined = {}
// turn alias lookup hash {key: ['alias1', 'alias2']} into
// a simple array ['key', 'alias1', 'alias2']
Object.keys(aliases).forEach(function (key) {
aliasArrays.push(
[].concat(aliases[key], key)
)
})
// combine arrays until zero changes are
// made in an iteration.
while (change) {
change = false
for (var i = 0; i < aliasArrays.length; i++) {
for (var ii = i + 1; ii < aliasArrays.length; ii++) {
var intersect = aliasArrays[i].filter(function (v) {
return aliasArrays[ii].indexOf(v) !== -1
})
if (intersect.length) {
aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii])
aliasArrays.splice(ii, 1)
change = true
break
}
}
}
}
// map arrays back to the hash-lookup (de-dupe while
// we're at it).
aliasArrays.forEach(function (aliasArray) {
aliasArray = aliasArray.filter(function (v, i, self) {
return self.indexOf(v) === i
})
combined[aliasArray.pop()] = aliasArray
})
return combined
}
|
[
"function",
"combineAliases",
"(",
"aliases",
")",
"{",
"var",
"aliasArrays",
"=",
"[",
"]",
"var",
"change",
"=",
"true",
"var",
"combined",
"=",
"{",
"}",
"// turn alias lookup hash {key: ['alias1', 'alias2']} into",
"// a simple array ['key', 'alias1', 'alias2']",
"Object",
".",
"keys",
"(",
"aliases",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"aliasArrays",
".",
"push",
"(",
"[",
"]",
".",
"concat",
"(",
"aliases",
"[",
"key",
"]",
",",
"key",
")",
")",
"}",
")",
"// combine arrays until zero changes are",
"// made in an iteration.",
"while",
"(",
"change",
")",
"{",
"change",
"=",
"false",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"aliasArrays",
".",
"length",
";",
"i",
"++",
")",
"{",
"for",
"(",
"var",
"ii",
"=",
"i",
"+",
"1",
";",
"ii",
"<",
"aliasArrays",
".",
"length",
";",
"ii",
"++",
")",
"{",
"var",
"intersect",
"=",
"aliasArrays",
"[",
"i",
"]",
".",
"filter",
"(",
"function",
"(",
"v",
")",
"{",
"return",
"aliasArrays",
"[",
"ii",
"]",
".",
"indexOf",
"(",
"v",
")",
"!==",
"-",
"1",
"}",
")",
"if",
"(",
"intersect",
".",
"length",
")",
"{",
"aliasArrays",
"[",
"i",
"]",
"=",
"aliasArrays",
"[",
"i",
"]",
".",
"concat",
"(",
"aliasArrays",
"[",
"ii",
"]",
")",
"aliasArrays",
".",
"splice",
"(",
"ii",
",",
"1",
")",
"change",
"=",
"true",
"break",
"}",
"}",
"}",
"}",
"// map arrays back to the hash-lookup (de-dupe while",
"// we're at it).",
"aliasArrays",
".",
"forEach",
"(",
"function",
"(",
"aliasArray",
")",
"{",
"aliasArray",
"=",
"aliasArray",
".",
"filter",
"(",
"function",
"(",
"v",
",",
"i",
",",
"self",
")",
"{",
"return",
"self",
".",
"indexOf",
"(",
"v",
")",
"===",
"i",
"}",
")",
"combined",
"[",
"aliasArray",
".",
"pop",
"(",
")",
"]",
"=",
"aliasArray",
"}",
")",
"return",
"combined",
"}"
] |
if any aliases reference each other, we should merge them together.
|
[
"if",
"any",
"aliases",
"reference",
"each",
"other",
"we",
"should",
"merge",
"them",
"together",
"."
] |
981e1512d15a0af757a74a9cd75c448259aa8efa
|
https://github.com/yargs/yargs-parser/blob/981e1512d15a0af757a74a9cd75c448259aa8efa/index.js#L831-L874
|
12,955
|
jaredhanson/passport-oauth2
|
lib/strategy.js
|
OAuth2Strategy
|
function OAuth2Strategy(options, verify) {
if (typeof options == 'function') {
verify = options;
options = undefined;
}
options = options || {};
if (!verify) { throw new TypeError('OAuth2Strategy requires a verify callback'); }
if (!options.authorizationURL) { throw new TypeError('OAuth2Strategy requires a authorizationURL option'); }
if (!options.tokenURL) { throw new TypeError('OAuth2Strategy requires a tokenURL option'); }
if (!options.clientID) { throw new TypeError('OAuth2Strategy requires a clientID option'); }
passport.Strategy.call(this);
this.name = 'oauth2';
this._verify = verify;
// NOTE: The _oauth2 property is considered "protected". Subclasses are
// allowed to use it when making protected resource requests to retrieve
// the user profile.
this._oauth2 = new OAuth2(options.clientID, options.clientSecret,
'', options.authorizationURL, options.tokenURL, options.customHeaders);
this._callbackURL = options.callbackURL;
this._scope = options.scope;
this._scopeSeparator = options.scopeSeparator || ' ';
this._pkceMethod = (options.pkce === true) ? 'S256' : options.pkce;
this._key = options.sessionKey || ('oauth2:' + url.parse(options.authorizationURL).hostname);
if (options.store) {
this._stateStore = options.store;
} else {
if (options.state) {
this._stateStore = options.pkce ? new PKCESessionStateStore({ key: this._key }) : new SessionStateStore({ key: this._key });
} else {
if (options.pkce) { throw new TypeError('OAuth2Strategy requires `state: true` option when PKCE is enabled'); }
this._stateStore = new NullStateStore();
}
}
this._trustProxy = options.proxy;
this._passReqToCallback = options.passReqToCallback;
this._skipUserProfile = (options.skipUserProfile === undefined) ? false : options.skipUserProfile;
}
|
javascript
|
function OAuth2Strategy(options, verify) {
if (typeof options == 'function') {
verify = options;
options = undefined;
}
options = options || {};
if (!verify) { throw new TypeError('OAuth2Strategy requires a verify callback'); }
if (!options.authorizationURL) { throw new TypeError('OAuth2Strategy requires a authorizationURL option'); }
if (!options.tokenURL) { throw new TypeError('OAuth2Strategy requires a tokenURL option'); }
if (!options.clientID) { throw new TypeError('OAuth2Strategy requires a clientID option'); }
passport.Strategy.call(this);
this.name = 'oauth2';
this._verify = verify;
// NOTE: The _oauth2 property is considered "protected". Subclasses are
// allowed to use it when making protected resource requests to retrieve
// the user profile.
this._oauth2 = new OAuth2(options.clientID, options.clientSecret,
'', options.authorizationURL, options.tokenURL, options.customHeaders);
this._callbackURL = options.callbackURL;
this._scope = options.scope;
this._scopeSeparator = options.scopeSeparator || ' ';
this._pkceMethod = (options.pkce === true) ? 'S256' : options.pkce;
this._key = options.sessionKey || ('oauth2:' + url.parse(options.authorizationURL).hostname);
if (options.store) {
this._stateStore = options.store;
} else {
if (options.state) {
this._stateStore = options.pkce ? new PKCESessionStateStore({ key: this._key }) : new SessionStateStore({ key: this._key });
} else {
if (options.pkce) { throw new TypeError('OAuth2Strategy requires `state: true` option when PKCE is enabled'); }
this._stateStore = new NullStateStore();
}
}
this._trustProxy = options.proxy;
this._passReqToCallback = options.passReqToCallback;
this._skipUserProfile = (options.skipUserProfile === undefined) ? false : options.skipUserProfile;
}
|
[
"function",
"OAuth2Strategy",
"(",
"options",
",",
"verify",
")",
"{",
"if",
"(",
"typeof",
"options",
"==",
"'function'",
")",
"{",
"verify",
"=",
"options",
";",
"options",
"=",
"undefined",
";",
"}",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"if",
"(",
"!",
"verify",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'OAuth2Strategy requires a verify callback'",
")",
";",
"}",
"if",
"(",
"!",
"options",
".",
"authorizationURL",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'OAuth2Strategy requires a authorizationURL option'",
")",
";",
"}",
"if",
"(",
"!",
"options",
".",
"tokenURL",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'OAuth2Strategy requires a tokenURL option'",
")",
";",
"}",
"if",
"(",
"!",
"options",
".",
"clientID",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'OAuth2Strategy requires a clientID option'",
")",
";",
"}",
"passport",
".",
"Strategy",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"name",
"=",
"'oauth2'",
";",
"this",
".",
"_verify",
"=",
"verify",
";",
"// NOTE: The _oauth2 property is considered \"protected\". Subclasses are",
"// allowed to use it when making protected resource requests to retrieve",
"// the user profile.",
"this",
".",
"_oauth2",
"=",
"new",
"OAuth2",
"(",
"options",
".",
"clientID",
",",
"options",
".",
"clientSecret",
",",
"''",
",",
"options",
".",
"authorizationURL",
",",
"options",
".",
"tokenURL",
",",
"options",
".",
"customHeaders",
")",
";",
"this",
".",
"_callbackURL",
"=",
"options",
".",
"callbackURL",
";",
"this",
".",
"_scope",
"=",
"options",
".",
"scope",
";",
"this",
".",
"_scopeSeparator",
"=",
"options",
".",
"scopeSeparator",
"||",
"' '",
";",
"this",
".",
"_pkceMethod",
"=",
"(",
"options",
".",
"pkce",
"===",
"true",
")",
"?",
"'S256'",
":",
"options",
".",
"pkce",
";",
"this",
".",
"_key",
"=",
"options",
".",
"sessionKey",
"||",
"(",
"'oauth2:'",
"+",
"url",
".",
"parse",
"(",
"options",
".",
"authorizationURL",
")",
".",
"hostname",
")",
";",
"if",
"(",
"options",
".",
"store",
")",
"{",
"this",
".",
"_stateStore",
"=",
"options",
".",
"store",
";",
"}",
"else",
"{",
"if",
"(",
"options",
".",
"state",
")",
"{",
"this",
".",
"_stateStore",
"=",
"options",
".",
"pkce",
"?",
"new",
"PKCESessionStateStore",
"(",
"{",
"key",
":",
"this",
".",
"_key",
"}",
")",
":",
"new",
"SessionStateStore",
"(",
"{",
"key",
":",
"this",
".",
"_key",
"}",
")",
";",
"}",
"else",
"{",
"if",
"(",
"options",
".",
"pkce",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'OAuth2Strategy requires `state: true` option when PKCE is enabled'",
")",
";",
"}",
"this",
".",
"_stateStore",
"=",
"new",
"NullStateStore",
"(",
")",
";",
"}",
"}",
"this",
".",
"_trustProxy",
"=",
"options",
".",
"proxy",
";",
"this",
".",
"_passReqToCallback",
"=",
"options",
".",
"passReqToCallback",
";",
"this",
".",
"_skipUserProfile",
"=",
"(",
"options",
".",
"skipUserProfile",
"===",
"undefined",
")",
"?",
"false",
":",
"options",
".",
"skipUserProfile",
";",
"}"
] |
Creates an instance of `OAuth2Strategy`.
The OAuth 2.0 authentication strategy authenticates requests using the OAuth
2.0 framework.
OAuth 2.0 provides a facility for delegated authentication, whereby users can
authenticate using a third-party service such as Facebook. Delegating in
this manner involves a sequence of events, including redirecting the user to
the third-party service for authorization. Once authorization has been
granted, the user is redirected back to the application and an authorization
code can be used to obtain credentials.
Applications must supply a `verify` callback, for which the function
signature is:
function(accessToken, refreshToken, profile, done) { ... }
The verify callback is responsible for finding or creating the user, and
invoking `done` with the following arguments:
done(err, user, info);
`user` should be set to `false` to indicate an authentication failure.
Additional `info` can optionally be passed as a third argument, typically
used to display informational messages. If an exception occured, `err`
should be set.
Options:
- `authorizationURL` URL used to obtain an authorization grant
- `tokenURL` URL used to obtain an access token
- `clientID` identifies client to service provider
- `clientSecret` secret used to establish ownership of the client identifer
- `callbackURL` URL to which the service provider will redirect the user after obtaining authorization
- `passReqToCallback` when `true`, `req` is the first argument to the verify callback (default: `false`)
Examples:
passport.use(new OAuth2Strategy({
authorizationURL: 'https://www.example.com/oauth2/authorize',
tokenURL: 'https://www.example.com/oauth2/token',
clientID: '123-456-789',
clientSecret: 'shhh-its-a-secret'
callbackURL: 'https://www.example.net/auth/example/callback'
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate(..., function (err, user) {
done(err, user);
});
}
));
@constructor
@param {Object} options
@param {Function} verify
@api public
|
[
"Creates",
"an",
"instance",
"of",
"OAuth2Strategy",
"."
] |
b938a915e45832971ead5d7252f7ae51eb5d6b27
|
https://github.com/jaredhanson/passport-oauth2/blob/b938a915e45832971ead5d7252f7ae51eb5d6b27/lib/strategy.js#L76-L117
|
12,956
|
moleculerjs/moleculer-web
|
src/utils.js
|
composeThen
|
function composeThen(req, res, ...mws) {
return new Promise((resolve, reject) => {
compose(...mws)(req, res, err => {
if (err) {
/* istanbul ignore next */
if (err instanceof MoleculerError)
return reject(err);
/* istanbul ignore next */
if (err instanceof Error)
return reject(new MoleculerError(err.message, err.code || err.status, err.type)); // TODO err.stack
/* istanbul ignore next */
return reject(new MoleculerError(err));
}
resolve();
});
});
}
|
javascript
|
function composeThen(req, res, ...mws) {
return new Promise((resolve, reject) => {
compose(...mws)(req, res, err => {
if (err) {
/* istanbul ignore next */
if (err instanceof MoleculerError)
return reject(err);
/* istanbul ignore next */
if (err instanceof Error)
return reject(new MoleculerError(err.message, err.code || err.status, err.type)); // TODO err.stack
/* istanbul ignore next */
return reject(new MoleculerError(err));
}
resolve();
});
});
}
|
[
"function",
"composeThen",
"(",
"req",
",",
"res",
",",
"...",
"mws",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"compose",
"(",
"...",
"mws",
")",
"(",
"req",
",",
"res",
",",
"err",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"/* istanbul ignore next */",
"if",
"(",
"err",
"instanceof",
"MoleculerError",
")",
"return",
"reject",
"(",
"err",
")",
";",
"/* istanbul ignore next */",
"if",
"(",
"err",
"instanceof",
"Error",
")",
"return",
"reject",
"(",
"new",
"MoleculerError",
"(",
"err",
".",
"message",
",",
"err",
".",
"code",
"||",
"err",
".",
"status",
",",
"err",
".",
"type",
")",
")",
";",
"// TODO err.stack",
"/* istanbul ignore next */",
"return",
"reject",
"(",
"new",
"MoleculerError",
"(",
"err",
")",
")",
";",
"}",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Compose middlewares and return Promise
@param {...Function} mws
@returns {Promise}
|
[
"Compose",
"middlewares",
"and",
"return",
"Promise"
] |
3843c39ee2c17625a101c5df8ab92030c4c7f86f
|
https://github.com/moleculerjs/moleculer-web/blob/3843c39ee2c17625a101c5df8ab92030c4c7f86f/src/utils.js#L82-L101
|
12,957
|
moleculerjs/moleculer-web
|
src/utils.js
|
generateETag
|
function generateETag(body, opt) {
if (_.isFunction(opt))
return opt.call(this, body);
let buf = !Buffer.isBuffer(body)
? Buffer.from(body)
: body;
return etag(buf, (opt === true || opt === "weak") ? { weak: true } : null);
}
|
javascript
|
function generateETag(body, opt) {
if (_.isFunction(opt))
return opt.call(this, body);
let buf = !Buffer.isBuffer(body)
? Buffer.from(body)
: body;
return etag(buf, (opt === true || opt === "weak") ? { weak: true } : null);
}
|
[
"function",
"generateETag",
"(",
"body",
",",
"opt",
")",
"{",
"if",
"(",
"_",
".",
"isFunction",
"(",
"opt",
")",
")",
"return",
"opt",
".",
"call",
"(",
"this",
",",
"body",
")",
";",
"let",
"buf",
"=",
"!",
"Buffer",
".",
"isBuffer",
"(",
"body",
")",
"?",
"Buffer",
".",
"from",
"(",
"body",
")",
":",
"body",
";",
"return",
"etag",
"(",
"buf",
",",
"(",
"opt",
"===",
"true",
"||",
"opt",
"===",
"\"weak\"",
")",
"?",
"{",
"weak",
":",
"true",
"}",
":",
"null",
")",
";",
"}"
] |
Generate ETag from content.
@param {any} body
@param {Boolean|String|Function?} opt
@returns {String}
|
[
"Generate",
"ETag",
"from",
"content",
"."
] |
3843c39ee2c17625a101c5df8ab92030c4c7f86f
|
https://github.com/moleculerjs/moleculer-web/blob/3843c39ee2c17625a101c5df8ab92030c4c7f86f/src/utils.js#L111-L120
|
12,958
|
moleculerjs/moleculer-web
|
src/utils.js
|
isFresh
|
function isFresh(req, res) {
if ((res.statusCode >= 200 && res.statusCode < 300) || 304 === res.statusCode) {
return fresh(req.headers, {
"etag": res.getHeader("ETag"),
"last-modified": res.getHeader("Last-Modified")
});
}
return false;
}
|
javascript
|
function isFresh(req, res) {
if ((res.statusCode >= 200 && res.statusCode < 300) || 304 === res.statusCode) {
return fresh(req.headers, {
"etag": res.getHeader("ETag"),
"last-modified": res.getHeader("Last-Modified")
});
}
return false;
}
|
[
"function",
"isFresh",
"(",
"req",
",",
"res",
")",
"{",
"if",
"(",
"(",
"res",
".",
"statusCode",
">=",
"200",
"&&",
"res",
".",
"statusCode",
"<",
"300",
")",
"||",
"304",
"===",
"res",
".",
"statusCode",
")",
"{",
"return",
"fresh",
"(",
"req",
".",
"headers",
",",
"{",
"\"etag\"",
":",
"res",
".",
"getHeader",
"(",
"\"ETag\"",
")",
",",
"\"last-modified\"",
":",
"res",
".",
"getHeader",
"(",
"\"Last-Modified\"",
")",
"}",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
Check the data freshness.
@param {*} req
@param {*} res
@returns {Boolean}
|
[
"Check",
"the",
"data",
"freshness",
"."
] |
3843c39ee2c17625a101c5df8ab92030c4c7f86f
|
https://github.com/moleculerjs/moleculer-web/blob/3843c39ee2c17625a101c5df8ab92030c4c7f86f/src/utils.js#L130-L138
|
12,959
|
biati-digital/glightbox
|
dist/js/glightbox.js
|
addClass
|
function addClass(node, name) {
if (hasClass(node, name)) {
return;
}
if (node.classList) {
node.classList.add(name);
} else {
node.className += " " + name;
}
}
|
javascript
|
function addClass(node, name) {
if (hasClass(node, name)) {
return;
}
if (node.classList) {
node.classList.add(name);
} else {
node.className += " " + name;
}
}
|
[
"function",
"addClass",
"(",
"node",
",",
"name",
")",
"{",
"if",
"(",
"hasClass",
"(",
"node",
",",
"name",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"node",
".",
"classList",
")",
"{",
"node",
".",
"classList",
".",
"add",
"(",
"name",
")",
";",
"}",
"else",
"{",
"node",
".",
"className",
"+=",
"\" \"",
"+",
"name",
";",
"}",
"}"
] |
Add element class
@param {node} element
@param {string} class name
|
[
"Add",
"element",
"class"
] |
49a0136d6faef64fc2e667fa90caf3a3bd444564
|
https://github.com/biati-digital/glightbox/blob/49a0136d6faef64fc2e667fa90caf3a3bd444564/dist/js/glightbox.js#L358-L367
|
12,960
|
biati-digital/glightbox
|
dist/js/glightbox.js
|
removeClass
|
function removeClass(node, name) {
var c = name.split(' ');
if (c.length > 1) {
each(c, function (cl) {
removeClass(node, cl);
});
return;
}
if (node.classList) {
node.classList.remove(name);
} else {
node.className = node.className.replace(name, "");
}
}
|
javascript
|
function removeClass(node, name) {
var c = name.split(' ');
if (c.length > 1) {
each(c, function (cl) {
removeClass(node, cl);
});
return;
}
if (node.classList) {
node.classList.remove(name);
} else {
node.className = node.className.replace(name, "");
}
}
|
[
"function",
"removeClass",
"(",
"node",
",",
"name",
")",
"{",
"var",
"c",
"=",
"name",
".",
"split",
"(",
"' '",
")",
";",
"if",
"(",
"c",
".",
"length",
">",
"1",
")",
"{",
"each",
"(",
"c",
",",
"function",
"(",
"cl",
")",
"{",
"removeClass",
"(",
"node",
",",
"cl",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"if",
"(",
"node",
".",
"classList",
")",
"{",
"node",
".",
"classList",
".",
"remove",
"(",
"name",
")",
";",
"}",
"else",
"{",
"node",
".",
"className",
"=",
"node",
".",
"className",
".",
"replace",
"(",
"name",
",",
"\"\"",
")",
";",
"}",
"}"
] |
Remove element class
@param {node} element
@param {string} class name
|
[
"Remove",
"element",
"class"
] |
49a0136d6faef64fc2e667fa90caf3a3bd444564
|
https://github.com/biati-digital/glightbox/blob/49a0136d6faef64fc2e667fa90caf3a3bd444564/dist/js/glightbox.js#L375-L388
|
12,961
|
biati-digital/glightbox
|
dist/js/glightbox.js
|
createHTML
|
function createHTML(htmlStr) {
var frag = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
|
javascript
|
function createHTML(htmlStr) {
var frag = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
|
[
"function",
"createHTML",
"(",
"htmlStr",
")",
"{",
"var",
"frag",
"=",
"document",
".",
"createDocumentFragment",
"(",
")",
",",
"temp",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"temp",
".",
"innerHTML",
"=",
"htmlStr",
";",
"while",
"(",
"temp",
".",
"firstChild",
")",
"{",
"frag",
".",
"appendChild",
"(",
"temp",
".",
"firstChild",
")",
";",
"}",
"return",
"frag",
";",
"}"
] |
Create a document fragment
@param {string} html code
|
[
"Create",
"a",
"document",
"fragment"
] |
49a0136d6faef64fc2e667fa90caf3a3bd444564
|
https://github.com/biati-digital/glightbox/blob/49a0136d6faef64fc2e667fa90caf3a3bd444564/dist/js/glightbox.js#L480-L488
|
12,962
|
biati-digital/glightbox
|
dist/js/glightbox.js
|
getClosest
|
function getClosest(elem, selector) {
while (elem !== document.body) {
elem = elem.parentElement;
var matches = typeof elem.matches == 'function' ? elem.matches(selector) : elem.msMatchesSelector(selector);
if (matches) return elem;
}
}
|
javascript
|
function getClosest(elem, selector) {
while (elem !== document.body) {
elem = elem.parentElement;
var matches = typeof elem.matches == 'function' ? elem.matches(selector) : elem.msMatchesSelector(selector);
if (matches) return elem;
}
}
|
[
"function",
"getClosest",
"(",
"elem",
",",
"selector",
")",
"{",
"while",
"(",
"elem",
"!==",
"document",
".",
"body",
")",
"{",
"elem",
"=",
"elem",
".",
"parentElement",
";",
"var",
"matches",
"=",
"typeof",
"elem",
".",
"matches",
"==",
"'function'",
"?",
"elem",
".",
"matches",
"(",
"selector",
")",
":",
"elem",
".",
"msMatchesSelector",
"(",
"selector",
")",
";",
"if",
"(",
"matches",
")",
"return",
"elem",
";",
"}",
"}"
] |
Get the closestElement
@param {node} element
@param {string} class name
|
[
"Get",
"the",
"closestElement"
] |
49a0136d6faef64fc2e667fa90caf3a3bd444564
|
https://github.com/biati-digital/glightbox/blob/49a0136d6faef64fc2e667fa90caf3a3bd444564/dist/js/glightbox.js#L496-L503
|
12,963
|
biati-digital/glightbox
|
dist/js/glightbox.js
|
youtubeApiHandle
|
function youtubeApiHandle() {
for (var i = 0; i < YTTemp.length; i++) {
var iframe = YTTemp[i];
var player = new YT.Player(iframe);
videoPlayers[iframe.id] = player;
}
}
|
javascript
|
function youtubeApiHandle() {
for (var i = 0; i < YTTemp.length; i++) {
var iframe = YTTemp[i];
var player = new YT.Player(iframe);
videoPlayers[iframe.id] = player;
}
}
|
[
"function",
"youtubeApiHandle",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"YTTemp",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"iframe",
"=",
"YTTemp",
"[",
"i",
"]",
";",
"var",
"player",
"=",
"new",
"YT",
".",
"Player",
"(",
"iframe",
")",
";",
"videoPlayers",
"[",
"iframe",
".",
"id",
"]",
"=",
"player",
";",
"}",
"}"
] |
Handle youtube Api
This is a simple fix, when the video
is ready sometimes the youtube api is still
loading so we can not autoplay or pause
we need to listen onYouTubeIframeAPIReady and
register the videos if required
|
[
"Handle",
"youtube",
"Api",
"This",
"is",
"a",
"simple",
"fix",
"when",
"the",
"video",
"is",
"ready",
"sometimes",
"the",
"youtube",
"api",
"is",
"still",
"loading",
"so",
"we",
"can",
"not",
"autoplay",
"or",
"pause",
"we",
"need",
"to",
"listen",
"onYouTubeIframeAPIReady",
"and",
"register",
"the",
"videos",
"if",
"required"
] |
49a0136d6faef64fc2e667fa90caf3a3bd444564
|
https://github.com/biati-digital/glightbox/blob/49a0136d6faef64fc2e667fa90caf3a3bd444564/dist/js/glightbox.js#L988-L994
|
12,964
|
biati-digital/glightbox
|
dist/js/glightbox.js
|
waitUntil
|
function waitUntil(check, onComplete, delay, timeout) {
if (check()) {
onComplete();
return;
}
if (!delay) delay = 100;
var timeoutPointer = void 0;
var intervalPointer = setInterval(function () {
if (!check()) return;
clearInterval(intervalPointer);
if (timeoutPointer) clearTimeout(timeoutPointer);
onComplete();
}, delay);
if (timeout) timeoutPointer = setTimeout(function () {
clearInterval(intervalPointer);
}, timeout);
}
|
javascript
|
function waitUntil(check, onComplete, delay, timeout) {
if (check()) {
onComplete();
return;
}
if (!delay) delay = 100;
var timeoutPointer = void 0;
var intervalPointer = setInterval(function () {
if (!check()) return;
clearInterval(intervalPointer);
if (timeoutPointer) clearTimeout(timeoutPointer);
onComplete();
}, delay);
if (timeout) timeoutPointer = setTimeout(function () {
clearInterval(intervalPointer);
}, timeout);
}
|
[
"function",
"waitUntil",
"(",
"check",
",",
"onComplete",
",",
"delay",
",",
"timeout",
")",
"{",
"if",
"(",
"check",
"(",
")",
")",
"{",
"onComplete",
"(",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"delay",
")",
"delay",
"=",
"100",
";",
"var",
"timeoutPointer",
"=",
"void",
"0",
";",
"var",
"intervalPointer",
"=",
"setInterval",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"check",
"(",
")",
")",
"return",
";",
"clearInterval",
"(",
"intervalPointer",
")",
";",
"if",
"(",
"timeoutPointer",
")",
"clearTimeout",
"(",
"timeoutPointer",
")",
";",
"onComplete",
"(",
")",
";",
"}",
",",
"delay",
")",
";",
"if",
"(",
"timeout",
")",
"timeoutPointer",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"clearInterval",
"(",
"intervalPointer",
")",
";",
"}",
",",
"timeout",
")",
";",
"}"
] |
Wait until
wait until all the validations
are passed
@param {function} check
@param {function} onComplete
@param {numeric} delay
@param {numeric} timeout
|
[
"Wait",
"until",
"wait",
"until",
"all",
"the",
"validations",
"are",
"passed"
] |
49a0136d6faef64fc2e667fa90caf3a3bd444564
|
https://github.com/biati-digital/glightbox/blob/49a0136d6faef64fc2e667fa90caf3a3bd444564/dist/js/glightbox.js#L1014-L1031
|
12,965
|
biati-digital/glightbox
|
dist/js/glightbox.js
|
setInlineContent
|
function setInlineContent(slide, data, callback) {
var slideMedia = slide.querySelector('.gslide-media');
var hash = data.href.split('#').pop().trim();
var div = document.getElementById(hash);
if (!div) {
return false;
}
var cloned = div.cloneNode(true);
cloned.style.height = data.height + 'px';
cloned.style.maxWidth = data.width + 'px';
addClass(cloned, 'ginlined-content');
slideMedia.appendChild(cloned);
if (utils.isFunction(callback)) {
callback();
}
return;
}
|
javascript
|
function setInlineContent(slide, data, callback) {
var slideMedia = slide.querySelector('.gslide-media');
var hash = data.href.split('#').pop().trim();
var div = document.getElementById(hash);
if (!div) {
return false;
}
var cloned = div.cloneNode(true);
cloned.style.height = data.height + 'px';
cloned.style.maxWidth = data.width + 'px';
addClass(cloned, 'ginlined-content');
slideMedia.appendChild(cloned);
if (utils.isFunction(callback)) {
callback();
}
return;
}
|
[
"function",
"setInlineContent",
"(",
"slide",
",",
"data",
",",
"callback",
")",
"{",
"var",
"slideMedia",
"=",
"slide",
".",
"querySelector",
"(",
"'.gslide-media'",
")",
";",
"var",
"hash",
"=",
"data",
".",
"href",
".",
"split",
"(",
"'#'",
")",
".",
"pop",
"(",
")",
".",
"trim",
"(",
")",
";",
"var",
"div",
"=",
"document",
".",
"getElementById",
"(",
"hash",
")",
";",
"if",
"(",
"!",
"div",
")",
"{",
"return",
"false",
";",
"}",
"var",
"cloned",
"=",
"div",
".",
"cloneNode",
"(",
"true",
")",
";",
"cloned",
".",
"style",
".",
"height",
"=",
"data",
".",
"height",
"+",
"'px'",
";",
"cloned",
".",
"style",
".",
"maxWidth",
"=",
"data",
".",
"width",
"+",
"'px'",
";",
"addClass",
"(",
"cloned",
",",
"'ginlined-content'",
")",
";",
"slideMedia",
".",
"appendChild",
"(",
"cloned",
")",
";",
"if",
"(",
"utils",
".",
"isFunction",
"(",
"callback",
")",
")",
"{",
"callback",
"(",
")",
";",
"}",
"return",
";",
"}"
] |
Set slide inline content
we'll extend this to make http
requests using the fetch api
but for now we keep it simple
@param {node} slide
@param {object} data
@param {function} callback
|
[
"Set",
"slide",
"inline",
"content",
"we",
"ll",
"extend",
"this",
"to",
"make",
"http",
"requests",
"using",
"the",
"fetch",
"api",
"but",
"for",
"now",
"we",
"keep",
"it",
"simple"
] |
49a0136d6faef64fc2e667fa90caf3a3bd444564
|
https://github.com/biati-digital/glightbox/blob/49a0136d6faef64fc2e667fa90caf3a3bd444564/dist/js/glightbox.js#L1063-L1083
|
12,966
|
biati-digital/glightbox
|
dist/js/glightbox.js
|
getSourceType
|
function getSourceType(url) {
var origin = url;
url = url.toLowerCase();
if (url.match(/\.(jpeg|jpg|gif|png|apn|webp|svg)$/) !== null) {
return 'image';
}
if (url.match(/(youtube\.com|youtube-nocookie\.com)\/watch\?v=([a-zA-Z0-9\-_]+)/) || url.match(/youtu\.be\/([a-zA-Z0-9\-_]+)/)) {
return 'video';
}
if (url.match(/vimeo\.com\/([0-9]*)/)) {
return 'video';
}
if (url.match(/\.(mp4|ogg|webm)$/) !== null) {
return 'video';
}
// Check if inline content
if (url.indexOf("#") > -1) {
var hash = origin.split('#').pop();
if (hash.trim() !== '') {
return 'inline';
}
}
// Ajax
if (url.includes("gajax=true")) {
return 'ajax';
}
return 'external';
}
|
javascript
|
function getSourceType(url) {
var origin = url;
url = url.toLowerCase();
if (url.match(/\.(jpeg|jpg|gif|png|apn|webp|svg)$/) !== null) {
return 'image';
}
if (url.match(/(youtube\.com|youtube-nocookie\.com)\/watch\?v=([a-zA-Z0-9\-_]+)/) || url.match(/youtu\.be\/([a-zA-Z0-9\-_]+)/)) {
return 'video';
}
if (url.match(/vimeo\.com\/([0-9]*)/)) {
return 'video';
}
if (url.match(/\.(mp4|ogg|webm)$/) !== null) {
return 'video';
}
// Check if inline content
if (url.indexOf("#") > -1) {
var hash = origin.split('#').pop();
if (hash.trim() !== '') {
return 'inline';
}
}
// Ajax
if (url.includes("gajax=true")) {
return 'ajax';
}
return 'external';
}
|
[
"function",
"getSourceType",
"(",
"url",
")",
"{",
"var",
"origin",
"=",
"url",
";",
"url",
"=",
"url",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"url",
".",
"match",
"(",
"/",
"\\.(jpeg|jpg|gif|png|apn|webp|svg)$",
"/",
")",
"!==",
"null",
")",
"{",
"return",
"'image'",
";",
"}",
"if",
"(",
"url",
".",
"match",
"(",
"/",
"(youtube\\.com|youtube-nocookie\\.com)\\/watch\\?v=([a-zA-Z0-9\\-_]+)",
"/",
")",
"||",
"url",
".",
"match",
"(",
"/",
"youtu\\.be\\/([a-zA-Z0-9\\-_]+)",
"/",
")",
")",
"{",
"return",
"'video'",
";",
"}",
"if",
"(",
"url",
".",
"match",
"(",
"/",
"vimeo\\.com\\/([0-9]*)",
"/",
")",
")",
"{",
"return",
"'video'",
";",
"}",
"if",
"(",
"url",
".",
"match",
"(",
"/",
"\\.(mp4|ogg|webm)$",
"/",
")",
"!==",
"null",
")",
"{",
"return",
"'video'",
";",
"}",
"// Check if inline content",
"if",
"(",
"url",
".",
"indexOf",
"(",
"\"#\"",
")",
">",
"-",
"1",
")",
"{",
"var",
"hash",
"=",
"origin",
".",
"split",
"(",
"'#'",
")",
".",
"pop",
"(",
")",
";",
"if",
"(",
"hash",
".",
"trim",
"(",
")",
"!==",
"''",
")",
"{",
"return",
"'inline'",
";",
"}",
"}",
"// Ajax",
"if",
"(",
"url",
".",
"includes",
"(",
"\"gajax=true\"",
")",
")",
"{",
"return",
"'ajax'",
";",
"}",
"return",
"'external'",
";",
"}"
] |
Get source type
gte the source type of a url
@param {string} url
|
[
"Get",
"source",
"type",
"gte",
"the",
"source",
"type",
"of",
"a",
"url"
] |
49a0136d6faef64fc2e667fa90caf3a3bd444564
|
https://github.com/biati-digital/glightbox/blob/49a0136d6faef64fc2e667fa90caf3a3bd444564/dist/js/glightbox.js#L1091-L1121
|
12,967
|
biati-digital/glightbox
|
dist/js/glightbox.js
|
keyboardNavigation
|
function keyboardNavigation() {
var _this3 = this;
if (this.events.hasOwnProperty('keyboard')) {
return false;
}
this.events['keyboard'] = addEvent('keydown', {
onElement: window,
withCallback: function withCallback(event, target) {
event = event || window.event;
var key = event.keyCode;
if (key == 39) _this3.nextSlide();
if (key == 37) _this3.prevSlide();
if (key == 27) _this3.close();
}
});
}
|
javascript
|
function keyboardNavigation() {
var _this3 = this;
if (this.events.hasOwnProperty('keyboard')) {
return false;
}
this.events['keyboard'] = addEvent('keydown', {
onElement: window,
withCallback: function withCallback(event, target) {
event = event || window.event;
var key = event.keyCode;
if (key == 39) _this3.nextSlide();
if (key == 37) _this3.prevSlide();
if (key == 27) _this3.close();
}
});
}
|
[
"function",
"keyboardNavigation",
"(",
")",
"{",
"var",
"_this3",
"=",
"this",
";",
"if",
"(",
"this",
".",
"events",
".",
"hasOwnProperty",
"(",
"'keyboard'",
")",
")",
"{",
"return",
"false",
";",
"}",
"this",
".",
"events",
"[",
"'keyboard'",
"]",
"=",
"addEvent",
"(",
"'keydown'",
",",
"{",
"onElement",
":",
"window",
",",
"withCallback",
":",
"function",
"withCallback",
"(",
"event",
",",
"target",
")",
"{",
"event",
"=",
"event",
"||",
"window",
".",
"event",
";",
"var",
"key",
"=",
"event",
".",
"keyCode",
";",
"if",
"(",
"key",
"==",
"39",
")",
"_this3",
".",
"nextSlide",
"(",
")",
";",
"if",
"(",
"key",
"==",
"37",
")",
"_this3",
".",
"prevSlide",
"(",
")",
";",
"if",
"(",
"key",
"==",
"27",
")",
"_this3",
".",
"close",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Desktop keyboard navigation
|
[
"Desktop",
"keyboard",
"navigation"
] |
49a0136d6faef64fc2e667fa90caf3a3bd444564
|
https://github.com/biati-digital/glightbox/blob/49a0136d6faef64fc2e667fa90caf3a3bd444564/dist/js/glightbox.js#L1126-L1142
|
12,968
|
biati-digital/glightbox
|
src/js/glightbox.js
|
getNodeEvents
|
function getNodeEvents(node, name = null, fn = null) {
const cache = (node[uid] = node[uid] || []);
const data = { all: cache, evt: null, found: null};
if (name && fn && utils.size(cache) > 0) {
each(cache, (cl, i) => {
if (cl.eventName == name && cl.fn.toString() == fn.toString()) {
data.found = true;
data.evt = i;
return false;
}
})
}
return data;
}
|
javascript
|
function getNodeEvents(node, name = null, fn = null) {
const cache = (node[uid] = node[uid] || []);
const data = { all: cache, evt: null, found: null};
if (name && fn && utils.size(cache) > 0) {
each(cache, (cl, i) => {
if (cl.eventName == name && cl.fn.toString() == fn.toString()) {
data.found = true;
data.evt = i;
return false;
}
})
}
return data;
}
|
[
"function",
"getNodeEvents",
"(",
"node",
",",
"name",
"=",
"null",
",",
"fn",
"=",
"null",
")",
"{",
"const",
"cache",
"=",
"(",
"node",
"[",
"uid",
"]",
"=",
"node",
"[",
"uid",
"]",
"||",
"[",
"]",
")",
";",
"const",
"data",
"=",
"{",
"all",
":",
"cache",
",",
"evt",
":",
"null",
",",
"found",
":",
"null",
"}",
";",
"if",
"(",
"name",
"&&",
"fn",
"&&",
"utils",
".",
"size",
"(",
"cache",
")",
">",
"0",
")",
"{",
"each",
"(",
"cache",
",",
"(",
"cl",
",",
"i",
")",
"=>",
"{",
"if",
"(",
"cl",
".",
"eventName",
"==",
"name",
"&&",
"cl",
".",
"fn",
".",
"toString",
"(",
")",
"==",
"fn",
".",
"toString",
"(",
")",
")",
"{",
"data",
".",
"found",
"=",
"true",
";",
"data",
".",
"evt",
"=",
"i",
";",
"return",
"false",
";",
"}",
"}",
")",
"}",
"return",
"data",
";",
"}"
] |
Get nde events
return node events and optionally
check if the node has already a specific event
to avoid duplicated callbacks
@param {node} node
@param {string} name event name
@param {object} fn callback
@returns {object}
|
[
"Get",
"nde",
"events",
"return",
"node",
"events",
"and",
"optionally",
"check",
"if",
"the",
"node",
"has",
"already",
"a",
"specific",
"event",
"to",
"avoid",
"duplicated",
"callbacks"
] |
49a0136d6faef64fc2e667fa90caf3a3bd444564
|
https://github.com/biati-digital/glightbox/blob/49a0136d6faef64fc2e667fa90caf3a3bd444564/src/js/glightbox.js#L243-L256
|
12,969
|
biati-digital/glightbox
|
src/js/glightbox.js
|
addEvent
|
function addEvent(eventName, {
onElement,
withCallback,
avoidDuplicate = true,
once = false,
useCapture = false} = { }, thisArg) {
let element = onElement || []
if (utils.isString(element)) {
element = document.querySelectorAll(element)
}
function handler(event) {
if (utils.isFunction(withCallback)) {
withCallback.call(thisArg, event, this)
}
if (once) {
handler.destroy();
}
}
handler.destroy = function() {
each(element, (el) => {
const events = getNodeEvents(el, eventName, handler);
if (events.found) { events.all.splice(events.evt, 1); }
if (el.removeEventListener) el.removeEventListener(eventName, handler, useCapture)
})
}
each(element, (el) => {
const events = getNodeEvents(el, eventName, handler);
if (el.addEventListener && (avoidDuplicate && !events.found) || !avoidDuplicate) {
el.addEventListener(eventName, handler, useCapture)
events.all.push({ eventName: eventName, fn: handler});
}
})
return handler
}
|
javascript
|
function addEvent(eventName, {
onElement,
withCallback,
avoidDuplicate = true,
once = false,
useCapture = false} = { }, thisArg) {
let element = onElement || []
if (utils.isString(element)) {
element = document.querySelectorAll(element)
}
function handler(event) {
if (utils.isFunction(withCallback)) {
withCallback.call(thisArg, event, this)
}
if (once) {
handler.destroy();
}
}
handler.destroy = function() {
each(element, (el) => {
const events = getNodeEvents(el, eventName, handler);
if (events.found) { events.all.splice(events.evt, 1); }
if (el.removeEventListener) el.removeEventListener(eventName, handler, useCapture)
})
}
each(element, (el) => {
const events = getNodeEvents(el, eventName, handler);
if (el.addEventListener && (avoidDuplicate && !events.found) || !avoidDuplicate) {
el.addEventListener(eventName, handler, useCapture)
events.all.push({ eventName: eventName, fn: handler});
}
})
return handler
}
|
[
"function",
"addEvent",
"(",
"eventName",
",",
"{",
"onElement",
",",
"withCallback",
",",
"avoidDuplicate",
"=",
"true",
",",
"once",
"=",
"false",
",",
"useCapture",
"=",
"false",
"}",
"=",
"{",
"}",
",",
"thisArg",
")",
"{",
"let",
"element",
"=",
"onElement",
"||",
"[",
"]",
"if",
"(",
"utils",
".",
"isString",
"(",
"element",
")",
")",
"{",
"element",
"=",
"document",
".",
"querySelectorAll",
"(",
"element",
")",
"}",
"function",
"handler",
"(",
"event",
")",
"{",
"if",
"(",
"utils",
".",
"isFunction",
"(",
"withCallback",
")",
")",
"{",
"withCallback",
".",
"call",
"(",
"thisArg",
",",
"event",
",",
"this",
")",
"}",
"if",
"(",
"once",
")",
"{",
"handler",
".",
"destroy",
"(",
")",
";",
"}",
"}",
"handler",
".",
"destroy",
"=",
"function",
"(",
")",
"{",
"each",
"(",
"element",
",",
"(",
"el",
")",
"=>",
"{",
"const",
"events",
"=",
"getNodeEvents",
"(",
"el",
",",
"eventName",
",",
"handler",
")",
";",
"if",
"(",
"events",
".",
"found",
")",
"{",
"events",
".",
"all",
".",
"splice",
"(",
"events",
".",
"evt",
",",
"1",
")",
";",
"}",
"if",
"(",
"el",
".",
"removeEventListener",
")",
"el",
".",
"removeEventListener",
"(",
"eventName",
",",
"handler",
",",
"useCapture",
")",
"}",
")",
"}",
"each",
"(",
"element",
",",
"(",
"el",
")",
"=>",
"{",
"const",
"events",
"=",
"getNodeEvents",
"(",
"el",
",",
"eventName",
",",
"handler",
")",
";",
"if",
"(",
"el",
".",
"addEventListener",
"&&",
"(",
"avoidDuplicate",
"&&",
"!",
"events",
".",
"found",
")",
"||",
"!",
"avoidDuplicate",
")",
"{",
"el",
".",
"addEventListener",
"(",
"eventName",
",",
"handler",
",",
"useCapture",
")",
"events",
".",
"all",
".",
"push",
"(",
"{",
"eventName",
":",
"eventName",
",",
"fn",
":",
"handler",
"}",
")",
";",
"}",
"}",
")",
"return",
"handler",
"}"
] |
Add Event
Add an event listener
@param {string} eventName
@param {object} detials
|
[
"Add",
"Event",
"Add",
"an",
"event",
"listener"
] |
49a0136d6faef64fc2e667fa90caf3a3bd444564
|
https://github.com/biati-digital/glightbox/blob/49a0136d6faef64fc2e667fa90caf3a3bd444564/src/js/glightbox.js#L266-L299
|
12,970
|
biati-digital/glightbox
|
src/js/glightbox.js
|
whichTransitionEvent
|
function whichTransitionEvent() {
let t,
el = document.createElement("fakeelement");
const transitions = {
transition: "transitionend",
OTransition: "oTransitionEnd",
MozTransition: "transitionend",
WebkitTransition: "webkitTransitionEnd"
};
for (t in transitions) {
if (el.style[t] !== undefined) {
return transitions[t];
}
}
}
|
javascript
|
function whichTransitionEvent() {
let t,
el = document.createElement("fakeelement");
const transitions = {
transition: "transitionend",
OTransition: "oTransitionEnd",
MozTransition: "transitionend",
WebkitTransition: "webkitTransitionEnd"
};
for (t in transitions) {
if (el.style[t] !== undefined) {
return transitions[t];
}
}
}
|
[
"function",
"whichTransitionEvent",
"(",
")",
"{",
"let",
"t",
",",
"el",
"=",
"document",
".",
"createElement",
"(",
"\"fakeelement\"",
")",
";",
"const",
"transitions",
"=",
"{",
"transition",
":",
"\"transitionend\"",
",",
"OTransition",
":",
"\"oTransitionEnd\"",
",",
"MozTransition",
":",
"\"transitionend\"",
",",
"WebkitTransition",
":",
"\"webkitTransitionEnd\"",
"}",
";",
"for",
"(",
"t",
"in",
"transitions",
")",
"{",
"if",
"(",
"el",
".",
"style",
"[",
"t",
"]",
"!==",
"undefined",
")",
"{",
"return",
"transitions",
"[",
"t",
"]",
";",
"}",
"}",
"}"
] |
Determine transition events
|
[
"Determine",
"transition",
"events"
] |
49a0136d6faef64fc2e667fa90caf3a3bd444564
|
https://github.com/biati-digital/glightbox/blob/49a0136d6faef64fc2e667fa90caf3a3bd444564/src/js/glightbox.js#L372-L388
|
12,971
|
biati-digital/glightbox
|
src/js/glightbox.js
|
getSlideData
|
function getSlideData(element = null, settings) {
let data = {
href: '',
title: '',
type: '',
description: '',
descPosition: 'bottom',
effect: '',
node: element
};
if (utils.isObject(element) && !utils.isNode(element)){
return extend(data, element);
}
let url = '';
let config = element.getAttribute('data-glightbox')
let nodeType = element.nodeName.toLowerCase();
if (nodeType === 'a')
url = element.href;
if (nodeType === 'img')
url = element.src;
data.href = url;
each(data, (val, key) => {
if (utils.has(settings, key)) {
data[key] = settings[key];
}
const nodeData = element.dataset[key];
if (!utils.isNil(nodeData)) {
data[key] = nodeData;
}
});
if (!data.type) {
data.type = getSourceType(url);
}
if (!utils.isNil(config)) {
let cleanKeys = [];
each(data, (v, k) => {
cleanKeys.push(';\\s?' + k);
})
cleanKeys = cleanKeys.join('\\s?:|');
if (config.trim() !== '') {
each(data, (val, key) => {
const str = config;
const match = '\s?' + key + '\s?:\s?(.*?)(' + cleanKeys + '\s?:|$)';
const regex = new RegExp(match);
const matches = str.match(regex);
if (matches && matches.length && matches[1]) {
const value = matches[1].trim().replace(/;\s*$/, '');
data[key] = value;
}
});
}
} else {
if (nodeType == 'a') {
let title = element.title
if (!utils.isNil(title) && title !== '') data.title = title;
}
if (nodeType == 'img') {
let alt = element.alt
if (!utils.isNil(alt) && alt !== '') data.title = alt;
}
let desc = element.getAttribute('data-description')
if (!utils.isNil(desc) && desc !== '') data.description = desc;
}
let nodeDesc = element.querySelector('.glightbox-desc')
if (nodeDesc) {
data.description = nodeDesc.innerHTML;
}
const defaultWith = (data.type == 'video' ? settings.videosWidth : settings.width);
const defaultHeight = (data.type == 'video' ? settings.videosHeight : settings.height);
data.width = (utils.has(data, 'width') ? data.width : defaultWith);
data.height = (utils.has(data, 'height') ? data.height : defaultHeight);
return data;
}
|
javascript
|
function getSlideData(element = null, settings) {
let data = {
href: '',
title: '',
type: '',
description: '',
descPosition: 'bottom',
effect: '',
node: element
};
if (utils.isObject(element) && !utils.isNode(element)){
return extend(data, element);
}
let url = '';
let config = element.getAttribute('data-glightbox')
let nodeType = element.nodeName.toLowerCase();
if (nodeType === 'a')
url = element.href;
if (nodeType === 'img')
url = element.src;
data.href = url;
each(data, (val, key) => {
if (utils.has(settings, key)) {
data[key] = settings[key];
}
const nodeData = element.dataset[key];
if (!utils.isNil(nodeData)) {
data[key] = nodeData;
}
});
if (!data.type) {
data.type = getSourceType(url);
}
if (!utils.isNil(config)) {
let cleanKeys = [];
each(data, (v, k) => {
cleanKeys.push(';\\s?' + k);
})
cleanKeys = cleanKeys.join('\\s?:|');
if (config.trim() !== '') {
each(data, (val, key) => {
const str = config;
const match = '\s?' + key + '\s?:\s?(.*?)(' + cleanKeys + '\s?:|$)';
const regex = new RegExp(match);
const matches = str.match(regex);
if (matches && matches.length && matches[1]) {
const value = matches[1].trim().replace(/;\s*$/, '');
data[key] = value;
}
});
}
} else {
if (nodeType == 'a') {
let title = element.title
if (!utils.isNil(title) && title !== '') data.title = title;
}
if (nodeType == 'img') {
let alt = element.alt
if (!utils.isNil(alt) && alt !== '') data.title = alt;
}
let desc = element.getAttribute('data-description')
if (!utils.isNil(desc) && desc !== '') data.description = desc;
}
let nodeDesc = element.querySelector('.glightbox-desc')
if (nodeDesc) {
data.description = nodeDesc.innerHTML;
}
const defaultWith = (data.type == 'video' ? settings.videosWidth : settings.width);
const defaultHeight = (data.type == 'video' ? settings.videosHeight : settings.height);
data.width = (utils.has(data, 'width') ? data.width : defaultWith);
data.height = (utils.has(data, 'height') ? data.height : defaultHeight);
return data;
}
|
[
"function",
"getSlideData",
"(",
"element",
"=",
"null",
",",
"settings",
")",
"{",
"let",
"data",
"=",
"{",
"href",
":",
"''",
",",
"title",
":",
"''",
",",
"type",
":",
"''",
",",
"description",
":",
"''",
",",
"descPosition",
":",
"'bottom'",
",",
"effect",
":",
"''",
",",
"node",
":",
"element",
"}",
";",
"if",
"(",
"utils",
".",
"isObject",
"(",
"element",
")",
"&&",
"!",
"utils",
".",
"isNode",
"(",
"element",
")",
")",
"{",
"return",
"extend",
"(",
"data",
",",
"element",
")",
";",
"}",
"let",
"url",
"=",
"''",
";",
"let",
"config",
"=",
"element",
".",
"getAttribute",
"(",
"'data-glightbox'",
")",
"let",
"nodeType",
"=",
"element",
".",
"nodeName",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"nodeType",
"===",
"'a'",
")",
"url",
"=",
"element",
".",
"href",
";",
"if",
"(",
"nodeType",
"===",
"'img'",
")",
"url",
"=",
"element",
".",
"src",
";",
"data",
".",
"href",
"=",
"url",
";",
"each",
"(",
"data",
",",
"(",
"val",
",",
"key",
")",
"=>",
"{",
"if",
"(",
"utils",
".",
"has",
"(",
"settings",
",",
"key",
")",
")",
"{",
"data",
"[",
"key",
"]",
"=",
"settings",
"[",
"key",
"]",
";",
"}",
"const",
"nodeData",
"=",
"element",
".",
"dataset",
"[",
"key",
"]",
";",
"if",
"(",
"!",
"utils",
".",
"isNil",
"(",
"nodeData",
")",
")",
"{",
"data",
"[",
"key",
"]",
"=",
"nodeData",
";",
"}",
"}",
")",
";",
"if",
"(",
"!",
"data",
".",
"type",
")",
"{",
"data",
".",
"type",
"=",
"getSourceType",
"(",
"url",
")",
";",
"}",
"if",
"(",
"!",
"utils",
".",
"isNil",
"(",
"config",
")",
")",
"{",
"let",
"cleanKeys",
"=",
"[",
"]",
";",
"each",
"(",
"data",
",",
"(",
"v",
",",
"k",
")",
"=>",
"{",
"cleanKeys",
".",
"push",
"(",
"';\\\\s?'",
"+",
"k",
")",
";",
"}",
")",
"cleanKeys",
"=",
"cleanKeys",
".",
"join",
"(",
"'\\\\s?:|'",
")",
";",
"if",
"(",
"config",
".",
"trim",
"(",
")",
"!==",
"''",
")",
"{",
"each",
"(",
"data",
",",
"(",
"val",
",",
"key",
")",
"=>",
"{",
"const",
"str",
"=",
"config",
";",
"const",
"match",
"=",
"'\\s?'",
"+",
"key",
"+",
"'\\s?:\\s?(.*?)('",
"+",
"cleanKeys",
"+",
"'\\s?:|$)'",
";",
"const",
"regex",
"=",
"new",
"RegExp",
"(",
"match",
")",
";",
"const",
"matches",
"=",
"str",
".",
"match",
"(",
"regex",
")",
";",
"if",
"(",
"matches",
"&&",
"matches",
".",
"length",
"&&",
"matches",
"[",
"1",
"]",
")",
"{",
"const",
"value",
"=",
"matches",
"[",
"1",
"]",
".",
"trim",
"(",
")",
".",
"replace",
"(",
"/",
";\\s*$",
"/",
",",
"''",
")",
";",
"data",
"[",
"key",
"]",
"=",
"value",
";",
"}",
"}",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"nodeType",
"==",
"'a'",
")",
"{",
"let",
"title",
"=",
"element",
".",
"title",
"if",
"(",
"!",
"utils",
".",
"isNil",
"(",
"title",
")",
"&&",
"title",
"!==",
"''",
")",
"data",
".",
"title",
"=",
"title",
";",
"}",
"if",
"(",
"nodeType",
"==",
"'img'",
")",
"{",
"let",
"alt",
"=",
"element",
".",
"alt",
"if",
"(",
"!",
"utils",
".",
"isNil",
"(",
"alt",
")",
"&&",
"alt",
"!==",
"''",
")",
"data",
".",
"title",
"=",
"alt",
";",
"}",
"let",
"desc",
"=",
"element",
".",
"getAttribute",
"(",
"'data-description'",
")",
"if",
"(",
"!",
"utils",
".",
"isNil",
"(",
"desc",
")",
"&&",
"desc",
"!==",
"''",
")",
"data",
".",
"description",
"=",
"desc",
";",
"}",
"let",
"nodeDesc",
"=",
"element",
".",
"querySelector",
"(",
"'.glightbox-desc'",
")",
"if",
"(",
"nodeDesc",
")",
"{",
"data",
".",
"description",
"=",
"nodeDesc",
".",
"innerHTML",
";",
"}",
"const",
"defaultWith",
"=",
"(",
"data",
".",
"type",
"==",
"'video'",
"?",
"settings",
".",
"videosWidth",
":",
"settings",
".",
"width",
")",
";",
"const",
"defaultHeight",
"=",
"(",
"data",
".",
"type",
"==",
"'video'",
"?",
"settings",
".",
"videosHeight",
":",
"settings",
".",
"height",
")",
";",
"data",
".",
"width",
"=",
"(",
"utils",
".",
"has",
"(",
"data",
",",
"'width'",
")",
"?",
"data",
".",
"width",
":",
"defaultWith",
")",
";",
"data",
".",
"height",
"=",
"(",
"utils",
".",
"has",
"(",
"data",
",",
"'height'",
")",
"?",
"data",
".",
"height",
":",
"defaultHeight",
")",
";",
"return",
"data",
";",
"}"
] |
Get slide data
@param {node} element
|
[
"Get",
"slide",
"data"
] |
49a0136d6faef64fc2e667fa90caf3a3bd444564
|
https://github.com/biati-digital/glightbox/blob/49a0136d6faef64fc2e667fa90caf3a3bd444564/src/js/glightbox.js#L479-L561
|
12,972
|
biati-digital/glightbox
|
src/js/glightbox.js
|
createIframe
|
function createIframe(config) {
let { url, width, height, allow, callback, appendTo } = config;
let iframe = document.createElement('iframe');
let winWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
iframe.className = 'vimeo-video gvideo';
iframe.src = url;
if (height) {
if (isMobile && winWidth < 767) {
iframe.style.height = ''
} else {
iframe.style.height = `${height}px`
}
}
if (width) {
iframe.style.width = `${width}px`
}
if (allow) {
iframe.setAttribute('allow', allow)
}
iframe.onload = function() {
addClass(iframe, 'iframe-ready');
if (utils.isFunction(callback)) {
callback()
}
};
if (appendTo) {
appendTo.appendChild(iframe);
}
return iframe;
}
|
javascript
|
function createIframe(config) {
let { url, width, height, allow, callback, appendTo } = config;
let iframe = document.createElement('iframe');
let winWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
iframe.className = 'vimeo-video gvideo';
iframe.src = url;
if (height) {
if (isMobile && winWidth < 767) {
iframe.style.height = ''
} else {
iframe.style.height = `${height}px`
}
}
if (width) {
iframe.style.width = `${width}px`
}
if (allow) {
iframe.setAttribute('allow', allow)
}
iframe.onload = function() {
addClass(iframe, 'iframe-ready');
if (utils.isFunction(callback)) {
callback()
}
};
if (appendTo) {
appendTo.appendChild(iframe);
}
return iframe;
}
|
[
"function",
"createIframe",
"(",
"config",
")",
"{",
"let",
"{",
"url",
",",
"width",
",",
"height",
",",
"allow",
",",
"callback",
",",
"appendTo",
"}",
"=",
"config",
";",
"let",
"iframe",
"=",
"document",
".",
"createElement",
"(",
"'iframe'",
")",
";",
"let",
"winWidth",
"=",
"window",
".",
"innerWidth",
"||",
"document",
".",
"documentElement",
".",
"clientWidth",
"||",
"document",
".",
"body",
".",
"clientWidth",
";",
"iframe",
".",
"className",
"=",
"'vimeo-video gvideo'",
";",
"iframe",
".",
"src",
"=",
"url",
";",
"if",
"(",
"height",
")",
"{",
"if",
"(",
"isMobile",
"&&",
"winWidth",
"<",
"767",
")",
"{",
"iframe",
".",
"style",
".",
"height",
"=",
"''",
"}",
"else",
"{",
"iframe",
".",
"style",
".",
"height",
"=",
"`",
"${",
"height",
"}",
"`",
"}",
"}",
"if",
"(",
"width",
")",
"{",
"iframe",
".",
"style",
".",
"width",
"=",
"`",
"${",
"width",
"}",
"`",
"}",
"if",
"(",
"allow",
")",
"{",
"iframe",
".",
"setAttribute",
"(",
"'allow'",
",",
"allow",
")",
"}",
"iframe",
".",
"onload",
"=",
"function",
"(",
")",
"{",
"addClass",
"(",
"iframe",
",",
"'iframe-ready'",
")",
";",
"if",
"(",
"utils",
".",
"isFunction",
"(",
"callback",
")",
")",
"{",
"callback",
"(",
")",
"}",
"}",
";",
"if",
"(",
"appendTo",
")",
"{",
"appendTo",
".",
"appendChild",
"(",
"iframe",
")",
";",
"}",
"return",
"iframe",
";",
"}"
] |
Create an iframe element
@param {string} url
@param {numeric} width
@param {numeric} height
@param {function} callback
|
[
"Create",
"an",
"iframe",
"element"
] |
49a0136d6faef64fc2e667fa90caf3a3bd444564
|
https://github.com/biati-digital/glightbox/blob/49a0136d6faef64fc2e667fa90caf3a3bd444564/src/js/glightbox.js#L843-L874
|
12,973
|
biati-digital/glightbox
|
src/js/glightbox.js
|
getYoutubeID
|
function getYoutubeID(url) {
let videoID = '';
url = url.replace(/(>|<)/gi, '').split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
if (url[2] !== undefined) {
videoID = url[2].split(/[^0-9a-z_\-]/i);
videoID = videoID[0];
} else {
videoID = url;
}
return videoID;
}
|
javascript
|
function getYoutubeID(url) {
let videoID = '';
url = url.replace(/(>|<)/gi, '').split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
if (url[2] !== undefined) {
videoID = url[2].split(/[^0-9a-z_\-]/i);
videoID = videoID[0];
} else {
videoID = url;
}
return videoID;
}
|
[
"function",
"getYoutubeID",
"(",
"url",
")",
"{",
"let",
"videoID",
"=",
"''",
";",
"url",
"=",
"url",
".",
"replace",
"(",
"/",
"(>|<)",
"/",
"gi",
",",
"''",
")",
".",
"split",
"(",
"/",
"(vi\\/|v=|\\/v\\/|youtu\\.be\\/|\\/embed\\/)",
"/",
")",
";",
"if",
"(",
"url",
"[",
"2",
"]",
"!==",
"undefined",
")",
"{",
"videoID",
"=",
"url",
"[",
"2",
"]",
".",
"split",
"(",
"/",
"[^0-9a-z_\\-]",
"/",
"i",
")",
";",
"videoID",
"=",
"videoID",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"videoID",
"=",
"url",
";",
"}",
"return",
"videoID",
";",
"}"
] |
Get youtube ID
@param {string} url
@returns {string} video id
|
[
"Get",
"youtube",
"ID"
] |
49a0136d6faef64fc2e667fa90caf3a3bd444564
|
https://github.com/biati-digital/glightbox/blob/49a0136d6faef64fc2e667fa90caf3a3bd444564/src/js/glightbox.js#L886-L896
|
12,974
|
biati-digital/glightbox
|
src/js/glightbox.js
|
injectVideoApi
|
function injectVideoApi(url, callback) {
if (utils.isNil(url)) {
console.error('Inject videos api error');
return;
}
let found = document.querySelectorAll('script[src="' + url + '"]')
if (utils.isNil(found) || found.length == 0) {
let script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onload = () => {
if (utils.isFunction(callback)) callback();
};
document.body.appendChild(script);
return false;
}
if (utils.isFunction(callback)) callback();
}
|
javascript
|
function injectVideoApi(url, callback) {
if (utils.isNil(url)) {
console.error('Inject videos api error');
return;
}
let found = document.querySelectorAll('script[src="' + url + '"]')
if (utils.isNil(found) || found.length == 0) {
let script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onload = () => {
if (utils.isFunction(callback)) callback();
};
document.body.appendChild(script);
return false;
}
if (utils.isFunction(callback)) callback();
}
|
[
"function",
"injectVideoApi",
"(",
"url",
",",
"callback",
")",
"{",
"if",
"(",
"utils",
".",
"isNil",
"(",
"url",
")",
")",
"{",
"console",
".",
"error",
"(",
"'Inject videos api error'",
")",
";",
"return",
";",
"}",
"let",
"found",
"=",
"document",
".",
"querySelectorAll",
"(",
"'script[src=\"'",
"+",
"url",
"+",
"'\"]'",
")",
"if",
"(",
"utils",
".",
"isNil",
"(",
"found",
")",
"||",
"found",
".",
"length",
"==",
"0",
")",
"{",
"let",
"script",
"=",
"document",
".",
"createElement",
"(",
"'script'",
")",
";",
"script",
".",
"type",
"=",
"'text/javascript'",
";",
"script",
".",
"src",
"=",
"url",
";",
"script",
".",
"onload",
"=",
"(",
")",
"=>",
"{",
"if",
"(",
"utils",
".",
"isFunction",
"(",
"callback",
")",
")",
"callback",
"(",
")",
";",
"}",
";",
"document",
".",
"body",
".",
"appendChild",
"(",
"script",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"utils",
".",
"isFunction",
"(",
"callback",
")",
")",
"callback",
"(",
")",
";",
"}"
] |
Inject videos api
used for youtube, vimeo and jwplayer
@param {string} url
@param {function} callback
|
[
"Inject",
"videos",
"api",
"used",
"for",
"youtube",
"vimeo",
"and",
"jwplayer"
] |
49a0136d6faef64fc2e667fa90caf3a3bd444564
|
https://github.com/biati-digital/glightbox/blob/49a0136d6faef64fc2e667fa90caf3a3bd444564/src/js/glightbox.js#L906-L923
|
12,975
|
biati-digital/glightbox
|
src/js/glightbox.js
|
parseUrlParams
|
function parseUrlParams(params) {
let qs = '';
let i = 0;
each(params, (val, key) => {
if (i > 0) {
qs += '&';
}
qs += key + '=' + val;
i += 1;
})
return qs;
}
|
javascript
|
function parseUrlParams(params) {
let qs = '';
let i = 0;
each(params, (val, key) => {
if (i > 0) {
qs += '&';
}
qs += key + '=' + val;
i += 1;
})
return qs;
}
|
[
"function",
"parseUrlParams",
"(",
"params",
")",
"{",
"let",
"qs",
"=",
"''",
";",
"let",
"i",
"=",
"0",
";",
"each",
"(",
"params",
",",
"(",
"val",
",",
"key",
")",
"=>",
"{",
"if",
"(",
"i",
">",
"0",
")",
"{",
"qs",
"+=",
"'&'",
";",
"}",
"qs",
"+=",
"key",
"+",
"'='",
"+",
"val",
";",
"i",
"+=",
"1",
";",
"}",
")",
"return",
"qs",
";",
"}"
] |
Parse url params
convert an object in to a
url query string parameters
@param {object} params
|
[
"Parse",
"url",
"params",
"convert",
"an",
"object",
"in",
"to",
"a",
"url",
"query",
"string",
"parameters"
] |
49a0136d6faef64fc2e667fa90caf3a3bd444564
|
https://github.com/biati-digital/glightbox/blob/49a0136d6faef64fc2e667fa90caf3a3bd444564/src/js/glightbox.js#L988-L999
|
12,976
|
redux-orm/redux-orm
|
src/Model.js
|
getByIdQuery
|
function getByIdQuery(modelInstance) {
const modelClass = modelInstance.getClass();
const { idAttribute, modelName } = modelClass;
return {
table: modelName,
clauses: [
{
type: FILTER,
payload: {
[idAttribute]: modelInstance.getId(),
},
},
],
};
}
|
javascript
|
function getByIdQuery(modelInstance) {
const modelClass = modelInstance.getClass();
const { idAttribute, modelName } = modelClass;
return {
table: modelName,
clauses: [
{
type: FILTER,
payload: {
[idAttribute]: modelInstance.getId(),
},
},
],
};
}
|
[
"function",
"getByIdQuery",
"(",
"modelInstance",
")",
"{",
"const",
"modelClass",
"=",
"modelInstance",
".",
"getClass",
"(",
")",
";",
"const",
"{",
"idAttribute",
",",
"modelName",
"}",
"=",
"modelClass",
";",
"return",
"{",
"table",
":",
"modelName",
",",
"clauses",
":",
"[",
"{",
"type",
":",
"FILTER",
",",
"payload",
":",
"{",
"[",
"idAttribute",
"]",
":",
"modelInstance",
".",
"getId",
"(",
")",
",",
"}",
",",
"}",
",",
"]",
",",
"}",
";",
"}"
] |
Generates a query specification to get the instance's
corresponding table row using its primary key.
@private
@returns {Object}
|
[
"Generates",
"a",
"query",
"specification",
"to",
"get",
"the",
"instance",
"s",
"corresponding",
"table",
"row",
"using",
"its",
"primary",
"key",
"."
] |
e6077dbfe7da47284ad6c22b1217967017959a7f
|
https://github.com/redux-orm/redux-orm/blob/e6077dbfe7da47284ad6c22b1217967017959a7f/src/Model.js#L28-L43
|
12,977
|
redux-orm/redux-orm
|
src/descriptors.js
|
attrDescriptor
|
function attrDescriptor(fieldName) {
return {
get() {
return this._fields[fieldName];
},
set(value) {
return this.set(fieldName, value);
},
enumerable: true,
configurable: true,
};
}
|
javascript
|
function attrDescriptor(fieldName) {
return {
get() {
return this._fields[fieldName];
},
set(value) {
return this.set(fieldName, value);
},
enumerable: true,
configurable: true,
};
}
|
[
"function",
"attrDescriptor",
"(",
"fieldName",
")",
"{",
"return",
"{",
"get",
"(",
")",
"{",
"return",
"this",
".",
"_fields",
"[",
"fieldName",
"]",
";",
"}",
",",
"set",
"(",
"value",
")",
"{",
"return",
"this",
".",
"set",
"(",
"fieldName",
",",
"value",
")",
";",
"}",
",",
"enumerable",
":",
"true",
",",
"configurable",
":",
"true",
",",
"}",
";",
"}"
] |
The functions in this file return custom JS property descriptors
that are supposed to be assigned to Model fields.
Some include the logic to look up models using foreign keys and
to add or remove relationships between models.
@module descriptors
Defines a basic non-key attribute.
@param {string} fieldName - the name of the field the descriptor will be assigned to.
|
[
"The",
"functions",
"in",
"this",
"file",
"return",
"custom",
"JS",
"property",
"descriptors",
"that",
"are",
"supposed",
"to",
"be",
"assigned",
"to",
"Model",
"fields",
"."
] |
e6077dbfe7da47284ad6c22b1217967017959a7f
|
https://github.com/redux-orm/redux-orm/blob/e6077dbfe7da47284ad6c22b1217967017959a7f/src/descriptors.js#L19-L32
|
12,978
|
redux-orm/redux-orm
|
src/descriptors.js
|
manyToManyDescriptor
|
function manyToManyDescriptor(
declaredFromModelName,
declaredToModelName,
throughModelName,
throughFields,
reverse
) {
return {
get() {
const {
session: {
[declaredFromModelName]: DeclaredFromModel,
[declaredToModelName]: DeclaredToModel,
[throughModelName]: ThroughModel,
},
} = this.getClass();
const ThisModel = reverse
? DeclaredToModel
: DeclaredFromModel;
const OtherModel = reverse
? DeclaredFromModel
: DeclaredToModel;
const thisReferencingField = reverse
? throughFields.to
: throughFields.from;
const otherReferencingField = reverse
? throughFields.from
: throughFields.to;
const thisId = this.getId();
const throughQs = ThroughModel.filter({
[thisReferencingField]: thisId,
});
/**
* all IDs of instances of the other model that are
* referenced by any instance of the current model
*/
const referencedOtherIds = new Set(
throughQs
.toRefArray()
.map(obj => obj[otherReferencingField])
);
/**
* selects all instances of other model that are referenced
* by any instance of the current model
*/
const qs = OtherModel.filter(otherModelInstance => (
referencedOtherIds.has(
otherModelInstance[OtherModel.idAttribute]
)
));
/**
* Allows adding OtherModel instances to be referenced by the current instance.
*
* E.g. Book.first().authors.add(1, 2) would add the authors with IDs 1 and 2
* to the first book's list of referenced authors.
*
* @return undefined
*/
qs.add = function add(...entities) {
const idsToAdd = new Set(
entities.map(normalizeEntity)
);
const existingQs = throughQs.filter(through => (
idsToAdd.has(through[otherReferencingField])
));
if (existingQs.exists()) {
const existingIds = existingQs
.toRefArray()
.map(through => through[otherReferencingField]);
throw new Error(`Tried to add already existing ${OtherModel.modelName} id(s) ${existingIds} to the ${ThisModel.modelName} instance with id ${thisId}`);
}
idsToAdd.forEach((id) => {
ThroughModel.create({
[otherReferencingField]: id,
[thisReferencingField]: thisId,
});
});
};
/**
* Removes references to all OtherModel instances from the current model.
*
* E.g. Book.first().authors.clear() would cause the first book's list
* of referenced authors to become empty.
*
* @return undefined
*/
qs.clear = function clear() {
throughQs.delete();
};
/**
* Removes references to all passed OtherModel instances from the current model.
*
* E.g. Book.first().authors.remove(1, 2) would cause the authors with
* IDs 1 and 2 to no longer be referenced by the first book.
*
* @return undefined
*/
qs.remove = function remove(...entities) {
const idsToRemove = new Set(
entities.map(normalizeEntity)
);
const entitiesToDelete = throughQs.filter(
through => idsToRemove.has(through[otherReferencingField])
);
if (entitiesToDelete.count() !== idsToRemove.size) {
// Tried deleting non-existing entities.
const entitiesToDeleteIds = entitiesToDelete
.toRefArray()
.map(through => through[otherReferencingField]);
const unexistingIds = [...idsToRemove].filter(
id => !entitiesToDeleteIds.includes(id)
);
throw new Error(`Tried to delete non-existing ${OtherModel.modelName} id(s) ${unexistingIds} from the ${ThisModel.modelName} instance with id ${thisId}`);
}
entitiesToDelete.delete();
};
return qs;
},
set() {
throw new Error('Tried setting a M2M field. Please use the related QuerySet methods add, remove and clear.');
},
};
}
|
javascript
|
function manyToManyDescriptor(
declaredFromModelName,
declaredToModelName,
throughModelName,
throughFields,
reverse
) {
return {
get() {
const {
session: {
[declaredFromModelName]: DeclaredFromModel,
[declaredToModelName]: DeclaredToModel,
[throughModelName]: ThroughModel,
},
} = this.getClass();
const ThisModel = reverse
? DeclaredToModel
: DeclaredFromModel;
const OtherModel = reverse
? DeclaredFromModel
: DeclaredToModel;
const thisReferencingField = reverse
? throughFields.to
: throughFields.from;
const otherReferencingField = reverse
? throughFields.from
: throughFields.to;
const thisId = this.getId();
const throughQs = ThroughModel.filter({
[thisReferencingField]: thisId,
});
/**
* all IDs of instances of the other model that are
* referenced by any instance of the current model
*/
const referencedOtherIds = new Set(
throughQs
.toRefArray()
.map(obj => obj[otherReferencingField])
);
/**
* selects all instances of other model that are referenced
* by any instance of the current model
*/
const qs = OtherModel.filter(otherModelInstance => (
referencedOtherIds.has(
otherModelInstance[OtherModel.idAttribute]
)
));
/**
* Allows adding OtherModel instances to be referenced by the current instance.
*
* E.g. Book.first().authors.add(1, 2) would add the authors with IDs 1 and 2
* to the first book's list of referenced authors.
*
* @return undefined
*/
qs.add = function add(...entities) {
const idsToAdd = new Set(
entities.map(normalizeEntity)
);
const existingQs = throughQs.filter(through => (
idsToAdd.has(through[otherReferencingField])
));
if (existingQs.exists()) {
const existingIds = existingQs
.toRefArray()
.map(through => through[otherReferencingField]);
throw new Error(`Tried to add already existing ${OtherModel.modelName} id(s) ${existingIds} to the ${ThisModel.modelName} instance with id ${thisId}`);
}
idsToAdd.forEach((id) => {
ThroughModel.create({
[otherReferencingField]: id,
[thisReferencingField]: thisId,
});
});
};
/**
* Removes references to all OtherModel instances from the current model.
*
* E.g. Book.first().authors.clear() would cause the first book's list
* of referenced authors to become empty.
*
* @return undefined
*/
qs.clear = function clear() {
throughQs.delete();
};
/**
* Removes references to all passed OtherModel instances from the current model.
*
* E.g. Book.first().authors.remove(1, 2) would cause the authors with
* IDs 1 and 2 to no longer be referenced by the first book.
*
* @return undefined
*/
qs.remove = function remove(...entities) {
const idsToRemove = new Set(
entities.map(normalizeEntity)
);
const entitiesToDelete = throughQs.filter(
through => idsToRemove.has(through[otherReferencingField])
);
if (entitiesToDelete.count() !== idsToRemove.size) {
// Tried deleting non-existing entities.
const entitiesToDeleteIds = entitiesToDelete
.toRefArray()
.map(through => through[otherReferencingField]);
const unexistingIds = [...idsToRemove].filter(
id => !entitiesToDeleteIds.includes(id)
);
throw new Error(`Tried to delete non-existing ${OtherModel.modelName} id(s) ${unexistingIds} from the ${ThisModel.modelName} instance with id ${thisId}`);
}
entitiesToDelete.delete();
};
return qs;
},
set() {
throw new Error('Tried setting a M2M field. Please use the related QuerySet methods add, remove and clear.');
},
};
}
|
[
"function",
"manyToManyDescriptor",
"(",
"declaredFromModelName",
",",
"declaredToModelName",
",",
"throughModelName",
",",
"throughFields",
",",
"reverse",
")",
"{",
"return",
"{",
"get",
"(",
")",
"{",
"const",
"{",
"session",
":",
"{",
"[",
"declaredFromModelName",
"]",
":",
"DeclaredFromModel",
",",
"[",
"declaredToModelName",
"]",
":",
"DeclaredToModel",
",",
"[",
"throughModelName",
"]",
":",
"ThroughModel",
",",
"}",
",",
"}",
"=",
"this",
".",
"getClass",
"(",
")",
";",
"const",
"ThisModel",
"=",
"reverse",
"?",
"DeclaredToModel",
":",
"DeclaredFromModel",
";",
"const",
"OtherModel",
"=",
"reverse",
"?",
"DeclaredFromModel",
":",
"DeclaredToModel",
";",
"const",
"thisReferencingField",
"=",
"reverse",
"?",
"throughFields",
".",
"to",
":",
"throughFields",
".",
"from",
";",
"const",
"otherReferencingField",
"=",
"reverse",
"?",
"throughFields",
".",
"from",
":",
"throughFields",
".",
"to",
";",
"const",
"thisId",
"=",
"this",
".",
"getId",
"(",
")",
";",
"const",
"throughQs",
"=",
"ThroughModel",
".",
"filter",
"(",
"{",
"[",
"thisReferencingField",
"]",
":",
"thisId",
",",
"}",
")",
";",
"/**\n * all IDs of instances of the other model that are\n * referenced by any instance of the current model\n */",
"const",
"referencedOtherIds",
"=",
"new",
"Set",
"(",
"throughQs",
".",
"toRefArray",
"(",
")",
".",
"map",
"(",
"obj",
"=>",
"obj",
"[",
"otherReferencingField",
"]",
")",
")",
";",
"/**\n * selects all instances of other model that are referenced\n * by any instance of the current model\n */",
"const",
"qs",
"=",
"OtherModel",
".",
"filter",
"(",
"otherModelInstance",
"=>",
"(",
"referencedOtherIds",
".",
"has",
"(",
"otherModelInstance",
"[",
"OtherModel",
".",
"idAttribute",
"]",
")",
")",
")",
";",
"/**\n * Allows adding OtherModel instances to be referenced by the current instance.\n *\n * E.g. Book.first().authors.add(1, 2) would add the authors with IDs 1 and 2\n * to the first book's list of referenced authors.\n *\n * @return undefined\n */",
"qs",
".",
"add",
"=",
"function",
"add",
"(",
"...",
"entities",
")",
"{",
"const",
"idsToAdd",
"=",
"new",
"Set",
"(",
"entities",
".",
"map",
"(",
"normalizeEntity",
")",
")",
";",
"const",
"existingQs",
"=",
"throughQs",
".",
"filter",
"(",
"through",
"=>",
"(",
"idsToAdd",
".",
"has",
"(",
"through",
"[",
"otherReferencingField",
"]",
")",
")",
")",
";",
"if",
"(",
"existingQs",
".",
"exists",
"(",
")",
")",
"{",
"const",
"existingIds",
"=",
"existingQs",
".",
"toRefArray",
"(",
")",
".",
"map",
"(",
"through",
"=>",
"through",
"[",
"otherReferencingField",
"]",
")",
";",
"throw",
"new",
"Error",
"(",
"`",
"${",
"OtherModel",
".",
"modelName",
"}",
"${",
"existingIds",
"}",
"${",
"ThisModel",
".",
"modelName",
"}",
"${",
"thisId",
"}",
"`",
")",
";",
"}",
"idsToAdd",
".",
"forEach",
"(",
"(",
"id",
")",
"=>",
"{",
"ThroughModel",
".",
"create",
"(",
"{",
"[",
"otherReferencingField",
"]",
":",
"id",
",",
"[",
"thisReferencingField",
"]",
":",
"thisId",
",",
"}",
")",
";",
"}",
")",
";",
"}",
";",
"/**\n * Removes references to all OtherModel instances from the current model.\n *\n * E.g. Book.first().authors.clear() would cause the first book's list\n * of referenced authors to become empty.\n *\n * @return undefined\n */",
"qs",
".",
"clear",
"=",
"function",
"clear",
"(",
")",
"{",
"throughQs",
".",
"delete",
"(",
")",
";",
"}",
";",
"/**\n * Removes references to all passed OtherModel instances from the current model.\n *\n * E.g. Book.first().authors.remove(1, 2) would cause the authors with\n * IDs 1 and 2 to no longer be referenced by the first book.\n *\n * @return undefined\n */",
"qs",
".",
"remove",
"=",
"function",
"remove",
"(",
"...",
"entities",
")",
"{",
"const",
"idsToRemove",
"=",
"new",
"Set",
"(",
"entities",
".",
"map",
"(",
"normalizeEntity",
")",
")",
";",
"const",
"entitiesToDelete",
"=",
"throughQs",
".",
"filter",
"(",
"through",
"=>",
"idsToRemove",
".",
"has",
"(",
"through",
"[",
"otherReferencingField",
"]",
")",
")",
";",
"if",
"(",
"entitiesToDelete",
".",
"count",
"(",
")",
"!==",
"idsToRemove",
".",
"size",
")",
"{",
"// Tried deleting non-existing entities.",
"const",
"entitiesToDeleteIds",
"=",
"entitiesToDelete",
".",
"toRefArray",
"(",
")",
".",
"map",
"(",
"through",
"=>",
"through",
"[",
"otherReferencingField",
"]",
")",
";",
"const",
"unexistingIds",
"=",
"[",
"...",
"idsToRemove",
"]",
".",
"filter",
"(",
"id",
"=>",
"!",
"entitiesToDeleteIds",
".",
"includes",
"(",
"id",
")",
")",
";",
"throw",
"new",
"Error",
"(",
"`",
"${",
"OtherModel",
".",
"modelName",
"}",
"${",
"unexistingIds",
"}",
"${",
"ThisModel",
".",
"modelName",
"}",
"${",
"thisId",
"}",
"`",
")",
";",
"}",
"entitiesToDelete",
".",
"delete",
"(",
")",
";",
"}",
";",
"return",
"qs",
";",
"}",
",",
"set",
"(",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Tried setting a M2M field. Please use the related QuerySet methods add, remove and clear.'",
")",
";",
"}",
",",
"}",
";",
"}"
] |
This descriptor is assigned to both sides of a many-to-many relationship.
To indicate the backwards direction pass `true` for `reverse`.
|
[
"This",
"descriptor",
"is",
"assigned",
"to",
"both",
"sides",
"of",
"a",
"many",
"-",
"to",
"-",
"many",
"relationship",
".",
"To",
"indicate",
"the",
"backwards",
"direction",
"pass",
"true",
"for",
"reverse",
"."
] |
e6077dbfe7da47284ad6c22b1217967017959a7f
|
https://github.com/redux-orm/redux-orm/blob/e6077dbfe7da47284ad6c22b1217967017959a7f/src/descriptors.js#L137-L279
|
12,979
|
redux-orm/redux-orm
|
src/utils.js
|
normalizeEntity
|
function normalizeEntity(entity) {
if (entity !== null &&
typeof entity !== 'undefined' &&
typeof entity.getId === 'function') {
return entity.getId();
}
return entity;
}
|
javascript
|
function normalizeEntity(entity) {
if (entity !== null &&
typeof entity !== 'undefined' &&
typeof entity.getId === 'function') {
return entity.getId();
}
return entity;
}
|
[
"function",
"normalizeEntity",
"(",
"entity",
")",
"{",
"if",
"(",
"entity",
"!==",
"null",
"&&",
"typeof",
"entity",
"!==",
"'undefined'",
"&&",
"typeof",
"entity",
".",
"getId",
"===",
"'function'",
")",
"{",
"return",
"entity",
".",
"getId",
"(",
")",
";",
"}",
"return",
"entity",
";",
"}"
] |
Normalizes `entity` to an id, where `entity` can be an id
or a Model instance.
@param {*} entity - either a Model instance or an id value
@return {*} the id value of `entity`
|
[
"Normalizes",
"entity",
"to",
"an",
"id",
"where",
"entity",
"can",
"be",
"an",
"id",
"or",
"a",
"Model",
"instance",
"."
] |
e6077dbfe7da47284ad6c22b1217967017959a7f
|
https://github.com/redux-orm/redux-orm/blob/e6077dbfe7da47284ad6c22b1217967017959a7f/src/utils.js#L123-L130
|
12,980
|
redux-orm/redux-orm
|
src/db/Table.js
|
idSequencer
|
function idSequencer(_currMax, userPassedId) {
let currMax = _currMax;
let newMax;
let newId;
if (currMax === undefined) {
currMax = -1;
}
if (userPassedId === undefined) {
newMax = currMax + 1;
newId = newMax;
} else {
newMax = Math.max(currMax + 1, userPassedId);
newId = userPassedId;
}
return [
newMax, // new max id
newId, // id to use for row creation
];
}
|
javascript
|
function idSequencer(_currMax, userPassedId) {
let currMax = _currMax;
let newMax;
let newId;
if (currMax === undefined) {
currMax = -1;
}
if (userPassedId === undefined) {
newMax = currMax + 1;
newId = newMax;
} else {
newMax = Math.max(currMax + 1, userPassedId);
newId = userPassedId;
}
return [
newMax, // new max id
newId, // id to use for row creation
];
}
|
[
"function",
"idSequencer",
"(",
"_currMax",
",",
"userPassedId",
")",
"{",
"let",
"currMax",
"=",
"_currMax",
";",
"let",
"newMax",
";",
"let",
"newId",
";",
"if",
"(",
"currMax",
"===",
"undefined",
")",
"{",
"currMax",
"=",
"-",
"1",
";",
"}",
"if",
"(",
"userPassedId",
"===",
"undefined",
")",
"{",
"newMax",
"=",
"currMax",
"+",
"1",
";",
"newId",
"=",
"newMax",
";",
"}",
"else",
"{",
"newMax",
"=",
"Math",
".",
"max",
"(",
"currMax",
"+",
"1",
",",
"userPassedId",
")",
";",
"newId",
"=",
"userPassedId",
";",
"}",
"return",
"[",
"newMax",
",",
"// new max id",
"newId",
",",
"// id to use for row creation",
"]",
";",
"}"
] |
Input is the current max id and the new id passed to the create action. Both may be undefined. The current max id in the case that this is the first Model being created, and the new id if the id was not explicitly passed to the database. Return value is the new max id and the id to use to create the new row. If the id's are strings, the id must be passed explicitly every time. In this case, the current max id will remain `NaN` due to `Math.max`, but that's fine.
|
[
"Input",
"is",
"the",
"current",
"max",
"id",
"and",
"the",
"new",
"id",
"passed",
"to",
"the",
"create",
"action",
".",
"Both",
"may",
"be",
"undefined",
".",
"The",
"current",
"max",
"id",
"in",
"the",
"case",
"that",
"this",
"is",
"the",
"first",
"Model",
"being",
"created",
"and",
"the",
"new",
"id",
"if",
"the",
"id",
"was",
"not",
"explicitly",
"passed",
"to",
"the",
"database",
".",
"Return",
"value",
"is",
"the",
"new",
"max",
"id",
"and",
"the",
"id",
"to",
"use",
"to",
"create",
"the",
"new",
"row",
".",
"If",
"the",
"id",
"s",
"are",
"strings",
"the",
"id",
"must",
"be",
"passed",
"explicitly",
"every",
"time",
".",
"In",
"this",
"case",
"the",
"current",
"max",
"id",
"will",
"remain",
"NaN",
"due",
"to",
"Math",
".",
"max",
"but",
"that",
"s",
"fine",
"."
] |
e6077dbfe7da47284ad6c22b1217967017959a7f
|
https://github.com/redux-orm/redux-orm/blob/e6077dbfe7da47284ad6c22b1217967017959a7f/src/db/Table.js#L27-L48
|
12,981
|
bencevans/node-sonos
|
lib/services/AVTransport.js
|
function (host, port) {
this.name = 'AVTransport'
this.host = host
this.port = port || 1400
this.controlURL = '/MediaRenderer/AVTransport/Control'
this.eventSubURL = '/MediaRenderer/AVTransport/Event'
this.SCPDURL = '/xml/AVTransport1.xml'
}
|
javascript
|
function (host, port) {
this.name = 'AVTransport'
this.host = host
this.port = port || 1400
this.controlURL = '/MediaRenderer/AVTransport/Control'
this.eventSubURL = '/MediaRenderer/AVTransport/Event'
this.SCPDURL = '/xml/AVTransport1.xml'
}
|
[
"function",
"(",
"host",
",",
"port",
")",
"{",
"this",
".",
"name",
"=",
"'AVTransport'",
"this",
".",
"host",
"=",
"host",
"this",
".",
"port",
"=",
"port",
"||",
"1400",
"this",
".",
"controlURL",
"=",
"'/MediaRenderer/AVTransport/Control'",
"this",
".",
"eventSubURL",
"=",
"'/MediaRenderer/AVTransport/Event'",
"this",
".",
"SCPDURL",
"=",
"'/xml/AVTransport1.xml'",
"}"
] |
Create a new instance of AVTransport
@class AVTransport
@param {String} host The host param of one of your sonos speakers
@param {Number} port The port of your sonos speaker, defaults to 1400
|
[
"Create",
"a",
"new",
"instance",
"of",
"AVTransport"
] |
f0d5c1f2aa522005b800f8f2727e0f99238aaeca
|
https://github.com/bencevans/node-sonos/blob/f0d5c1f2aa522005b800f8f2727e0f99238aaeca/lib/services/AVTransport.js#L18-L25
|
|
12,982
|
bencevans/node-sonos
|
lib/services/Service.js
|
function (options) {
this.name = options.name
this.host = options.host
this.port = options.port || 1400
this.controlURL = options.controlURL
this.eventSubURL = options.eventSubURL
this.SCPDURL = options.SCPDURL
return this
}
|
javascript
|
function (options) {
this.name = options.name
this.host = options.host
this.port = options.port || 1400
this.controlURL = options.controlURL
this.eventSubURL = options.eventSubURL
this.SCPDURL = options.SCPDURL
return this
}
|
[
"function",
"(",
"options",
")",
"{",
"this",
".",
"name",
"=",
"options",
".",
"name",
"this",
".",
"host",
"=",
"options",
".",
"host",
"this",
".",
"port",
"=",
"options",
".",
"port",
"||",
"1400",
"this",
".",
"controlURL",
"=",
"options",
".",
"controlURL",
"this",
".",
"eventSubURL",
"=",
"options",
".",
"eventSubURL",
"this",
".",
"SCPDURL",
"=",
"options",
".",
"SCPDURL",
"return",
"this",
"}"
] |
Create a new instance of Service
@class Service
@param {Object} [options] All the required options to use this class
@param {String} options.host The host param of one of your sonos speakers
@param {Number} options.port The port of your sonos speaker, defaults to 1400
@param {String} options.controlURL The control url used for the calls
@param {String} options.eventURL The Event URL used for the calls
@param {String} options.SCPDURL The SCPDURL (ask Ben)
|
[
"Create",
"a",
"new",
"instance",
"of",
"Service"
] |
f0d5c1f2aa522005b800f8f2727e0f99238aaeca
|
https://github.com/bencevans/node-sonos/blob/f0d5c1f2aa522005b800f8f2727e0f99238aaeca/lib/services/Service.js#L26-L34
|
|
12,983
|
bencevans/node-sonos
|
lib/sonos.js
|
Sonos
|
function Sonos (host, port, options) {
this.host = host
this.port = port || 1400
this.options = options || {}
if (!this.options.endpoints) this.options.endpoints = {}
if (!this.options.endpoints.transport) this.options.endpoints.transport = TRANSPORT_ENDPOINT
if (!this.options.endpoints.rendering) this.options.endpoints.rendering = RENDERING_ENDPOINT
if (!this.options.endpoints.device) this.options.endpoints.device = DEVICE_ENDPOINT
this.options.spotify = this.options.spotify || {}
this.options.spotify.region = this.options.spotify.region || SpotifyRegion.US
// Attach to newListener event
var self = this
var implicitListen = async function (event, listener) {
if (event === 'newListener') return
self.removeListener('newListener', implicitListen)
return Listener.subscribeTo(self).catch(err => {
debug('Error subscribing to listener %j', err)
})
}
this.on('newListener', implicitListen)
// Maybe stop the eventListener once last listener is removed?
}
|
javascript
|
function Sonos (host, port, options) {
this.host = host
this.port = port || 1400
this.options = options || {}
if (!this.options.endpoints) this.options.endpoints = {}
if (!this.options.endpoints.transport) this.options.endpoints.transport = TRANSPORT_ENDPOINT
if (!this.options.endpoints.rendering) this.options.endpoints.rendering = RENDERING_ENDPOINT
if (!this.options.endpoints.device) this.options.endpoints.device = DEVICE_ENDPOINT
this.options.spotify = this.options.spotify || {}
this.options.spotify.region = this.options.spotify.region || SpotifyRegion.US
// Attach to newListener event
var self = this
var implicitListen = async function (event, listener) {
if (event === 'newListener') return
self.removeListener('newListener', implicitListen)
return Listener.subscribeTo(self).catch(err => {
debug('Error subscribing to listener %j', err)
})
}
this.on('newListener', implicitListen)
// Maybe stop the eventListener once last listener is removed?
}
|
[
"function",
"Sonos",
"(",
"host",
",",
"port",
",",
"options",
")",
"{",
"this",
".",
"host",
"=",
"host",
"this",
".",
"port",
"=",
"port",
"||",
"1400",
"this",
".",
"options",
"=",
"options",
"||",
"{",
"}",
"if",
"(",
"!",
"this",
".",
"options",
".",
"endpoints",
")",
"this",
".",
"options",
".",
"endpoints",
"=",
"{",
"}",
"if",
"(",
"!",
"this",
".",
"options",
".",
"endpoints",
".",
"transport",
")",
"this",
".",
"options",
".",
"endpoints",
".",
"transport",
"=",
"TRANSPORT_ENDPOINT",
"if",
"(",
"!",
"this",
".",
"options",
".",
"endpoints",
".",
"rendering",
")",
"this",
".",
"options",
".",
"endpoints",
".",
"rendering",
"=",
"RENDERING_ENDPOINT",
"if",
"(",
"!",
"this",
".",
"options",
".",
"endpoints",
".",
"device",
")",
"this",
".",
"options",
".",
"endpoints",
".",
"device",
"=",
"DEVICE_ENDPOINT",
"this",
".",
"options",
".",
"spotify",
"=",
"this",
".",
"options",
".",
"spotify",
"||",
"{",
"}",
"this",
".",
"options",
".",
"spotify",
".",
"region",
"=",
"this",
".",
"options",
".",
"spotify",
".",
"region",
"||",
"SpotifyRegion",
".",
"US",
"// Attach to newListener event",
"var",
"self",
"=",
"this",
"var",
"implicitListen",
"=",
"async",
"function",
"(",
"event",
",",
"listener",
")",
"{",
"if",
"(",
"event",
"===",
"'newListener'",
")",
"return",
"self",
".",
"removeListener",
"(",
"'newListener'",
",",
"implicitListen",
")",
"return",
"Listener",
".",
"subscribeTo",
"(",
"self",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"debug",
"(",
"'Error subscribing to listener %j'",
",",
"err",
")",
"}",
")",
"}",
"this",
".",
"on",
"(",
"'newListener'",
",",
"implicitListen",
")",
"// Maybe stop the eventListener once last listener is removed?",
"}"
] |
Create an instance of Sonos
@class Sonos
@param {String} host IP/DNS
@param {Number} port
@returns {Sonos}
|
[
"Create",
"an",
"instance",
"of",
"Sonos"
] |
f0d5c1f2aa522005b800f8f2727e0f99238aaeca
|
https://github.com/bencevans/node-sonos/blob/f0d5c1f2aa522005b800f8f2727e0f99238aaeca/lib/sonos.js#L52-L75
|
12,984
|
webscopeio/react-textarea-autocomplete
|
cypress/integration/textarea.js
|
repeat
|
function repeat(string, times = 1) {
let result = "";
let round = times;
while (round--) {
result += string;
}
return result;
}
|
javascript
|
function repeat(string, times = 1) {
let result = "";
let round = times;
while (round--) {
result += string;
}
return result;
}
|
[
"function",
"repeat",
"(",
"string",
",",
"times",
"=",
"1",
")",
"{",
"let",
"result",
"=",
"\"\"",
";",
"let",
"round",
"=",
"times",
";",
"while",
"(",
"round",
"--",
")",
"{",
"result",
"+=",
"string",
";",
"}",
"return",
"result",
";",
"}"
] |
Helper function for a repeating of commands
e.g : cy
.get('.rta__textarea')
.type(`${repeat('{backspace}', 13)} again {downarrow}{enter}`);
|
[
"Helper",
"function",
"for",
"a",
"repeating",
"of",
"commands"
] |
a0f4d87cd7d7a49726916ee6c5f9e7468a7b1427
|
https://github.com/webscopeio/react-textarea-autocomplete/blob/a0f4d87cd7d7a49726916ee6c5f9e7468a7b1427/cypress/integration/textarea.js#L8-L16
|
12,985
|
andrewplummer/Sugar
|
lib/object.js
|
toQueryStringWithOptions
|
function toQueryStringWithOptions(obj, opts) {
opts = opts || {};
if (isUndefined(opts.separator)) {
opts.separator = '_';
}
return toQueryString(obj, opts.deep, opts.transform, opts.prefix || '', opts.separator);
}
|
javascript
|
function toQueryStringWithOptions(obj, opts) {
opts = opts || {};
if (isUndefined(opts.separator)) {
opts.separator = '_';
}
return toQueryString(obj, opts.deep, opts.transform, opts.prefix || '', opts.separator);
}
|
[
"function",
"toQueryStringWithOptions",
"(",
"obj",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"if",
"(",
"isUndefined",
"(",
"opts",
".",
"separator",
")",
")",
"{",
"opts",
".",
"separator",
"=",
"'_'",
";",
"}",
"return",
"toQueryString",
"(",
"obj",
",",
"opts",
".",
"deep",
",",
"opts",
".",
"transform",
",",
"opts",
".",
"prefix",
"||",
"''",
",",
"opts",
".",
"separator",
")",
";",
"}"
] |
Query Strings | Creating
|
[
"Query",
"Strings",
"|",
"Creating"
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/object.js#L36-L42
|
12,986
|
andrewplummer/Sugar
|
lib/object.js
|
fromQueryStringWithOptions
|
function fromQueryStringWithOptions(obj, opts) {
var str = String(obj || '').replace(/^.*?\?/, ''), result = {}, auto;
opts = opts || {};
if (str) {
forEach(str.split('&'), function(p) {
var split = p.split('=');
var key = decodeURIComponent(split[0]);
var val = split.length === 2 ? decodeURIComponent(split[1]) : '';
auto = opts.auto !== false;
parseQueryComponent(result, key, val, opts.deep, auto, opts.separator, opts.transform);
});
}
return result;
}
|
javascript
|
function fromQueryStringWithOptions(obj, opts) {
var str = String(obj || '').replace(/^.*?\?/, ''), result = {}, auto;
opts = opts || {};
if (str) {
forEach(str.split('&'), function(p) {
var split = p.split('=');
var key = decodeURIComponent(split[0]);
var val = split.length === 2 ? decodeURIComponent(split[1]) : '';
auto = opts.auto !== false;
parseQueryComponent(result, key, val, opts.deep, auto, opts.separator, opts.transform);
});
}
return result;
}
|
[
"function",
"fromQueryStringWithOptions",
"(",
"obj",
",",
"opts",
")",
"{",
"var",
"str",
"=",
"String",
"(",
"obj",
"||",
"''",
")",
".",
"replace",
"(",
"/",
"^.*?\\?",
"/",
",",
"''",
")",
",",
"result",
"=",
"{",
"}",
",",
"auto",
";",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"if",
"(",
"str",
")",
"{",
"forEach",
"(",
"str",
".",
"split",
"(",
"'&'",
")",
",",
"function",
"(",
"p",
")",
"{",
"var",
"split",
"=",
"p",
".",
"split",
"(",
"'='",
")",
";",
"var",
"key",
"=",
"decodeURIComponent",
"(",
"split",
"[",
"0",
"]",
")",
";",
"var",
"val",
"=",
"split",
".",
"length",
"===",
"2",
"?",
"decodeURIComponent",
"(",
"split",
"[",
"1",
"]",
")",
":",
"''",
";",
"auto",
"=",
"opts",
".",
"auto",
"!==",
"false",
";",
"parseQueryComponent",
"(",
"result",
",",
"key",
",",
"val",
",",
"opts",
".",
"deep",
",",
"auto",
",",
"opts",
".",
"separator",
",",
"opts",
".",
"transform",
")",
";",
"}",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
Query Strings | Parsing
|
[
"Query",
"Strings",
"|",
"Parsing"
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/object.js#L111-L124
|
12,987
|
andrewplummer/Sugar
|
lib/object.js
|
iterateOverKeys
|
function iterateOverKeys(getFn, obj, fn, hidden) {
var keys = getFn(obj), desc;
for (var i = 0, key; key = keys[i]; i++) {
desc = getOwnPropertyDescriptor(obj, key);
if (desc.enumerable || hidden) {
fn(obj[key], key);
}
}
}
|
javascript
|
function iterateOverKeys(getFn, obj, fn, hidden) {
var keys = getFn(obj), desc;
for (var i = 0, key; key = keys[i]; i++) {
desc = getOwnPropertyDescriptor(obj, key);
if (desc.enumerable || hidden) {
fn(obj[key], key);
}
}
}
|
[
"function",
"iterateOverKeys",
"(",
"getFn",
",",
"obj",
",",
"fn",
",",
"hidden",
")",
"{",
"var",
"keys",
"=",
"getFn",
"(",
"obj",
")",
",",
"desc",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"key",
";",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"i",
"++",
")",
"{",
"desc",
"=",
"getOwnPropertyDescriptor",
"(",
"obj",
",",
"key",
")",
";",
"if",
"(",
"desc",
".",
"enumerable",
"||",
"hidden",
")",
"{",
"fn",
"(",
"obj",
"[",
"key",
"]",
",",
"key",
")",
";",
"}",
"}",
"}"
] |
"keys" may include symbols
|
[
"keys",
"may",
"include",
"symbols"
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/object.js#L232-L240
|
12,988
|
andrewplummer/Sugar
|
lib/function.js
|
collectArguments
|
function collectArguments() {
var args = arguments, i = args.length, arr = new Array(i);
while (i--) {
arr[i] = args[i];
}
return arr;
}
|
javascript
|
function collectArguments() {
var args = arguments, i = args.length, arr = new Array(i);
while (i--) {
arr[i] = args[i];
}
return arr;
}
|
[
"function",
"collectArguments",
"(",
")",
"{",
"var",
"args",
"=",
"arguments",
",",
"i",
"=",
"args",
".",
"length",
",",
"arr",
"=",
"new",
"Array",
"(",
"i",
")",
";",
"while",
"(",
"i",
"--",
")",
"{",
"arr",
"[",
"i",
"]",
"=",
"args",
"[",
"i",
"]",
";",
"}",
"return",
"arr",
";",
"}"
] |
Collecting arguments in an array instead of passing back the arguments object which will deopt this function in V8.
|
[
"Collecting",
"arguments",
"in",
"an",
"array",
"instead",
"of",
"passing",
"back",
"the",
"arguments",
"object",
"which",
"will",
"deopt",
"this",
"function",
"in",
"V8",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/function.js#L97-L103
|
12,989
|
andrewplummer/Sugar
|
gulpfile.js
|
getSplitModule
|
function getSplitModule(content, constraints) {
var src = '', lastIdx = 0, currentNamespace;
content.replace(/\/\*\*\* @namespace (\w+) \*\*\*\/\n|$/g, function(match, nextNamespace, idx) {
if (!currentNamespace || constraints[currentNamespace]) {
src += content.slice(lastIdx, idx);
}
currentNamespace = (nextNamespace || '').toLowerCase();
lastIdx = idx;
});
return src;
}
|
javascript
|
function getSplitModule(content, constraints) {
var src = '', lastIdx = 0, currentNamespace;
content.replace(/\/\*\*\* @namespace (\w+) \*\*\*\/\n|$/g, function(match, nextNamespace, idx) {
if (!currentNamespace || constraints[currentNamespace]) {
src += content.slice(lastIdx, idx);
}
currentNamespace = (nextNamespace || '').toLowerCase();
lastIdx = idx;
});
return src;
}
|
[
"function",
"getSplitModule",
"(",
"content",
",",
"constraints",
")",
"{",
"var",
"src",
"=",
"''",
",",
"lastIdx",
"=",
"0",
",",
"currentNamespace",
";",
"content",
".",
"replace",
"(",
"/",
"\\/\\*\\*\\* @namespace (\\w+) \\*\\*\\*\\/\\n|$",
"/",
"g",
",",
"function",
"(",
"match",
",",
"nextNamespace",
",",
"idx",
")",
"{",
"if",
"(",
"!",
"currentNamespace",
"||",
"constraints",
"[",
"currentNamespace",
"]",
")",
"{",
"src",
"+=",
"content",
".",
"slice",
"(",
"lastIdx",
",",
"idx",
")",
";",
"}",
"currentNamespace",
"=",
"(",
"nextNamespace",
"||",
"''",
")",
".",
"toLowerCase",
"(",
")",
";",
"lastIdx",
"=",
"idx",
";",
"}",
")",
";",
"return",
"src",
";",
"}"
] |
Split the module into namespaces here and match on the allowed one.
|
[
"Split",
"the",
"module",
"into",
"namespaces",
"here",
"and",
"match",
"on",
"the",
"allowed",
"one",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/gulpfile.js#L632-L642
|
12,990
|
andrewplummer/Sugar
|
gulpfile.js
|
addFixes
|
function addFixes() {
var match = fnPackage.name.match(/^build(\w+)Fix$/);
if (match) {
addSugarFix(match[1], fnPackage);
fnPackage.dependencies.push(fnCallName);
fnPackage.postAssigns = findVarAssignments(fnPackage.node.body.body, true);
}
}
|
javascript
|
function addFixes() {
var match = fnPackage.name.match(/^build(\w+)Fix$/);
if (match) {
addSugarFix(match[1], fnPackage);
fnPackage.dependencies.push(fnCallName);
fnPackage.postAssigns = findVarAssignments(fnPackage.node.body.body, true);
}
}
|
[
"function",
"addFixes",
"(",
")",
"{",
"var",
"match",
"=",
"fnPackage",
".",
"name",
".",
"match",
"(",
"/",
"^build(\\w+)Fix$",
"/",
")",
";",
"if",
"(",
"match",
")",
"{",
"addSugarFix",
"(",
"match",
"[",
"1",
"]",
",",
"fnPackage",
")",
";",
"fnPackage",
".",
"dependencies",
".",
"push",
"(",
"fnCallName",
")",
";",
"fnPackage",
".",
"postAssigns",
"=",
"findVarAssignments",
"(",
"fnPackage",
".",
"node",
".",
"body",
".",
"body",
",",
"true",
")",
";",
"}",
"}"
] |
Fixes are special types of build methods that fix broken behavior but are not polyfills or attached to a specific method, so need to be handled differently.
|
[
"Fixes",
"are",
"special",
"types",
"of",
"build",
"methods",
"that",
"fix",
"broken",
"behavior",
"but",
"are",
"not",
"polyfills",
"or",
"attached",
"to",
"a",
"specific",
"method",
"so",
"need",
"to",
"be",
"handled",
"differently",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/gulpfile.js#L1886-L1893
|
12,991
|
andrewplummer/Sugar
|
gulpfile.js
|
transposeDependencies
|
function transposeDependencies() {
sourcePackages.forEach(function(p) {
if (p.name === fnCallName) {
// Do not transpose the call package itself. After this loop
// there should be only one dependency on the build function anymore.
return;
}
var index = p.dependencies.indexOf(fnName);
if (index !== -1) {
p.dependencies.splice(index, 1, fnCallName);
}
});
}
|
javascript
|
function transposeDependencies() {
sourcePackages.forEach(function(p) {
if (p.name === fnCallName) {
// Do not transpose the call package itself. After this loop
// there should be only one dependency on the build function anymore.
return;
}
var index = p.dependencies.indexOf(fnName);
if (index !== -1) {
p.dependencies.splice(index, 1, fnCallName);
}
});
}
|
[
"function",
"transposeDependencies",
"(",
")",
"{",
"sourcePackages",
".",
"forEach",
"(",
"function",
"(",
"p",
")",
"{",
"if",
"(",
"p",
".",
"name",
"===",
"fnCallName",
")",
"{",
"// Do not transpose the call package itself. After this loop",
"// there should be only one dependency on the build function anymore.",
"return",
";",
"}",
"var",
"index",
"=",
"p",
".",
"dependencies",
".",
"indexOf",
"(",
"fnName",
")",
";",
"if",
"(",
"index",
"!==",
"-",
"1",
")",
"{",
"p",
".",
"dependencies",
".",
"splice",
"(",
"index",
",",
"1",
",",
"fnCallName",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Step through all source packages and transpose dependencies on the build function to be dependent on the function call instead, ensuring that the function is finally called. Although we could simply push the call body into the build package, this way allows the source to be faithfully rebuilt no matter where the build call occurs.
|
[
"Step",
"through",
"all",
"source",
"packages",
"and",
"transpose",
"dependencies",
"on",
"the",
"build",
"function",
"to",
"be",
"dependent",
"on",
"the",
"function",
"call",
"instead",
"ensuring",
"that",
"the",
"function",
"is",
"finally",
"called",
".",
"Although",
"we",
"could",
"simply",
"push",
"the",
"call",
"body",
"into",
"the",
"build",
"package",
"this",
"way",
"allows",
"the",
"source",
"to",
"be",
"faithfully",
"rebuilt",
"no",
"matter",
"where",
"the",
"build",
"call",
"occurs",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/gulpfile.js#L1900-L1912
|
12,992
|
andrewplummer/Sugar
|
gulpfile.js
|
transposeVarDependencies
|
function transposeVarDependencies() {
var map = {};
sourcePackages.forEach(function(p) {
if (p.vars) {
p.vars.forEach(function(v) {
map[v] = p.name;
});
}
});
sourcePackages.forEach(function(p) {
var deps = [];
var varDeps = [];
p.dependencies.forEach(function(d) {
var normalized = map[d] || d;
if (deps.indexOf(normalized) === -1) {
deps.push(normalized);
}
if (d in map) {
varDeps.push(d);
}
});
p.dependencies = deps;
if (varDeps.length) {
p.varDependencies = varDeps;
}
});
}
|
javascript
|
function transposeVarDependencies() {
var map = {};
sourcePackages.forEach(function(p) {
if (p.vars) {
p.vars.forEach(function(v) {
map[v] = p.name;
});
}
});
sourcePackages.forEach(function(p) {
var deps = [];
var varDeps = [];
p.dependencies.forEach(function(d) {
var normalized = map[d] || d;
if (deps.indexOf(normalized) === -1) {
deps.push(normalized);
}
if (d in map) {
varDeps.push(d);
}
});
p.dependencies = deps;
if (varDeps.length) {
p.varDependencies = varDeps;
}
});
}
|
[
"function",
"transposeVarDependencies",
"(",
")",
"{",
"var",
"map",
"=",
"{",
"}",
";",
"sourcePackages",
".",
"forEach",
"(",
"function",
"(",
"p",
")",
"{",
"if",
"(",
"p",
".",
"vars",
")",
"{",
"p",
".",
"vars",
".",
"forEach",
"(",
"function",
"(",
"v",
")",
"{",
"map",
"[",
"v",
"]",
"=",
"p",
".",
"name",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"sourcePackages",
".",
"forEach",
"(",
"function",
"(",
"p",
")",
"{",
"var",
"deps",
"=",
"[",
"]",
";",
"var",
"varDeps",
"=",
"[",
"]",
";",
"p",
".",
"dependencies",
".",
"forEach",
"(",
"function",
"(",
"d",
")",
"{",
"var",
"normalized",
"=",
"map",
"[",
"d",
"]",
"||",
"d",
";",
"if",
"(",
"deps",
".",
"indexOf",
"(",
"normalized",
")",
"===",
"-",
"1",
")",
"{",
"deps",
".",
"push",
"(",
"normalized",
")",
";",
"}",
"if",
"(",
"d",
"in",
"map",
")",
"{",
"varDeps",
".",
"push",
"(",
"d",
")",
";",
"}",
"}",
")",
";",
"p",
".",
"dependencies",
"=",
"deps",
";",
"if",
"(",
"varDeps",
".",
"length",
")",
"{",
"p",
".",
"varDependencies",
"=",
"varDeps",
";",
"}",
"}",
")",
";",
"}"
] |
Find packages depending on specific vars and transpose the dependency to the bundled var package instead. However keep the references as "varDependencies" for later consumption.
|
[
"Find",
"packages",
"depending",
"on",
"specific",
"vars",
"and",
"transpose",
"the",
"dependency",
"to",
"the",
"bundled",
"var",
"package",
"instead",
".",
"However",
"keep",
"the",
"references",
"as",
"varDependencies",
"for",
"later",
"consumption",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/gulpfile.js#L2096-L2122
|
12,993
|
andrewplummer/Sugar
|
gulpfile.js
|
getDirectRequires
|
function getDirectRequires(p) {
return p.dependencies.filter(function(d) {
return DIRECT_REQUIRES_REG.test(d);
}).map(function(d) {
return "require('"+ getDependencyPath(d, p) +"');";
}).join('\n');
}
|
javascript
|
function getDirectRequires(p) {
return p.dependencies.filter(function(d) {
return DIRECT_REQUIRES_REG.test(d);
}).map(function(d) {
return "require('"+ getDependencyPath(d, p) +"');";
}).join('\n');
}
|
[
"function",
"getDirectRequires",
"(",
"p",
")",
"{",
"return",
"p",
".",
"dependencies",
".",
"filter",
"(",
"function",
"(",
"d",
")",
"{",
"return",
"DIRECT_REQUIRES_REG",
".",
"test",
"(",
"d",
")",
";",
"}",
")",
".",
"map",
"(",
"function",
"(",
"d",
")",
"{",
"return",
"\"require('\"",
"+",
"getDependencyPath",
"(",
"d",
",",
"p",
")",
"+",
"\"');\"",
";",
"}",
")",
".",
"join",
"(",
"'\\n'",
")",
";",
"}"
] |
Any build method calls don't require a reference and can be simply required directly, so output them here.
|
[
"Any",
"build",
"method",
"calls",
"don",
"t",
"require",
"a",
"reference",
"and",
"can",
"be",
"simply",
"required",
"directly",
"so",
"output",
"them",
"here",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/gulpfile.js#L2544-L2550
|
12,994
|
andrewplummer/Sugar
|
gulpfile.js
|
bundleCircularDependencies
|
function bundleCircularDependencies() {
function findCircular(deps, chain) {
for (var i = 0, startIndex, c, p; i < deps.length; i++) {
// Only top level dependencies will be included in the chain.
p = sourcePackages.findByDependencyName(deps[i]);
if (!p) {
continue;
}
startIndex = chain.indexOf(p.name);
if (startIndex !== -1) {
return chain.slice(startIndex);
} else {
c = findCircular(p.dependencies, chain.concat(p.name));
if (c) {
return c;
}
}
}
}
function bundleCircular(chain) {
// Sort the chain so that all packages are
// bundled into the first found in the source.
chain = sortChain(chain);
var target = sourcePackages.findByDependencyName(chain[0]);
delete target.comments;
chain.slice(1).forEach(function(n) {
var src = sourcePackages.findByDependencyName(n);
target.body += '\n\n' + src.body;
target.bodyWithComments += '\n\n' + src.bodyWithComments;
bundleArray(target, src, 'dependencies', true);
bundleArray(target, src, 'varDependencies', true);
bundleArray(target, src, 'vars');
bundleMap(target, src, 'assigns');
updateExternalDependencies(src.name, target.name);
if (src.type === 'build' && (!target.vars || !target.vars.length)) {
// A build function that is having it's call block being bundled
// into it can also take on the type "build". This generally means
// that it has no exports. However don't do this if the function is
// building up variables, in which case it will have a "vars".
target.type = 'build';
}
removePackage(src);
});
}
function sortChain(chain) {
return chain.sort(function(a, b) {
return getPackageIndexByName(a) - getPackageIndexByName(b);
});
}
function getPackageIndexByName(name) {
return sourcePackages.findIndex(function(p) {
return p.name === name;
});
}
// Bundle all dependencies from the source into the target,
// but only after removing the circular dependency itself.
function bundleArray(target, src, name, notSelf) {
var srcValues, targetValues;
if (src[name]) {
srcValues = src[name] || [];
targetValues = target[name] || [];
target[name] = uniq(targetValues.concat(srcValues.filter(function(d) {
return !notSelf || d !== target.name;
})));
}
}
function bundleMap(target, src, name) {
if (src[name]) {
target[name] = target[name] || {};
merge(target[name], src[name]);
}
}
// Update all packages pointing to the old package.
function updateExternalDependencies(oldName, newName) {
sourcePackages.forEach(function(p) {
var index = p.dependencies.indexOf(oldName);
if (index !== -1) {
if (p.name === newName || p.dependencies.indexOf(newName) !== -1) {
// If the package has the same name as the one we are trying to
// update to, then we are trying to update the package to point
// to itself as a dependency, which isn't possible so just remove
// the old dependency. Alternatively, if the package already has
// the new name, then we can simply remove the old one and move on.
p.dependencies.splice(index, 1);
} else {
// If the package is NOT trying to update to itself and does NOT
// have the new dependency already, then add it in place of the
// old one.
p.dependencies.splice(index, 1, newName);
}
}
});
}
function removePackage(p) {
var index = sourcePackages.indexOf(p);
sourcePackages.splice(index, 1);
}
sourcePackages.forEach(function(p) {
var chain = findCircular(p.dependencies, []);
if (chain) {
bundleCircular(chain);
}
});
}
|
javascript
|
function bundleCircularDependencies() {
function findCircular(deps, chain) {
for (var i = 0, startIndex, c, p; i < deps.length; i++) {
// Only top level dependencies will be included in the chain.
p = sourcePackages.findByDependencyName(deps[i]);
if (!p) {
continue;
}
startIndex = chain.indexOf(p.name);
if (startIndex !== -1) {
return chain.slice(startIndex);
} else {
c = findCircular(p.dependencies, chain.concat(p.name));
if (c) {
return c;
}
}
}
}
function bundleCircular(chain) {
// Sort the chain so that all packages are
// bundled into the first found in the source.
chain = sortChain(chain);
var target = sourcePackages.findByDependencyName(chain[0]);
delete target.comments;
chain.slice(1).forEach(function(n) {
var src = sourcePackages.findByDependencyName(n);
target.body += '\n\n' + src.body;
target.bodyWithComments += '\n\n' + src.bodyWithComments;
bundleArray(target, src, 'dependencies', true);
bundleArray(target, src, 'varDependencies', true);
bundleArray(target, src, 'vars');
bundleMap(target, src, 'assigns');
updateExternalDependencies(src.name, target.name);
if (src.type === 'build' && (!target.vars || !target.vars.length)) {
// A build function that is having it's call block being bundled
// into it can also take on the type "build". This generally means
// that it has no exports. However don't do this if the function is
// building up variables, in which case it will have a "vars".
target.type = 'build';
}
removePackage(src);
});
}
function sortChain(chain) {
return chain.sort(function(a, b) {
return getPackageIndexByName(a) - getPackageIndexByName(b);
});
}
function getPackageIndexByName(name) {
return sourcePackages.findIndex(function(p) {
return p.name === name;
});
}
// Bundle all dependencies from the source into the target,
// but only after removing the circular dependency itself.
function bundleArray(target, src, name, notSelf) {
var srcValues, targetValues;
if (src[name]) {
srcValues = src[name] || [];
targetValues = target[name] || [];
target[name] = uniq(targetValues.concat(srcValues.filter(function(d) {
return !notSelf || d !== target.name;
})));
}
}
function bundleMap(target, src, name) {
if (src[name]) {
target[name] = target[name] || {};
merge(target[name], src[name]);
}
}
// Update all packages pointing to the old package.
function updateExternalDependencies(oldName, newName) {
sourcePackages.forEach(function(p) {
var index = p.dependencies.indexOf(oldName);
if (index !== -1) {
if (p.name === newName || p.dependencies.indexOf(newName) !== -1) {
// If the package has the same name as the one we are trying to
// update to, then we are trying to update the package to point
// to itself as a dependency, which isn't possible so just remove
// the old dependency. Alternatively, if the package already has
// the new name, then we can simply remove the old one and move on.
p.dependencies.splice(index, 1);
} else {
// If the package is NOT trying to update to itself and does NOT
// have the new dependency already, then add it in place of the
// old one.
p.dependencies.splice(index, 1, newName);
}
}
});
}
function removePackage(p) {
var index = sourcePackages.indexOf(p);
sourcePackages.splice(index, 1);
}
sourcePackages.forEach(function(p) {
var chain = findCircular(p.dependencies, []);
if (chain) {
bundleCircular(chain);
}
});
}
|
[
"function",
"bundleCircularDependencies",
"(",
")",
"{",
"function",
"findCircular",
"(",
"deps",
",",
"chain",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"startIndex",
",",
"c",
",",
"p",
";",
"i",
"<",
"deps",
".",
"length",
";",
"i",
"++",
")",
"{",
"// Only top level dependencies will be included in the chain.",
"p",
"=",
"sourcePackages",
".",
"findByDependencyName",
"(",
"deps",
"[",
"i",
"]",
")",
";",
"if",
"(",
"!",
"p",
")",
"{",
"continue",
";",
"}",
"startIndex",
"=",
"chain",
".",
"indexOf",
"(",
"p",
".",
"name",
")",
";",
"if",
"(",
"startIndex",
"!==",
"-",
"1",
")",
"{",
"return",
"chain",
".",
"slice",
"(",
"startIndex",
")",
";",
"}",
"else",
"{",
"c",
"=",
"findCircular",
"(",
"p",
".",
"dependencies",
",",
"chain",
".",
"concat",
"(",
"p",
".",
"name",
")",
")",
";",
"if",
"(",
"c",
")",
"{",
"return",
"c",
";",
"}",
"}",
"}",
"}",
"function",
"bundleCircular",
"(",
"chain",
")",
"{",
"// Sort the chain so that all packages are",
"// bundled into the first found in the source.",
"chain",
"=",
"sortChain",
"(",
"chain",
")",
";",
"var",
"target",
"=",
"sourcePackages",
".",
"findByDependencyName",
"(",
"chain",
"[",
"0",
"]",
")",
";",
"delete",
"target",
".",
"comments",
";",
"chain",
".",
"slice",
"(",
"1",
")",
".",
"forEach",
"(",
"function",
"(",
"n",
")",
"{",
"var",
"src",
"=",
"sourcePackages",
".",
"findByDependencyName",
"(",
"n",
")",
";",
"target",
".",
"body",
"+=",
"'\\n\\n'",
"+",
"src",
".",
"body",
";",
"target",
".",
"bodyWithComments",
"+=",
"'\\n\\n'",
"+",
"src",
".",
"bodyWithComments",
";",
"bundleArray",
"(",
"target",
",",
"src",
",",
"'dependencies'",
",",
"true",
")",
";",
"bundleArray",
"(",
"target",
",",
"src",
",",
"'varDependencies'",
",",
"true",
")",
";",
"bundleArray",
"(",
"target",
",",
"src",
",",
"'vars'",
")",
";",
"bundleMap",
"(",
"target",
",",
"src",
",",
"'assigns'",
")",
";",
"updateExternalDependencies",
"(",
"src",
".",
"name",
",",
"target",
".",
"name",
")",
";",
"if",
"(",
"src",
".",
"type",
"===",
"'build'",
"&&",
"(",
"!",
"target",
".",
"vars",
"||",
"!",
"target",
".",
"vars",
".",
"length",
")",
")",
"{",
"// A build function that is having it's call block being bundled",
"// into it can also take on the type \"build\". This generally means",
"// that it has no exports. However don't do this if the function is",
"// building up variables, in which case it will have a \"vars\".",
"target",
".",
"type",
"=",
"'build'",
";",
"}",
"removePackage",
"(",
"src",
")",
";",
"}",
")",
";",
"}",
"function",
"sortChain",
"(",
"chain",
")",
"{",
"return",
"chain",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"getPackageIndexByName",
"(",
"a",
")",
"-",
"getPackageIndexByName",
"(",
"b",
")",
";",
"}",
")",
";",
"}",
"function",
"getPackageIndexByName",
"(",
"name",
")",
"{",
"return",
"sourcePackages",
".",
"findIndex",
"(",
"function",
"(",
"p",
")",
"{",
"return",
"p",
".",
"name",
"===",
"name",
";",
"}",
")",
";",
"}",
"// Bundle all dependencies from the source into the target,",
"// but only after removing the circular dependency itself.",
"function",
"bundleArray",
"(",
"target",
",",
"src",
",",
"name",
",",
"notSelf",
")",
"{",
"var",
"srcValues",
",",
"targetValues",
";",
"if",
"(",
"src",
"[",
"name",
"]",
")",
"{",
"srcValues",
"=",
"src",
"[",
"name",
"]",
"||",
"[",
"]",
";",
"targetValues",
"=",
"target",
"[",
"name",
"]",
"||",
"[",
"]",
";",
"target",
"[",
"name",
"]",
"=",
"uniq",
"(",
"targetValues",
".",
"concat",
"(",
"srcValues",
".",
"filter",
"(",
"function",
"(",
"d",
")",
"{",
"return",
"!",
"notSelf",
"||",
"d",
"!==",
"target",
".",
"name",
";",
"}",
")",
")",
")",
";",
"}",
"}",
"function",
"bundleMap",
"(",
"target",
",",
"src",
",",
"name",
")",
"{",
"if",
"(",
"src",
"[",
"name",
"]",
")",
"{",
"target",
"[",
"name",
"]",
"=",
"target",
"[",
"name",
"]",
"||",
"{",
"}",
";",
"merge",
"(",
"target",
"[",
"name",
"]",
",",
"src",
"[",
"name",
"]",
")",
";",
"}",
"}",
"// Update all packages pointing to the old package.",
"function",
"updateExternalDependencies",
"(",
"oldName",
",",
"newName",
")",
"{",
"sourcePackages",
".",
"forEach",
"(",
"function",
"(",
"p",
")",
"{",
"var",
"index",
"=",
"p",
".",
"dependencies",
".",
"indexOf",
"(",
"oldName",
")",
";",
"if",
"(",
"index",
"!==",
"-",
"1",
")",
"{",
"if",
"(",
"p",
".",
"name",
"===",
"newName",
"||",
"p",
".",
"dependencies",
".",
"indexOf",
"(",
"newName",
")",
"!==",
"-",
"1",
")",
"{",
"// If the package has the same name as the one we are trying to",
"// update to, then we are trying to update the package to point",
"// to itself as a dependency, which isn't possible so just remove",
"// the old dependency. Alternatively, if the package already has",
"// the new name, then we can simply remove the old one and move on.",
"p",
".",
"dependencies",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"}",
"else",
"{",
"// If the package is NOT trying to update to itself and does NOT",
"// have the new dependency already, then add it in place of the",
"// old one.",
"p",
".",
"dependencies",
".",
"splice",
"(",
"index",
",",
"1",
",",
"newName",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"function",
"removePackage",
"(",
"p",
")",
"{",
"var",
"index",
"=",
"sourcePackages",
".",
"indexOf",
"(",
"p",
")",
";",
"sourcePackages",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"}",
"sourcePackages",
".",
"forEach",
"(",
"function",
"(",
"p",
")",
"{",
"var",
"chain",
"=",
"findCircular",
"(",
"p",
".",
"dependencies",
",",
"[",
"]",
")",
";",
"if",
"(",
"chain",
")",
"{",
"bundleCircular",
"(",
"chain",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Circular dependencies are not necessarily a problem for Javascript at execution time due to having different code paths, however they don't work for npm packages, so they must be bundled together. This isn't too fancy so more complicated dependencies should be refactored. First in the source will be the target package for the bundle.
|
[
"Circular",
"dependencies",
"are",
"not",
"necessarily",
"a",
"problem",
"for",
"Javascript",
"at",
"execution",
"time",
"due",
"to",
"having",
"different",
"code",
"paths",
"however",
"they",
"don",
"t",
"work",
"for",
"npm",
"packages",
"so",
"they",
"must",
"be",
"bundled",
"together",
".",
"This",
"isn",
"t",
"too",
"fancy",
"so",
"more",
"complicated",
"dependencies",
"should",
"be",
"refactored",
".",
"First",
"in",
"the",
"source",
"will",
"be",
"the",
"target",
"package",
"for",
"the",
"bundle",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/gulpfile.js#L2714-L2831
|
12,995
|
andrewplummer/Sugar
|
gulpfile.js
|
bundleArray
|
function bundleArray(target, src, name, notSelf) {
var srcValues, targetValues;
if (src[name]) {
srcValues = src[name] || [];
targetValues = target[name] || [];
target[name] = uniq(targetValues.concat(srcValues.filter(function(d) {
return !notSelf || d !== target.name;
})));
}
}
|
javascript
|
function bundleArray(target, src, name, notSelf) {
var srcValues, targetValues;
if (src[name]) {
srcValues = src[name] || [];
targetValues = target[name] || [];
target[name] = uniq(targetValues.concat(srcValues.filter(function(d) {
return !notSelf || d !== target.name;
})));
}
}
|
[
"function",
"bundleArray",
"(",
"target",
",",
"src",
",",
"name",
",",
"notSelf",
")",
"{",
"var",
"srcValues",
",",
"targetValues",
";",
"if",
"(",
"src",
"[",
"name",
"]",
")",
"{",
"srcValues",
"=",
"src",
"[",
"name",
"]",
"||",
"[",
"]",
";",
"targetValues",
"=",
"target",
"[",
"name",
"]",
"||",
"[",
"]",
";",
"target",
"[",
"name",
"]",
"=",
"uniq",
"(",
"targetValues",
".",
"concat",
"(",
"srcValues",
".",
"filter",
"(",
"function",
"(",
"d",
")",
"{",
"return",
"!",
"notSelf",
"||",
"d",
"!==",
"target",
".",
"name",
";",
"}",
")",
")",
")",
";",
"}",
"}"
] |
Bundle all dependencies from the source into the target, but only after removing the circular dependency itself.
|
[
"Bundle",
"all",
"dependencies",
"from",
"the",
"source",
"into",
"the",
"target",
"but",
"only",
"after",
"removing",
"the",
"circular",
"dependency",
"itself",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/gulpfile.js#L2780-L2789
|
12,996
|
andrewplummer/Sugar
|
gulpfile.js
|
updateExternalDependencies
|
function updateExternalDependencies(oldName, newName) {
sourcePackages.forEach(function(p) {
var index = p.dependencies.indexOf(oldName);
if (index !== -1) {
if (p.name === newName || p.dependencies.indexOf(newName) !== -1) {
// If the package has the same name as the one we are trying to
// update to, then we are trying to update the package to point
// to itself as a dependency, which isn't possible so just remove
// the old dependency. Alternatively, if the package already has
// the new name, then we can simply remove the old one and move on.
p.dependencies.splice(index, 1);
} else {
// If the package is NOT trying to update to itself and does NOT
// have the new dependency already, then add it in place of the
// old one.
p.dependencies.splice(index, 1, newName);
}
}
});
}
|
javascript
|
function updateExternalDependencies(oldName, newName) {
sourcePackages.forEach(function(p) {
var index = p.dependencies.indexOf(oldName);
if (index !== -1) {
if (p.name === newName || p.dependencies.indexOf(newName) !== -1) {
// If the package has the same name as the one we are trying to
// update to, then we are trying to update the package to point
// to itself as a dependency, which isn't possible so just remove
// the old dependency. Alternatively, if the package already has
// the new name, then we can simply remove the old one and move on.
p.dependencies.splice(index, 1);
} else {
// If the package is NOT trying to update to itself and does NOT
// have the new dependency already, then add it in place of the
// old one.
p.dependencies.splice(index, 1, newName);
}
}
});
}
|
[
"function",
"updateExternalDependencies",
"(",
"oldName",
",",
"newName",
")",
"{",
"sourcePackages",
".",
"forEach",
"(",
"function",
"(",
"p",
")",
"{",
"var",
"index",
"=",
"p",
".",
"dependencies",
".",
"indexOf",
"(",
"oldName",
")",
";",
"if",
"(",
"index",
"!==",
"-",
"1",
")",
"{",
"if",
"(",
"p",
".",
"name",
"===",
"newName",
"||",
"p",
".",
"dependencies",
".",
"indexOf",
"(",
"newName",
")",
"!==",
"-",
"1",
")",
"{",
"// If the package has the same name as the one we are trying to",
"// update to, then we are trying to update the package to point",
"// to itself as a dependency, which isn't possible so just remove",
"// the old dependency. Alternatively, if the package already has",
"// the new name, then we can simply remove the old one and move on.",
"p",
".",
"dependencies",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"}",
"else",
"{",
"// If the package is NOT trying to update to itself and does NOT",
"// have the new dependency already, then add it in place of the",
"// old one.",
"p",
".",
"dependencies",
".",
"splice",
"(",
"index",
",",
"1",
",",
"newName",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] |
Update all packages pointing to the old package.
|
[
"Update",
"all",
"packages",
"pointing",
"to",
"the",
"old",
"package",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/gulpfile.js#L2799-L2818
|
12,997
|
andrewplummer/Sugar
|
gulpfile.js
|
unpackMethodSets
|
function unpackMethodSets(methods) {
var result = [];
methods.forEach(function(method) {
if (method.set) {
method.set.forEach(function(name) {
var setMethod = clone(method);
setMethod.name = name;
result.push(setMethod);
});
} else {
result.push(method);
}
});
return result;
}
|
javascript
|
function unpackMethodSets(methods) {
var result = [];
methods.forEach(function(method) {
if (method.set) {
method.set.forEach(function(name) {
var setMethod = clone(method);
setMethod.name = name;
result.push(setMethod);
});
} else {
result.push(method);
}
});
return result;
}
|
[
"function",
"unpackMethodSets",
"(",
"methods",
")",
"{",
"var",
"result",
"=",
"[",
"]",
";",
"methods",
".",
"forEach",
"(",
"function",
"(",
"method",
")",
"{",
"if",
"(",
"method",
".",
"set",
")",
"{",
"method",
".",
"set",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"var",
"setMethod",
"=",
"clone",
"(",
"method",
")",
";",
"setMethod",
".",
"name",
"=",
"name",
";",
"result",
".",
"push",
"(",
"setMethod",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"result",
".",
"push",
"(",
"method",
")",
";",
"}",
"}",
")",
";",
"return",
"result",
";",
"}"
] |
Expands method sets and merges declaration supplements.
|
[
"Expands",
"method",
"sets",
"and",
"merges",
"declaration",
"supplements",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/gulpfile.js#L4328-L4343
|
12,998
|
andrewplummer/Sugar
|
gulpfile.js
|
getAlternateTypes
|
function getAlternateTypes(method) {
var types = [];
function process(arr) {
if (arr) {
arr.forEach(function(obj) {
if (obj.type) {
var split = obj.type.split('|');
if (split.length > 1) {
types = types.concat(split);
}
}
});
}
}
process(method.params);
process(method.options);
return types;
}
|
javascript
|
function getAlternateTypes(method) {
var types = [];
function process(arr) {
if (arr) {
arr.forEach(function(obj) {
if (obj.type) {
var split = obj.type.split('|');
if (split.length > 1) {
types = types.concat(split);
}
}
});
}
}
process(method.params);
process(method.options);
return types;
}
|
[
"function",
"getAlternateTypes",
"(",
"method",
")",
"{",
"var",
"types",
"=",
"[",
"]",
";",
"function",
"process",
"(",
"arr",
")",
"{",
"if",
"(",
"arr",
")",
"{",
"arr",
".",
"forEach",
"(",
"function",
"(",
"obj",
")",
"{",
"if",
"(",
"obj",
".",
"type",
")",
"{",
"var",
"split",
"=",
"obj",
".",
"type",
".",
"split",
"(",
"'|'",
")",
";",
"if",
"(",
"split",
".",
"length",
">",
"1",
")",
"{",
"types",
"=",
"types",
".",
"concat",
"(",
"split",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"}",
"process",
"(",
"method",
".",
"params",
")",
";",
"process",
"(",
"method",
".",
"options",
")",
";",
"return",
"types",
";",
"}"
] |
If the param has multiple types, then move callbacks into the module as named types. Only do this if there are multiple types, otherwise the callback signature can be inlined into the method declaration.
|
[
"If",
"the",
"param",
"has",
"multiple",
"types",
"then",
"move",
"callbacks",
"into",
"the",
"module",
"as",
"named",
"types",
".",
"Only",
"do",
"this",
"if",
"there",
"are",
"multiple",
"types",
"otherwise",
"the",
"callback",
"signature",
"can",
"be",
"inlined",
"into",
"the",
"method",
"declaration",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/gulpfile.js#L4447-L4467
|
12,999
|
andrewplummer/Sugar
|
lib/date.js
|
callDateSetWithWeek
|
function callDateSetWithWeek(d, method, value, safe) {
if (method === 'ISOWeek') {
setISOWeekNumber(d, value);
} else {
callDateSet(d, method, value, safe);
}
}
|
javascript
|
function callDateSetWithWeek(d, method, value, safe) {
if (method === 'ISOWeek') {
setISOWeekNumber(d, value);
} else {
callDateSet(d, method, value, safe);
}
}
|
[
"function",
"callDateSetWithWeek",
"(",
"d",
",",
"method",
",",
"value",
",",
"safe",
")",
"{",
"if",
"(",
"method",
"===",
"'ISOWeek'",
")",
"{",
"setISOWeekNumber",
"(",
"d",
",",
"value",
")",
";",
"}",
"else",
"{",
"callDateSet",
"(",
"d",
",",
"method",
",",
"value",
",",
"safe",
")",
";",
"}",
"}"
] |
Normal callDateSet method with ability to handle ISOWeek setting as well.
|
[
"Normal",
"callDateSet",
"method",
"with",
"ability",
"to",
"handle",
"ISOWeek",
"setting",
"as",
"well",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/date.js#L677-L683
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.