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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
17,900
|
erming/shout
|
client/js/libs/jquery/tabcomplete.js
|
select
|
function select(word) {
var input = this;
var value = input.val();
if (word) {
input.val(
value
+ word.substr(value.split(/ |\n/).pop().length)
);
// Select hint.
input[0].selectionStart = value.length;
}
}
|
javascript
|
function select(word) {
var input = this;
var value = input.val();
if (word) {
input.val(
value
+ word.substr(value.split(/ |\n/).pop().length)
);
// Select hint.
input[0].selectionStart = value.length;
}
}
|
[
"function",
"select",
"(",
"word",
")",
"{",
"var",
"input",
"=",
"this",
";",
"var",
"value",
"=",
"input",
".",
"val",
"(",
")",
";",
"if",
"(",
"word",
")",
"{",
"input",
".",
"val",
"(",
"value",
"+",
"word",
".",
"substr",
"(",
"value",
".",
"split",
"(",
"/",
" |\\n",
"/",
")",
".",
"pop",
"(",
")",
".",
"length",
")",
")",
";",
"// Select hint.",
"input",
"[",
"0",
"]",
".",
"selectionStart",
"=",
"value",
".",
"length",
";",
"}",
"}"
] |
Hint by selecting part of the suggested word.
|
[
"Hint",
"by",
"selecting",
"part",
"of",
"the",
"suggested",
"word",
"."
] |
90a62c56af4412c6b0e0ae51fe84f3825f49e226
|
https://github.com/erming/shout/blob/90a62c56af4412c6b0e0ae51fe84f3825f49e226/client/js/libs/jquery/tabcomplete.js#L243-L255
|
17,901
|
andrewrk/groovebasin
|
lib/player.js
|
cacheTracksArray
|
function cacheTracksArray(self) {
self.tracksInOrder = Object.keys(self.playlist).map(trackById);
self.tracksInOrder.sort(asc);
self.tracksInOrder.forEach(function(track, index) {
track.index = index;
});
function asc(a, b) {
return operatorCompare(a.sortKey, b.sortKey);
}
function trackById(id) {
return self.playlist[id];
}
}
|
javascript
|
function cacheTracksArray(self) {
self.tracksInOrder = Object.keys(self.playlist).map(trackById);
self.tracksInOrder.sort(asc);
self.tracksInOrder.forEach(function(track, index) {
track.index = index;
});
function asc(a, b) {
return operatorCompare(a.sortKey, b.sortKey);
}
function trackById(id) {
return self.playlist[id];
}
}
|
[
"function",
"cacheTracksArray",
"(",
"self",
")",
"{",
"self",
".",
"tracksInOrder",
"=",
"Object",
".",
"keys",
"(",
"self",
".",
"playlist",
")",
".",
"map",
"(",
"trackById",
")",
";",
"self",
".",
"tracksInOrder",
".",
"sort",
"(",
"asc",
")",
";",
"self",
".",
"tracksInOrder",
".",
"forEach",
"(",
"function",
"(",
"track",
",",
"index",
")",
"{",
"track",
".",
"index",
"=",
"index",
";",
"}",
")",
";",
"function",
"asc",
"(",
"a",
",",
"b",
")",
"{",
"return",
"operatorCompare",
"(",
"a",
".",
"sortKey",
",",
"b",
".",
"sortKey",
")",
";",
"}",
"function",
"trackById",
"(",
"id",
")",
"{",
"return",
"self",
".",
"playlist",
"[",
"id",
"]",
";",
"}",
"}"
] |
generate self.tracksInOrder from self.playlist
|
[
"generate",
"self",
".",
"tracksInOrder",
"from",
"self",
".",
"playlist"
] |
482b04d9ce982dbec011f3e42ed993b4de22e8be
|
https://github.com/andrewrk/groovebasin/blob/482b04d9ce982dbec011f3e42ed993b4de22e8be/lib/player.js#L2464-L2477
|
17,902
|
andrewrk/groovebasin
|
lib/player.js
|
sortTracks
|
function sortTracks(tracks) {
var lib = new MusicLibraryIndex();
tracks.forEach(function(track) {
lib.addTrack(track);
});
lib.rebuildTracks();
var results = [];
lib.artistList.forEach(function(artist) {
artist.albumList.forEach(function(album) {
album.trackList.forEach(function(track) {
results.push(track);
});
});
});
return results;
}
|
javascript
|
function sortTracks(tracks) {
var lib = new MusicLibraryIndex();
tracks.forEach(function(track) {
lib.addTrack(track);
});
lib.rebuildTracks();
var results = [];
lib.artistList.forEach(function(artist) {
artist.albumList.forEach(function(album) {
album.trackList.forEach(function(track) {
results.push(track);
});
});
});
return results;
}
|
[
"function",
"sortTracks",
"(",
"tracks",
")",
"{",
"var",
"lib",
"=",
"new",
"MusicLibraryIndex",
"(",
")",
";",
"tracks",
".",
"forEach",
"(",
"function",
"(",
"track",
")",
"{",
"lib",
".",
"addTrack",
"(",
"track",
")",
";",
"}",
")",
";",
"lib",
".",
"rebuildTracks",
"(",
")",
";",
"var",
"results",
"=",
"[",
"]",
";",
"lib",
".",
"artistList",
".",
"forEach",
"(",
"function",
"(",
"artist",
")",
"{",
"artist",
".",
"albumList",
".",
"forEach",
"(",
"function",
"(",
"album",
")",
"{",
"album",
".",
"trackList",
".",
"forEach",
"(",
"function",
"(",
"track",
")",
"{",
"results",
".",
"push",
"(",
"track",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"results",
";",
"}"
] |
sort keys according to how they appear in the library
|
[
"sort",
"keys",
"according",
"to",
"how",
"they",
"appear",
"in",
"the",
"library"
] |
482b04d9ce982dbec011f3e42ed993b4de22e8be
|
https://github.com/andrewrk/groovebasin/blob/482b04d9ce982dbec011f3e42ed993b4de22e8be/lib/player.js#L3077-L3092
|
17,903
|
strathausen/dracula
|
examples/binary_tree.js
|
function(r, n) {
/* the Raphael set is obligatory, containing all you want to display */
var set = r.set().push(
/* custom objects go here */
r.rect(n.point[0]-30, n.point[1]-13, 50, 50)
.attr({"fill": "#fa8", "stroke-width": 2, r: 9}))
.push(r.text(n.point[0], n.point[1] + 15, n.id)
.attr({"font-size":"20px"}));
return set;
}
|
javascript
|
function(r, n) {
/* the Raphael set is obligatory, containing all you want to display */
var set = r.set().push(
/* custom objects go here */
r.rect(n.point[0]-30, n.point[1]-13, 50, 50)
.attr({"fill": "#fa8", "stroke-width": 2, r: 9}))
.push(r.text(n.point[0], n.point[1] + 15, n.id)
.attr({"font-size":"20px"}));
return set;
}
|
[
"function",
"(",
"r",
",",
"n",
")",
"{",
"/* the Raphael set is obligatory, containing all you want to display */",
"var",
"set",
"=",
"r",
".",
"set",
"(",
")",
".",
"push",
"(",
"/* custom objects go here */",
"r",
".",
"rect",
"(",
"n",
".",
"point",
"[",
"0",
"]",
"-",
"30",
",",
"n",
".",
"point",
"[",
"1",
"]",
"-",
"13",
",",
"50",
",",
"50",
")",
".",
"attr",
"(",
"{",
"\"fill\"",
":",
"\"#fa8\"",
",",
"\"stroke-width\"",
":",
"2",
",",
"r",
":",
"9",
"}",
")",
")",
".",
"push",
"(",
"r",
".",
"text",
"(",
"n",
".",
"point",
"[",
"0",
"]",
",",
"n",
".",
"point",
"[",
"1",
"]",
"+",
"15",
",",
"n",
".",
"id",
")",
".",
"attr",
"(",
"{",
"\"font-size\"",
":",
"\"20px\"",
"}",
")",
")",
";",
"return",
"set",
";",
"}"
] |
Custom render function, to be used as the default for every node
|
[
"Custom",
"render",
"function",
"to",
"be",
"used",
"as",
"the",
"default",
"for",
"every",
"node"
] |
590ec23ac3341632d9fc1957c72e95b4f0ccc4d0
|
https://github.com/strathausen/dracula/blob/590ec23ac3341632d9fc1957c72e95b4f0ccc4d0/examples/binary_tree.js#L19-L28
|
|
17,904
|
strathausen/dracula
|
lib/algorithms.js
|
prefix
|
function prefix(p) {
/* pi contains the computed skip marks */
var pi = [0],
k = 0;
for (q = 1; q < p.length; q++) {
while (k > 0 && p.charAt(k) !== p.charAt(q)) {
k = pi[k - 1];
}if (p.charAt(k) === p.charAt(q)) {
k++;
}
pi[q] = k;
}
return pi;
}
|
javascript
|
function prefix(p) {
/* pi contains the computed skip marks */
var pi = [0],
k = 0;
for (q = 1; q < p.length; q++) {
while (k > 0 && p.charAt(k) !== p.charAt(q)) {
k = pi[k - 1];
}if (p.charAt(k) === p.charAt(q)) {
k++;
}
pi[q] = k;
}
return pi;
}
|
[
"function",
"prefix",
"(",
"p",
")",
"{",
"/* pi contains the computed skip marks */",
"var",
"pi",
"=",
"[",
"0",
"]",
",",
"k",
"=",
"0",
";",
"for",
"(",
"q",
"=",
"1",
";",
"q",
"<",
"p",
".",
"length",
";",
"q",
"++",
")",
"{",
"while",
"(",
"k",
">",
"0",
"&&",
"p",
".",
"charAt",
"(",
"k",
")",
"!==",
"p",
".",
"charAt",
"(",
"q",
")",
")",
"{",
"k",
"=",
"pi",
"[",
"k",
"-",
"1",
"]",
";",
"}",
"if",
"(",
"p",
".",
"charAt",
"(",
"k",
")",
"===",
"p",
".",
"charAt",
"(",
"q",
")",
")",
"{",
"k",
"++",
";",
"}",
"pi",
"[",
"q",
"]",
"=",
"k",
";",
"}",
"return",
"pi",
";",
"}"
] |
PREFIX, OVERLAP or FALIURE function for KMP. Computes how many iterations
the algorithm can skip after a mismatch.
@input p - pattern (string)
@result array of skippable iterations
|
[
"PREFIX",
"OVERLAP",
"or",
"FALIURE",
"function",
"for",
"KMP",
".",
"Computes",
"how",
"many",
"iterations",
"the",
"algorithm",
"can",
"skip",
"after",
"a",
"mismatch",
"."
] |
590ec23ac3341632d9fc1957c72e95b4f0ccc4d0
|
https://github.com/strathausen/dracula/blob/590ec23ac3341632d9fc1957c72e95b4f0ccc4d0/lib/algorithms.js#L194-L209
|
17,905
|
sidorares/node-x11
|
examples/vncviewer/rfbclient.js
|
nextTile
|
function nextTile()
{
clog('nextTile');
rect.emit('tile', tile);
tile = {};
if (rect.tilex < rect.widthTiles)
{
rect.tilex++;
//clog([rect.tilex, rect.tiley]);
return cli.readHextileTile(rect, cb);
} else {
clog('===================== new row! ' + rect.tiley);
rect.tilex = 0;
if (rect.tiley < rect.heightTiles)
{
rect.tiley++;
//clog([rect.tilex, rect.tiley]);
return cli.readHextileTile(rect, cb);
} else {
clog('====================')
clog(rect);
return cb();
}
}
}
|
javascript
|
function nextTile()
{
clog('nextTile');
rect.emit('tile', tile);
tile = {};
if (rect.tilex < rect.widthTiles)
{
rect.tilex++;
//clog([rect.tilex, rect.tiley]);
return cli.readHextileTile(rect, cb);
} else {
clog('===================== new row! ' + rect.tiley);
rect.tilex = 0;
if (rect.tiley < rect.heightTiles)
{
rect.tiley++;
//clog([rect.tilex, rect.tiley]);
return cli.readHextileTile(rect, cb);
} else {
clog('====================')
clog(rect);
return cb();
}
}
}
|
[
"function",
"nextTile",
"(",
")",
"{",
"clog",
"(",
"'nextTile'",
")",
";",
"rect",
".",
"emit",
"(",
"'tile'",
",",
"tile",
")",
";",
"tile",
"=",
"{",
"}",
";",
"if",
"(",
"rect",
".",
"tilex",
"<",
"rect",
".",
"widthTiles",
")",
"{",
"rect",
".",
"tilex",
"++",
";",
"//clog([rect.tilex, rect.tiley]);",
"return",
"cli",
".",
"readHextileTile",
"(",
"rect",
",",
"cb",
")",
";",
"}",
"else",
"{",
"clog",
"(",
"'===================== new row! '",
"+",
"rect",
".",
"tiley",
")",
";",
"rect",
".",
"tilex",
"=",
"0",
";",
"if",
"(",
"rect",
".",
"tiley",
"<",
"rect",
".",
"heightTiles",
")",
"{",
"rect",
".",
"tiley",
"++",
";",
"//clog([rect.tilex, rect.tiley]);",
"return",
"cli",
".",
"readHextileTile",
"(",
"rect",
",",
"cb",
")",
";",
"}",
"else",
"{",
"clog",
"(",
"'===================='",
")",
"clog",
"(",
"rect",
")",
";",
"return",
"cb",
"(",
")",
";",
"}",
"}",
"}"
] |
calculate next tilex & tiley and move up 'stack' if we at the last tile
|
[
"calculate",
"next",
"tilex",
"&",
"tiley",
"and",
"move",
"up",
"stack",
"if",
"we",
"at",
"the",
"last",
"tile"
] |
f6547d387617f833c038ea420ba9c2174f9d340b
|
https://github.com/sidorares/node-x11/blob/f6547d387617f833c038ea420ba9c2174f9d340b/examples/vncviewer/rfbclient.js#L361-L385
|
17,906
|
sidorares/node-x11
|
lib/corereqs.js
|
function(id, parentId, x, y, width, height, borderWidth, depth, _class, visual, values) {
if (borderWidth === undefined)
borderWidth = 0;
if (depth === undefined)
depth = 0;
if (_class === undefined)
_class = 0;
if (visual === undefined)
visual = 0;
if (values === undefined)
values = {}
var format = 'CCSLLssSSSSLL';
// TODO: slice from function arguments?
// TODO: the code is a little bit mess
// additional values need to be packed in the following way:
// bitmask (bytes #24 to #31 in the packet) - 32 bit indicating what adittional arguments we supply
// values list (bytes #32 .. #32+4*num_values) in order of corresponding bits TODO: it's actually not 4*num. Some values are 4b ytes, some - 1 byte
var vals = packValueMask('CreateWindow', values);
var packetLength = 8 + (values ? vals[2].length : 0);
var args = [1, depth, packetLength, id, parentId, x, y, width, height, borderWidth, _class, visual];
format += vals[0];
args.push(vals[1]);
args = args.concat(vals[2]);
return [format, args];
}
|
javascript
|
function(id, parentId, x, y, width, height, borderWidth, depth, _class, visual, values) {
if (borderWidth === undefined)
borderWidth = 0;
if (depth === undefined)
depth = 0;
if (_class === undefined)
_class = 0;
if (visual === undefined)
visual = 0;
if (values === undefined)
values = {}
var format = 'CCSLLssSSSSLL';
// TODO: slice from function arguments?
// TODO: the code is a little bit mess
// additional values need to be packed in the following way:
// bitmask (bytes #24 to #31 in the packet) - 32 bit indicating what adittional arguments we supply
// values list (bytes #32 .. #32+4*num_values) in order of corresponding bits TODO: it's actually not 4*num. Some values are 4b ytes, some - 1 byte
var vals = packValueMask('CreateWindow', values);
var packetLength = 8 + (values ? vals[2].length : 0);
var args = [1, depth, packetLength, id, parentId, x, y, width, height, borderWidth, _class, visual];
format += vals[0];
args.push(vals[1]);
args = args.concat(vals[2]);
return [format, args];
}
|
[
"function",
"(",
"id",
",",
"parentId",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"borderWidth",
",",
"depth",
",",
"_class",
",",
"visual",
",",
"values",
")",
"{",
"if",
"(",
"borderWidth",
"===",
"undefined",
")",
"borderWidth",
"=",
"0",
";",
"if",
"(",
"depth",
"===",
"undefined",
")",
"depth",
"=",
"0",
";",
"if",
"(",
"_class",
"===",
"undefined",
")",
"_class",
"=",
"0",
";",
"if",
"(",
"visual",
"===",
"undefined",
")",
"visual",
"=",
"0",
";",
"if",
"(",
"values",
"===",
"undefined",
")",
"values",
"=",
"{",
"}",
"var",
"format",
"=",
"'CCSLLssSSSSLL'",
";",
"// TODO: slice from function arguments?",
"// TODO: the code is a little bit mess",
"// additional values need to be packed in the following way:",
"// bitmask (bytes #24 to #31 in the packet) - 32 bit indicating what adittional arguments we supply",
"// values list (bytes #32 .. #32+4*num_values) in order of corresponding bits TODO: it's actually not 4*num. Some values are 4b ytes, some - 1 byte",
"var",
"vals",
"=",
"packValueMask",
"(",
"'CreateWindow'",
",",
"values",
")",
";",
"var",
"packetLength",
"=",
"8",
"+",
"(",
"values",
"?",
"vals",
"[",
"2",
"]",
".",
"length",
":",
"0",
")",
";",
"var",
"args",
"=",
"[",
"1",
",",
"depth",
",",
"packetLength",
",",
"id",
",",
"parentId",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"borderWidth",
",",
"_class",
",",
"visual",
"]",
";",
"format",
"+=",
"vals",
"[",
"0",
"]",
";",
"args",
".",
"push",
"(",
"vals",
"[",
"1",
"]",
")",
";",
"args",
"=",
"args",
".",
"concat",
"(",
"vals",
"[",
"2",
"]",
")",
";",
"return",
"[",
"format",
",",
"args",
"]",
";",
"}"
] |
create request packet - function OR format string
|
[
"create",
"request",
"packet",
"-",
"function",
"OR",
"format",
"string"
] |
f6547d387617f833c038ea420ba9c2174f9d340b
|
https://github.com/sidorares/node-x11/blob/f6547d387617f833c038ea420ba9c2174f9d340b/lib/corereqs.js#L268-L297
|
|
17,907
|
nodejs/node-inspect
|
lib/internal/inspect_repl.js
|
leftPad
|
function leftPad(n, prefix, maxN) {
const s = n.toString();
const nchars = Math.max(2, String(maxN).length) + 1;
const nspaces = nchars - s.length - 1;
return prefix + ' '.repeat(nspaces) + s;
}
|
javascript
|
function leftPad(n, prefix, maxN) {
const s = n.toString();
const nchars = Math.max(2, String(maxN).length) + 1;
const nspaces = nchars - s.length - 1;
return prefix + ' '.repeat(nspaces) + s;
}
|
[
"function",
"leftPad",
"(",
"n",
",",
"prefix",
",",
"maxN",
")",
"{",
"const",
"s",
"=",
"n",
".",
"toString",
"(",
")",
";",
"const",
"nchars",
"=",
"Math",
".",
"max",
"(",
"2",
",",
"String",
"(",
"maxN",
")",
".",
"length",
")",
"+",
"1",
";",
"const",
"nspaces",
"=",
"nchars",
"-",
"s",
".",
"length",
"-",
"1",
";",
"return",
"prefix",
"+",
"' '",
".",
"repeat",
"(",
"nspaces",
")",
"+",
"s",
";",
"}"
] |
Adds spaces and prefix to number maxN is a maximum number we should have space for
|
[
"Adds",
"spaces",
"and",
"prefix",
"to",
"number",
"maxN",
"is",
"a",
"maximum",
"number",
"we",
"should",
"have",
"space",
"for"
] |
5def3292741334d8001737a1866efe93b7e15481
|
https://github.com/nodejs/node-inspect/blob/5def3292741334d8001737a1866efe93b7e15481/lib/internal/inspect_repl.js#L111-L117
|
17,908
|
nodejs/node-inspect
|
lib/internal/inspect_repl.js
|
list
|
function list(delta = 5) {
return selectedFrame.list(delta)
.then(null, (error) => {
print('You can\'t list source code right now');
throw error;
});
}
|
javascript
|
function list(delta = 5) {
return selectedFrame.list(delta)
.then(null, (error) => {
print('You can\'t list source code right now');
throw error;
});
}
|
[
"function",
"list",
"(",
"delta",
"=",
"5",
")",
"{",
"return",
"selectedFrame",
".",
"list",
"(",
"delta",
")",
".",
"then",
"(",
"null",
",",
"(",
"error",
")",
"=>",
"{",
"print",
"(",
"'You can\\'t list source code right now'",
")",
";",
"throw",
"error",
";",
"}",
")",
";",
"}"
] |
List source code
|
[
"List",
"source",
"code"
] |
5def3292741334d8001737a1866efe93b7e15481
|
https://github.com/nodejs/node-inspect/blob/5def3292741334d8001737a1866efe93b7e15481/lib/internal/inspect_repl.js#L587-L593
|
17,909
|
nodejs/node-inspect
|
tools/eslint-rules/required-modules.js
|
getRequiredModuleName
|
function getRequiredModuleName(node) {
var moduleName;
// node has arguments and first argument is string
if (node.arguments.length && isString(node.arguments[0])) {
var argValue = path.basename(node.arguments[0].value.trim());
// check if value is in required modules array
if (requiredModules.indexOf(argValue) !== -1) {
moduleName = argValue;
}
}
return moduleName;
}
|
javascript
|
function getRequiredModuleName(node) {
var moduleName;
// node has arguments and first argument is string
if (node.arguments.length && isString(node.arguments[0])) {
var argValue = path.basename(node.arguments[0].value.trim());
// check if value is in required modules array
if (requiredModules.indexOf(argValue) !== -1) {
moduleName = argValue;
}
}
return moduleName;
}
|
[
"function",
"getRequiredModuleName",
"(",
"node",
")",
"{",
"var",
"moduleName",
";",
"// node has arguments and first argument is string",
"if",
"(",
"node",
".",
"arguments",
".",
"length",
"&&",
"isString",
"(",
"node",
".",
"arguments",
"[",
"0",
"]",
")",
")",
"{",
"var",
"argValue",
"=",
"path",
".",
"basename",
"(",
"node",
".",
"arguments",
"[",
"0",
"]",
".",
"value",
".",
"trim",
"(",
")",
")",
";",
"// check if value is in required modules array",
"if",
"(",
"requiredModules",
".",
"indexOf",
"(",
"argValue",
")",
"!==",
"-",
"1",
")",
"{",
"moduleName",
"=",
"argValue",
";",
"}",
"}",
"return",
"moduleName",
";",
"}"
] |
Function to check if a node has an argument that is a required module and
return its name.
@param {ASTNode} node The node to check
@returns {undefined|String} required module name or undefined
|
[
"Function",
"to",
"check",
"if",
"a",
"node",
"has",
"an",
"argument",
"that",
"is",
"a",
"required",
"module",
"and",
"return",
"its",
"name",
"."
] |
5def3292741334d8001737a1866efe93b7e15481
|
https://github.com/nodejs/node-inspect/blob/5def3292741334d8001737a1866efe93b7e15481/tools/eslint-rules/required-modules.js#L48-L62
|
17,910
|
guyht/notp
|
index.js
|
intToBytes
|
function intToBytes(num) {
var bytes = [];
for(var i=7 ; i>=0 ; --i) {
bytes[i] = num & (255);
num = num >> 8;
}
return bytes;
}
|
javascript
|
function intToBytes(num) {
var bytes = [];
for(var i=7 ; i>=0 ; --i) {
bytes[i] = num & (255);
num = num >> 8;
}
return bytes;
}
|
[
"function",
"intToBytes",
"(",
"num",
")",
"{",
"var",
"bytes",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"7",
";",
"i",
">=",
"0",
";",
"--",
"i",
")",
"{",
"bytes",
"[",
"i",
"]",
"=",
"num",
"&",
"(",
"255",
")",
";",
"num",
"=",
"num",
">>",
"8",
";",
"}",
"return",
"bytes",
";",
"}"
] |
convert an integer to a byte array
@param {Integer} num
@return {Array} bytes
|
[
"convert",
"an",
"integer",
"to",
"a",
"byte",
"array"
] |
bbdf82a34e5cb1534c411aaa63185bfab29feba0
|
https://github.com/guyht/notp/blob/bbdf82a34e5cb1534c411aaa63185bfab29feba0/index.js#L10-L19
|
17,911
|
guyht/notp
|
index.js
|
hexToBytes
|
function hexToBytes(hex) {
var bytes = [];
for(var c = 0, C = hex.length; c < C; c += 2) {
bytes.push(parseInt(hex.substr(c, 2), 16));
}
return bytes;
}
|
javascript
|
function hexToBytes(hex) {
var bytes = [];
for(var c = 0, C = hex.length; c < C; c += 2) {
bytes.push(parseInt(hex.substr(c, 2), 16));
}
return bytes;
}
|
[
"function",
"hexToBytes",
"(",
"hex",
")",
"{",
"var",
"bytes",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"c",
"=",
"0",
",",
"C",
"=",
"hex",
".",
"length",
";",
"c",
"<",
"C",
";",
"c",
"+=",
"2",
")",
"{",
"bytes",
".",
"push",
"(",
"parseInt",
"(",
"hex",
".",
"substr",
"(",
"c",
",",
"2",
")",
",",
"16",
")",
")",
";",
"}",
"return",
"bytes",
";",
"}"
] |
convert a hex value to a byte array
@param {String} hex string of hex to convert to a byte array
@return {Array} bytes
|
[
"convert",
"a",
"hex",
"value",
"to",
"a",
"byte",
"array"
] |
bbdf82a34e5cb1534c411aaa63185bfab29feba0
|
https://github.com/guyht/notp/blob/bbdf82a34e5cb1534c411aaa63185bfab29feba0/index.js#L26-L32
|
17,912
|
wooorm/refractor
|
lang/markup.js
|
addInlined
|
function addInlined(tagName, lang) {
var includedCdataInside = {}
includedCdataInside['language-' + lang] = {
pattern: /(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,
lookbehind: true,
inside: Prism.languages[lang]
}
includedCdataInside['cdata'] = /^<!\[CDATA\[|\]\]>$/i
var inside = {
'included-cdata': {
pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
inside: includedCdataInside
}
}
inside['language-' + lang] = {
pattern: /[\s\S]+/,
inside: Prism.languages[lang]
}
var def = {}
def[tagName] = {
pattern: RegExp(
/(<__[\s\S]*?>)(?:<!\[CDATA\[[\s\S]*?\]\]>\s*|[\s\S])*?(?=<\/__>)/.source.replace(
/__/g,
tagName
),
'i'
),
lookbehind: true,
greedy: true,
inside: inside
}
Prism.languages.insertBefore('markup', 'cdata', def)
}
|
javascript
|
function addInlined(tagName, lang) {
var includedCdataInside = {}
includedCdataInside['language-' + lang] = {
pattern: /(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,
lookbehind: true,
inside: Prism.languages[lang]
}
includedCdataInside['cdata'] = /^<!\[CDATA\[|\]\]>$/i
var inside = {
'included-cdata': {
pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
inside: includedCdataInside
}
}
inside['language-' + lang] = {
pattern: /[\s\S]+/,
inside: Prism.languages[lang]
}
var def = {}
def[tagName] = {
pattern: RegExp(
/(<__[\s\S]*?>)(?:<!\[CDATA\[[\s\S]*?\]\]>\s*|[\s\S])*?(?=<\/__>)/.source.replace(
/__/g,
tagName
),
'i'
),
lookbehind: true,
greedy: true,
inside: inside
}
Prism.languages.insertBefore('markup', 'cdata', def)
}
|
[
"function",
"addInlined",
"(",
"tagName",
",",
"lang",
")",
"{",
"var",
"includedCdataInside",
"=",
"{",
"}",
"includedCdataInside",
"[",
"'language-'",
"+",
"lang",
"]",
"=",
"{",
"pattern",
":",
"/",
"(^<!\\[CDATA\\[)[\\s\\S]+?(?=\\]\\]>$)",
"/",
"i",
",",
"lookbehind",
":",
"true",
",",
"inside",
":",
"Prism",
".",
"languages",
"[",
"lang",
"]",
"}",
"includedCdataInside",
"[",
"'cdata'",
"]",
"=",
"/",
"^<!\\[CDATA\\[|\\]\\]>$",
"/",
"i",
"var",
"inside",
"=",
"{",
"'included-cdata'",
":",
"{",
"pattern",
":",
"/",
"<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",
"/",
"i",
",",
"inside",
":",
"includedCdataInside",
"}",
"}",
"inside",
"[",
"'language-'",
"+",
"lang",
"]",
"=",
"{",
"pattern",
":",
"/",
"[\\s\\S]+",
"/",
",",
"inside",
":",
"Prism",
".",
"languages",
"[",
"lang",
"]",
"}",
"var",
"def",
"=",
"{",
"}",
"def",
"[",
"tagName",
"]",
"=",
"{",
"pattern",
":",
"RegExp",
"(",
"/",
"(<__[\\s\\S]*?>)(?:<!\\[CDATA\\[[\\s\\S]*?\\]\\]>\\s*|[\\s\\S])*?(?=<\\/__>)",
"/",
".",
"source",
".",
"replace",
"(",
"/",
"__",
"/",
"g",
",",
"tagName",
")",
",",
"'i'",
")",
",",
"lookbehind",
":",
"true",
",",
"greedy",
":",
"true",
",",
"inside",
":",
"inside",
"}",
"Prism",
".",
"languages",
".",
"insertBefore",
"(",
"'markup'",
",",
"'cdata'",
",",
"def",
")",
"}"
] |
Adds an inlined language to markup.
An example of an inlined language is CSS with `<style>` tags.
@param {string} tagName The name of the tag that contains the inlined language. This name will be treated as
case insensitive.
@param {string} lang The language key.
@example
addInlined('style', 'css');
|
[
"Adds",
"an",
"inlined",
"language",
"to",
"markup",
"."
] |
2fc340f19b83b88c511822f8989a20d5f3a0b192
|
https://github.com/wooorm/refractor/blob/2fc340f19b83b88c511822f8989a20d5f3a0b192/lang/markup.js#L66-L98
|
17,913
|
wooorm/refractor
|
lang/markup-templating.js
|
function(env, language, placeholderPattern, replaceFilter) {
if (env.language !== language) {
return
}
var tokenStack = (env.tokenStack = [])
env.code = env.code.replace(placeholderPattern, function(match) {
if (typeof replaceFilter === 'function' && !replaceFilter(match)) {
return match
}
var i = tokenStack.length
var placeholder
// Check for existing strings
while (
env.code.indexOf((placeholder = getPlaceholder(language, i))) !==
-1
)
++i
// Create a sparse array
tokenStack[i] = match
return placeholder
})
// Switch the grammar to markup
env.grammar = Prism.languages.markup
}
|
javascript
|
function(env, language, placeholderPattern, replaceFilter) {
if (env.language !== language) {
return
}
var tokenStack = (env.tokenStack = [])
env.code = env.code.replace(placeholderPattern, function(match) {
if (typeof replaceFilter === 'function' && !replaceFilter(match)) {
return match
}
var i = tokenStack.length
var placeholder
// Check for existing strings
while (
env.code.indexOf((placeholder = getPlaceholder(language, i))) !==
-1
)
++i
// Create a sparse array
tokenStack[i] = match
return placeholder
})
// Switch the grammar to markup
env.grammar = Prism.languages.markup
}
|
[
"function",
"(",
"env",
",",
"language",
",",
"placeholderPattern",
",",
"replaceFilter",
")",
"{",
"if",
"(",
"env",
".",
"language",
"!==",
"language",
")",
"{",
"return",
"}",
"var",
"tokenStack",
"=",
"(",
"env",
".",
"tokenStack",
"=",
"[",
"]",
")",
"env",
".",
"code",
"=",
"env",
".",
"code",
".",
"replace",
"(",
"placeholderPattern",
",",
"function",
"(",
"match",
")",
"{",
"if",
"(",
"typeof",
"replaceFilter",
"===",
"'function'",
"&&",
"!",
"replaceFilter",
"(",
"match",
")",
")",
"{",
"return",
"match",
"}",
"var",
"i",
"=",
"tokenStack",
".",
"length",
"var",
"placeholder",
"// Check for existing strings",
"while",
"(",
"env",
".",
"code",
".",
"indexOf",
"(",
"(",
"placeholder",
"=",
"getPlaceholder",
"(",
"language",
",",
"i",
")",
")",
")",
"!==",
"-",
"1",
")",
"++",
"i",
"// Create a sparse array",
"tokenStack",
"[",
"i",
"]",
"=",
"match",
"return",
"placeholder",
"}",
")",
"// Switch the grammar to markup",
"env",
".",
"grammar",
"=",
"Prism",
".",
"languages",
".",
"markup",
"}"
] |
Tokenize all inline templating expressions matching `placeholderPattern`.
If `replaceFilter` is provided, only matches of `placeholderPattern` for which `replaceFilter` returns
`true` will be replaced.
@param {object} env The environment of the `before-tokenize` hook.
@param {string} language The language id.
@param {RegExp} placeholderPattern The matches of this pattern will be replaced by placeholders.
@param {(match: string) => boolean} [replaceFilter]
|
[
"Tokenize",
"all",
"inline",
"templating",
"expressions",
"matching",
"placeholderPattern",
"."
] |
2fc340f19b83b88c511822f8989a20d5f3a0b192
|
https://github.com/wooorm/refractor/blob/2fc340f19b83b88c511822f8989a20d5f3a0b192/lang/markup-templating.js#L31-L54
|
|
17,914
|
wooorm/refractor
|
lang/markup-templating.js
|
function(env, language) {
if (env.language !== language || !env.tokenStack) {
return
}
// Switch the grammar back
env.grammar = Prism.languages[language]
var j = 0
var keys = Object.keys(env.tokenStack)
function walkTokens(tokens) {
for (var i = 0; i < tokens.length; i++) {
// all placeholders are replaced already
if (j >= keys.length) {
break
}
var token = tokens[i]
if (
typeof token === 'string' ||
(token.content && typeof token.content === 'string')
) {
var k = keys[j]
var t = env.tokenStack[k]
var s = typeof token === 'string' ? token : token.content
var placeholder = getPlaceholder(language, k)
var index = s.indexOf(placeholder)
if (index > -1) {
++j
var before = s.substring(0, index)
var middle = new Prism.Token(
language,
Prism.tokenize(t, env.grammar),
'language-' + language,
t
)
var after = s.substring(index + placeholder.length)
var replacement = []
if (before) {
replacement.push.apply(replacement, walkTokens([before]))
}
replacement.push(middle)
if (after) {
replacement.push.apply(replacement, walkTokens([after]))
}
if (typeof token === 'string') {
tokens.splice.apply(tokens, [i, 1].concat(replacement))
} else {
token.content = replacement
}
}
} else if (
token.content /* && typeof token.content !== 'string' */
) {
walkTokens(token.content)
}
}
return tokens
}
walkTokens(env.tokens)
}
|
javascript
|
function(env, language) {
if (env.language !== language || !env.tokenStack) {
return
}
// Switch the grammar back
env.grammar = Prism.languages[language]
var j = 0
var keys = Object.keys(env.tokenStack)
function walkTokens(tokens) {
for (var i = 0; i < tokens.length; i++) {
// all placeholders are replaced already
if (j >= keys.length) {
break
}
var token = tokens[i]
if (
typeof token === 'string' ||
(token.content && typeof token.content === 'string')
) {
var k = keys[j]
var t = env.tokenStack[k]
var s = typeof token === 'string' ? token : token.content
var placeholder = getPlaceholder(language, k)
var index = s.indexOf(placeholder)
if (index > -1) {
++j
var before = s.substring(0, index)
var middle = new Prism.Token(
language,
Prism.tokenize(t, env.grammar),
'language-' + language,
t
)
var after = s.substring(index + placeholder.length)
var replacement = []
if (before) {
replacement.push.apply(replacement, walkTokens([before]))
}
replacement.push(middle)
if (after) {
replacement.push.apply(replacement, walkTokens([after]))
}
if (typeof token === 'string') {
tokens.splice.apply(tokens, [i, 1].concat(replacement))
} else {
token.content = replacement
}
}
} else if (
token.content /* && typeof token.content !== 'string' */
) {
walkTokens(token.content)
}
}
return tokens
}
walkTokens(env.tokens)
}
|
[
"function",
"(",
"env",
",",
"language",
")",
"{",
"if",
"(",
"env",
".",
"language",
"!==",
"language",
"||",
"!",
"env",
".",
"tokenStack",
")",
"{",
"return",
"}",
"// Switch the grammar back",
"env",
".",
"grammar",
"=",
"Prism",
".",
"languages",
"[",
"language",
"]",
"var",
"j",
"=",
"0",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"env",
".",
"tokenStack",
")",
"function",
"walkTokens",
"(",
"tokens",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"tokens",
".",
"length",
";",
"i",
"++",
")",
"{",
"// all placeholders are replaced already",
"if",
"(",
"j",
">=",
"keys",
".",
"length",
")",
"{",
"break",
"}",
"var",
"token",
"=",
"tokens",
"[",
"i",
"]",
"if",
"(",
"typeof",
"token",
"===",
"'string'",
"||",
"(",
"token",
".",
"content",
"&&",
"typeof",
"token",
".",
"content",
"===",
"'string'",
")",
")",
"{",
"var",
"k",
"=",
"keys",
"[",
"j",
"]",
"var",
"t",
"=",
"env",
".",
"tokenStack",
"[",
"k",
"]",
"var",
"s",
"=",
"typeof",
"token",
"===",
"'string'",
"?",
"token",
":",
"token",
".",
"content",
"var",
"placeholder",
"=",
"getPlaceholder",
"(",
"language",
",",
"k",
")",
"var",
"index",
"=",
"s",
".",
"indexOf",
"(",
"placeholder",
")",
"if",
"(",
"index",
">",
"-",
"1",
")",
"{",
"++",
"j",
"var",
"before",
"=",
"s",
".",
"substring",
"(",
"0",
",",
"index",
")",
"var",
"middle",
"=",
"new",
"Prism",
".",
"Token",
"(",
"language",
",",
"Prism",
".",
"tokenize",
"(",
"t",
",",
"env",
".",
"grammar",
")",
",",
"'language-'",
"+",
"language",
",",
"t",
")",
"var",
"after",
"=",
"s",
".",
"substring",
"(",
"index",
"+",
"placeholder",
".",
"length",
")",
"var",
"replacement",
"=",
"[",
"]",
"if",
"(",
"before",
")",
"{",
"replacement",
".",
"push",
".",
"apply",
"(",
"replacement",
",",
"walkTokens",
"(",
"[",
"before",
"]",
")",
")",
"}",
"replacement",
".",
"push",
"(",
"middle",
")",
"if",
"(",
"after",
")",
"{",
"replacement",
".",
"push",
".",
"apply",
"(",
"replacement",
",",
"walkTokens",
"(",
"[",
"after",
"]",
")",
")",
"}",
"if",
"(",
"typeof",
"token",
"===",
"'string'",
")",
"{",
"tokens",
".",
"splice",
".",
"apply",
"(",
"tokens",
",",
"[",
"i",
",",
"1",
"]",
".",
"concat",
"(",
"replacement",
")",
")",
"}",
"else",
"{",
"token",
".",
"content",
"=",
"replacement",
"}",
"}",
"}",
"else",
"if",
"(",
"token",
".",
"content",
"/* && typeof token.content !== 'string' */",
")",
"{",
"walkTokens",
"(",
"token",
".",
"content",
")",
"}",
"}",
"return",
"tokens",
"}",
"walkTokens",
"(",
"env",
".",
"tokens",
")",
"}"
] |
Replace placeholders with proper tokens after tokenizing.
@param {object} env The environment of the `after-tokenize` hook.
@param {string} language The language id.
|
[
"Replace",
"placeholders",
"with",
"proper",
"tokens",
"after",
"tokenizing",
"."
] |
2fc340f19b83b88c511822f8989a20d5f3a0b192
|
https://github.com/wooorm/refractor/blob/2fc340f19b83b88c511822f8989a20d5f3a0b192/lang/markup-templating.js#L63-L120
|
|
17,915
|
antvis/hierarchy
|
src/layout/non-layered-tidy.js
|
WrappedTree
|
function WrappedTree(w, h, y, c = []) {
const me = this;
// size
me.w = w || 0;
me.h = h || 0;
// position
me.y = y || 0;
me.x = 0;
// children
me.c = c || [];
me.cs = c.length;
// modified
me.prelim = 0;
me.mod = 0;
me.shift = 0;
me.change = 0;
// left/right tree
me.tl = null;
me.tr = null;
// extreme left/right tree
me.el = null;
me.er = null;
// modified left/right tree
me.msel = 0;
me.mser = 0;
}
|
javascript
|
function WrappedTree(w, h, y, c = []) {
const me = this;
// size
me.w = w || 0;
me.h = h || 0;
// position
me.y = y || 0;
me.x = 0;
// children
me.c = c || [];
me.cs = c.length;
// modified
me.prelim = 0;
me.mod = 0;
me.shift = 0;
me.change = 0;
// left/right tree
me.tl = null;
me.tr = null;
// extreme left/right tree
me.el = null;
me.er = null;
// modified left/right tree
me.msel = 0;
me.mser = 0;
}
|
[
"function",
"WrappedTree",
"(",
"w",
",",
"h",
",",
"y",
",",
"c",
"=",
"[",
"]",
")",
"{",
"const",
"me",
"=",
"this",
";",
"// size",
"me",
".",
"w",
"=",
"w",
"||",
"0",
";",
"me",
".",
"h",
"=",
"h",
"||",
"0",
";",
"// position",
"me",
".",
"y",
"=",
"y",
"||",
"0",
";",
"me",
".",
"x",
"=",
"0",
";",
"// children",
"me",
".",
"c",
"=",
"c",
"||",
"[",
"]",
";",
"me",
".",
"cs",
"=",
"c",
".",
"length",
";",
"// modified",
"me",
".",
"prelim",
"=",
"0",
";",
"me",
".",
"mod",
"=",
"0",
";",
"me",
".",
"shift",
"=",
"0",
";",
"me",
".",
"change",
"=",
"0",
";",
"// left/right tree",
"me",
".",
"tl",
"=",
"null",
";",
"me",
".",
"tr",
"=",
"null",
";",
"// extreme left/right tree",
"me",
".",
"el",
"=",
"null",
";",
"me",
".",
"er",
"=",
"null",
";",
"// modified left/right tree",
"me",
".",
"msel",
"=",
"0",
";",
"me",
".",
"mser",
"=",
"0",
";",
"}"
] |
wrap tree node
|
[
"wrap",
"tree",
"node"
] |
27e4c75e5ff08a373f82d0ae2ba17a3beadd2cd2
|
https://github.com/antvis/hierarchy/blob/27e4c75e5ff08a373f82d0ae2ba17a3beadd2cd2/src/layout/non-layered-tidy.js#L2-L33
|
17,916
|
uber/npm-shrinkwrap
|
trim-and-sort-shrinkwrap.js
|
sortedKeys
|
function sortedKeys(obj, orderedKeys) {
var keys = Object.keys(obj).sort();
var fresh = {};
orderedKeys.forEach(function (key) {
if (keys.indexOf(key) === -1) {
return;
}
fresh[key] = obj[key];
});
keys.forEach(function (key) {
if (orderedKeys.indexOf(key) !== -1) {
return;
}
fresh[key] = obj[key];
});
return fresh;
}
|
javascript
|
function sortedKeys(obj, orderedKeys) {
var keys = Object.keys(obj).sort();
var fresh = {};
orderedKeys.forEach(function (key) {
if (keys.indexOf(key) === -1) {
return;
}
fresh[key] = obj[key];
});
keys.forEach(function (key) {
if (orderedKeys.indexOf(key) !== -1) {
return;
}
fresh[key] = obj[key];
});
return fresh;
}
|
[
"function",
"sortedKeys",
"(",
"obj",
",",
"orderedKeys",
")",
"{",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"obj",
")",
".",
"sort",
"(",
")",
";",
"var",
"fresh",
"=",
"{",
"}",
";",
"orderedKeys",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"keys",
".",
"indexOf",
"(",
"key",
")",
"===",
"-",
"1",
")",
"{",
"return",
";",
"}",
"fresh",
"[",
"key",
"]",
"=",
"obj",
"[",
"key",
"]",
";",
"}",
")",
";",
"keys",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"orderedKeys",
".",
"indexOf",
"(",
"key",
")",
"!==",
"-",
"1",
")",
"{",
"return",
";",
"}",
"fresh",
"[",
"key",
"]",
"=",
"obj",
"[",
"key",
"]",
";",
"}",
")",
";",
"return",
"fresh",
";",
"}"
] |
set keys in an order
|
[
"set",
"keys",
"in",
"an",
"order"
] |
21c8fab10259b599fc8e443ab41d3a3c85545069
|
https://github.com/uber/npm-shrinkwrap/blob/21c8fab10259b599fc8e443ab41d3a3c85545069/trim-and-sort-shrinkwrap.js#L14-L35
|
17,917
|
visionmedia/bytes.js
|
index.js
|
bytes
|
function bytes(value, options) {
if (typeof value === 'string') {
return parse(value);
}
if (typeof value === 'number') {
return format(value, options);
}
return null;
}
|
javascript
|
function bytes(value, options) {
if (typeof value === 'string') {
return parse(value);
}
if (typeof value === 'number') {
return format(value, options);
}
return null;
}
|
[
"function",
"bytes",
"(",
"value",
",",
"options",
")",
"{",
"if",
"(",
"typeof",
"value",
"===",
"'string'",
")",
"{",
"return",
"parse",
"(",
"value",
")",
";",
"}",
"if",
"(",
"typeof",
"value",
"===",
"'number'",
")",
"{",
"return",
"format",
"(",
"value",
",",
"options",
")",
";",
"}",
"return",
"null",
";",
"}"
] |
Convert the given value in bytes into a string or parse to string to an integer in bytes.
@param {string|number} value
@param {{
case: [string],
decimalPlaces: [number]
fixedDecimals: [boolean]
thousandsSeparator: [string]
unitSeparator: [string]
}} [options] bytes options.
@returns {string|number|null}
|
[
"Convert",
"the",
"given",
"value",
"in",
"bytes",
"into",
"a",
"string",
"or",
"parse",
"to",
"string",
"to",
"an",
"integer",
"in",
"bytes",
"."
] |
804a840d71302f9b07bd544a02654fa9ec90a1e4
|
https://github.com/visionmedia/bytes.js/blob/804a840d71302f9b07bd544a02654fa9ec90a1e4/index.js#L54-L64
|
17,918
|
visionmedia/bytes.js
|
index.js
|
format
|
function format(value, options) {
if (!Number.isFinite(value)) {
return null;
}
var mag = Math.abs(value);
var thousandsSeparator = (options && options.thousandsSeparator) || '';
var unitSeparator = (options && options.unitSeparator) || '';
var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2;
var fixedDecimals = Boolean(options && options.fixedDecimals);
var unit = (options && options.unit) || '';
if (!unit || !map[unit.toLowerCase()]) {
if (mag >= map.pb) {
unit = 'PB';
} else if (mag >= map.tb) {
unit = 'TB';
} else if (mag >= map.gb) {
unit = 'GB';
} else if (mag >= map.mb) {
unit = 'MB';
} else if (mag >= map.kb) {
unit = 'KB';
} else {
unit = 'B';
}
}
var val = value / map[unit.toLowerCase()];
var str = val.toFixed(decimalPlaces);
if (!fixedDecimals) {
str = str.replace(formatDecimalsRegExp, '$1');
}
if (thousandsSeparator) {
str = str.replace(formatThousandsRegExp, thousandsSeparator);
}
return str + unitSeparator + unit;
}
|
javascript
|
function format(value, options) {
if (!Number.isFinite(value)) {
return null;
}
var mag = Math.abs(value);
var thousandsSeparator = (options && options.thousandsSeparator) || '';
var unitSeparator = (options && options.unitSeparator) || '';
var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2;
var fixedDecimals = Boolean(options && options.fixedDecimals);
var unit = (options && options.unit) || '';
if (!unit || !map[unit.toLowerCase()]) {
if (mag >= map.pb) {
unit = 'PB';
} else if (mag >= map.tb) {
unit = 'TB';
} else if (mag >= map.gb) {
unit = 'GB';
} else if (mag >= map.mb) {
unit = 'MB';
} else if (mag >= map.kb) {
unit = 'KB';
} else {
unit = 'B';
}
}
var val = value / map[unit.toLowerCase()];
var str = val.toFixed(decimalPlaces);
if (!fixedDecimals) {
str = str.replace(formatDecimalsRegExp, '$1');
}
if (thousandsSeparator) {
str = str.replace(formatThousandsRegExp, thousandsSeparator);
}
return str + unitSeparator + unit;
}
|
[
"function",
"format",
"(",
"value",
",",
"options",
")",
"{",
"if",
"(",
"!",
"Number",
".",
"isFinite",
"(",
"value",
")",
")",
"{",
"return",
"null",
";",
"}",
"var",
"mag",
"=",
"Math",
".",
"abs",
"(",
"value",
")",
";",
"var",
"thousandsSeparator",
"=",
"(",
"options",
"&&",
"options",
".",
"thousandsSeparator",
")",
"||",
"''",
";",
"var",
"unitSeparator",
"=",
"(",
"options",
"&&",
"options",
".",
"unitSeparator",
")",
"||",
"''",
";",
"var",
"decimalPlaces",
"=",
"(",
"options",
"&&",
"options",
".",
"decimalPlaces",
"!==",
"undefined",
")",
"?",
"options",
".",
"decimalPlaces",
":",
"2",
";",
"var",
"fixedDecimals",
"=",
"Boolean",
"(",
"options",
"&&",
"options",
".",
"fixedDecimals",
")",
";",
"var",
"unit",
"=",
"(",
"options",
"&&",
"options",
".",
"unit",
")",
"||",
"''",
";",
"if",
"(",
"!",
"unit",
"||",
"!",
"map",
"[",
"unit",
".",
"toLowerCase",
"(",
")",
"]",
")",
"{",
"if",
"(",
"mag",
">=",
"map",
".",
"pb",
")",
"{",
"unit",
"=",
"'PB'",
";",
"}",
"else",
"if",
"(",
"mag",
">=",
"map",
".",
"tb",
")",
"{",
"unit",
"=",
"'TB'",
";",
"}",
"else",
"if",
"(",
"mag",
">=",
"map",
".",
"gb",
")",
"{",
"unit",
"=",
"'GB'",
";",
"}",
"else",
"if",
"(",
"mag",
">=",
"map",
".",
"mb",
")",
"{",
"unit",
"=",
"'MB'",
";",
"}",
"else",
"if",
"(",
"mag",
">=",
"map",
".",
"kb",
")",
"{",
"unit",
"=",
"'KB'",
";",
"}",
"else",
"{",
"unit",
"=",
"'B'",
";",
"}",
"}",
"var",
"val",
"=",
"value",
"/",
"map",
"[",
"unit",
".",
"toLowerCase",
"(",
")",
"]",
";",
"var",
"str",
"=",
"val",
".",
"toFixed",
"(",
"decimalPlaces",
")",
";",
"if",
"(",
"!",
"fixedDecimals",
")",
"{",
"str",
"=",
"str",
".",
"replace",
"(",
"formatDecimalsRegExp",
",",
"'$1'",
")",
";",
"}",
"if",
"(",
"thousandsSeparator",
")",
"{",
"str",
"=",
"str",
".",
"replace",
"(",
"formatThousandsRegExp",
",",
"thousandsSeparator",
")",
";",
"}",
"return",
"str",
"+",
"unitSeparator",
"+",
"unit",
";",
"}"
] |
Format the given value in bytes into a string.
If the value is negative, it is kept as such. If it is a float,
it is rounded.
@param {number} value
@param {object} [options]
@param {number} [options.decimalPlaces=2]
@param {number} [options.fixedDecimals=false]
@param {string} [options.thousandsSeparator=]
@param {string} [options.unit=]
@param {string} [options.unitSeparator=]
@returns {string|null}
@public
|
[
"Format",
"the",
"given",
"value",
"in",
"bytes",
"into",
"a",
"string",
"."
] |
804a840d71302f9b07bd544a02654fa9ec90a1e4
|
https://github.com/visionmedia/bytes.js/blob/804a840d71302f9b07bd544a02654fa9ec90a1e4/index.js#L84-L124
|
17,919
|
visionmedia/bytes.js
|
index.js
|
parse
|
function parse(val) {
if (typeof val === 'number' && !isNaN(val)) {
return val;
}
if (typeof val !== 'string') {
return null;
}
// Test if the string passed is valid
var results = parseRegExp.exec(val);
var floatValue;
var unit = 'b';
if (!results) {
// Nothing could be extracted from the given string
floatValue = parseInt(val, 10);
unit = 'b'
} else {
// Retrieve the value and the unit
floatValue = parseFloat(results[1]);
unit = results[4].toLowerCase();
}
return Math.floor(map[unit] * floatValue);
}
|
javascript
|
function parse(val) {
if (typeof val === 'number' && !isNaN(val)) {
return val;
}
if (typeof val !== 'string') {
return null;
}
// Test if the string passed is valid
var results = parseRegExp.exec(val);
var floatValue;
var unit = 'b';
if (!results) {
// Nothing could be extracted from the given string
floatValue = parseInt(val, 10);
unit = 'b'
} else {
// Retrieve the value and the unit
floatValue = parseFloat(results[1]);
unit = results[4].toLowerCase();
}
return Math.floor(map[unit] * floatValue);
}
|
[
"function",
"parse",
"(",
"val",
")",
"{",
"if",
"(",
"typeof",
"val",
"===",
"'number'",
"&&",
"!",
"isNaN",
"(",
"val",
")",
")",
"{",
"return",
"val",
";",
"}",
"if",
"(",
"typeof",
"val",
"!==",
"'string'",
")",
"{",
"return",
"null",
";",
"}",
"// Test if the string passed is valid",
"var",
"results",
"=",
"parseRegExp",
".",
"exec",
"(",
"val",
")",
";",
"var",
"floatValue",
";",
"var",
"unit",
"=",
"'b'",
";",
"if",
"(",
"!",
"results",
")",
"{",
"// Nothing could be extracted from the given string",
"floatValue",
"=",
"parseInt",
"(",
"val",
",",
"10",
")",
";",
"unit",
"=",
"'b'",
"}",
"else",
"{",
"// Retrieve the value and the unit",
"floatValue",
"=",
"parseFloat",
"(",
"results",
"[",
"1",
"]",
")",
";",
"unit",
"=",
"results",
"[",
"4",
"]",
".",
"toLowerCase",
"(",
")",
";",
"}",
"return",
"Math",
".",
"floor",
"(",
"map",
"[",
"unit",
"]",
"*",
"floatValue",
")",
";",
"}"
] |
Parse the string value into an integer in bytes.
If no unit is given, it is assumed the value is in bytes.
@param {number|string} val
@returns {number|null}
@public
|
[
"Parse",
"the",
"string",
"value",
"into",
"an",
"integer",
"in",
"bytes",
"."
] |
804a840d71302f9b07bd544a02654fa9ec90a1e4
|
https://github.com/visionmedia/bytes.js/blob/804a840d71302f9b07bd544a02654fa9ec90a1e4/index.js#L137-L162
|
17,920
|
lambdabaa/dav
|
dav.js
|
traverseChild
|
function traverseChild(node, childNode, childspec, result) {
if (childNode.nodeType === 3 && /^\s+$/.test(childNode.nodeValue)) {
// Whitespace... nothing to do.
return;
}
var localName = (0, _camelize2['default'])(childNode.localName, '-');
if (!(localName in childspec)) {
debug('Unexpected node of type ' + localName + ' encountered while ' + 'parsing ' + node.localName + ' node!');
var value = childNode.textContent;
if (localName in result) {
if (!Array.isArray(result[localName])) {
// Since we've already encountered this node type and we haven't yet
// made an array for it, make an array now.
result[localName] = [result[localName]];
}
result[localName].push(value);
return;
}
// First time we're encountering this node.
result[localName] = value;
return;
}
var traversal = traverse[localName](childNode);
if (childspec[localName]) {
// Expect multiple.
result[localName].push(traversal);
} else {
// Expect single.
result[localName] = traversal;
}
}
|
javascript
|
function traverseChild(node, childNode, childspec, result) {
if (childNode.nodeType === 3 && /^\s+$/.test(childNode.nodeValue)) {
// Whitespace... nothing to do.
return;
}
var localName = (0, _camelize2['default'])(childNode.localName, '-');
if (!(localName in childspec)) {
debug('Unexpected node of type ' + localName + ' encountered while ' + 'parsing ' + node.localName + ' node!');
var value = childNode.textContent;
if (localName in result) {
if (!Array.isArray(result[localName])) {
// Since we've already encountered this node type and we haven't yet
// made an array for it, make an array now.
result[localName] = [result[localName]];
}
result[localName].push(value);
return;
}
// First time we're encountering this node.
result[localName] = value;
return;
}
var traversal = traverse[localName](childNode);
if (childspec[localName]) {
// Expect multiple.
result[localName].push(traversal);
} else {
// Expect single.
result[localName] = traversal;
}
}
|
[
"function",
"traverseChild",
"(",
"node",
",",
"childNode",
",",
"childspec",
",",
"result",
")",
"{",
"if",
"(",
"childNode",
".",
"nodeType",
"===",
"3",
"&&",
"/",
"^\\s+$",
"/",
".",
"test",
"(",
"childNode",
".",
"nodeValue",
")",
")",
"{",
"// Whitespace... nothing to do.",
"return",
";",
"}",
"var",
"localName",
"=",
"(",
"0",
",",
"_camelize2",
"[",
"'default'",
"]",
")",
"(",
"childNode",
".",
"localName",
",",
"'-'",
")",
";",
"if",
"(",
"!",
"(",
"localName",
"in",
"childspec",
")",
")",
"{",
"debug",
"(",
"'Unexpected node of type '",
"+",
"localName",
"+",
"' encountered while '",
"+",
"'parsing '",
"+",
"node",
".",
"localName",
"+",
"' node!'",
")",
";",
"var",
"value",
"=",
"childNode",
".",
"textContent",
";",
"if",
"(",
"localName",
"in",
"result",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"result",
"[",
"localName",
"]",
")",
")",
"{",
"// Since we've already encountered this node type and we haven't yet",
"// made an array for it, make an array now.",
"result",
"[",
"localName",
"]",
"=",
"[",
"result",
"[",
"localName",
"]",
"]",
";",
"}",
"result",
"[",
"localName",
"]",
".",
"push",
"(",
"value",
")",
";",
"return",
";",
"}",
"// First time we're encountering this node.",
"result",
"[",
"localName",
"]",
"=",
"value",
";",
"return",
";",
"}",
"var",
"traversal",
"=",
"traverse",
"[",
"localName",
"]",
"(",
"childNode",
")",
";",
"if",
"(",
"childspec",
"[",
"localName",
"]",
")",
"{",
"// Expect multiple.",
"result",
"[",
"localName",
"]",
".",
"push",
"(",
"traversal",
")",
";",
"}",
"else",
"{",
"// Expect single.",
"result",
"[",
"localName",
"]",
"=",
"traversal",
";",
"}",
"}"
] |
Parse child childNode of node with childspec and write outcome to result.
|
[
"Parse",
"child",
"childNode",
"of",
"node",
"with",
"childspec",
"and",
"write",
"outcome",
"to",
"result",
"."
] |
9c72a392dee7e307dfc2fe94e06a31f71469a18a
|
https://github.com/lambdabaa/dav/blob/9c72a392dee7e307dfc2fe94e06a31f71469a18a/dav.js#L2316-L2350
|
17,921
|
lambdabaa/dav
|
dav.js
|
co
|
function co(gen) {
var ctx = this;
var args = slice.call(arguments, 1)
// we wrap everything in a promise to avoid promise chaining,
// which leads to memory leak errors.
// see https://github.com/tj/co/issues/180
return new Promise(function(resolve, reject) {
if (typeof gen === 'function') gen = gen.apply(ctx, args);
if (!gen || typeof gen.next !== 'function') return resolve(gen);
onFulfilled();
/**
* @param {Mixed} res
* @return {Promise}
* @api private
*/
function onFulfilled(res) {
var ret;
try {
ret = gen.next(res);
} catch (e) {
return reject(e);
}
next(ret);
}
/**
* @param {Error} err
* @return {Promise}
* @api private
*/
function onRejected(err) {
var ret;
try {
ret = gen.throw(err);
} catch (e) {
return reject(e);
}
next(ret);
}
/**
* Get the next value in the generator,
* return a promise.
*
* @param {Object} ret
* @return {Promise}
* @api private
*/
function next(ret) {
if (ret.done) return resolve(ret.value);
var value = toPromise.call(ctx, ret.value);
if (value && isPromise(value)) return value.then(onFulfilled, onRejected);
return onRejected(new TypeError('You may only yield a function, promise, generator, array, or object, '
+ 'but the following object was passed: "' + String(ret.value) + '"'));
}
});
}
|
javascript
|
function co(gen) {
var ctx = this;
var args = slice.call(arguments, 1)
// we wrap everything in a promise to avoid promise chaining,
// which leads to memory leak errors.
// see https://github.com/tj/co/issues/180
return new Promise(function(resolve, reject) {
if (typeof gen === 'function') gen = gen.apply(ctx, args);
if (!gen || typeof gen.next !== 'function') return resolve(gen);
onFulfilled();
/**
* @param {Mixed} res
* @return {Promise}
* @api private
*/
function onFulfilled(res) {
var ret;
try {
ret = gen.next(res);
} catch (e) {
return reject(e);
}
next(ret);
}
/**
* @param {Error} err
* @return {Promise}
* @api private
*/
function onRejected(err) {
var ret;
try {
ret = gen.throw(err);
} catch (e) {
return reject(e);
}
next(ret);
}
/**
* Get the next value in the generator,
* return a promise.
*
* @param {Object} ret
* @return {Promise}
* @api private
*/
function next(ret) {
if (ret.done) return resolve(ret.value);
var value = toPromise.call(ctx, ret.value);
if (value && isPromise(value)) return value.then(onFulfilled, onRejected);
return onRejected(new TypeError('You may only yield a function, promise, generator, array, or object, '
+ 'but the following object was passed: "' + String(ret.value) + '"'));
}
});
}
|
[
"function",
"co",
"(",
"gen",
")",
"{",
"var",
"ctx",
"=",
"this",
";",
"var",
"args",
"=",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
"// we wrap everything in a promise to avoid promise chaining,",
"// which leads to memory leak errors.",
"// see https://github.com/tj/co/issues/180",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"if",
"(",
"typeof",
"gen",
"===",
"'function'",
")",
"gen",
"=",
"gen",
".",
"apply",
"(",
"ctx",
",",
"args",
")",
";",
"if",
"(",
"!",
"gen",
"||",
"typeof",
"gen",
".",
"next",
"!==",
"'function'",
")",
"return",
"resolve",
"(",
"gen",
")",
";",
"onFulfilled",
"(",
")",
";",
"/**\n * @param {Mixed} res\n * @return {Promise}\n * @api private\n */",
"function",
"onFulfilled",
"(",
"res",
")",
"{",
"var",
"ret",
";",
"try",
"{",
"ret",
"=",
"gen",
".",
"next",
"(",
"res",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"reject",
"(",
"e",
")",
";",
"}",
"next",
"(",
"ret",
")",
";",
"}",
"/**\n * @param {Error} err\n * @return {Promise}\n * @api private\n */",
"function",
"onRejected",
"(",
"err",
")",
"{",
"var",
"ret",
";",
"try",
"{",
"ret",
"=",
"gen",
".",
"throw",
"(",
"err",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"reject",
"(",
"e",
")",
";",
"}",
"next",
"(",
"ret",
")",
";",
"}",
"/**\n * Get the next value in the generator,\n * return a promise.\n *\n * @param {Object} ret\n * @return {Promise}\n * @api private\n */",
"function",
"next",
"(",
"ret",
")",
"{",
"if",
"(",
"ret",
".",
"done",
")",
"return",
"resolve",
"(",
"ret",
".",
"value",
")",
";",
"var",
"value",
"=",
"toPromise",
".",
"call",
"(",
"ctx",
",",
"ret",
".",
"value",
")",
";",
"if",
"(",
"value",
"&&",
"isPromise",
"(",
"value",
")",
")",
"return",
"value",
".",
"then",
"(",
"onFulfilled",
",",
"onRejected",
")",
";",
"return",
"onRejected",
"(",
"new",
"TypeError",
"(",
"'You may only yield a function, promise, generator, array, or object, '",
"+",
"'but the following object was passed: \"'",
"+",
"String",
"(",
"ret",
".",
"value",
")",
"+",
"'\"'",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Execute the generator function or a generator
and return a promise.
@param {Function} fn
@return {Promise}
@api public
|
[
"Execute",
"the",
"generator",
"function",
"or",
"a",
"generator",
"and",
"return",
"a",
"promise",
"."
] |
9c72a392dee7e307dfc2fe94e06a31f71469a18a
|
https://github.com/lambdabaa/dav/blob/9c72a392dee7e307dfc2fe94e06a31f71469a18a/dav.js#L3490-L3552
|
17,922
|
lambdabaa/dav
|
dav.js
|
ucs2encode
|
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
|
javascript
|
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
|
[
"function",
"ucs2encode",
"(",
"array",
")",
"{",
"return",
"map",
"(",
"array",
",",
"function",
"(",
"value",
")",
"{",
"var",
"output",
"=",
"''",
";",
"if",
"(",
"value",
">",
"0xFFFF",
")",
"{",
"value",
"-=",
"0x10000",
";",
"output",
"+=",
"stringFromCharCode",
"(",
"value",
">>>",
"10",
"&",
"0x3FF",
"|",
"0xD800",
")",
";",
"value",
"=",
"0xDC00",
"|",
"value",
"&",
"0x3FF",
";",
"}",
"output",
"+=",
"stringFromCharCode",
"(",
"value",
")",
";",
"return",
"output",
";",
"}",
")",
".",
"join",
"(",
"''",
")",
";",
"}"
] |
Creates a string based on an array of numeric code points.
@see `punycode.ucs2.decode`
@memberOf punycode.ucs2
@name encode
@param {Array} codePoints The array of numeric code points.
@returns {String} The new Unicode string (UCS-2).
|
[
"Creates",
"a",
"string",
"based",
"on",
"an",
"array",
"of",
"numeric",
"code",
"points",
"."
] |
9c72a392dee7e307dfc2fe94e06a31f71469a18a
|
https://github.com/lambdabaa/dav/blob/9c72a392dee7e307dfc2fe94e06a31f71469a18a/dav.js#L3847-L3858
|
17,923
|
lambdabaa/dav
|
dav.js
|
toUnicode
|
function toUnicode(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
|
javascript
|
function toUnicode(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
|
[
"function",
"toUnicode",
"(",
"input",
")",
"{",
"return",
"mapDomain",
"(",
"input",
",",
"function",
"(",
"string",
")",
"{",
"return",
"regexPunycode",
".",
"test",
"(",
"string",
")",
"?",
"decode",
"(",
"string",
".",
"slice",
"(",
"4",
")",
".",
"toLowerCase",
"(",
")",
")",
":",
"string",
";",
"}",
")",
";",
"}"
] |
Converts a Punycode string representing a domain name or an email address
to Unicode. Only the Punycoded parts of the input will be converted, i.e.
it doesn't matter if you call it on a string that has already been
converted to Unicode.
@memberOf punycode
@param {String} input The Punycoded domain name or email address to
convert to Unicode.
@returns {String} The Unicode representation of the given Punycode
string.
|
[
"Converts",
"a",
"Punycode",
"string",
"representing",
"a",
"domain",
"name",
"or",
"an",
"email",
"address",
"to",
"Unicode",
".",
"Only",
"the",
"Punycoded",
"parts",
"of",
"the",
"input",
"will",
"be",
"converted",
"i",
".",
"e",
".",
"it",
"doesn",
"t",
"matter",
"if",
"you",
"call",
"it",
"on",
"a",
"string",
"that",
"has",
"already",
"been",
"converted",
"to",
"Unicode",
"."
] |
9c72a392dee7e307dfc2fe94e06a31f71469a18a
|
https://github.com/lambdabaa/dav/blob/9c72a392dee7e307dfc2fe94e06a31f71469a18a/dav.js#L4140-L4146
|
17,924
|
lambdabaa/dav
|
dav.js
|
toASCII
|
function toASCII(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
|
javascript
|
function toASCII(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
|
[
"function",
"toASCII",
"(",
"input",
")",
"{",
"return",
"mapDomain",
"(",
"input",
",",
"function",
"(",
"string",
")",
"{",
"return",
"regexNonASCII",
".",
"test",
"(",
"string",
")",
"?",
"'xn--'",
"+",
"encode",
"(",
"string",
")",
":",
"string",
";",
"}",
")",
";",
"}"
] |
Converts a Unicode string representing a domain name or an email address to
Punycode. Only the non-ASCII parts of the domain name will be converted,
i.e. it doesn't matter if you call it with a domain that's already in
ASCII.
@memberOf punycode
@param {String} input The domain name or email address to convert, as a
Unicode string.
@returns {String} The Punycode representation of the given domain name or
email address.
|
[
"Converts",
"a",
"Unicode",
"string",
"representing",
"a",
"domain",
"name",
"or",
"an",
"email",
"address",
"to",
"Punycode",
".",
"Only",
"the",
"non",
"-",
"ASCII",
"parts",
"of",
"the",
"domain",
"name",
"will",
"be",
"converted",
"i",
".",
"e",
".",
"it",
"doesn",
"t",
"matter",
"if",
"you",
"call",
"it",
"with",
"a",
"domain",
"that",
"s",
"already",
"in",
"ASCII",
"."
] |
9c72a392dee7e307dfc2fe94e06a31f71469a18a
|
https://github.com/lambdabaa/dav/blob/9c72a392dee7e307dfc2fe94e06a31f71469a18a/dav.js#L4159-L4165
|
17,925
|
ivanseidel/node-draftlog
|
examples/progress.js
|
ProgressBar
|
function ProgressBar(progress) {
// Make it 50 characters length
progress = Math.min(100, progress)
var units = Math.round(progress / 2)
return chalk.dim('[') + chalk.blue('=').repeat(units) + ' '.repeat(50 - units) + chalk.dim('] ') + chalk.yellow(progress + '%')
}
|
javascript
|
function ProgressBar(progress) {
// Make it 50 characters length
progress = Math.min(100, progress)
var units = Math.round(progress / 2)
return chalk.dim('[') + chalk.blue('=').repeat(units) + ' '.repeat(50 - units) + chalk.dim('] ') + chalk.yellow(progress + '%')
}
|
[
"function",
"ProgressBar",
"(",
"progress",
")",
"{",
"// Make it 50 characters length",
"progress",
"=",
"Math",
".",
"min",
"(",
"100",
",",
"progress",
")",
"var",
"units",
"=",
"Math",
".",
"round",
"(",
"progress",
"/",
"2",
")",
"return",
"chalk",
".",
"dim",
"(",
"'['",
")",
"+",
"chalk",
".",
"blue",
"(",
"'='",
")",
".",
"repeat",
"(",
"units",
")",
"+",
"' '",
".",
"repeat",
"(",
"50",
"-",
"units",
")",
"+",
"chalk",
".",
"dim",
"(",
"'] '",
")",
"+",
"chalk",
".",
"yellow",
"(",
"progress",
"+",
"'%'",
")",
"}"
] |
Input progess goes from 0 to 100
|
[
"Input",
"progess",
"goes",
"from",
"0",
"to",
"100"
] |
474d73fc18ca4fc8c6195896fd89cf409c246a56
|
https://github.com/ivanseidel/node-draftlog/blob/474d73fc18ca4fc8c6195896fd89cf409c246a56/examples/progress.js#L8-L13
|
17,926
|
ivanseidel/node-draftlog
|
examples/installer.js
|
InstalationProgress
|
function InstalationProgress(library, step, finished) {
var fillSpaces = ' '.repeat(15 - library.length)
if (finished) {
return chalk.cyan.dim(' > ') + chalk.yellow.dim(library) + fillSpaces + chalk.green('Installed')
} else {
return chalk.cyan(' > ') + chalk.yellow(library) + fillSpaces+ chalk.blue(step)
}
}
|
javascript
|
function InstalationProgress(library, step, finished) {
var fillSpaces = ' '.repeat(15 - library.length)
if (finished) {
return chalk.cyan.dim(' > ') + chalk.yellow.dim(library) + fillSpaces + chalk.green('Installed')
} else {
return chalk.cyan(' > ') + chalk.yellow(library) + fillSpaces+ chalk.blue(step)
}
}
|
[
"function",
"InstalationProgress",
"(",
"library",
",",
"step",
",",
"finished",
")",
"{",
"var",
"fillSpaces",
"=",
"' '",
".",
"repeat",
"(",
"15",
"-",
"library",
".",
"length",
")",
"if",
"(",
"finished",
")",
"{",
"return",
"chalk",
".",
"cyan",
".",
"dim",
"(",
"' > '",
")",
"+",
"chalk",
".",
"yellow",
".",
"dim",
"(",
"library",
")",
"+",
"fillSpaces",
"+",
"chalk",
".",
"green",
"(",
"'Installed'",
")",
"}",
"else",
"{",
"return",
"chalk",
".",
"cyan",
"(",
"' > '",
")",
"+",
"chalk",
".",
"yellow",
"(",
"library",
")",
"+",
"fillSpaces",
"+",
"chalk",
".",
"blue",
"(",
"step",
")",
"}",
"}"
] |
Shows an instalation log for a `library` on the `step`
|
[
"Shows",
"an",
"instalation",
"log",
"for",
"a",
"library",
"on",
"the",
"step"
] |
474d73fc18ca4fc8c6195896fd89cf409c246a56
|
https://github.com/ivanseidel/node-draftlog/blob/474d73fc18ca4fc8c6195896fd89cf409c246a56/examples/installer.js#L8-L15
|
17,927
|
ankane/chartkick.js
|
src/helpers.js
|
negativeValues
|
function negativeValues(series) {
let i, j, data;
for (i = 0; i < series.length; i++) {
data = series[i].data;
for (j = 0; j < data.length; j++) {
if (data[j][1] < 0) {
return true;
}
}
}
return false;
}
|
javascript
|
function negativeValues(series) {
let i, j, data;
for (i = 0; i < series.length; i++) {
data = series[i].data;
for (j = 0; j < data.length; j++) {
if (data[j][1] < 0) {
return true;
}
}
}
return false;
}
|
[
"function",
"negativeValues",
"(",
"series",
")",
"{",
"let",
"i",
",",
"j",
",",
"data",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"series",
".",
"length",
";",
"i",
"++",
")",
"{",
"data",
"=",
"series",
"[",
"i",
"]",
".",
"data",
";",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"data",
".",
"length",
";",
"j",
"++",
")",
"{",
"if",
"(",
"data",
"[",
"j",
"]",
"[",
"1",
"]",
"<",
"0",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}"
] |
end iso8601.js
|
[
"end",
"iso8601",
".",
"js"
] |
d813297d9a8b36179cace4a89fa0e445f942aa05
|
https://github.com/ankane/chartkick.js/blob/d813297d9a8b36179cace4a89fa0e445f942aa05/src/helpers.js#L76-L87
|
17,928
|
ankane/chartkick.js
|
src/index.js
|
copySeries
|
function copySeries(series) {
let newSeries = [], i, j;
for (i = 0; i < series.length; i++) {
let copy = {};
for (j in series[i]) {
if (series[i].hasOwnProperty(j)) {
copy[j] = series[i][j];
}
}
newSeries.push(copy);
}
return newSeries;
}
|
javascript
|
function copySeries(series) {
let newSeries = [], i, j;
for (i = 0; i < series.length; i++) {
let copy = {};
for (j in series[i]) {
if (series[i].hasOwnProperty(j)) {
copy[j] = series[i][j];
}
}
newSeries.push(copy);
}
return newSeries;
}
|
[
"function",
"copySeries",
"(",
"series",
")",
"{",
"let",
"newSeries",
"=",
"[",
"]",
",",
"i",
",",
"j",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"series",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"copy",
"=",
"{",
"}",
";",
"for",
"(",
"j",
"in",
"series",
"[",
"i",
"]",
")",
"{",
"if",
"(",
"series",
"[",
"i",
"]",
".",
"hasOwnProperty",
"(",
"j",
")",
")",
"{",
"copy",
"[",
"j",
"]",
"=",
"series",
"[",
"i",
"]",
"[",
"j",
"]",
";",
"}",
"}",
"newSeries",
".",
"push",
"(",
"copy",
")",
";",
"}",
"return",
"newSeries",
";",
"}"
] |
creates a shallow copy of each element of the array elements are expected to be objects
|
[
"creates",
"a",
"shallow",
"copy",
"of",
"each",
"element",
"of",
"the",
"array",
"elements",
"are",
"expected",
"to",
"be",
"objects"
] |
d813297d9a8b36179cace4a89fa0e445f942aa05
|
https://github.com/ankane/chartkick.js/blob/d813297d9a8b36179cace4a89fa0e445f942aa05/src/index.js#L270-L282
|
17,929
|
wix/eyes.it
|
src/eyes-it.js
|
eyesIt
|
function eyesIt(_it, _itArgs, config) {
const {
windowSize,
specVersion,
enableSnapshotAtBrowserGet,
enableSnapshotAtEnd,
} = merge({}, defaultConfig, config);
const spec = _it.apply(this, _itArgs);
const hooked = spec.beforeAndAfterFns;
spec.beforeAndAfterFns = function() {
//TODO: are we sure that we need to pass args (msg, itFn) to hooked?
const result = hooked.apply(this, _itArgs);
result.befores.unshift({
fn: function(done) {
_enableSnapshotAtBrowserGet = enableSnapshotAtBrowserGet;
eyes
.open(browser, appName, buildSpecName(spec, specVersion), windowSize)
.then(done);
},
timeout: () => 30000,
});
result.afters.unshift({
fn: function(done) {
_enableSnapshotAtBrowserGet = false;
Promise.resolve()
.then(() => {
if (enableSnapshotAtEnd) {
return eyes.checkWindow('end');
}
})
.then(done)
.catch(err => handleError(err, done));
},
timeout: () => 30000,
});
result.afters.push({
fn: function(done) {
eyes
.close()
.then(done)
.catch(err => handleError(err, done));
},
timeout: () => 30000,
});
return result;
};
return spec;
}
|
javascript
|
function eyesIt(_it, _itArgs, config) {
const {
windowSize,
specVersion,
enableSnapshotAtBrowserGet,
enableSnapshotAtEnd,
} = merge({}, defaultConfig, config);
const spec = _it.apply(this, _itArgs);
const hooked = spec.beforeAndAfterFns;
spec.beforeAndAfterFns = function() {
//TODO: are we sure that we need to pass args (msg, itFn) to hooked?
const result = hooked.apply(this, _itArgs);
result.befores.unshift({
fn: function(done) {
_enableSnapshotAtBrowserGet = enableSnapshotAtBrowserGet;
eyes
.open(browser, appName, buildSpecName(spec, specVersion), windowSize)
.then(done);
},
timeout: () => 30000,
});
result.afters.unshift({
fn: function(done) {
_enableSnapshotAtBrowserGet = false;
Promise.resolve()
.then(() => {
if (enableSnapshotAtEnd) {
return eyes.checkWindow('end');
}
})
.then(done)
.catch(err => handleError(err, done));
},
timeout: () => 30000,
});
result.afters.push({
fn: function(done) {
eyes
.close()
.then(done)
.catch(err => handleError(err, done));
},
timeout: () => 30000,
});
return result;
};
return spec;
}
|
[
"function",
"eyesIt",
"(",
"_it",
",",
"_itArgs",
",",
"config",
")",
"{",
"const",
"{",
"windowSize",
",",
"specVersion",
",",
"enableSnapshotAtBrowserGet",
",",
"enableSnapshotAtEnd",
",",
"}",
"=",
"merge",
"(",
"{",
"}",
",",
"defaultConfig",
",",
"config",
")",
";",
"const",
"spec",
"=",
"_it",
".",
"apply",
"(",
"this",
",",
"_itArgs",
")",
";",
"const",
"hooked",
"=",
"spec",
".",
"beforeAndAfterFns",
";",
"spec",
".",
"beforeAndAfterFns",
"=",
"function",
"(",
")",
"{",
"//TODO: are we sure that we need to pass args (msg, itFn) to hooked?",
"const",
"result",
"=",
"hooked",
".",
"apply",
"(",
"this",
",",
"_itArgs",
")",
";",
"result",
".",
"befores",
".",
"unshift",
"(",
"{",
"fn",
":",
"function",
"(",
"done",
")",
"{",
"_enableSnapshotAtBrowserGet",
"=",
"enableSnapshotAtBrowserGet",
";",
"eyes",
".",
"open",
"(",
"browser",
",",
"appName",
",",
"buildSpecName",
"(",
"spec",
",",
"specVersion",
")",
",",
"windowSize",
")",
".",
"then",
"(",
"done",
")",
";",
"}",
",",
"timeout",
":",
"(",
")",
"=>",
"30000",
",",
"}",
")",
";",
"result",
".",
"afters",
".",
"unshift",
"(",
"{",
"fn",
":",
"function",
"(",
"done",
")",
"{",
"_enableSnapshotAtBrowserGet",
"=",
"false",
";",
"Promise",
".",
"resolve",
"(",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"if",
"(",
"enableSnapshotAtEnd",
")",
"{",
"return",
"eyes",
".",
"checkWindow",
"(",
"'end'",
")",
";",
"}",
"}",
")",
".",
"then",
"(",
"done",
")",
".",
"catch",
"(",
"err",
"=>",
"handleError",
"(",
"err",
",",
"done",
")",
")",
";",
"}",
",",
"timeout",
":",
"(",
")",
"=>",
"30000",
",",
"}",
")",
";",
"result",
".",
"afters",
".",
"push",
"(",
"{",
"fn",
":",
"function",
"(",
"done",
")",
"{",
"eyes",
".",
"close",
"(",
")",
".",
"then",
"(",
"done",
")",
".",
"catch",
"(",
"err",
"=>",
"handleError",
"(",
"err",
",",
"done",
")",
")",
";",
"}",
",",
"timeout",
":",
"(",
")",
"=>",
"30000",
",",
"}",
")",
";",
"return",
"result",
";",
"}",
";",
"return",
"spec",
";",
"}"
] |
Call original `it` and modify before and after
@param {*} _it the original `it` or `fit` function
@param {*} _itArgs the original arguments of the original `it` or `fit` function.
@param {*} config `eyes.it` configuration
@returns spec
|
[
"Call",
"original",
"it",
"and",
"modify",
"before",
"and",
"after"
] |
39de24bf472d1a02164fad838be26fa71d48dd03
|
https://github.com/wix/eyes.it/blob/39de24bf472d1a02164fad838be26fa71d48dd03/src/eyes-it.js#L42-L91
|
17,930
|
longseespace/react-qml
|
packages/react-qml-cli/src/utils/findProvidesModule.js
|
findProvidesModule
|
function findProvidesModule(directories, opts = {}) {
const options = Object.assign({}, defaultOpts, opts);
const modulesMap = {};
const walk = dir => {
const stat = fs.lstatSync(dir);
if (stat.isDirectory()) {
fs.readdirSync(dir).forEach(file => {
if (options.blacklist.indexOf(file) >= 0) {
return;
}
walk(path.join(dir, file));
});
return;
}
if (stat.isFile()) {
const jsFileName = getJSFileName(dir);
if (!jsFileName) {
return;
}
const fileName = getPlatformFileName(jsFileName, options.platforms);
const moduleName = getProvidedModuleName(dir);
if (!moduleName) {
return;
}
// Throw when duplicated modules are provided from a different
// fileName
if (modulesMap[moduleName] && modulesMap[moduleName] !== fileName) {
throw new Error('Duplicate haste module found');
}
modulesMap[moduleName] = fileName;
}
};
directories.forEach(walk);
return modulesMap;
}
|
javascript
|
function findProvidesModule(directories, opts = {}) {
const options = Object.assign({}, defaultOpts, opts);
const modulesMap = {};
const walk = dir => {
const stat = fs.lstatSync(dir);
if (stat.isDirectory()) {
fs.readdirSync(dir).forEach(file => {
if (options.blacklist.indexOf(file) >= 0) {
return;
}
walk(path.join(dir, file));
});
return;
}
if (stat.isFile()) {
const jsFileName = getJSFileName(dir);
if (!jsFileName) {
return;
}
const fileName = getPlatformFileName(jsFileName, options.platforms);
const moduleName = getProvidedModuleName(dir);
if (!moduleName) {
return;
}
// Throw when duplicated modules are provided from a different
// fileName
if (modulesMap[moduleName] && modulesMap[moduleName] !== fileName) {
throw new Error('Duplicate haste module found');
}
modulesMap[moduleName] = fileName;
}
};
directories.forEach(walk);
return modulesMap;
}
|
[
"function",
"findProvidesModule",
"(",
"directories",
",",
"opts",
"=",
"{",
"}",
")",
"{",
"const",
"options",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"defaultOpts",
",",
"opts",
")",
";",
"const",
"modulesMap",
"=",
"{",
"}",
";",
"const",
"walk",
"=",
"dir",
"=>",
"{",
"const",
"stat",
"=",
"fs",
".",
"lstatSync",
"(",
"dir",
")",
";",
"if",
"(",
"stat",
".",
"isDirectory",
"(",
")",
")",
"{",
"fs",
".",
"readdirSync",
"(",
"dir",
")",
".",
"forEach",
"(",
"file",
"=>",
"{",
"if",
"(",
"options",
".",
"blacklist",
".",
"indexOf",
"(",
"file",
")",
">=",
"0",
")",
"{",
"return",
";",
"}",
"walk",
"(",
"path",
".",
"join",
"(",
"dir",
",",
"file",
")",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"if",
"(",
"stat",
".",
"isFile",
"(",
")",
")",
"{",
"const",
"jsFileName",
"=",
"getJSFileName",
"(",
"dir",
")",
";",
"if",
"(",
"!",
"jsFileName",
")",
"{",
"return",
";",
"}",
"const",
"fileName",
"=",
"getPlatformFileName",
"(",
"jsFileName",
",",
"options",
".",
"platforms",
")",
";",
"const",
"moduleName",
"=",
"getProvidedModuleName",
"(",
"dir",
")",
";",
"if",
"(",
"!",
"moduleName",
")",
"{",
"return",
";",
"}",
"// Throw when duplicated modules are provided from a different",
"// fileName",
"if",
"(",
"modulesMap",
"[",
"moduleName",
"]",
"&&",
"modulesMap",
"[",
"moduleName",
"]",
"!==",
"fileName",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Duplicate haste module found'",
")",
";",
"}",
"modulesMap",
"[",
"moduleName",
"]",
"=",
"fileName",
";",
"}",
"}",
";",
"directories",
".",
"forEach",
"(",
"walk",
")",
";",
"return",
"modulesMap",
";",
"}"
] |
Recursively loops over given directories and returns a map of all
haste modules
|
[
"Recursively",
"loops",
"over",
"given",
"directories",
"and",
"returns",
"a",
"map",
"of",
"all",
"haste",
"modules"
] |
682dae6778d65305956fb40324b7ec59afa57a77
|
https://github.com/longseespace/react-qml/blob/682dae6778d65305956fb40324b7ec59afa57a77/packages/react-qml-cli/src/utils/findProvidesModule.js#L54-L97
|
17,931
|
longseespace/react-qml
|
packages/react-qml-cli/src/commands/reload.js
|
reload
|
async function reload() {
const requestOptions = {
hostname: 'localhost',
port: 8081,
path: '/reloadapp',
method: 'HEAD',
};
const req = http.request(requestOptions, () => {
clear();
logger.done('Sent reload request');
req.end();
});
req.on('error', e => {
clear();
const error = e.toString();
if (error.includes('connect ECONNREFUSED')) {
logger.error(`Reload request failed. Make sure Haul is up.`);
} else {
logger.error(e);
}
});
req.end();
}
|
javascript
|
async function reload() {
const requestOptions = {
hostname: 'localhost',
port: 8081,
path: '/reloadapp',
method: 'HEAD',
};
const req = http.request(requestOptions, () => {
clear();
logger.done('Sent reload request');
req.end();
});
req.on('error', e => {
clear();
const error = e.toString();
if (error.includes('connect ECONNREFUSED')) {
logger.error(`Reload request failed. Make sure Haul is up.`);
} else {
logger.error(e);
}
});
req.end();
}
|
[
"async",
"function",
"reload",
"(",
")",
"{",
"const",
"requestOptions",
"=",
"{",
"hostname",
":",
"'localhost'",
",",
"port",
":",
"8081",
",",
"path",
":",
"'/reloadapp'",
",",
"method",
":",
"'HEAD'",
",",
"}",
";",
"const",
"req",
"=",
"http",
".",
"request",
"(",
"requestOptions",
",",
"(",
")",
"=>",
"{",
"clear",
"(",
")",
";",
"logger",
".",
"done",
"(",
"'Sent reload request'",
")",
";",
"req",
".",
"end",
"(",
")",
";",
"}",
")",
";",
"req",
".",
"on",
"(",
"'error'",
",",
"e",
"=>",
"{",
"clear",
"(",
")",
";",
"const",
"error",
"=",
"e",
".",
"toString",
"(",
")",
";",
"if",
"(",
"error",
".",
"includes",
"(",
"'connect ECONNREFUSED'",
")",
")",
"{",
"logger",
".",
"error",
"(",
"`",
"`",
")",
";",
"}",
"else",
"{",
"logger",
".",
"error",
"(",
"e",
")",
";",
"}",
"}",
")",
";",
"req",
".",
"end",
"(",
")",
";",
"}"
] |
Send reload request to devices
|
[
"Send",
"reload",
"request",
"to",
"devices"
] |
682dae6778d65305956fb40324b7ec59afa57a77
|
https://github.com/longseespace/react-qml/blob/682dae6778d65305956fb40324b7ec59afa57a77/packages/react-qml-cli/src/commands/reload.js#L17-L42
|
17,932
|
jhipster/jhipster-uml
|
lib/editors/parser_helper.js
|
extractClassName
|
function extractClassName(name) {
if (name.indexOf('(') === -1) {
return { entityName: name, tableName: _.snakeCase(name).toLowerCase() };
}
const split = name.split('(');
return {
entityName: split[0].trim(),
tableName: _.snakeCase(
split[1].slice(0, split[1].length - 1).trim()
).toLowerCase()
};
}
|
javascript
|
function extractClassName(name) {
if (name.indexOf('(') === -1) {
return { entityName: name, tableName: _.snakeCase(name).toLowerCase() };
}
const split = name.split('(');
return {
entityName: split[0].trim(),
tableName: _.snakeCase(
split[1].slice(0, split[1].length - 1).trim()
).toLowerCase()
};
}
|
[
"function",
"extractClassName",
"(",
"name",
")",
"{",
"if",
"(",
"name",
".",
"indexOf",
"(",
"'('",
")",
"===",
"-",
"1",
")",
"{",
"return",
"{",
"entityName",
":",
"name",
",",
"tableName",
":",
"_",
".",
"snakeCase",
"(",
"name",
")",
".",
"toLowerCase",
"(",
")",
"}",
";",
"}",
"const",
"split",
"=",
"name",
".",
"split",
"(",
"'('",
")",
";",
"return",
"{",
"entityName",
":",
"split",
"[",
"0",
"]",
".",
"trim",
"(",
")",
",",
"tableName",
":",
"_",
".",
"snakeCase",
"(",
"split",
"[",
"1",
"]",
".",
"slice",
"(",
"0",
",",
"split",
"[",
"1",
"]",
".",
"length",
"-",
"1",
")",
".",
"trim",
"(",
")",
")",
".",
"toLowerCase",
"(",
")",
"}",
";",
"}"
] |
Extracts the entity name and the table name from the name parsed from
the XMI file.
@param name the name from the XMI file.
@return {Object} the object containing the entity name and the table name.
|
[
"Extracts",
"the",
"entity",
"name",
"and",
"the",
"table",
"name",
"from",
"the",
"name",
"parsed",
"from",
"the",
"XMI",
"file",
"."
] |
c18334aa05b8b247464560c1849a7809f8c206bc
|
https://github.com/jhipster/jhipster-uml/blob/c18334aa05b8b247464560c1849a7809f8c206bc/lib/editors/parser_helper.js#L54-L65
|
17,933
|
jhipster/jhipster-uml
|
lib/editors/parser_helper.js
|
getXmlElementFromRawIndexes
|
function getXmlElementFromRawIndexes(root, indexInfo) {
let parentPackage = root;
for (let j = 0; j < indexInfo.path.length; j++) {
parentPackage = parentPackage.packagedElement[indexInfo.path[j]];
}
return parentPackage.packagedElement[indexInfo.index];
}
|
javascript
|
function getXmlElementFromRawIndexes(root, indexInfo) {
let parentPackage = root;
for (let j = 0; j < indexInfo.path.length; j++) {
parentPackage = parentPackage.packagedElement[indexInfo.path[j]];
}
return parentPackage.packagedElement[indexInfo.index];
}
|
[
"function",
"getXmlElementFromRawIndexes",
"(",
"root",
",",
"indexInfo",
")",
"{",
"let",
"parentPackage",
"=",
"root",
";",
"for",
"(",
"let",
"j",
"=",
"0",
";",
"j",
"<",
"indexInfo",
".",
"path",
".",
"length",
";",
"j",
"++",
")",
"{",
"parentPackage",
"=",
"parentPackage",
".",
"packagedElement",
"[",
"indexInfo",
".",
"path",
"[",
"j",
"]",
"]",
";",
"}",
"return",
"parentPackage",
".",
"packagedElement",
"[",
"indexInfo",
".",
"index",
"]",
";",
"}"
] |
Extract indexInfo in rawIndexes array and use it to get the referenced element
@param root the root document
@param indexInfo the index info element
@returns {Object} the xml element
|
[
"Extract",
"indexInfo",
"in",
"rawIndexes",
"array",
"and",
"use",
"it",
"to",
"get",
"the",
"referenced",
"element"
] |
c18334aa05b8b247464560c1849a7809f8c206bc
|
https://github.com/jhipster/jhipster-uml/blob/c18334aa05b8b247464560c1849a7809f8c206bc/lib/editors/parser_helper.js#L73-L79
|
17,934
|
jhipster/jhipster-uml
|
lib/entity_generator.js
|
generateEntities
|
function generateEntities(entityIdsToGenerate, classes, entityNamesToGenerate, options) {
if (shouldEntitiesBeGenerated(entityIdsToGenerate, entityNamesToGenerate, classes)) {
winston.info('No entity has to be generated.');
return;
}
displayEntitiesToGenerate(entityIdsToGenerate, entityNamesToGenerate, classes);
entityIdsToGenerate.forEach((entityToGenerate, index) => {
if (entityNamesToGenerate.includes(classes[entityToGenerate].name)) {
const commandWrapper = createAndInitCommandBuilder(
classes[entityToGenerate].name,
options,
index !== entityIdsToGenerate.length - 1
);
childProcess.spawnSync(
commandWrapper.command,
commandWrapper.args,
{ stdio: commandWrapper.stdio }
);
winston.info('\n');
}
});
}
|
javascript
|
function generateEntities(entityIdsToGenerate, classes, entityNamesToGenerate, options) {
if (shouldEntitiesBeGenerated(entityIdsToGenerate, entityNamesToGenerate, classes)) {
winston.info('No entity has to be generated.');
return;
}
displayEntitiesToGenerate(entityIdsToGenerate, entityNamesToGenerate, classes);
entityIdsToGenerate.forEach((entityToGenerate, index) => {
if (entityNamesToGenerate.includes(classes[entityToGenerate].name)) {
const commandWrapper = createAndInitCommandBuilder(
classes[entityToGenerate].name,
options,
index !== entityIdsToGenerate.length - 1
);
childProcess.spawnSync(
commandWrapper.command,
commandWrapper.args,
{ stdio: commandWrapper.stdio }
);
winston.info('\n');
}
});
}
|
[
"function",
"generateEntities",
"(",
"entityIdsToGenerate",
",",
"classes",
",",
"entityNamesToGenerate",
",",
"options",
")",
"{",
"if",
"(",
"shouldEntitiesBeGenerated",
"(",
"entityIdsToGenerate",
",",
"entityNamesToGenerate",
",",
"classes",
")",
")",
"{",
"winston",
".",
"info",
"(",
"'No entity has to be generated.'",
")",
";",
"return",
";",
"}",
"displayEntitiesToGenerate",
"(",
"entityIdsToGenerate",
",",
"entityNamesToGenerate",
",",
"classes",
")",
";",
"entityIdsToGenerate",
".",
"forEach",
"(",
"(",
"entityToGenerate",
",",
"index",
")",
"=>",
"{",
"if",
"(",
"entityNamesToGenerate",
".",
"includes",
"(",
"classes",
"[",
"entityToGenerate",
"]",
".",
"name",
")",
")",
"{",
"const",
"commandWrapper",
"=",
"createAndInitCommandBuilder",
"(",
"classes",
"[",
"entityToGenerate",
"]",
".",
"name",
",",
"options",
",",
"index",
"!==",
"entityIdsToGenerate",
".",
"length",
"-",
"1",
")",
";",
"childProcess",
".",
"spawnSync",
"(",
"commandWrapper",
".",
"command",
",",
"commandWrapper",
".",
"args",
",",
"{",
"stdio",
":",
"commandWrapper",
".",
"stdio",
"}",
")",
";",
"winston",
".",
"info",
"(",
"'\\n'",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Generates the entities locally by using JHipster to create the JSON files, and
generate the different output files.
@param entityIdsToGenerate {array<String>} the entities to generate.
@param classes {object} the classes to add.
@param entityNamesToGenerate {array} the names of the entities to generate.
@param options {object} an object containing:
- force {boolean} the force flag.
- listOfNoClient {array} the array containing the classes that won't
have any client code.
- listOfNoServer {array} the array containing the classes that won't
have any server code.
- angularSuffixes {object} the angular suffixes for each entity.
- noFluentMethods {array} the array containing the classes that won't
have fluent methods.
|
[
"Generates",
"the",
"entities",
"locally",
"by",
"using",
"JHipster",
"to",
"create",
"the",
"JSON",
"files",
"and",
"generate",
"the",
"different",
"output",
"files",
"."
] |
c18334aa05b8b247464560c1849a7809f8c206bc
|
https://github.com/jhipster/jhipster-uml/blob/c18334aa05b8b247464560c1849a7809f8c206bc/lib/entity_generator.js#L44-L67
|
17,935
|
jhipster/jhipster-uml
|
lib/helpers/association_helper.js
|
checkValidityOfAssociation
|
function checkValidityOfAssociation(association, sourceName, destinationName) {
if (!association || !association.type) {
throw new BuildException(
exceptions.NullPointer, 'The association must not be nil.');
}
switch (association.type) {
case cardinalities.ONE_TO_ONE:
checkOneToOne(association, sourceName, destinationName);
break;
case cardinalities.ONE_TO_MANY:
checkOneToMany(association, sourceName, destinationName);
break;
case cardinalities.MANY_TO_ONE:
checkManyToOne(association, sourceName, destinationName);
break;
case cardinalities.MANY_TO_MANY:
checkManyToMany(association, sourceName, destinationName);
break;
default:
throw new BuildException(
exceptions.WrongAssociation,
`The association type ${association.type} isn't supported.`);
}
}
|
javascript
|
function checkValidityOfAssociation(association, sourceName, destinationName) {
if (!association || !association.type) {
throw new BuildException(
exceptions.NullPointer, 'The association must not be nil.');
}
switch (association.type) {
case cardinalities.ONE_TO_ONE:
checkOneToOne(association, sourceName, destinationName);
break;
case cardinalities.ONE_TO_MANY:
checkOneToMany(association, sourceName, destinationName);
break;
case cardinalities.MANY_TO_ONE:
checkManyToOne(association, sourceName, destinationName);
break;
case cardinalities.MANY_TO_MANY:
checkManyToMany(association, sourceName, destinationName);
break;
default:
throw new BuildException(
exceptions.WrongAssociation,
`The association type ${association.type} isn't supported.`);
}
}
|
[
"function",
"checkValidityOfAssociation",
"(",
"association",
",",
"sourceName",
",",
"destinationName",
")",
"{",
"if",
"(",
"!",
"association",
"||",
"!",
"association",
".",
"type",
")",
"{",
"throw",
"new",
"BuildException",
"(",
"exceptions",
".",
"NullPointer",
",",
"'The association must not be nil.'",
")",
";",
"}",
"switch",
"(",
"association",
".",
"type",
")",
"{",
"case",
"cardinalities",
".",
"ONE_TO_ONE",
":",
"checkOneToOne",
"(",
"association",
",",
"sourceName",
",",
"destinationName",
")",
";",
"break",
";",
"case",
"cardinalities",
".",
"ONE_TO_MANY",
":",
"checkOneToMany",
"(",
"association",
",",
"sourceName",
",",
"destinationName",
")",
";",
"break",
";",
"case",
"cardinalities",
".",
"MANY_TO_ONE",
":",
"checkManyToOne",
"(",
"association",
",",
"sourceName",
",",
"destinationName",
")",
";",
"break",
";",
"case",
"cardinalities",
".",
"MANY_TO_MANY",
":",
"checkManyToMany",
"(",
"association",
",",
"sourceName",
",",
"destinationName",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"BuildException",
"(",
"exceptions",
".",
"WrongAssociation",
",",
"`",
"${",
"association",
".",
"type",
"}",
"`",
")",
";",
"}",
"}"
] |
Checks the validity of the association.
@param {AssociationData} association the association to check.
@param {String} sourceName the source's name.
@param {String} destinationName the destination's name.
@throws NullPointerException if the association is nil.
@throws AssociationException if the association is invalid.
|
[
"Checks",
"the",
"validity",
"of",
"the",
"association",
"."
] |
c18334aa05b8b247464560c1849a7809f8c206bc
|
https://github.com/jhipster/jhipster-uml/blob/c18334aa05b8b247464560c1849a7809f8c206bc/lib/helpers/association_helper.js#L37-L60
|
17,936
|
jhipster/jhipster-uml
|
lib/helpers/class_helper.js
|
getClassNames
|
function getClassNames(classes) {
if (!classes) {
throw new BuildException(
exceptions.NullPointer, 'The classes object cannot be nil.');
}
const object = {};
Object.keys(classes).forEach((classId) => {
object[classId] = classes[classId].name;
});
return object;
}
|
javascript
|
function getClassNames(classes) {
if (!classes) {
throw new BuildException(
exceptions.NullPointer, 'The classes object cannot be nil.');
}
const object = {};
Object.keys(classes).forEach((classId) => {
object[classId] = classes[classId].name;
});
return object;
}
|
[
"function",
"getClassNames",
"(",
"classes",
")",
"{",
"if",
"(",
"!",
"classes",
")",
"{",
"throw",
"new",
"BuildException",
"(",
"exceptions",
".",
"NullPointer",
",",
"'The classes object cannot be nil.'",
")",
";",
"}",
"const",
"object",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"classes",
")",
".",
"forEach",
"(",
"(",
"classId",
")",
"=>",
"{",
"object",
"[",
"classId",
"]",
"=",
"classes",
"[",
"classId",
"]",
".",
"name",
";",
"}",
")",
";",
"return",
"object",
";",
"}"
] |
Gets the class' names.
@param classes the classes
@returns {Object} an object containing all the class' names by their id.
@throws {NullPointerException} if the passed object is nil.
|
[
"Gets",
"the",
"class",
"names",
"."
] |
c18334aa05b8b247464560c1849a7809f8c206bc
|
https://github.com/jhipster/jhipster-uml/blob/c18334aa05b8b247464560c1849a7809f8c206bc/lib/helpers/class_helper.js#L32-L42
|
17,937
|
jhipster/jhipster-uml
|
lib/editors/editor_detector.js
|
detect
|
function detect(root) {
if (!root) {
throw new BuildException(
exceptions.NullPointer, 'The root element can not be null.');
}
if (root.eAnnotations && root.eAnnotations[0].$.source === 'Objing') {
winston.info('Parser detected: MODELIO.\n');
return modelio;
} else if (root.eAnnotations
&& root.eAnnotations[0].$.source === 'genmymodel') {
winston.info('Parser detected: GENMYMODEL.\n');
return genmymodel;
}
if (UndetectedEditors.length === 0) {
// this should not be happening
throw new BuildException(exceptions.UndetectedEditor,
'Your editor has not been detected, and this should not be happening.'
+ '\nPlease report this issue by mentioning what your editor is.');
}
return askForEditor();
}
|
javascript
|
function detect(root) {
if (!root) {
throw new BuildException(
exceptions.NullPointer, 'The root element can not be null.');
}
if (root.eAnnotations && root.eAnnotations[0].$.source === 'Objing') {
winston.info('Parser detected: MODELIO.\n');
return modelio;
} else if (root.eAnnotations
&& root.eAnnotations[0].$.source === 'genmymodel') {
winston.info('Parser detected: GENMYMODEL.\n');
return genmymodel;
}
if (UndetectedEditors.length === 0) {
// this should not be happening
throw new BuildException(exceptions.UndetectedEditor,
'Your editor has not been detected, and this should not be happening.'
+ '\nPlease report this issue by mentioning what your editor is.');
}
return askForEditor();
}
|
[
"function",
"detect",
"(",
"root",
")",
"{",
"if",
"(",
"!",
"root",
")",
"{",
"throw",
"new",
"BuildException",
"(",
"exceptions",
".",
"NullPointer",
",",
"'The root element can not be null.'",
")",
";",
"}",
"if",
"(",
"root",
".",
"eAnnotations",
"&&",
"root",
".",
"eAnnotations",
"[",
"0",
"]",
".",
"$",
".",
"source",
"===",
"'Objing'",
")",
"{",
"winston",
".",
"info",
"(",
"'Parser detected: MODELIO.\\n'",
")",
";",
"return",
"modelio",
";",
"}",
"else",
"if",
"(",
"root",
".",
"eAnnotations",
"&&",
"root",
".",
"eAnnotations",
"[",
"0",
"]",
".",
"$",
".",
"source",
"===",
"'genmymodel'",
")",
"{",
"winston",
".",
"info",
"(",
"'Parser detected: GENMYMODEL.\\n'",
")",
";",
"return",
"genmymodel",
";",
"}",
"if",
"(",
"UndetectedEditors",
".",
"length",
"===",
"0",
")",
"{",
"// this should not be happening",
"throw",
"new",
"BuildException",
"(",
"exceptions",
".",
"UndetectedEditor",
",",
"'Your editor has not been detected, and this should not be happening.'",
"+",
"'\\nPlease report this issue by mentioning what your editor is.'",
")",
";",
"}",
"return",
"askForEditor",
"(",
")",
";",
"}"
] |
Detects the editor that made the document represented by its passed root.
@param root {Object} the document's root.
@return {string} the editor's name.
|
[
"Detects",
"the",
"editor",
"that",
"made",
"the",
"document",
"represented",
"by",
"its",
"passed",
"root",
"."
] |
c18334aa05b8b247464560c1849a7809f8c206bc
|
https://github.com/jhipster/jhipster-uml/blob/c18334aa05b8b247464560c1849a7809f8c206bc/lib/editors/editor_detector.js#L36-L57
|
17,938
|
jhipster/jhipster-uml
|
lib/helpers/question_asker.js
|
askConfirmation
|
function askConfirmation(args) {
let userAnswer = 'no-answer';
const merged = merge(DEFAULTS.CONFIRMATIONS, args);
inquirer.prompt([
{
type: DEFAULTS.QUESTION_TYPES.CONFIRM,
name: 'choice',
message: merged.question,
default: merged.defaultValue
}
]).then((answer) => {
userAnswer = answer.choice;
});
while (userAnswer === 'no-answer') {
wait(100);
}
return userAnswer;
}
|
javascript
|
function askConfirmation(args) {
let userAnswer = 'no-answer';
const merged = merge(DEFAULTS.CONFIRMATIONS, args);
inquirer.prompt([
{
type: DEFAULTS.QUESTION_TYPES.CONFIRM,
name: 'choice',
message: merged.question,
default: merged.defaultValue
}
]).then((answer) => {
userAnswer = answer.choice;
});
while (userAnswer === 'no-answer') {
wait(100);
}
return userAnswer;
}
|
[
"function",
"askConfirmation",
"(",
"args",
")",
"{",
"let",
"userAnswer",
"=",
"'no-answer'",
";",
"const",
"merged",
"=",
"merge",
"(",
"DEFAULTS",
".",
"CONFIRMATIONS",
",",
"args",
")",
";",
"inquirer",
".",
"prompt",
"(",
"[",
"{",
"type",
":",
"DEFAULTS",
".",
"QUESTION_TYPES",
".",
"CONFIRM",
",",
"name",
":",
"'choice'",
",",
"message",
":",
"merged",
".",
"question",
",",
"default",
":",
"merged",
".",
"defaultValue",
"}",
"]",
")",
".",
"then",
"(",
"(",
"answer",
")",
"=>",
"{",
"userAnswer",
"=",
"answer",
".",
"choice",
";",
"}",
")",
";",
"while",
"(",
"userAnswer",
"===",
"'no-answer'",
")",
"{",
"wait",
"(",
"100",
")",
";",
"}",
"return",
"userAnswer",
";",
"}"
] |
Asks the user for confirmation.
@param args {object} keys: question, defaultValue
@return {boolean} the user's answer.
|
[
"Asks",
"the",
"user",
"for",
"confirmation",
"."
] |
c18334aa05b8b247464560c1849a7809f8c206bc
|
https://github.com/jhipster/jhipster-uml/blob/c18334aa05b8b247464560c1849a7809f8c206bc/lib/helpers/question_asker.js#L58-L75
|
17,939
|
jhipster/jhipster-uml
|
lib/helpers/question_asker.js
|
selectMultipleChoices
|
function selectMultipleChoices(args) {
args.choices = args.choices || prepareChoices(args.classes);
let result = null;
const merged = merge(DEFAULTS.MULTIPLE_CHOICES, args);
inquirer.prompt([
{
type: DEFAULTS.QUESTION_TYPES.CHECKBOX,
name: 'answer',
message: merged.question,
choices: merged.choices,
filter: merged.filterFunction
}
]).then((answers) => {
if (answers.answer.length === 0) {
result = DEFAULTS.NOTHING;
} else {
result = answers.answer;
}
});
while (!result) {
wait(100);
}
return result;
}
|
javascript
|
function selectMultipleChoices(args) {
args.choices = args.choices || prepareChoices(args.classes);
let result = null;
const merged = merge(DEFAULTS.MULTIPLE_CHOICES, args);
inquirer.prompt([
{
type: DEFAULTS.QUESTION_TYPES.CHECKBOX,
name: 'answer',
message: merged.question,
choices: merged.choices,
filter: merged.filterFunction
}
]).then((answers) => {
if (answers.answer.length === 0) {
result = DEFAULTS.NOTHING;
} else {
result = answers.answer;
}
});
while (!result) {
wait(100);
}
return result;
}
|
[
"function",
"selectMultipleChoices",
"(",
"args",
")",
"{",
"args",
".",
"choices",
"=",
"args",
".",
"choices",
"||",
"prepareChoices",
"(",
"args",
".",
"classes",
")",
";",
"let",
"result",
"=",
"null",
";",
"const",
"merged",
"=",
"merge",
"(",
"DEFAULTS",
".",
"MULTIPLE_CHOICES",
",",
"args",
")",
";",
"inquirer",
".",
"prompt",
"(",
"[",
"{",
"type",
":",
"DEFAULTS",
".",
"QUESTION_TYPES",
".",
"CHECKBOX",
",",
"name",
":",
"'answer'",
",",
"message",
":",
"merged",
".",
"question",
",",
"choices",
":",
"merged",
".",
"choices",
",",
"filter",
":",
"merged",
".",
"filterFunction",
"}",
"]",
")",
".",
"then",
"(",
"(",
"answers",
")",
"=>",
"{",
"if",
"(",
"answers",
".",
"answer",
".",
"length",
"===",
"0",
")",
"{",
"result",
"=",
"DEFAULTS",
".",
"NOTHING",
";",
"}",
"else",
"{",
"result",
"=",
"answers",
".",
"answer",
";",
"}",
"}",
")",
";",
"while",
"(",
"!",
"result",
")",
"{",
"wait",
"(",
"100",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
Asks the user for one, or more choices.
@param args {object} keys: classes, choices, question, filterFunction
@return the choice.
|
[
"Asks",
"the",
"user",
"for",
"one",
"or",
"more",
"choices",
"."
] |
c18334aa05b8b247464560c1849a7809f8c206bc
|
https://github.com/jhipster/jhipster-uml/blob/c18334aa05b8b247464560c1849a7809f8c206bc/lib/helpers/question_asker.js#L82-L105
|
17,940
|
jhipster/jhipster-uml
|
lib/export/jdl_exporter.js
|
toJDL
|
function toJDL(parsedData, options) {
assertParsedDataIsValid(parsedData);
const jdlObject = new JDLObject();
const jdlEnumArray = convertEnums(parsedData.enums);
addEnumsToJDLObject(jdlObject, jdlEnumArray);
const jdlEntityObject = convertClasses(parsedData);
addEntitiesToJDLObject(jdlObject, jdlEntityObject);
const jdlRelationshipArray = convertAssociations(parsedData, jdlObject.entities);
addRelationshipsToJDLObject(jdlObject, jdlRelationshipArray);
if (options) {
const jdlOptionArray = convertOptions(options, parsedData.classNames.length);
addOptionsToJDLObject(jdlObject, jdlOptionArray);
}
return jdlObject;
}
|
javascript
|
function toJDL(parsedData, options) {
assertParsedDataIsValid(parsedData);
const jdlObject = new JDLObject();
const jdlEnumArray = convertEnums(parsedData.enums);
addEnumsToJDLObject(jdlObject, jdlEnumArray);
const jdlEntityObject = convertClasses(parsedData);
addEntitiesToJDLObject(jdlObject, jdlEntityObject);
const jdlRelationshipArray = convertAssociations(parsedData, jdlObject.entities);
addRelationshipsToJDLObject(jdlObject, jdlRelationshipArray);
if (options) {
const jdlOptionArray = convertOptions(options, parsedData.classNames.length);
addOptionsToJDLObject(jdlObject, jdlOptionArray);
}
return jdlObject;
}
|
[
"function",
"toJDL",
"(",
"parsedData",
",",
"options",
")",
"{",
"assertParsedDataIsValid",
"(",
"parsedData",
")",
";",
"const",
"jdlObject",
"=",
"new",
"JDLObject",
"(",
")",
";",
"const",
"jdlEnumArray",
"=",
"convertEnums",
"(",
"parsedData",
".",
"enums",
")",
";",
"addEnumsToJDLObject",
"(",
"jdlObject",
",",
"jdlEnumArray",
")",
";",
"const",
"jdlEntityObject",
"=",
"convertClasses",
"(",
"parsedData",
")",
";",
"addEntitiesToJDLObject",
"(",
"jdlObject",
",",
"jdlEntityObject",
")",
";",
"const",
"jdlRelationshipArray",
"=",
"convertAssociations",
"(",
"parsedData",
",",
"jdlObject",
".",
"entities",
")",
";",
"addRelationshipsToJDLObject",
"(",
"jdlObject",
",",
"jdlRelationshipArray",
")",
";",
"if",
"(",
"options",
")",
"{",
"const",
"jdlOptionArray",
"=",
"convertOptions",
"(",
"options",
",",
"parsedData",
".",
"classNames",
".",
"length",
")",
";",
"addOptionsToJDLObject",
"(",
"jdlObject",
",",
"jdlOptionArray",
")",
";",
"}",
"return",
"jdlObject",
";",
"}"
] |
Converts the parsed data from any XMI file to a JDLObject.
@param parsedData the parsed data.
@param options an object having as keys:
- listDTO,
- listPagination,
- listService,
- listOfNoClient,
- listOfNoServer,
- angularSuffixes,
- microserviceNames,
- searchEngines
|
[
"Converts",
"the",
"parsed",
"data",
"from",
"any",
"XMI",
"file",
"to",
"a",
"JDLObject",
"."
] |
c18334aa05b8b247464560c1849a7809f8c206bc
|
https://github.com/jhipster/jhipster-uml/blob/c18334aa05b8b247464560c1849a7809f8c206bc/lib/export/jdl_exporter.js#L59-L73
|
17,941
|
jhipster/jhipster-uml
|
lib/editors/parser_factory.js
|
createParser
|
function createParser(args) {
if (!args || !args.file || !args.databaseType) {
throw new BuildException(
exceptions.IllegalArgument,
'The file and the database type must be passed');
}
const types = initDatabaseTypeHolder(args.databaseType);
if (args.editor) {
const root = getRootElement(readFileContent(args.file));
return getFileParserByEditor(args.editor, root, types, args.noUserManagement);
}
return getParserForSingleFile(args.file, types, args.noUserManagement);
}
|
javascript
|
function createParser(args) {
if (!args || !args.file || !args.databaseType) {
throw new BuildException(
exceptions.IllegalArgument,
'The file and the database type must be passed');
}
const types = initDatabaseTypeHolder(args.databaseType);
if (args.editor) {
const root = getRootElement(readFileContent(args.file));
return getFileParserByEditor(args.editor, root, types, args.noUserManagement);
}
return getParserForSingleFile(args.file, types, args.noUserManagement);
}
|
[
"function",
"createParser",
"(",
"args",
")",
"{",
"if",
"(",
"!",
"args",
"||",
"!",
"args",
".",
"file",
"||",
"!",
"args",
".",
"databaseType",
")",
"{",
"throw",
"new",
"BuildException",
"(",
"exceptions",
".",
"IllegalArgument",
",",
"'The file and the database type must be passed'",
")",
";",
"}",
"const",
"types",
"=",
"initDatabaseTypeHolder",
"(",
"args",
".",
"databaseType",
")",
";",
"if",
"(",
"args",
".",
"editor",
")",
"{",
"const",
"root",
"=",
"getRootElement",
"(",
"readFileContent",
"(",
"args",
".",
"file",
")",
")",
";",
"return",
"getFileParserByEditor",
"(",
"args",
".",
"editor",
",",
"root",
",",
"types",
",",
"args",
".",
"noUserManagement",
")",
";",
"}",
"return",
"getParserForSingleFile",
"(",
"args",
".",
"file",
",",
"types",
",",
"args",
".",
"noUserManagement",
")",
";",
"}"
] |
Creates a parser.
@param args {Object} the arguments: file, files, databaseType, and the noUserManagement flag.
@return {Parser} the created parser.
|
[
"Creates",
"a",
"parser",
"."
] |
c18334aa05b8b247464560c1849a7809f8c206bc
|
https://github.com/jhipster/jhipster-uml/blob/c18334aa05b8b247464560c1849a7809f8c206bc/lib/editors/parser_factory.js#L39-L51
|
17,942
|
jhipster/jhipster-uml
|
lib/utils/jhipster_utils.js
|
checkForReservedClassName
|
function checkForReservedClassName(args) {
if (!args) {
return;
}
if (JHipsterCore.isReservedClassName(args.name)) {
if (args.shouldThrow) {
throw new BuildException(
exceptions.IllegalName,
`The passed class name '${args.name}' is reserved.`);
} else {
winston.warn(
chalk.yellow(
`The passed class name '${args.name}' is reserved .`));
}
}
}
|
javascript
|
function checkForReservedClassName(args) {
if (!args) {
return;
}
if (JHipsterCore.isReservedClassName(args.name)) {
if (args.shouldThrow) {
throw new BuildException(
exceptions.IllegalName,
`The passed class name '${args.name}' is reserved.`);
} else {
winston.warn(
chalk.yellow(
`The passed class name '${args.name}' is reserved .`));
}
}
}
|
[
"function",
"checkForReservedClassName",
"(",
"args",
")",
"{",
"if",
"(",
"!",
"args",
")",
"{",
"return",
";",
"}",
"if",
"(",
"JHipsterCore",
".",
"isReservedClassName",
"(",
"args",
".",
"name",
")",
")",
"{",
"if",
"(",
"args",
".",
"shouldThrow",
")",
"{",
"throw",
"new",
"BuildException",
"(",
"exceptions",
".",
"IllegalName",
",",
"`",
"${",
"args",
".",
"name",
"}",
"`",
")",
";",
"}",
"else",
"{",
"winston",
".",
"warn",
"(",
"chalk",
".",
"yellow",
"(",
"`",
"${",
"args",
".",
"name",
"}",
"`",
")",
")",
";",
"}",
"}",
"}"
] |
Checks for reserved class name.
@param args an object having as keys: name and shouldThrow
|
[
"Checks",
"for",
"reserved",
"class",
"name",
"."
] |
c18334aa05b8b247464560c1849a7809f8c206bc
|
https://github.com/jhipster/jhipster-uml/blob/c18334aa05b8b247464560c1849a7809f8c206bc/lib/utils/jhipster_utils.js#L61-L76
|
17,943
|
jhipster/jhipster-uml
|
lib/utils/jhipster_utils.js
|
checkForReservedTableName
|
function checkForReservedTableName(args) {
if (!args) {
return;
}
if (args.databaseTypeName) {
checkTableName(args.name, args.databaseTypeName, args.shouldThrow);
} else {
for (let i = 0, types = Object.keys(DatabaseTypes); i < types.length; i++) {
if (typeof DatabaseTypes[types[i]] !== 'function') {
checkTableName(args.name, DatabaseTypes[types[i]], args.shouldThrow);
}
}
}
}
|
javascript
|
function checkForReservedTableName(args) {
if (!args) {
return;
}
if (args.databaseTypeName) {
checkTableName(args.name, args.databaseTypeName, args.shouldThrow);
} else {
for (let i = 0, types = Object.keys(DatabaseTypes); i < types.length; i++) {
if (typeof DatabaseTypes[types[i]] !== 'function') {
checkTableName(args.name, DatabaseTypes[types[i]], args.shouldThrow);
}
}
}
}
|
[
"function",
"checkForReservedTableName",
"(",
"args",
")",
"{",
"if",
"(",
"!",
"args",
")",
"{",
"return",
";",
"}",
"if",
"(",
"args",
".",
"databaseTypeName",
")",
"{",
"checkTableName",
"(",
"args",
".",
"name",
",",
"args",
".",
"databaseTypeName",
",",
"args",
".",
"shouldThrow",
")",
";",
"}",
"else",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"types",
"=",
"Object",
".",
"keys",
"(",
"DatabaseTypes",
")",
";",
"i",
"<",
"types",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"typeof",
"DatabaseTypes",
"[",
"types",
"[",
"i",
"]",
"]",
"!==",
"'function'",
")",
"{",
"checkTableName",
"(",
"args",
".",
"name",
",",
"DatabaseTypes",
"[",
"types",
"[",
"i",
"]",
"]",
",",
"args",
".",
"shouldThrow",
")",
";",
"}",
"}",
"}",
"}"
] |
Checks for reserved table name.
@param args an object having as keys: name, databaseTypeName and shouldThrow
|
[
"Checks",
"for",
"reserved",
"table",
"name",
"."
] |
c18334aa05b8b247464560c1849a7809f8c206bc
|
https://github.com/jhipster/jhipster-uml/blob/c18334aa05b8b247464560c1849a7809f8c206bc/lib/utils/jhipster_utils.js#L82-L95
|
17,944
|
jhipster/jhipster-uml
|
lib/utils/jhipster_utils.js
|
checkForReservedFieldName
|
function checkForReservedFieldName(args) {
if (!args) {
return;
}
if (args.databaseTypeName) {
checkFieldName(args.name, args.databaseTypeName, args.shouldThrow);
} else {
for (let i = 0, types = Object.keys(DatabaseTypes); i < types.length; i++) {
checkFieldName(args.name, DatabaseTypes[types[i]], args.shouldThrow);
}
}
}
|
javascript
|
function checkForReservedFieldName(args) {
if (!args) {
return;
}
if (args.databaseTypeName) {
checkFieldName(args.name, args.databaseTypeName, args.shouldThrow);
} else {
for (let i = 0, types = Object.keys(DatabaseTypes); i < types.length; i++) {
checkFieldName(args.name, DatabaseTypes[types[i]], args.shouldThrow);
}
}
}
|
[
"function",
"checkForReservedFieldName",
"(",
"args",
")",
"{",
"if",
"(",
"!",
"args",
")",
"{",
"return",
";",
"}",
"if",
"(",
"args",
".",
"databaseTypeName",
")",
"{",
"checkFieldName",
"(",
"args",
".",
"name",
",",
"args",
".",
"databaseTypeName",
",",
"args",
".",
"shouldThrow",
")",
";",
"}",
"else",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"types",
"=",
"Object",
".",
"keys",
"(",
"DatabaseTypes",
")",
";",
"i",
"<",
"types",
".",
"length",
";",
"i",
"++",
")",
"{",
"checkFieldName",
"(",
"args",
".",
"name",
",",
"DatabaseTypes",
"[",
"types",
"[",
"i",
"]",
"]",
",",
"args",
".",
"shouldThrow",
")",
";",
"}",
"}",
"}"
] |
Checks for reserved field name.
@param args an object having as keys: name, databaseTypeName and shouldThrow
|
[
"Checks",
"for",
"reserved",
"field",
"name",
"."
] |
c18334aa05b8b247464560c1849a7809f8c206bc
|
https://github.com/jhipster/jhipster-uml/blob/c18334aa05b8b247464560c1849a7809f8c206bc/lib/utils/jhipster_utils.js#L115-L126
|
17,945
|
regularjs/regular
|
lib/helper/watcher.js
|
function(){
if(this.$phase === 'digest' || this._mute) return;
this.$phase = 'digest';
var dirty = false, n =0;
while(dirty = this._digest()){
if((++n) > 20){ // max loop
throw Error('there may a circular dependencies reaches')
}
}
// stable watch is dirty
var stableDirty = this._digest(true);
if( (n > 0 || stableDirty) && this.$emit) {
this.$emit("$update");
if (this.devtools) {
this.devtools.emit("flush", this)
}
}
this.$phase = null;
}
|
javascript
|
function(){
if(this.$phase === 'digest' || this._mute) return;
this.$phase = 'digest';
var dirty = false, n =0;
while(dirty = this._digest()){
if((++n) > 20){ // max loop
throw Error('there may a circular dependencies reaches')
}
}
// stable watch is dirty
var stableDirty = this._digest(true);
if( (n > 0 || stableDirty) && this.$emit) {
this.$emit("$update");
if (this.devtools) {
this.devtools.emit("flush", this)
}
}
this.$phase = null;
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"$phase",
"===",
"'digest'",
"||",
"this",
".",
"_mute",
")",
"return",
";",
"this",
".",
"$phase",
"=",
"'digest'",
";",
"var",
"dirty",
"=",
"false",
",",
"n",
"=",
"0",
";",
"while",
"(",
"dirty",
"=",
"this",
".",
"_digest",
"(",
")",
")",
"{",
"if",
"(",
"(",
"++",
"n",
")",
">",
"20",
")",
"{",
"// max loop",
"throw",
"Error",
"(",
"'there may a circular dependencies reaches'",
")",
"}",
"}",
"// stable watch is dirty",
"var",
"stableDirty",
"=",
"this",
".",
"_digest",
"(",
"true",
")",
";",
"if",
"(",
"(",
"n",
">",
"0",
"||",
"stableDirty",
")",
"&&",
"this",
".",
"$emit",
")",
"{",
"this",
".",
"$emit",
"(",
"\"$update\"",
")",
";",
"if",
"(",
"this",
".",
"devtools",
")",
"{",
"this",
".",
"devtools",
".",
"emit",
"(",
"\"flush\"",
",",
"this",
")",
"}",
"}",
"this",
".",
"$phase",
"=",
"null",
";",
"}"
] |
the whole digest loop ,just like angular, it just a dirty-check loop;
@param {String} path now regular process a pure dirty-check loop, but in parse phase,
Regular's parser extract the dependencies, in future maybe it will change to dirty-check combine with path-aware update;
@return {Void}
|
[
"the",
"whole",
"digest",
"loop",
"just",
"like",
"angular",
"it",
"just",
"a",
"dirty",
"-",
"check",
"loop",
";"
] |
bdb9d43034c1310c3bc8179c1d3a240e22802fba
|
https://github.com/regularjs/regular/blob/bdb9d43034c1310c3bc8179c1d3a240e22802fba/lib/helper/watcher.js#L119-L139
|
|
17,946
|
regularjs/regular
|
lib/helper/watcher.js
|
function(stable){
if(this._mute) return;
var watchers = !stable? this._watchers: this._watchersForStable;
var dirty = false, children, watcher, watcherDirty;
var len = watchers && watchers.length;
if(len){
var mark = 0, needRemoved=0;
for(var i =0; i < len; i++ ){
watcher = watchers[i];
var shouldRemove = !watcher || watcher.removed;
if( shouldRemove ){
needRemoved += 1;
}else{
watcherDirty = this._checkSingleWatch(watcher);
if(watcherDirty) dirty = true;
}
// remove when encounter first unmoved item or touch the end
if( !shouldRemove || i === len-1 ){
if( needRemoved ){
watchers.splice(mark, needRemoved );
len -= needRemoved;
i -= needRemoved;
needRemoved = 0;
}
mark = i+1;
}
}
}
// check children's dirty.
children = this._children;
if(children && children.length){
for(var m = 0, mlen = children.length; m < mlen; m++){
var child = children[m];
if(child && child._digest(stable)) dirty = true;
}
}
return dirty;
}
|
javascript
|
function(stable){
if(this._mute) return;
var watchers = !stable? this._watchers: this._watchersForStable;
var dirty = false, children, watcher, watcherDirty;
var len = watchers && watchers.length;
if(len){
var mark = 0, needRemoved=0;
for(var i =0; i < len; i++ ){
watcher = watchers[i];
var shouldRemove = !watcher || watcher.removed;
if( shouldRemove ){
needRemoved += 1;
}else{
watcherDirty = this._checkSingleWatch(watcher);
if(watcherDirty) dirty = true;
}
// remove when encounter first unmoved item or touch the end
if( !shouldRemove || i === len-1 ){
if( needRemoved ){
watchers.splice(mark, needRemoved );
len -= needRemoved;
i -= needRemoved;
needRemoved = 0;
}
mark = i+1;
}
}
}
// check children's dirty.
children = this._children;
if(children && children.length){
for(var m = 0, mlen = children.length; m < mlen; m++){
var child = children[m];
if(child && child._digest(stable)) dirty = true;
}
}
return dirty;
}
|
[
"function",
"(",
"stable",
")",
"{",
"if",
"(",
"this",
".",
"_mute",
")",
"return",
";",
"var",
"watchers",
"=",
"!",
"stable",
"?",
"this",
".",
"_watchers",
":",
"this",
".",
"_watchersForStable",
";",
"var",
"dirty",
"=",
"false",
",",
"children",
",",
"watcher",
",",
"watcherDirty",
";",
"var",
"len",
"=",
"watchers",
"&&",
"watchers",
".",
"length",
";",
"if",
"(",
"len",
")",
"{",
"var",
"mark",
"=",
"0",
",",
"needRemoved",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"watcher",
"=",
"watchers",
"[",
"i",
"]",
";",
"var",
"shouldRemove",
"=",
"!",
"watcher",
"||",
"watcher",
".",
"removed",
";",
"if",
"(",
"shouldRemove",
")",
"{",
"needRemoved",
"+=",
"1",
";",
"}",
"else",
"{",
"watcherDirty",
"=",
"this",
".",
"_checkSingleWatch",
"(",
"watcher",
")",
";",
"if",
"(",
"watcherDirty",
")",
"dirty",
"=",
"true",
";",
"}",
"// remove when encounter first unmoved item or touch the end",
"if",
"(",
"!",
"shouldRemove",
"||",
"i",
"===",
"len",
"-",
"1",
")",
"{",
"if",
"(",
"needRemoved",
")",
"{",
"watchers",
".",
"splice",
"(",
"mark",
",",
"needRemoved",
")",
";",
"len",
"-=",
"needRemoved",
";",
"i",
"-=",
"needRemoved",
";",
"needRemoved",
"=",
"0",
";",
"}",
"mark",
"=",
"i",
"+",
"1",
";",
"}",
"}",
"}",
"// check children's dirty.",
"children",
"=",
"this",
".",
"_children",
";",
"if",
"(",
"children",
"&&",
"children",
".",
"length",
")",
"{",
"for",
"(",
"var",
"m",
"=",
"0",
",",
"mlen",
"=",
"children",
".",
"length",
";",
"m",
"<",
"mlen",
";",
"m",
"++",
")",
"{",
"var",
"child",
"=",
"children",
"[",
"m",
"]",
";",
"if",
"(",
"child",
"&&",
"child",
".",
"_digest",
"(",
"stable",
")",
")",
"dirty",
"=",
"true",
";",
"}",
"}",
"return",
"dirty",
";",
"}"
] |
private digest logic
|
[
"private",
"digest",
"logic"
] |
bdb9d43034c1310c3bc8179c1d3a240e22802fba
|
https://github.com/regularjs/regular/blob/bdb9d43034c1310c3bc8179c1d3a240e22802fba/lib/helper/watcher.js#L141-L178
|
|
17,947
|
regularjs/regular
|
lib/helper/watcher.js
|
function(watcher){
var dirty = false;
if(!watcher) return;
var now, last, tlast, tnow,
eq, diff, keyOf, trackDiff
if(!watcher.test){
now = watcher.get(this);
last = watcher.last;
keyOf = watcher.keyOf
if(now !== last || watcher.force){
tlast = _.typeOf(last);
tnow = _.typeOf(now);
eq = true;
// !Object
if( !(tnow === 'object' && tlast==='object' && watcher.deep) ){
// Array
if( tnow === 'array' && ( tlast=='undefined' || tlast === 'array') ){
if(typeof keyOf === 'function'){
trackDiff = diffTrack(now, watcher.last || [], keyOf )
diff = trackDiff.steps;
if(trackDiff.dirty) dirty = true;
}else{
diff = diffArray(now, watcher.last || [], watcher.diff)
}
if(!dirty && (tlast !== 'array' || diff === true || diff.length) ) dirty = true;
}else{
eq = _.equals( now, last );
if( !eq || watcher.force ){
watcher.force = null;
dirty = true;
}
}
}else{
diff = diffObject( now, last, watcher.diff, keyOf );
if(diff.isTrack){
trackDiff = diff;
diff = trackDiff.steps;
}
if( diff === true || diff.length ) dirty = true;
}
}
} else{
// @TODO 是否把多重改掉
var result = watcher.test(this);
if(result){
dirty = true;
watcher.fn.apply(this, result)
}
}
if(dirty && !watcher.test){
if(tnow === 'object' && watcher.deep || tnow === 'array'){
watcher.last = _.clone(now);
}else{
watcher.last = now;
}
watcher.fn.call(this, now, last, diff, trackDiff && trackDiff.oldKeyMap, trackDiff && trackDiff.dirty)
if(watcher.once) this.$unwatch(watcher)
}
return dirty;
}
|
javascript
|
function(watcher){
var dirty = false;
if(!watcher) return;
var now, last, tlast, tnow,
eq, diff, keyOf, trackDiff
if(!watcher.test){
now = watcher.get(this);
last = watcher.last;
keyOf = watcher.keyOf
if(now !== last || watcher.force){
tlast = _.typeOf(last);
tnow = _.typeOf(now);
eq = true;
// !Object
if( !(tnow === 'object' && tlast==='object' && watcher.deep) ){
// Array
if( tnow === 'array' && ( tlast=='undefined' || tlast === 'array') ){
if(typeof keyOf === 'function'){
trackDiff = diffTrack(now, watcher.last || [], keyOf )
diff = trackDiff.steps;
if(trackDiff.dirty) dirty = true;
}else{
diff = diffArray(now, watcher.last || [], watcher.diff)
}
if(!dirty && (tlast !== 'array' || diff === true || diff.length) ) dirty = true;
}else{
eq = _.equals( now, last );
if( !eq || watcher.force ){
watcher.force = null;
dirty = true;
}
}
}else{
diff = diffObject( now, last, watcher.diff, keyOf );
if(diff.isTrack){
trackDiff = diff;
diff = trackDiff.steps;
}
if( diff === true || diff.length ) dirty = true;
}
}
} else{
// @TODO 是否把多重改掉
var result = watcher.test(this);
if(result){
dirty = true;
watcher.fn.apply(this, result)
}
}
if(dirty && !watcher.test){
if(tnow === 'object' && watcher.deep || tnow === 'array'){
watcher.last = _.clone(now);
}else{
watcher.last = now;
}
watcher.fn.call(this, now, last, diff, trackDiff && trackDiff.oldKeyMap, trackDiff && trackDiff.dirty)
if(watcher.once) this.$unwatch(watcher)
}
return dirty;
}
|
[
"function",
"(",
"watcher",
")",
"{",
"var",
"dirty",
"=",
"false",
";",
"if",
"(",
"!",
"watcher",
")",
"return",
";",
"var",
"now",
",",
"last",
",",
"tlast",
",",
"tnow",
",",
"eq",
",",
"diff",
",",
"keyOf",
",",
"trackDiff",
"if",
"(",
"!",
"watcher",
".",
"test",
")",
"{",
"now",
"=",
"watcher",
".",
"get",
"(",
"this",
")",
";",
"last",
"=",
"watcher",
".",
"last",
";",
"keyOf",
"=",
"watcher",
".",
"keyOf",
"if",
"(",
"now",
"!==",
"last",
"||",
"watcher",
".",
"force",
")",
"{",
"tlast",
"=",
"_",
".",
"typeOf",
"(",
"last",
")",
";",
"tnow",
"=",
"_",
".",
"typeOf",
"(",
"now",
")",
";",
"eq",
"=",
"true",
";",
"// !Object",
"if",
"(",
"!",
"(",
"tnow",
"===",
"'object'",
"&&",
"tlast",
"===",
"'object'",
"&&",
"watcher",
".",
"deep",
")",
")",
"{",
"// Array",
"if",
"(",
"tnow",
"===",
"'array'",
"&&",
"(",
"tlast",
"==",
"'undefined'",
"||",
"tlast",
"===",
"'array'",
")",
")",
"{",
"if",
"(",
"typeof",
"keyOf",
"===",
"'function'",
")",
"{",
"trackDiff",
"=",
"diffTrack",
"(",
"now",
",",
"watcher",
".",
"last",
"||",
"[",
"]",
",",
"keyOf",
")",
"diff",
"=",
"trackDiff",
".",
"steps",
";",
"if",
"(",
"trackDiff",
".",
"dirty",
")",
"dirty",
"=",
"true",
";",
"}",
"else",
"{",
"diff",
"=",
"diffArray",
"(",
"now",
",",
"watcher",
".",
"last",
"||",
"[",
"]",
",",
"watcher",
".",
"diff",
")",
"}",
"if",
"(",
"!",
"dirty",
"&&",
"(",
"tlast",
"!==",
"'array'",
"||",
"diff",
"===",
"true",
"||",
"diff",
".",
"length",
")",
")",
"dirty",
"=",
"true",
";",
"}",
"else",
"{",
"eq",
"=",
"_",
".",
"equals",
"(",
"now",
",",
"last",
")",
";",
"if",
"(",
"!",
"eq",
"||",
"watcher",
".",
"force",
")",
"{",
"watcher",
".",
"force",
"=",
"null",
";",
"dirty",
"=",
"true",
";",
"}",
"}",
"}",
"else",
"{",
"diff",
"=",
"diffObject",
"(",
"now",
",",
"last",
",",
"watcher",
".",
"diff",
",",
"keyOf",
")",
";",
"if",
"(",
"diff",
".",
"isTrack",
")",
"{",
"trackDiff",
"=",
"diff",
";",
"diff",
"=",
"trackDiff",
".",
"steps",
";",
"}",
"if",
"(",
"diff",
"===",
"true",
"||",
"diff",
".",
"length",
")",
"dirty",
"=",
"true",
";",
"}",
"}",
"}",
"else",
"{",
"// @TODO 是否把多重改掉",
"var",
"result",
"=",
"watcher",
".",
"test",
"(",
"this",
")",
";",
"if",
"(",
"result",
")",
"{",
"dirty",
"=",
"true",
";",
"watcher",
".",
"fn",
".",
"apply",
"(",
"this",
",",
"result",
")",
"}",
"}",
"if",
"(",
"dirty",
"&&",
"!",
"watcher",
".",
"test",
")",
"{",
"if",
"(",
"tnow",
"===",
"'object'",
"&&",
"watcher",
".",
"deep",
"||",
"tnow",
"===",
"'array'",
")",
"{",
"watcher",
".",
"last",
"=",
"_",
".",
"clone",
"(",
"now",
")",
";",
"}",
"else",
"{",
"watcher",
".",
"last",
"=",
"now",
";",
"}",
"watcher",
".",
"fn",
".",
"call",
"(",
"this",
",",
"now",
",",
"last",
",",
"diff",
",",
"trackDiff",
"&&",
"trackDiff",
".",
"oldKeyMap",
",",
"trackDiff",
"&&",
"trackDiff",
".",
"dirty",
")",
"if",
"(",
"watcher",
".",
"once",
")",
"this",
".",
"$unwatch",
"(",
"watcher",
")",
"}",
"return",
"dirty",
";",
"}"
] |
check a single one watcher
|
[
"check",
"a",
"single",
"one",
"watcher"
] |
bdb9d43034c1310c3bc8179c1d3a240e22802fba
|
https://github.com/regularjs/regular/blob/bdb9d43034c1310c3bc8179c1d3a240e22802fba/lib/helper/watcher.js#L180-L248
|
|
17,948
|
regularjs/regular
|
lib/helper/combine.js
|
function(item){
var children,node, nodes;
if(!item) return;
if(typeof item.node === "function") return item.node();
if(typeof item.nodeType === "number") return item;
if(item.group) return combine.node(item.group)
item = item.children || item;
if( Array.isArray(item )){
var len = item.length;
if(len === 1){
return combine.node(item[0]);
}
nodes = [];
for(var i = 0, len = item.length; i < len; i++ ){
node = combine.node(item[i]);
if(Array.isArray(node)){
for (var j = 0, len1 = node.length; j < len1; j++){
nodes.push(node[j])
}
}else if(node) {
nodes.push(node)
}
}
return nodes;
}
}
|
javascript
|
function(item){
var children,node, nodes;
if(!item) return;
if(typeof item.node === "function") return item.node();
if(typeof item.nodeType === "number") return item;
if(item.group) return combine.node(item.group)
item = item.children || item;
if( Array.isArray(item )){
var len = item.length;
if(len === 1){
return combine.node(item[0]);
}
nodes = [];
for(var i = 0, len = item.length; i < len; i++ ){
node = combine.node(item[i]);
if(Array.isArray(node)){
for (var j = 0, len1 = node.length; j < len1; j++){
nodes.push(node[j])
}
}else if(node) {
nodes.push(node)
}
}
return nodes;
}
}
|
[
"function",
"(",
"item",
")",
"{",
"var",
"children",
",",
"node",
",",
"nodes",
";",
"if",
"(",
"!",
"item",
")",
"return",
";",
"if",
"(",
"typeof",
"item",
".",
"node",
"===",
"\"function\"",
")",
"return",
"item",
".",
"node",
"(",
")",
";",
"if",
"(",
"typeof",
"item",
".",
"nodeType",
"===",
"\"number\"",
")",
"return",
"item",
";",
"if",
"(",
"item",
".",
"group",
")",
"return",
"combine",
".",
"node",
"(",
"item",
".",
"group",
")",
"item",
"=",
"item",
".",
"children",
"||",
"item",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"item",
")",
")",
"{",
"var",
"len",
"=",
"item",
".",
"length",
";",
"if",
"(",
"len",
"===",
"1",
")",
"{",
"return",
"combine",
".",
"node",
"(",
"item",
"[",
"0",
"]",
")",
";",
"}",
"nodes",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"item",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"node",
"=",
"combine",
".",
"node",
"(",
"item",
"[",
"i",
"]",
")",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"node",
")",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
",",
"len1",
"=",
"node",
".",
"length",
";",
"j",
"<",
"len1",
";",
"j",
"++",
")",
"{",
"nodes",
".",
"push",
"(",
"node",
"[",
"j",
"]",
")",
"}",
"}",
"else",
"if",
"(",
"node",
")",
"{",
"nodes",
".",
"push",
"(",
"node",
")",
"}",
"}",
"return",
"nodes",
";",
"}",
"}"
] |
get the initial dom in object
|
[
"get",
"the",
"initial",
"dom",
"in",
"object"
] |
bdb9d43034c1310c3bc8179c1d3a240e22802fba
|
https://github.com/regularjs/regular/blob/bdb9d43034c1310c3bc8179c1d3a240e22802fba/lib/helper/combine.js#L10-L37
|
|
17,949
|
regularjs/regular
|
lib/helper/diff.js
|
ld
|
function ld(array1, array2, equalFn){
var n = array1.length;
var m = array2.length;
var equalFn = equalFn || equals;
var matrix = [];
for(var i = 0; i <= n; i++){
matrix.push([i]);
}
for(var j=1;j<=m;j++){
matrix[0][j]=j;
}
for(var i = 1; i <= n; i++){
for(var j = 1; j <= m; j++){
if(equalFn(array1[i-1], array2[j-1])){
matrix[i][j] = matrix[i-1][j-1];
}else{
matrix[i][j] = Math.min(
matrix[i-1][j]+1, //delete
matrix[i][j-1]+1//add
)
}
}
}
return matrix;
}
|
javascript
|
function ld(array1, array2, equalFn){
var n = array1.length;
var m = array2.length;
var equalFn = equalFn || equals;
var matrix = [];
for(var i = 0; i <= n; i++){
matrix.push([i]);
}
for(var j=1;j<=m;j++){
matrix[0][j]=j;
}
for(var i = 1; i <= n; i++){
for(var j = 1; j <= m; j++){
if(equalFn(array1[i-1], array2[j-1])){
matrix[i][j] = matrix[i-1][j-1];
}else{
matrix[i][j] = Math.min(
matrix[i-1][j]+1, //delete
matrix[i][j-1]+1//add
)
}
}
}
return matrix;
}
|
[
"function",
"ld",
"(",
"array1",
",",
"array2",
",",
"equalFn",
")",
"{",
"var",
"n",
"=",
"array1",
".",
"length",
";",
"var",
"m",
"=",
"array2",
".",
"length",
";",
"var",
"equalFn",
"=",
"equalFn",
"||",
"equals",
";",
"var",
"matrix",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<=",
"n",
";",
"i",
"++",
")",
"{",
"matrix",
".",
"push",
"(",
"[",
"i",
"]",
")",
";",
"}",
"for",
"(",
"var",
"j",
"=",
"1",
";",
"j",
"<=",
"m",
";",
"j",
"++",
")",
"{",
"matrix",
"[",
"0",
"]",
"[",
"j",
"]",
"=",
"j",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<=",
"n",
";",
"i",
"++",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"1",
";",
"j",
"<=",
"m",
";",
"j",
"++",
")",
"{",
"if",
"(",
"equalFn",
"(",
"array1",
"[",
"i",
"-",
"1",
"]",
",",
"array2",
"[",
"j",
"-",
"1",
"]",
")",
")",
"{",
"matrix",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"matrix",
"[",
"i",
"-",
"1",
"]",
"[",
"j",
"-",
"1",
"]",
";",
"}",
"else",
"{",
"matrix",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"Math",
".",
"min",
"(",
"matrix",
"[",
"i",
"-",
"1",
"]",
"[",
"j",
"]",
"+",
"1",
",",
"//delete",
"matrix",
"[",
"i",
"]",
"[",
"j",
"-",
"1",
"]",
"+",
"1",
"//add",
")",
"}",
"}",
"}",
"return",
"matrix",
";",
"}"
] |
array1 - old array array2 - new array
|
[
"array1",
"-",
"old",
"array",
"array2",
"-",
"new",
"array"
] |
bdb9d43034c1310c3bc8179c1d3a240e22802fba
|
https://github.com/regularjs/regular/blob/bdb9d43034c1310c3bc8179c1d3a240e22802fba/lib/helper/diff.js#L11-L35
|
17,950
|
regularjs/regular
|
lib/helper/diff.js
|
diffArray
|
function diffArray(arr2, arr1, diff, diffFn) {
if(!diff) return _.simpleDiff(arr2, arr1);
var matrix = ld(arr1, arr2, diffFn)
var n = arr1.length;
var i = n;
var m = arr2.length;
var j = m;
var edits = [];
var current = matrix[i][j];
while(i>0 || j>0){
// the last line
if (i === 0) {
edits.unshift(3);
j--;
continue;
}
// the last col
if (j === 0) {
edits.unshift(2);
i--;
continue;
}
var northWest = matrix[i - 1][j - 1];
var west = matrix[i - 1][j];
var north = matrix[i][j - 1];
var min = Math.min(north, west, northWest);
if (min === west) {
edits.unshift(2); //delete
i--;
current = west;
} else if (min === northWest ) {
if (northWest === current) {
edits.unshift(0); //no change
} else {
edits.unshift(1); //update
current = northWest;
}
i--;
j--;
} else {
edits.unshift(3); //add
j--;
current = north;
}
}
var LEAVE = 0;
var ADD = 3;
var DELELE = 2;
var UPDATE = 1;
var n = 0;m=0;
var steps = [];
var step = { index: null, add:0, removed:[] };
for(var i=0;i<edits.length;i++){
if(edits[i] > 0 ){ // NOT LEAVE
if(step.index === null){
step.index = m;
}
} else { //LEAVE
if(step.index != null){
steps.push(step)
step = {index: null, add:0, removed:[]};
}
}
switch(edits[i]){
case LEAVE:
n++;
m++;
break;
case ADD:
step.add++;
m++;
break;
case DELELE:
step.removed.push(arr1[n])
n++;
break;
case UPDATE:
step.add++;
step.removed.push(arr1[n])
n++;
m++;
break;
}
}
if(step.index != null){
steps.push(step)
}
return steps
}
|
javascript
|
function diffArray(arr2, arr1, diff, diffFn) {
if(!diff) return _.simpleDiff(arr2, arr1);
var matrix = ld(arr1, arr2, diffFn)
var n = arr1.length;
var i = n;
var m = arr2.length;
var j = m;
var edits = [];
var current = matrix[i][j];
while(i>0 || j>0){
// the last line
if (i === 0) {
edits.unshift(3);
j--;
continue;
}
// the last col
if (j === 0) {
edits.unshift(2);
i--;
continue;
}
var northWest = matrix[i - 1][j - 1];
var west = matrix[i - 1][j];
var north = matrix[i][j - 1];
var min = Math.min(north, west, northWest);
if (min === west) {
edits.unshift(2); //delete
i--;
current = west;
} else if (min === northWest ) {
if (northWest === current) {
edits.unshift(0); //no change
} else {
edits.unshift(1); //update
current = northWest;
}
i--;
j--;
} else {
edits.unshift(3); //add
j--;
current = north;
}
}
var LEAVE = 0;
var ADD = 3;
var DELELE = 2;
var UPDATE = 1;
var n = 0;m=0;
var steps = [];
var step = { index: null, add:0, removed:[] };
for(var i=0;i<edits.length;i++){
if(edits[i] > 0 ){ // NOT LEAVE
if(step.index === null){
step.index = m;
}
} else { //LEAVE
if(step.index != null){
steps.push(step)
step = {index: null, add:0, removed:[]};
}
}
switch(edits[i]){
case LEAVE:
n++;
m++;
break;
case ADD:
step.add++;
m++;
break;
case DELELE:
step.removed.push(arr1[n])
n++;
break;
case UPDATE:
step.add++;
step.removed.push(arr1[n])
n++;
m++;
break;
}
}
if(step.index != null){
steps.push(step)
}
return steps
}
|
[
"function",
"diffArray",
"(",
"arr2",
",",
"arr1",
",",
"diff",
",",
"diffFn",
")",
"{",
"if",
"(",
"!",
"diff",
")",
"return",
"_",
".",
"simpleDiff",
"(",
"arr2",
",",
"arr1",
")",
";",
"var",
"matrix",
"=",
"ld",
"(",
"arr1",
",",
"arr2",
",",
"diffFn",
")",
"var",
"n",
"=",
"arr1",
".",
"length",
";",
"var",
"i",
"=",
"n",
";",
"var",
"m",
"=",
"arr2",
".",
"length",
";",
"var",
"j",
"=",
"m",
";",
"var",
"edits",
"=",
"[",
"]",
";",
"var",
"current",
"=",
"matrix",
"[",
"i",
"]",
"[",
"j",
"]",
";",
"while",
"(",
"i",
">",
"0",
"||",
"j",
">",
"0",
")",
"{",
"// the last line",
"if",
"(",
"i",
"===",
"0",
")",
"{",
"edits",
".",
"unshift",
"(",
"3",
")",
";",
"j",
"--",
";",
"continue",
";",
"}",
"// the last col",
"if",
"(",
"j",
"===",
"0",
")",
"{",
"edits",
".",
"unshift",
"(",
"2",
")",
";",
"i",
"--",
";",
"continue",
";",
"}",
"var",
"northWest",
"=",
"matrix",
"[",
"i",
"-",
"1",
"]",
"[",
"j",
"-",
"1",
"]",
";",
"var",
"west",
"=",
"matrix",
"[",
"i",
"-",
"1",
"]",
"[",
"j",
"]",
";",
"var",
"north",
"=",
"matrix",
"[",
"i",
"]",
"[",
"j",
"-",
"1",
"]",
";",
"var",
"min",
"=",
"Math",
".",
"min",
"(",
"north",
",",
"west",
",",
"northWest",
")",
";",
"if",
"(",
"min",
"===",
"west",
")",
"{",
"edits",
".",
"unshift",
"(",
"2",
")",
";",
"//delete",
"i",
"--",
";",
"current",
"=",
"west",
";",
"}",
"else",
"if",
"(",
"min",
"===",
"northWest",
")",
"{",
"if",
"(",
"northWest",
"===",
"current",
")",
"{",
"edits",
".",
"unshift",
"(",
"0",
")",
";",
"//no change",
"}",
"else",
"{",
"edits",
".",
"unshift",
"(",
"1",
")",
";",
"//update",
"current",
"=",
"northWest",
";",
"}",
"i",
"--",
";",
"j",
"--",
";",
"}",
"else",
"{",
"edits",
".",
"unshift",
"(",
"3",
")",
";",
"//add",
"j",
"--",
";",
"current",
"=",
"north",
";",
"}",
"}",
"var",
"LEAVE",
"=",
"0",
";",
"var",
"ADD",
"=",
"3",
";",
"var",
"DELELE",
"=",
"2",
";",
"var",
"UPDATE",
"=",
"1",
";",
"var",
"n",
"=",
"0",
";",
"m",
"=",
"0",
";",
"var",
"steps",
"=",
"[",
"]",
";",
"var",
"step",
"=",
"{",
"index",
":",
"null",
",",
"add",
":",
"0",
",",
"removed",
":",
"[",
"]",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"edits",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"edits",
"[",
"i",
"]",
">",
"0",
")",
"{",
"// NOT LEAVE",
"if",
"(",
"step",
".",
"index",
"===",
"null",
")",
"{",
"step",
".",
"index",
"=",
"m",
";",
"}",
"}",
"else",
"{",
"//LEAVE",
"if",
"(",
"step",
".",
"index",
"!=",
"null",
")",
"{",
"steps",
".",
"push",
"(",
"step",
")",
"step",
"=",
"{",
"index",
":",
"null",
",",
"add",
":",
"0",
",",
"removed",
":",
"[",
"]",
"}",
";",
"}",
"}",
"switch",
"(",
"edits",
"[",
"i",
"]",
")",
"{",
"case",
"LEAVE",
":",
"n",
"++",
";",
"m",
"++",
";",
"break",
";",
"case",
"ADD",
":",
"step",
".",
"add",
"++",
";",
"m",
"++",
";",
"break",
";",
"case",
"DELELE",
":",
"step",
".",
"removed",
".",
"push",
"(",
"arr1",
"[",
"n",
"]",
")",
"n",
"++",
";",
"break",
";",
"case",
"UPDATE",
":",
"step",
".",
"add",
"++",
";",
"step",
".",
"removed",
".",
"push",
"(",
"arr1",
"[",
"n",
"]",
")",
"n",
"++",
";",
"m",
"++",
";",
"break",
";",
"}",
"}",
"if",
"(",
"step",
".",
"index",
"!=",
"null",
")",
"{",
"steps",
".",
"push",
"(",
"step",
")",
"}",
"return",
"steps",
"}"
] |
arr2 - new array arr1 - old array
|
[
"arr2",
"-",
"new",
"array",
"arr1",
"-",
"old",
"array"
] |
bdb9d43034c1310c3bc8179c1d3a240e22802fba
|
https://github.com/regularjs/regular/blob/bdb9d43034c1310c3bc8179c1d3a240e22802fba/lib/helper/diff.js#L38-L129
|
17,951
|
regularjs/regular
|
lib/render/shared.js
|
wrapSet
|
function wrapSet(set){
return function(context, value){
set.call( context, value, context.data );
return value;
}
}
|
javascript
|
function wrapSet(set){
return function(context, value){
set.call( context, value, context.data );
return value;
}
}
|
[
"function",
"wrapSet",
"(",
"set",
")",
"{",
"return",
"function",
"(",
"context",
",",
"value",
")",
"{",
"set",
".",
"call",
"(",
"context",
",",
"value",
",",
"context",
".",
"data",
")",
";",
"return",
"value",
";",
"}",
"}"
] |
wrap the computed setter;
|
[
"wrap",
"the",
"computed",
"setter",
";"
] |
bdb9d43034c1310c3bc8179c1d3a240e22802fba
|
https://github.com/regularjs/regular/blob/bdb9d43034c1310c3bc8179c1d3a240e22802fba/lib/render/shared.js#L82-L87
|
17,952
|
regularjs/regular
|
lib/parser/FSM.js
|
createFSM
|
function createFSM() {
return {
_stack: [],
enter: function(state) {
this._stack.push(state);
return this;
},
leave: function(state) {
var stack = this._stack;
// if state is falsy or state equals to last item in stack
if(!state || stack[stack.length-1] === state) {
stack.pop();
}
return this;
},
get: function() {
var stack = this._stack;
return stack[stack.length - 1];
},
all: function() {
return this._stack;
},
is: function(state) {
var stack = this._stack;
return stack[stack.length - 1] === state
}
}
}
|
javascript
|
function createFSM() {
return {
_stack: [],
enter: function(state) {
this._stack.push(state);
return this;
},
leave: function(state) {
var stack = this._stack;
// if state is falsy or state equals to last item in stack
if(!state || stack[stack.length-1] === state) {
stack.pop();
}
return this;
},
get: function() {
var stack = this._stack;
return stack[stack.length - 1];
},
all: function() {
return this._stack;
},
is: function(state) {
var stack = this._stack;
return stack[stack.length - 1] === state
}
}
}
|
[
"function",
"createFSM",
"(",
")",
"{",
"return",
"{",
"_stack",
":",
"[",
"]",
",",
"enter",
":",
"function",
"(",
"state",
")",
"{",
"this",
".",
"_stack",
".",
"push",
"(",
"state",
")",
";",
"return",
"this",
";",
"}",
",",
"leave",
":",
"function",
"(",
"state",
")",
"{",
"var",
"stack",
"=",
"this",
".",
"_stack",
";",
"// if state is falsy or state equals to last item in stack",
"if",
"(",
"!",
"state",
"||",
"stack",
"[",
"stack",
".",
"length",
"-",
"1",
"]",
"===",
"state",
")",
"{",
"stack",
".",
"pop",
"(",
")",
";",
"}",
"return",
"this",
";",
"}",
",",
"get",
":",
"function",
"(",
")",
"{",
"var",
"stack",
"=",
"this",
".",
"_stack",
";",
"return",
"stack",
"[",
"stack",
".",
"length",
"-",
"1",
"]",
";",
"}",
",",
"all",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"_stack",
";",
"}",
",",
"is",
":",
"function",
"(",
"state",
")",
"{",
"var",
"stack",
"=",
"this",
".",
"_stack",
";",
"return",
"stack",
"[",
"stack",
".",
"length",
"-",
"1",
"]",
"===",
"state",
"}",
"}",
"}"
] |
create a simple finite state machine
|
[
"create",
"a",
"simple",
"finite",
"state",
"machine"
] |
bdb9d43034c1310c3bc8179c1d3a240e22802fba
|
https://github.com/regularjs/regular/blob/bdb9d43034c1310c3bc8179c1d3a240e22802fba/lib/parser/FSM.js#L2-L29
|
17,953
|
regularjs/regular
|
lib/render/client.js
|
function(definition, options){
var prevRunning = env.isRunning;
env.isRunning = true;
var node, template, cursor, context = this, body, mountNode;
options = options || {};
definition = definition || {};
var dtemplate = definition.template;
if(env.browser) {
if( node = tryGetSelector( dtemplate ) ){
dtemplate = node;
}
if( dtemplate && dtemplate.nodeType ){
definition.template = dtemplate.innerHTML
}
mountNode = definition.mountNode;
if(typeof mountNode === 'string'){
mountNode = dom.find( mountNode );
if(!mountNode) throw Error('mountNode ' + mountNode + ' is not found')
}
if(mountNode){
cursor = nodeCursor(mountNode.firstChild, mountNode)
delete definition.mountNode
}else{
cursor = options.cursor
}
}
template = shared.initDefinition(context, definition)
if(context.$parent){
context.$parent._append(context);
}
context._children = [];
context.$refs = {};
context.$root = context.$root || context;
var extra = options.extra;
var oldModify = extra && extra.$$modify;
var newExtra;
if( body = context._body ){
context._body = null
var modifyBodyComponent = context.modifyBodyComponent;
if( typeof modifyBodyComponent === 'function'){
modifyBodyComponent = modifyBodyComponent.bind(this)
newExtra = _.createObject(extra);
newExtra.$$modify = function( comp ){
return modifyBodyComponent(comp, oldModify? oldModify: NOOP)
}
}else{ //@FIXIT: multiply modifier
newExtra = extra
}
if(body.ast && body.ast.length){
context.$body = _.getCompileFn(body.ast, body.ctx , {
outer: context,
namespace: options.namespace,
extra: newExtra,
record: true
})
}
}
// handle computed
if(template){
var cplOpt = {
namespace: options.namespace,
cursor: cursor
}
// if(extra && extra.$$modify){
cplOpt.extra = {$$modify : extra&& extra.$$modify}
// }
context.group = context.$compile(template, cplOpt);
combine.node(context);
}
// modify在compile之后调用, 这样就无需处理SSR相关逻辑
if( oldModify ){
oldModify(this);
}
// this is outest component
if( !context.$parent ) context.$update();
context.$ready = true;
context.$emit("$init");
if( context.init ) context.init( context.data );
context.$emit("$afterInit");
env.isRunning = prevRunning;
// children is not required;
if (this.devtools) {
this.devtools.emit("init", this)
}
}
|
javascript
|
function(definition, options){
var prevRunning = env.isRunning;
env.isRunning = true;
var node, template, cursor, context = this, body, mountNode;
options = options || {};
definition = definition || {};
var dtemplate = definition.template;
if(env.browser) {
if( node = tryGetSelector( dtemplate ) ){
dtemplate = node;
}
if( dtemplate && dtemplate.nodeType ){
definition.template = dtemplate.innerHTML
}
mountNode = definition.mountNode;
if(typeof mountNode === 'string'){
mountNode = dom.find( mountNode );
if(!mountNode) throw Error('mountNode ' + mountNode + ' is not found')
}
if(mountNode){
cursor = nodeCursor(mountNode.firstChild, mountNode)
delete definition.mountNode
}else{
cursor = options.cursor
}
}
template = shared.initDefinition(context, definition)
if(context.$parent){
context.$parent._append(context);
}
context._children = [];
context.$refs = {};
context.$root = context.$root || context;
var extra = options.extra;
var oldModify = extra && extra.$$modify;
var newExtra;
if( body = context._body ){
context._body = null
var modifyBodyComponent = context.modifyBodyComponent;
if( typeof modifyBodyComponent === 'function'){
modifyBodyComponent = modifyBodyComponent.bind(this)
newExtra = _.createObject(extra);
newExtra.$$modify = function( comp ){
return modifyBodyComponent(comp, oldModify? oldModify: NOOP)
}
}else{ //@FIXIT: multiply modifier
newExtra = extra
}
if(body.ast && body.ast.length){
context.$body = _.getCompileFn(body.ast, body.ctx , {
outer: context,
namespace: options.namespace,
extra: newExtra,
record: true
})
}
}
// handle computed
if(template){
var cplOpt = {
namespace: options.namespace,
cursor: cursor
}
// if(extra && extra.$$modify){
cplOpt.extra = {$$modify : extra&& extra.$$modify}
// }
context.group = context.$compile(template, cplOpt);
combine.node(context);
}
// modify在compile之后调用, 这样就无需处理SSR相关逻辑
if( oldModify ){
oldModify(this);
}
// this is outest component
if( !context.$parent ) context.$update();
context.$ready = true;
context.$emit("$init");
if( context.init ) context.init( context.data );
context.$emit("$afterInit");
env.isRunning = prevRunning;
// children is not required;
if (this.devtools) {
this.devtools.emit("init", this)
}
}
|
[
"function",
"(",
"definition",
",",
"options",
")",
"{",
"var",
"prevRunning",
"=",
"env",
".",
"isRunning",
";",
"env",
".",
"isRunning",
"=",
"true",
";",
"var",
"node",
",",
"template",
",",
"cursor",
",",
"context",
"=",
"this",
",",
"body",
",",
"mountNode",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"definition",
"=",
"definition",
"||",
"{",
"}",
";",
"var",
"dtemplate",
"=",
"definition",
".",
"template",
";",
"if",
"(",
"env",
".",
"browser",
")",
"{",
"if",
"(",
"node",
"=",
"tryGetSelector",
"(",
"dtemplate",
")",
")",
"{",
"dtemplate",
"=",
"node",
";",
"}",
"if",
"(",
"dtemplate",
"&&",
"dtemplate",
".",
"nodeType",
")",
"{",
"definition",
".",
"template",
"=",
"dtemplate",
".",
"innerHTML",
"}",
"mountNode",
"=",
"definition",
".",
"mountNode",
";",
"if",
"(",
"typeof",
"mountNode",
"===",
"'string'",
")",
"{",
"mountNode",
"=",
"dom",
".",
"find",
"(",
"mountNode",
")",
";",
"if",
"(",
"!",
"mountNode",
")",
"throw",
"Error",
"(",
"'mountNode '",
"+",
"mountNode",
"+",
"' is not found'",
")",
"}",
"if",
"(",
"mountNode",
")",
"{",
"cursor",
"=",
"nodeCursor",
"(",
"mountNode",
".",
"firstChild",
",",
"mountNode",
")",
"delete",
"definition",
".",
"mountNode",
"}",
"else",
"{",
"cursor",
"=",
"options",
".",
"cursor",
"}",
"}",
"template",
"=",
"shared",
".",
"initDefinition",
"(",
"context",
",",
"definition",
")",
"if",
"(",
"context",
".",
"$parent",
")",
"{",
"context",
".",
"$parent",
".",
"_append",
"(",
"context",
")",
";",
"}",
"context",
".",
"_children",
"=",
"[",
"]",
";",
"context",
".",
"$refs",
"=",
"{",
"}",
";",
"context",
".",
"$root",
"=",
"context",
".",
"$root",
"||",
"context",
";",
"var",
"extra",
"=",
"options",
".",
"extra",
";",
"var",
"oldModify",
"=",
"extra",
"&&",
"extra",
".",
"$$modify",
";",
"var",
"newExtra",
";",
"if",
"(",
"body",
"=",
"context",
".",
"_body",
")",
"{",
"context",
".",
"_body",
"=",
"null",
"var",
"modifyBodyComponent",
"=",
"context",
".",
"modifyBodyComponent",
";",
"if",
"(",
"typeof",
"modifyBodyComponent",
"===",
"'function'",
")",
"{",
"modifyBodyComponent",
"=",
"modifyBodyComponent",
".",
"bind",
"(",
"this",
")",
"newExtra",
"=",
"_",
".",
"createObject",
"(",
"extra",
")",
";",
"newExtra",
".",
"$$modify",
"=",
"function",
"(",
"comp",
")",
"{",
"return",
"modifyBodyComponent",
"(",
"comp",
",",
"oldModify",
"?",
"oldModify",
":",
"NOOP",
")",
"}",
"}",
"else",
"{",
"//@FIXIT: multiply modifier",
"newExtra",
"=",
"extra",
"}",
"if",
"(",
"body",
".",
"ast",
"&&",
"body",
".",
"ast",
".",
"length",
")",
"{",
"context",
".",
"$body",
"=",
"_",
".",
"getCompileFn",
"(",
"body",
".",
"ast",
",",
"body",
".",
"ctx",
",",
"{",
"outer",
":",
"context",
",",
"namespace",
":",
"options",
".",
"namespace",
",",
"extra",
":",
"newExtra",
",",
"record",
":",
"true",
"}",
")",
"}",
"}",
"// handle computed",
"if",
"(",
"template",
")",
"{",
"var",
"cplOpt",
"=",
"{",
"namespace",
":",
"options",
".",
"namespace",
",",
"cursor",
":",
"cursor",
"}",
"// if(extra && extra.$$modify){",
"cplOpt",
".",
"extra",
"=",
"{",
"$$modify",
":",
"extra",
"&&",
"extra",
".",
"$$modify",
"}",
"// }",
"context",
".",
"group",
"=",
"context",
".",
"$compile",
"(",
"template",
",",
"cplOpt",
")",
";",
"combine",
".",
"node",
"(",
"context",
")",
";",
"}",
"// modify在compile之后调用, 这样就无需处理SSR相关逻辑",
"if",
"(",
"oldModify",
")",
"{",
"oldModify",
"(",
"this",
")",
";",
"}",
"// this is outest component",
"if",
"(",
"!",
"context",
".",
"$parent",
")",
"context",
".",
"$update",
"(",
")",
";",
"context",
".",
"$ready",
"=",
"true",
";",
"context",
".",
"$emit",
"(",
"\"$init\"",
")",
";",
"if",
"(",
"context",
".",
"init",
")",
"context",
".",
"init",
"(",
"context",
".",
"data",
")",
";",
"context",
".",
"$emit",
"(",
"\"$afterInit\"",
")",
";",
"env",
".",
"isRunning",
"=",
"prevRunning",
";",
"// children is not required;",
"if",
"(",
"this",
".",
"devtools",
")",
"{",
"this",
".",
"devtools",
".",
"emit",
"(",
"\"init\"",
",",
"this",
")",
"}",
"}"
] |
`Regular` is regularjs's NameSpace and BaseClass. Every Component is inherited from it
@class Regular
@module Regular
@constructor
@param {Object} options specification of the component
|
[
"Regular",
"is",
"regularjs",
"s",
"NameSpace",
"and",
"BaseClass",
".",
"Every",
"Component",
"is",
"inherited",
"from",
"it"
] |
bdb9d43034c1310c3bc8179c1d3a240e22802fba
|
https://github.com/regularjs/regular/blob/bdb9d43034c1310c3bc8179c1d3a240e22802fba/lib/render/client.js#L38-L147
|
|
17,954
|
regularjs/regular
|
lib/render/client.js
|
function(name, cfg){
if(!name) return;
var type = typeof name;
if(type === 'object' && !cfg){
for(var k in name){
if(name.hasOwnProperty(k)) this.directive(k, name[k]);
}
return this;
}
var directives = this._directives, directive;
if(cfg == null){
if( type === 'string' ){
if( directive = directives[name] ) return directive;
else{
var regexp = directives.__regexp__;
for(var i = 0, len = regexp.length; i < len ; i++){
directive = regexp[i];
var test = directive.regexp.test(name);
if(test) return directive;
}
}
}
}else{
if( typeof cfg === 'function') cfg = { link: cfg }
if( type === 'string' ) directives[name] = cfg;
else{
cfg.regexp = name;
directives.__regexp__.push(cfg)
}
if(typeof cfg.link !== 'function') cfg.link = NOOP;
return this
}
}
|
javascript
|
function(name, cfg){
if(!name) return;
var type = typeof name;
if(type === 'object' && !cfg){
for(var k in name){
if(name.hasOwnProperty(k)) this.directive(k, name[k]);
}
return this;
}
var directives = this._directives, directive;
if(cfg == null){
if( type === 'string' ){
if( directive = directives[name] ) return directive;
else{
var regexp = directives.__regexp__;
for(var i = 0, len = regexp.length; i < len ; i++){
directive = regexp[i];
var test = directive.regexp.test(name);
if(test) return directive;
}
}
}
}else{
if( typeof cfg === 'function') cfg = { link: cfg }
if( type === 'string' ) directives[name] = cfg;
else{
cfg.regexp = name;
directives.__regexp__.push(cfg)
}
if(typeof cfg.link !== 'function') cfg.link = NOOP;
return this
}
}
|
[
"function",
"(",
"name",
",",
"cfg",
")",
"{",
"if",
"(",
"!",
"name",
")",
"return",
";",
"var",
"type",
"=",
"typeof",
"name",
";",
"if",
"(",
"type",
"===",
"'object'",
"&&",
"!",
"cfg",
")",
"{",
"for",
"(",
"var",
"k",
"in",
"name",
")",
"{",
"if",
"(",
"name",
".",
"hasOwnProperty",
"(",
"k",
")",
")",
"this",
".",
"directive",
"(",
"k",
",",
"name",
"[",
"k",
"]",
")",
";",
"}",
"return",
"this",
";",
"}",
"var",
"directives",
"=",
"this",
".",
"_directives",
",",
"directive",
";",
"if",
"(",
"cfg",
"==",
"null",
")",
"{",
"if",
"(",
"type",
"===",
"'string'",
")",
"{",
"if",
"(",
"directive",
"=",
"directives",
"[",
"name",
"]",
")",
"return",
"directive",
";",
"else",
"{",
"var",
"regexp",
"=",
"directives",
".",
"__regexp__",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"regexp",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"directive",
"=",
"regexp",
"[",
"i",
"]",
";",
"var",
"test",
"=",
"directive",
".",
"regexp",
".",
"test",
"(",
"name",
")",
";",
"if",
"(",
"test",
")",
"return",
"directive",
";",
"}",
"}",
"}",
"}",
"else",
"{",
"if",
"(",
"typeof",
"cfg",
"===",
"'function'",
")",
"cfg",
"=",
"{",
"link",
":",
"cfg",
"}",
"if",
"(",
"type",
"===",
"'string'",
")",
"directives",
"[",
"name",
"]",
"=",
"cfg",
";",
"else",
"{",
"cfg",
".",
"regexp",
"=",
"name",
";",
"directives",
".",
"__regexp__",
".",
"push",
"(",
"cfg",
")",
"}",
"if",
"(",
"typeof",
"cfg",
".",
"link",
"!==",
"'function'",
")",
"cfg",
".",
"link",
"=",
"NOOP",
";",
"return",
"this",
"}",
"}"
] |
Define a directive
@method directive
@return {Object} Copy of ...
|
[
"Define",
"a",
"directive"
] |
bdb9d43034c1310c3bc8179c1d3a240e22802fba
|
https://github.com/regularjs/regular/blob/bdb9d43034c1310c3bc8179c1d3a240e22802fba/lib/render/client.js#L204-L237
|
|
17,955
|
regularjs/regular
|
lib/render/client.js
|
function(name, value){
var needGenLexer = false;
if(typeof name === "object"){
for(var i in name){
// if you config
if( i ==="END" || i==='BEGIN' ) needGenLexer = true;
config[i] = name[i];
}
}
if(needGenLexer) Lexer.setup();
}
|
javascript
|
function(name, value){
var needGenLexer = false;
if(typeof name === "object"){
for(var i in name){
// if you config
if( i ==="END" || i==='BEGIN' ) needGenLexer = true;
config[i] = name[i];
}
}
if(needGenLexer) Lexer.setup();
}
|
[
"function",
"(",
"name",
",",
"value",
")",
"{",
"var",
"needGenLexer",
"=",
"false",
";",
"if",
"(",
"typeof",
"name",
"===",
"\"object\"",
")",
"{",
"for",
"(",
"var",
"i",
"in",
"name",
")",
"{",
"// if you config",
"if",
"(",
"i",
"===",
"\"END\"",
"||",
"i",
"===",
"'BEGIN'",
")",
"needGenLexer",
"=",
"true",
";",
"config",
"[",
"i",
"]",
"=",
"name",
"[",
"i",
"]",
";",
"}",
"}",
"if",
"(",
"needGenLexer",
")",
"Lexer",
".",
"setup",
"(",
")",
";",
"}"
] |
config the Regularjs's global
|
[
"config",
"the",
"Regularjs",
"s",
"global"
] |
bdb9d43034c1310c3bc8179c1d3a240e22802fba
|
https://github.com/regularjs/regular/blob/bdb9d43034c1310c3bc8179c1d3a240e22802fba/lib/render/client.js#L251-L261
|
|
17,956
|
regularjs/regular
|
lib/render/client.js
|
function(ast, options){
options = options || {};
if(typeof ast === 'string'){
ast = new Parser(ast).parse()
}
var preExt = this.__ext__,
record = options.record,
records;
if(options.extra) this.__ext__ = options.extra;
if(record) this._record();
var group = this._walk(ast, options);
if(record){
records = this._release();
var self = this;
if( records.length ){
// auto destroy all wather;
group.ondestroy = function(){ self.$unwatch(records); }
}
}
if(options.extra) this.__ext__ = preExt;
return group;
}
|
javascript
|
function(ast, options){
options = options || {};
if(typeof ast === 'string'){
ast = new Parser(ast).parse()
}
var preExt = this.__ext__,
record = options.record,
records;
if(options.extra) this.__ext__ = options.extra;
if(record) this._record();
var group = this._walk(ast, options);
if(record){
records = this._release();
var self = this;
if( records.length ){
// auto destroy all wather;
group.ondestroy = function(){ self.$unwatch(records); }
}
}
if(options.extra) this.__ext__ = preExt;
return group;
}
|
[
"function",
"(",
"ast",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"if",
"(",
"typeof",
"ast",
"===",
"'string'",
")",
"{",
"ast",
"=",
"new",
"Parser",
"(",
"ast",
")",
".",
"parse",
"(",
")",
"}",
"var",
"preExt",
"=",
"this",
".",
"__ext__",
",",
"record",
"=",
"options",
".",
"record",
",",
"records",
";",
"if",
"(",
"options",
".",
"extra",
")",
"this",
".",
"__ext__",
"=",
"options",
".",
"extra",
";",
"if",
"(",
"record",
")",
"this",
".",
"_record",
"(",
")",
";",
"var",
"group",
"=",
"this",
".",
"_walk",
"(",
"ast",
",",
"options",
")",
";",
"if",
"(",
"record",
")",
"{",
"records",
"=",
"this",
".",
"_release",
"(",
")",
";",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"records",
".",
"length",
")",
"{",
"// auto destroy all wather;",
"group",
".",
"ondestroy",
"=",
"function",
"(",
")",
"{",
"self",
".",
"$unwatch",
"(",
"records",
")",
";",
"}",
"}",
"}",
"if",
"(",
"options",
".",
"extra",
")",
"this",
".",
"__ext__",
"=",
"preExt",
";",
"return",
"group",
";",
"}"
] |
compile a block ast ; return a group;
@param {Array} parsed ast
@param {[type]} record
@return {[type]}
|
[
"compile",
"a",
"block",
"ast",
";",
"return",
"a",
"group",
";"
] |
bdb9d43034c1310c3bc8179c1d3a240e22802fba
|
https://github.com/regularjs/regular/blob/bdb9d43034c1310c3bc8179c1d3a240e22802fba/lib/render/client.js#L350-L374
|
|
17,957
|
regularjs/regular
|
lib/render/client.js
|
function(component, expr1, expr2){
var self = this;
// basic binding
if(!component || !(component instanceof Regular)) throw "$bind() should pass Regular component as first argument";
if(!expr1) throw "$bind() should pass as least one expression to bind";
if(!expr2) expr2 = expr1;
expr1 = parse.expression( expr1 );
expr2 = parse.expression( expr2 );
// set is need to operate setting ;
if(expr2.set){
var wid1 = this.$watch( expr1, function(value){
component.$update(expr2, value)
});
component.$on('$destroy', function(){
self.$unwatch(wid1)
})
}
if(expr1.set){
var wid2 = component.$watch(expr2, function(value){
self.$update(expr1, value)
});
// when brother destroy, we unlink this watcher
this.$on('$destroy', component.$unwatch.bind(component,wid2))
}
// sync the component's state to called's state
expr2.set(component, expr1.get(this));
}
|
javascript
|
function(component, expr1, expr2){
var self = this;
// basic binding
if(!component || !(component instanceof Regular)) throw "$bind() should pass Regular component as first argument";
if(!expr1) throw "$bind() should pass as least one expression to bind";
if(!expr2) expr2 = expr1;
expr1 = parse.expression( expr1 );
expr2 = parse.expression( expr2 );
// set is need to operate setting ;
if(expr2.set){
var wid1 = this.$watch( expr1, function(value){
component.$update(expr2, value)
});
component.$on('$destroy', function(){
self.$unwatch(wid1)
})
}
if(expr1.set){
var wid2 = component.$watch(expr2, function(value){
self.$update(expr1, value)
});
// when brother destroy, we unlink this watcher
this.$on('$destroy', component.$unwatch.bind(component,wid2))
}
// sync the component's state to called's state
expr2.set(component, expr1.get(this));
}
|
[
"function",
"(",
"component",
",",
"expr1",
",",
"expr2",
")",
"{",
"var",
"self",
"=",
"this",
";",
"// basic binding",
"if",
"(",
"!",
"component",
"||",
"!",
"(",
"component",
"instanceof",
"Regular",
")",
")",
"throw",
"\"$bind() should pass Regular component as first argument\"",
";",
"if",
"(",
"!",
"expr1",
")",
"throw",
"\"$bind() should pass as least one expression to bind\"",
";",
"if",
"(",
"!",
"expr2",
")",
"expr2",
"=",
"expr1",
";",
"expr1",
"=",
"parse",
".",
"expression",
"(",
"expr1",
")",
";",
"expr2",
"=",
"parse",
".",
"expression",
"(",
"expr2",
")",
";",
"// set is need to operate setting ;",
"if",
"(",
"expr2",
".",
"set",
")",
"{",
"var",
"wid1",
"=",
"this",
".",
"$watch",
"(",
"expr1",
",",
"function",
"(",
"value",
")",
"{",
"component",
".",
"$update",
"(",
"expr2",
",",
"value",
")",
"}",
")",
";",
"component",
".",
"$on",
"(",
"'$destroy'",
",",
"function",
"(",
")",
"{",
"self",
".",
"$unwatch",
"(",
"wid1",
")",
"}",
")",
"}",
"if",
"(",
"expr1",
".",
"set",
")",
"{",
"var",
"wid2",
"=",
"component",
".",
"$watch",
"(",
"expr2",
",",
"function",
"(",
"value",
")",
"{",
"self",
".",
"$update",
"(",
"expr1",
",",
"value",
")",
"}",
")",
";",
"// when brother destroy, we unlink this watcher",
"this",
".",
"$on",
"(",
"'$destroy'",
",",
"component",
".",
"$unwatch",
".",
"bind",
"(",
"component",
",",
"wid2",
")",
")",
"}",
"// sync the component's state to called's state",
"expr2",
".",
"set",
"(",
"component",
",",
"expr1",
".",
"get",
"(",
"this",
")",
")",
";",
"}"
] |
private bind logic
|
[
"private",
"bind",
"logic"
] |
bdb9d43034c1310c3bc8179c1d3a240e22802fba
|
https://github.com/regularjs/regular/blob/bdb9d43034c1310c3bc8179c1d3a240e22802fba/lib/render/client.js#L443-L474
|
|
17,958
|
regularjs/regular
|
lib/render/client.js
|
function(path, parent, defaults, ext){
if( path === undefined ) return undefined;
if(ext && typeof ext === 'object'){
if(ext[path] !== undefined) return ext[path];
}
// reject to get from computed, return undefined directly
// like { empty.prop }, empty equals undefined
// prop shouldn't get from computed
if(parent === null) {
return undefined
}
if(parent && typeof parent[path] !== 'undefined') {
return parent[path]
}
// without parent, get from computed
if (parent !== null) {
var computed = this.computed,
computedProperty = computed[path];
if(computedProperty){
if(computedProperty.type==='expression' && !computedProperty.get) this._touchExpr(computedProperty);
if(computedProperty.get) return computedProperty.get(this);
else _.log("the computed '" + path + "' don't define the get function, get data."+path + " altnately", "warn")
}
}
if( defaults === undefined ){
return undefined;
}
return defaults[path];
}
|
javascript
|
function(path, parent, defaults, ext){
if( path === undefined ) return undefined;
if(ext && typeof ext === 'object'){
if(ext[path] !== undefined) return ext[path];
}
// reject to get from computed, return undefined directly
// like { empty.prop }, empty equals undefined
// prop shouldn't get from computed
if(parent === null) {
return undefined
}
if(parent && typeof parent[path] !== 'undefined') {
return parent[path]
}
// without parent, get from computed
if (parent !== null) {
var computed = this.computed,
computedProperty = computed[path];
if(computedProperty){
if(computedProperty.type==='expression' && !computedProperty.get) this._touchExpr(computedProperty);
if(computedProperty.get) return computedProperty.get(this);
else _.log("the computed '" + path + "' don't define the get function, get data."+path + " altnately", "warn")
}
}
if( defaults === undefined ){
return undefined;
}
return defaults[path];
}
|
[
"function",
"(",
"path",
",",
"parent",
",",
"defaults",
",",
"ext",
")",
"{",
"if",
"(",
"path",
"===",
"undefined",
")",
"return",
"undefined",
";",
"if",
"(",
"ext",
"&&",
"typeof",
"ext",
"===",
"'object'",
")",
"{",
"if",
"(",
"ext",
"[",
"path",
"]",
"!==",
"undefined",
")",
"return",
"ext",
"[",
"path",
"]",
";",
"}",
"// reject to get from computed, return undefined directly",
"// like { empty.prop }, empty equals undefined",
"// prop shouldn't get from computed",
"if",
"(",
"parent",
"===",
"null",
")",
"{",
"return",
"undefined",
"}",
"if",
"(",
"parent",
"&&",
"typeof",
"parent",
"[",
"path",
"]",
"!==",
"'undefined'",
")",
"{",
"return",
"parent",
"[",
"path",
"]",
"}",
"// without parent, get from computed",
"if",
"(",
"parent",
"!==",
"null",
")",
"{",
"var",
"computed",
"=",
"this",
".",
"computed",
",",
"computedProperty",
"=",
"computed",
"[",
"path",
"]",
";",
"if",
"(",
"computedProperty",
")",
"{",
"if",
"(",
"computedProperty",
".",
"type",
"===",
"'expression'",
"&&",
"!",
"computedProperty",
".",
"get",
")",
"this",
".",
"_touchExpr",
"(",
"computedProperty",
")",
";",
"if",
"(",
"computedProperty",
".",
"get",
")",
"return",
"computedProperty",
".",
"get",
"(",
"this",
")",
";",
"else",
"_",
".",
"log",
"(",
"\"the computed '\"",
"+",
"path",
"+",
"\"' don't define the get function, get data.\"",
"+",
"path",
"+",
"\" altnately\"",
",",
"\"warn\"",
")",
"}",
"}",
"if",
"(",
"defaults",
"===",
"undefined",
")",
"{",
"return",
"undefined",
";",
"}",
"return",
"defaults",
"[",
"path",
"]",
";",
"}"
] |
simple accessor get ext > parent > computed > defaults
|
[
"simple",
"accessor",
"get",
"ext",
">",
"parent",
">",
"computed",
">",
"defaults"
] |
bdb9d43034c1310c3bc8179c1d3a240e22802fba
|
https://github.com/regularjs/regular/blob/bdb9d43034c1310c3bc8179c1d3a240e22802fba/lib/render/client.js#L557-L591
|
|
17,959
|
regularjs/regular
|
lib/render/client.js
|
function(path, value, data , op, computed){
var computed = this.computed,
op = op || "=", prev,
computedProperty = computed? computed[path]:null;
if(op !== '='){
prev = computedProperty? computedProperty.get(this): data[path];
switch(op){
case "+=":
value = prev + value;
break;
case "-=":
value = prev - value;
break;
case "*=":
value = prev * value;
break;
case "/=":
value = prev / value;
break;
case "%=":
value = prev % value;
break;
}
}
if(computedProperty) {
if(computedProperty.set) return computedProperty.set(this, value);
}
data[path] = value;
return value;
}
|
javascript
|
function(path, value, data , op, computed){
var computed = this.computed,
op = op || "=", prev,
computedProperty = computed? computed[path]:null;
if(op !== '='){
prev = computedProperty? computedProperty.get(this): data[path];
switch(op){
case "+=":
value = prev + value;
break;
case "-=":
value = prev - value;
break;
case "*=":
value = prev * value;
break;
case "/=":
value = prev / value;
break;
case "%=":
value = prev % value;
break;
}
}
if(computedProperty) {
if(computedProperty.set) return computedProperty.set(this, value);
}
data[path] = value;
return value;
}
|
[
"function",
"(",
"path",
",",
"value",
",",
"data",
",",
"op",
",",
"computed",
")",
"{",
"var",
"computed",
"=",
"this",
".",
"computed",
",",
"op",
"=",
"op",
"||",
"\"=\"",
",",
"prev",
",",
"computedProperty",
"=",
"computed",
"?",
"computed",
"[",
"path",
"]",
":",
"null",
";",
"if",
"(",
"op",
"!==",
"'='",
")",
"{",
"prev",
"=",
"computedProperty",
"?",
"computedProperty",
".",
"get",
"(",
"this",
")",
":",
"data",
"[",
"path",
"]",
";",
"switch",
"(",
"op",
")",
"{",
"case",
"\"+=\"",
":",
"value",
"=",
"prev",
"+",
"value",
";",
"break",
";",
"case",
"\"-=\"",
":",
"value",
"=",
"prev",
"-",
"value",
";",
"break",
";",
"case",
"\"*=\"",
":",
"value",
"=",
"prev",
"*",
"value",
";",
"break",
";",
"case",
"\"/=\"",
":",
"value",
"=",
"prev",
"/",
"value",
";",
"break",
";",
"case",
"\"%=\"",
":",
"value",
"=",
"prev",
"%",
"value",
";",
"break",
";",
"}",
"}",
"if",
"(",
"computedProperty",
")",
"{",
"if",
"(",
"computedProperty",
".",
"set",
")",
"return",
"computedProperty",
".",
"set",
"(",
"this",
",",
"value",
")",
";",
"}",
"data",
"[",
"path",
"]",
"=",
"value",
";",
"return",
"value",
";",
"}"
] |
simple accessor set
|
[
"simple",
"accessor",
"set"
] |
bdb9d43034c1310c3bc8179c1d3a240e22802fba
|
https://github.com/regularjs/regular/blob/bdb9d43034c1310c3bc8179c1d3a240e22802fba/lib/render/client.js#L593-L623
|
|
17,960
|
regularjs/regular
|
lib/walkers.js
|
updateSimple
|
function updateSimple(newList, oldList, rawNewValue ){
var nlen = newList.length;
var olen = oldList.length;
var mlen = Math.min(nlen, olen);
updateRange(0, mlen, newList, rawNewValue)
if(nlen < olen){ //need add
removeRange(nlen, olen-nlen, children);
}else if(nlen > olen){
addRange(olen, nlen, newList, rawNewValue);
}
}
|
javascript
|
function updateSimple(newList, oldList, rawNewValue ){
var nlen = newList.length;
var olen = oldList.length;
var mlen = Math.min(nlen, olen);
updateRange(0, mlen, newList, rawNewValue)
if(nlen < olen){ //need add
removeRange(nlen, olen-nlen, children);
}else if(nlen > olen){
addRange(olen, nlen, newList, rawNewValue);
}
}
|
[
"function",
"updateSimple",
"(",
"newList",
",",
"oldList",
",",
"rawNewValue",
")",
"{",
"var",
"nlen",
"=",
"newList",
".",
"length",
";",
"var",
"olen",
"=",
"oldList",
".",
"length",
";",
"var",
"mlen",
"=",
"Math",
".",
"min",
"(",
"nlen",
",",
"olen",
")",
";",
"updateRange",
"(",
"0",
",",
"mlen",
",",
"newList",
",",
"rawNewValue",
")",
"if",
"(",
"nlen",
"<",
"olen",
")",
"{",
"//need add",
"removeRange",
"(",
"nlen",
",",
"olen",
"-",
"nlen",
",",
"children",
")",
";",
"}",
"else",
"if",
"(",
"nlen",
">",
"olen",
")",
"{",
"addRange",
"(",
"olen",
",",
"nlen",
",",
"newList",
",",
"rawNewValue",
")",
";",
"}",
"}"
] |
if the track is constant test.
|
[
"if",
"the",
"track",
"is",
"constant",
"test",
"."
] |
bdb9d43034c1310c3bc8179c1d3a240e22802fba
|
https://github.com/regularjs/regular/blob/bdb9d43034c1310c3bc8179c1d3a240e22802fba/lib/walkers.js#L176-L188
|
17,961
|
regularjs/regular
|
lib/directive/form.js
|
initText
|
function initText(elem, parsed, extra){
var param = extra.param;
var throttle, lazy = param.lazy
if('throttle' in param){
// <input throttle r-model>
if(param.throttle === true){
throttle = 400;
}else{
throttle = parseInt(param.throttle, 10)
}
}
var self = this;
var wc = this.$watch(parsed, function(newValue){
if(elem.value !== newValue) elem.value = newValue == null? "": "" + newValue;
}, STABLE);
// @TODO to fixed event
var isCompositing = false;
var handler = function (ev){
if(isCompositing) return;
isCompositing = false;
var that = this;
if(ev.type==='cut' || ev.type==='paste'){
_.nextTick(function(){
var value = that.value
parsed.set(self, value);
wc.last = value;
self.$update();
})
}else{
var value = that.value
parsed.set(self, value);
wc.last = value;
self.$update();
}
};
function onCompositionStart(){
isCompositing = true;
}
function onCompositionEnd(ev){
isCompositing = false;
handler.call(this,ev)
}
if(throttle && !lazy){
var preHandle = handler, tid;
handler = _.throttle(handler, throttle);
}
if(hasInput === undefined){
hasInput = dom.msie !== 9 && "oninput" in document.createElement('input')
}
if(lazy){
dom.on(elem, 'change', handler)
}else{
if(typeof CompositionEvent === 'function' ){ //lazy的情况不需要compositionend
elem.addEventListener("compositionstart", onCompositionStart );
elem.addEventListener("compositionend", onCompositionEnd );
}
if( hasInput){
elem.addEventListener("input", handler );
}else{
dom.on(elem, "paste keyup cut change", handler)
}
}
if(parsed.get(self) === undefined && elem.value){
parsed.set(self, elem.value);
}
return function (){
if(lazy) return dom.off(elem, "change", handler);
if( hasInput ){
elem.removeEventListener("input", handler );
}else{
dom.off(elem, "paste keyup cut change", handler)
}
}
}
|
javascript
|
function initText(elem, parsed, extra){
var param = extra.param;
var throttle, lazy = param.lazy
if('throttle' in param){
// <input throttle r-model>
if(param.throttle === true){
throttle = 400;
}else{
throttle = parseInt(param.throttle, 10)
}
}
var self = this;
var wc = this.$watch(parsed, function(newValue){
if(elem.value !== newValue) elem.value = newValue == null? "": "" + newValue;
}, STABLE);
// @TODO to fixed event
var isCompositing = false;
var handler = function (ev){
if(isCompositing) return;
isCompositing = false;
var that = this;
if(ev.type==='cut' || ev.type==='paste'){
_.nextTick(function(){
var value = that.value
parsed.set(self, value);
wc.last = value;
self.$update();
})
}else{
var value = that.value
parsed.set(self, value);
wc.last = value;
self.$update();
}
};
function onCompositionStart(){
isCompositing = true;
}
function onCompositionEnd(ev){
isCompositing = false;
handler.call(this,ev)
}
if(throttle && !lazy){
var preHandle = handler, tid;
handler = _.throttle(handler, throttle);
}
if(hasInput === undefined){
hasInput = dom.msie !== 9 && "oninput" in document.createElement('input')
}
if(lazy){
dom.on(elem, 'change', handler)
}else{
if(typeof CompositionEvent === 'function' ){ //lazy的情况不需要compositionend
elem.addEventListener("compositionstart", onCompositionStart );
elem.addEventListener("compositionend", onCompositionEnd );
}
if( hasInput){
elem.addEventListener("input", handler );
}else{
dom.on(elem, "paste keyup cut change", handler)
}
}
if(parsed.get(self) === undefined && elem.value){
parsed.set(self, elem.value);
}
return function (){
if(lazy) return dom.off(elem, "change", handler);
if( hasInput ){
elem.removeEventListener("input", handler );
}else{
dom.off(elem, "paste keyup cut change", handler)
}
}
}
|
[
"function",
"initText",
"(",
"elem",
",",
"parsed",
",",
"extra",
")",
"{",
"var",
"param",
"=",
"extra",
".",
"param",
";",
"var",
"throttle",
",",
"lazy",
"=",
"param",
".",
"lazy",
"if",
"(",
"'throttle'",
"in",
"param",
")",
"{",
"// <input throttle r-model>",
"if",
"(",
"param",
".",
"throttle",
"===",
"true",
")",
"{",
"throttle",
"=",
"400",
";",
"}",
"else",
"{",
"throttle",
"=",
"parseInt",
"(",
"param",
".",
"throttle",
",",
"10",
")",
"}",
"}",
"var",
"self",
"=",
"this",
";",
"var",
"wc",
"=",
"this",
".",
"$watch",
"(",
"parsed",
",",
"function",
"(",
"newValue",
")",
"{",
"if",
"(",
"elem",
".",
"value",
"!==",
"newValue",
")",
"elem",
".",
"value",
"=",
"newValue",
"==",
"null",
"?",
"\"\"",
":",
"\"\"",
"+",
"newValue",
";",
"}",
",",
"STABLE",
")",
";",
"// @TODO to fixed event",
"var",
"isCompositing",
"=",
"false",
";",
"var",
"handler",
"=",
"function",
"(",
"ev",
")",
"{",
"if",
"(",
"isCompositing",
")",
"return",
";",
"isCompositing",
"=",
"false",
";",
"var",
"that",
"=",
"this",
";",
"if",
"(",
"ev",
".",
"type",
"===",
"'cut'",
"||",
"ev",
".",
"type",
"===",
"'paste'",
")",
"{",
"_",
".",
"nextTick",
"(",
"function",
"(",
")",
"{",
"var",
"value",
"=",
"that",
".",
"value",
"parsed",
".",
"set",
"(",
"self",
",",
"value",
")",
";",
"wc",
".",
"last",
"=",
"value",
";",
"self",
".",
"$update",
"(",
")",
";",
"}",
")",
"}",
"else",
"{",
"var",
"value",
"=",
"that",
".",
"value",
"parsed",
".",
"set",
"(",
"self",
",",
"value",
")",
";",
"wc",
".",
"last",
"=",
"value",
";",
"self",
".",
"$update",
"(",
")",
";",
"}",
"}",
";",
"function",
"onCompositionStart",
"(",
")",
"{",
"isCompositing",
"=",
"true",
";",
"}",
"function",
"onCompositionEnd",
"(",
"ev",
")",
"{",
"isCompositing",
"=",
"false",
";",
"handler",
".",
"call",
"(",
"this",
",",
"ev",
")",
"}",
"if",
"(",
"throttle",
"&&",
"!",
"lazy",
")",
"{",
"var",
"preHandle",
"=",
"handler",
",",
"tid",
";",
"handler",
"=",
"_",
".",
"throttle",
"(",
"handler",
",",
"throttle",
")",
";",
"}",
"if",
"(",
"hasInput",
"===",
"undefined",
")",
"{",
"hasInput",
"=",
"dom",
".",
"msie",
"!==",
"9",
"&&",
"\"oninput\"",
"in",
"document",
".",
"createElement",
"(",
"'input'",
")",
"}",
"if",
"(",
"lazy",
")",
"{",
"dom",
".",
"on",
"(",
"elem",
",",
"'change'",
",",
"handler",
")",
"}",
"else",
"{",
"if",
"(",
"typeof",
"CompositionEvent",
"===",
"'function'",
")",
"{",
"//lazy的情况不需要compositionend",
"elem",
".",
"addEventListener",
"(",
"\"compositionstart\"",
",",
"onCompositionStart",
")",
";",
"elem",
".",
"addEventListener",
"(",
"\"compositionend\"",
",",
"onCompositionEnd",
")",
";",
"}",
"if",
"(",
"hasInput",
")",
"{",
"elem",
".",
"addEventListener",
"(",
"\"input\"",
",",
"handler",
")",
";",
"}",
"else",
"{",
"dom",
".",
"on",
"(",
"elem",
",",
"\"paste keyup cut change\"",
",",
"handler",
")",
"}",
"}",
"if",
"(",
"parsed",
".",
"get",
"(",
"self",
")",
"===",
"undefined",
"&&",
"elem",
".",
"value",
")",
"{",
"parsed",
".",
"set",
"(",
"self",
",",
"elem",
".",
"value",
")",
";",
"}",
"return",
"function",
"(",
")",
"{",
"if",
"(",
"lazy",
")",
"return",
"dom",
".",
"off",
"(",
"elem",
",",
"\"change\"",
",",
"handler",
")",
";",
"if",
"(",
"hasInput",
")",
"{",
"elem",
".",
"removeEventListener",
"(",
"\"input\"",
",",
"handler",
")",
";",
"}",
"else",
"{",
"dom",
".",
"off",
"(",
"elem",
",",
"\"paste keyup cut change\"",
",",
"handler",
")",
"}",
"}",
"}"
] |
input,textarea binding
|
[
"input",
"textarea",
"binding"
] |
bdb9d43034c1310c3bc8179c1d3a240e22802fba
|
https://github.com/regularjs/regular/blob/bdb9d43034c1310c3bc8179c1d3a240e22802fba/lib/directive/form.js#L100-L186
|
17,962
|
traverson/traverson
|
browser/lib/shim/request.js
|
mapResponse
|
function mapResponse(response) {
response.body = response.text;
response.statusCode = response.status;
return response;
}
|
javascript
|
function mapResponse(response) {
response.body = response.text;
response.statusCode = response.status;
return response;
}
|
[
"function",
"mapResponse",
"(",
"response",
")",
"{",
"response",
".",
"body",
"=",
"response",
".",
"text",
";",
"response",
".",
"statusCode",
"=",
"response",
".",
"status",
";",
"return",
"response",
";",
"}"
] |
map XHR response object properties to Node.js request lib's response object properties
|
[
"map",
"XHR",
"response",
"object",
"properties",
"to",
"Node",
".",
"js",
"request",
"lib",
"s",
"response",
"object",
"properties"
] |
4b65f3f6a54e5c87ead08b4a29efe54158a56890
|
https://github.com/traverson/traverson/blob/4b65f3f6a54e5c87ead08b4a29efe54158a56890/browser/lib/shim/request.js#L102-L106
|
17,963
|
ZhonganTechENG/zarm-vue
|
src/mixins/scrollable.js
|
getScrollTop
|
function getScrollTop() {
// vue-jest ignore
if (!document) return;
if (document.scrollingElement) {
return document.scrollingElement.scrollTop;
}
if (document.body || window.pageXOffset) {
return document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset;
}
}
|
javascript
|
function getScrollTop() {
// vue-jest ignore
if (!document) return;
if (document.scrollingElement) {
return document.scrollingElement.scrollTop;
}
if (document.body || window.pageXOffset) {
return document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset;
}
}
|
[
"function",
"getScrollTop",
"(",
")",
"{",
"// vue-jest ignore",
"if",
"(",
"!",
"document",
")",
"return",
";",
"if",
"(",
"document",
".",
"scrollingElement",
")",
"{",
"return",
"document",
".",
"scrollingElement",
".",
"scrollTop",
";",
"}",
"if",
"(",
"document",
".",
"body",
"||",
"window",
".",
"pageXOffset",
")",
"{",
"return",
"document",
".",
"body",
".",
"scrollTop",
"||",
"document",
".",
"documentElement",
".",
"scrollTop",
"||",
"window",
".",
"pageYOffset",
";",
"}",
"}"
] |
document scrollable on clientwindow
|
[
"document",
"scrollable",
"on",
"clientwindow"
] |
c6f1a63799052e551c56cf30abc85cbfc92421ba
|
https://github.com/ZhonganTechENG/zarm-vue/blob/c6f1a63799052e551c56cf30abc85cbfc92421ba/src/mixins/scrollable.js#L4-L13
|
17,964
|
AlCalzone/node-tradfri-client
|
build/lib/discovery.js
|
discoverGateway
|
function discoverGateway(timeout = 10000) {
const mdns = createMDNSServer({
reuseAddr: true,
loopback: false,
noInit: true,
});
let timer;
const domain = "_coap._udp.local";
return new Promise((resolve, reject) => {
mdns.on("response", (resp) => {
const allAnswers = [...resp.answers, ...resp.additionals];
const discard = allAnswers.find(a => a.name === domain) == null;
if (discard)
return;
// ensure all record types were received
const ptrRecord = allAnswers.find(a => a.type === "PTR");
if (!ptrRecord)
return;
const srvRecord = allAnswers.find(a => a.type === "SRV");
if (!srvRecord)
return;
const txtRecord = allAnswers.find(a => a.type === "TXT");
if (!txtRecord)
return;
const aRecords = allAnswers.filter(a => a.type === "A" || a.type === "AAAA");
if (aRecords.length === 0)
return;
// extract the data
const match = /^gw\-[0-9a-f]{12}/.exec(ptrRecord.data);
const name = !!match ? match[0] : "unknown";
const host = srvRecord.data.target;
const { version } = parseTXTRecord(txtRecord.data);
const addresses = aRecords.map(a => a.data);
clearTimeout(timer);
mdns.destroy();
resolve({
name, host, version, addresses,
});
});
mdns.on("ready", () => {
mdns.query([
{ name: domain, type: "A" },
{ name: domain, type: "AAAA" },
{ name: domain, type: "PTR" },
{ name: domain, type: "SRV" },
{ name: domain, type: "TXT" },
]);
});
mdns.on("error", reject);
mdns.initServer();
if (typeof timeout === "number" && timeout > 0) {
timer = setTimeout(() => {
mdns.destroy();
resolve(null);
}, timeout);
}
});
}
|
javascript
|
function discoverGateway(timeout = 10000) {
const mdns = createMDNSServer({
reuseAddr: true,
loopback: false,
noInit: true,
});
let timer;
const domain = "_coap._udp.local";
return new Promise((resolve, reject) => {
mdns.on("response", (resp) => {
const allAnswers = [...resp.answers, ...resp.additionals];
const discard = allAnswers.find(a => a.name === domain) == null;
if (discard)
return;
// ensure all record types were received
const ptrRecord = allAnswers.find(a => a.type === "PTR");
if (!ptrRecord)
return;
const srvRecord = allAnswers.find(a => a.type === "SRV");
if (!srvRecord)
return;
const txtRecord = allAnswers.find(a => a.type === "TXT");
if (!txtRecord)
return;
const aRecords = allAnswers.filter(a => a.type === "A" || a.type === "AAAA");
if (aRecords.length === 0)
return;
// extract the data
const match = /^gw\-[0-9a-f]{12}/.exec(ptrRecord.data);
const name = !!match ? match[0] : "unknown";
const host = srvRecord.data.target;
const { version } = parseTXTRecord(txtRecord.data);
const addresses = aRecords.map(a => a.data);
clearTimeout(timer);
mdns.destroy();
resolve({
name, host, version, addresses,
});
});
mdns.on("ready", () => {
mdns.query([
{ name: domain, type: "A" },
{ name: domain, type: "AAAA" },
{ name: domain, type: "PTR" },
{ name: domain, type: "SRV" },
{ name: domain, type: "TXT" },
]);
});
mdns.on("error", reject);
mdns.initServer();
if (typeof timeout === "number" && timeout > 0) {
timer = setTimeout(() => {
mdns.destroy();
resolve(null);
}, timeout);
}
});
}
|
[
"function",
"discoverGateway",
"(",
"timeout",
"=",
"10000",
")",
"{",
"const",
"mdns",
"=",
"createMDNSServer",
"(",
"{",
"reuseAddr",
":",
"true",
",",
"loopback",
":",
"false",
",",
"noInit",
":",
"true",
",",
"}",
")",
";",
"let",
"timer",
";",
"const",
"domain",
"=",
"\"_coap._udp.local\"",
";",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"mdns",
".",
"on",
"(",
"\"response\"",
",",
"(",
"resp",
")",
"=>",
"{",
"const",
"allAnswers",
"=",
"[",
"...",
"resp",
".",
"answers",
",",
"...",
"resp",
".",
"additionals",
"]",
";",
"const",
"discard",
"=",
"allAnswers",
".",
"find",
"(",
"a",
"=>",
"a",
".",
"name",
"===",
"domain",
")",
"==",
"null",
";",
"if",
"(",
"discard",
")",
"return",
";",
"// ensure all record types were received",
"const",
"ptrRecord",
"=",
"allAnswers",
".",
"find",
"(",
"a",
"=>",
"a",
".",
"type",
"===",
"\"PTR\"",
")",
";",
"if",
"(",
"!",
"ptrRecord",
")",
"return",
";",
"const",
"srvRecord",
"=",
"allAnswers",
".",
"find",
"(",
"a",
"=>",
"a",
".",
"type",
"===",
"\"SRV\"",
")",
";",
"if",
"(",
"!",
"srvRecord",
")",
"return",
";",
"const",
"txtRecord",
"=",
"allAnswers",
".",
"find",
"(",
"a",
"=>",
"a",
".",
"type",
"===",
"\"TXT\"",
")",
";",
"if",
"(",
"!",
"txtRecord",
")",
"return",
";",
"const",
"aRecords",
"=",
"allAnswers",
".",
"filter",
"(",
"a",
"=>",
"a",
".",
"type",
"===",
"\"A\"",
"||",
"a",
".",
"type",
"===",
"\"AAAA\"",
")",
";",
"if",
"(",
"aRecords",
".",
"length",
"===",
"0",
")",
"return",
";",
"// extract the data",
"const",
"match",
"=",
"/",
"^gw\\-[0-9a-f]{12}",
"/",
".",
"exec",
"(",
"ptrRecord",
".",
"data",
")",
";",
"const",
"name",
"=",
"!",
"!",
"match",
"?",
"match",
"[",
"0",
"]",
":",
"\"unknown\"",
";",
"const",
"host",
"=",
"srvRecord",
".",
"data",
".",
"target",
";",
"const",
"{",
"version",
"}",
"=",
"parseTXTRecord",
"(",
"txtRecord",
".",
"data",
")",
";",
"const",
"addresses",
"=",
"aRecords",
".",
"map",
"(",
"a",
"=>",
"a",
".",
"data",
")",
";",
"clearTimeout",
"(",
"timer",
")",
";",
"mdns",
".",
"destroy",
"(",
")",
";",
"resolve",
"(",
"{",
"name",
",",
"host",
",",
"version",
",",
"addresses",
",",
"}",
")",
";",
"}",
")",
";",
"mdns",
".",
"on",
"(",
"\"ready\"",
",",
"(",
")",
"=>",
"{",
"mdns",
".",
"query",
"(",
"[",
"{",
"name",
":",
"domain",
",",
"type",
":",
"\"A\"",
"}",
",",
"{",
"name",
":",
"domain",
",",
"type",
":",
"\"AAAA\"",
"}",
",",
"{",
"name",
":",
"domain",
",",
"type",
":",
"\"PTR\"",
"}",
",",
"{",
"name",
":",
"domain",
",",
"type",
":",
"\"SRV\"",
"}",
",",
"{",
"name",
":",
"domain",
",",
"type",
":",
"\"TXT\"",
"}",
",",
"]",
")",
";",
"}",
")",
";",
"mdns",
".",
"on",
"(",
"\"error\"",
",",
"reject",
")",
";",
"mdns",
".",
"initServer",
"(",
")",
";",
"if",
"(",
"typeof",
"timeout",
"===",
"\"number\"",
"&&",
"timeout",
">",
"0",
")",
"{",
"timer",
"=",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"mdns",
".",
"destroy",
"(",
")",
";",
"resolve",
"(",
"null",
")",
";",
"}",
",",
"timeout",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Auto-discover a tradfri gateway on the network.
@param timeout (optional) Time in milliseconds to wait for a response. Default 10000.
Pass false or a negative number to explicitly wait forever.
|
[
"Auto",
"-",
"discover",
"a",
"tradfri",
"gateway",
"on",
"the",
"network",
"."
] |
8c4a1d6571068dca90c6a68f6a4c1feb56da88ee
|
https://github.com/AlCalzone/node-tradfri-client/blob/8c4a1d6571068dca90c6a68f6a4c1feb56da88ee/build/lib/discovery.js#L21-L78
|
17,965
|
AlCalzone/node-tradfri-client
|
build/lib/ipsoObject.js
|
buildPropertyTransform
|
function buildPropertyTransform(kernel, options = {}) {
if (options.splitArrays == null)
options.splitArrays = true;
if (options.neverSkip == null)
options.neverSkip = false;
const ret = kernel;
ret.splitArrays = options.splitArrays;
ret.neverSkip = options.neverSkip;
return ret;
}
|
javascript
|
function buildPropertyTransform(kernel, options = {}) {
if (options.splitArrays == null)
options.splitArrays = true;
if (options.neverSkip == null)
options.neverSkip = false;
const ret = kernel;
ret.splitArrays = options.splitArrays;
ret.neverSkip = options.neverSkip;
return ret;
}
|
[
"function",
"buildPropertyTransform",
"(",
"kernel",
",",
"options",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"options",
".",
"splitArrays",
"==",
"null",
")",
"options",
".",
"splitArrays",
"=",
"true",
";",
"if",
"(",
"options",
".",
"neverSkip",
"==",
"null",
")",
"options",
".",
"neverSkip",
"=",
"false",
";",
"const",
"ret",
"=",
"kernel",
";",
"ret",
".",
"splitArrays",
"=",
"options",
".",
"splitArrays",
";",
"ret",
".",
"neverSkip",
"=",
"options",
".",
"neverSkip",
";",
"return",
"ret",
";",
"}"
] |
Builds a property transform from a kernel and some options
@param kernel The transform kernel
@param options Some options regarding the property transform
|
[
"Builds",
"a",
"property",
"transform",
"from",
"a",
"kernel",
"and",
"some",
"options"
] |
8c4a1d6571068dca90c6a68f6a4c1feb56da88ee
|
https://github.com/AlCalzone/node-tradfri-client/blob/8c4a1d6571068dca90c6a68f6a4c1feb56da88ee/build/lib/ipsoObject.js#L28-L37
|
17,966
|
AlCalzone/node-tradfri-client
|
build/lib/ipsoObject.js
|
lookupKeyOrProperty
|
function lookupKeyOrProperty(target, keyOrProperty /*| keyof T*/) {
// get the class constructor
const constr = target.constructor;
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_ipsoKey, constr);
return metadata && metadata[keyOrProperty];
}
|
javascript
|
function lookupKeyOrProperty(target, keyOrProperty /*| keyof T*/) {
// get the class constructor
const constr = target.constructor;
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_ipsoKey, constr);
return metadata && metadata[keyOrProperty];
}
|
[
"function",
"lookupKeyOrProperty",
"(",
"target",
",",
"keyOrProperty",
"/*| keyof T*/",
")",
"{",
"// get the class constructor",
"const",
"constr",
"=",
"target",
".",
"constructor",
";",
"// retrieve the current metadata",
"const",
"metadata",
"=",
"Reflect",
".",
"getMetadata",
"(",
"METADATA_ipsoKey",
",",
"constr",
")",
";",
"return",
"metadata",
"&&",
"metadata",
"[",
"keyOrProperty",
"]",
";",
"}"
] |
Looks up previously stored property ipso key definitions.
Returns a property name if the key was given, or the key if a property name was given.
@param keyOrProperty - ipso key or property name to lookup
|
[
"Looks",
"up",
"previously",
"stored",
"property",
"ipso",
"key",
"definitions",
".",
"Returns",
"a",
"property",
"name",
"if",
"the",
"key",
"was",
"given",
"or",
"the",
"key",
"if",
"a",
"property",
"name",
"was",
"given",
"."
] |
8c4a1d6571068dca90c6a68f6a4c1feb56da88ee
|
https://github.com/AlCalzone/node-tradfri-client/blob/8c4a1d6571068dca90c6a68f6a4c1feb56da88ee/build/lib/ipsoObject.js#L59-L65
|
17,967
|
AlCalzone/node-tradfri-client
|
build/lib/ipsoObject.js
|
isRequired
|
function isRequired(target, reference, property) {
// get the class constructor
const constr = target.constructor;
logger_1.log(`${constr.name}: checking if ${property} is required...`, "silly");
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_required, constr) || {};
if (metadata.hasOwnProperty(property)) {
const ret = metadata[property];
if (typeof ret === "boolean")
return ret;
return ret(target, reference);
}
return false;
}
|
javascript
|
function isRequired(target, reference, property) {
// get the class constructor
const constr = target.constructor;
logger_1.log(`${constr.name}: checking if ${property} is required...`, "silly");
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_required, constr) || {};
if (metadata.hasOwnProperty(property)) {
const ret = metadata[property];
if (typeof ret === "boolean")
return ret;
return ret(target, reference);
}
return false;
}
|
[
"function",
"isRequired",
"(",
"target",
",",
"reference",
",",
"property",
")",
"{",
"// get the class constructor",
"const",
"constr",
"=",
"target",
".",
"constructor",
";",
"logger_1",
".",
"log",
"(",
"`",
"${",
"constr",
".",
"name",
"}",
"${",
"property",
"}",
"`",
",",
"\"silly\"",
")",
";",
"// retrieve the current metadata",
"const",
"metadata",
"=",
"Reflect",
".",
"getMetadata",
"(",
"METADATA_required",
",",
"constr",
")",
"||",
"{",
"}",
";",
"if",
"(",
"metadata",
".",
"hasOwnProperty",
"(",
"property",
")",
")",
"{",
"const",
"ret",
"=",
"metadata",
"[",
"property",
"]",
";",
"if",
"(",
"typeof",
"ret",
"===",
"\"boolean\"",
")",
"return",
"ret",
";",
"return",
"ret",
"(",
"target",
",",
"reference",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
Checks if a property is required to be present in a serialized CoAP object
@param property - property name to lookup
|
[
"Checks",
"if",
"a",
"property",
"is",
"required",
"to",
"be",
"present",
"in",
"a",
"serialized",
"CoAP",
"object"
] |
8c4a1d6571068dca90c6a68f6a4c1feb56da88ee
|
https://github.com/AlCalzone/node-tradfri-client/blob/8c4a1d6571068dca90c6a68f6a4c1feb56da88ee/build/lib/ipsoObject.js#L85-L98
|
17,968
|
AlCalzone/node-tradfri-client
|
build/lib/ipsoObject.js
|
serializeWith
|
function serializeWith(kernel, options) {
const transform = buildPropertyTransform(kernel, options);
return (target, property) => {
// get the class constructor
const constr = target.constructor;
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_serializeWith, constr) || {};
metadata[property] = transform;
// store back to the object
Reflect.defineMetadata(METADATA_serializeWith, metadata, constr);
};
}
|
javascript
|
function serializeWith(kernel, options) {
const transform = buildPropertyTransform(kernel, options);
return (target, property) => {
// get the class constructor
const constr = target.constructor;
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_serializeWith, constr) || {};
metadata[property] = transform;
// store back to the object
Reflect.defineMetadata(METADATA_serializeWith, metadata, constr);
};
}
|
[
"function",
"serializeWith",
"(",
"kernel",
",",
"options",
")",
"{",
"const",
"transform",
"=",
"buildPropertyTransform",
"(",
"kernel",
",",
"options",
")",
";",
"return",
"(",
"target",
",",
"property",
")",
"=>",
"{",
"// get the class constructor",
"const",
"constr",
"=",
"target",
".",
"constructor",
";",
"// retrieve the current metadata",
"const",
"metadata",
"=",
"Reflect",
".",
"getMetadata",
"(",
"METADATA_serializeWith",
",",
"constr",
")",
"||",
"{",
"}",
";",
"metadata",
"[",
"property",
"]",
"=",
"transform",
";",
"// store back to the object",
"Reflect",
".",
"defineMetadata",
"(",
"METADATA_serializeWith",
",",
"metadata",
",",
"constr",
")",
";",
"}",
";",
"}"
] |
Defines the required transformations to serialize a property to a CoAP object
@param kernel The transformation to apply during serialization
@param options Some options regarding the behavior of the property transform
|
[
"Defines",
"the",
"required",
"transformations",
"to",
"serialize",
"a",
"property",
"to",
"a",
"CoAP",
"object"
] |
8c4a1d6571068dca90c6a68f6a4c1feb56da88ee
|
https://github.com/AlCalzone/node-tradfri-client/blob/8c4a1d6571068dca90c6a68f6a4c1feb56da88ee/build/lib/ipsoObject.js#L122-L133
|
17,969
|
AlCalzone/node-tradfri-client
|
build/lib/ipsoObject.js
|
getSerializer
|
function getSerializer(target, property /* | keyof T*/) {
// get the class constructor
const constr = target.constructor;
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_serializeWith, constr) || {};
if (metadata.hasOwnProperty(property))
return metadata[property];
// If there's no custom serializer, try to find a default one
const type = getPropertyType(target, property);
if (type && type.name in defaultSerializers) {
return defaultSerializers[type.name];
}
}
|
javascript
|
function getSerializer(target, property /* | keyof T*/) {
// get the class constructor
const constr = target.constructor;
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_serializeWith, constr) || {};
if (metadata.hasOwnProperty(property))
return metadata[property];
// If there's no custom serializer, try to find a default one
const type = getPropertyType(target, property);
if (type && type.name in defaultSerializers) {
return defaultSerializers[type.name];
}
}
|
[
"function",
"getSerializer",
"(",
"target",
",",
"property",
"/* | keyof T*/",
")",
"{",
"// get the class constructor",
"const",
"constr",
"=",
"target",
".",
"constructor",
";",
"// retrieve the current metadata",
"const",
"metadata",
"=",
"Reflect",
".",
"getMetadata",
"(",
"METADATA_serializeWith",
",",
"constr",
")",
"||",
"{",
"}",
";",
"if",
"(",
"metadata",
".",
"hasOwnProperty",
"(",
"property",
")",
")",
"return",
"metadata",
"[",
"property",
"]",
";",
"// If there's no custom serializer, try to find a default one",
"const",
"type",
"=",
"getPropertyType",
"(",
"target",
",",
"property",
")",
";",
"if",
"(",
"type",
"&&",
"type",
".",
"name",
"in",
"defaultSerializers",
")",
"{",
"return",
"defaultSerializers",
"[",
"type",
".",
"name",
"]",
";",
"}",
"}"
] |
Retrieves the serializer for a given property
|
[
"Retrieves",
"the",
"serializer",
"for",
"a",
"given",
"property"
] |
8c4a1d6571068dca90c6a68f6a4c1feb56da88ee
|
https://github.com/AlCalzone/node-tradfri-client/blob/8c4a1d6571068dca90c6a68f6a4c1feb56da88ee/build/lib/ipsoObject.js#L142-L154
|
17,970
|
AlCalzone/node-tradfri-client
|
build/lib/ipsoObject.js
|
deserializeWith
|
function deserializeWith(kernel, options) {
const transform = buildPropertyTransform(kernel, options);
return (target, property) => {
// get the class constructor
const constr = target.constructor;
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_deserializeWith, constr) || {};
metadata[property] = transform;
// store back to the object
Reflect.defineMetadata(METADATA_deserializeWith, metadata, constr);
};
}
|
javascript
|
function deserializeWith(kernel, options) {
const transform = buildPropertyTransform(kernel, options);
return (target, property) => {
// get the class constructor
const constr = target.constructor;
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_deserializeWith, constr) || {};
metadata[property] = transform;
// store back to the object
Reflect.defineMetadata(METADATA_deserializeWith, metadata, constr);
};
}
|
[
"function",
"deserializeWith",
"(",
"kernel",
",",
"options",
")",
"{",
"const",
"transform",
"=",
"buildPropertyTransform",
"(",
"kernel",
",",
"options",
")",
";",
"return",
"(",
"target",
",",
"property",
")",
"=>",
"{",
"// get the class constructor",
"const",
"constr",
"=",
"target",
".",
"constructor",
";",
"// retrieve the current metadata",
"const",
"metadata",
"=",
"Reflect",
".",
"getMetadata",
"(",
"METADATA_deserializeWith",
",",
"constr",
")",
"||",
"{",
"}",
";",
"metadata",
"[",
"property",
"]",
"=",
"transform",
";",
"// store back to the object",
"Reflect",
".",
"defineMetadata",
"(",
"METADATA_deserializeWith",
",",
"metadata",
",",
"constr",
")",
";",
"}",
";",
"}"
] |
Defines the required transformations to deserialize a property from a CoAP object
@param kernel The transformation to apply during deserialization
@param options Options for deserialisation
|
[
"Defines",
"the",
"required",
"transformations",
"to",
"deserialize",
"a",
"property",
"from",
"a",
"CoAP",
"object"
] |
8c4a1d6571068dca90c6a68f6a4c1feb56da88ee
|
https://github.com/AlCalzone/node-tradfri-client/blob/8c4a1d6571068dca90c6a68f6a4c1feb56da88ee/build/lib/ipsoObject.js#L160-L171
|
17,971
|
AlCalzone/node-tradfri-client
|
build/lib/ipsoObject.js
|
isSerializable
|
function isSerializable(target, property) {
// get the class constructor
const constr = target.constructor;
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_doNotSerialize, constr) || {};
// if doNotSerialize is defined, don't serialize!
return !metadata.hasOwnProperty(property);
}
|
javascript
|
function isSerializable(target, property) {
// get the class constructor
const constr = target.constructor;
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_doNotSerialize, constr) || {};
// if doNotSerialize is defined, don't serialize!
return !metadata.hasOwnProperty(property);
}
|
[
"function",
"isSerializable",
"(",
"target",
",",
"property",
")",
"{",
"// get the class constructor",
"const",
"constr",
"=",
"target",
".",
"constructor",
";",
"// retrieve the current metadata",
"const",
"metadata",
"=",
"Reflect",
".",
"getMetadata",
"(",
"METADATA_doNotSerialize",
",",
"constr",
")",
"||",
"{",
"}",
";",
"// if doNotSerialize is defined, don't serialize!",
"return",
"!",
"metadata",
".",
"hasOwnProperty",
"(",
"property",
")",
";",
"}"
] |
Checks if a given property will be serialized or not
|
[
"Checks",
"if",
"a",
"given",
"property",
"will",
"be",
"serialized",
"or",
"not"
] |
8c4a1d6571068dca90c6a68f6a4c1feb56da88ee
|
https://github.com/AlCalzone/node-tradfri-client/blob/8c4a1d6571068dca90c6a68f6a4c1feb56da88ee/build/lib/ipsoObject.js#L188-L195
|
17,972
|
AlCalzone/node-tradfri-client
|
build/lib/ipsoObject.js
|
getDeserializer
|
function getDeserializer(target, property /*| keyof T*/) {
// get the class constructor
const constr = target.constructor;
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_deserializeWith, constr) || {};
if (metadata.hasOwnProperty(property)) {
return metadata[property];
}
// If there's no custom deserializer, try to find a default one
const type = getPropertyType(target, property);
if (type && type.name in defaultDeserializers) {
return defaultDeserializers[type.name];
}
}
|
javascript
|
function getDeserializer(target, property /*| keyof T*/) {
// get the class constructor
const constr = target.constructor;
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_deserializeWith, constr) || {};
if (metadata.hasOwnProperty(property)) {
return metadata[property];
}
// If there's no custom deserializer, try to find a default one
const type = getPropertyType(target, property);
if (type && type.name in defaultDeserializers) {
return defaultDeserializers[type.name];
}
}
|
[
"function",
"getDeserializer",
"(",
"target",
",",
"property",
"/*| keyof T*/",
")",
"{",
"// get the class constructor",
"const",
"constr",
"=",
"target",
".",
"constructor",
";",
"// retrieve the current metadata",
"const",
"metadata",
"=",
"Reflect",
".",
"getMetadata",
"(",
"METADATA_deserializeWith",
",",
"constr",
")",
"||",
"{",
"}",
";",
"if",
"(",
"metadata",
".",
"hasOwnProperty",
"(",
"property",
")",
")",
"{",
"return",
"metadata",
"[",
"property",
"]",
";",
"}",
"// If there's no custom deserializer, try to find a default one",
"const",
"type",
"=",
"getPropertyType",
"(",
"target",
",",
"property",
")",
";",
"if",
"(",
"type",
"&&",
"type",
".",
"name",
"in",
"defaultDeserializers",
")",
"{",
"return",
"defaultDeserializers",
"[",
"type",
".",
"name",
"]",
";",
"}",
"}"
] |
Retrieves the deserializer for a given property
|
[
"Retrieves",
"the",
"deserializer",
"for",
"a",
"given",
"property"
] |
8c4a1d6571068dca90c6a68f6a4c1feb56da88ee
|
https://github.com/AlCalzone/node-tradfri-client/blob/8c4a1d6571068dca90c6a68f6a4c1feb56da88ee/build/lib/ipsoObject.js#L203-L216
|
17,973
|
AlCalzone/node-tradfri-client
|
build/lib/notification.js
|
parseNotificationDetails
|
function parseNotificationDetails(kvpList) {
const ret = {};
for (const kvp of kvpList) {
const parts = kvp.split("=");
ret[parts[0]] = parts[1];
}
return ret;
}
|
javascript
|
function parseNotificationDetails(kvpList) {
const ret = {};
for (const kvp of kvpList) {
const parts = kvp.split("=");
ret[parts[0]] = parts[1];
}
return ret;
}
|
[
"function",
"parseNotificationDetails",
"(",
"kvpList",
")",
"{",
"const",
"ret",
"=",
"{",
"}",
";",
"for",
"(",
"const",
"kvp",
"of",
"kvpList",
")",
"{",
"const",
"parts",
"=",
"kvp",
".",
"split",
"(",
"\"=\"",
")",
";",
"ret",
"[",
"parts",
"[",
"0",
"]",
"]",
"=",
"parts",
"[",
"1",
"]",
";",
"}",
"return",
"ret",
";",
"}"
] |
Turns a key=value-Array into a Dictionary object
|
[
"Turns",
"a",
"key",
"=",
"value",
"-",
"Array",
"into",
"a",
"Dictionary",
"object"
] |
8c4a1d6571068dca90c6a68f6a4c1feb56da88ee
|
https://github.com/AlCalzone/node-tradfri-client/blob/8c4a1d6571068dca90c6a68f6a4c1feb56da88ee/build/lib/notification.js#L104-L111
|
17,974
|
AlCalzone/node-tradfri-client
|
build/tradfri-client.js
|
normalizeResourcePath
|
function normalizeResourcePath(path) {
path = path || "";
while (path.startsWith("/"))
path = path.slice(1);
while (path.endsWith("/"))
path = path.slice(0, -1);
return path;
}
|
javascript
|
function normalizeResourcePath(path) {
path = path || "";
while (path.startsWith("/"))
path = path.slice(1);
while (path.endsWith("/"))
path = path.slice(0, -1);
return path;
}
|
[
"function",
"normalizeResourcePath",
"(",
"path",
")",
"{",
"path",
"=",
"path",
"||",
"\"\"",
";",
"while",
"(",
"path",
".",
"startsWith",
"(",
"\"/\"",
")",
")",
"path",
"=",
"path",
".",
"slice",
"(",
"1",
")",
";",
"while",
"(",
"path",
".",
"endsWith",
"(",
"\"/\"",
")",
")",
"path",
"=",
"path",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
";",
"return",
"path",
";",
"}"
] |
Normalizes the path to a resource, so it can be used for storing the observer
|
[
"Normalizes",
"the",
"path",
"to",
"a",
"resource",
"so",
"it",
"can",
"be",
"used",
"for",
"storing",
"the",
"observer"
] |
8c4a1d6571068dca90c6a68f6a4c1feb56da88ee
|
https://github.com/AlCalzone/node-tradfri-client/blob/8c4a1d6571068dca90c6a68f6a4c1feb56da88ee/build/tradfri-client.js#L935-L942
|
17,975
|
AlCalzone/node-tradfri-client
|
build/lib/light.js
|
createRGBProxy
|
function createRGBProxy(raw = false) {
function get(me, key) {
switch (key) {
case "color": {
if (typeof me.color === "string" && rgbRegex.test(me.color)) {
// predefined color, return it
return me.color;
}
else {
// calculate it from hue/saturation
const { r, g, b } = conversions_1.conversions.rgbFromHSV(me.hue, me.saturation / 100, 1);
return conversions_1.conversions.rgbToString(r, g, b);
}
}
default: return me[key];
}
}
function set(me, key, value) {
switch (key) {
case "color": {
if (predefined_colors_1.predefinedColors.has(value)) {
// its a predefined color, use the predefined values
const definition = predefined_colors_1.predefinedColors.get(value); // we checked with `has`
if (raw) {
me.hue = definition.hue_raw;
me.saturation = definition.saturation_raw;
}
else {
me.hue = definition.hue;
me.saturation = definition.saturation;
}
}
else {
// only accept HEX colors
if (rgbRegex.test(value)) {
// calculate the X/Y values
const { r, g, b } = conversions_1.conversions.rgbFromString(value);
const { h, s /* ignore v */ } = conversions_1.conversions.rgbToHSV(r, g, b);
if (raw) {
me.hue = Math.round(h / 360 * predefined_colors_1.MAX_COLOR);
me.saturation = Math.round(s * predefined_colors_1.MAX_COLOR);
}
else {
me.hue = h;
me.saturation = s * 100;
}
}
}
break;
}
default: me[key] = value;
}
return true;
}
return { get, set };
}
|
javascript
|
function createRGBProxy(raw = false) {
function get(me, key) {
switch (key) {
case "color": {
if (typeof me.color === "string" && rgbRegex.test(me.color)) {
// predefined color, return it
return me.color;
}
else {
// calculate it from hue/saturation
const { r, g, b } = conversions_1.conversions.rgbFromHSV(me.hue, me.saturation / 100, 1);
return conversions_1.conversions.rgbToString(r, g, b);
}
}
default: return me[key];
}
}
function set(me, key, value) {
switch (key) {
case "color": {
if (predefined_colors_1.predefinedColors.has(value)) {
// its a predefined color, use the predefined values
const definition = predefined_colors_1.predefinedColors.get(value); // we checked with `has`
if (raw) {
me.hue = definition.hue_raw;
me.saturation = definition.saturation_raw;
}
else {
me.hue = definition.hue;
me.saturation = definition.saturation;
}
}
else {
// only accept HEX colors
if (rgbRegex.test(value)) {
// calculate the X/Y values
const { r, g, b } = conversions_1.conversions.rgbFromString(value);
const { h, s /* ignore v */ } = conversions_1.conversions.rgbToHSV(r, g, b);
if (raw) {
me.hue = Math.round(h / 360 * predefined_colors_1.MAX_COLOR);
me.saturation = Math.round(s * predefined_colors_1.MAX_COLOR);
}
else {
me.hue = h;
me.saturation = s * 100;
}
}
}
break;
}
default: me[key] = value;
}
return true;
}
return { get, set };
}
|
[
"function",
"createRGBProxy",
"(",
"raw",
"=",
"false",
")",
"{",
"function",
"get",
"(",
"me",
",",
"key",
")",
"{",
"switch",
"(",
"key",
")",
"{",
"case",
"\"color\"",
":",
"{",
"if",
"(",
"typeof",
"me",
".",
"color",
"===",
"\"string\"",
"&&",
"rgbRegex",
".",
"test",
"(",
"me",
".",
"color",
")",
")",
"{",
"// predefined color, return it",
"return",
"me",
".",
"color",
";",
"}",
"else",
"{",
"// calculate it from hue/saturation",
"const",
"{",
"r",
",",
"g",
",",
"b",
"}",
"=",
"conversions_1",
".",
"conversions",
".",
"rgbFromHSV",
"(",
"me",
".",
"hue",
",",
"me",
".",
"saturation",
"/",
"100",
",",
"1",
")",
";",
"return",
"conversions_1",
".",
"conversions",
".",
"rgbToString",
"(",
"r",
",",
"g",
",",
"b",
")",
";",
"}",
"}",
"default",
":",
"return",
"me",
"[",
"key",
"]",
";",
"}",
"}",
"function",
"set",
"(",
"me",
",",
"key",
",",
"value",
")",
"{",
"switch",
"(",
"key",
")",
"{",
"case",
"\"color\"",
":",
"{",
"if",
"(",
"predefined_colors_1",
".",
"predefinedColors",
".",
"has",
"(",
"value",
")",
")",
"{",
"// its a predefined color, use the predefined values",
"const",
"definition",
"=",
"predefined_colors_1",
".",
"predefinedColors",
".",
"get",
"(",
"value",
")",
";",
"// we checked with `has`",
"if",
"(",
"raw",
")",
"{",
"me",
".",
"hue",
"=",
"definition",
".",
"hue_raw",
";",
"me",
".",
"saturation",
"=",
"definition",
".",
"saturation_raw",
";",
"}",
"else",
"{",
"me",
".",
"hue",
"=",
"definition",
".",
"hue",
";",
"me",
".",
"saturation",
"=",
"definition",
".",
"saturation",
";",
"}",
"}",
"else",
"{",
"// only accept HEX colors",
"if",
"(",
"rgbRegex",
".",
"test",
"(",
"value",
")",
")",
"{",
"// calculate the X/Y values",
"const",
"{",
"r",
",",
"g",
",",
"b",
"}",
"=",
"conversions_1",
".",
"conversions",
".",
"rgbFromString",
"(",
"value",
")",
";",
"const",
"{",
"h",
",",
"s",
"/* ignore v */",
"}",
"=",
"conversions_1",
".",
"conversions",
".",
"rgbToHSV",
"(",
"r",
",",
"g",
",",
"b",
")",
";",
"if",
"(",
"raw",
")",
"{",
"me",
".",
"hue",
"=",
"Math",
".",
"round",
"(",
"h",
"/",
"360",
"*",
"predefined_colors_1",
".",
"MAX_COLOR",
")",
";",
"me",
".",
"saturation",
"=",
"Math",
".",
"round",
"(",
"s",
"*",
"predefined_colors_1",
".",
"MAX_COLOR",
")",
";",
"}",
"else",
"{",
"me",
".",
"hue",
"=",
"h",
";",
"me",
".",
"saturation",
"=",
"s",
"*",
"100",
";",
"}",
"}",
"}",
"break",
";",
"}",
"default",
":",
"me",
"[",
"key",
"]",
"=",
"value",
";",
"}",
"return",
"true",
";",
"}",
"return",
"{",
"get",
",",
"set",
"}",
";",
"}"
] |
Creates a proxy for an RGB lamp,
which converts RGB color to CIE xy
|
[
"Creates",
"a",
"proxy",
"for",
"an",
"RGB",
"lamp",
"which",
"converts",
"RGB",
"color",
"to",
"CIE",
"xy"
] |
8c4a1d6571068dca90c6a68f6a4c1feb56da88ee
|
https://github.com/AlCalzone/node-tradfri-client/blob/8c4a1d6571068dca90c6a68f6a4c1feb56da88ee/build/lib/light.js#L327-L382
|
17,976
|
Netflix/falcor-router
|
src/parse-tree/index.js
|
setHashOrThrowError
|
function setHashOrThrowError(parseMap, routeObject) {
var route = routeObject.route;
var get = routeObject.get;
var set = routeObject.set;
var call = routeObject.call;
getHashesFromRoute(route).
map(function mapHashToString(hash) { return hash.join(','); }).
forEach(function forEachRouteHash(hash) {
if (get && parseMap[hash + 'get'] ||
set && parseMap[hash + 'set'] ||
call && parseMap[hash + 'call']) {
throw new Error(errors.routeWithSamePrecedence + ' ' +
prettifyRoute(route));
}
if (get) {
parseMap[hash + 'get'] = true;
}
if (set) {
parseMap[hash + 'set'] = true;
}
if (call) {
parseMap[hash + 'call'] = true;
}
});
}
|
javascript
|
function setHashOrThrowError(parseMap, routeObject) {
var route = routeObject.route;
var get = routeObject.get;
var set = routeObject.set;
var call = routeObject.call;
getHashesFromRoute(route).
map(function mapHashToString(hash) { return hash.join(','); }).
forEach(function forEachRouteHash(hash) {
if (get && parseMap[hash + 'get'] ||
set && parseMap[hash + 'set'] ||
call && parseMap[hash + 'call']) {
throw new Error(errors.routeWithSamePrecedence + ' ' +
prettifyRoute(route));
}
if (get) {
parseMap[hash + 'get'] = true;
}
if (set) {
parseMap[hash + 'set'] = true;
}
if (call) {
parseMap[hash + 'call'] = true;
}
});
}
|
[
"function",
"setHashOrThrowError",
"(",
"parseMap",
",",
"routeObject",
")",
"{",
"var",
"route",
"=",
"routeObject",
".",
"route",
";",
"var",
"get",
"=",
"routeObject",
".",
"get",
";",
"var",
"set",
"=",
"routeObject",
".",
"set",
";",
"var",
"call",
"=",
"routeObject",
".",
"call",
";",
"getHashesFromRoute",
"(",
"route",
")",
".",
"map",
"(",
"function",
"mapHashToString",
"(",
"hash",
")",
"{",
"return",
"hash",
".",
"join",
"(",
"','",
")",
";",
"}",
")",
".",
"forEach",
"(",
"function",
"forEachRouteHash",
"(",
"hash",
")",
"{",
"if",
"(",
"get",
"&&",
"parseMap",
"[",
"hash",
"+",
"'get'",
"]",
"||",
"set",
"&&",
"parseMap",
"[",
"hash",
"+",
"'set'",
"]",
"||",
"call",
"&&",
"parseMap",
"[",
"hash",
"+",
"'call'",
"]",
")",
"{",
"throw",
"new",
"Error",
"(",
"errors",
".",
"routeWithSamePrecedence",
"+",
"' '",
"+",
"prettifyRoute",
"(",
"route",
")",
")",
";",
"}",
"if",
"(",
"get",
")",
"{",
"parseMap",
"[",
"hash",
"+",
"'get'",
"]",
"=",
"true",
";",
"}",
"if",
"(",
"set",
")",
"{",
"parseMap",
"[",
"hash",
"+",
"'set'",
"]",
"=",
"true",
";",
"}",
"if",
"(",
"call",
")",
"{",
"parseMap",
"[",
"hash",
"+",
"'call'",
"]",
"=",
"true",
";",
"}",
"}",
")",
";",
"}"
] |
ensure that two routes of the same precedence do not get
set in.
|
[
"ensure",
"that",
"two",
"routes",
"of",
"the",
"same",
"precedence",
"do",
"not",
"get",
"set",
"in",
"."
] |
7f00a2fe4fd7ce603d15526b60568af7f1e3176e
|
https://github.com/Netflix/falcor-router/blob/7f00a2fe4fd7ce603d15526b60568af7f1e3176e/src/parse-tree/index.js#L115-L140
|
17,977
|
Netflix/falcor-router
|
src/parse-tree/index.js
|
decendTreeByRoutedToken
|
function decendTreeByRoutedToken(node, value, routeToken) {
var next = null;
switch (value) {
case Keys.keys:
case Keys.integers:
case Keys.ranges:
next = node[value];
if (!next) {
next = node[value] = {};
}
break;
default:
break;
}
if (next && routeToken) {
// matches the naming information on the node.
next[Keys.named] = routeToken.named;
next[Keys.name] = routeToken.name;
}
return next;
}
|
javascript
|
function decendTreeByRoutedToken(node, value, routeToken) {
var next = null;
switch (value) {
case Keys.keys:
case Keys.integers:
case Keys.ranges:
next = node[value];
if (!next) {
next = node[value] = {};
}
break;
default:
break;
}
if (next && routeToken) {
// matches the naming information on the node.
next[Keys.named] = routeToken.named;
next[Keys.name] = routeToken.name;
}
return next;
}
|
[
"function",
"decendTreeByRoutedToken",
"(",
"node",
",",
"value",
",",
"routeToken",
")",
"{",
"var",
"next",
"=",
"null",
";",
"switch",
"(",
"value",
")",
"{",
"case",
"Keys",
".",
"keys",
":",
"case",
"Keys",
".",
"integers",
":",
"case",
"Keys",
".",
"ranges",
":",
"next",
"=",
"node",
"[",
"value",
"]",
";",
"if",
"(",
"!",
"next",
")",
"{",
"next",
"=",
"node",
"[",
"value",
"]",
"=",
"{",
"}",
";",
"}",
"break",
";",
"default",
":",
"break",
";",
"}",
"if",
"(",
"next",
"&&",
"routeToken",
")",
"{",
"// matches the naming information on the node.",
"next",
"[",
"Keys",
".",
"named",
"]",
"=",
"routeToken",
".",
"named",
";",
"next",
"[",
"Keys",
".",
"name",
"]",
"=",
"routeToken",
".",
"name",
";",
"}",
"return",
"next",
";",
"}"
] |
decends the rst and fills in any naming information at the node.
if what is passed in is not a routed token identifier, then the return
value will be null
|
[
"decends",
"the",
"rst",
"and",
"fills",
"in",
"any",
"naming",
"information",
"at",
"the",
"node",
".",
"if",
"what",
"is",
"passed",
"in",
"is",
"not",
"a",
"routed",
"token",
"identifier",
"then",
"the",
"return",
"value",
"will",
"be",
"null"
] |
7f00a2fe4fd7ce603d15526b60568af7f1e3176e
|
https://github.com/Netflix/falcor-router/blob/7f00a2fe4fd7ce603d15526b60568af7f1e3176e/src/parse-tree/index.js#L147-L168
|
17,978
|
Netflix/falcor-router
|
src/parse-tree/index.js
|
getHashesFromRoute
|
function getHashesFromRoute(route, depth, hashes, hash) {
/*eslint-disable no-func-assign, no-param-reassign*/
depth = depth || 0;
hashes = hashes || [];
hash = hash || [];
/*eslint-enable no-func-assign, no-param-reassign*/
var routeValue = route[depth];
var isArray = Array.isArray(routeValue);
var length = isArray && routeValue.length || 0;
var idx = 0;
var value;
if (typeof routeValue === 'object' && !isArray) {
value = routeValue.type;
}
else if (!isArray) {
value = routeValue;
}
do {
if (isArray) {
value = routeValue[idx];
}
if (value === Keys.integers || value === Keys.ranges) {
hash[depth] = '__I__';
}
else if (value === Keys.keys) {
hash[depth] ='__K__';
}
else {
hash[depth] = value;
}
// recurse down the routed token
if (depth + 1 !== route.length) {
getHashesFromRoute(route, depth + 1, hashes, hash);
}
// Or just add it to hashes
else {
hashes.push(cloneArray(hash));
}
} while (isArray && ++idx < length);
return hashes;
}
|
javascript
|
function getHashesFromRoute(route, depth, hashes, hash) {
/*eslint-disable no-func-assign, no-param-reassign*/
depth = depth || 0;
hashes = hashes || [];
hash = hash || [];
/*eslint-enable no-func-assign, no-param-reassign*/
var routeValue = route[depth];
var isArray = Array.isArray(routeValue);
var length = isArray && routeValue.length || 0;
var idx = 0;
var value;
if (typeof routeValue === 'object' && !isArray) {
value = routeValue.type;
}
else if (!isArray) {
value = routeValue;
}
do {
if (isArray) {
value = routeValue[idx];
}
if (value === Keys.integers || value === Keys.ranges) {
hash[depth] = '__I__';
}
else if (value === Keys.keys) {
hash[depth] ='__K__';
}
else {
hash[depth] = value;
}
// recurse down the routed token
if (depth + 1 !== route.length) {
getHashesFromRoute(route, depth + 1, hashes, hash);
}
// Or just add it to hashes
else {
hashes.push(cloneArray(hash));
}
} while (isArray && ++idx < length);
return hashes;
}
|
[
"function",
"getHashesFromRoute",
"(",
"route",
",",
"depth",
",",
"hashes",
",",
"hash",
")",
"{",
"/*eslint-disable no-func-assign, no-param-reassign*/",
"depth",
"=",
"depth",
"||",
"0",
";",
"hashes",
"=",
"hashes",
"||",
"[",
"]",
";",
"hash",
"=",
"hash",
"||",
"[",
"]",
";",
"/*eslint-enable no-func-assign, no-param-reassign*/",
"var",
"routeValue",
"=",
"route",
"[",
"depth",
"]",
";",
"var",
"isArray",
"=",
"Array",
".",
"isArray",
"(",
"routeValue",
")",
";",
"var",
"length",
"=",
"isArray",
"&&",
"routeValue",
".",
"length",
"||",
"0",
";",
"var",
"idx",
"=",
"0",
";",
"var",
"value",
";",
"if",
"(",
"typeof",
"routeValue",
"===",
"'object'",
"&&",
"!",
"isArray",
")",
"{",
"value",
"=",
"routeValue",
".",
"type",
";",
"}",
"else",
"if",
"(",
"!",
"isArray",
")",
"{",
"value",
"=",
"routeValue",
";",
"}",
"do",
"{",
"if",
"(",
"isArray",
")",
"{",
"value",
"=",
"routeValue",
"[",
"idx",
"]",
";",
"}",
"if",
"(",
"value",
"===",
"Keys",
".",
"integers",
"||",
"value",
"===",
"Keys",
".",
"ranges",
")",
"{",
"hash",
"[",
"depth",
"]",
"=",
"'__I__'",
";",
"}",
"else",
"if",
"(",
"value",
"===",
"Keys",
".",
"keys",
")",
"{",
"hash",
"[",
"depth",
"]",
"=",
"'__K__'",
";",
"}",
"else",
"{",
"hash",
"[",
"depth",
"]",
"=",
"value",
";",
"}",
"// recurse down the routed token",
"if",
"(",
"depth",
"+",
"1",
"!==",
"route",
".",
"length",
")",
"{",
"getHashesFromRoute",
"(",
"route",
",",
"depth",
"+",
"1",
",",
"hashes",
",",
"hash",
")",
";",
"}",
"// Or just add it to hashes",
"else",
"{",
"hashes",
".",
"push",
"(",
"cloneArray",
"(",
"hash",
")",
")",
";",
"}",
"}",
"while",
"(",
"isArray",
"&&",
"++",
"idx",
"<",
"length",
")",
";",
"return",
"hashes",
";",
"}"
] |
creates a hash of the virtual path where integers and ranges
will collide but everything else is unique.
|
[
"creates",
"a",
"hash",
"of",
"the",
"virtual",
"path",
"where",
"integers",
"and",
"ranges",
"will",
"collide",
"but",
"everything",
"else",
"is",
"unique",
"."
] |
7f00a2fe4fd7ce603d15526b60568af7f1e3176e
|
https://github.com/Netflix/falcor-router/blob/7f00a2fe4fd7ce603d15526b60568af7f1e3176e/src/parse-tree/index.js#L174-L224
|
17,979
|
Netflix/falcor-router
|
src/parse-tree/actionWrapper.js
|
createNamedVariables
|
function createNamedVariables(route, action) {
return function innerCreateNamedVariables(matchedPath) {
var convertedArguments;
var len = -1;
var restOfArgs = slice(arguments, 1);
var isJSONObject = !isArray(matchedPath);
// A set uses a json object
if (isJSONObject) {
restOfArgs = [];
convertedArguments = matchedPath;
}
// Could be an array of pathValues for a set operation.
else if (isPathValue(matchedPath[0])) {
convertedArguments = [];
matchedPath.forEach(function(pV) {
pV.path = convertPathToRoute(pV.path, route);
convertedArguments[++len] = pV;
});
}
// else just convert and assign
else {
convertedArguments =
convertPathToRoute(matchedPath, route);
}
return action.apply(this, [convertedArguments].concat(restOfArgs));
};
}
|
javascript
|
function createNamedVariables(route, action) {
return function innerCreateNamedVariables(matchedPath) {
var convertedArguments;
var len = -1;
var restOfArgs = slice(arguments, 1);
var isJSONObject = !isArray(matchedPath);
// A set uses a json object
if (isJSONObject) {
restOfArgs = [];
convertedArguments = matchedPath;
}
// Could be an array of pathValues for a set operation.
else if (isPathValue(matchedPath[0])) {
convertedArguments = [];
matchedPath.forEach(function(pV) {
pV.path = convertPathToRoute(pV.path, route);
convertedArguments[++len] = pV;
});
}
// else just convert and assign
else {
convertedArguments =
convertPathToRoute(matchedPath, route);
}
return action.apply(this, [convertedArguments].concat(restOfArgs));
};
}
|
[
"function",
"createNamedVariables",
"(",
"route",
",",
"action",
")",
"{",
"return",
"function",
"innerCreateNamedVariables",
"(",
"matchedPath",
")",
"{",
"var",
"convertedArguments",
";",
"var",
"len",
"=",
"-",
"1",
";",
"var",
"restOfArgs",
"=",
"slice",
"(",
"arguments",
",",
"1",
")",
";",
"var",
"isJSONObject",
"=",
"!",
"isArray",
"(",
"matchedPath",
")",
";",
"// A set uses a json object",
"if",
"(",
"isJSONObject",
")",
"{",
"restOfArgs",
"=",
"[",
"]",
";",
"convertedArguments",
"=",
"matchedPath",
";",
"}",
"// Could be an array of pathValues for a set operation.",
"else",
"if",
"(",
"isPathValue",
"(",
"matchedPath",
"[",
"0",
"]",
")",
")",
"{",
"convertedArguments",
"=",
"[",
"]",
";",
"matchedPath",
".",
"forEach",
"(",
"function",
"(",
"pV",
")",
"{",
"pV",
".",
"path",
"=",
"convertPathToRoute",
"(",
"pV",
".",
"path",
",",
"route",
")",
";",
"convertedArguments",
"[",
"++",
"len",
"]",
"=",
"pV",
";",
"}",
")",
";",
"}",
"// else just convert and assign",
"else",
"{",
"convertedArguments",
"=",
"convertPathToRoute",
"(",
"matchedPath",
",",
"route",
")",
";",
"}",
"return",
"action",
".",
"apply",
"(",
"this",
",",
"[",
"convertedArguments",
"]",
".",
"concat",
"(",
"restOfArgs",
")",
")",
";",
"}",
";",
"}"
] |
Creates the named variables and coerces it into its
virtual type.
@param {Array} route - The route that produced this action wrapper
@private
|
[
"Creates",
"the",
"named",
"variables",
"and",
"coerces",
"it",
"into",
"its",
"virtual",
"type",
"."
] |
7f00a2fe4fd7ce603d15526b60568af7f1e3176e
|
https://github.com/Netflix/falcor-router/blob/7f00a2fe4fd7ce603d15526b60568af7f1e3176e/src/parse-tree/actionWrapper.js#L13-L43
|
17,980
|
neveldo/jQuery-Mapael
|
js/jquery.mapael.js
|
function(isInit) {
var containerWidth = self.$map.width();
if (self.paper.width !== containerWidth) {
var newScale = containerWidth / self.mapConf.width;
// Set new size
self.paper.setSize(containerWidth, self.mapConf.height * newScale);
// Create plots legend again to take into account the new scale
// Do not do this on init (it will be done later)
if (isInit !== true && self.options.legend.redrawOnResize) {
self.createLegends("plot", self.plots, newScale);
}
}
}
|
javascript
|
function(isInit) {
var containerWidth = self.$map.width();
if (self.paper.width !== containerWidth) {
var newScale = containerWidth / self.mapConf.width;
// Set new size
self.paper.setSize(containerWidth, self.mapConf.height * newScale);
// Create plots legend again to take into account the new scale
// Do not do this on init (it will be done later)
if (isInit !== true && self.options.legend.redrawOnResize) {
self.createLegends("plot", self.plots, newScale);
}
}
}
|
[
"function",
"(",
"isInit",
")",
"{",
"var",
"containerWidth",
"=",
"self",
".",
"$map",
".",
"width",
"(",
")",
";",
"if",
"(",
"self",
".",
"paper",
".",
"width",
"!==",
"containerWidth",
")",
"{",
"var",
"newScale",
"=",
"containerWidth",
"/",
"self",
".",
"mapConf",
".",
"width",
";",
"// Set new size",
"self",
".",
"paper",
".",
"setSize",
"(",
"containerWidth",
",",
"self",
".",
"mapConf",
".",
"height",
"*",
"newScale",
")",
";",
"// Create plots legend again to take into account the new scale",
"// Do not do this on init (it will be done later)",
"if",
"(",
"isInit",
"!==",
"true",
"&&",
"self",
".",
"options",
".",
"legend",
".",
"redrawOnResize",
")",
"{",
"self",
".",
"createLegends",
"(",
"\"plot\"",
",",
"self",
".",
"plots",
",",
"newScale",
")",
";",
"}",
"}",
"}"
] |
Function that actually handle the resizing
|
[
"Function",
"that",
"actually",
"handle",
"the",
"resizing"
] |
66d58661c5385f366efa6c9867adb7283d158013
|
https://github.com/neveldo/jQuery-Mapael/blob/66d58661c5385f366efa6c9867adb7283d158013/js/jquery.mapael.js#L335-L349
|
|
17,981
|
neveldo/jQuery-Mapael
|
js/jquery.mapael.js
|
function (elem) {
// Starts with hidden elements
elem.mapElem.attr({opacity: 0});
if (elem.textElem) elem.textElem.attr({opacity: 0});
// Set final element opacity
self.setElementOpacity(
elem,
(elem.mapElem.originalAttrs.opacity !== undefined) ? elem.mapElem.originalAttrs.opacity : 1,
animDuration
);
}
|
javascript
|
function (elem) {
// Starts with hidden elements
elem.mapElem.attr({opacity: 0});
if (elem.textElem) elem.textElem.attr({opacity: 0});
// Set final element opacity
self.setElementOpacity(
elem,
(elem.mapElem.originalAttrs.opacity !== undefined) ? elem.mapElem.originalAttrs.opacity : 1,
animDuration
);
}
|
[
"function",
"(",
"elem",
")",
"{",
"// Starts with hidden elements",
"elem",
".",
"mapElem",
".",
"attr",
"(",
"{",
"opacity",
":",
"0",
"}",
")",
";",
"if",
"(",
"elem",
".",
"textElem",
")",
"elem",
".",
"textElem",
".",
"attr",
"(",
"{",
"opacity",
":",
"0",
"}",
")",
";",
"// Set final element opacity",
"self",
".",
"setElementOpacity",
"(",
"elem",
",",
"(",
"elem",
".",
"mapElem",
".",
"originalAttrs",
".",
"opacity",
"!==",
"undefined",
")",
"?",
"elem",
".",
"mapElem",
".",
"originalAttrs",
".",
"opacity",
":",
"1",
",",
"animDuration",
")",
";",
"}"
] |
This function show an element using animation Used for newPlots and newLinks
|
[
"This",
"function",
"show",
"an",
"element",
"using",
"animation",
"Used",
"for",
"newPlots",
"and",
"newLinks"
] |
66d58661c5385f366efa6c9867adb7283d158013
|
https://github.com/neveldo/jQuery-Mapael/blob/66d58661c5385f366efa6c9867adb7283d158013/js/jquery.mapael.js#L1127-L1137
|
|
17,982
|
millermedeiros/esformatter
|
lib/format.js
|
pipe
|
function pipe(commands, input) {
if (!commands) {
return input;
}
return commands.reduce(function(input, cmd) {
return npmRun.sync(cmd, {
input: input
});
}, input);
}
|
javascript
|
function pipe(commands, input) {
if (!commands) {
return input;
}
return commands.reduce(function(input, cmd) {
return npmRun.sync(cmd, {
input: input
});
}, input);
}
|
[
"function",
"pipe",
"(",
"commands",
",",
"input",
")",
"{",
"if",
"(",
"!",
"commands",
")",
"{",
"return",
"input",
";",
"}",
"return",
"commands",
".",
"reduce",
"(",
"function",
"(",
"input",
",",
"cmd",
")",
"{",
"return",
"npmRun",
".",
"sync",
"(",
"cmd",
",",
"{",
"input",
":",
"input",
"}",
")",
";",
"}",
",",
"input",
")",
";",
"}"
] |
run cli tools in series passing the stdout of previous tool as stdin of next one
|
[
"run",
"cli",
"tools",
"in",
"series",
"passing",
"the",
"stdout",
"of",
"previous",
"tool",
"as",
"stdin",
"of",
"next",
"one"
] |
29045f0aa731c7738042c89d7ed4758faf9aacd1
|
https://github.com/millermedeiros/esformatter/blob/29045f0aa731c7738042c89d7ed4758faf9aacd1/lib/format.js#L73-L82
|
17,983
|
millermedeiros/esformatter
|
lib/cli.js
|
logError
|
function logError(e) {
var msg = typeof e === 'string' ? e : e.message;
// esprima.parse errors are in the format 'Line 123: Unexpected token &'
// we support both formats since users might replace the parser
if ((/Line \d+:/).test(msg)) {
// convert into "Error: <filepath>:<line> <error_message>"
msg = 'Error: ' + msg.replace(/[^\d]+(\d+): (.+)/, e.file + ':$1 $2');
} else {
// babylon.parse errors are in the format 'Unexpected token (0:4)'
var m = (/^([^\(]+)\s\((\d+):(\d+)\)/).exec(msg);
if (m) {
// convert into "Error: <filepath>:<line>:<char> <error_message>"
msg = 'Error: ' + e.file + ':' + m[2] + ':' + m[3] + ' ' + m[1];
} else if (msg.indexOf('Error:') < 0) {
msg = 'Error: ' + (e.file ? e.file + ' ' : '') + msg;
}
}
// set the error flag to true to use an exit code !== 0
exports.exitCode = 1;
// we don't call console.error directly to make it possible to mock during
// unit tests
exports.stderr.write(msg + '\n');
if (e.stack) {
exports.stderr.write(e.stack + '\n');
}
}
|
javascript
|
function logError(e) {
var msg = typeof e === 'string' ? e : e.message;
// esprima.parse errors are in the format 'Line 123: Unexpected token &'
// we support both formats since users might replace the parser
if ((/Line \d+:/).test(msg)) {
// convert into "Error: <filepath>:<line> <error_message>"
msg = 'Error: ' + msg.replace(/[^\d]+(\d+): (.+)/, e.file + ':$1 $2');
} else {
// babylon.parse errors are in the format 'Unexpected token (0:4)'
var m = (/^([^\(]+)\s\((\d+):(\d+)\)/).exec(msg);
if (m) {
// convert into "Error: <filepath>:<line>:<char> <error_message>"
msg = 'Error: ' + e.file + ':' + m[2] + ':' + m[3] + ' ' + m[1];
} else if (msg.indexOf('Error:') < 0) {
msg = 'Error: ' + (e.file ? e.file + ' ' : '') + msg;
}
}
// set the error flag to true to use an exit code !== 0
exports.exitCode = 1;
// we don't call console.error directly to make it possible to mock during
// unit tests
exports.stderr.write(msg + '\n');
if (e.stack) {
exports.stderr.write(e.stack + '\n');
}
}
|
[
"function",
"logError",
"(",
"e",
")",
"{",
"var",
"msg",
"=",
"typeof",
"e",
"===",
"'string'",
"?",
"e",
":",
"e",
".",
"message",
";",
"// esprima.parse errors are in the format 'Line 123: Unexpected token &'",
"// we support both formats since users might replace the parser",
"if",
"(",
"(",
"/",
"Line \\d+:",
"/",
")",
".",
"test",
"(",
"msg",
")",
")",
"{",
"// convert into \"Error: <filepath>:<line> <error_message>\"",
"msg",
"=",
"'Error: '",
"+",
"msg",
".",
"replace",
"(",
"/",
"[^\\d]+(\\d+): (.+)",
"/",
",",
"e",
".",
"file",
"+",
"':$1 $2'",
")",
";",
"}",
"else",
"{",
"// babylon.parse errors are in the format 'Unexpected token (0:4)'",
"var",
"m",
"=",
"(",
"/",
"^([^\\(]+)\\s\\((\\d+):(\\d+)\\)",
"/",
")",
".",
"exec",
"(",
"msg",
")",
";",
"if",
"(",
"m",
")",
"{",
"// convert into \"Error: <filepath>:<line>:<char> <error_message>\"",
"msg",
"=",
"'Error: '",
"+",
"e",
".",
"file",
"+",
"':'",
"+",
"m",
"[",
"2",
"]",
"+",
"':'",
"+",
"m",
"[",
"3",
"]",
"+",
"' '",
"+",
"m",
"[",
"1",
"]",
";",
"}",
"else",
"if",
"(",
"msg",
".",
"indexOf",
"(",
"'Error:'",
")",
"<",
"0",
")",
"{",
"msg",
"=",
"'Error: '",
"+",
"(",
"e",
".",
"file",
"?",
"e",
".",
"file",
"+",
"' '",
":",
"''",
")",
"+",
"msg",
";",
"}",
"}",
"// set the error flag to true to use an exit code !== 0",
"exports",
".",
"exitCode",
"=",
"1",
";",
"// we don't call console.error directly to make it possible to mock during",
"// unit tests",
"exports",
".",
"stderr",
".",
"write",
"(",
"msg",
"+",
"'\\n'",
")",
";",
"if",
"(",
"e",
".",
"stack",
")",
"{",
"exports",
".",
"stderr",
".",
"write",
"(",
"e",
".",
"stack",
"+",
"'\\n'",
")",
";",
"}",
"}"
] |
we are handling errors this way instead of prematurely terminating the program because user might be editing multiple files at once and error might only be present on a single file
|
[
"we",
"are",
"handling",
"errors",
"this",
"way",
"instead",
"of",
"prematurely",
"terminating",
"the",
"program",
"because",
"user",
"might",
"be",
"editing",
"multiple",
"files",
"at",
"once",
"and",
"error",
"might",
"only",
"be",
"present",
"on",
"a",
"single",
"file"
] |
29045f0aa731c7738042c89d7ed4758faf9aacd1
|
https://github.com/millermedeiros/esformatter/blob/29045f0aa731c7738042c89d7ed4758faf9aacd1/lib/cli.js#L112-L141
|
17,984
|
twitter/recess
|
lib/index.js
|
recess
|
function recess(init, path, err) {
if (path = paths.shift()) {
return instances.push(new RECESS(path, options, recess))
}
// map/filter for errors
err = instances
.map(function (i) {
return i.errors.length && i.errors
})
.filter(function (i) {
return i
})
// if no error, set explicitly to null
err = err.length ? err[0] : null
//callback
callback && callback(err, instances)
}
|
javascript
|
function recess(init, path, err) {
if (path = paths.shift()) {
return instances.push(new RECESS(path, options, recess))
}
// map/filter for errors
err = instances
.map(function (i) {
return i.errors.length && i.errors
})
.filter(function (i) {
return i
})
// if no error, set explicitly to null
err = err.length ? err[0] : null
//callback
callback && callback(err, instances)
}
|
[
"function",
"recess",
"(",
"init",
",",
"path",
",",
"err",
")",
"{",
"if",
"(",
"path",
"=",
"paths",
".",
"shift",
"(",
")",
")",
"{",
"return",
"instances",
".",
"push",
"(",
"new",
"RECESS",
"(",
"path",
",",
"options",
",",
"recess",
")",
")",
"}",
"// map/filter for errors",
"err",
"=",
"instances",
".",
"map",
"(",
"function",
"(",
"i",
")",
"{",
"return",
"i",
".",
"errors",
".",
"length",
"&&",
"i",
".",
"errors",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"i",
")",
"{",
"return",
"i",
"}",
")",
"// if no error, set explicitly to null",
"err",
"=",
"err",
".",
"length",
"?",
"err",
"[",
"0",
"]",
":",
"null",
"//callback",
"callback",
"&&",
"callback",
"(",
"err",
",",
"instances",
")",
"}"
] |
for each path, create a new RECESS instance
|
[
"for",
"each",
"path",
"create",
"a",
"new",
"RECESS",
"instance"
] |
146143bc0876e559e16a9895bd2d5212eee8730d
|
https://github.com/twitter/recess/blob/146143bc0876e559e16a9895bd2d5212eee8730d/lib/index.js#L47-L66
|
17,985
|
twitter/recess
|
lib/util.js
|
function (def, err) {
def.errors = def.errors || []
err.message = err.message.cyan
def.errors.push(err)
}
|
javascript
|
function (def, err) {
def.errors = def.errors || []
err.message = err.message.cyan
def.errors.push(err)
}
|
[
"function",
"(",
"def",
",",
"err",
")",
"{",
"def",
".",
"errors",
"=",
"def",
".",
"errors",
"||",
"[",
"]",
"err",
".",
"message",
"=",
"err",
".",
"message",
".",
"cyan",
"def",
".",
"errors",
".",
"push",
"(",
"err",
")",
"}"
] |
set fail output object
|
[
"set",
"fail",
"output",
"object"
] |
146143bc0876e559e16a9895bd2d5212eee8730d
|
https://github.com/twitter/recess/blob/146143bc0876e559e16a9895bd2d5212eee8730d/lib/util.js#L17-L21
|
|
17,986
|
twitter/recess
|
lib/core.js
|
RECESS
|
function RECESS(path, options, callback) {
this.path = path
this.output = []
this.errors = []
this.options = _.extend({}, RECESS.DEFAULTS, options)
path && this.read()
this.callback = callback
}
|
javascript
|
function RECESS(path, options, callback) {
this.path = path
this.output = []
this.errors = []
this.options = _.extend({}, RECESS.DEFAULTS, options)
path && this.read()
this.callback = callback
}
|
[
"function",
"RECESS",
"(",
"path",
",",
"options",
",",
"callback",
")",
"{",
"this",
".",
"path",
"=",
"path",
"this",
".",
"output",
"=",
"[",
"]",
"this",
".",
"errors",
"=",
"[",
"]",
"this",
".",
"options",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"RECESS",
".",
"DEFAULTS",
",",
"options",
")",
"path",
"&&",
"this",
".",
"read",
"(",
")",
"this",
".",
"callback",
"=",
"callback",
"}"
] |
core class defintion
|
[
"core",
"class",
"defintion"
] |
146143bc0876e559e16a9895bd2d5212eee8730d
|
https://github.com/twitter/recess/blob/146143bc0876e559e16a9895bd2d5212eee8730d/lib/core.js#L20-L27
|
17,987
|
ai/visibilityjs
|
lib/visibility.core.js
|
function(event) {
var state = self.state();
for ( var i in self._callbacks ) {
self._callbacks[i].call(self._doc, event, state);
}
}
|
javascript
|
function(event) {
var state = self.state();
for ( var i in self._callbacks ) {
self._callbacks[i].call(self._doc, event, state);
}
}
|
[
"function",
"(",
"event",
")",
"{",
"var",
"state",
"=",
"self",
".",
"state",
"(",
")",
";",
"for",
"(",
"var",
"i",
"in",
"self",
".",
"_callbacks",
")",
"{",
"self",
".",
"_callbacks",
"[",
"i",
"]",
".",
"call",
"(",
"self",
".",
"_doc",
",",
"event",
",",
"state",
")",
";",
"}",
"}"
] |
Listener for `visibilitychange` event.
|
[
"Listener",
"for",
"visibilitychange",
"event",
"."
] |
a1e126e79f670b89a8c74283f09ba54784c13d26
|
https://github.com/ai/visibilityjs/blob/a1e126e79f670b89a8c74283f09ba54784c13d26/lib/visibility.core.js#L151-L157
|
|
17,988
|
ai/visibilityjs
|
lib/visibility.core.js
|
function () {
if ( self._init ) {
return;
}
var event = 'visibilitychange';
if ( self._doc.webkitVisibilityState ) {
event = 'webkit' + event;
}
var listener = function () {
self._change.apply(self, arguments);
};
if ( self._doc.addEventListener ) {
self._doc.addEventListener(event, listener);
} else {
self._doc.attachEvent(event, listener);
}
self._init = true;
}
|
javascript
|
function () {
if ( self._init ) {
return;
}
var event = 'visibilitychange';
if ( self._doc.webkitVisibilityState ) {
event = 'webkit' + event;
}
var listener = function () {
self._change.apply(self, arguments);
};
if ( self._doc.addEventListener ) {
self._doc.addEventListener(event, listener);
} else {
self._doc.attachEvent(event, listener);
}
self._init = true;
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"self",
".",
"_init",
")",
"{",
"return",
";",
"}",
"var",
"event",
"=",
"'visibilitychange'",
";",
"if",
"(",
"self",
".",
"_doc",
".",
"webkitVisibilityState",
")",
"{",
"event",
"=",
"'webkit'",
"+",
"event",
";",
"}",
"var",
"listener",
"=",
"function",
"(",
")",
"{",
"self",
".",
"_change",
".",
"apply",
"(",
"self",
",",
"arguments",
")",
";",
"}",
";",
"if",
"(",
"self",
".",
"_doc",
".",
"addEventListener",
")",
"{",
"self",
".",
"_doc",
".",
"addEventListener",
"(",
"event",
",",
"listener",
")",
";",
"}",
"else",
"{",
"self",
".",
"_doc",
".",
"attachEvent",
"(",
"event",
",",
"listener",
")",
";",
"}",
"self",
".",
"_init",
"=",
"true",
";",
"}"
] |
Set listener for `visibilitychange` event.
|
[
"Set",
"listener",
"for",
"visibilitychange",
"event",
"."
] |
a1e126e79f670b89a8c74283f09ba54784c13d26
|
https://github.com/ai/visibilityjs/blob/a1e126e79f670b89a8c74283f09ba54784c13d26/lib/visibility.core.js#L160-L179
|
|
17,989
|
creationix/step
|
lib/step.js
|
next
|
function next() {
counter = pending = 0;
// Check if there are no steps left
if (steps.length === 0) {
// Throw uncaught errors
if (arguments[0]) {
throw arguments[0];
}
return;
}
// Get the next step to execute
var fn = steps.shift();
results = [];
// Run the step in a try..catch block so exceptions don't get out of hand.
try {
lock = true;
var result = fn.apply(next, arguments);
} catch (e) {
// Pass any exceptions on through the next callback
next(e);
}
if (counter > 0 && pending == 0) {
// If parallel() was called, and all parallel branches executed
// synchronously, go on to the next step immediately.
next.apply(null, results);
} else if (result !== undefined) {
// If a synchronous return is used, pass it to the callback
next(undefined, result);
}
lock = false;
}
|
javascript
|
function next() {
counter = pending = 0;
// Check if there are no steps left
if (steps.length === 0) {
// Throw uncaught errors
if (arguments[0]) {
throw arguments[0];
}
return;
}
// Get the next step to execute
var fn = steps.shift();
results = [];
// Run the step in a try..catch block so exceptions don't get out of hand.
try {
lock = true;
var result = fn.apply(next, arguments);
} catch (e) {
// Pass any exceptions on through the next callback
next(e);
}
if (counter > 0 && pending == 0) {
// If parallel() was called, and all parallel branches executed
// synchronously, go on to the next step immediately.
next.apply(null, results);
} else if (result !== undefined) {
// If a synchronous return is used, pass it to the callback
next(undefined, result);
}
lock = false;
}
|
[
"function",
"next",
"(",
")",
"{",
"counter",
"=",
"pending",
"=",
"0",
";",
"// Check if there are no steps left",
"if",
"(",
"steps",
".",
"length",
"===",
"0",
")",
"{",
"// Throw uncaught errors",
"if",
"(",
"arguments",
"[",
"0",
"]",
")",
"{",
"throw",
"arguments",
"[",
"0",
"]",
";",
"}",
"return",
";",
"}",
"// Get the next step to execute",
"var",
"fn",
"=",
"steps",
".",
"shift",
"(",
")",
";",
"results",
"=",
"[",
"]",
";",
"// Run the step in a try..catch block so exceptions don't get out of hand.",
"try",
"{",
"lock",
"=",
"true",
";",
"var",
"result",
"=",
"fn",
".",
"apply",
"(",
"next",
",",
"arguments",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// Pass any exceptions on through the next callback",
"next",
"(",
"e",
")",
";",
"}",
"if",
"(",
"counter",
">",
"0",
"&&",
"pending",
"==",
"0",
")",
"{",
"// If parallel() was called, and all parallel branches executed",
"// synchronously, go on to the next step immediately.",
"next",
".",
"apply",
"(",
"null",
",",
"results",
")",
";",
"}",
"else",
"if",
"(",
"result",
"!==",
"undefined",
")",
"{",
"// If a synchronous return is used, pass it to the callback",
"next",
"(",
"undefined",
",",
"result",
")",
";",
"}",
"lock",
"=",
"false",
";",
"}"
] |
Define the main callback that's given as `this` to the steps.
|
[
"Define",
"the",
"main",
"callback",
"that",
"s",
"given",
"as",
"this",
"to",
"the",
"steps",
"."
] |
2806543cdd75bfafd556a0396f5611c8a18eacff
|
https://github.com/creationix/step/blob/2806543cdd75bfafd556a0396f5611c8a18eacff/lib/step.js#L32-L66
|
17,990
|
ajaxorg/treehugger
|
lib/treehugger/traverse.js
|
seq
|
function seq() {
var fn;
var t = this;
for (var i = 0; i < arguments.length; i++) {
fn = arguments[i];
t = fn.call(t);
if (!t)
return false;
}
return this;
}
|
javascript
|
function seq() {
var fn;
var t = this;
for (var i = 0; i < arguments.length; i++) {
fn = arguments[i];
t = fn.call(t);
if (!t)
return false;
}
return this;
}
|
[
"function",
"seq",
"(",
")",
"{",
"var",
"fn",
";",
"var",
"t",
"=",
"this",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"fn",
"=",
"arguments",
"[",
"i",
"]",
";",
"t",
"=",
"fn",
".",
"call",
"(",
"t",
")",
";",
"if",
"(",
"!",
"t",
")",
"return",
"false",
";",
"}",
"return",
"this",
";",
"}"
] |
Sequential application last argument is term
|
[
"Sequential",
"application",
"last",
"argument",
"is",
"term"
] |
30a335ba99f0dd05f8532ce8aaa4903d5fcd2ab7
|
https://github.com/ajaxorg/treehugger/blob/30a335ba99f0dd05f8532ce8aaa4903d5fcd2ab7/lib/treehugger/traverse.js#L75-L85
|
17,991
|
ajaxorg/treehugger
|
lib/treehugger/traverse.js
|
traverseTopDown
|
function traverseTopDown(fn) {
var result, i;
result = fn.call(this);
if(result)
return result;
if (this instanceof tree.ConsNode || this instanceof tree.ListNode) {
for (i = 0; i < this.length; i++) {
traverseTopDown.call(this[i], fn);
}
}
return this;
}
|
javascript
|
function traverseTopDown(fn) {
var result, i;
result = fn.call(this);
if(result)
return result;
if (this instanceof tree.ConsNode || this instanceof tree.ListNode) {
for (i = 0; i < this.length; i++) {
traverseTopDown.call(this[i], fn);
}
}
return this;
}
|
[
"function",
"traverseTopDown",
"(",
"fn",
")",
"{",
"var",
"result",
",",
"i",
";",
"result",
"=",
"fn",
".",
"call",
"(",
"this",
")",
";",
"if",
"(",
"result",
")",
"return",
"result",
";",
"if",
"(",
"this",
"instanceof",
"tree",
".",
"ConsNode",
"||",
"this",
"instanceof",
"tree",
".",
"ListNode",
")",
"{",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"length",
";",
"i",
"++",
")",
"{",
"traverseTopDown",
".",
"call",
"(",
"this",
"[",
"i",
"]",
",",
"fn",
")",
";",
"}",
"}",
"return",
"this",
";",
"}"
] |
A somewhat optimized version of the "clean" topdown traversal
|
[
"A",
"somewhat",
"optimized",
"version",
"of",
"the",
"clean",
"topdown",
"traversal"
] |
30a335ba99f0dd05f8532ce8aaa4903d5fcd2ab7
|
https://github.com/ajaxorg/treehugger/blob/30a335ba99f0dd05f8532ce8aaa4903d5fcd2ab7/lib/treehugger/traverse.js#L99-L110
|
17,992
|
ajaxorg/treehugger
|
lib/treehugger/tree.js
|
ConsNode
|
function ConsNode(cons, children) {
this.cons = cons;
for(var i = 0; i < children.length; i++) {
this[i] = children[i];
}
this.length = children.length;
}
|
javascript
|
function ConsNode(cons, children) {
this.cons = cons;
for(var i = 0; i < children.length; i++) {
this[i] = children[i];
}
this.length = children.length;
}
|
[
"function",
"ConsNode",
"(",
"cons",
",",
"children",
")",
"{",
"this",
".",
"cons",
"=",
"cons",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"children",
".",
"length",
";",
"i",
"++",
")",
"{",
"this",
"[",
"i",
"]",
"=",
"children",
"[",
"i",
"]",
";",
"}",
"this",
".",
"length",
"=",
"children",
".",
"length",
";",
"}"
] |
Represents a constructor node
Example: Add(Num("1"), Num("2")) is constucted
using new ConsNode(new ConsNode("Num", [new StringNode("1")]),
new ConsNode("Num", [new StringNode("2")]))
or, more briefly:
tree.cons("Add", [tree.cons("Num", [ast.string("1"), ast.string("2")])])
|
[
"Represents",
"a",
"constructor",
"node"
] |
30a335ba99f0dd05f8532ce8aaa4903d5fcd2ab7
|
https://github.com/ajaxorg/treehugger/blob/30a335ba99f0dd05f8532ce8aaa4903d5fcd2ab7/lib/treehugger/tree.js#L67-L73
|
17,993
|
ajaxorg/treehugger
|
lib/acorn/dist/walk.js
|
findNodeAround
|
function findNodeAround(node, pos, test, base, state) {
test = makeTest(test);
if (!base) base = exports.base;
try {
;(function c(node, st, override) {
var type = override || node.type;
if (node.start > pos || node.end < pos) return;
base[type](node, st, c);
if (test(type, node)) throw new Found(node, st);
})(node, state);
} catch (e) {
if (e instanceof Found) return e;
throw e;
}
}
|
javascript
|
function findNodeAround(node, pos, test, base, state) {
test = makeTest(test);
if (!base) base = exports.base;
try {
;(function c(node, st, override) {
var type = override || node.type;
if (node.start > pos || node.end < pos) return;
base[type](node, st, c);
if (test(type, node)) throw new Found(node, st);
})(node, state);
} catch (e) {
if (e instanceof Found) return e;
throw e;
}
}
|
[
"function",
"findNodeAround",
"(",
"node",
",",
"pos",
",",
"test",
",",
"base",
",",
"state",
")",
"{",
"test",
"=",
"makeTest",
"(",
"test",
")",
";",
"if",
"(",
"!",
"base",
")",
"base",
"=",
"exports",
".",
"base",
";",
"try",
"{",
";",
"(",
"function",
"c",
"(",
"node",
",",
"st",
",",
"override",
")",
"{",
"var",
"type",
"=",
"override",
"||",
"node",
".",
"type",
";",
"if",
"(",
"node",
".",
"start",
">",
"pos",
"||",
"node",
".",
"end",
"<",
"pos",
")",
"return",
";",
"base",
"[",
"type",
"]",
"(",
"node",
",",
"st",
",",
"c",
")",
";",
"if",
"(",
"test",
"(",
"type",
",",
"node",
")",
")",
"throw",
"new",
"Found",
"(",
"node",
",",
"st",
")",
";",
"}",
")",
"(",
"node",
",",
"state",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"e",
"instanceof",
"Found",
")",
"return",
"e",
";",
"throw",
"e",
";",
"}",
"}"
] |
Find the innermost node of a given type that contains the given position. Interface similar to findNodeAt.
|
[
"Find",
"the",
"innermost",
"node",
"of",
"a",
"given",
"type",
"that",
"contains",
"the",
"given",
"position",
".",
"Interface",
"similar",
"to",
"findNodeAt",
"."
] |
30a335ba99f0dd05f8532ce8aaa4903d5fcd2ab7
|
https://github.com/ajaxorg/treehugger/blob/30a335ba99f0dd05f8532ce8aaa4903d5fcd2ab7/lib/acorn/dist/walk.js#L110-L124
|
17,994
|
ajaxorg/treehugger
|
lib/acorn/dist/acorn.js
|
isIdentifierChar
|
function isIdentifierChar(code, astral) {
if (code < 48) return code === 36;
if (code < 58) return true;
if (code < 65) return false;
if (code < 91) return true;
if (code < 97) return code === 95;
if (code < 123) return true;
return code >= 0xaa;
}
|
javascript
|
function isIdentifierChar(code, astral) {
if (code < 48) return code === 36;
if (code < 58) return true;
if (code < 65) return false;
if (code < 91) return true;
if (code < 97) return code === 95;
if (code < 123) return true;
return code >= 0xaa;
}
|
[
"function",
"isIdentifierChar",
"(",
"code",
",",
"astral",
")",
"{",
"if",
"(",
"code",
"<",
"48",
")",
"return",
"code",
"===",
"36",
";",
"if",
"(",
"code",
"<",
"58",
")",
"return",
"true",
";",
"if",
"(",
"code",
"<",
"65",
")",
"return",
"false",
";",
"if",
"(",
"code",
"<",
"91",
")",
"return",
"true",
";",
"if",
"(",
"code",
"<",
"97",
")",
"return",
"code",
"===",
"95",
";",
"if",
"(",
"code",
"<",
"123",
")",
"return",
"true",
";",
"return",
"code",
">=",
"0xaa",
";",
"}"
] |
Test whether a given character is part of an identifier.
|
[
"Test",
"whether",
"a",
"given",
"character",
"is",
"part",
"of",
"an",
"identifier",
"."
] |
30a335ba99f0dd05f8532ce8aaa4903d5fcd2ab7
|
https://github.com/ajaxorg/treehugger/blob/30a335ba99f0dd05f8532ce8aaa4903d5fcd2ab7/lib/acorn/dist/acorn.js#L742-L750
|
17,995
|
ajaxorg/treehugger
|
lib/acorn/dist/acorn.js
|
parseExpressionAt
|
function parseExpressionAt(input, pos, options) {
var p = new _state.Parser(options, input, pos);
p.nextToken();
return p.parseExpression();
}
|
javascript
|
function parseExpressionAt(input, pos, options) {
var p = new _state.Parser(options, input, pos);
p.nextToken();
return p.parseExpression();
}
|
[
"function",
"parseExpressionAt",
"(",
"input",
",",
"pos",
",",
"options",
")",
"{",
"var",
"p",
"=",
"new",
"_state",
".",
"Parser",
"(",
"options",
",",
"input",
",",
"pos",
")",
";",
"p",
".",
"nextToken",
"(",
")",
";",
"return",
"p",
".",
"parseExpression",
"(",
")",
";",
"}"
] |
This function tries to parse a single expression at a given offset in a string. Useful for parsing mixed-language formats that embed JavaScript expressions.
|
[
"This",
"function",
"tries",
"to",
"parse",
"a",
"single",
"expression",
"at",
"a",
"given",
"offset",
"in",
"a",
"string",
".",
"Useful",
"for",
"parsing",
"mixed",
"-",
"language",
"formats",
"that",
"embed",
"JavaScript",
"expressions",
"."
] |
30a335ba99f0dd05f8532ce8aaa4903d5fcd2ab7
|
https://github.com/ajaxorg/treehugger/blob/30a335ba99f0dd05f8532ce8aaa4903d5fcd2ab7/lib/acorn/dist/acorn.js#L852-L856
|
17,996
|
ajaxorg/treehugger
|
lib/acorn/dist/acorn.js
|
finishNodeAt
|
function finishNodeAt(node, type, pos, loc) {
node.type = type;
node.end = pos;
if (this.options.locations) node.loc.end = loc;
if (this.options.ranges) node.range[1] = pos;
return node;
}
|
javascript
|
function finishNodeAt(node, type, pos, loc) {
node.type = type;
node.end = pos;
if (this.options.locations) node.loc.end = loc;
if (this.options.ranges) node.range[1] = pos;
return node;
}
|
[
"function",
"finishNodeAt",
"(",
"node",
",",
"type",
",",
"pos",
",",
"loc",
")",
"{",
"node",
".",
"type",
"=",
"type",
";",
"node",
".",
"end",
"=",
"pos",
";",
"if",
"(",
"this",
".",
"options",
".",
"locations",
")",
"node",
".",
"loc",
".",
"end",
"=",
"loc",
";",
"if",
"(",
"this",
".",
"options",
".",
"ranges",
")",
"node",
".",
"range",
"[",
"1",
"]",
"=",
"pos",
";",
"return",
"node",
";",
"}"
] |
Finish an AST node, adding `type` and `end` properties.
|
[
"Finish",
"an",
"AST",
"node",
"adding",
"type",
"and",
"end",
"properties",
"."
] |
30a335ba99f0dd05f8532ce8aaa4903d5fcd2ab7
|
https://github.com/ajaxorg/treehugger/blob/30a335ba99f0dd05f8532ce8aaa4903d5fcd2ab7/lib/acorn/dist/acorn.js#L1209-L1215
|
17,997
|
ajaxorg/treehugger
|
lib/acorn/dist/acorn.js
|
getOptions
|
function getOptions(opts) {
var options = {};
for (var opt in defaultOptions) {
options[opt] = opts && _util.has(opts, opt) ? opts[opt] : defaultOptions[opt];
}if (options.allowReserved == null) options.allowReserved = options.ecmaVersion < 5;
if (_util.isArray(options.onToken)) {
(function () {
var tokens = options.onToken;
options.onToken = function (token) {
return tokens.push(token);
};
})();
}
if (_util.isArray(options.onComment)) options.onComment = pushComment(options, options.onComment);
return options;
}
|
javascript
|
function getOptions(opts) {
var options = {};
for (var opt in defaultOptions) {
options[opt] = opts && _util.has(opts, opt) ? opts[opt] : defaultOptions[opt];
}if (options.allowReserved == null) options.allowReserved = options.ecmaVersion < 5;
if (_util.isArray(options.onToken)) {
(function () {
var tokens = options.onToken;
options.onToken = function (token) {
return tokens.push(token);
};
})();
}
if (_util.isArray(options.onComment)) options.onComment = pushComment(options, options.onComment);
return options;
}
|
[
"function",
"getOptions",
"(",
"opts",
")",
"{",
"var",
"options",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"opt",
"in",
"defaultOptions",
")",
"{",
"options",
"[",
"opt",
"]",
"=",
"opts",
"&&",
"_util",
".",
"has",
"(",
"opts",
",",
"opt",
")",
"?",
"opts",
"[",
"opt",
"]",
":",
"defaultOptions",
"[",
"opt",
"]",
";",
"}",
"if",
"(",
"options",
".",
"allowReserved",
"==",
"null",
")",
"options",
".",
"allowReserved",
"=",
"options",
".",
"ecmaVersion",
"<",
"5",
";",
"if",
"(",
"_util",
".",
"isArray",
"(",
"options",
".",
"onToken",
")",
")",
"{",
"(",
"function",
"(",
")",
"{",
"var",
"tokens",
"=",
"options",
".",
"onToken",
";",
"options",
".",
"onToken",
"=",
"function",
"(",
"token",
")",
"{",
"return",
"tokens",
".",
"push",
"(",
"token",
")",
";",
"}",
";",
"}",
")",
"(",
")",
";",
"}",
"if",
"(",
"_util",
".",
"isArray",
"(",
"options",
".",
"onComment",
")",
")",
"options",
".",
"onComment",
"=",
"pushComment",
"(",
"options",
",",
"options",
".",
"onComment",
")",
";",
"return",
"options",
";",
"}"
] |
Interpret and default an options object
|
[
"Interpret",
"and",
"default",
"an",
"options",
"object"
] |
30a335ba99f0dd05f8532ce8aaa4903d5fcd2ab7
|
https://github.com/ajaxorg/treehugger/blob/30a335ba99f0dd05f8532ce8aaa4903d5fcd2ab7/lib/acorn/dist/acorn.js#L1323-L1340
|
17,998
|
ajaxorg/treehugger
|
lib/acorn/dist/acorn.js
|
Token
|
function Token(p) {
this.type = p.type;
this.value = p.value;
this.start = p.start;
this.end = p.end;
if (p.options.locations) this.loc = new _locutil.SourceLocation(p, p.startLoc, p.endLoc);
if (p.options.ranges) this.range = [p.start, p.end];
}
|
javascript
|
function Token(p) {
this.type = p.type;
this.value = p.value;
this.start = p.start;
this.end = p.end;
if (p.options.locations) this.loc = new _locutil.SourceLocation(p, p.startLoc, p.endLoc);
if (p.options.ranges) this.range = [p.start, p.end];
}
|
[
"function",
"Token",
"(",
"p",
")",
"{",
"this",
".",
"type",
"=",
"p",
".",
"type",
";",
"this",
".",
"value",
"=",
"p",
".",
"value",
";",
"this",
".",
"start",
"=",
"p",
".",
"start",
";",
"this",
".",
"end",
"=",
"p",
".",
"end",
";",
"if",
"(",
"p",
".",
"options",
".",
"locations",
")",
"this",
".",
"loc",
"=",
"new",
"_locutil",
".",
"SourceLocation",
"(",
"p",
",",
"p",
".",
"startLoc",
",",
"p",
".",
"endLoc",
")",
";",
"if",
"(",
"p",
".",
"options",
".",
"ranges",
")",
"this",
".",
"range",
"=",
"[",
"p",
".",
"start",
",",
"p",
".",
"end",
"]",
";",
"}"
] |
Object type used to represent tokens. Note that normally, tokens simply exist as properties on the parser object. This is only used for the onToken callback and the external tokenizer.
|
[
"Object",
"type",
"used",
"to",
"represent",
"tokens",
".",
"Note",
"that",
"normally",
"tokens",
"simply",
"exist",
"as",
"properties",
"on",
"the",
"parser",
"object",
".",
"This",
"is",
"only",
"used",
"for",
"the",
"onToken",
"callback",
"and",
"the",
"external",
"tokenizer",
"."
] |
30a335ba99f0dd05f8532ce8aaa4903d5fcd2ab7
|
https://github.com/ajaxorg/treehugger/blob/30a335ba99f0dd05f8532ce8aaa4903d5fcd2ab7/lib/acorn/dist/acorn.js#L2379-L2388
|
17,999
|
yargs/cliui
|
index.js
|
_minWidth
|
function _minWidth (col) {
var padding = col.padding || []
var minWidth = 1 + (padding[left] || 0) + (padding[right] || 0)
if (col.border) minWidth += 4
return minWidth
}
|
javascript
|
function _minWidth (col) {
var padding = col.padding || []
var minWidth = 1 + (padding[left] || 0) + (padding[right] || 0)
if (col.border) minWidth += 4
return minWidth
}
|
[
"function",
"_minWidth",
"(",
"col",
")",
"{",
"var",
"padding",
"=",
"col",
".",
"padding",
"||",
"[",
"]",
"var",
"minWidth",
"=",
"1",
"+",
"(",
"padding",
"[",
"left",
"]",
"||",
"0",
")",
"+",
"(",
"padding",
"[",
"right",
"]",
"||",
"0",
")",
"if",
"(",
"col",
".",
"border",
")",
"minWidth",
"+=",
"4",
"return",
"minWidth",
"}"
] |
calculates the minimum width of a column, based on padding preferences.
|
[
"calculates",
"the",
"minimum",
"width",
"of",
"a",
"column",
"based",
"on",
"padding",
"preferences",
"."
] |
e49b32f3358d0269663f80d4e2a81c9936af3ba9
|
https://github.com/yargs/cliui/blob/e49b32f3358d0269663f80d4e2a81c9936af3ba9/index.js#L282-L287
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.