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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
13,000
|
andrewplummer/Sugar
|
lib/date.js
|
iterateOverDateUnits
|
function iterateOverDateUnits(fn, startIndex, endIndex) {
endIndex = endIndex || 0;
if (isUndefined(startIndex)) {
startIndex = YEAR_INDEX;
}
for (var index = startIndex; index >= endIndex; index--) {
if (fn(DateUnits[index], index) === false) {
break;
}
}
}
|
javascript
|
function iterateOverDateUnits(fn, startIndex, endIndex) {
endIndex = endIndex || 0;
if (isUndefined(startIndex)) {
startIndex = YEAR_INDEX;
}
for (var index = startIndex; index >= endIndex; index--) {
if (fn(DateUnits[index], index) === false) {
break;
}
}
}
|
[
"function",
"iterateOverDateUnits",
"(",
"fn",
",",
"startIndex",
",",
"endIndex",
")",
"{",
"endIndex",
"=",
"endIndex",
"||",
"0",
";",
"if",
"(",
"isUndefined",
"(",
"startIndex",
")",
")",
"{",
"startIndex",
"=",
"YEAR_INDEX",
";",
"}",
"for",
"(",
"var",
"index",
"=",
"startIndex",
";",
"index",
">=",
"endIndex",
";",
"index",
"--",
")",
"{",
"if",
"(",
"fn",
"(",
"DateUnits",
"[",
"index",
"]",
",",
"index",
")",
"===",
"false",
")",
"{",
"break",
";",
"}",
"}",
"}"
] |
Iteration helpers Years -> Milliseconds
|
[
"Iteration",
"helpers",
"Years",
"-",
">",
"Milliseconds"
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/date.js#L746-L756
|
13,001
|
andrewplummer/Sugar
|
lib/date.js
|
iterateOverDateParams
|
function iterateOverDateParams(params, fn, startIndex, endIndex) {
function run(name, unit, i) {
var val = getDateParam(params, name);
if (isDefined(val)) {
fn(name, val, unit, i);
}
}
iterateOverDateUnits(function (unit, i) {
var result = run(unit.name, unit, i);
if (result !== false && i === DAY_INDEX) {
// Check for "weekday", which has a distinct meaning
// in the context of setting a date, but has the same
// meaning as "day" as a unit of time.
result = run('weekday', unit, i);
}
return result;
}, startIndex, endIndex);
}
|
javascript
|
function iterateOverDateParams(params, fn, startIndex, endIndex) {
function run(name, unit, i) {
var val = getDateParam(params, name);
if (isDefined(val)) {
fn(name, val, unit, i);
}
}
iterateOverDateUnits(function (unit, i) {
var result = run(unit.name, unit, i);
if (result !== false && i === DAY_INDEX) {
// Check for "weekday", which has a distinct meaning
// in the context of setting a date, but has the same
// meaning as "day" as a unit of time.
result = run('weekday', unit, i);
}
return result;
}, startIndex, endIndex);
}
|
[
"function",
"iterateOverDateParams",
"(",
"params",
",",
"fn",
",",
"startIndex",
",",
"endIndex",
")",
"{",
"function",
"run",
"(",
"name",
",",
"unit",
",",
"i",
")",
"{",
"var",
"val",
"=",
"getDateParam",
"(",
"params",
",",
"name",
")",
";",
"if",
"(",
"isDefined",
"(",
"val",
")",
")",
"{",
"fn",
"(",
"name",
",",
"val",
",",
"unit",
",",
"i",
")",
";",
"}",
"}",
"iterateOverDateUnits",
"(",
"function",
"(",
"unit",
",",
"i",
")",
"{",
"var",
"result",
"=",
"run",
"(",
"unit",
".",
"name",
",",
"unit",
",",
"i",
")",
";",
"if",
"(",
"result",
"!==",
"false",
"&&",
"i",
"===",
"DAY_INDEX",
")",
"{",
"// Check for \"weekday\", which has a distinct meaning",
"// in the context of setting a date, but has the same",
"// meaning as \"day\" as a unit of time.",
"result",
"=",
"run",
"(",
"'weekday'",
",",
"unit",
",",
"i",
")",
";",
"}",
"return",
"result",
";",
"}",
",",
"startIndex",
",",
"endIndex",
")",
";",
"}"
] |
Years -> Milliseconds checking all date params including "weekday"
|
[
"Years",
"-",
">",
"Milliseconds",
"checking",
"all",
"date",
"params",
"including",
"weekday"
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/date.js#L784-L804
|
13,002
|
andrewplummer/Sugar
|
lib/date.js
|
setISOWeekNumber
|
function setISOWeekNumber(d, num) {
if (isNumber(num)) {
// Intentionally avoiding updateDate here to prevent circular dependencies.
var isoWeek = cloneDate(d), dow = getWeekday(d);
moveToFirstDayOfWeekYear(isoWeek, ISO_FIRST_DAY_OF_WEEK, ISO_FIRST_DAY_OF_WEEK_YEAR);
setDate(isoWeek, getDate(isoWeek) + 7 * (num - 1));
setYear(d, getYear(isoWeek));
setMonth(d, getMonth(isoWeek));
setDate(d, getDate(isoWeek));
setWeekday(d, dow || 7);
}
return d.getTime();
}
|
javascript
|
function setISOWeekNumber(d, num) {
if (isNumber(num)) {
// Intentionally avoiding updateDate here to prevent circular dependencies.
var isoWeek = cloneDate(d), dow = getWeekday(d);
moveToFirstDayOfWeekYear(isoWeek, ISO_FIRST_DAY_OF_WEEK, ISO_FIRST_DAY_OF_WEEK_YEAR);
setDate(isoWeek, getDate(isoWeek) + 7 * (num - 1));
setYear(d, getYear(isoWeek));
setMonth(d, getMonth(isoWeek));
setDate(d, getDate(isoWeek));
setWeekday(d, dow || 7);
}
return d.getTime();
}
|
[
"function",
"setISOWeekNumber",
"(",
"d",
",",
"num",
")",
"{",
"if",
"(",
"isNumber",
"(",
"num",
")",
")",
"{",
"// Intentionally avoiding updateDate here to prevent circular dependencies.",
"var",
"isoWeek",
"=",
"cloneDate",
"(",
"d",
")",
",",
"dow",
"=",
"getWeekday",
"(",
"d",
")",
";",
"moveToFirstDayOfWeekYear",
"(",
"isoWeek",
",",
"ISO_FIRST_DAY_OF_WEEK",
",",
"ISO_FIRST_DAY_OF_WEEK_YEAR",
")",
";",
"setDate",
"(",
"isoWeek",
",",
"getDate",
"(",
"isoWeek",
")",
"+",
"7",
"*",
"(",
"num",
"-",
"1",
")",
")",
";",
"setYear",
"(",
"d",
",",
"getYear",
"(",
"isoWeek",
")",
")",
";",
"setMonth",
"(",
"d",
",",
"getMonth",
"(",
"isoWeek",
")",
")",
";",
"setDate",
"(",
"d",
",",
"getDate",
"(",
"isoWeek",
")",
")",
";",
"setWeekday",
"(",
"d",
",",
"dow",
"||",
"7",
")",
";",
"}",
"return",
"d",
".",
"getTime",
"(",
")",
";",
"}"
] |
Week number helpers
|
[
"Week",
"number",
"helpers"
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/date.js#L959-L971
|
13,003
|
andrewplummer/Sugar
|
lib/date.js
|
getWeekYear
|
function getWeekYear(d, localeCode, iso) {
var year, month, firstDayOfWeek, firstDayOfWeekYear, week, loc;
year = getYear(d);
month = getMonth(d);
if (month === 0 || month === 11) {
if (!iso) {
loc = localeManager.get(localeCode);
firstDayOfWeek = loc.getFirstDayOfWeek(localeCode);
firstDayOfWeekYear = loc.getFirstDayOfWeekYear(localeCode);
}
week = getWeekNumber(d, false, firstDayOfWeek, firstDayOfWeekYear);
if (month === 0 && week === 0) {
year -= 1;
} else if (month === 11 && week === 1) {
year += 1;
}
}
return year;
}
|
javascript
|
function getWeekYear(d, localeCode, iso) {
var year, month, firstDayOfWeek, firstDayOfWeekYear, week, loc;
year = getYear(d);
month = getMonth(d);
if (month === 0 || month === 11) {
if (!iso) {
loc = localeManager.get(localeCode);
firstDayOfWeek = loc.getFirstDayOfWeek(localeCode);
firstDayOfWeekYear = loc.getFirstDayOfWeekYear(localeCode);
}
week = getWeekNumber(d, false, firstDayOfWeek, firstDayOfWeekYear);
if (month === 0 && week === 0) {
year -= 1;
} else if (month === 11 && week === 1) {
year += 1;
}
}
return year;
}
|
[
"function",
"getWeekYear",
"(",
"d",
",",
"localeCode",
",",
"iso",
")",
"{",
"var",
"year",
",",
"month",
",",
"firstDayOfWeek",
",",
"firstDayOfWeekYear",
",",
"week",
",",
"loc",
";",
"year",
"=",
"getYear",
"(",
"d",
")",
";",
"month",
"=",
"getMonth",
"(",
"d",
")",
";",
"if",
"(",
"month",
"===",
"0",
"||",
"month",
"===",
"11",
")",
"{",
"if",
"(",
"!",
"iso",
")",
"{",
"loc",
"=",
"localeManager",
".",
"get",
"(",
"localeCode",
")",
";",
"firstDayOfWeek",
"=",
"loc",
".",
"getFirstDayOfWeek",
"(",
"localeCode",
")",
";",
"firstDayOfWeekYear",
"=",
"loc",
".",
"getFirstDayOfWeekYear",
"(",
"localeCode",
")",
";",
"}",
"week",
"=",
"getWeekNumber",
"(",
"d",
",",
"false",
",",
"firstDayOfWeek",
",",
"firstDayOfWeekYear",
")",
";",
"if",
"(",
"month",
"===",
"0",
"&&",
"week",
"===",
"0",
")",
"{",
"year",
"-=",
"1",
";",
"}",
"else",
"if",
"(",
"month",
"===",
"11",
"&&",
"week",
"===",
"1",
")",
"{",
"year",
"+=",
"1",
";",
"}",
"}",
"return",
"year",
";",
"}"
] |
Week year helpers
|
[
"Week",
"year",
"helpers"
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/date.js#L1002-L1020
|
13,004
|
andrewplummer/Sugar
|
lib/date.js
|
getAdjustedUnit
|
function getAdjustedUnit(ms, fn) {
var unitIndex = 0, value = 0;
iterateOverDateUnits(function(unit, i) {
value = abs(fn(unit));
if (value >= 1) {
unitIndex = i;
return false;
}
});
return [value, unitIndex, ms];
}
|
javascript
|
function getAdjustedUnit(ms, fn) {
var unitIndex = 0, value = 0;
iterateOverDateUnits(function(unit, i) {
value = abs(fn(unit));
if (value >= 1) {
unitIndex = i;
return false;
}
});
return [value, unitIndex, ms];
}
|
[
"function",
"getAdjustedUnit",
"(",
"ms",
",",
"fn",
")",
"{",
"var",
"unitIndex",
"=",
"0",
",",
"value",
"=",
"0",
";",
"iterateOverDateUnits",
"(",
"function",
"(",
"unit",
",",
"i",
")",
"{",
"value",
"=",
"abs",
"(",
"fn",
"(",
"unit",
")",
")",
";",
"if",
"(",
"value",
">=",
"1",
")",
"{",
"unitIndex",
"=",
"i",
";",
"return",
"false",
";",
"}",
"}",
")",
";",
"return",
"[",
"value",
",",
"unitIndex",
",",
"ms",
"]",
";",
"}"
] |
Gets an "adjusted date unit" which is a way of representing the largest possible meaningful unit. In other words, if passed 3600000, this will return an array which represents "1 hour".
|
[
"Gets",
"an",
"adjusted",
"date",
"unit",
"which",
"is",
"a",
"way",
"of",
"representing",
"the",
"largest",
"possible",
"meaningful",
"unit",
".",
"In",
"other",
"words",
"if",
"passed",
"3600000",
"this",
"will",
"return",
"an",
"array",
"which",
"represents",
"1",
"hour",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/date.js#L1065-L1075
|
13,005
|
andrewplummer/Sugar
|
lib/date.js
|
getAdjustedUnitForNumber
|
function getAdjustedUnitForNumber(ms) {
return getAdjustedUnit(ms, function(unit) {
return trunc(withPrecision(ms / unit.multiplier, 1));
});
}
|
javascript
|
function getAdjustedUnitForNumber(ms) {
return getAdjustedUnit(ms, function(unit) {
return trunc(withPrecision(ms / unit.multiplier, 1));
});
}
|
[
"function",
"getAdjustedUnitForNumber",
"(",
"ms",
")",
"{",
"return",
"getAdjustedUnit",
"(",
"ms",
",",
"function",
"(",
"unit",
")",
"{",
"return",
"trunc",
"(",
"withPrecision",
"(",
"ms",
"/",
"unit",
".",
"multiplier",
",",
"1",
")",
")",
";",
"}",
")",
";",
"}"
] |
Gets the adjusted unit based on simple division by date unit multiplier.
|
[
"Gets",
"the",
"adjusted",
"unit",
"based",
"on",
"simple",
"division",
"by",
"date",
"unit",
"multiplier",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/date.js#L1079-L1083
|
13,006
|
andrewplummer/Sugar
|
lib/date.js
|
cloneDateByFlag
|
function cloneDateByFlag(d, clone) {
if (_utc(d) && !isDefined(optFromUTC)) {
optFromUTC = true;
}
if (_utc(d) && !isDefined(optSetUTC)) {
optSetUTC = true;
}
if (clone) {
d = new Date(d.getTime());
}
return d;
}
|
javascript
|
function cloneDateByFlag(d, clone) {
if (_utc(d) && !isDefined(optFromUTC)) {
optFromUTC = true;
}
if (_utc(d) && !isDefined(optSetUTC)) {
optSetUTC = true;
}
if (clone) {
d = new Date(d.getTime());
}
return d;
}
|
[
"function",
"cloneDateByFlag",
"(",
"d",
",",
"clone",
")",
"{",
"if",
"(",
"_utc",
"(",
"d",
")",
"&&",
"!",
"isDefined",
"(",
"optFromUTC",
")",
")",
"{",
"optFromUTC",
"=",
"true",
";",
"}",
"if",
"(",
"_utc",
"(",
"d",
")",
"&&",
"!",
"isDefined",
"(",
"optSetUTC",
")",
")",
"{",
"optSetUTC",
"=",
"true",
";",
"}",
"if",
"(",
"clone",
")",
"{",
"d",
"=",
"new",
"Date",
"(",
"d",
".",
"getTime",
"(",
")",
")",
";",
"}",
"return",
"d",
";",
"}"
] |
Force the UTC flags to be true if the source date date is UTC, as they will be overwritten later.
|
[
"Force",
"the",
"UTC",
"flags",
"to",
"be",
"true",
"if",
"the",
"source",
"date",
"date",
"is",
"UTC",
"as",
"they",
"will",
"be",
"overwritten",
"later",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/date.js#L1416-L1427
|
13,007
|
andrewplummer/Sugar
|
lib/array.js
|
arraySafeConcat
|
function arraySafeConcat(arr, arg) {
var result = arrayClone(arr), len = result.length, arr2;
arr2 = isArray(arg) ? arg : [arg];
result.length += arr2.length;
forEach(arr2, function(el, i) {
result[len + i] = el;
});
return result;
}
|
javascript
|
function arraySafeConcat(arr, arg) {
var result = arrayClone(arr), len = result.length, arr2;
arr2 = isArray(arg) ? arg : [arg];
result.length += arr2.length;
forEach(arr2, function(el, i) {
result[len + i] = el;
});
return result;
}
|
[
"function",
"arraySafeConcat",
"(",
"arr",
",",
"arg",
")",
"{",
"var",
"result",
"=",
"arrayClone",
"(",
"arr",
")",
",",
"len",
"=",
"result",
".",
"length",
",",
"arr2",
";",
"arr2",
"=",
"isArray",
"(",
"arg",
")",
"?",
"arg",
":",
"[",
"arg",
"]",
";",
"result",
".",
"length",
"+=",
"arr2",
".",
"length",
";",
"forEach",
"(",
"arr2",
",",
"function",
"(",
"el",
",",
"i",
")",
"{",
"result",
"[",
"len",
"+",
"i",
"]",
"=",
"el",
";",
"}",
")",
";",
"return",
"result",
";",
"}"
] |
Avoids issues with concat in < IE8 istanbul ignore next
|
[
"Avoids",
"issues",
"with",
"concat",
"in",
"<",
"IE8",
"istanbul",
"ignore",
"next"
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/array.js#L142-L150
|
13,008
|
andrewplummer/Sugar
|
lib/string.js
|
runGlobalMatch
|
function runGlobalMatch(str, reg) {
var result = [], match, lastLastIndex;
while ((match = reg.exec(str)) != null) {
if (reg.lastIndex === lastLastIndex) {
reg.lastIndex += 1;
} else {
result.push(match[0]);
}
lastLastIndex = reg.lastIndex;
}
return result;
}
|
javascript
|
function runGlobalMatch(str, reg) {
var result = [], match, lastLastIndex;
while ((match = reg.exec(str)) != null) {
if (reg.lastIndex === lastLastIndex) {
reg.lastIndex += 1;
} else {
result.push(match[0]);
}
lastLastIndex = reg.lastIndex;
}
return result;
}
|
[
"function",
"runGlobalMatch",
"(",
"str",
",",
"reg",
")",
"{",
"var",
"result",
"=",
"[",
"]",
",",
"match",
",",
"lastLastIndex",
";",
"while",
"(",
"(",
"match",
"=",
"reg",
".",
"exec",
"(",
"str",
")",
")",
"!=",
"null",
")",
"{",
"if",
"(",
"reg",
".",
"lastIndex",
"===",
"lastLastIndex",
")",
"{",
"reg",
".",
"lastIndex",
"+=",
"1",
";",
"}",
"else",
"{",
"result",
".",
"push",
"(",
"match",
"[",
"0",
"]",
")",
";",
"}",
"lastLastIndex",
"=",
"reg",
".",
"lastIndex",
";",
"}",
"return",
"result",
";",
"}"
] |
"match" in < IE9 has enumable properties that will confuse for..in loops, so ensure that the match is a normal array by manually running "exec". Note that this method is also slightly more performant.
|
[
"match",
"in",
"<",
"IE9",
"has",
"enumable",
"properties",
"that",
"will",
"confuse",
"for",
"..",
"in",
"loops",
"so",
"ensure",
"that",
"the",
"match",
"is",
"a",
"normal",
"array",
"by",
"manually",
"running",
"exec",
".",
"Note",
"that",
"this",
"method",
"is",
"also",
"slightly",
"more",
"performant",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/string.js#L124-L135
|
13,009
|
andrewplummer/Sugar
|
lib/enumerable.js
|
sliceArrayFromRight
|
function sliceArrayFromRight(arr, startIndex, loop) {
if (!loop) {
startIndex += 1;
arr = arr.slice(0, max(0, startIndex));
}
return arr;
}
|
javascript
|
function sliceArrayFromRight(arr, startIndex, loop) {
if (!loop) {
startIndex += 1;
arr = arr.slice(0, max(0, startIndex));
}
return arr;
}
|
[
"function",
"sliceArrayFromRight",
"(",
"arr",
",",
"startIndex",
",",
"loop",
")",
"{",
"if",
"(",
"!",
"loop",
")",
"{",
"startIndex",
"+=",
"1",
";",
"arr",
"=",
"arr",
".",
"slice",
"(",
"0",
",",
"max",
"(",
"0",
",",
"startIndex",
")",
")",
";",
"}",
"return",
"arr",
";",
"}"
] |
When iterating from the right, indexes are effectively shifted by 1. For example, iterating from the right from index 2 in an array of 3 should also include the last element in the array. This matches the "lastIndexOf" method which also iterates from the right.
|
[
"When",
"iterating",
"from",
"the",
"right",
"indexes",
"are",
"effectively",
"shifted",
"by",
"1",
".",
"For",
"example",
"iterating",
"from",
"the",
"right",
"from",
"index",
"2",
"in",
"an",
"array",
"of",
"3",
"should",
"also",
"include",
"the",
"last",
"element",
"in",
"the",
"array",
".",
"This",
"matches",
"the",
"lastIndexOf",
"method",
"which",
"also",
"iterates",
"from",
"the",
"right",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/enumerable.js#L304-L310
|
13,010
|
andrewplummer/Sugar
|
lib/common.js
|
defineOnPrototype
|
function defineOnPrototype(ctor, methods) {
var proto = ctor.prototype;
forEachProperty(methods, function(val, key) {
proto[key] = val;
});
}
|
javascript
|
function defineOnPrototype(ctor, methods) {
var proto = ctor.prototype;
forEachProperty(methods, function(val, key) {
proto[key] = val;
});
}
|
[
"function",
"defineOnPrototype",
"(",
"ctor",
",",
"methods",
")",
"{",
"var",
"proto",
"=",
"ctor",
".",
"prototype",
";",
"forEachProperty",
"(",
"methods",
",",
"function",
"(",
"val",
",",
"key",
")",
"{",
"proto",
"[",
"key",
"]",
"=",
"val",
";",
"}",
")",
";",
"}"
] |
For methods defined directly on the prototype like Range
|
[
"For",
"methods",
"defined",
"directly",
"on",
"the",
"prototype",
"like",
"Range"
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/common.js#L268-L273
|
13,011
|
andrewplummer/Sugar
|
lib/common.js
|
coercePositiveInteger
|
function coercePositiveInteger(n) {
n = +n || 0;
if (n < 0 || !isNumber(n) || !isFinite(n)) {
throw new RangeError('Invalid number');
}
return trunc(n);
}
|
javascript
|
function coercePositiveInteger(n) {
n = +n || 0;
if (n < 0 || !isNumber(n) || !isFinite(n)) {
throw new RangeError('Invalid number');
}
return trunc(n);
}
|
[
"function",
"coercePositiveInteger",
"(",
"n",
")",
"{",
"n",
"=",
"+",
"n",
"||",
"0",
";",
"if",
"(",
"n",
"<",
"0",
"||",
"!",
"isNumber",
"(",
"n",
")",
"||",
"!",
"isFinite",
"(",
"n",
")",
")",
"{",
"throw",
"new",
"RangeError",
"(",
"'Invalid number'",
")",
";",
"}",
"return",
"trunc",
"(",
"n",
")",
";",
"}"
] |
Coerces an object to a positive integer. Does not allow Infinity.
|
[
"Coerces",
"an",
"object",
"to",
"a",
"positive",
"integer",
".",
"Does",
"not",
"allow",
"Infinity",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/common.js#L307-L313
|
13,012
|
andrewplummer/Sugar
|
lib/common.js
|
getMatcher
|
function getMatcher(f) {
if (!isPrimitive(f)) {
var className = classToString(f);
if (isRegExp(f, className)) {
return regexMatcher(f);
} else if (isDate(f, className)) {
return dateMatcher(f);
} else if (isFunction(f, className)) {
return functionMatcher(f);
} else if (isPlainObject(f, className)) {
return fuzzyMatcher(f);
}
}
// Default is standard isEqual
return defaultMatcher(f);
}
|
javascript
|
function getMatcher(f) {
if (!isPrimitive(f)) {
var className = classToString(f);
if (isRegExp(f, className)) {
return regexMatcher(f);
} else if (isDate(f, className)) {
return dateMatcher(f);
} else if (isFunction(f, className)) {
return functionMatcher(f);
} else if (isPlainObject(f, className)) {
return fuzzyMatcher(f);
}
}
// Default is standard isEqual
return defaultMatcher(f);
}
|
[
"function",
"getMatcher",
"(",
"f",
")",
"{",
"if",
"(",
"!",
"isPrimitive",
"(",
"f",
")",
")",
"{",
"var",
"className",
"=",
"classToString",
"(",
"f",
")",
";",
"if",
"(",
"isRegExp",
"(",
"f",
",",
"className",
")",
")",
"{",
"return",
"regexMatcher",
"(",
"f",
")",
";",
"}",
"else",
"if",
"(",
"isDate",
"(",
"f",
",",
"className",
")",
")",
"{",
"return",
"dateMatcher",
"(",
"f",
")",
";",
"}",
"else",
"if",
"(",
"isFunction",
"(",
"f",
",",
"className",
")",
")",
"{",
"return",
"functionMatcher",
"(",
"f",
")",
";",
"}",
"else",
"if",
"(",
"isPlainObject",
"(",
"f",
",",
"className",
")",
")",
"{",
"return",
"fuzzyMatcher",
"(",
"f",
")",
";",
"}",
"}",
"// Default is standard isEqual",
"return",
"defaultMatcher",
"(",
"f",
")",
";",
"}"
] |
Fuzzy matching helpers
|
[
"Fuzzy",
"matching",
"helpers"
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/common.js#L345-L360
|
13,013
|
andrewplummer/Sugar
|
lib/common.js
|
handleArrayIndexRange
|
function handleArrayIndexRange(obj, key, any, val) {
var match, start, end, leading, trailing, arr, set;
match = key.match(PROPERTY_RANGE_REG);
if (!match) {
return;
}
set = isDefined(val);
leading = match[1];
if (leading) {
arr = handleDeepProperty(obj, leading, any, false, set ? true : false, true);
} else {
arr = obj;
}
assertArray(arr);
trailing = match[4];
start = match[2] ? +match[2] : 0;
end = match[3] ? +match[3] : arr.length;
// A range of 0..1 is inclusive, so we need to add 1 to the end. If this
// pushes the index from -1 to 0, then set it to the full length of the
// array, otherwise it will return nothing.
end = end === -1 ? arr.length : end + 1;
if (set) {
for (var i = start; i < end; i++) {
handleDeepProperty(arr, i + trailing, any, false, true, false, val);
}
} else {
arr = arr.slice(start, end);
// If there are trailing properties, then they need to be mapped for each
// element in the array.
if (trailing) {
if (trailing.charAt(0) === HALF_WIDTH_PERIOD) {
// Need to chomp the period if one is trailing after the range. We
// can't do this at the regex level because it will be required if
// we're setting the value as it needs to be concatentated together
// with the array index to be set.
trailing = trailing.slice(1);
}
return map(arr, function(el) {
return handleDeepProperty(el, trailing);
});
}
}
return arr;
}
|
javascript
|
function handleArrayIndexRange(obj, key, any, val) {
var match, start, end, leading, trailing, arr, set;
match = key.match(PROPERTY_RANGE_REG);
if (!match) {
return;
}
set = isDefined(val);
leading = match[1];
if (leading) {
arr = handleDeepProperty(obj, leading, any, false, set ? true : false, true);
} else {
arr = obj;
}
assertArray(arr);
trailing = match[4];
start = match[2] ? +match[2] : 0;
end = match[3] ? +match[3] : arr.length;
// A range of 0..1 is inclusive, so we need to add 1 to the end. If this
// pushes the index from -1 to 0, then set it to the full length of the
// array, otherwise it will return nothing.
end = end === -1 ? arr.length : end + 1;
if (set) {
for (var i = start; i < end; i++) {
handleDeepProperty(arr, i + trailing, any, false, true, false, val);
}
} else {
arr = arr.slice(start, end);
// If there are trailing properties, then they need to be mapped for each
// element in the array.
if (trailing) {
if (trailing.charAt(0) === HALF_WIDTH_PERIOD) {
// Need to chomp the period if one is trailing after the range. We
// can't do this at the regex level because it will be required if
// we're setting the value as it needs to be concatentated together
// with the array index to be set.
trailing = trailing.slice(1);
}
return map(arr, function(el) {
return handleDeepProperty(el, trailing);
});
}
}
return arr;
}
|
[
"function",
"handleArrayIndexRange",
"(",
"obj",
",",
"key",
",",
"any",
",",
"val",
")",
"{",
"var",
"match",
",",
"start",
",",
"end",
",",
"leading",
",",
"trailing",
",",
"arr",
",",
"set",
";",
"match",
"=",
"key",
".",
"match",
"(",
"PROPERTY_RANGE_REG",
")",
";",
"if",
"(",
"!",
"match",
")",
"{",
"return",
";",
"}",
"set",
"=",
"isDefined",
"(",
"val",
")",
";",
"leading",
"=",
"match",
"[",
"1",
"]",
";",
"if",
"(",
"leading",
")",
"{",
"arr",
"=",
"handleDeepProperty",
"(",
"obj",
",",
"leading",
",",
"any",
",",
"false",
",",
"set",
"?",
"true",
":",
"false",
",",
"true",
")",
";",
"}",
"else",
"{",
"arr",
"=",
"obj",
";",
"}",
"assertArray",
"(",
"arr",
")",
";",
"trailing",
"=",
"match",
"[",
"4",
"]",
";",
"start",
"=",
"match",
"[",
"2",
"]",
"?",
"+",
"match",
"[",
"2",
"]",
":",
"0",
";",
"end",
"=",
"match",
"[",
"3",
"]",
"?",
"+",
"match",
"[",
"3",
"]",
":",
"arr",
".",
"length",
";",
"// A range of 0..1 is inclusive, so we need to add 1 to the end. If this",
"// pushes the index from -1 to 0, then set it to the full length of the",
"// array, otherwise it will return nothing.",
"end",
"=",
"end",
"===",
"-",
"1",
"?",
"arr",
".",
"length",
":",
"end",
"+",
"1",
";",
"if",
"(",
"set",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"start",
";",
"i",
"<",
"end",
";",
"i",
"++",
")",
"{",
"handleDeepProperty",
"(",
"arr",
",",
"i",
"+",
"trailing",
",",
"any",
",",
"false",
",",
"true",
",",
"false",
",",
"val",
")",
";",
"}",
"}",
"else",
"{",
"arr",
"=",
"arr",
".",
"slice",
"(",
"start",
",",
"end",
")",
";",
"// If there are trailing properties, then they need to be mapped for each",
"// element in the array.",
"if",
"(",
"trailing",
")",
"{",
"if",
"(",
"trailing",
".",
"charAt",
"(",
"0",
")",
"===",
"HALF_WIDTH_PERIOD",
")",
"{",
"// Need to chomp the period if one is trailing after the range. We",
"// can't do this at the regex level because it will be required if",
"// we're setting the value as it needs to be concatentated together",
"// with the array index to be set.",
"trailing",
"=",
"trailing",
".",
"slice",
"(",
"1",
")",
";",
"}",
"return",
"map",
"(",
"arr",
",",
"function",
"(",
"el",
")",
"{",
"return",
"handleDeepProperty",
"(",
"el",
",",
"trailing",
")",
";",
"}",
")",
";",
"}",
"}",
"return",
"arr",
";",
"}"
] |
Get object property with support for 0..1 style range notation.
|
[
"Get",
"object",
"property",
"with",
"support",
"for",
"0",
"..",
"1",
"style",
"range",
"notation",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/common.js#L519-L569
|
13,014
|
andrewplummer/Sugar
|
lib/common.js
|
coercePrimitiveToObject
|
function coercePrimitiveToObject(obj) {
if (isPrimitive(obj)) {
obj = Object(obj);
}
// istanbul ignore next
if (NO_KEYS_IN_STRING_OBJECTS && isString(obj)) {
forceStringCoercion(obj);
}
return obj;
}
|
javascript
|
function coercePrimitiveToObject(obj) {
if (isPrimitive(obj)) {
obj = Object(obj);
}
// istanbul ignore next
if (NO_KEYS_IN_STRING_OBJECTS && isString(obj)) {
forceStringCoercion(obj);
}
return obj;
}
|
[
"function",
"coercePrimitiveToObject",
"(",
"obj",
")",
"{",
"if",
"(",
"isPrimitive",
"(",
"obj",
")",
")",
"{",
"obj",
"=",
"Object",
"(",
"obj",
")",
";",
"}",
"// istanbul ignore next",
"if",
"(",
"NO_KEYS_IN_STRING_OBJECTS",
"&&",
"isString",
"(",
"obj",
")",
")",
"{",
"forceStringCoercion",
"(",
"obj",
")",
";",
"}",
"return",
"obj",
";",
"}"
] |
Make primtives types like strings into objects.
|
[
"Make",
"primtives",
"types",
"like",
"strings",
"into",
"objects",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/common.js#L647-L656
|
13,015
|
andrewplummer/Sugar
|
lib/common.js
|
forceStringCoercion
|
function forceStringCoercion(obj) {
var i = 0, chr;
while (chr = obj.charAt(i)) {
obj[i++] = chr;
}
}
|
javascript
|
function forceStringCoercion(obj) {
var i = 0, chr;
while (chr = obj.charAt(i)) {
obj[i++] = chr;
}
}
|
[
"function",
"forceStringCoercion",
"(",
"obj",
")",
"{",
"var",
"i",
"=",
"0",
",",
"chr",
";",
"while",
"(",
"chr",
"=",
"obj",
".",
"charAt",
"(",
"i",
")",
")",
"{",
"obj",
"[",
"i",
"++",
"]",
"=",
"chr",
";",
"}",
"}"
] |
Force strings to have their indexes set in environments that don't do this automatically. istanbul ignore next
|
[
"Force",
"strings",
"to",
"have",
"their",
"indexes",
"set",
"in",
"environments",
"that",
"don",
"t",
"do",
"this",
"automatically",
".",
"istanbul",
"ignore",
"next"
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/common.js#L661-L666
|
13,016
|
andrewplummer/Sugar
|
lib/common.js
|
isEqual
|
function isEqual(a, b, stack) {
var aClass, bClass;
if (a === b) {
// Return quickly up front when matched by reference,
// but be careful about 0 !== -0.
return a !== 0 || 1 / a === 1 / b;
}
aClass = classToString(a);
bClass = classToString(b);
if (aClass !== bClass) {
return false;
}
if (isSerializable(a, aClass) && isSerializable(b, bClass)) {
return objectIsEqual(a, b, aClass, stack);
} else if (isSet(a, aClass) && isSet(b, bClass)) {
return a.size === b.size && isEqual(setToArray(a), setToArray(b), stack);
} else if (isMap(a, aClass) && isMap(b, bClass)) {
return a.size === b.size && isEqual(mapToArray(a), mapToArray(b), stack);
} else if (isError(a, aClass) && isError(b, bClass)) {
return a.toString() === b.toString();
}
return false;
}
|
javascript
|
function isEqual(a, b, stack) {
var aClass, bClass;
if (a === b) {
// Return quickly up front when matched by reference,
// but be careful about 0 !== -0.
return a !== 0 || 1 / a === 1 / b;
}
aClass = classToString(a);
bClass = classToString(b);
if (aClass !== bClass) {
return false;
}
if (isSerializable(a, aClass) && isSerializable(b, bClass)) {
return objectIsEqual(a, b, aClass, stack);
} else if (isSet(a, aClass) && isSet(b, bClass)) {
return a.size === b.size && isEqual(setToArray(a), setToArray(b), stack);
} else if (isMap(a, aClass) && isMap(b, bClass)) {
return a.size === b.size && isEqual(mapToArray(a), mapToArray(b), stack);
} else if (isError(a, aClass) && isError(b, bClass)) {
return a.toString() === b.toString();
}
return false;
}
|
[
"function",
"isEqual",
"(",
"a",
",",
"b",
",",
"stack",
")",
"{",
"var",
"aClass",
",",
"bClass",
";",
"if",
"(",
"a",
"===",
"b",
")",
"{",
"// Return quickly up front when matched by reference,",
"// but be careful about 0 !== -0.",
"return",
"a",
"!==",
"0",
"||",
"1",
"/",
"a",
"===",
"1",
"/",
"b",
";",
"}",
"aClass",
"=",
"classToString",
"(",
"a",
")",
";",
"bClass",
"=",
"classToString",
"(",
"b",
")",
";",
"if",
"(",
"aClass",
"!==",
"bClass",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"isSerializable",
"(",
"a",
",",
"aClass",
")",
"&&",
"isSerializable",
"(",
"b",
",",
"bClass",
")",
")",
"{",
"return",
"objectIsEqual",
"(",
"a",
",",
"b",
",",
"aClass",
",",
"stack",
")",
";",
"}",
"else",
"if",
"(",
"isSet",
"(",
"a",
",",
"aClass",
")",
"&&",
"isSet",
"(",
"b",
",",
"bClass",
")",
")",
"{",
"return",
"a",
".",
"size",
"===",
"b",
".",
"size",
"&&",
"isEqual",
"(",
"setToArray",
"(",
"a",
")",
",",
"setToArray",
"(",
"b",
")",
",",
"stack",
")",
";",
"}",
"else",
"if",
"(",
"isMap",
"(",
"a",
",",
"aClass",
")",
"&&",
"isMap",
"(",
"b",
",",
"bClass",
")",
")",
"{",
"return",
"a",
".",
"size",
"===",
"b",
".",
"size",
"&&",
"isEqual",
"(",
"mapToArray",
"(",
"a",
")",
",",
"mapToArray",
"(",
"b",
")",
",",
"stack",
")",
";",
"}",
"else",
"if",
"(",
"isError",
"(",
"a",
",",
"aClass",
")",
"&&",
"isError",
"(",
"b",
",",
"bClass",
")",
")",
"{",
"return",
"a",
".",
"toString",
"(",
")",
"===",
"b",
".",
"toString",
"(",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
Equality helpers Perf
|
[
"Equality",
"helpers",
"Perf"
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/common.js#L671-L695
|
13,017
|
andrewplummer/Sugar
|
lib/common.js
|
serializeInternal
|
function serializeInternal(obj, refs, stack) {
var type = typeof obj, sign = '', className, value, ref;
// Return up front on
if (1 / obj === -Infinity) {
sign = '-';
}
// Return quickly for primitives to save cycles
if (isPrimitive(obj, type) && !isRealNaN(obj)) {
return type + sign + obj;
}
className = classToString(obj);
if (!isSerializable(obj, className)) {
ref = indexOf(refs, obj);
if (ref === -1) {
ref = refs.length;
refs.push(obj);
}
return ref;
} else if (isObjectType(obj)) {
value = serializeDeep(obj, refs, stack) + obj.toString();
} else if (obj.valueOf) {
value = obj.valueOf();
}
return type + className + sign + value;
}
|
javascript
|
function serializeInternal(obj, refs, stack) {
var type = typeof obj, sign = '', className, value, ref;
// Return up front on
if (1 / obj === -Infinity) {
sign = '-';
}
// Return quickly for primitives to save cycles
if (isPrimitive(obj, type) && !isRealNaN(obj)) {
return type + sign + obj;
}
className = classToString(obj);
if (!isSerializable(obj, className)) {
ref = indexOf(refs, obj);
if (ref === -1) {
ref = refs.length;
refs.push(obj);
}
return ref;
} else if (isObjectType(obj)) {
value = serializeDeep(obj, refs, stack) + obj.toString();
} else if (obj.valueOf) {
value = obj.valueOf();
}
return type + className + sign + value;
}
|
[
"function",
"serializeInternal",
"(",
"obj",
",",
"refs",
",",
"stack",
")",
"{",
"var",
"type",
"=",
"typeof",
"obj",
",",
"sign",
"=",
"''",
",",
"className",
",",
"value",
",",
"ref",
";",
"// Return up front on",
"if",
"(",
"1",
"/",
"obj",
"===",
"-",
"Infinity",
")",
"{",
"sign",
"=",
"'-'",
";",
"}",
"// Return quickly for primitives to save cycles",
"if",
"(",
"isPrimitive",
"(",
"obj",
",",
"type",
")",
"&&",
"!",
"isRealNaN",
"(",
"obj",
")",
")",
"{",
"return",
"type",
"+",
"sign",
"+",
"obj",
";",
"}",
"className",
"=",
"classToString",
"(",
"obj",
")",
";",
"if",
"(",
"!",
"isSerializable",
"(",
"obj",
",",
"className",
")",
")",
"{",
"ref",
"=",
"indexOf",
"(",
"refs",
",",
"obj",
")",
";",
"if",
"(",
"ref",
"===",
"-",
"1",
")",
"{",
"ref",
"=",
"refs",
".",
"length",
";",
"refs",
".",
"push",
"(",
"obj",
")",
";",
"}",
"return",
"ref",
";",
"}",
"else",
"if",
"(",
"isObjectType",
"(",
"obj",
")",
")",
"{",
"value",
"=",
"serializeDeep",
"(",
"obj",
",",
"refs",
",",
"stack",
")",
"+",
"obj",
".",
"toString",
"(",
")",
";",
"}",
"else",
"if",
"(",
"obj",
".",
"valueOf",
")",
"{",
"value",
"=",
"obj",
".",
"valueOf",
"(",
")",
";",
"}",
"return",
"type",
"+",
"className",
"+",
"sign",
"+",
"value",
";",
"}"
] |
Serializes an object in a way that will provide a token unique to the type, class, and value of an object. Host objects, class instances etc, are not serializable, and are held in an array of references that will return the index as a unique identifier for the object. This array is passed from outside so that the calling function can decide when to dispose of this array.
|
[
"Serializes",
"an",
"object",
"in",
"a",
"way",
"that",
"will",
"provide",
"a",
"token",
"unique",
"to",
"the",
"type",
"class",
"and",
"value",
"of",
"an",
"object",
".",
"Host",
"objects",
"class",
"instances",
"etc",
"are",
"not",
"serializable",
"and",
"are",
"held",
"in",
"an",
"array",
"of",
"references",
"that",
"will",
"return",
"the",
"index",
"as",
"a",
"unique",
"identifier",
"for",
"the",
"object",
".",
"This",
"array",
"is",
"passed",
"from",
"outside",
"so",
"that",
"the",
"calling",
"function",
"can",
"decide",
"when",
"to",
"dispose",
"of",
"this",
"array",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/common.js#L731-L759
|
13,018
|
andrewplummer/Sugar
|
lib/common.js
|
stringToNumber
|
function stringToNumber(str, base) {
var sanitized, isDecimal;
sanitized = str.replace(fullWidthNumberReg, function(chr) {
var replacement = getOwn(fullWidthNumberMap, chr);
if (replacement === HALF_WIDTH_PERIOD) {
isDecimal = true;
}
return replacement;
});
return isDecimal ? parseFloat(sanitized) : parseInt(sanitized, base || 10);
}
|
javascript
|
function stringToNumber(str, base) {
var sanitized, isDecimal;
sanitized = str.replace(fullWidthNumberReg, function(chr) {
var replacement = getOwn(fullWidthNumberMap, chr);
if (replacement === HALF_WIDTH_PERIOD) {
isDecimal = true;
}
return replacement;
});
return isDecimal ? parseFloat(sanitized) : parseInt(sanitized, base || 10);
}
|
[
"function",
"stringToNumber",
"(",
"str",
",",
"base",
")",
"{",
"var",
"sanitized",
",",
"isDecimal",
";",
"sanitized",
"=",
"str",
".",
"replace",
"(",
"fullWidthNumberReg",
",",
"function",
"(",
"chr",
")",
"{",
"var",
"replacement",
"=",
"getOwn",
"(",
"fullWidthNumberMap",
",",
"chr",
")",
";",
"if",
"(",
"replacement",
"===",
"HALF_WIDTH_PERIOD",
")",
"{",
"isDecimal",
"=",
"true",
";",
"}",
"return",
"replacement",
";",
"}",
")",
";",
"return",
"isDecimal",
"?",
"parseFloat",
"(",
"sanitized",
")",
":",
"parseInt",
"(",
"sanitized",
",",
"base",
"||",
"10",
")",
";",
"}"
] |
Takes into account full-width characters, commas, and decimals.
|
[
"Takes",
"into",
"account",
"full",
"-",
"width",
"characters",
"commas",
"and",
"decimals",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/common.js#L1009-L1019
|
13,019
|
andrewplummer/Sugar
|
lib/es5.js
|
defineNativeMethodsOnChainable
|
function defineNativeMethodsOnChainable() {
var nativeTokens = {
'Function': 'apply,call',
'RegExp': 'compile,exec,test',
'Number': 'toExponential,toFixed,toLocaleString,toPrecision',
'Object': 'hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString',
'Array': 'concat,join,pop,push,reverse,shift,slice,sort,splice,toLocaleString,unshift',
'Date': 'getTime,getTimezoneOffset,setTime,toDateString,toGMTString,toLocaleDateString,toLocaleString,toLocaleTimeString,toTimeString,toUTCString',
'String': 'anchor,big,blink,bold,charAt,charCodeAt,concat,fixed,fontcolor,fontsize,indexOf,italics,lastIndexOf,link,localeCompare,match,replace,search,slice,small,split,strike,sub,substr,substring,sup,toLocaleLowerCase,toLocaleUpperCase,toLowerCase,toUpperCase'
};
var dateTokens = 'FullYear,Month,Date,Hours,Minutes,Seconds,Milliseconds'.split(',');
function addDateTokens(prefix, arr) {
for (var i = 0; i < dateTokens.length; i++) {
arr.push(prefix + dateTokens[i]);
}
}
forEachProperty(nativeTokens, function(str, name) {
var tokens = str.split(',');
if (name === 'Date') {
addDateTokens('get', tokens);
addDateTokens('set', tokens);
addDateTokens('getUTC', tokens);
addDateTokens('setUTC', tokens);
}
tokens.push('toString');
mapNativeToChainable(name, tokens);
});
}
|
javascript
|
function defineNativeMethodsOnChainable() {
var nativeTokens = {
'Function': 'apply,call',
'RegExp': 'compile,exec,test',
'Number': 'toExponential,toFixed,toLocaleString,toPrecision',
'Object': 'hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString',
'Array': 'concat,join,pop,push,reverse,shift,slice,sort,splice,toLocaleString,unshift',
'Date': 'getTime,getTimezoneOffset,setTime,toDateString,toGMTString,toLocaleDateString,toLocaleString,toLocaleTimeString,toTimeString,toUTCString',
'String': 'anchor,big,blink,bold,charAt,charCodeAt,concat,fixed,fontcolor,fontsize,indexOf,italics,lastIndexOf,link,localeCompare,match,replace,search,slice,small,split,strike,sub,substr,substring,sup,toLocaleLowerCase,toLocaleUpperCase,toLowerCase,toUpperCase'
};
var dateTokens = 'FullYear,Month,Date,Hours,Minutes,Seconds,Milliseconds'.split(',');
function addDateTokens(prefix, arr) {
for (var i = 0; i < dateTokens.length; i++) {
arr.push(prefix + dateTokens[i]);
}
}
forEachProperty(nativeTokens, function(str, name) {
var tokens = str.split(',');
if (name === 'Date') {
addDateTokens('get', tokens);
addDateTokens('set', tokens);
addDateTokens('getUTC', tokens);
addDateTokens('setUTC', tokens);
}
tokens.push('toString');
mapNativeToChainable(name, tokens);
});
}
|
[
"function",
"defineNativeMethodsOnChainable",
"(",
")",
"{",
"var",
"nativeTokens",
"=",
"{",
"'Function'",
":",
"'apply,call'",
",",
"'RegExp'",
":",
"'compile,exec,test'",
",",
"'Number'",
":",
"'toExponential,toFixed,toLocaleString,toPrecision'",
",",
"'Object'",
":",
"'hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString'",
",",
"'Array'",
":",
"'concat,join,pop,push,reverse,shift,slice,sort,splice,toLocaleString,unshift'",
",",
"'Date'",
":",
"'getTime,getTimezoneOffset,setTime,toDateString,toGMTString,toLocaleDateString,toLocaleString,toLocaleTimeString,toTimeString,toUTCString'",
",",
"'String'",
":",
"'anchor,big,blink,bold,charAt,charCodeAt,concat,fixed,fontcolor,fontsize,indexOf,italics,lastIndexOf,link,localeCompare,match,replace,search,slice,small,split,strike,sub,substr,substring,sup,toLocaleLowerCase,toLocaleUpperCase,toLowerCase,toUpperCase'",
"}",
";",
"var",
"dateTokens",
"=",
"'FullYear,Month,Date,Hours,Minutes,Seconds,Milliseconds'",
".",
"split",
"(",
"','",
")",
";",
"function",
"addDateTokens",
"(",
"prefix",
",",
"arr",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"dateTokens",
".",
"length",
";",
"i",
"++",
")",
"{",
"arr",
".",
"push",
"(",
"prefix",
"+",
"dateTokens",
"[",
"i",
"]",
")",
";",
"}",
"}",
"forEachProperty",
"(",
"nativeTokens",
",",
"function",
"(",
"str",
",",
"name",
")",
"{",
"var",
"tokens",
"=",
"str",
".",
"split",
"(",
"','",
")",
";",
"if",
"(",
"name",
"===",
"'Date'",
")",
"{",
"addDateTokens",
"(",
"'get'",
",",
"tokens",
")",
";",
"addDateTokens",
"(",
"'set'",
",",
"tokens",
")",
";",
"addDateTokens",
"(",
"'getUTC'",
",",
"tokens",
")",
";",
"addDateTokens",
"(",
"'setUTC'",
",",
"tokens",
")",
";",
"}",
"tokens",
".",
"push",
"(",
"'toString'",
")",
";",
"mapNativeToChainable",
"(",
"name",
",",
"tokens",
")",
";",
"}",
")",
";",
"}"
] |
Polyfilled methods will automatically be added to the chainable prototype. However, Object.getOwnPropertyNames cannot be shimmed for non-enumerable properties, so if it does not exist, then the only way to access native methods previous to ES5 is to provide them as a list of tokens here.
|
[
"Polyfilled",
"methods",
"will",
"automatically",
"be",
"added",
"to",
"the",
"chainable",
"prototype",
".",
"However",
"Object",
".",
"getOwnPropertyNames",
"cannot",
"be",
"shimmed",
"for",
"non",
"-",
"enumerable",
"properties",
"so",
"if",
"it",
"does",
"not",
"exist",
"then",
"the",
"only",
"way",
"to",
"access",
"native",
"methods",
"previous",
"to",
"ES5",
"is",
"to",
"provide",
"them",
"as",
"a",
"list",
"of",
"tokens",
"here",
"."
] |
4adba2e6ef8c8734a693af3141461dec6d674d50
|
https://github.com/andrewplummer/Sugar/blob/4adba2e6ef8c8734a693af3141461dec6d674d50/lib/es5.js#L55-L87
|
13,020
|
kentcdodds/nps
|
src/bin-utils/parser.js
|
showHelp
|
function showHelp(specifiedScripts) {
if (parsedArgv.help) {
// if --help was specified, then yargs will show the default help
log.info(help(psConfig))
return true
}
const helpStyle = String(psConfig.options['help-style'])
const hasDefaultScript = Boolean(psConfig.scripts.default)
const noScriptSpecifiedAndNoDefault =
!specifiedScripts.length && !hasDefaultScript
const hasHelpScript = Boolean(psConfig.scripts.help)
const commandIsHelp =
isEqual(specifiedScripts[0], 'help') && !hasHelpScript
const shouldShowSpecificScriptHelp =
commandIsHelp && specifiedScripts.length > 1
if (shouldShowSpecificScriptHelp) {
log.info(specificHelpScript(psConfig, specifiedScripts[1]))
return true
} else if (commandIsHelp || noScriptSpecifiedAndNoDefault) {
// Can't achieve 100% branch coverage without refactoring this showHelp()
// function into ./index.js and re-working existing tests and such. Branch
// options aren't relevant here either, so telling Istanbul to ignore.
/* istanbul ignore next */
if (helpStyle === 'all') {
parser.showHelp('log')
}
log.info(help(psConfig))
return true
}
return false
}
|
javascript
|
function showHelp(specifiedScripts) {
if (parsedArgv.help) {
// if --help was specified, then yargs will show the default help
log.info(help(psConfig))
return true
}
const helpStyle = String(psConfig.options['help-style'])
const hasDefaultScript = Boolean(psConfig.scripts.default)
const noScriptSpecifiedAndNoDefault =
!specifiedScripts.length && !hasDefaultScript
const hasHelpScript = Boolean(psConfig.scripts.help)
const commandIsHelp =
isEqual(specifiedScripts[0], 'help') && !hasHelpScript
const shouldShowSpecificScriptHelp =
commandIsHelp && specifiedScripts.length > 1
if (shouldShowSpecificScriptHelp) {
log.info(specificHelpScript(psConfig, specifiedScripts[1]))
return true
} else if (commandIsHelp || noScriptSpecifiedAndNoDefault) {
// Can't achieve 100% branch coverage without refactoring this showHelp()
// function into ./index.js and re-working existing tests and such. Branch
// options aren't relevant here either, so telling Istanbul to ignore.
/* istanbul ignore next */
if (helpStyle === 'all') {
parser.showHelp('log')
}
log.info(help(psConfig))
return true
}
return false
}
|
[
"function",
"showHelp",
"(",
"specifiedScripts",
")",
"{",
"if",
"(",
"parsedArgv",
".",
"help",
")",
"{",
"// if --help was specified, then yargs will show the default help",
"log",
".",
"info",
"(",
"help",
"(",
"psConfig",
")",
")",
"return",
"true",
"}",
"const",
"helpStyle",
"=",
"String",
"(",
"psConfig",
".",
"options",
"[",
"'help-style'",
"]",
")",
"const",
"hasDefaultScript",
"=",
"Boolean",
"(",
"psConfig",
".",
"scripts",
".",
"default",
")",
"const",
"noScriptSpecifiedAndNoDefault",
"=",
"!",
"specifiedScripts",
".",
"length",
"&&",
"!",
"hasDefaultScript",
"const",
"hasHelpScript",
"=",
"Boolean",
"(",
"psConfig",
".",
"scripts",
".",
"help",
")",
"const",
"commandIsHelp",
"=",
"isEqual",
"(",
"specifiedScripts",
"[",
"0",
"]",
",",
"'help'",
")",
"&&",
"!",
"hasHelpScript",
"const",
"shouldShowSpecificScriptHelp",
"=",
"commandIsHelp",
"&&",
"specifiedScripts",
".",
"length",
">",
"1",
"if",
"(",
"shouldShowSpecificScriptHelp",
")",
"{",
"log",
".",
"info",
"(",
"specificHelpScript",
"(",
"psConfig",
",",
"specifiedScripts",
"[",
"1",
"]",
")",
")",
"return",
"true",
"}",
"else",
"if",
"(",
"commandIsHelp",
"||",
"noScriptSpecifiedAndNoDefault",
")",
"{",
"// Can't achieve 100% branch coverage without refactoring this showHelp()",
"// function into ./index.js and re-working existing tests and such. Branch",
"// options aren't relevant here either, so telling Istanbul to ignore.",
"/* istanbul ignore next */",
"if",
"(",
"helpStyle",
"===",
"'all'",
")",
"{",
"parser",
".",
"showHelp",
"(",
"'log'",
")",
"}",
"log",
".",
"info",
"(",
"help",
"(",
"psConfig",
")",
")",
"return",
"true",
"}",
"return",
"false",
"}"
] |
util functions eslint-disable-next-line complexity
|
[
"util",
"functions",
"eslint",
"-",
"disable",
"-",
"next",
"-",
"line",
"complexity"
] |
a0c961a2986ebb89d41bcd0f0dd54cada986cd2e
|
https://github.com/kentcdodds/nps/blob/a0c961a2986ebb89d41bcd0f0dd54cada986cd2e/src/bin-utils/parser.js#L121-L152
|
13,021
|
kentcdodds/nps
|
src/bin-utils/initialize/stringify-object.js
|
stringifyObject
|
function stringifyObject(object, indent) {
return Object.keys(object).reduce((string, key, index) => {
const script = object[key]
let value
if (isPlainObject(script)) {
value = `{${stringifyObject(script, `${indent} `)}\n${indent}}`
} else {
value = `'${escapeSingleQuote(script)}'`
}
const comma = getComma(isLast(object, index))
return `${string}\n${indent}${key}: ${value}${comma}`
}, '')
}
|
javascript
|
function stringifyObject(object, indent) {
return Object.keys(object).reduce((string, key, index) => {
const script = object[key]
let value
if (isPlainObject(script)) {
value = `{${stringifyObject(script, `${indent} `)}\n${indent}}`
} else {
value = `'${escapeSingleQuote(script)}'`
}
const comma = getComma(isLast(object, index))
return `${string}\n${indent}${key}: ${value}${comma}`
}, '')
}
|
[
"function",
"stringifyObject",
"(",
"object",
",",
"indent",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"object",
")",
".",
"reduce",
"(",
"(",
"string",
",",
"key",
",",
"index",
")",
"=>",
"{",
"const",
"script",
"=",
"object",
"[",
"key",
"]",
"let",
"value",
"if",
"(",
"isPlainObject",
"(",
"script",
")",
")",
"{",
"value",
"=",
"`",
"${",
"stringifyObject",
"(",
"script",
",",
"`",
"${",
"indent",
"}",
"`",
")",
"}",
"\\n",
"${",
"indent",
"}",
"`",
"}",
"else",
"{",
"value",
"=",
"`",
"${",
"escapeSingleQuote",
"(",
"script",
")",
"}",
"`",
"}",
"const",
"comma",
"=",
"getComma",
"(",
"isLast",
"(",
"object",
",",
"index",
")",
")",
"return",
"`",
"${",
"string",
"}",
"\\n",
"${",
"indent",
"}",
"${",
"key",
"}",
"${",
"value",
"}",
"${",
"comma",
"}",
"`",
"}",
",",
"''",
")",
"}"
] |
Converts given object to its string representation.
Every line is preceded by given indent.
@param {object} object "Object to convert"
@param {string} indent "Indent to use"
@returns {string} "Stringified and indented object"
|
[
"Converts",
"given",
"object",
"to",
"its",
"string",
"representation",
".",
"Every",
"line",
"is",
"preceded",
"by",
"given",
"indent",
"."
] |
a0c961a2986ebb89d41bcd0f0dd54cada986cd2e
|
https://github.com/kentcdodds/nps/blob/a0c961a2986ebb89d41bcd0f0dd54cada986cd2e/src/bin-utils/initialize/stringify-object.js#L11-L23
|
13,022
|
kentcdodds/nps
|
src/bin-utils/index.js
|
loadConfig
|
function loadConfig(configPath, input) {
let config
if (configPath.endsWith('.yml') || configPath.endsWith('.yaml')) {
config = loadYAMLConfig(configPath)
} else {
config = loadJSConfig(configPath)
}
if (isUndefined(config)) {
// let the caller deal with this
return config
}
let typeMessage = `Your config data type was`
if (isFunction(config)) {
config = config(input)
typeMessage = `${typeMessage} a function which returned`
}
const emptyConfig = isEmpty(config)
const plainObjectConfig = isPlainObject(config)
if (plainObjectConfig && emptyConfig) {
typeMessage = `${typeMessage} an object, but it was empty`
} else {
typeMessage = `${typeMessage} a data type of "${typeOf(config)}"`
}
if (!plainObjectConfig || emptyConfig) {
log.error({
message: chalk.red(
oneLine`
The package-scripts configuration
("${configPath.replace(/\\/g, '/')}") must be a non-empty object
or a function that returns a non-empty object.
`,
),
ref: 'config-must-be-an-object',
})
throw new Error(typeMessage)
}
const defaultConfig = {
options: {
'help-style': 'all',
},
}
return {...defaultConfig, ...config}
}
|
javascript
|
function loadConfig(configPath, input) {
let config
if (configPath.endsWith('.yml') || configPath.endsWith('.yaml')) {
config = loadYAMLConfig(configPath)
} else {
config = loadJSConfig(configPath)
}
if (isUndefined(config)) {
// let the caller deal with this
return config
}
let typeMessage = `Your config data type was`
if (isFunction(config)) {
config = config(input)
typeMessage = `${typeMessage} a function which returned`
}
const emptyConfig = isEmpty(config)
const plainObjectConfig = isPlainObject(config)
if (plainObjectConfig && emptyConfig) {
typeMessage = `${typeMessage} an object, but it was empty`
} else {
typeMessage = `${typeMessage} a data type of "${typeOf(config)}"`
}
if (!plainObjectConfig || emptyConfig) {
log.error({
message: chalk.red(
oneLine`
The package-scripts configuration
("${configPath.replace(/\\/g, '/')}") must be a non-empty object
or a function that returns a non-empty object.
`,
),
ref: 'config-must-be-an-object',
})
throw new Error(typeMessage)
}
const defaultConfig = {
options: {
'help-style': 'all',
},
}
return {...defaultConfig, ...config}
}
|
[
"function",
"loadConfig",
"(",
"configPath",
",",
"input",
")",
"{",
"let",
"config",
"if",
"(",
"configPath",
".",
"endsWith",
"(",
"'.yml'",
")",
"||",
"configPath",
".",
"endsWith",
"(",
"'.yaml'",
")",
")",
"{",
"config",
"=",
"loadYAMLConfig",
"(",
"configPath",
")",
"}",
"else",
"{",
"config",
"=",
"loadJSConfig",
"(",
"configPath",
")",
"}",
"if",
"(",
"isUndefined",
"(",
"config",
")",
")",
"{",
"// let the caller deal with this",
"return",
"config",
"}",
"let",
"typeMessage",
"=",
"`",
"`",
"if",
"(",
"isFunction",
"(",
"config",
")",
")",
"{",
"config",
"=",
"config",
"(",
"input",
")",
"typeMessage",
"=",
"`",
"${",
"typeMessage",
"}",
"`",
"}",
"const",
"emptyConfig",
"=",
"isEmpty",
"(",
"config",
")",
"const",
"plainObjectConfig",
"=",
"isPlainObject",
"(",
"config",
")",
"if",
"(",
"plainObjectConfig",
"&&",
"emptyConfig",
")",
"{",
"typeMessage",
"=",
"`",
"${",
"typeMessage",
"}",
"`",
"}",
"else",
"{",
"typeMessage",
"=",
"`",
"${",
"typeMessage",
"}",
"${",
"typeOf",
"(",
"config",
")",
"}",
"`",
"}",
"if",
"(",
"!",
"plainObjectConfig",
"||",
"emptyConfig",
")",
"{",
"log",
".",
"error",
"(",
"{",
"message",
":",
"chalk",
".",
"red",
"(",
"oneLine",
"`",
"${",
"configPath",
".",
"replace",
"(",
"/",
"\\\\",
"/",
"g",
",",
"'/'",
")",
"}",
"`",
",",
")",
",",
"ref",
":",
"'config-must-be-an-object'",
",",
"}",
")",
"throw",
"new",
"Error",
"(",
"typeMessage",
")",
"}",
"const",
"defaultConfig",
"=",
"{",
"options",
":",
"{",
"'help-style'",
":",
"'all'",
",",
"}",
",",
"}",
"return",
"{",
"...",
"defaultConfig",
",",
"...",
"config",
"}",
"}"
] |
Attempts to load the config and logs an error if there's a problem
@param {String} configPath The path to attempt to require the config from
@param {*} input the input to pass to the config if it's a function
@return {Object} The config
eslint-disable-next-line complexity
|
[
"Attempts",
"to",
"load",
"the",
"config",
"and",
"logs",
"an",
"error",
"if",
"there",
"s",
"a",
"problem"
] |
a0c961a2986ebb89d41bcd0f0dd54cada986cd2e
|
https://github.com/kentcdodds/nps/blob/a0c961a2986ebb89d41bcd0f0dd54cada986cd2e/src/bin-utils/index.js#L67-L112
|
13,023
|
jshttp/mime-db
|
scripts/build.js
|
addData
|
function addData (db, mime, source) {
Object.keys(mime).forEach(function (key) {
var data = mime[key]
var type = key.toLowerCase()
var obj = db[type] = db[type] || createTypeEntry(source)
// add missing data
setValue(obj, 'charset', data.charset)
setValue(obj, 'compressible', data.compressible)
// append new extensions
appendExtensions(obj, data.extensions)
})
}
|
javascript
|
function addData (db, mime, source) {
Object.keys(mime).forEach(function (key) {
var data = mime[key]
var type = key.toLowerCase()
var obj = db[type] = db[type] || createTypeEntry(source)
// add missing data
setValue(obj, 'charset', data.charset)
setValue(obj, 'compressible', data.compressible)
// append new extensions
appendExtensions(obj, data.extensions)
})
}
|
[
"function",
"addData",
"(",
"db",
",",
"mime",
",",
"source",
")",
"{",
"Object",
".",
"keys",
"(",
"mime",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"var",
"data",
"=",
"mime",
"[",
"key",
"]",
"var",
"type",
"=",
"key",
".",
"toLowerCase",
"(",
")",
"var",
"obj",
"=",
"db",
"[",
"type",
"]",
"=",
"db",
"[",
"type",
"]",
"||",
"createTypeEntry",
"(",
"source",
")",
"// add missing data",
"setValue",
"(",
"obj",
",",
"'charset'",
",",
"data",
".",
"charset",
")",
"setValue",
"(",
"obj",
",",
"'compressible'",
",",
"data",
".",
"compressible",
")",
"// append new extensions",
"appendExtensions",
"(",
"obj",
",",
"data",
".",
"extensions",
")",
"}",
")",
"}"
] |
Add mime data to the db, marked as a given source.
|
[
"Add",
"mime",
"data",
"to",
"the",
"db",
"marked",
"as",
"a",
"given",
"source",
"."
] |
4db92114124a76a38bf29b7d572d4c7da33a1261
|
https://github.com/jshttp/mime-db/blob/4db92114124a76a38bf29b7d572d4c7da33a1261/scripts/build.js#L37-L50
|
13,024
|
jshttp/mime-db
|
scripts/build.js
|
appendExtension
|
function appendExtension (obj, extension) {
if (!obj.extensions) {
obj.extensions = []
}
if (obj.extensions.indexOf(extension) === -1) {
obj.extensions.push(extension)
}
}
|
javascript
|
function appendExtension (obj, extension) {
if (!obj.extensions) {
obj.extensions = []
}
if (obj.extensions.indexOf(extension) === -1) {
obj.extensions.push(extension)
}
}
|
[
"function",
"appendExtension",
"(",
"obj",
",",
"extension",
")",
"{",
"if",
"(",
"!",
"obj",
".",
"extensions",
")",
"{",
"obj",
".",
"extensions",
"=",
"[",
"]",
"}",
"if",
"(",
"obj",
".",
"extensions",
".",
"indexOf",
"(",
"extension",
")",
"===",
"-",
"1",
")",
"{",
"obj",
".",
"extensions",
".",
"push",
"(",
"extension",
")",
"}",
"}"
] |
Append an extension to an object.
|
[
"Append",
"an",
"extension",
"to",
"an",
"object",
"."
] |
4db92114124a76a38bf29b7d572d4c7da33a1261
|
https://github.com/jshttp/mime-db/blob/4db92114124a76a38bf29b7d572d4c7da33a1261/scripts/build.js#L55-L63
|
13,025
|
jshttp/mime-db
|
scripts/build.js
|
appendExtensions
|
function appendExtensions (obj, extensions) {
if (!extensions) {
return
}
for (var i = 0; i < extensions.length; i++) {
var extension = extensions[i]
// add extension to the type entry
appendExtension(obj, extension)
}
}
|
javascript
|
function appendExtensions (obj, extensions) {
if (!extensions) {
return
}
for (var i = 0; i < extensions.length; i++) {
var extension = extensions[i]
// add extension to the type entry
appendExtension(obj, extension)
}
}
|
[
"function",
"appendExtensions",
"(",
"obj",
",",
"extensions",
")",
"{",
"if",
"(",
"!",
"extensions",
")",
"{",
"return",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"extensions",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"extension",
"=",
"extensions",
"[",
"i",
"]",
"// add extension to the type entry",
"appendExtension",
"(",
"obj",
",",
"extension",
")",
"}",
"}"
] |
Append extensions to an object.
|
[
"Append",
"extensions",
"to",
"an",
"object",
"."
] |
4db92114124a76a38bf29b7d572d4c7da33a1261
|
https://github.com/jshttp/mime-db/blob/4db92114124a76a38bf29b7d572d4c7da33a1261/scripts/build.js#L68-L79
|
13,026
|
jshttp/mime-db
|
scripts/build.js
|
setValue
|
function setValue (obj, prop, value) {
if (value !== undefined && obj[prop] === undefined) {
obj[prop] = value
}
}
|
javascript
|
function setValue (obj, prop, value) {
if (value !== undefined && obj[prop] === undefined) {
obj[prop] = value
}
}
|
[
"function",
"setValue",
"(",
"obj",
",",
"prop",
",",
"value",
")",
"{",
"if",
"(",
"value",
"!==",
"undefined",
"&&",
"obj",
"[",
"prop",
"]",
"===",
"undefined",
")",
"{",
"obj",
"[",
"prop",
"]",
"=",
"value",
"}",
"}"
] |
Set a value on an object, if not already set.
|
[
"Set",
"a",
"value",
"on",
"an",
"object",
"if",
"not",
"already",
"set",
"."
] |
4db92114124a76a38bf29b7d572d4c7da33a1261
|
https://github.com/jshttp/mime-db/blob/4db92114124a76a38bf29b7d572d4c7da33a1261/scripts/build.js#L97-L101
|
13,027
|
jshttp/mime-db
|
scripts/fetch-apache.js
|
get
|
function get (url, callback) {
https.get(url, function onResponse (res) {
if (res.statusCode !== 200) {
callback(new Error('got status code ' + res.statusCode + ' from ' + URL))
} else {
getBody(res, true, callback)
}
})
}
|
javascript
|
function get (url, callback) {
https.get(url, function onResponse (res) {
if (res.statusCode !== 200) {
callback(new Error('got status code ' + res.statusCode + ' from ' + URL))
} else {
getBody(res, true, callback)
}
})
}
|
[
"function",
"get",
"(",
"url",
",",
"callback",
")",
"{",
"https",
".",
"get",
"(",
"url",
",",
"function",
"onResponse",
"(",
"res",
")",
"{",
"if",
"(",
"res",
".",
"statusCode",
"!==",
"200",
")",
"{",
"callback",
"(",
"new",
"Error",
"(",
"'got status code '",
"+",
"res",
".",
"statusCode",
"+",
"' from '",
"+",
"URL",
")",
")",
"}",
"else",
"{",
"getBody",
"(",
"res",
",",
"true",
",",
"callback",
")",
"}",
"}",
")",
"}"
] |
Get HTTPS resource.
|
[
"Get",
"HTTPS",
"resource",
"."
] |
4db92114124a76a38bf29b7d572d4c7da33a1261
|
https://github.com/jshttp/mime-db/blob/4db92114124a76a38bf29b7d572d4c7da33a1261/scripts/fetch-apache.js#L88-L96
|
13,028
|
allenhwkim/angularjs-google-maps
|
directives/heatmap-layer.js
|
parseScope
|
function parseScope( path, obj ) {
return path.split('.').reduce( function( prev, curr ) {
return prev[curr];
}, obj || this );
}
|
javascript
|
function parseScope( path, obj ) {
return path.split('.').reduce( function( prev, curr ) {
return prev[curr];
}, obj || this );
}
|
[
"function",
"parseScope",
"(",
"path",
",",
"obj",
")",
"{",
"return",
"path",
".",
"split",
"(",
"'.'",
")",
".",
"reduce",
"(",
"function",
"(",
"prev",
",",
"curr",
")",
"{",
"return",
"prev",
"[",
"curr",
"]",
";",
"}",
",",
"obj",
"||",
"this",
")",
";",
"}"
] |
helper get nexted path
|
[
"helper",
"get",
"nexted",
"path"
] |
8d485a6b3e0b94fa7c78fce9d5b3f101ccd6149c
|
https://github.com/allenhwkim/angularjs-google-maps/blob/8d485a6b3e0b94fa7c78fce9d5b3f101ccd6149c/directives/heatmap-layer.js#L51-L55
|
13,029
|
allenhwkim/angularjs-google-maps
|
build/scripts/ng-map.debug.js
|
function(el) {
(el.length > 0) && (el = el[0]);
var orgAttributes = {};
for (var i=0; i<el.attributes.length; i++) {
var attr = el.attributes[i];
orgAttributes[attr.name] = attr.value;
}
return orgAttributes;
}
|
javascript
|
function(el) {
(el.length > 0) && (el = el[0]);
var orgAttributes = {};
for (var i=0; i<el.attributes.length; i++) {
var attr = el.attributes[i];
orgAttributes[attr.name] = attr.value;
}
return orgAttributes;
}
|
[
"function",
"(",
"el",
")",
"{",
"(",
"el",
".",
"length",
">",
"0",
")",
"&&",
"(",
"el",
"=",
"el",
"[",
"0",
"]",
")",
";",
"var",
"orgAttributes",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"el",
".",
"attributes",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"attr",
"=",
"el",
".",
"attributes",
"[",
"i",
"]",
";",
"orgAttributes",
"[",
"attr",
".",
"name",
"]",
"=",
"attr",
".",
"value",
";",
"}",
"return",
"orgAttributes",
";",
"}"
] |
Returns the attributes of an element as hash
@memberof Attr2MapOptions
@param {HTMLElement} el html element
@returns {Hash} attributes
|
[
"Returns",
"the",
"attributes",
"of",
"an",
"element",
"as",
"hash"
] |
8d485a6b3e0b94fa7c78fce9d5b3f101ccd6149c
|
https://github.com/allenhwkim/angularjs-google-maps/blob/8d485a6b3e0b94fa7c78fce9d5b3f101ccd6149c/build/scripts/ng-map.debug.js#L2519-L2527
|
|
13,030
|
allenhwkim/angularjs-google-maps
|
build/scripts/ng-map.debug.js
|
function(scope, attrs) {
var events = {};
var toLowercaseFunc = function($1){
return "_"+$1.toLowerCase();
};
var EventFunc = function(attrValue) {
// funcName(argsStr)
var matches = attrValue.match(/([^\(]+)\(([^\)]*)\)/);
var funcName = matches[1];
var argsStr = matches[2].replace(/event[ ,]*/,''); //remove string 'event'
var argsExpr = $parse("["+argsStr+"]"); //for perf when triggering event
return function(event) {
var args = argsExpr(scope); //get args here to pass updated model values
function index(obj,i) {return obj[i];}
var f = funcName.split('.').reduce(index, scope);
f && f.apply(this, [event].concat(args));
$timeout( function() {
scope.$apply();
});
};
};
for(var key in attrs) {
if (attrs[key]) {
if (!key.match(/^on[A-Z]/)) { //skip if not events
continue;
}
//get event name as underscored. i.e. zoom_changed
var eventName = key.replace(/^on/,'');
eventName = eventName.charAt(0).toLowerCase() + eventName.slice(1);
eventName = eventName.replace(/([A-Z])/g, toLowercaseFunc);
var attrValue = attrs[key];
events[eventName] = new EventFunc(attrValue);
}
}
return events;
}
|
javascript
|
function(scope, attrs) {
var events = {};
var toLowercaseFunc = function($1){
return "_"+$1.toLowerCase();
};
var EventFunc = function(attrValue) {
// funcName(argsStr)
var matches = attrValue.match(/([^\(]+)\(([^\)]*)\)/);
var funcName = matches[1];
var argsStr = matches[2].replace(/event[ ,]*/,''); //remove string 'event'
var argsExpr = $parse("["+argsStr+"]"); //for perf when triggering event
return function(event) {
var args = argsExpr(scope); //get args here to pass updated model values
function index(obj,i) {return obj[i];}
var f = funcName.split('.').reduce(index, scope);
f && f.apply(this, [event].concat(args));
$timeout( function() {
scope.$apply();
});
};
};
for(var key in attrs) {
if (attrs[key]) {
if (!key.match(/^on[A-Z]/)) { //skip if not events
continue;
}
//get event name as underscored. i.e. zoom_changed
var eventName = key.replace(/^on/,'');
eventName = eventName.charAt(0).toLowerCase() + eventName.slice(1);
eventName = eventName.replace(/([A-Z])/g, toLowercaseFunc);
var attrValue = attrs[key];
events[eventName] = new EventFunc(attrValue);
}
}
return events;
}
|
[
"function",
"(",
"scope",
",",
"attrs",
")",
"{",
"var",
"events",
"=",
"{",
"}",
";",
"var",
"toLowercaseFunc",
"=",
"function",
"(",
"$1",
")",
"{",
"return",
"\"_\"",
"+",
"$1",
".",
"toLowerCase",
"(",
")",
";",
"}",
";",
"var",
"EventFunc",
"=",
"function",
"(",
"attrValue",
")",
"{",
"// funcName(argsStr)",
"var",
"matches",
"=",
"attrValue",
".",
"match",
"(",
"/",
"([^\\(]+)\\(([^\\)]*)\\)",
"/",
")",
";",
"var",
"funcName",
"=",
"matches",
"[",
"1",
"]",
";",
"var",
"argsStr",
"=",
"matches",
"[",
"2",
"]",
".",
"replace",
"(",
"/",
"event[ ,]*",
"/",
",",
"''",
")",
";",
"//remove string 'event'",
"var",
"argsExpr",
"=",
"$parse",
"(",
"\"[\"",
"+",
"argsStr",
"+",
"\"]\"",
")",
";",
"//for perf when triggering event",
"return",
"function",
"(",
"event",
")",
"{",
"var",
"args",
"=",
"argsExpr",
"(",
"scope",
")",
";",
"//get args here to pass updated model values",
"function",
"index",
"(",
"obj",
",",
"i",
")",
"{",
"return",
"obj",
"[",
"i",
"]",
";",
"}",
"var",
"f",
"=",
"funcName",
".",
"split",
"(",
"'.'",
")",
".",
"reduce",
"(",
"index",
",",
"scope",
")",
";",
"f",
"&&",
"f",
".",
"apply",
"(",
"this",
",",
"[",
"event",
"]",
".",
"concat",
"(",
"args",
")",
")",
";",
"$timeout",
"(",
"function",
"(",
")",
"{",
"scope",
".",
"$apply",
"(",
")",
";",
"}",
")",
";",
"}",
";",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"attrs",
")",
"{",
"if",
"(",
"attrs",
"[",
"key",
"]",
")",
"{",
"if",
"(",
"!",
"key",
".",
"match",
"(",
"/",
"^on[A-Z]",
"/",
")",
")",
"{",
"//skip if not events",
"continue",
";",
"}",
"//get event name as underscored. i.e. zoom_changed",
"var",
"eventName",
"=",
"key",
".",
"replace",
"(",
"/",
"^on",
"/",
",",
"''",
")",
";",
"eventName",
"=",
"eventName",
".",
"charAt",
"(",
"0",
")",
".",
"toLowerCase",
"(",
")",
"+",
"eventName",
".",
"slice",
"(",
"1",
")",
";",
"eventName",
"=",
"eventName",
".",
"replace",
"(",
"/",
"([A-Z])",
"/",
"g",
",",
"toLowercaseFunc",
")",
";",
"var",
"attrValue",
"=",
"attrs",
"[",
"key",
"]",
";",
"events",
"[",
"eventName",
"]",
"=",
"new",
"EventFunc",
"(",
"attrValue",
")",
";",
"}",
"}",
"return",
"events",
";",
"}"
] |
converts attributes hash to scope-specific event function
@memberof Attr2MapOptions
@param {scope} scope angularjs scope
@param {Hash} attrs tag attributes
@returns {Hash} events converted events
|
[
"converts",
"attributes",
"hash",
"to",
"scope",
"-",
"specific",
"event",
"function"
] |
8d485a6b3e0b94fa7c78fce9d5b3f101ccd6149c
|
https://github.com/allenhwkim/angularjs-google-maps/blob/8d485a6b3e0b94fa7c78fce9d5b3f101ccd6149c/build/scripts/ng-map.debug.js#L2767-L2805
|
|
13,031
|
allenhwkim/angularjs-google-maps
|
build/scripts/ng-map.debug.js
|
function(filtered) {
var controlOptions = {};
if (typeof filtered != 'object') {
return false;
}
for (var attr in filtered) {
if (filtered[attr]) {
if (!attr.match(/(.*)ControlOptions$/)) {
continue; // if not controlOptions, skip it
}
//change invalid json to valid one, i.e. {foo:1} to {"foo": 1}
var orgValue = filtered[attr];
var newValue = orgValue.replace(/'/g, '"');
newValue = newValue.replace(/([^"]+)|("[^"]+")/g, function($0, $1, $2) {
if ($1) {
return $1.replace(/([a-zA-Z0-9]+?):/g, '"$1":');
} else {
return $2;
}
});
try {
var options = JSON.parse(newValue);
for (var key in options) { //assign the right values
if (options[key]) {
var value = options[key];
if (typeof value === 'string') {
value = value.toUpperCase();
} else if (key === "mapTypeIds") {
value = value.map( function(str) {
if (str.match(/^[A-Z]+$/)) { // if constant
return google.maps.MapTypeId[str.toUpperCase()];
} else { // else, custom map-type
return str;
}
});
}
if (key === "style") {
var str = attr.charAt(0).toUpperCase() + attr.slice(1);
var objName = str.replace(/Options$/,'')+"Style";
options[key] = google.maps[objName][value];
} else if (key === "position") {
options[key] = google.maps.ControlPosition[value];
} else {
options[key] = value;
}
}
}
controlOptions[attr] = options;
} catch (e) {
console.error('invald option for', attr, newValue, e, e.stack);
}
}
} // for
return controlOptions;
}
|
javascript
|
function(filtered) {
var controlOptions = {};
if (typeof filtered != 'object') {
return false;
}
for (var attr in filtered) {
if (filtered[attr]) {
if (!attr.match(/(.*)ControlOptions$/)) {
continue; // if not controlOptions, skip it
}
//change invalid json to valid one, i.e. {foo:1} to {"foo": 1}
var orgValue = filtered[attr];
var newValue = orgValue.replace(/'/g, '"');
newValue = newValue.replace(/([^"]+)|("[^"]+")/g, function($0, $1, $2) {
if ($1) {
return $1.replace(/([a-zA-Z0-9]+?):/g, '"$1":');
} else {
return $2;
}
});
try {
var options = JSON.parse(newValue);
for (var key in options) { //assign the right values
if (options[key]) {
var value = options[key];
if (typeof value === 'string') {
value = value.toUpperCase();
} else if (key === "mapTypeIds") {
value = value.map( function(str) {
if (str.match(/^[A-Z]+$/)) { // if constant
return google.maps.MapTypeId[str.toUpperCase()];
} else { // else, custom map-type
return str;
}
});
}
if (key === "style") {
var str = attr.charAt(0).toUpperCase() + attr.slice(1);
var objName = str.replace(/Options$/,'')+"Style";
options[key] = google.maps[objName][value];
} else if (key === "position") {
options[key] = google.maps.ControlPosition[value];
} else {
options[key] = value;
}
}
}
controlOptions[attr] = options;
} catch (e) {
console.error('invald option for', attr, newValue, e, e.stack);
}
}
} // for
return controlOptions;
}
|
[
"function",
"(",
"filtered",
")",
"{",
"var",
"controlOptions",
"=",
"{",
"}",
";",
"if",
"(",
"typeof",
"filtered",
"!=",
"'object'",
")",
"{",
"return",
"false",
";",
"}",
"for",
"(",
"var",
"attr",
"in",
"filtered",
")",
"{",
"if",
"(",
"filtered",
"[",
"attr",
"]",
")",
"{",
"if",
"(",
"!",
"attr",
".",
"match",
"(",
"/",
"(.*)ControlOptions$",
"/",
")",
")",
"{",
"continue",
";",
"// if not controlOptions, skip it",
"}",
"//change invalid json to valid one, i.e. {foo:1} to {\"foo\": 1}",
"var",
"orgValue",
"=",
"filtered",
"[",
"attr",
"]",
";",
"var",
"newValue",
"=",
"orgValue",
".",
"replace",
"(",
"/",
"'",
"/",
"g",
",",
"'\"'",
")",
";",
"newValue",
"=",
"newValue",
".",
"replace",
"(",
"/",
"([^\"]+)|(\"[^\"]+\")",
"/",
"g",
",",
"function",
"(",
"$0",
",",
"$1",
",",
"$2",
")",
"{",
"if",
"(",
"$1",
")",
"{",
"return",
"$1",
".",
"replace",
"(",
"/",
"([a-zA-Z0-9]+?):",
"/",
"g",
",",
"'\"$1\":'",
")",
";",
"}",
"else",
"{",
"return",
"$2",
";",
"}",
"}",
")",
";",
"try",
"{",
"var",
"options",
"=",
"JSON",
".",
"parse",
"(",
"newValue",
")",
";",
"for",
"(",
"var",
"key",
"in",
"options",
")",
"{",
"//assign the right values",
"if",
"(",
"options",
"[",
"key",
"]",
")",
"{",
"var",
"value",
"=",
"options",
"[",
"key",
"]",
";",
"if",
"(",
"typeof",
"value",
"===",
"'string'",
")",
"{",
"value",
"=",
"value",
".",
"toUpperCase",
"(",
")",
";",
"}",
"else",
"if",
"(",
"key",
"===",
"\"mapTypeIds\"",
")",
"{",
"value",
"=",
"value",
".",
"map",
"(",
"function",
"(",
"str",
")",
"{",
"if",
"(",
"str",
".",
"match",
"(",
"/",
"^[A-Z]+$",
"/",
")",
")",
"{",
"// if constant",
"return",
"google",
".",
"maps",
".",
"MapTypeId",
"[",
"str",
".",
"toUpperCase",
"(",
")",
"]",
";",
"}",
"else",
"{",
"// else, custom map-type",
"return",
"str",
";",
"}",
"}",
")",
";",
"}",
"if",
"(",
"key",
"===",
"\"style\"",
")",
"{",
"var",
"str",
"=",
"attr",
".",
"charAt",
"(",
"0",
")",
".",
"toUpperCase",
"(",
")",
"+",
"attr",
".",
"slice",
"(",
"1",
")",
";",
"var",
"objName",
"=",
"str",
".",
"replace",
"(",
"/",
"Options$",
"/",
",",
"''",
")",
"+",
"\"Style\"",
";",
"options",
"[",
"key",
"]",
"=",
"google",
".",
"maps",
"[",
"objName",
"]",
"[",
"value",
"]",
";",
"}",
"else",
"if",
"(",
"key",
"===",
"\"position\"",
")",
"{",
"options",
"[",
"key",
"]",
"=",
"google",
".",
"maps",
".",
"ControlPosition",
"[",
"value",
"]",
";",
"}",
"else",
"{",
"options",
"[",
"key",
"]",
"=",
"value",
";",
"}",
"}",
"}",
"controlOptions",
"[",
"attr",
"]",
"=",
"options",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"error",
"(",
"'invald option for'",
",",
"attr",
",",
"newValue",
",",
"e",
",",
"e",
".",
"stack",
")",
";",
"}",
"}",
"}",
"// for",
"return",
"controlOptions",
";",
"}"
] |
control means map controls, i.e streetview, pan, etc, not a general control
@memberof Attr2MapOptions
@param {Hash} filtered filtered tag attributes
@returns {Hash} Google Map options
|
[
"control",
"means",
"map",
"controls",
"i",
".",
"e",
"streetview",
"pan",
"etc",
"not",
"a",
"general",
"control"
] |
8d485a6b3e0b94fa7c78fce9d5b3f101ccd6149c
|
https://github.com/allenhwkim/angularjs-google-maps/blob/8d485a6b3e0b94fa7c78fce9d5b3f101ccd6149c/build/scripts/ng-map.debug.js#L2813-L2871
|
|
13,032
|
allenhwkim/angularjs-google-maps
|
build/scripts/ng-map.debug.js
|
function(map, panoId) {
var svp = new google.maps.StreetViewPanorama(
map.getDiv(), {enableCloseButton: true}
);
svp.setPano(panoId);
}
|
javascript
|
function(map, panoId) {
var svp = new google.maps.StreetViewPanorama(
map.getDiv(), {enableCloseButton: true}
);
svp.setPano(panoId);
}
|
[
"function",
"(",
"map",
",",
"panoId",
")",
"{",
"var",
"svp",
"=",
"new",
"google",
".",
"maps",
".",
"StreetViewPanorama",
"(",
"map",
".",
"getDiv",
"(",
")",
",",
"{",
"enableCloseButton",
":",
"true",
"}",
")",
";",
"svp",
".",
"setPano",
"(",
"panoId",
")",
";",
"}"
] |
Set panorama view on the given map with the panorama id
@memberof StreetView
@param {map} map Google map instance
@param {String} panoId Panorama id fro getPanorama method
@example
StreetView.setPanorama(map, panoId);
|
[
"Set",
"panorama",
"view",
"on",
"the",
"given",
"map",
"with",
"the",
"panorama",
"id"
] |
8d485a6b3e0b94fa7c78fce9d5b3f101ccd6149c
|
https://github.com/allenhwkim/angularjs-google-maps/blob/8d485a6b3e0b94fa7c78fce9d5b3f101ccd6149c/build/scripts/ng-map.debug.js#L3518-L3523
|
|
13,033
|
zurb/foundation-emails-template
|
gulpfile.babel.js
|
pages
|
function pages() {
return gulp.src(['src/pages/**/*.html', '!src/pages/archive/**/*.html'])
.pipe(panini({
root: 'src/pages',
layouts: 'src/layouts',
partials: 'src/partials',
helpers: 'src/helpers'
}))
.pipe(inky())
.pipe(gulp.dest('dist'));
}
|
javascript
|
function pages() {
return gulp.src(['src/pages/**/*.html', '!src/pages/archive/**/*.html'])
.pipe(panini({
root: 'src/pages',
layouts: 'src/layouts',
partials: 'src/partials',
helpers: 'src/helpers'
}))
.pipe(inky())
.pipe(gulp.dest('dist'));
}
|
[
"function",
"pages",
"(",
")",
"{",
"return",
"gulp",
".",
"src",
"(",
"[",
"'src/pages/**/*.html'",
",",
"'!src/pages/archive/**/*.html'",
"]",
")",
".",
"pipe",
"(",
"panini",
"(",
"{",
"root",
":",
"'src/pages'",
",",
"layouts",
":",
"'src/layouts'",
",",
"partials",
":",
"'src/partials'",
",",
"helpers",
":",
"'src/helpers'",
"}",
")",
")",
".",
"pipe",
"(",
"inky",
"(",
")",
")",
".",
"pipe",
"(",
"gulp",
".",
"dest",
"(",
"'dist'",
")",
")",
";",
"}"
] |
Compile layouts, pages, and partials into flat HTML files Then parse using Inky templates
|
[
"Compile",
"layouts",
"pages",
"and",
"partials",
"into",
"flat",
"HTML",
"files",
"Then",
"parse",
"using",
"Inky",
"templates"
] |
2f0cfa9a978ad7ced4ee3de33366224a90168724
|
https://github.com/zurb/foundation-emails-template/blob/2f0cfa9a978ad7ced4ee3de33366224a90168724/gulpfile.babel.js#L53-L63
|
13,034
|
zurb/foundation-emails-template
|
gulpfile.babel.js
|
sass
|
function sass() {
return gulp.src('src/assets/scss/app.scss')
.pipe($.if(!PRODUCTION, $.sourcemaps.init()))
.pipe($.sass({
includePaths: ['node_modules/foundation-emails/scss']
}).on('error', $.sass.logError))
.pipe($.if(PRODUCTION, $.uncss(
{
html: ['dist/**/*.html']
})))
.pipe($.if(!PRODUCTION, $.sourcemaps.write()))
.pipe(gulp.dest('dist/css'));
}
|
javascript
|
function sass() {
return gulp.src('src/assets/scss/app.scss')
.pipe($.if(!PRODUCTION, $.sourcemaps.init()))
.pipe($.sass({
includePaths: ['node_modules/foundation-emails/scss']
}).on('error', $.sass.logError))
.pipe($.if(PRODUCTION, $.uncss(
{
html: ['dist/**/*.html']
})))
.pipe($.if(!PRODUCTION, $.sourcemaps.write()))
.pipe(gulp.dest('dist/css'));
}
|
[
"function",
"sass",
"(",
")",
"{",
"return",
"gulp",
".",
"src",
"(",
"'src/assets/scss/app.scss'",
")",
".",
"pipe",
"(",
"$",
".",
"if",
"(",
"!",
"PRODUCTION",
",",
"$",
".",
"sourcemaps",
".",
"init",
"(",
")",
")",
")",
".",
"pipe",
"(",
"$",
".",
"sass",
"(",
"{",
"includePaths",
":",
"[",
"'node_modules/foundation-emails/scss'",
"]",
"}",
")",
".",
"on",
"(",
"'error'",
",",
"$",
".",
"sass",
".",
"logError",
")",
")",
".",
"pipe",
"(",
"$",
".",
"if",
"(",
"PRODUCTION",
",",
"$",
".",
"uncss",
"(",
"{",
"html",
":",
"[",
"'dist/**/*.html'",
"]",
"}",
")",
")",
")",
".",
"pipe",
"(",
"$",
".",
"if",
"(",
"!",
"PRODUCTION",
",",
"$",
".",
"sourcemaps",
".",
"write",
"(",
")",
")",
")",
".",
"pipe",
"(",
"gulp",
".",
"dest",
"(",
"'dist/css'",
")",
")",
";",
"}"
] |
Compile Sass into CSS
|
[
"Compile",
"Sass",
"into",
"CSS"
] |
2f0cfa9a978ad7ced4ee3de33366224a90168724
|
https://github.com/zurb/foundation-emails-template/blob/2f0cfa9a978ad7ced4ee3de33366224a90168724/gulpfile.babel.js#L72-L84
|
13,035
|
zurb/foundation-emails-template
|
gulpfile.babel.js
|
watch
|
function watch() {
gulp.watch('src/pages/**/*.html').on('all', gulp.series(pages, inline, browser.reload));
gulp.watch(['src/layouts/**/*', 'src/partials/**/*']).on('all', gulp.series(resetPages, pages, inline, browser.reload));
gulp.watch(['../scss/**/*.scss', 'src/assets/scss/**/*.scss']).on('all', gulp.series(resetPages, sass, pages, inline, browser.reload));
gulp.watch('src/assets/img/**/*').on('all', gulp.series(images, browser.reload));
}
|
javascript
|
function watch() {
gulp.watch('src/pages/**/*.html').on('all', gulp.series(pages, inline, browser.reload));
gulp.watch(['src/layouts/**/*', 'src/partials/**/*']).on('all', gulp.series(resetPages, pages, inline, browser.reload));
gulp.watch(['../scss/**/*.scss', 'src/assets/scss/**/*.scss']).on('all', gulp.series(resetPages, sass, pages, inline, browser.reload));
gulp.watch('src/assets/img/**/*').on('all', gulp.series(images, browser.reload));
}
|
[
"function",
"watch",
"(",
")",
"{",
"gulp",
".",
"watch",
"(",
"'src/pages/**/*.html'",
")",
".",
"on",
"(",
"'all'",
",",
"gulp",
".",
"series",
"(",
"pages",
",",
"inline",
",",
"browser",
".",
"reload",
")",
")",
";",
"gulp",
".",
"watch",
"(",
"[",
"'src/layouts/**/*'",
",",
"'src/partials/**/*'",
"]",
")",
".",
"on",
"(",
"'all'",
",",
"gulp",
".",
"series",
"(",
"resetPages",
",",
"pages",
",",
"inline",
",",
"browser",
".",
"reload",
")",
")",
";",
"gulp",
".",
"watch",
"(",
"[",
"'../scss/**/*.scss'",
",",
"'src/assets/scss/**/*.scss'",
"]",
")",
".",
"on",
"(",
"'all'",
",",
"gulp",
".",
"series",
"(",
"resetPages",
",",
"sass",
",",
"pages",
",",
"inline",
",",
"browser",
".",
"reload",
")",
")",
";",
"gulp",
".",
"watch",
"(",
"'src/assets/img/**/*'",
")",
".",
"on",
"(",
"'all'",
",",
"gulp",
".",
"series",
"(",
"images",
",",
"browser",
".",
"reload",
")",
")",
";",
"}"
] |
Watch for file changes
|
[
"Watch",
"for",
"file",
"changes"
] |
2f0cfa9a978ad7ced4ee3de33366224a90168724
|
https://github.com/zurb/foundation-emails-template/blob/2f0cfa9a978ad7ced4ee3de33366224a90168724/gulpfile.babel.js#L109-L114
|
13,036
|
zurb/foundation-emails-template
|
gulpfile.babel.js
|
creds
|
function creds(done) {
var configPath = './config.json';
try { CONFIG = JSON.parse(fs.readFileSync(configPath)); }
catch(e) {
beep();
console.log('[AWS]'.bold.red + ' Sorry, there was an issue locating your config.json. Please see README.md');
process.exit();
}
done();
}
|
javascript
|
function creds(done) {
var configPath = './config.json';
try { CONFIG = JSON.parse(fs.readFileSync(configPath)); }
catch(e) {
beep();
console.log('[AWS]'.bold.red + ' Sorry, there was an issue locating your config.json. Please see README.md');
process.exit();
}
done();
}
|
[
"function",
"creds",
"(",
"done",
")",
"{",
"var",
"configPath",
"=",
"'./config.json'",
";",
"try",
"{",
"CONFIG",
"=",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"configPath",
")",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"beep",
"(",
")",
";",
"console",
".",
"log",
"(",
"'[AWS]'",
".",
"bold",
".",
"red",
"+",
"' Sorry, there was an issue locating your config.json. Please see README.md'",
")",
";",
"process",
".",
"exit",
"(",
")",
";",
"}",
"done",
"(",
")",
";",
"}"
] |
Ensure creds for Litmus are at least there.
|
[
"Ensure",
"creds",
"for",
"Litmus",
"are",
"at",
"least",
"there",
"."
] |
2f0cfa9a978ad7ced4ee3de33366224a90168724
|
https://github.com/zurb/foundation-emails-template/blob/2f0cfa9a978ad7ced4ee3de33366224a90168724/gulpfile.babel.js#L139-L148
|
13,037
|
zurb/foundation-emails-template
|
gulpfile.babel.js
|
aws
|
function aws() {
var publisher = !!CONFIG.aws ? $.awspublish.create(CONFIG.aws) : $.awspublish.create();
var headers = {
'Cache-Control': 'max-age=315360000, no-transform, public'
};
return gulp.src('./dist/assets/img/*')
// publisher will add Content-Length, Content-Type and headers specified above
// If not specified it will set x-amz-acl to public-read by default
.pipe(publisher.publish(headers))
// create a cache file to speed up consecutive uploads
//.pipe(publisher.cache())
// print upload updates to console
.pipe($.awspublish.reporter());
}
|
javascript
|
function aws() {
var publisher = !!CONFIG.aws ? $.awspublish.create(CONFIG.aws) : $.awspublish.create();
var headers = {
'Cache-Control': 'max-age=315360000, no-transform, public'
};
return gulp.src('./dist/assets/img/*')
// publisher will add Content-Length, Content-Type and headers specified above
// If not specified it will set x-amz-acl to public-read by default
.pipe(publisher.publish(headers))
// create a cache file to speed up consecutive uploads
//.pipe(publisher.cache())
// print upload updates to console
.pipe($.awspublish.reporter());
}
|
[
"function",
"aws",
"(",
")",
"{",
"var",
"publisher",
"=",
"!",
"!",
"CONFIG",
".",
"aws",
"?",
"$",
".",
"awspublish",
".",
"create",
"(",
"CONFIG",
".",
"aws",
")",
":",
"$",
".",
"awspublish",
".",
"create",
"(",
")",
";",
"var",
"headers",
"=",
"{",
"'Cache-Control'",
":",
"'max-age=315360000, no-transform, public'",
"}",
";",
"return",
"gulp",
".",
"src",
"(",
"'./dist/assets/img/*'",
")",
"// publisher will add Content-Length, Content-Type and headers specified above",
"// If not specified it will set x-amz-acl to public-read by default",
".",
"pipe",
"(",
"publisher",
".",
"publish",
"(",
"headers",
")",
")",
"// create a cache file to speed up consecutive uploads",
"//.pipe(publisher.cache())",
"// print upload updates to console",
".",
"pipe",
"(",
"$",
".",
"awspublish",
".",
"reporter",
"(",
")",
")",
";",
"}"
] |
Post images to AWS S3 so they are accessible to Litmus and manual test
|
[
"Post",
"images",
"to",
"AWS",
"S3",
"so",
"they",
"are",
"accessible",
"to",
"Litmus",
"and",
"manual",
"test"
] |
2f0cfa9a978ad7ced4ee3de33366224a90168724
|
https://github.com/zurb/foundation-emails-template/blob/2f0cfa9a978ad7ced4ee3de33366224a90168724/gulpfile.babel.js#L151-L167
|
13,038
|
zurb/foundation-emails-template
|
gulpfile.babel.js
|
litmus
|
function litmus() {
var awsURL = !!CONFIG && !!CONFIG.aws && !!CONFIG.aws.url ? CONFIG.aws.url : false;
return gulp.src('dist/**/*.html')
.pipe($.if(!!awsURL, $.replace(/=('|")(\/?assets\/img)/g, "=$1"+ awsURL)))
.pipe($.litmus(CONFIG.litmus))
.pipe(gulp.dest('dist'));
}
|
javascript
|
function litmus() {
var awsURL = !!CONFIG && !!CONFIG.aws && !!CONFIG.aws.url ? CONFIG.aws.url : false;
return gulp.src('dist/**/*.html')
.pipe($.if(!!awsURL, $.replace(/=('|")(\/?assets\/img)/g, "=$1"+ awsURL)))
.pipe($.litmus(CONFIG.litmus))
.pipe(gulp.dest('dist'));
}
|
[
"function",
"litmus",
"(",
")",
"{",
"var",
"awsURL",
"=",
"!",
"!",
"CONFIG",
"&&",
"!",
"!",
"CONFIG",
".",
"aws",
"&&",
"!",
"!",
"CONFIG",
".",
"aws",
".",
"url",
"?",
"CONFIG",
".",
"aws",
".",
"url",
":",
"false",
";",
"return",
"gulp",
".",
"src",
"(",
"'dist/**/*.html'",
")",
".",
"pipe",
"(",
"$",
".",
"if",
"(",
"!",
"!",
"awsURL",
",",
"$",
".",
"replace",
"(",
"/",
"=('|\")(\\/?assets\\/img)",
"/",
"g",
",",
"\"=$1\"",
"+",
"awsURL",
")",
")",
")",
".",
"pipe",
"(",
"$",
".",
"litmus",
"(",
"CONFIG",
".",
"litmus",
")",
")",
".",
"pipe",
"(",
"gulp",
".",
"dest",
"(",
"'dist'",
")",
")",
";",
"}"
] |
Send email to Litmus for testing. If no AWS creds then do not replace img urls.
|
[
"Send",
"email",
"to",
"Litmus",
"for",
"testing",
".",
"If",
"no",
"AWS",
"creds",
"then",
"do",
"not",
"replace",
"img",
"urls",
"."
] |
2f0cfa9a978ad7ced4ee3de33366224a90168724
|
https://github.com/zurb/foundation-emails-template/blob/2f0cfa9a978ad7ced4ee3de33366224a90168724/gulpfile.babel.js#L170-L177
|
13,039
|
zurb/foundation-emails-template
|
gulpfile.babel.js
|
mail
|
function mail() {
var awsURL = !!CONFIG && !!CONFIG.aws && !!CONFIG.aws.url ? CONFIG.aws.url : false;
if (EMAIL) {
CONFIG.mail.to = [EMAIL];
}
return gulp.src('dist/**/*.html')
.pipe($.if(!!awsURL, $.replace(/=('|")(\/?assets\/img)/g, "=$1"+ awsURL)))
.pipe($.mail(CONFIG.mail))
.pipe(gulp.dest('dist'));
}
|
javascript
|
function mail() {
var awsURL = !!CONFIG && !!CONFIG.aws && !!CONFIG.aws.url ? CONFIG.aws.url : false;
if (EMAIL) {
CONFIG.mail.to = [EMAIL];
}
return gulp.src('dist/**/*.html')
.pipe($.if(!!awsURL, $.replace(/=('|")(\/?assets\/img)/g, "=$1"+ awsURL)))
.pipe($.mail(CONFIG.mail))
.pipe(gulp.dest('dist'));
}
|
[
"function",
"mail",
"(",
")",
"{",
"var",
"awsURL",
"=",
"!",
"!",
"CONFIG",
"&&",
"!",
"!",
"CONFIG",
".",
"aws",
"&&",
"!",
"!",
"CONFIG",
".",
"aws",
".",
"url",
"?",
"CONFIG",
".",
"aws",
".",
"url",
":",
"false",
";",
"if",
"(",
"EMAIL",
")",
"{",
"CONFIG",
".",
"mail",
".",
"to",
"=",
"[",
"EMAIL",
"]",
";",
"}",
"return",
"gulp",
".",
"src",
"(",
"'dist/**/*.html'",
")",
".",
"pipe",
"(",
"$",
".",
"if",
"(",
"!",
"!",
"awsURL",
",",
"$",
".",
"replace",
"(",
"/",
"=('|\")(\\/?assets\\/img)",
"/",
"g",
",",
"\"=$1\"",
"+",
"awsURL",
")",
")",
")",
".",
"pipe",
"(",
"$",
".",
"mail",
"(",
"CONFIG",
".",
"mail",
")",
")",
".",
"pipe",
"(",
"gulp",
".",
"dest",
"(",
"'dist'",
")",
")",
";",
"}"
] |
Send email to specified email for testing. If no AWS creds then do not replace img urls.
|
[
"Send",
"email",
"to",
"specified",
"email",
"for",
"testing",
".",
"If",
"no",
"AWS",
"creds",
"then",
"do",
"not",
"replace",
"img",
"urls",
"."
] |
2f0cfa9a978ad7ced4ee3de33366224a90168724
|
https://github.com/zurb/foundation-emails-template/blob/2f0cfa9a978ad7ced4ee3de33366224a90168724/gulpfile.babel.js#L180-L191
|
13,040
|
zurb/foundation-emails-template
|
gulpfile.babel.js
|
zip
|
function zip() {
var dist = 'dist';
var ext = '.html';
function getHtmlFiles(dir) {
return fs.readdirSync(dir)
.filter(function(file) {
var fileExt = path.join(dir, file);
var isHtml = path.extname(fileExt) == ext;
return fs.statSync(fileExt).isFile() && isHtml;
});
}
var htmlFiles = getHtmlFiles(dist);
var moveTasks = htmlFiles.map(function(file){
var sourcePath = path.join(dist, file);
var fileName = path.basename(sourcePath, ext);
var moveHTML = gulp.src(sourcePath)
.pipe($.rename(function (path) {
path.dirname = fileName;
return path;
}));
var moveImages = gulp.src(sourcePath)
.pipe($.htmlSrc({ selector: 'img'}))
.pipe($.rename(function (path) {
path.dirname = fileName + path.dirname.replace('dist', '');
return path;
}));
return merge(moveHTML, moveImages)
.pipe($.zip(fileName+ '.zip'))
.pipe(gulp.dest('dist'));
});
return merge(moveTasks);
}
|
javascript
|
function zip() {
var dist = 'dist';
var ext = '.html';
function getHtmlFiles(dir) {
return fs.readdirSync(dir)
.filter(function(file) {
var fileExt = path.join(dir, file);
var isHtml = path.extname(fileExt) == ext;
return fs.statSync(fileExt).isFile() && isHtml;
});
}
var htmlFiles = getHtmlFiles(dist);
var moveTasks = htmlFiles.map(function(file){
var sourcePath = path.join(dist, file);
var fileName = path.basename(sourcePath, ext);
var moveHTML = gulp.src(sourcePath)
.pipe($.rename(function (path) {
path.dirname = fileName;
return path;
}));
var moveImages = gulp.src(sourcePath)
.pipe($.htmlSrc({ selector: 'img'}))
.pipe($.rename(function (path) {
path.dirname = fileName + path.dirname.replace('dist', '');
return path;
}));
return merge(moveHTML, moveImages)
.pipe($.zip(fileName+ '.zip'))
.pipe(gulp.dest('dist'));
});
return merge(moveTasks);
}
|
[
"function",
"zip",
"(",
")",
"{",
"var",
"dist",
"=",
"'dist'",
";",
"var",
"ext",
"=",
"'.html'",
";",
"function",
"getHtmlFiles",
"(",
"dir",
")",
"{",
"return",
"fs",
".",
"readdirSync",
"(",
"dir",
")",
".",
"filter",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"fileExt",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"file",
")",
";",
"var",
"isHtml",
"=",
"path",
".",
"extname",
"(",
"fileExt",
")",
"==",
"ext",
";",
"return",
"fs",
".",
"statSync",
"(",
"fileExt",
")",
".",
"isFile",
"(",
")",
"&&",
"isHtml",
";",
"}",
")",
";",
"}",
"var",
"htmlFiles",
"=",
"getHtmlFiles",
"(",
"dist",
")",
";",
"var",
"moveTasks",
"=",
"htmlFiles",
".",
"map",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"sourcePath",
"=",
"path",
".",
"join",
"(",
"dist",
",",
"file",
")",
";",
"var",
"fileName",
"=",
"path",
".",
"basename",
"(",
"sourcePath",
",",
"ext",
")",
";",
"var",
"moveHTML",
"=",
"gulp",
".",
"src",
"(",
"sourcePath",
")",
".",
"pipe",
"(",
"$",
".",
"rename",
"(",
"function",
"(",
"path",
")",
"{",
"path",
".",
"dirname",
"=",
"fileName",
";",
"return",
"path",
";",
"}",
")",
")",
";",
"var",
"moveImages",
"=",
"gulp",
".",
"src",
"(",
"sourcePath",
")",
".",
"pipe",
"(",
"$",
".",
"htmlSrc",
"(",
"{",
"selector",
":",
"'img'",
"}",
")",
")",
".",
"pipe",
"(",
"$",
".",
"rename",
"(",
"function",
"(",
"path",
")",
"{",
"path",
".",
"dirname",
"=",
"fileName",
"+",
"path",
".",
"dirname",
".",
"replace",
"(",
"'dist'",
",",
"''",
")",
";",
"return",
"path",
";",
"}",
")",
")",
";",
"return",
"merge",
"(",
"moveHTML",
",",
"moveImages",
")",
".",
"pipe",
"(",
"$",
".",
"zip",
"(",
"fileName",
"+",
"'.zip'",
")",
")",
".",
"pipe",
"(",
"gulp",
".",
"dest",
"(",
"'dist'",
")",
")",
";",
"}",
")",
";",
"return",
"merge",
"(",
"moveTasks",
")",
";",
"}"
] |
Copy and compress into Zip
|
[
"Copy",
"and",
"compress",
"into",
"Zip"
] |
2f0cfa9a978ad7ced4ee3de33366224a90168724
|
https://github.com/zurb/foundation-emails-template/blob/2f0cfa9a978ad7ced4ee3de33366224a90168724/gulpfile.babel.js#L194-L232
|
13,041
|
sandywalker/webui-popover
|
dist/jquery.webui-popover.js
|
function() {
if (this.$element[0] instanceof document.constructor && !this.options.selector) {
throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!');
}
if (this.getTrigger() !== 'manual') {
//init the event handlers
if (isMobile) {
this.$element.off('touchend', this.options.selector).on('touchend', this.options.selector, $.proxy(this.toggle, this));
} else if (this.getTrigger() === 'click') {
this.$element.off('click', this.options.selector).on('click', this.options.selector, $.proxy(this.toggle, this));
} else if (this.getTrigger() === 'hover') {
this.$element
.off('mouseenter mouseleave click', this.options.selector)
.on('mouseenter', this.options.selector, $.proxy(this.mouseenterHandler, this))
.on('mouseleave', this.options.selector, $.proxy(this.mouseleaveHandler, this));
}
}
this._poped = false;
this._inited = true;
this._opened = false;
this._idSeed = _globalIdSeed;
this.id = pluginName + this._idSeed;
// normalize container
this.options.container = $(this.options.container || document.body).first();
if (this.options.backdrop) {
backdrop.appendTo(this.options.container).hide();
}
_globalIdSeed++;
if (this.getTrigger() === 'sticky') {
this.show();
}
if (this.options.selector) {
this._options = $.extend({}, this.options, {
selector: ''
});
}
}
|
javascript
|
function() {
if (this.$element[0] instanceof document.constructor && !this.options.selector) {
throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!');
}
if (this.getTrigger() !== 'manual') {
//init the event handlers
if (isMobile) {
this.$element.off('touchend', this.options.selector).on('touchend', this.options.selector, $.proxy(this.toggle, this));
} else if (this.getTrigger() === 'click') {
this.$element.off('click', this.options.selector).on('click', this.options.selector, $.proxy(this.toggle, this));
} else if (this.getTrigger() === 'hover') {
this.$element
.off('mouseenter mouseleave click', this.options.selector)
.on('mouseenter', this.options.selector, $.proxy(this.mouseenterHandler, this))
.on('mouseleave', this.options.selector, $.proxy(this.mouseleaveHandler, this));
}
}
this._poped = false;
this._inited = true;
this._opened = false;
this._idSeed = _globalIdSeed;
this.id = pluginName + this._idSeed;
// normalize container
this.options.container = $(this.options.container || document.body).first();
if (this.options.backdrop) {
backdrop.appendTo(this.options.container).hide();
}
_globalIdSeed++;
if (this.getTrigger() === 'sticky') {
this.show();
}
if (this.options.selector) {
this._options = $.extend({}, this.options, {
selector: ''
});
}
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"$element",
"[",
"0",
"]",
"instanceof",
"document",
".",
"constructor",
"&&",
"!",
"this",
".",
"options",
".",
"selector",
")",
"{",
"throw",
"new",
"Error",
"(",
"'`selector` option must be specified when initializing '",
"+",
"this",
".",
"type",
"+",
"' on the window.document object!'",
")",
";",
"}",
"if",
"(",
"this",
".",
"getTrigger",
"(",
")",
"!==",
"'manual'",
")",
"{",
"//init the event handlers",
"if",
"(",
"isMobile",
")",
"{",
"this",
".",
"$element",
".",
"off",
"(",
"'touchend'",
",",
"this",
".",
"options",
".",
"selector",
")",
".",
"on",
"(",
"'touchend'",
",",
"this",
".",
"options",
".",
"selector",
",",
"$",
".",
"proxy",
"(",
"this",
".",
"toggle",
",",
"this",
")",
")",
";",
"}",
"else",
"if",
"(",
"this",
".",
"getTrigger",
"(",
")",
"===",
"'click'",
")",
"{",
"this",
".",
"$element",
".",
"off",
"(",
"'click'",
",",
"this",
".",
"options",
".",
"selector",
")",
".",
"on",
"(",
"'click'",
",",
"this",
".",
"options",
".",
"selector",
",",
"$",
".",
"proxy",
"(",
"this",
".",
"toggle",
",",
"this",
")",
")",
";",
"}",
"else",
"if",
"(",
"this",
".",
"getTrigger",
"(",
")",
"===",
"'hover'",
")",
"{",
"this",
".",
"$element",
".",
"off",
"(",
"'mouseenter mouseleave click'",
",",
"this",
".",
"options",
".",
"selector",
")",
".",
"on",
"(",
"'mouseenter'",
",",
"this",
".",
"options",
".",
"selector",
",",
"$",
".",
"proxy",
"(",
"this",
".",
"mouseenterHandler",
",",
"this",
")",
")",
".",
"on",
"(",
"'mouseleave'",
",",
"this",
".",
"options",
".",
"selector",
",",
"$",
".",
"proxy",
"(",
"this",
".",
"mouseleaveHandler",
",",
"this",
")",
")",
";",
"}",
"}",
"this",
".",
"_poped",
"=",
"false",
";",
"this",
".",
"_inited",
"=",
"true",
";",
"this",
".",
"_opened",
"=",
"false",
";",
"this",
".",
"_idSeed",
"=",
"_globalIdSeed",
";",
"this",
".",
"id",
"=",
"pluginName",
"+",
"this",
".",
"_idSeed",
";",
"// normalize container",
"this",
".",
"options",
".",
"container",
"=",
"$",
"(",
"this",
".",
"options",
".",
"container",
"||",
"document",
".",
"body",
")",
".",
"first",
"(",
")",
";",
"if",
"(",
"this",
".",
"options",
".",
"backdrop",
")",
"{",
"backdrop",
".",
"appendTo",
"(",
"this",
".",
"options",
".",
"container",
")",
".",
"hide",
"(",
")",
";",
"}",
"_globalIdSeed",
"++",
";",
"if",
"(",
"this",
".",
"getTrigger",
"(",
")",
"===",
"'sticky'",
")",
"{",
"this",
".",
"show",
"(",
")",
";",
"}",
"if",
"(",
"this",
".",
"options",
".",
"selector",
")",
"{",
"this",
".",
"_options",
"=",
"$",
".",
"extend",
"(",
"{",
"}",
",",
"this",
".",
"options",
",",
"{",
"selector",
":",
"''",
"}",
")",
";",
"}",
"}"
] |
init webui popover
|
[
"init",
"webui",
"popover"
] |
b02d6ba8ea9d2ced5ce0333d7ddb1eec6f9eb3ae
|
https://github.com/sandywalker/webui-popover/blob/b02d6ba8ea9d2ced5ce0333d7ddb1eec6f9eb3ae/dist/jquery.webui-popover.js#L166-L206
|
|
13,042
|
a8m/angular-filter
|
src/_filter/collection/unique.js
|
some
|
function some(array, member) {
if(isUndefined(member)) {
return false;
}
return array.some(function(el) {
return equals(el, member);
});
}
|
javascript
|
function some(array, member) {
if(isUndefined(member)) {
return false;
}
return array.some(function(el) {
return equals(el, member);
});
}
|
[
"function",
"some",
"(",
"array",
",",
"member",
")",
"{",
"if",
"(",
"isUndefined",
"(",
"member",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"array",
".",
"some",
"(",
"function",
"(",
"el",
")",
"{",
"return",
"equals",
"(",
"el",
",",
"member",
")",
";",
"}",
")",
";",
"}"
] |
checked if the unique identifier is already exist
|
[
"checked",
"if",
"the",
"unique",
"identifier",
"is",
"already",
"exist"
] |
0bc1607f2468bf003a8419718f42f310b1445bd9
|
https://github.com/a8m/angular-filter/blob/0bc1607f2468bf003a8419718f42f310b1445bd9/src/_filter/collection/unique.js#L47-L54
|
13,043
|
a8m/angular-filter
|
src/_common.js
|
indexOf
|
function indexOf(word, p, c) {
var j = 0;
while ((p + j) <= word.length) {
if (word.charAt(p + j) == c) return j;
j++;
}
return -1;
}
|
javascript
|
function indexOf(word, p, c) {
var j = 0;
while ((p + j) <= word.length) {
if (word.charAt(p + j) == c) return j;
j++;
}
return -1;
}
|
[
"function",
"indexOf",
"(",
"word",
",",
"p",
",",
"c",
")",
"{",
"var",
"j",
"=",
"0",
";",
"while",
"(",
"(",
"p",
"+",
"j",
")",
"<=",
"word",
".",
"length",
")",
"{",
"if",
"(",
"word",
".",
"charAt",
"(",
"p",
"+",
"j",
")",
"==",
"c",
")",
"return",
"j",
";",
"j",
"++",
";",
"}",
"return",
"-",
"1",
";",
"}"
] |
cheaper version of indexOf; instead of creating each iteration new str.
|
[
"cheaper",
"version",
"of",
"indexOf",
";",
"instead",
"of",
"creating",
"each",
"iteration",
"new",
"str",
"."
] |
0bc1607f2468bf003a8419718f42f310b1445bd9
|
https://github.com/a8m/angular-filter/blob/0bc1607f2468bf003a8419718f42f310b1445bd9/src/_common.js#L65-L72
|
13,044
|
css/csso
|
lib/restructure/utils.js
|
hasSimilarSelectors
|
function hasSimilarSelectors(selectors1, selectors2) {
var cursor1 = selectors1.head;
while (cursor1 !== null) {
var cursor2 = selectors2.head;
while (cursor2 !== null) {
if (cursor1.data.compareMarker === cursor2.data.compareMarker) {
return true;
}
cursor2 = cursor2.next;
}
cursor1 = cursor1.next;
}
return false;
}
|
javascript
|
function hasSimilarSelectors(selectors1, selectors2) {
var cursor1 = selectors1.head;
while (cursor1 !== null) {
var cursor2 = selectors2.head;
while (cursor2 !== null) {
if (cursor1.data.compareMarker === cursor2.data.compareMarker) {
return true;
}
cursor2 = cursor2.next;
}
cursor1 = cursor1.next;
}
return false;
}
|
[
"function",
"hasSimilarSelectors",
"(",
"selectors1",
",",
"selectors2",
")",
"{",
"var",
"cursor1",
"=",
"selectors1",
".",
"head",
";",
"while",
"(",
"cursor1",
"!==",
"null",
")",
"{",
"var",
"cursor2",
"=",
"selectors2",
".",
"head",
";",
"while",
"(",
"cursor2",
"!==",
"null",
")",
"{",
"if",
"(",
"cursor1",
".",
"data",
".",
"compareMarker",
"===",
"cursor2",
".",
"data",
".",
"compareMarker",
")",
"{",
"return",
"true",
";",
"}",
"cursor2",
"=",
"cursor2",
".",
"next",
";",
"}",
"cursor1",
"=",
"cursor1",
".",
"next",
";",
"}",
"return",
"false",
";",
"}"
] |
check if simpleselectors has no equal specificity and element selector
|
[
"check",
"if",
"simpleselectors",
"has",
"no",
"equal",
"specificity",
"and",
"element",
"selector"
] |
3f2ce359996e28548ee1ba48e35640f311137b3f
|
https://github.com/css/csso/blob/3f2ce359996e28548ee1ba48e35640f311137b3f/lib/restructure/utils.js#L101-L119
|
13,045
|
css/csso
|
lib/restructure/utils.js
|
unsafeToSkipNode
|
function unsafeToSkipNode(node) {
switch (node.type) {
case 'Rule':
// unsafe skip ruleset with selector similarities
return hasSimilarSelectors(node.prelude.children, this);
case 'Atrule':
// can skip at-rules with blocks
if (node.block) {
// unsafe skip at-rule if block contains something unsafe to skip
return node.block.children.some(unsafeToSkipNode, this);
}
break;
case 'Declaration':
return false;
}
// unsafe by default
return true;
}
|
javascript
|
function unsafeToSkipNode(node) {
switch (node.type) {
case 'Rule':
// unsafe skip ruleset with selector similarities
return hasSimilarSelectors(node.prelude.children, this);
case 'Atrule':
// can skip at-rules with blocks
if (node.block) {
// unsafe skip at-rule if block contains something unsafe to skip
return node.block.children.some(unsafeToSkipNode, this);
}
break;
case 'Declaration':
return false;
}
// unsafe by default
return true;
}
|
[
"function",
"unsafeToSkipNode",
"(",
"node",
")",
"{",
"switch",
"(",
"node",
".",
"type",
")",
"{",
"case",
"'Rule'",
":",
"// unsafe skip ruleset with selector similarities",
"return",
"hasSimilarSelectors",
"(",
"node",
".",
"prelude",
".",
"children",
",",
"this",
")",
";",
"case",
"'Atrule'",
":",
"// can skip at-rules with blocks",
"if",
"(",
"node",
".",
"block",
")",
"{",
"// unsafe skip at-rule if block contains something unsafe to skip",
"return",
"node",
".",
"block",
".",
"children",
".",
"some",
"(",
"unsafeToSkipNode",
",",
"this",
")",
";",
"}",
"break",
";",
"case",
"'Declaration'",
":",
"return",
"false",
";",
"}",
"// unsafe by default",
"return",
"true",
";",
"}"
] |
test node can't to be skipped
|
[
"test",
"node",
"can",
"t",
"to",
"be",
"skipped"
] |
3f2ce359996e28548ee1ba48e35640f311137b3f
|
https://github.com/css/csso/blob/3f2ce359996e28548ee1ba48e35640f311137b3f/lib/restructure/utils.js#L122-L142
|
13,046
|
SupremeTechnopriest/react-idle-timer
|
src/index.js
|
throttled
|
function throttled (fn, delay) {
let lastCall = 0
return function (...args) {
const now = new Date().getTime()
if (now - lastCall < delay) {
return
}
lastCall = now
return fn(...args)
}
}
|
javascript
|
function throttled (fn, delay) {
let lastCall = 0
return function (...args) {
const now = new Date().getTime()
if (now - lastCall < delay) {
return
}
lastCall = now
return fn(...args)
}
}
|
[
"function",
"throttled",
"(",
"fn",
",",
"delay",
")",
"{",
"let",
"lastCall",
"=",
"0",
"return",
"function",
"(",
"...",
"args",
")",
"{",
"const",
"now",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"if",
"(",
"now",
"-",
"lastCall",
"<",
"delay",
")",
"{",
"return",
"}",
"lastCall",
"=",
"now",
"return",
"fn",
"(",
"...",
"args",
")",
"}",
"}"
] |
Creates a throttled function that only invokes func at most
once per every wait milliseconds.
@name throttled
@param {Function} fn Function to debounce
@param {Number} delay How long to wait
@return {Function} Executed Function
|
[
"Creates",
"a",
"throttled",
"function",
"that",
"only",
"invokes",
"func",
"at",
"most",
"once",
"per",
"every",
"wait",
"milliseconds",
"."
] |
5cb71957dd3b1bbe27e475b31898f1673856e8dd
|
https://github.com/SupremeTechnopriest/react-idle-timer/blob/5cb71957dd3b1bbe27e475b31898f1673856e8dd/src/index.js#L586-L596
|
13,047
|
yaacov/node-modbus-serial
|
ports/rtubufferedport.js
|
function(path, options) {
var self = this;
// options
if (typeof(options) === "undefined") options = {};
// disable auto open, as we handle the open
options.autoOpen = false;
// internal buffer
this._buffer = Buffer.alloc(0);
this._id = 0;
this._cmd = 0;
this._length = 0;
// create the SerialPort
this._client = new SerialPort(path, options);
// register the port data event
this._client.on("data", function onData(data) {
// add data to buffer
self._buffer = Buffer.concat([self._buffer, data]);
// check if buffer include a complete modbus answer
var expectedLength = self._length;
var bufferLength = self._buffer.length;
modbusSerialDebug({ action: "receive serial rtu buffered port", data: data, buffer: self._buffer });
// check data length
if (expectedLength < MIN_DATA_LENGTH || bufferLength < EXCEPTION_LENGTH) return;
// check buffer size for MAX_BUFFER_SIZE
if (bufferLength > MAX_BUFFER_LENGTH) {
self._buffer = self._buffer.slice(-MAX_BUFFER_LENGTH);
bufferLength = MAX_BUFFER_LENGTH;
}
// loop and check length-sized buffer chunks
var maxOffset = bufferLength - EXCEPTION_LENGTH;
for (var i = 0; i <= maxOffset; i++) {
var unitId = self._buffer[i];
var functionCode = self._buffer[i + 1];
if (unitId !== self._id) continue;
if (functionCode === self._cmd && i + expectedLength <= bufferLength) {
self._emitData(i, expectedLength);
return;
}
if (functionCode === (0x80 | self._cmd) && i + EXCEPTION_LENGTH <= bufferLength) {
self._emitData(i, EXCEPTION_LENGTH);
return;
}
// frame header matches, but still missing bytes pending
if (functionCode === (0x7f & self._cmd)) break;
}
});
/**
* Check if port is open.
*
* @returns {boolean}
*/
Object.defineProperty(this, "isOpen", {
enumerable: true,
get: function() {
return this._client.isOpen;
}
});
EventEmitter.call(this);
}
|
javascript
|
function(path, options) {
var self = this;
// options
if (typeof(options) === "undefined") options = {};
// disable auto open, as we handle the open
options.autoOpen = false;
// internal buffer
this._buffer = Buffer.alloc(0);
this._id = 0;
this._cmd = 0;
this._length = 0;
// create the SerialPort
this._client = new SerialPort(path, options);
// register the port data event
this._client.on("data", function onData(data) {
// add data to buffer
self._buffer = Buffer.concat([self._buffer, data]);
// check if buffer include a complete modbus answer
var expectedLength = self._length;
var bufferLength = self._buffer.length;
modbusSerialDebug({ action: "receive serial rtu buffered port", data: data, buffer: self._buffer });
// check data length
if (expectedLength < MIN_DATA_LENGTH || bufferLength < EXCEPTION_LENGTH) return;
// check buffer size for MAX_BUFFER_SIZE
if (bufferLength > MAX_BUFFER_LENGTH) {
self._buffer = self._buffer.slice(-MAX_BUFFER_LENGTH);
bufferLength = MAX_BUFFER_LENGTH;
}
// loop and check length-sized buffer chunks
var maxOffset = bufferLength - EXCEPTION_LENGTH;
for (var i = 0; i <= maxOffset; i++) {
var unitId = self._buffer[i];
var functionCode = self._buffer[i + 1];
if (unitId !== self._id) continue;
if (functionCode === self._cmd && i + expectedLength <= bufferLength) {
self._emitData(i, expectedLength);
return;
}
if (functionCode === (0x80 | self._cmd) && i + EXCEPTION_LENGTH <= bufferLength) {
self._emitData(i, EXCEPTION_LENGTH);
return;
}
// frame header matches, but still missing bytes pending
if (functionCode === (0x7f & self._cmd)) break;
}
});
/**
* Check if port is open.
*
* @returns {boolean}
*/
Object.defineProperty(this, "isOpen", {
enumerable: true,
get: function() {
return this._client.isOpen;
}
});
EventEmitter.call(this);
}
|
[
"function",
"(",
"path",
",",
"options",
")",
"{",
"var",
"self",
"=",
"this",
";",
"// options",
"if",
"(",
"typeof",
"(",
"options",
")",
"===",
"\"undefined\"",
")",
"options",
"=",
"{",
"}",
";",
"// disable auto open, as we handle the open",
"options",
".",
"autoOpen",
"=",
"false",
";",
"// internal buffer",
"this",
".",
"_buffer",
"=",
"Buffer",
".",
"alloc",
"(",
"0",
")",
";",
"this",
".",
"_id",
"=",
"0",
";",
"this",
".",
"_cmd",
"=",
"0",
";",
"this",
".",
"_length",
"=",
"0",
";",
"// create the SerialPort",
"this",
".",
"_client",
"=",
"new",
"SerialPort",
"(",
"path",
",",
"options",
")",
";",
"// register the port data event",
"this",
".",
"_client",
".",
"on",
"(",
"\"data\"",
",",
"function",
"onData",
"(",
"data",
")",
"{",
"// add data to buffer",
"self",
".",
"_buffer",
"=",
"Buffer",
".",
"concat",
"(",
"[",
"self",
".",
"_buffer",
",",
"data",
"]",
")",
";",
"// check if buffer include a complete modbus answer",
"var",
"expectedLength",
"=",
"self",
".",
"_length",
";",
"var",
"bufferLength",
"=",
"self",
".",
"_buffer",
".",
"length",
";",
"modbusSerialDebug",
"(",
"{",
"action",
":",
"\"receive serial rtu buffered port\"",
",",
"data",
":",
"data",
",",
"buffer",
":",
"self",
".",
"_buffer",
"}",
")",
";",
"// check data length",
"if",
"(",
"expectedLength",
"<",
"MIN_DATA_LENGTH",
"||",
"bufferLength",
"<",
"EXCEPTION_LENGTH",
")",
"return",
";",
"// check buffer size for MAX_BUFFER_SIZE",
"if",
"(",
"bufferLength",
">",
"MAX_BUFFER_LENGTH",
")",
"{",
"self",
".",
"_buffer",
"=",
"self",
".",
"_buffer",
".",
"slice",
"(",
"-",
"MAX_BUFFER_LENGTH",
")",
";",
"bufferLength",
"=",
"MAX_BUFFER_LENGTH",
";",
"}",
"// loop and check length-sized buffer chunks",
"var",
"maxOffset",
"=",
"bufferLength",
"-",
"EXCEPTION_LENGTH",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<=",
"maxOffset",
";",
"i",
"++",
")",
"{",
"var",
"unitId",
"=",
"self",
".",
"_buffer",
"[",
"i",
"]",
";",
"var",
"functionCode",
"=",
"self",
".",
"_buffer",
"[",
"i",
"+",
"1",
"]",
";",
"if",
"(",
"unitId",
"!==",
"self",
".",
"_id",
")",
"continue",
";",
"if",
"(",
"functionCode",
"===",
"self",
".",
"_cmd",
"&&",
"i",
"+",
"expectedLength",
"<=",
"bufferLength",
")",
"{",
"self",
".",
"_emitData",
"(",
"i",
",",
"expectedLength",
")",
";",
"return",
";",
"}",
"if",
"(",
"functionCode",
"===",
"(",
"0x80",
"|",
"self",
".",
"_cmd",
")",
"&&",
"i",
"+",
"EXCEPTION_LENGTH",
"<=",
"bufferLength",
")",
"{",
"self",
".",
"_emitData",
"(",
"i",
",",
"EXCEPTION_LENGTH",
")",
";",
"return",
";",
"}",
"// frame header matches, but still missing bytes pending",
"if",
"(",
"functionCode",
"===",
"(",
"0x7f",
"&",
"self",
".",
"_cmd",
")",
")",
"break",
";",
"}",
"}",
")",
";",
"/**\n * Check if port is open.\n *\n * @returns {boolean}\n */",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"\"isOpen\"",
",",
"{",
"enumerable",
":",
"true",
",",
"get",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"_client",
".",
"isOpen",
";",
"}",
"}",
")",
";",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"}"
] |
Simulate a modbus-RTU port using buffered serial connection.
@param path
@param options
@constructor
|
[
"Simulate",
"a",
"modbus",
"-",
"RTU",
"port",
"using",
"buffered",
"serial",
"connection",
"."
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/ports/rtubufferedport.js#L20-L93
|
|
13,048
|
yaacov/node-modbus-serial
|
examples/logger.js
|
checkError
|
function checkError(e) {
if(e.errno && networkErrors.includes(e.errno)) {
console.log("we have to reconnect");
// close port
client.close();
// re open client
client = new ModbusRTU();
timeoutConnectRef = setTimeout(connect, 1000);
}
}
|
javascript
|
function checkError(e) {
if(e.errno && networkErrors.includes(e.errno)) {
console.log("we have to reconnect");
// close port
client.close();
// re open client
client = new ModbusRTU();
timeoutConnectRef = setTimeout(connect, 1000);
}
}
|
[
"function",
"checkError",
"(",
"e",
")",
"{",
"if",
"(",
"e",
".",
"errno",
"&&",
"networkErrors",
".",
"includes",
"(",
"e",
".",
"errno",
")",
")",
"{",
"console",
".",
"log",
"(",
"\"we have to reconnect\"",
")",
";",
"// close port",
"client",
".",
"close",
"(",
")",
";",
"// re open client",
"client",
"=",
"new",
"ModbusRTU",
"(",
")",
";",
"timeoutConnectRef",
"=",
"setTimeout",
"(",
"connect",
",",
"1000",
")",
";",
"}",
"}"
] |
check error, and reconnect if needed
|
[
"check",
"error",
"and",
"reconnect",
"if",
"needed"
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/examples/logger.js#L13-L24
|
13,049
|
yaacov/node-modbus-serial
|
examples/logger.js
|
connect
|
function connect() {
// clear pending timeouts
clearTimeout(timeoutConnectRef);
// if client already open, just run
if (client.isOpen) {
run();
}
// if client closed, open a new connection
client.connectTCP("127.0.0.1", { port: 8502 })
.then(setClient)
.then(function() {
console.log("Connected"); })
.catch(function(e) {
checkError(e);
console.log(e.message); });
}
|
javascript
|
function connect() {
// clear pending timeouts
clearTimeout(timeoutConnectRef);
// if client already open, just run
if (client.isOpen) {
run();
}
// if client closed, open a new connection
client.connectTCP("127.0.0.1", { port: 8502 })
.then(setClient)
.then(function() {
console.log("Connected"); })
.catch(function(e) {
checkError(e);
console.log(e.message); });
}
|
[
"function",
"connect",
"(",
")",
"{",
"// clear pending timeouts",
"clearTimeout",
"(",
"timeoutConnectRef",
")",
";",
"// if client already open, just run",
"if",
"(",
"client",
".",
"isOpen",
")",
"{",
"run",
"(",
")",
";",
"}",
"// if client closed, open a new connection",
"client",
".",
"connectTCP",
"(",
"\"127.0.0.1\"",
",",
"{",
"port",
":",
"8502",
"}",
")",
".",
"then",
"(",
"setClient",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"console",
".",
"log",
"(",
"\"Connected\"",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"e",
")",
"{",
"checkError",
"(",
"e",
")",
";",
"console",
".",
"log",
"(",
"e",
".",
"message",
")",
";",
"}",
")",
";",
"}"
] |
open connection to a serial port
|
[
"open",
"connection",
"to",
"a",
"serial",
"port"
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/examples/logger.js#L27-L44
|
13,050
|
yaacov/node-modbus-serial
|
ports/asciiport.js
|
_asciiEncodeRequestBuffer
|
function _asciiEncodeRequestBuffer(buf) {
// replace the 2 byte crc16 with a single byte lrc
buf.writeUInt8(calculateLrc(buf.slice(0, -2)), buf.length - 2);
// create a new buffer of the correct size
var bufAscii = Buffer.alloc(buf.length * 2 + 1); // 1 byte start delimit + x2 data as ascii encoded + 2 lrc + 2 end delimit
// create the ascii payload
// start with the single start delimiter
bufAscii.write(":", 0);
// encode the data, with the new single byte lrc
bufAscii.write(buf.toString("hex", 0, buf.length - 1).toUpperCase(), 1);
// end with the two end delimiters
bufAscii.write("\r", bufAscii.length - 2);
bufAscii.write("\n", bufAscii.length - 1);
return bufAscii;
}
|
javascript
|
function _asciiEncodeRequestBuffer(buf) {
// replace the 2 byte crc16 with a single byte lrc
buf.writeUInt8(calculateLrc(buf.slice(0, -2)), buf.length - 2);
// create a new buffer of the correct size
var bufAscii = Buffer.alloc(buf.length * 2 + 1); // 1 byte start delimit + x2 data as ascii encoded + 2 lrc + 2 end delimit
// create the ascii payload
// start with the single start delimiter
bufAscii.write(":", 0);
// encode the data, with the new single byte lrc
bufAscii.write(buf.toString("hex", 0, buf.length - 1).toUpperCase(), 1);
// end with the two end delimiters
bufAscii.write("\r", bufAscii.length - 2);
bufAscii.write("\n", bufAscii.length - 1);
return bufAscii;
}
|
[
"function",
"_asciiEncodeRequestBuffer",
"(",
"buf",
")",
"{",
"// replace the 2 byte crc16 with a single byte lrc",
"buf",
".",
"writeUInt8",
"(",
"calculateLrc",
"(",
"buf",
".",
"slice",
"(",
"0",
",",
"-",
"2",
")",
")",
",",
"buf",
".",
"length",
"-",
"2",
")",
";",
"// create a new buffer of the correct size",
"var",
"bufAscii",
"=",
"Buffer",
".",
"alloc",
"(",
"buf",
".",
"length",
"*",
"2",
"+",
"1",
")",
";",
"// 1 byte start delimit + x2 data as ascii encoded + 2 lrc + 2 end delimit",
"// create the ascii payload",
"// start with the single start delimiter",
"bufAscii",
".",
"write",
"(",
"\":\"",
",",
"0",
")",
";",
"// encode the data, with the new single byte lrc",
"bufAscii",
".",
"write",
"(",
"buf",
".",
"toString",
"(",
"\"hex\"",
",",
"0",
",",
"buf",
".",
"length",
"-",
"1",
")",
".",
"toUpperCase",
"(",
")",
",",
"1",
")",
";",
"// end with the two end delimiters",
"bufAscii",
".",
"write",
"(",
"\"\\r\"",
",",
"bufAscii",
".",
"length",
"-",
"2",
")",
";",
"bufAscii",
".",
"write",
"(",
"\"\\n\"",
",",
"bufAscii",
".",
"length",
"-",
"1",
")",
";",
"return",
"bufAscii",
";",
"}"
] |
Ascii encode a 'request' buffer and return it. This includes removing
the CRC bytes and replacing them with an LRC.
@param {Buffer} buf the data buffer to encode.
@return {Buffer} the ascii encoded buffer
@private
|
[
"Ascii",
"encode",
"a",
"request",
"buffer",
"and",
"return",
"it",
".",
"This",
"includes",
"removing",
"the",
"CRC",
"bytes",
"and",
"replacing",
"them",
"with",
"an",
"LRC",
"."
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/ports/asciiport.js#L22-L41
|
13,051
|
yaacov/node-modbus-serial
|
ports/asciiport.js
|
_asciiDecodeResponseBuffer
|
function _asciiDecodeResponseBuffer(bufAscii) {
// create a new buffer of the correct size (based on ascii encoded buffer length)
var bufDecoded = Buffer.alloc((bufAscii.length - 1) / 2);
// decode into new buffer (removing delimiters at start and end)
for (var i = 0; i < (bufAscii.length - 3) / 2; i++) {
bufDecoded.write(String.fromCharCode(bufAscii.readUInt8(i * 2 + 1), bufAscii.readUInt8(i * 2 + 2)), i, 1, "hex");
}
// check the lrc is true
var lrcIn = bufDecoded.readUInt8(bufDecoded.length - 2);
if(calculateLrc(bufDecoded.slice(0, -2)) !== lrcIn) {
// return null if lrc error
var calcLrc = calculateLrc(bufDecoded.slice(0, -2));
modbusSerialDebug({ action: "LRC error", LRC: lrcIn.toString(16), calcLRC: calcLrc.toString(16) });
return null;
}
// replace the 1 byte lrc with a two byte crc16
bufDecoded.writeUInt16LE(crc16(bufDecoded.slice(0, -2)), bufDecoded.length - 2);
return bufDecoded;
}
|
javascript
|
function _asciiDecodeResponseBuffer(bufAscii) {
// create a new buffer of the correct size (based on ascii encoded buffer length)
var bufDecoded = Buffer.alloc((bufAscii.length - 1) / 2);
// decode into new buffer (removing delimiters at start and end)
for (var i = 0; i < (bufAscii.length - 3) / 2; i++) {
bufDecoded.write(String.fromCharCode(bufAscii.readUInt8(i * 2 + 1), bufAscii.readUInt8(i * 2 + 2)), i, 1, "hex");
}
// check the lrc is true
var lrcIn = bufDecoded.readUInt8(bufDecoded.length - 2);
if(calculateLrc(bufDecoded.slice(0, -2)) !== lrcIn) {
// return null if lrc error
var calcLrc = calculateLrc(bufDecoded.slice(0, -2));
modbusSerialDebug({ action: "LRC error", LRC: lrcIn.toString(16), calcLRC: calcLrc.toString(16) });
return null;
}
// replace the 1 byte lrc with a two byte crc16
bufDecoded.writeUInt16LE(crc16(bufDecoded.slice(0, -2)), bufDecoded.length - 2);
return bufDecoded;
}
|
[
"function",
"_asciiDecodeResponseBuffer",
"(",
"bufAscii",
")",
"{",
"// create a new buffer of the correct size (based on ascii encoded buffer length)",
"var",
"bufDecoded",
"=",
"Buffer",
".",
"alloc",
"(",
"(",
"bufAscii",
".",
"length",
"-",
"1",
")",
"/",
"2",
")",
";",
"// decode into new buffer (removing delimiters at start and end)",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"(",
"bufAscii",
".",
"length",
"-",
"3",
")",
"/",
"2",
";",
"i",
"++",
")",
"{",
"bufDecoded",
".",
"write",
"(",
"String",
".",
"fromCharCode",
"(",
"bufAscii",
".",
"readUInt8",
"(",
"i",
"*",
"2",
"+",
"1",
")",
",",
"bufAscii",
".",
"readUInt8",
"(",
"i",
"*",
"2",
"+",
"2",
")",
")",
",",
"i",
",",
"1",
",",
"\"hex\"",
")",
";",
"}",
"// check the lrc is true",
"var",
"lrcIn",
"=",
"bufDecoded",
".",
"readUInt8",
"(",
"bufDecoded",
".",
"length",
"-",
"2",
")",
";",
"if",
"(",
"calculateLrc",
"(",
"bufDecoded",
".",
"slice",
"(",
"0",
",",
"-",
"2",
")",
")",
"!==",
"lrcIn",
")",
"{",
"// return null if lrc error",
"var",
"calcLrc",
"=",
"calculateLrc",
"(",
"bufDecoded",
".",
"slice",
"(",
"0",
",",
"-",
"2",
")",
")",
";",
"modbusSerialDebug",
"(",
"{",
"action",
":",
"\"LRC error\"",
",",
"LRC",
":",
"lrcIn",
".",
"toString",
"(",
"16",
")",
",",
"calcLRC",
":",
"calcLrc",
".",
"toString",
"(",
"16",
")",
"}",
")",
";",
"return",
"null",
";",
"}",
"// replace the 1 byte lrc with a two byte crc16",
"bufDecoded",
".",
"writeUInt16LE",
"(",
"crc16",
"(",
"bufDecoded",
".",
"slice",
"(",
"0",
",",
"-",
"2",
")",
")",
",",
"bufDecoded",
".",
"length",
"-",
"2",
")",
";",
"return",
"bufDecoded",
";",
"}"
] |
Ascii decode a 'response' buffer and return it.
@param {Buffer} bufAscii the ascii data buffer to decode.
@return {Buffer} the decoded buffer, or null if decode error
@private
|
[
"Ascii",
"decode",
"a",
"response",
"buffer",
"and",
"return",
"it",
"."
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/ports/asciiport.js#L50-L74
|
13,052
|
yaacov/node-modbus-serial
|
ports/asciiport.js
|
_checkData
|
function _checkData(modbus, buf) {
// check buffer size
if (buf.length !== modbus._length && buf.length !== 5) {
modbusSerialDebug({ action: "length error", recive: buf.length, expected: modbus._length });
return false;
}
// check buffer unit-id and command
return (buf[0] === modbus._id &&
(0x7f & buf[1]) === modbus._cmd);
}
|
javascript
|
function _checkData(modbus, buf) {
// check buffer size
if (buf.length !== modbus._length && buf.length !== 5) {
modbusSerialDebug({ action: "length error", recive: buf.length, expected: modbus._length });
return false;
}
// check buffer unit-id and command
return (buf[0] === modbus._id &&
(0x7f & buf[1]) === modbus._cmd);
}
|
[
"function",
"_checkData",
"(",
"modbus",
",",
"buf",
")",
"{",
"// check buffer size",
"if",
"(",
"buf",
".",
"length",
"!==",
"modbus",
".",
"_length",
"&&",
"buf",
".",
"length",
"!==",
"5",
")",
"{",
"modbusSerialDebug",
"(",
"{",
"action",
":",
"\"length error\"",
",",
"recive",
":",
"buf",
".",
"length",
",",
"expected",
":",
"modbus",
".",
"_length",
"}",
")",
";",
"return",
"false",
";",
"}",
"// check buffer unit-id and command",
"return",
"(",
"buf",
"[",
"0",
"]",
"===",
"modbus",
".",
"_id",
"&&",
"(",
"0x7f",
"&",
"buf",
"[",
"1",
"]",
")",
"===",
"modbus",
".",
"_cmd",
")",
";",
"}"
] |
check if a buffer chunk can be a modbus answer
or modbus exception
@param {AsciiPort} modbus
@param {Buffer} buf the buffer to check.
@return {boolean} if the buffer can be an answer
@private
|
[
"check",
"if",
"a",
"buffer",
"chunk",
"can",
"be",
"a",
"modbus",
"answer",
"or",
"modbus",
"exception"
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/ports/asciiport.js#L85-L96
|
13,053
|
yaacov/node-modbus-serial
|
ports/asciiport.js
|
function(path, options) {
var modbus = this;
// options
options = options || {};
// disable auto open, as we handle the open
options.autoOpen = false;
// internal buffer
this._buffer = Buffer.from("");
this._id = 0;
this._cmd = 0;
this._length = 0;
// create the SerialPort
this._client = new SerialPort(path, options);
// register the port data event
this._client.on("data", function(data) {
// add new data to buffer
modbus._buffer = Buffer.concat([modbus._buffer, data]);
modbusSerialDebug({ action: "receive serial ascii port", data: data, buffer: modbus._buffer });
modbusSerialDebug(JSON.stringify({ action: "receive serial ascii port strings", data: data, buffer: modbus._buffer }));
// check buffer for start delimiter
var sdIndex = modbus._buffer.indexOf(0x3A); // ascii for ':'
if(sdIndex === -1) {
// if not there, reset the buffer and return
modbus._buffer = Buffer.from("");
return;
}
// if there is data before the start delimiter, remove it
if(sdIndex > 0) {
modbus._buffer = modbus._buffer.slice(sdIndex);
}
// do we have the complete message (i.e. are the end delimiters there)
if(modbus._buffer.includes("\r\n", 1, "ascii") === true) {
// check there is no excess data after end delimiters
var edIndex = modbus._buffer.indexOf(0x0A); // ascii for '\n'
if(edIndex !== modbus._buffer.length - 1) {
// if there is, remove it
modbus._buffer = modbus._buffer.slice(0, edIndex + 1);
}
// we have what looks like a complete ascii encoded response message, so decode
var _data = _asciiDecodeResponseBuffer(modbus._buffer);
modbusSerialDebug({ action: "got EOM", data: _data, buffer: modbus._buffer });
if(_data !== null) {
// check if this is the data we are waiting for
if (_checkData(modbus, _data)) {
modbusSerialDebug({ action: "emit data serial ascii port", data: data, buffer: modbus._buffer });
modbusSerialDebug(JSON.stringify({ action: "emit data serial ascii port strings", data: data, buffer: modbus._buffer }));
// emit a data signal
modbus.emit("data", _data);
}
}
// reset the buffer now its been used
modbus._buffer = Buffer.from("");
} else {
// otherwise just wait for more data to arrive
}
});
/**
* Check if port is open.
*
* @returns {boolean}
*/
Object.defineProperty(this, "isOpen", {
enumerable: true,
get: function() {
return this._client.isOpen;
}
});
EventEmitter.call(this);
}
|
javascript
|
function(path, options) {
var modbus = this;
// options
options = options || {};
// disable auto open, as we handle the open
options.autoOpen = false;
// internal buffer
this._buffer = Buffer.from("");
this._id = 0;
this._cmd = 0;
this._length = 0;
// create the SerialPort
this._client = new SerialPort(path, options);
// register the port data event
this._client.on("data", function(data) {
// add new data to buffer
modbus._buffer = Buffer.concat([modbus._buffer, data]);
modbusSerialDebug({ action: "receive serial ascii port", data: data, buffer: modbus._buffer });
modbusSerialDebug(JSON.stringify({ action: "receive serial ascii port strings", data: data, buffer: modbus._buffer }));
// check buffer for start delimiter
var sdIndex = modbus._buffer.indexOf(0x3A); // ascii for ':'
if(sdIndex === -1) {
// if not there, reset the buffer and return
modbus._buffer = Buffer.from("");
return;
}
// if there is data before the start delimiter, remove it
if(sdIndex > 0) {
modbus._buffer = modbus._buffer.slice(sdIndex);
}
// do we have the complete message (i.e. are the end delimiters there)
if(modbus._buffer.includes("\r\n", 1, "ascii") === true) {
// check there is no excess data after end delimiters
var edIndex = modbus._buffer.indexOf(0x0A); // ascii for '\n'
if(edIndex !== modbus._buffer.length - 1) {
// if there is, remove it
modbus._buffer = modbus._buffer.slice(0, edIndex + 1);
}
// we have what looks like a complete ascii encoded response message, so decode
var _data = _asciiDecodeResponseBuffer(modbus._buffer);
modbusSerialDebug({ action: "got EOM", data: _data, buffer: modbus._buffer });
if(_data !== null) {
// check if this is the data we are waiting for
if (_checkData(modbus, _data)) {
modbusSerialDebug({ action: "emit data serial ascii port", data: data, buffer: modbus._buffer });
modbusSerialDebug(JSON.stringify({ action: "emit data serial ascii port strings", data: data, buffer: modbus._buffer }));
// emit a data signal
modbus.emit("data", _data);
}
}
// reset the buffer now its been used
modbus._buffer = Buffer.from("");
} else {
// otherwise just wait for more data to arrive
}
});
/**
* Check if port is open.
*
* @returns {boolean}
*/
Object.defineProperty(this, "isOpen", {
enumerable: true,
get: function() {
return this._client.isOpen;
}
});
EventEmitter.call(this);
}
|
[
"function",
"(",
"path",
",",
"options",
")",
"{",
"var",
"modbus",
"=",
"this",
";",
"// options",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"// disable auto open, as we handle the open",
"options",
".",
"autoOpen",
"=",
"false",
";",
"// internal buffer",
"this",
".",
"_buffer",
"=",
"Buffer",
".",
"from",
"(",
"\"\"",
")",
";",
"this",
".",
"_id",
"=",
"0",
";",
"this",
".",
"_cmd",
"=",
"0",
";",
"this",
".",
"_length",
"=",
"0",
";",
"// create the SerialPort",
"this",
".",
"_client",
"=",
"new",
"SerialPort",
"(",
"path",
",",
"options",
")",
";",
"// register the port data event",
"this",
".",
"_client",
".",
"on",
"(",
"\"data\"",
",",
"function",
"(",
"data",
")",
"{",
"// add new data to buffer",
"modbus",
".",
"_buffer",
"=",
"Buffer",
".",
"concat",
"(",
"[",
"modbus",
".",
"_buffer",
",",
"data",
"]",
")",
";",
"modbusSerialDebug",
"(",
"{",
"action",
":",
"\"receive serial ascii port\"",
",",
"data",
":",
"data",
",",
"buffer",
":",
"modbus",
".",
"_buffer",
"}",
")",
";",
"modbusSerialDebug",
"(",
"JSON",
".",
"stringify",
"(",
"{",
"action",
":",
"\"receive serial ascii port strings\"",
",",
"data",
":",
"data",
",",
"buffer",
":",
"modbus",
".",
"_buffer",
"}",
")",
")",
";",
"// check buffer for start delimiter",
"var",
"sdIndex",
"=",
"modbus",
".",
"_buffer",
".",
"indexOf",
"(",
"0x3A",
")",
";",
"// ascii for ':'",
"if",
"(",
"sdIndex",
"===",
"-",
"1",
")",
"{",
"// if not there, reset the buffer and return",
"modbus",
".",
"_buffer",
"=",
"Buffer",
".",
"from",
"(",
"\"\"",
")",
";",
"return",
";",
"}",
"// if there is data before the start delimiter, remove it",
"if",
"(",
"sdIndex",
">",
"0",
")",
"{",
"modbus",
".",
"_buffer",
"=",
"modbus",
".",
"_buffer",
".",
"slice",
"(",
"sdIndex",
")",
";",
"}",
"// do we have the complete message (i.e. are the end delimiters there)",
"if",
"(",
"modbus",
".",
"_buffer",
".",
"includes",
"(",
"\"\\r\\n\"",
",",
"1",
",",
"\"ascii\"",
")",
"===",
"true",
")",
"{",
"// check there is no excess data after end delimiters",
"var",
"edIndex",
"=",
"modbus",
".",
"_buffer",
".",
"indexOf",
"(",
"0x0A",
")",
";",
"// ascii for '\\n'",
"if",
"(",
"edIndex",
"!==",
"modbus",
".",
"_buffer",
".",
"length",
"-",
"1",
")",
"{",
"// if there is, remove it",
"modbus",
".",
"_buffer",
"=",
"modbus",
".",
"_buffer",
".",
"slice",
"(",
"0",
",",
"edIndex",
"+",
"1",
")",
";",
"}",
"// we have what looks like a complete ascii encoded response message, so decode",
"var",
"_data",
"=",
"_asciiDecodeResponseBuffer",
"(",
"modbus",
".",
"_buffer",
")",
";",
"modbusSerialDebug",
"(",
"{",
"action",
":",
"\"got EOM\"",
",",
"data",
":",
"_data",
",",
"buffer",
":",
"modbus",
".",
"_buffer",
"}",
")",
";",
"if",
"(",
"_data",
"!==",
"null",
")",
"{",
"// check if this is the data we are waiting for",
"if",
"(",
"_checkData",
"(",
"modbus",
",",
"_data",
")",
")",
"{",
"modbusSerialDebug",
"(",
"{",
"action",
":",
"\"emit data serial ascii port\"",
",",
"data",
":",
"data",
",",
"buffer",
":",
"modbus",
".",
"_buffer",
"}",
")",
";",
"modbusSerialDebug",
"(",
"JSON",
".",
"stringify",
"(",
"{",
"action",
":",
"\"emit data serial ascii port strings\"",
",",
"data",
":",
"data",
",",
"buffer",
":",
"modbus",
".",
"_buffer",
"}",
")",
")",
";",
"// emit a data signal",
"modbus",
".",
"emit",
"(",
"\"data\"",
",",
"_data",
")",
";",
"}",
"}",
"// reset the buffer now its been used",
"modbus",
".",
"_buffer",
"=",
"Buffer",
".",
"from",
"(",
"\"\"",
")",
";",
"}",
"else",
"{",
"// otherwise just wait for more data to arrive",
"}",
"}",
")",
";",
"/**\n * Check if port is open.\n *\n * @returns {boolean}\n */",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"\"isOpen\"",
",",
"{",
"enumerable",
":",
"true",
",",
"get",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"_client",
".",
"isOpen",
";",
"}",
"}",
")",
";",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"}"
] |
Simulate a modbus-ascii port using serial connection.
@param path
@param options
@constructor
|
[
"Simulate",
"a",
"modbus",
"-",
"ascii",
"port",
"using",
"serial",
"connection",
"."
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/ports/asciiport.js#L105-L185
|
|
13,054
|
yaacov/node-modbus-serial
|
index.js
|
_startTimeout
|
function _startTimeout(duration, transaction) {
if (!duration) {
return undefined;
}
return setTimeout(function() {
transaction._timeoutFired = true;
if (transaction.next) {
transaction.next(new TransactionTimedOutError());
}
}, duration);
}
|
javascript
|
function _startTimeout(duration, transaction) {
if (!duration) {
return undefined;
}
return setTimeout(function() {
transaction._timeoutFired = true;
if (transaction.next) {
transaction.next(new TransactionTimedOutError());
}
}, duration);
}
|
[
"function",
"_startTimeout",
"(",
"duration",
",",
"transaction",
")",
"{",
"if",
"(",
"!",
"duration",
")",
"{",
"return",
"undefined",
";",
"}",
"return",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"transaction",
".",
"_timeoutFired",
"=",
"true",
";",
"if",
"(",
"transaction",
".",
"next",
")",
"{",
"transaction",
".",
"next",
"(",
"new",
"TransactionTimedOutError",
"(",
")",
")",
";",
"}",
"}",
",",
"duration",
")",
";",
"}"
] |
Starts the timeout timer with the given duration.
If the timeout ends before it was cancelled, it will call the callback with an error.
@param {number} duration the timeout duration in milliseconds.
@param {Function} next the function to call next.
@return {number} The handle of the timeout
@private
|
[
"Starts",
"the",
"timeout",
"timer",
"with",
"the",
"given",
"duration",
".",
"If",
"the",
"timeout",
"ends",
"before",
"it",
"was",
"cancelled",
"it",
"will",
"call",
"the",
"callback",
"with",
"an",
"error",
"."
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/index.js#L174-L184
|
13,055
|
yaacov/node-modbus-serial
|
servers/servertcp_handler.js
|
_handlePromiseOrValue
|
function _handlePromiseOrValue(promiseOrValue, cb) {
if (promiseOrValue && promiseOrValue.then && typeof promiseOrValue.then === "function") {
promiseOrValue
.then(function(value) {
cb(null, value);
})
.catch(function(err) {
cb(err);
});
} else {
cb(null, promiseOrValue);
}
}
|
javascript
|
function _handlePromiseOrValue(promiseOrValue, cb) {
if (promiseOrValue && promiseOrValue.then && typeof promiseOrValue.then === "function") {
promiseOrValue
.then(function(value) {
cb(null, value);
})
.catch(function(err) {
cb(err);
});
} else {
cb(null, promiseOrValue);
}
}
|
[
"function",
"_handlePromiseOrValue",
"(",
"promiseOrValue",
",",
"cb",
")",
"{",
"if",
"(",
"promiseOrValue",
"&&",
"promiseOrValue",
".",
"then",
"&&",
"typeof",
"promiseOrValue",
".",
"then",
"===",
"\"function\"",
")",
"{",
"promiseOrValue",
".",
"then",
"(",
"function",
"(",
"value",
")",
"{",
"cb",
"(",
"null",
",",
"value",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"null",
",",
"promiseOrValue",
")",
";",
"}",
"}"
] |
Handle the callback invocation for Promises or synchronous values
@param promiseOrValue - the Promise to be resolved or value to be returned
@param cb - the callback to be invoked
@returns undefined
@private
|
[
"Handle",
"the",
"callback",
"invocation",
"for",
"Promises",
"or",
"synchronous",
"values"
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/servers/servertcp_handler.js#L45-L57
|
13,056
|
yaacov/node-modbus-serial
|
servers/servertcp_handler.js
|
_handleReadCoilsOrInputDiscretes
|
function _handleReadCoilsOrInputDiscretes(requestBuffer, vector, unitID, callback, fc) {
var address = requestBuffer.readUInt16BE(2);
var length = requestBuffer.readUInt16BE(4);
if (_errorRequestBufferLength(requestBuffer)) {
return;
}
// build answer
var dataBytes = parseInt((length - 1) / 8 + 1);
var responseBuffer = Buffer.alloc(3 + dataBytes + 2);
try {
responseBuffer.writeUInt8(dataBytes, 2);
}
catch (err) {
callback(err);
return;
}
var vectorCB;
if(fc === 1)
vectorCB = vector.getCoil;
else if (fc === 2)
vectorCB = vector.getDiscreteInput;
// read coils
if (vectorCB) {
var callbackInvoked = false;
var cbCount = 0;
var buildCb = function(i) {
return function(err, value) {
if (err) {
if (!callbackInvoked) {
callbackInvoked = true;
callback(err);
}
return;
}
cbCount = cbCount + 1;
responseBuffer.writeBit(value, i % 8, 3 + parseInt(i / 8));
if (cbCount === length && !callbackInvoked) {
modbusSerialDebug({ action: "FC" + fc + " response", responseBuffer: responseBuffer });
callbackInvoked = true;
callback(null, responseBuffer);
}
};
};
if (length === 0)
callback({
modbusErrorCode: 0x02, // Illegal address
msg: "Invalid length"
});
for (var i = 0; i < length; i++) {
var cb = buildCb(i);
try {
if (vectorCB.length === 3) {
vectorCB(address + i, unitID, cb);
}
else {
var promiseOrValue = vectorCB(address + i, unitID);
_handlePromiseOrValue(promiseOrValue, cb);
}
}
catch(err) {
cb(err);
}
}
}
}
|
javascript
|
function _handleReadCoilsOrInputDiscretes(requestBuffer, vector, unitID, callback, fc) {
var address = requestBuffer.readUInt16BE(2);
var length = requestBuffer.readUInt16BE(4);
if (_errorRequestBufferLength(requestBuffer)) {
return;
}
// build answer
var dataBytes = parseInt((length - 1) / 8 + 1);
var responseBuffer = Buffer.alloc(3 + dataBytes + 2);
try {
responseBuffer.writeUInt8(dataBytes, 2);
}
catch (err) {
callback(err);
return;
}
var vectorCB;
if(fc === 1)
vectorCB = vector.getCoil;
else if (fc === 2)
vectorCB = vector.getDiscreteInput;
// read coils
if (vectorCB) {
var callbackInvoked = false;
var cbCount = 0;
var buildCb = function(i) {
return function(err, value) {
if (err) {
if (!callbackInvoked) {
callbackInvoked = true;
callback(err);
}
return;
}
cbCount = cbCount + 1;
responseBuffer.writeBit(value, i % 8, 3 + parseInt(i / 8));
if (cbCount === length && !callbackInvoked) {
modbusSerialDebug({ action: "FC" + fc + " response", responseBuffer: responseBuffer });
callbackInvoked = true;
callback(null, responseBuffer);
}
};
};
if (length === 0)
callback({
modbusErrorCode: 0x02, // Illegal address
msg: "Invalid length"
});
for (var i = 0; i < length; i++) {
var cb = buildCb(i);
try {
if (vectorCB.length === 3) {
vectorCB(address + i, unitID, cb);
}
else {
var promiseOrValue = vectorCB(address + i, unitID);
_handlePromiseOrValue(promiseOrValue, cb);
}
}
catch(err) {
cb(err);
}
}
}
}
|
[
"function",
"_handleReadCoilsOrInputDiscretes",
"(",
"requestBuffer",
",",
"vector",
",",
"unitID",
",",
"callback",
",",
"fc",
")",
"{",
"var",
"address",
"=",
"requestBuffer",
".",
"readUInt16BE",
"(",
"2",
")",
";",
"var",
"length",
"=",
"requestBuffer",
".",
"readUInt16BE",
"(",
"4",
")",
";",
"if",
"(",
"_errorRequestBufferLength",
"(",
"requestBuffer",
")",
")",
"{",
"return",
";",
"}",
"// build answer",
"var",
"dataBytes",
"=",
"parseInt",
"(",
"(",
"length",
"-",
"1",
")",
"/",
"8",
"+",
"1",
")",
";",
"var",
"responseBuffer",
"=",
"Buffer",
".",
"alloc",
"(",
"3",
"+",
"dataBytes",
"+",
"2",
")",
";",
"try",
"{",
"responseBuffer",
".",
"writeUInt8",
"(",
"dataBytes",
",",
"2",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"return",
";",
"}",
"var",
"vectorCB",
";",
"if",
"(",
"fc",
"===",
"1",
")",
"vectorCB",
"=",
"vector",
".",
"getCoil",
";",
"else",
"if",
"(",
"fc",
"===",
"2",
")",
"vectorCB",
"=",
"vector",
".",
"getDiscreteInput",
";",
"// read coils",
"if",
"(",
"vectorCB",
")",
"{",
"var",
"callbackInvoked",
"=",
"false",
";",
"var",
"cbCount",
"=",
"0",
";",
"var",
"buildCb",
"=",
"function",
"(",
"i",
")",
"{",
"return",
"function",
"(",
"err",
",",
"value",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"!",
"callbackInvoked",
")",
"{",
"callbackInvoked",
"=",
"true",
";",
"callback",
"(",
"err",
")",
";",
"}",
"return",
";",
"}",
"cbCount",
"=",
"cbCount",
"+",
"1",
";",
"responseBuffer",
".",
"writeBit",
"(",
"value",
",",
"i",
"%",
"8",
",",
"3",
"+",
"parseInt",
"(",
"i",
"/",
"8",
")",
")",
";",
"if",
"(",
"cbCount",
"===",
"length",
"&&",
"!",
"callbackInvoked",
")",
"{",
"modbusSerialDebug",
"(",
"{",
"action",
":",
"\"FC\"",
"+",
"fc",
"+",
"\" response\"",
",",
"responseBuffer",
":",
"responseBuffer",
"}",
")",
";",
"callbackInvoked",
"=",
"true",
";",
"callback",
"(",
"null",
",",
"responseBuffer",
")",
";",
"}",
"}",
";",
"}",
";",
"if",
"(",
"length",
"===",
"0",
")",
"callback",
"(",
"{",
"modbusErrorCode",
":",
"0x02",
",",
"// Illegal address",
"msg",
":",
"\"Invalid length\"",
"}",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"var",
"cb",
"=",
"buildCb",
"(",
"i",
")",
";",
"try",
"{",
"if",
"(",
"vectorCB",
".",
"length",
"===",
"3",
")",
"{",
"vectorCB",
"(",
"address",
"+",
"i",
",",
"unitID",
",",
"cb",
")",
";",
"}",
"else",
"{",
"var",
"promiseOrValue",
"=",
"vectorCB",
"(",
"address",
"+",
"i",
",",
"unitID",
")",
";",
"_handlePromiseOrValue",
"(",
"promiseOrValue",
",",
"cb",
")",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
";",
"}",
"}",
"}",
"}"
] |
Function to handle FC1 or FC2 request.
@param requestBuffer - request Buffer from client
@param vector - vector of functions for read and write
@param unitID - Id of the requesting unit
@param {function} callback - callback to be invoked passing {Buffer} response
@returns undefined
@private
|
[
"Function",
"to",
"handle",
"FC1",
"or",
"FC2",
"request",
"."
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/servers/servertcp_handler.js#L70-L145
|
13,057
|
yaacov/node-modbus-serial
|
servers/servertcp_handler.js
|
_handleWriteCoil
|
function _handleWriteCoil(requestBuffer, vector, unitID, callback) {
var address = requestBuffer.readUInt16BE(2);
var state = requestBuffer.readUInt16BE(4);
if (_errorRequestBufferLength(requestBuffer)) {
return;
}
// build answer
var responseBuffer = Buffer.alloc(8);
responseBuffer.writeUInt16BE(address, 2);
responseBuffer.writeUInt16BE(state, 4);
if (vector.setCoil) {
var callbackInvoked = false;
var cb = function(err) {
if (err) {
if (!callbackInvoked) {
callbackInvoked = true;
callback(err);
}
return;
}
if (!callbackInvoked) {
modbusSerialDebug({ action: "FC5 response", responseBuffer: responseBuffer });
callbackInvoked = true;
callback(null, responseBuffer);
}
};
try {
if (vector.setCoil.length === 4) {
vector.setCoil(address, state === 0xff00, unitID, cb);
}
else {
var promiseOrValue = vector.setCoil(address, state === 0xff00, unitID);
_handlePromiseOrValue(promiseOrValue, cb);
}
}
catch(err) {
cb(err);
}
}
}
|
javascript
|
function _handleWriteCoil(requestBuffer, vector, unitID, callback) {
var address = requestBuffer.readUInt16BE(2);
var state = requestBuffer.readUInt16BE(4);
if (_errorRequestBufferLength(requestBuffer)) {
return;
}
// build answer
var responseBuffer = Buffer.alloc(8);
responseBuffer.writeUInt16BE(address, 2);
responseBuffer.writeUInt16BE(state, 4);
if (vector.setCoil) {
var callbackInvoked = false;
var cb = function(err) {
if (err) {
if (!callbackInvoked) {
callbackInvoked = true;
callback(err);
}
return;
}
if (!callbackInvoked) {
modbusSerialDebug({ action: "FC5 response", responseBuffer: responseBuffer });
callbackInvoked = true;
callback(null, responseBuffer);
}
};
try {
if (vector.setCoil.length === 4) {
vector.setCoil(address, state === 0xff00, unitID, cb);
}
else {
var promiseOrValue = vector.setCoil(address, state === 0xff00, unitID);
_handlePromiseOrValue(promiseOrValue, cb);
}
}
catch(err) {
cb(err);
}
}
}
|
[
"function",
"_handleWriteCoil",
"(",
"requestBuffer",
",",
"vector",
",",
"unitID",
",",
"callback",
")",
"{",
"var",
"address",
"=",
"requestBuffer",
".",
"readUInt16BE",
"(",
"2",
")",
";",
"var",
"state",
"=",
"requestBuffer",
".",
"readUInt16BE",
"(",
"4",
")",
";",
"if",
"(",
"_errorRequestBufferLength",
"(",
"requestBuffer",
")",
")",
"{",
"return",
";",
"}",
"// build answer",
"var",
"responseBuffer",
"=",
"Buffer",
".",
"alloc",
"(",
"8",
")",
";",
"responseBuffer",
".",
"writeUInt16BE",
"(",
"address",
",",
"2",
")",
";",
"responseBuffer",
".",
"writeUInt16BE",
"(",
"state",
",",
"4",
")",
";",
"if",
"(",
"vector",
".",
"setCoil",
")",
"{",
"var",
"callbackInvoked",
"=",
"false",
";",
"var",
"cb",
"=",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"!",
"callbackInvoked",
")",
"{",
"callbackInvoked",
"=",
"true",
";",
"callback",
"(",
"err",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"!",
"callbackInvoked",
")",
"{",
"modbusSerialDebug",
"(",
"{",
"action",
":",
"\"FC5 response\"",
",",
"responseBuffer",
":",
"responseBuffer",
"}",
")",
";",
"callbackInvoked",
"=",
"true",
";",
"callback",
"(",
"null",
",",
"responseBuffer",
")",
";",
"}",
"}",
";",
"try",
"{",
"if",
"(",
"vector",
".",
"setCoil",
".",
"length",
"===",
"4",
")",
"{",
"vector",
".",
"setCoil",
"(",
"address",
",",
"state",
"===",
"0xff00",
",",
"unitID",
",",
"cb",
")",
";",
"}",
"else",
"{",
"var",
"promiseOrValue",
"=",
"vector",
".",
"setCoil",
"(",
"address",
",",
"state",
"===",
"0xff00",
",",
"unitID",
")",
";",
"_handlePromiseOrValue",
"(",
"promiseOrValue",
",",
"cb",
")",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
";",
"}",
"}",
"}"
] |
Function to handle FC5 request.
@param requestBuffer - request Buffer from client
@param vector - vector of functions for read and write
@param unitID - Id of the requesting unit
@param {function} callback - callback to be invoked passing {Buffer} response
@returns undefined
@private
|
[
"Function",
"to",
"handle",
"FC5",
"request",
"."
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/servers/servertcp_handler.js#L408-L454
|
13,058
|
yaacov/node-modbus-serial
|
servers/servertcp_handler.js
|
_handleWriteSingleRegister
|
function _handleWriteSingleRegister(requestBuffer, vector, unitID, callback) {
var address = requestBuffer.readUInt16BE(2);
var value = requestBuffer.readUInt16BE(4);
if (_errorRequestBufferLength(requestBuffer)) {
return;
}
// build answer
var responseBuffer = Buffer.alloc(8);
responseBuffer.writeUInt16BE(address, 2);
responseBuffer.writeUInt16BE(value, 4);
if (vector.setRegister) {
var callbackInvoked = false;
var cb = function(err) {
if (err) {
if (!callbackInvoked) {
callbackInvoked = true;
callback(err);
}
return;
}
if (!callbackInvoked) {
modbusSerialDebug({ action: "FC6 response", responseBuffer: responseBuffer });
callbackInvoked = true;
callback(null, responseBuffer);
}
};
try {
if (vector.setRegister.length === 4) {
vector.setRegister(address, value, unitID, cb);
}
else {
var promiseOrValue = vector.setRegister(address, value, unitID);
_handlePromiseOrValue(promiseOrValue, cb);
}
} catch(err) {
cb(err);
}
}
}
|
javascript
|
function _handleWriteSingleRegister(requestBuffer, vector, unitID, callback) {
var address = requestBuffer.readUInt16BE(2);
var value = requestBuffer.readUInt16BE(4);
if (_errorRequestBufferLength(requestBuffer)) {
return;
}
// build answer
var responseBuffer = Buffer.alloc(8);
responseBuffer.writeUInt16BE(address, 2);
responseBuffer.writeUInt16BE(value, 4);
if (vector.setRegister) {
var callbackInvoked = false;
var cb = function(err) {
if (err) {
if (!callbackInvoked) {
callbackInvoked = true;
callback(err);
}
return;
}
if (!callbackInvoked) {
modbusSerialDebug({ action: "FC6 response", responseBuffer: responseBuffer });
callbackInvoked = true;
callback(null, responseBuffer);
}
};
try {
if (vector.setRegister.length === 4) {
vector.setRegister(address, value, unitID, cb);
}
else {
var promiseOrValue = vector.setRegister(address, value, unitID);
_handlePromiseOrValue(promiseOrValue, cb);
}
} catch(err) {
cb(err);
}
}
}
|
[
"function",
"_handleWriteSingleRegister",
"(",
"requestBuffer",
",",
"vector",
",",
"unitID",
",",
"callback",
")",
"{",
"var",
"address",
"=",
"requestBuffer",
".",
"readUInt16BE",
"(",
"2",
")",
";",
"var",
"value",
"=",
"requestBuffer",
".",
"readUInt16BE",
"(",
"4",
")",
";",
"if",
"(",
"_errorRequestBufferLength",
"(",
"requestBuffer",
")",
")",
"{",
"return",
";",
"}",
"// build answer",
"var",
"responseBuffer",
"=",
"Buffer",
".",
"alloc",
"(",
"8",
")",
";",
"responseBuffer",
".",
"writeUInt16BE",
"(",
"address",
",",
"2",
")",
";",
"responseBuffer",
".",
"writeUInt16BE",
"(",
"value",
",",
"4",
")",
";",
"if",
"(",
"vector",
".",
"setRegister",
")",
"{",
"var",
"callbackInvoked",
"=",
"false",
";",
"var",
"cb",
"=",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"!",
"callbackInvoked",
")",
"{",
"callbackInvoked",
"=",
"true",
";",
"callback",
"(",
"err",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"!",
"callbackInvoked",
")",
"{",
"modbusSerialDebug",
"(",
"{",
"action",
":",
"\"FC6 response\"",
",",
"responseBuffer",
":",
"responseBuffer",
"}",
")",
";",
"callbackInvoked",
"=",
"true",
";",
"callback",
"(",
"null",
",",
"responseBuffer",
")",
";",
"}",
"}",
";",
"try",
"{",
"if",
"(",
"vector",
".",
"setRegister",
".",
"length",
"===",
"4",
")",
"{",
"vector",
".",
"setRegister",
"(",
"address",
",",
"value",
",",
"unitID",
",",
"cb",
")",
";",
"}",
"else",
"{",
"var",
"promiseOrValue",
"=",
"vector",
".",
"setRegister",
"(",
"address",
",",
"value",
",",
"unitID",
")",
";",
"_handlePromiseOrValue",
"(",
"promiseOrValue",
",",
"cb",
")",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
";",
"}",
"}",
"}"
] |
Function to handle FC6 request.
@param requestBuffer - request Buffer from client
@param vector - vector of functions for read and write
@param unitID - Id of the requesting unit
@param {function} callback - callback to be invoked passing {Buffer} response
@returns undefined
@private
|
[
"Function",
"to",
"handle",
"FC6",
"request",
"."
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/servers/servertcp_handler.js#L466-L511
|
13,059
|
yaacov/node-modbus-serial
|
servers/servertcp_handler.js
|
_handleForceMultipleCoils
|
function _handleForceMultipleCoils(requestBuffer, vector, unitID, callback) {
var address = requestBuffer.readUInt16BE(2);
var length = requestBuffer.readUInt16BE(4);
// if length is bad, ignore message
if (requestBuffer.length !== 7 + Math.ceil(length / 8) + 2) {
return;
}
// build answer
var responseBuffer = Buffer.alloc(8);
responseBuffer.writeUInt16BE(address, 2);
responseBuffer.writeUInt16BE(length, 4);
var callbackInvoked = false;
var cbCount = 0;
var buildCb = function(/* i - not used at the moment */) {
return function(err) {
if (err) {
if (!callbackInvoked) {
callbackInvoked = true;
callback(err);
}
return;
}
cbCount = cbCount + 1;
if (cbCount === length && !callbackInvoked) {
modbusSerialDebug({ action: "FC15 response", responseBuffer: responseBuffer });
callbackInvoked = true;
callback(null, responseBuffer);
}
};
};
if (length === 0)
callback({
modbusErrorCode: 0x02, // Illegal address
msg: "Invalid length"
});
if (vector.setCoil) {
var state;
for (var i = 0; i < length; i++) {
var cb = buildCb(i);
state = requestBuffer.readBit(i, 7);
try {
if (vector.setCoil.length === 4) {
vector.setCoil(address + i, state !== false, unitID, cb);
}
else {
var promiseOrValue = vector.setCoil(address + i, state !== false, unitID);
_handlePromiseOrValue(promiseOrValue, cb);
}
}
catch(err) {
cb(err);
}
}
} else if (vector.setCoilArray) {
state = [];
for (i = 0; i < length; i++) {
cb = buildCb(i);
state.push(requestBuffer.readBit(i, 7));
_handlePromiseOrValue(promiseOrValue, cb);
}
try {
if (vector.setCoilArray.length === 4) {
vector.setCoilArray(address, state, unitID, cb);
}
else {
vector.setCoilArray(address, state, unitID);
}
}
catch(err) {
cb(err);
}
}
}
|
javascript
|
function _handleForceMultipleCoils(requestBuffer, vector, unitID, callback) {
var address = requestBuffer.readUInt16BE(2);
var length = requestBuffer.readUInt16BE(4);
// if length is bad, ignore message
if (requestBuffer.length !== 7 + Math.ceil(length / 8) + 2) {
return;
}
// build answer
var responseBuffer = Buffer.alloc(8);
responseBuffer.writeUInt16BE(address, 2);
responseBuffer.writeUInt16BE(length, 4);
var callbackInvoked = false;
var cbCount = 0;
var buildCb = function(/* i - not used at the moment */) {
return function(err) {
if (err) {
if (!callbackInvoked) {
callbackInvoked = true;
callback(err);
}
return;
}
cbCount = cbCount + 1;
if (cbCount === length && !callbackInvoked) {
modbusSerialDebug({ action: "FC15 response", responseBuffer: responseBuffer });
callbackInvoked = true;
callback(null, responseBuffer);
}
};
};
if (length === 0)
callback({
modbusErrorCode: 0x02, // Illegal address
msg: "Invalid length"
});
if (vector.setCoil) {
var state;
for (var i = 0; i < length; i++) {
var cb = buildCb(i);
state = requestBuffer.readBit(i, 7);
try {
if (vector.setCoil.length === 4) {
vector.setCoil(address + i, state !== false, unitID, cb);
}
else {
var promiseOrValue = vector.setCoil(address + i, state !== false, unitID);
_handlePromiseOrValue(promiseOrValue, cb);
}
}
catch(err) {
cb(err);
}
}
} else if (vector.setCoilArray) {
state = [];
for (i = 0; i < length; i++) {
cb = buildCb(i);
state.push(requestBuffer.readBit(i, 7));
_handlePromiseOrValue(promiseOrValue, cb);
}
try {
if (vector.setCoilArray.length === 4) {
vector.setCoilArray(address, state, unitID, cb);
}
else {
vector.setCoilArray(address, state, unitID);
}
}
catch(err) {
cb(err);
}
}
}
|
[
"function",
"_handleForceMultipleCoils",
"(",
"requestBuffer",
",",
"vector",
",",
"unitID",
",",
"callback",
")",
"{",
"var",
"address",
"=",
"requestBuffer",
".",
"readUInt16BE",
"(",
"2",
")",
";",
"var",
"length",
"=",
"requestBuffer",
".",
"readUInt16BE",
"(",
"4",
")",
";",
"// if length is bad, ignore message",
"if",
"(",
"requestBuffer",
".",
"length",
"!==",
"7",
"+",
"Math",
".",
"ceil",
"(",
"length",
"/",
"8",
")",
"+",
"2",
")",
"{",
"return",
";",
"}",
"// build answer",
"var",
"responseBuffer",
"=",
"Buffer",
".",
"alloc",
"(",
"8",
")",
";",
"responseBuffer",
".",
"writeUInt16BE",
"(",
"address",
",",
"2",
")",
";",
"responseBuffer",
".",
"writeUInt16BE",
"(",
"length",
",",
"4",
")",
";",
"var",
"callbackInvoked",
"=",
"false",
";",
"var",
"cbCount",
"=",
"0",
";",
"var",
"buildCb",
"=",
"function",
"(",
"/* i - not used at the moment */",
")",
"{",
"return",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"!",
"callbackInvoked",
")",
"{",
"callbackInvoked",
"=",
"true",
";",
"callback",
"(",
"err",
")",
";",
"}",
"return",
";",
"}",
"cbCount",
"=",
"cbCount",
"+",
"1",
";",
"if",
"(",
"cbCount",
"===",
"length",
"&&",
"!",
"callbackInvoked",
")",
"{",
"modbusSerialDebug",
"(",
"{",
"action",
":",
"\"FC15 response\"",
",",
"responseBuffer",
":",
"responseBuffer",
"}",
")",
";",
"callbackInvoked",
"=",
"true",
";",
"callback",
"(",
"null",
",",
"responseBuffer",
")",
";",
"}",
"}",
";",
"}",
";",
"if",
"(",
"length",
"===",
"0",
")",
"callback",
"(",
"{",
"modbusErrorCode",
":",
"0x02",
",",
"// Illegal address",
"msg",
":",
"\"Invalid length\"",
"}",
")",
";",
"if",
"(",
"vector",
".",
"setCoil",
")",
"{",
"var",
"state",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"var",
"cb",
"=",
"buildCb",
"(",
"i",
")",
";",
"state",
"=",
"requestBuffer",
".",
"readBit",
"(",
"i",
",",
"7",
")",
";",
"try",
"{",
"if",
"(",
"vector",
".",
"setCoil",
".",
"length",
"===",
"4",
")",
"{",
"vector",
".",
"setCoil",
"(",
"address",
"+",
"i",
",",
"state",
"!==",
"false",
",",
"unitID",
",",
"cb",
")",
";",
"}",
"else",
"{",
"var",
"promiseOrValue",
"=",
"vector",
".",
"setCoil",
"(",
"address",
"+",
"i",
",",
"state",
"!==",
"false",
",",
"unitID",
")",
";",
"_handlePromiseOrValue",
"(",
"promiseOrValue",
",",
"cb",
")",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"vector",
".",
"setCoilArray",
")",
"{",
"state",
"=",
"[",
"]",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"cb",
"=",
"buildCb",
"(",
"i",
")",
";",
"state",
".",
"push",
"(",
"requestBuffer",
".",
"readBit",
"(",
"i",
",",
"7",
")",
")",
";",
"_handlePromiseOrValue",
"(",
"promiseOrValue",
",",
"cb",
")",
";",
"}",
"try",
"{",
"if",
"(",
"vector",
".",
"setCoilArray",
".",
"length",
"===",
"4",
")",
"{",
"vector",
".",
"setCoilArray",
"(",
"address",
",",
"state",
",",
"unitID",
",",
"cb",
")",
";",
"}",
"else",
"{",
"vector",
".",
"setCoilArray",
"(",
"address",
",",
"state",
",",
"unitID",
")",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
";",
"}",
"}",
"}"
] |
Function to handle FC15 request.
@param requestBuffer - request Buffer from client
@param vector - vector of functions for read and write
@param unitID - Id of the requesting unit
@param {function} callback - callback to be invoked passing {Buffer} response
@returns undefined
@private
|
[
"Function",
"to",
"handle",
"FC15",
"request",
"."
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/servers/servertcp_handler.js#L523-L608
|
13,060
|
yaacov/node-modbus-serial
|
servers/servertcp_handler.js
|
_handleWriteMultipleRegisters
|
function _handleWriteMultipleRegisters(requestBuffer, vector, unitID, callback) {
var address = requestBuffer.readUInt16BE(2);
var length = requestBuffer.readUInt16BE(4);
// if length is bad, ignore message
if (requestBuffer.length !== (7 + length * 2 + 2)) {
return;
}
// build answer
var responseBuffer = Buffer.alloc(8);
responseBuffer.writeUInt16BE(address, 2);
responseBuffer.writeUInt16BE(length, 4);
// write registers
var callbackInvoked = false;
var cbCount = 0;
var buildCb = function(/* i - not used at the moment */) {
return function(err) {
if (err) {
if (!callbackInvoked) {
callbackInvoked = true;
callback(err);
}
return;
}
cbCount = cbCount + 1;
if (cbCount === length && !callbackInvoked) {
modbusSerialDebug({ action: "FC16 response", responseBuffer: responseBuffer });
callbackInvoked = true;
callback(null, responseBuffer);
}
};
};
if (length === 0)
callback({
modbusErrorCode: 0x02, // Illegal address
msg: "Invalid length"
});
if (vector.setRegister) {
var value;
for (var i = 0; i < length; i++) {
var cb = buildCb(i);
value = requestBuffer.readUInt16BE(7 + i * 2);
try {
if (vector.setRegister.length === 4) {
vector.setRegister(address + i, value, unitID, cb);
}
else {
var promiseOrValue = vector.setRegister(address + i, value, unitID);
_handlePromiseOrValue(promiseOrValue, cb);
}
}
catch(err) {
cb(err);
}
}
} else if (vector.setRegisterArray) {
value = [];
for (i = 0; i < length; i++) {
cb = buildCb(i);
value.push(requestBuffer.readUInt16BE(7 + i * 2));
_handlePromiseOrValue(value, cb);
}
try {
if (vector.setRegisterArray.length === 6) {
vector.setRegisterArray(address, value, unitID, cb);
}
else {
vector.setRegisterArray(address, value, unitID);
}
}
catch (err) {
cb(err);
}
}
}
|
javascript
|
function _handleWriteMultipleRegisters(requestBuffer, vector, unitID, callback) {
var address = requestBuffer.readUInt16BE(2);
var length = requestBuffer.readUInt16BE(4);
// if length is bad, ignore message
if (requestBuffer.length !== (7 + length * 2 + 2)) {
return;
}
// build answer
var responseBuffer = Buffer.alloc(8);
responseBuffer.writeUInt16BE(address, 2);
responseBuffer.writeUInt16BE(length, 4);
// write registers
var callbackInvoked = false;
var cbCount = 0;
var buildCb = function(/* i - not used at the moment */) {
return function(err) {
if (err) {
if (!callbackInvoked) {
callbackInvoked = true;
callback(err);
}
return;
}
cbCount = cbCount + 1;
if (cbCount === length && !callbackInvoked) {
modbusSerialDebug({ action: "FC16 response", responseBuffer: responseBuffer });
callbackInvoked = true;
callback(null, responseBuffer);
}
};
};
if (length === 0)
callback({
modbusErrorCode: 0x02, // Illegal address
msg: "Invalid length"
});
if (vector.setRegister) {
var value;
for (var i = 0; i < length; i++) {
var cb = buildCb(i);
value = requestBuffer.readUInt16BE(7 + i * 2);
try {
if (vector.setRegister.length === 4) {
vector.setRegister(address + i, value, unitID, cb);
}
else {
var promiseOrValue = vector.setRegister(address + i, value, unitID);
_handlePromiseOrValue(promiseOrValue, cb);
}
}
catch(err) {
cb(err);
}
}
} else if (vector.setRegisterArray) {
value = [];
for (i = 0; i < length; i++) {
cb = buildCb(i);
value.push(requestBuffer.readUInt16BE(7 + i * 2));
_handlePromiseOrValue(value, cb);
}
try {
if (vector.setRegisterArray.length === 6) {
vector.setRegisterArray(address, value, unitID, cb);
}
else {
vector.setRegisterArray(address, value, unitID);
}
}
catch (err) {
cb(err);
}
}
}
|
[
"function",
"_handleWriteMultipleRegisters",
"(",
"requestBuffer",
",",
"vector",
",",
"unitID",
",",
"callback",
")",
"{",
"var",
"address",
"=",
"requestBuffer",
".",
"readUInt16BE",
"(",
"2",
")",
";",
"var",
"length",
"=",
"requestBuffer",
".",
"readUInt16BE",
"(",
"4",
")",
";",
"// if length is bad, ignore message",
"if",
"(",
"requestBuffer",
".",
"length",
"!==",
"(",
"7",
"+",
"length",
"*",
"2",
"+",
"2",
")",
")",
"{",
"return",
";",
"}",
"// build answer",
"var",
"responseBuffer",
"=",
"Buffer",
".",
"alloc",
"(",
"8",
")",
";",
"responseBuffer",
".",
"writeUInt16BE",
"(",
"address",
",",
"2",
")",
";",
"responseBuffer",
".",
"writeUInt16BE",
"(",
"length",
",",
"4",
")",
";",
"// write registers",
"var",
"callbackInvoked",
"=",
"false",
";",
"var",
"cbCount",
"=",
"0",
";",
"var",
"buildCb",
"=",
"function",
"(",
"/* i - not used at the moment */",
")",
"{",
"return",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"!",
"callbackInvoked",
")",
"{",
"callbackInvoked",
"=",
"true",
";",
"callback",
"(",
"err",
")",
";",
"}",
"return",
";",
"}",
"cbCount",
"=",
"cbCount",
"+",
"1",
";",
"if",
"(",
"cbCount",
"===",
"length",
"&&",
"!",
"callbackInvoked",
")",
"{",
"modbusSerialDebug",
"(",
"{",
"action",
":",
"\"FC16 response\"",
",",
"responseBuffer",
":",
"responseBuffer",
"}",
")",
";",
"callbackInvoked",
"=",
"true",
";",
"callback",
"(",
"null",
",",
"responseBuffer",
")",
";",
"}",
"}",
";",
"}",
";",
"if",
"(",
"length",
"===",
"0",
")",
"callback",
"(",
"{",
"modbusErrorCode",
":",
"0x02",
",",
"// Illegal address",
"msg",
":",
"\"Invalid length\"",
"}",
")",
";",
"if",
"(",
"vector",
".",
"setRegister",
")",
"{",
"var",
"value",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"var",
"cb",
"=",
"buildCb",
"(",
"i",
")",
";",
"value",
"=",
"requestBuffer",
".",
"readUInt16BE",
"(",
"7",
"+",
"i",
"*",
"2",
")",
";",
"try",
"{",
"if",
"(",
"vector",
".",
"setRegister",
".",
"length",
"===",
"4",
")",
"{",
"vector",
".",
"setRegister",
"(",
"address",
"+",
"i",
",",
"value",
",",
"unitID",
",",
"cb",
")",
";",
"}",
"else",
"{",
"var",
"promiseOrValue",
"=",
"vector",
".",
"setRegister",
"(",
"address",
"+",
"i",
",",
"value",
",",
"unitID",
")",
";",
"_handlePromiseOrValue",
"(",
"promiseOrValue",
",",
"cb",
")",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"vector",
".",
"setRegisterArray",
")",
"{",
"value",
"=",
"[",
"]",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"cb",
"=",
"buildCb",
"(",
"i",
")",
";",
"value",
".",
"push",
"(",
"requestBuffer",
".",
"readUInt16BE",
"(",
"7",
"+",
"i",
"*",
"2",
")",
")",
";",
"_handlePromiseOrValue",
"(",
"value",
",",
"cb",
")",
";",
"}",
"try",
"{",
"if",
"(",
"vector",
".",
"setRegisterArray",
".",
"length",
"===",
"6",
")",
"{",
"vector",
".",
"setRegisterArray",
"(",
"address",
",",
"value",
",",
"unitID",
",",
"cb",
")",
";",
"}",
"else",
"{",
"vector",
".",
"setRegisterArray",
"(",
"address",
",",
"value",
",",
"unitID",
")",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
";",
"}",
"}",
"}"
] |
Function to handle FC16 request.
@param requestBuffer - request Buffer from client
@param vector - vector of functions for read and write
@param unitID - Id of the requesting unit
@param {function} callback - callback to be invoked passing {Buffer} response
@returns undefined
@private
|
[
"Function",
"to",
"handle",
"FC16",
"request",
"."
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/servers/servertcp_handler.js#L620-L707
|
13,061
|
yaacov/node-modbus-serial
|
servers/servertcp_handler.js
|
_handleMEI
|
function _handleMEI(requestBuffer, vector, unitID, callback) {
var MEIType = requestBuffer[2];
switch(parseInt(MEIType)) {
case 14:
_handleReadDeviceIdentification(requestBuffer, vector, unitID, callback);
break;
default:
callback({ modbusErrorCode: 0x01 }); // illegal MEI type
}
}
|
javascript
|
function _handleMEI(requestBuffer, vector, unitID, callback) {
var MEIType = requestBuffer[2];
switch(parseInt(MEIType)) {
case 14:
_handleReadDeviceIdentification(requestBuffer, vector, unitID, callback);
break;
default:
callback({ modbusErrorCode: 0x01 }); // illegal MEI type
}
}
|
[
"function",
"_handleMEI",
"(",
"requestBuffer",
",",
"vector",
",",
"unitID",
",",
"callback",
")",
"{",
"var",
"MEIType",
"=",
"requestBuffer",
"[",
"2",
"]",
";",
"switch",
"(",
"parseInt",
"(",
"MEIType",
")",
")",
"{",
"case",
"14",
":",
"_handleReadDeviceIdentification",
"(",
"requestBuffer",
",",
"vector",
",",
"unitID",
",",
"callback",
")",
";",
"break",
";",
"default",
":",
"callback",
"(",
"{",
"modbusErrorCode",
":",
"0x01",
"}",
")",
";",
"// illegal MEI type",
"}",
"}"
] |
Function to handle FC43 request.
@param requestBuffer - request Buffer from client
@param vector - vector of functions for read and write
@param unitID - Id of the requesting unit
@param {function} callback - callback to be invoked passing {Buffer} response
@returns undefined
@private
|
[
"Function",
"to",
"handle",
"FC43",
"request",
"."
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/servers/servertcp_handler.js#L719-L728
|
13,062
|
yaacov/node-modbus-serial
|
servers/servertcp.js
|
_serverDebug
|
function _serverDebug(text, unitID, functionCode, responseBuffer) {
// If no responseBuffer, then assume this is an error
// o/w assume an action
if (typeof responseBuffer === "undefined") {
modbusSerialDebug({
error: text,
unitID: unitID,
functionCode: functionCode
});
} else {
modbusSerialDebug({
action: text,
unitID: unitID,
functionCode: functionCode,
responseBuffer: responseBuffer.toString("hex")
});
}
}
|
javascript
|
function _serverDebug(text, unitID, functionCode, responseBuffer) {
// If no responseBuffer, then assume this is an error
// o/w assume an action
if (typeof responseBuffer === "undefined") {
modbusSerialDebug({
error: text,
unitID: unitID,
functionCode: functionCode
});
} else {
modbusSerialDebug({
action: text,
unitID: unitID,
functionCode: functionCode,
responseBuffer: responseBuffer.toString("hex")
});
}
}
|
[
"function",
"_serverDebug",
"(",
"text",
",",
"unitID",
",",
"functionCode",
",",
"responseBuffer",
")",
"{",
"// If no responseBuffer, then assume this is an error",
"// o/w assume an action",
"if",
"(",
"typeof",
"responseBuffer",
"===",
"\"undefined\"",
")",
"{",
"modbusSerialDebug",
"(",
"{",
"error",
":",
"text",
",",
"unitID",
":",
"unitID",
",",
"functionCode",
":",
"functionCode",
"}",
")",
";",
"}",
"else",
"{",
"modbusSerialDebug",
"(",
"{",
"action",
":",
"text",
",",
"unitID",
":",
"unitID",
",",
"functionCode",
":",
"functionCode",
",",
"responseBuffer",
":",
"responseBuffer",
".",
"toString",
"(",
"\"hex\"",
")",
"}",
")",
";",
"}",
"}"
] |
Helper function for sending debug objects.
@param {string} text - text of message, an error or an action
@param {int} unitID - Id of the requesting unit
@param {int} functionCode - a modbus function code.
@param {Buffer} requestBuffer - request Buffer from client
@returns undefined
@private
|
[
"Helper",
"function",
"for",
"sending",
"debug",
"objects",
"."
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/servers/servertcp.js#L49-L67
|
13,063
|
yaacov/node-modbus-serial
|
servers/servertcp.js
|
_callbackFactory
|
function _callbackFactory(unitID, functionCode, sockWriter) {
return function cb(err, responseBuffer) {
var crc;
// If we have an error.
if (err) {
var errorCode = 0x04; // slave device failure
if (!isNaN(err.modbusErrorCode)) {
errorCode = err.modbusErrorCode;
}
// Set an error response
functionCode = parseInt(functionCode) | 0x80;
responseBuffer = Buffer.alloc(3 + 2);
responseBuffer.writeUInt8(errorCode, 2);
_serverDebug("error processing response", unitID, functionCode);
}
// If we do not have a responseBuffer
if (!responseBuffer) {
_serverDebug("no response buffer", unitID, functionCode);
return sockWriter(null, responseBuffer);
}
// add unit number and function code
responseBuffer.writeUInt8(unitID, 0);
responseBuffer.writeUInt8(functionCode, 1);
// Add crc
crc = crc16(responseBuffer.slice(0, -2));
responseBuffer.writeUInt16LE(crc, responseBuffer.length - 2);
// Call callback function
_serverDebug("server response", unitID, functionCode, responseBuffer);
return sockWriter(null, responseBuffer);
};
}
|
javascript
|
function _callbackFactory(unitID, functionCode, sockWriter) {
return function cb(err, responseBuffer) {
var crc;
// If we have an error.
if (err) {
var errorCode = 0x04; // slave device failure
if (!isNaN(err.modbusErrorCode)) {
errorCode = err.modbusErrorCode;
}
// Set an error response
functionCode = parseInt(functionCode) | 0x80;
responseBuffer = Buffer.alloc(3 + 2);
responseBuffer.writeUInt8(errorCode, 2);
_serverDebug("error processing response", unitID, functionCode);
}
// If we do not have a responseBuffer
if (!responseBuffer) {
_serverDebug("no response buffer", unitID, functionCode);
return sockWriter(null, responseBuffer);
}
// add unit number and function code
responseBuffer.writeUInt8(unitID, 0);
responseBuffer.writeUInt8(functionCode, 1);
// Add crc
crc = crc16(responseBuffer.slice(0, -2));
responseBuffer.writeUInt16LE(crc, responseBuffer.length - 2);
// Call callback function
_serverDebug("server response", unitID, functionCode, responseBuffer);
return sockWriter(null, responseBuffer);
};
}
|
[
"function",
"_callbackFactory",
"(",
"unitID",
",",
"functionCode",
",",
"sockWriter",
")",
"{",
"return",
"function",
"cb",
"(",
"err",
",",
"responseBuffer",
")",
"{",
"var",
"crc",
";",
"// If we have an error.",
"if",
"(",
"err",
")",
"{",
"var",
"errorCode",
"=",
"0x04",
";",
"// slave device failure",
"if",
"(",
"!",
"isNaN",
"(",
"err",
".",
"modbusErrorCode",
")",
")",
"{",
"errorCode",
"=",
"err",
".",
"modbusErrorCode",
";",
"}",
"// Set an error response",
"functionCode",
"=",
"parseInt",
"(",
"functionCode",
")",
"|",
"0x80",
";",
"responseBuffer",
"=",
"Buffer",
".",
"alloc",
"(",
"3",
"+",
"2",
")",
";",
"responseBuffer",
".",
"writeUInt8",
"(",
"errorCode",
",",
"2",
")",
";",
"_serverDebug",
"(",
"\"error processing response\"",
",",
"unitID",
",",
"functionCode",
")",
";",
"}",
"// If we do not have a responseBuffer",
"if",
"(",
"!",
"responseBuffer",
")",
"{",
"_serverDebug",
"(",
"\"no response buffer\"",
",",
"unitID",
",",
"functionCode",
")",
";",
"return",
"sockWriter",
"(",
"null",
",",
"responseBuffer",
")",
";",
"}",
"// add unit number and function code",
"responseBuffer",
".",
"writeUInt8",
"(",
"unitID",
",",
"0",
")",
";",
"responseBuffer",
".",
"writeUInt8",
"(",
"functionCode",
",",
"1",
")",
";",
"// Add crc",
"crc",
"=",
"crc16",
"(",
"responseBuffer",
".",
"slice",
"(",
"0",
",",
"-",
"2",
")",
")",
";",
"responseBuffer",
".",
"writeUInt16LE",
"(",
"crc",
",",
"responseBuffer",
".",
"length",
"-",
"2",
")",
";",
"// Call callback function",
"_serverDebug",
"(",
"\"server response\"",
",",
"unitID",
",",
"functionCode",
",",
"responseBuffer",
")",
";",
"return",
"sockWriter",
"(",
"null",
",",
"responseBuffer",
")",
";",
"}",
";",
"}"
] |
Helper function for creating callback functions.
@param {int} unitID - Id of the requesting unit
@param {int} functionCode - a modbus function code
@param {function} sockWriter - write buffer (or error) to tcp socket
@returns {function} - a callback function
@private
|
[
"Helper",
"function",
"for",
"creating",
"callback",
"functions",
"."
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/servers/servertcp.js#L78-L115
|
13,064
|
yaacov/node-modbus-serial
|
servers/servertcp.js
|
_parseModbusBuffer
|
function _parseModbusBuffer(requestBuffer, vector, serverUnitID, sockWriter) {
var cb;
// Check requestBuffer length
if (!requestBuffer || requestBuffer.length < MBAP_LEN) {
modbusSerialDebug("wrong size of request Buffer " + requestBuffer.length);
return;
}
var unitID = requestBuffer[0];
var functionCode = requestBuffer[1];
var crc = requestBuffer[requestBuffer.length - 2] + requestBuffer[requestBuffer.length - 1] * 0x100;
// if crc is bad, ignore message
if (crc !== crc16(requestBuffer.slice(0, -2))) {
modbusSerialDebug("wrong CRC of request Buffer");
return;
}
// if crc is bad, ignore message
if (serverUnitID !== 255 && serverUnitID !== unitID) {
modbusSerialDebug("wrong unitID");
return;
}
modbusSerialDebug("request for function code " + functionCode);
cb = _callbackFactory(unitID, functionCode, sockWriter);
switch (parseInt(functionCode)) {
case 1:
case 2:
handlers.readCoilsOrInputDiscretes(requestBuffer, vector, unitID, cb, functionCode);
break;
case 3:
handlers.readMultipleRegisters(requestBuffer, vector, unitID, cb);
break;
case 4:
handlers.readInputRegisters(requestBuffer, vector, unitID, cb);
break;
case 5:
handlers.writeCoil(requestBuffer, vector, unitID, cb);
break;
case 6:
handlers.writeSingleRegister(requestBuffer, vector, unitID, cb);
break;
case 15:
handlers.forceMultipleCoils(requestBuffer, vector, unitID, cb);
break;
case 16:
handlers.writeMultipleRegisters(requestBuffer, vector, unitID, cb);
break;
case 43:
handlers.handleMEI(requestBuffer, vector, unitID, cb);
break;
default:
var errorCode = 0x01; // illegal function
// set an error response
functionCode = parseInt(functionCode) | 0x80;
var responseBuffer = Buffer.alloc(3 + 2);
responseBuffer.writeUInt8(errorCode, 2);
modbusSerialDebug({
error: "Illegal function",
functionCode: functionCode
});
cb({ modbusErrorCode: errorCode }, responseBuffer);
}
}
|
javascript
|
function _parseModbusBuffer(requestBuffer, vector, serverUnitID, sockWriter) {
var cb;
// Check requestBuffer length
if (!requestBuffer || requestBuffer.length < MBAP_LEN) {
modbusSerialDebug("wrong size of request Buffer " + requestBuffer.length);
return;
}
var unitID = requestBuffer[0];
var functionCode = requestBuffer[1];
var crc = requestBuffer[requestBuffer.length - 2] + requestBuffer[requestBuffer.length - 1] * 0x100;
// if crc is bad, ignore message
if (crc !== crc16(requestBuffer.slice(0, -2))) {
modbusSerialDebug("wrong CRC of request Buffer");
return;
}
// if crc is bad, ignore message
if (serverUnitID !== 255 && serverUnitID !== unitID) {
modbusSerialDebug("wrong unitID");
return;
}
modbusSerialDebug("request for function code " + functionCode);
cb = _callbackFactory(unitID, functionCode, sockWriter);
switch (parseInt(functionCode)) {
case 1:
case 2:
handlers.readCoilsOrInputDiscretes(requestBuffer, vector, unitID, cb, functionCode);
break;
case 3:
handlers.readMultipleRegisters(requestBuffer, vector, unitID, cb);
break;
case 4:
handlers.readInputRegisters(requestBuffer, vector, unitID, cb);
break;
case 5:
handlers.writeCoil(requestBuffer, vector, unitID, cb);
break;
case 6:
handlers.writeSingleRegister(requestBuffer, vector, unitID, cb);
break;
case 15:
handlers.forceMultipleCoils(requestBuffer, vector, unitID, cb);
break;
case 16:
handlers.writeMultipleRegisters(requestBuffer, vector, unitID, cb);
break;
case 43:
handlers.handleMEI(requestBuffer, vector, unitID, cb);
break;
default:
var errorCode = 0x01; // illegal function
// set an error response
functionCode = parseInt(functionCode) | 0x80;
var responseBuffer = Buffer.alloc(3 + 2);
responseBuffer.writeUInt8(errorCode, 2);
modbusSerialDebug({
error: "Illegal function",
functionCode: functionCode
});
cb({ modbusErrorCode: errorCode }, responseBuffer);
}
}
|
[
"function",
"_parseModbusBuffer",
"(",
"requestBuffer",
",",
"vector",
",",
"serverUnitID",
",",
"sockWriter",
")",
"{",
"var",
"cb",
";",
"// Check requestBuffer length",
"if",
"(",
"!",
"requestBuffer",
"||",
"requestBuffer",
".",
"length",
"<",
"MBAP_LEN",
")",
"{",
"modbusSerialDebug",
"(",
"\"wrong size of request Buffer \"",
"+",
"requestBuffer",
".",
"length",
")",
";",
"return",
";",
"}",
"var",
"unitID",
"=",
"requestBuffer",
"[",
"0",
"]",
";",
"var",
"functionCode",
"=",
"requestBuffer",
"[",
"1",
"]",
";",
"var",
"crc",
"=",
"requestBuffer",
"[",
"requestBuffer",
".",
"length",
"-",
"2",
"]",
"+",
"requestBuffer",
"[",
"requestBuffer",
".",
"length",
"-",
"1",
"]",
"*",
"0x100",
";",
"// if crc is bad, ignore message",
"if",
"(",
"crc",
"!==",
"crc16",
"(",
"requestBuffer",
".",
"slice",
"(",
"0",
",",
"-",
"2",
")",
")",
")",
"{",
"modbusSerialDebug",
"(",
"\"wrong CRC of request Buffer\"",
")",
";",
"return",
";",
"}",
"// if crc is bad, ignore message",
"if",
"(",
"serverUnitID",
"!==",
"255",
"&&",
"serverUnitID",
"!==",
"unitID",
")",
"{",
"modbusSerialDebug",
"(",
"\"wrong unitID\"",
")",
";",
"return",
";",
"}",
"modbusSerialDebug",
"(",
"\"request for function code \"",
"+",
"functionCode",
")",
";",
"cb",
"=",
"_callbackFactory",
"(",
"unitID",
",",
"functionCode",
",",
"sockWriter",
")",
";",
"switch",
"(",
"parseInt",
"(",
"functionCode",
")",
")",
"{",
"case",
"1",
":",
"case",
"2",
":",
"handlers",
".",
"readCoilsOrInputDiscretes",
"(",
"requestBuffer",
",",
"vector",
",",
"unitID",
",",
"cb",
",",
"functionCode",
")",
";",
"break",
";",
"case",
"3",
":",
"handlers",
".",
"readMultipleRegisters",
"(",
"requestBuffer",
",",
"vector",
",",
"unitID",
",",
"cb",
")",
";",
"break",
";",
"case",
"4",
":",
"handlers",
".",
"readInputRegisters",
"(",
"requestBuffer",
",",
"vector",
",",
"unitID",
",",
"cb",
")",
";",
"break",
";",
"case",
"5",
":",
"handlers",
".",
"writeCoil",
"(",
"requestBuffer",
",",
"vector",
",",
"unitID",
",",
"cb",
")",
";",
"break",
";",
"case",
"6",
":",
"handlers",
".",
"writeSingleRegister",
"(",
"requestBuffer",
",",
"vector",
",",
"unitID",
",",
"cb",
")",
";",
"break",
";",
"case",
"15",
":",
"handlers",
".",
"forceMultipleCoils",
"(",
"requestBuffer",
",",
"vector",
",",
"unitID",
",",
"cb",
")",
";",
"break",
";",
"case",
"16",
":",
"handlers",
".",
"writeMultipleRegisters",
"(",
"requestBuffer",
",",
"vector",
",",
"unitID",
",",
"cb",
")",
";",
"break",
";",
"case",
"43",
":",
"handlers",
".",
"handleMEI",
"(",
"requestBuffer",
",",
"vector",
",",
"unitID",
",",
"cb",
")",
";",
"break",
";",
"default",
":",
"var",
"errorCode",
"=",
"0x01",
";",
"// illegal function",
"// set an error response",
"functionCode",
"=",
"parseInt",
"(",
"functionCode",
")",
"|",
"0x80",
";",
"var",
"responseBuffer",
"=",
"Buffer",
".",
"alloc",
"(",
"3",
"+",
"2",
")",
";",
"responseBuffer",
".",
"writeUInt8",
"(",
"errorCode",
",",
"2",
")",
";",
"modbusSerialDebug",
"(",
"{",
"error",
":",
"\"Illegal function\"",
",",
"functionCode",
":",
"functionCode",
"}",
")",
";",
"cb",
"(",
"{",
"modbusErrorCode",
":",
"errorCode",
"}",
",",
"responseBuffer",
")",
";",
"}",
"}"
] |
Parse a ModbusRTU buffer and return an answer buffer.
@param {Buffer} requestBuffer - request Buffer from client
@param {object} vector - vector of functions for read and write
@param {function} callback - callback to be invoked passing {Buffer} response
@returns undefined
@private
|
[
"Parse",
"a",
"ModbusRTU",
"buffer",
"and",
"return",
"an",
"answer",
"buffer",
"."
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/servers/servertcp.js#L126-L195
|
13,065
|
yaacov/node-modbus-serial
|
ports/c701port.js
|
_checkData
|
function _checkData(modbus, buf) {
// check buffer size
if (buf.length !== modbus._length && buf.length !== 5) return false;
// calculate crc16
var crcIn = buf.readUInt16LE(buf.length - 2);
// check buffer unit-id, command and crc
return (buf[0] === modbus._id &&
(0x7f & buf[1]) === modbus._cmd &&
crcIn === crc16(buf.slice(0, -2)));
}
|
javascript
|
function _checkData(modbus, buf) {
// check buffer size
if (buf.length !== modbus._length && buf.length !== 5) return false;
// calculate crc16
var crcIn = buf.readUInt16LE(buf.length - 2);
// check buffer unit-id, command and crc
return (buf[0] === modbus._id &&
(0x7f & buf[1]) === modbus._cmd &&
crcIn === crc16(buf.slice(0, -2)));
}
|
[
"function",
"_checkData",
"(",
"modbus",
",",
"buf",
")",
"{",
"// check buffer size",
"if",
"(",
"buf",
".",
"length",
"!==",
"modbus",
".",
"_length",
"&&",
"buf",
".",
"length",
"!==",
"5",
")",
"return",
"false",
";",
"// calculate crc16",
"var",
"crcIn",
"=",
"buf",
".",
"readUInt16LE",
"(",
"buf",
".",
"length",
"-",
"2",
")",
";",
"// check buffer unit-id, command and crc",
"return",
"(",
"buf",
"[",
"0",
"]",
"===",
"modbus",
".",
"_id",
"&&",
"(",
"0x7f",
"&",
"buf",
"[",
"1",
"]",
")",
"===",
"modbus",
".",
"_cmd",
"&&",
"crcIn",
"===",
"crc16",
"(",
"buf",
".",
"slice",
"(",
"0",
",",
"-",
"2",
")",
")",
")",
";",
"}"
] |
Check if a buffer chunk can be a Modbus answer or modbus exception.
@param {UdpPort} modbus
@param {Buffer} buf the buffer to check.
@return {boolean} if the buffer can be an answer
@private
|
[
"Check",
"if",
"a",
"buffer",
"chunk",
"can",
"be",
"a",
"Modbus",
"answer",
"or",
"modbus",
"exception",
"."
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/ports/c701port.js#L23-L34
|
13,066
|
yaacov/node-modbus-serial
|
ports/c701port.js
|
function(ip, options) {
var modbus = this;
this.ip = ip;
this.openFlag = false;
// options
if (typeof(options) === "undefined") options = {};
this.port = options.port || C701_PORT; // C701 port
// create a socket
this._client = dgram.createSocket("udp4");
// wait for answer
this._client.on("message", function(data) {
var buffer = null;
// check expected length
if (modbus.length < 6) return;
// check message length
if (data.length < (116 + 5)) return;
// check the C701 packet magic
if (data.readUInt16LE(2) !== 602) return;
// check for modbus valid answer
// get the serial data from the C701 packet
buffer = data.slice(data.length - modbus._length);
modbusSerialDebug({ action: "receive c701 upd port", data: data, buffer: buffer });
modbusSerialDebug(JSON.stringify({ action: "receive c701 upd port strings", data: data, buffer: buffer }));
// check the serial data
if (_checkData(modbus, buffer)) {
modbusSerialDebug({ action: "emit data serial rtu buffered port", buffer: buffer });
modbusSerialDebug(JSON.stringify({ action: "emit data serial rtu buffered port strings", buffer: buffer }));
modbus.emit("data", buffer);
} else {
// check for modbus exception
// get the serial data from the C701 packet
buffer = data.slice(data.length - 5);
// check the serial data
if (_checkData(modbus, buffer)) {
modbusSerialDebug({ action: "emit data serial rtu buffered port", buffer: buffer });
modbusSerialDebug(JSON.stringify({
action: "emit data serial rtu buffered port strings",
buffer: buffer
}));
modbus.emit("data", buffer);
}
}
});
this._client.on("listening", function() {
modbus.openFlag = true;
});
this._client.on("close", function() {
modbus.openFlag = false;
});
/**
* Check if port is open.
*
* @returns {boolean}
*/
Object.defineProperty(this, "isOpen", {
enumerable: true,
get: function() {
return this.openFlag;
}
});
EventEmitter.call(this);
}
|
javascript
|
function(ip, options) {
var modbus = this;
this.ip = ip;
this.openFlag = false;
// options
if (typeof(options) === "undefined") options = {};
this.port = options.port || C701_PORT; // C701 port
// create a socket
this._client = dgram.createSocket("udp4");
// wait for answer
this._client.on("message", function(data) {
var buffer = null;
// check expected length
if (modbus.length < 6) return;
// check message length
if (data.length < (116 + 5)) return;
// check the C701 packet magic
if (data.readUInt16LE(2) !== 602) return;
// check for modbus valid answer
// get the serial data from the C701 packet
buffer = data.slice(data.length - modbus._length);
modbusSerialDebug({ action: "receive c701 upd port", data: data, buffer: buffer });
modbusSerialDebug(JSON.stringify({ action: "receive c701 upd port strings", data: data, buffer: buffer }));
// check the serial data
if (_checkData(modbus, buffer)) {
modbusSerialDebug({ action: "emit data serial rtu buffered port", buffer: buffer });
modbusSerialDebug(JSON.stringify({ action: "emit data serial rtu buffered port strings", buffer: buffer }));
modbus.emit("data", buffer);
} else {
// check for modbus exception
// get the serial data from the C701 packet
buffer = data.slice(data.length - 5);
// check the serial data
if (_checkData(modbus, buffer)) {
modbusSerialDebug({ action: "emit data serial rtu buffered port", buffer: buffer });
modbusSerialDebug(JSON.stringify({
action: "emit data serial rtu buffered port strings",
buffer: buffer
}));
modbus.emit("data", buffer);
}
}
});
this._client.on("listening", function() {
modbus.openFlag = true;
});
this._client.on("close", function() {
modbus.openFlag = false;
});
/**
* Check if port is open.
*
* @returns {boolean}
*/
Object.defineProperty(this, "isOpen", {
enumerable: true,
get: function() {
return this.openFlag;
}
});
EventEmitter.call(this);
}
|
[
"function",
"(",
"ip",
",",
"options",
")",
"{",
"var",
"modbus",
"=",
"this",
";",
"this",
".",
"ip",
"=",
"ip",
";",
"this",
".",
"openFlag",
"=",
"false",
";",
"// options",
"if",
"(",
"typeof",
"(",
"options",
")",
"===",
"\"undefined\"",
")",
"options",
"=",
"{",
"}",
";",
"this",
".",
"port",
"=",
"options",
".",
"port",
"||",
"C701_PORT",
";",
"// C701 port",
"// create a socket",
"this",
".",
"_client",
"=",
"dgram",
".",
"createSocket",
"(",
"\"udp4\"",
")",
";",
"// wait for answer",
"this",
".",
"_client",
".",
"on",
"(",
"\"message\"",
",",
"function",
"(",
"data",
")",
"{",
"var",
"buffer",
"=",
"null",
";",
"// check expected length",
"if",
"(",
"modbus",
".",
"length",
"<",
"6",
")",
"return",
";",
"// check message length",
"if",
"(",
"data",
".",
"length",
"<",
"(",
"116",
"+",
"5",
")",
")",
"return",
";",
"// check the C701 packet magic",
"if",
"(",
"data",
".",
"readUInt16LE",
"(",
"2",
")",
"!==",
"602",
")",
"return",
";",
"// check for modbus valid answer",
"// get the serial data from the C701 packet",
"buffer",
"=",
"data",
".",
"slice",
"(",
"data",
".",
"length",
"-",
"modbus",
".",
"_length",
")",
";",
"modbusSerialDebug",
"(",
"{",
"action",
":",
"\"receive c701 upd port\"",
",",
"data",
":",
"data",
",",
"buffer",
":",
"buffer",
"}",
")",
";",
"modbusSerialDebug",
"(",
"JSON",
".",
"stringify",
"(",
"{",
"action",
":",
"\"receive c701 upd port strings\"",
",",
"data",
":",
"data",
",",
"buffer",
":",
"buffer",
"}",
")",
")",
";",
"// check the serial data",
"if",
"(",
"_checkData",
"(",
"modbus",
",",
"buffer",
")",
")",
"{",
"modbusSerialDebug",
"(",
"{",
"action",
":",
"\"emit data serial rtu buffered port\"",
",",
"buffer",
":",
"buffer",
"}",
")",
";",
"modbusSerialDebug",
"(",
"JSON",
".",
"stringify",
"(",
"{",
"action",
":",
"\"emit data serial rtu buffered port strings\"",
",",
"buffer",
":",
"buffer",
"}",
")",
")",
";",
"modbus",
".",
"emit",
"(",
"\"data\"",
",",
"buffer",
")",
";",
"}",
"else",
"{",
"// check for modbus exception",
"// get the serial data from the C701 packet",
"buffer",
"=",
"data",
".",
"slice",
"(",
"data",
".",
"length",
"-",
"5",
")",
";",
"// check the serial data",
"if",
"(",
"_checkData",
"(",
"modbus",
",",
"buffer",
")",
")",
"{",
"modbusSerialDebug",
"(",
"{",
"action",
":",
"\"emit data serial rtu buffered port\"",
",",
"buffer",
":",
"buffer",
"}",
")",
";",
"modbusSerialDebug",
"(",
"JSON",
".",
"stringify",
"(",
"{",
"action",
":",
"\"emit data serial rtu buffered port strings\"",
",",
"buffer",
":",
"buffer",
"}",
")",
")",
";",
"modbus",
".",
"emit",
"(",
"\"data\"",
",",
"buffer",
")",
";",
"}",
"}",
"}",
")",
";",
"this",
".",
"_client",
".",
"on",
"(",
"\"listening\"",
",",
"function",
"(",
")",
"{",
"modbus",
".",
"openFlag",
"=",
"true",
";",
"}",
")",
";",
"this",
".",
"_client",
".",
"on",
"(",
"\"close\"",
",",
"function",
"(",
")",
"{",
"modbus",
".",
"openFlag",
"=",
"false",
";",
"}",
")",
";",
"/**\n * Check if port is open.\n *\n * @returns {boolean}\n */",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"\"isOpen\"",
",",
"{",
"enumerable",
":",
"true",
",",
"get",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"openFlag",
";",
"}",
"}",
")",
";",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"}"
] |
Simulate a modbus-RTU port using C701 UDP-to-Serial bridge.
@param ip
@param options
@constructor
|
[
"Simulate",
"a",
"modbus",
"-",
"RTU",
"port",
"using",
"C701",
"UDP",
"-",
"to",
"-",
"Serial",
"bridge",
"."
] |
bc11a54bc256986deb749efbde23a3657d28ff20
|
https://github.com/yaacov/node-modbus-serial/blob/bc11a54bc256986deb749efbde23a3657d28ff20/ports/c701port.js#L43-L120
|
|
13,067
|
pahen/madge
|
lib/graph.js
|
checkGraphvizInstalled
|
function checkGraphvizInstalled(config) {
if (config.graphVizPath) {
const cmd = path.join(config.graphVizPath, 'gvpr -V');
return exec(cmd)
.catch(() => {
throw new Error('Could not execute ' + cmd);
});
}
return exec('gvpr -V')
.catch((error) => {
throw new Error('Graphviz could not be found. Ensure that "gvpr" is in your $PATH.\n' + error);
});
}
|
javascript
|
function checkGraphvizInstalled(config) {
if (config.graphVizPath) {
const cmd = path.join(config.graphVizPath, 'gvpr -V');
return exec(cmd)
.catch(() => {
throw new Error('Could not execute ' + cmd);
});
}
return exec('gvpr -V')
.catch((error) => {
throw new Error('Graphviz could not be found. Ensure that "gvpr" is in your $PATH.\n' + error);
});
}
|
[
"function",
"checkGraphvizInstalled",
"(",
"config",
")",
"{",
"if",
"(",
"config",
".",
"graphVizPath",
")",
"{",
"const",
"cmd",
"=",
"path",
".",
"join",
"(",
"config",
".",
"graphVizPath",
",",
"'gvpr -V'",
")",
";",
"return",
"exec",
"(",
"cmd",
")",
".",
"catch",
"(",
"(",
")",
"=>",
"{",
"throw",
"new",
"Error",
"(",
"'Could not execute '",
"+",
"cmd",
")",
";",
"}",
")",
";",
"}",
"return",
"exec",
"(",
"'gvpr -V'",
")",
".",
"catch",
"(",
"(",
"error",
")",
"=>",
"{",
"throw",
"new",
"Error",
"(",
"'Graphviz could not be found. Ensure that \"gvpr\" is in your $PATH.\\n'",
"+",
"error",
")",
";",
"}",
")",
";",
"}"
] |
Check if Graphviz is installed on the system.
@param {Object} config
@return {Promise}
|
[
"Check",
"if",
"Graphviz",
"is",
"installed",
"on",
"the",
"system",
"."
] |
f8c3e640a51825ff7dc0aefe79510c8a584cf6cf
|
https://github.com/pahen/madge/blob/f8c3e640a51825ff7dc0aefe79510c8a584cf6cf/lib/graph.js#L25-L38
|
13,068
|
pahen/madge
|
lib/graph.js
|
createGraphvizOptions
|
function createGraphvizOptions(config) {
const graphVizOptions = config.graphVizOptions || {};
return {
G: Object.assign({
overlap: false,
pad: 0.3,
rankdir: config.rankdir,
layout: config.layout,
bgcolor: config.backgroundColor
}, graphVizOptions.G),
E: Object.assign({
color: config.edgeColor
}, graphVizOptions.E),
N: Object.assign({
fontname: config.fontName,
fontsize: config.fontSize,
color: config.nodeColor,
shape: config.nodeShape,
style: config.nodeStyle,
height: 0,
fontcolor: config.nodeColor
}, graphVizOptions.N)
};
}
|
javascript
|
function createGraphvizOptions(config) {
const graphVizOptions = config.graphVizOptions || {};
return {
G: Object.assign({
overlap: false,
pad: 0.3,
rankdir: config.rankdir,
layout: config.layout,
bgcolor: config.backgroundColor
}, graphVizOptions.G),
E: Object.assign({
color: config.edgeColor
}, graphVizOptions.E),
N: Object.assign({
fontname: config.fontName,
fontsize: config.fontSize,
color: config.nodeColor,
shape: config.nodeShape,
style: config.nodeStyle,
height: 0,
fontcolor: config.nodeColor
}, graphVizOptions.N)
};
}
|
[
"function",
"createGraphvizOptions",
"(",
"config",
")",
"{",
"const",
"graphVizOptions",
"=",
"config",
".",
"graphVizOptions",
"||",
"{",
"}",
";",
"return",
"{",
"G",
":",
"Object",
".",
"assign",
"(",
"{",
"overlap",
":",
"false",
",",
"pad",
":",
"0.3",
",",
"rankdir",
":",
"config",
".",
"rankdir",
",",
"layout",
":",
"config",
".",
"layout",
",",
"bgcolor",
":",
"config",
".",
"backgroundColor",
"}",
",",
"graphVizOptions",
".",
"G",
")",
",",
"E",
":",
"Object",
".",
"assign",
"(",
"{",
"color",
":",
"config",
".",
"edgeColor",
"}",
",",
"graphVizOptions",
".",
"E",
")",
",",
"N",
":",
"Object",
".",
"assign",
"(",
"{",
"fontname",
":",
"config",
".",
"fontName",
",",
"fontsize",
":",
"config",
".",
"fontSize",
",",
"color",
":",
"config",
".",
"nodeColor",
",",
"shape",
":",
"config",
".",
"nodeShape",
",",
"style",
":",
"config",
".",
"nodeStyle",
",",
"height",
":",
"0",
",",
"fontcolor",
":",
"config",
".",
"nodeColor",
"}",
",",
"graphVizOptions",
".",
"N",
")",
"}",
";",
"}"
] |
Return options to use with graphviz digraph.
@param {Object} config
@return {Object}
|
[
"Return",
"options",
"to",
"use",
"with",
"graphviz",
"digraph",
"."
] |
f8c3e640a51825ff7dc0aefe79510c8a584cf6cf
|
https://github.com/pahen/madge/blob/f8c3e640a51825ff7dc0aefe79510c8a584cf6cf/lib/graph.js#L45-L69
|
13,069
|
pahen/madge
|
lib/graph.js
|
createGraph
|
function createGraph(modules, circular, config, options) {
const g = graphviz.digraph('G');
const nodes = {};
const cyclicModules = circular.reduce((a, b) => a.concat(b), []);
if (config.graphVizPath) {
g.setGraphVizPath(config.graphVizPath);
}
Object.keys(modules).forEach((id) => {
nodes[id] = nodes[id] || g.addNode(id);
if (!modules[id].length) {
setNodeColor(nodes[id], config.noDependencyColor);
} else if (cyclicModules.indexOf(id) >= 0) {
setNodeColor(nodes[id], config.cyclicNodeColor);
}
modules[id].forEach((depId) => {
nodes[depId] = nodes[depId] || g.addNode(depId);
if (!modules[depId]) {
setNodeColor(nodes[depId], config.noDependencyColor);
}
g.addEdge(nodes[id], nodes[depId]);
});
});
return new Promise((resolve, reject) => {
g.output(options, resolve, (code, out, err) => {
reject(new Error(err));
});
});
}
|
javascript
|
function createGraph(modules, circular, config, options) {
const g = graphviz.digraph('G');
const nodes = {};
const cyclicModules = circular.reduce((a, b) => a.concat(b), []);
if (config.graphVizPath) {
g.setGraphVizPath(config.graphVizPath);
}
Object.keys(modules).forEach((id) => {
nodes[id] = nodes[id] || g.addNode(id);
if (!modules[id].length) {
setNodeColor(nodes[id], config.noDependencyColor);
} else if (cyclicModules.indexOf(id) >= 0) {
setNodeColor(nodes[id], config.cyclicNodeColor);
}
modules[id].forEach((depId) => {
nodes[depId] = nodes[depId] || g.addNode(depId);
if (!modules[depId]) {
setNodeColor(nodes[depId], config.noDependencyColor);
}
g.addEdge(nodes[id], nodes[depId]);
});
});
return new Promise((resolve, reject) => {
g.output(options, resolve, (code, out, err) => {
reject(new Error(err));
});
});
}
|
[
"function",
"createGraph",
"(",
"modules",
",",
"circular",
",",
"config",
",",
"options",
")",
"{",
"const",
"g",
"=",
"graphviz",
".",
"digraph",
"(",
"'G'",
")",
";",
"const",
"nodes",
"=",
"{",
"}",
";",
"const",
"cyclicModules",
"=",
"circular",
".",
"reduce",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"a",
".",
"concat",
"(",
"b",
")",
",",
"[",
"]",
")",
";",
"if",
"(",
"config",
".",
"graphVizPath",
")",
"{",
"g",
".",
"setGraphVizPath",
"(",
"config",
".",
"graphVizPath",
")",
";",
"}",
"Object",
".",
"keys",
"(",
"modules",
")",
".",
"forEach",
"(",
"(",
"id",
")",
"=>",
"{",
"nodes",
"[",
"id",
"]",
"=",
"nodes",
"[",
"id",
"]",
"||",
"g",
".",
"addNode",
"(",
"id",
")",
";",
"if",
"(",
"!",
"modules",
"[",
"id",
"]",
".",
"length",
")",
"{",
"setNodeColor",
"(",
"nodes",
"[",
"id",
"]",
",",
"config",
".",
"noDependencyColor",
")",
";",
"}",
"else",
"if",
"(",
"cyclicModules",
".",
"indexOf",
"(",
"id",
")",
">=",
"0",
")",
"{",
"setNodeColor",
"(",
"nodes",
"[",
"id",
"]",
",",
"config",
".",
"cyclicNodeColor",
")",
";",
"}",
"modules",
"[",
"id",
"]",
".",
"forEach",
"(",
"(",
"depId",
")",
"=>",
"{",
"nodes",
"[",
"depId",
"]",
"=",
"nodes",
"[",
"depId",
"]",
"||",
"g",
".",
"addNode",
"(",
"depId",
")",
";",
"if",
"(",
"!",
"modules",
"[",
"depId",
"]",
")",
"{",
"setNodeColor",
"(",
"nodes",
"[",
"depId",
"]",
",",
"config",
".",
"noDependencyColor",
")",
";",
"}",
"g",
".",
"addEdge",
"(",
"nodes",
"[",
"id",
"]",
",",
"nodes",
"[",
"depId",
"]",
")",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"g",
".",
"output",
"(",
"options",
",",
"resolve",
",",
"(",
"code",
",",
"out",
",",
"err",
")",
"=>",
"{",
"reject",
"(",
"new",
"Error",
"(",
"err",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Creates the graphviz graph.
@param {Object} modules
@param {Array} circular
@param {Object} config
@param {Object} options
@return {Promise}
|
[
"Creates",
"the",
"graphviz",
"graph",
"."
] |
f8c3e640a51825ff7dc0aefe79510c8a584cf6cf
|
https://github.com/pahen/madge/blob/f8c3e640a51825ff7dc0aefe79510c8a584cf6cf/lib/graph.js#L79-L113
|
13,070
|
pahen/madge
|
lib/cyclic.js
|
getPath
|
function getPath(parent, unresolved) {
let parentVisited = false;
return Object.keys(unresolved).filter((module) => {
if (module === parent) {
parentVisited = true;
}
return parentVisited && unresolved[module];
});
}
|
javascript
|
function getPath(parent, unresolved) {
let parentVisited = false;
return Object.keys(unresolved).filter((module) => {
if (module === parent) {
parentVisited = true;
}
return parentVisited && unresolved[module];
});
}
|
[
"function",
"getPath",
"(",
"parent",
",",
"unresolved",
")",
"{",
"let",
"parentVisited",
"=",
"false",
";",
"return",
"Object",
".",
"keys",
"(",
"unresolved",
")",
".",
"filter",
"(",
"(",
"module",
")",
"=>",
"{",
"if",
"(",
"module",
"===",
"parent",
")",
"{",
"parentVisited",
"=",
"true",
";",
"}",
"return",
"parentVisited",
"&&",
"unresolved",
"[",
"module",
"]",
";",
"}",
")",
";",
"}"
] |
Get path to the circular dependency.
@param {String} parent
@param {Object} unresolved
@return {Array}
|
[
"Get",
"path",
"to",
"the",
"circular",
"dependency",
"."
] |
f8c3e640a51825ff7dc0aefe79510c8a584cf6cf
|
https://github.com/pahen/madge/blob/f8c3e640a51825ff7dc0aefe79510c8a584cf6cf/lib/cyclic.js#L9-L18
|
13,071
|
pahen/madge
|
lib/cyclic.js
|
resolver
|
function resolver(id, modules, circular, resolved, unresolved) {
unresolved[id] = true;
if (modules[id]) {
modules[id].forEach((dependency) => {
if (!resolved[dependency]) {
if (unresolved[dependency]) {
circular.push(getPath(dependency, unresolved));
return;
}
resolver(dependency, modules, circular, resolved, unresolved);
}
});
}
resolved[id] = true;
unresolved[id] = false;
}
|
javascript
|
function resolver(id, modules, circular, resolved, unresolved) {
unresolved[id] = true;
if (modules[id]) {
modules[id].forEach((dependency) => {
if (!resolved[dependency]) {
if (unresolved[dependency]) {
circular.push(getPath(dependency, unresolved));
return;
}
resolver(dependency, modules, circular, resolved, unresolved);
}
});
}
resolved[id] = true;
unresolved[id] = false;
}
|
[
"function",
"resolver",
"(",
"id",
",",
"modules",
",",
"circular",
",",
"resolved",
",",
"unresolved",
")",
"{",
"unresolved",
"[",
"id",
"]",
"=",
"true",
";",
"if",
"(",
"modules",
"[",
"id",
"]",
")",
"{",
"modules",
"[",
"id",
"]",
".",
"forEach",
"(",
"(",
"dependency",
")",
"=>",
"{",
"if",
"(",
"!",
"resolved",
"[",
"dependency",
"]",
")",
"{",
"if",
"(",
"unresolved",
"[",
"dependency",
"]",
")",
"{",
"circular",
".",
"push",
"(",
"getPath",
"(",
"dependency",
",",
"unresolved",
")",
")",
";",
"return",
";",
"}",
"resolver",
"(",
"dependency",
",",
"modules",
",",
"circular",
",",
"resolved",
",",
"unresolved",
")",
";",
"}",
"}",
")",
";",
"}",
"resolved",
"[",
"id",
"]",
"=",
"true",
";",
"unresolved",
"[",
"id",
"]",
"=",
"false",
";",
"}"
] |
A circular dependency is occurring when we see a software package
more than once, unless that software package has all its dependencies resolved.
@param {String} id
@param {Object} modules
@param {Object} circular
@param {Object} resolved
@param {Object} unresolved
|
[
"A",
"circular",
"dependency",
"is",
"occurring",
"when",
"we",
"see",
"a",
"software",
"package",
"more",
"than",
"once",
"unless",
"that",
"software",
"package",
"has",
"all",
"its",
"dependencies",
"resolved",
"."
] |
f8c3e640a51825ff7dc0aefe79510c8a584cf6cf
|
https://github.com/pahen/madge/blob/f8c3e640a51825ff7dc0aefe79510c8a584cf6cf/lib/cyclic.js#L29-L46
|
13,072
|
WeCodePixels/theia-sticky-sidebar
|
js/theia-sticky-sidebar.js
|
tryInitOrHookIntoEvents
|
function tryInitOrHookIntoEvents(options, $that) {
var success = tryInit(options, $that);
if (!success) {
console.log('TSS: Body width smaller than options.minWidth. Init is delayed.');
$(document).on('scroll.' + options.namespace, function (options, $that) {
return function (evt) {
var success = tryInit(options, $that);
if (success) {
$(this).unbind(evt);
}
};
}(options, $that));
$(window).on('resize.' + options.namespace, function (options, $that) {
return function (evt) {
var success = tryInit(options, $that);
if (success) {
$(this).unbind(evt);
}
};
}(options, $that))
}
}
|
javascript
|
function tryInitOrHookIntoEvents(options, $that) {
var success = tryInit(options, $that);
if (!success) {
console.log('TSS: Body width smaller than options.minWidth. Init is delayed.');
$(document).on('scroll.' + options.namespace, function (options, $that) {
return function (evt) {
var success = tryInit(options, $that);
if (success) {
$(this).unbind(evt);
}
};
}(options, $that));
$(window).on('resize.' + options.namespace, function (options, $that) {
return function (evt) {
var success = tryInit(options, $that);
if (success) {
$(this).unbind(evt);
}
};
}(options, $that))
}
}
|
[
"function",
"tryInitOrHookIntoEvents",
"(",
"options",
",",
"$that",
")",
"{",
"var",
"success",
"=",
"tryInit",
"(",
"options",
",",
"$that",
")",
";",
"if",
"(",
"!",
"success",
")",
"{",
"console",
".",
"log",
"(",
"'TSS: Body width smaller than options.minWidth. Init is delayed.'",
")",
";",
"$",
"(",
"document",
")",
".",
"on",
"(",
"'scroll.'",
"+",
"options",
".",
"namespace",
",",
"function",
"(",
"options",
",",
"$that",
")",
"{",
"return",
"function",
"(",
"evt",
")",
"{",
"var",
"success",
"=",
"tryInit",
"(",
"options",
",",
"$that",
")",
";",
"if",
"(",
"success",
")",
"{",
"$",
"(",
"this",
")",
".",
"unbind",
"(",
"evt",
")",
";",
"}",
"}",
";",
"}",
"(",
"options",
",",
"$that",
")",
")",
";",
"$",
"(",
"window",
")",
".",
"on",
"(",
"'resize.'",
"+",
"options",
".",
"namespace",
",",
"function",
"(",
"options",
",",
"$that",
")",
"{",
"return",
"function",
"(",
"evt",
")",
"{",
"var",
"success",
"=",
"tryInit",
"(",
"options",
",",
"$that",
")",
";",
"if",
"(",
"success",
")",
"{",
"$",
"(",
"this",
")",
".",
"unbind",
"(",
"evt",
")",
";",
"}",
"}",
";",
"}",
"(",
"options",
",",
"$that",
")",
")",
"}",
"}"
] |
Try doing init, otherwise hook into window.resize and document.scroll and try again then.
|
[
"Try",
"doing",
"init",
"otherwise",
"hook",
"into",
"window",
".",
"resize",
"and",
"document",
".",
"scroll",
"and",
"try",
"again",
"then",
"."
] |
8f13b3ce686c824d52118e73a812d374c5c00656
|
https://github.com/WeCodePixels/theia-sticky-sidebar/blob/8f13b3ce686c824d52118e73a812d374c5c00656/js/theia-sticky-sidebar.js#L33-L58
|
13,073
|
WeCodePixels/theia-sticky-sidebar
|
js/theia-sticky-sidebar.js
|
tryInit
|
function tryInit(options, $that) {
if (options.initialized === true) {
return true;
}
if ($('body').width() < options.minWidth) {
return false;
}
init(options, $that);
return true;
}
|
javascript
|
function tryInit(options, $that) {
if (options.initialized === true) {
return true;
}
if ($('body').width() < options.minWidth) {
return false;
}
init(options, $that);
return true;
}
|
[
"function",
"tryInit",
"(",
"options",
",",
"$that",
")",
"{",
"if",
"(",
"options",
".",
"initialized",
"===",
"true",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"$",
"(",
"'body'",
")",
".",
"width",
"(",
")",
"<",
"options",
".",
"minWidth",
")",
"{",
"return",
"false",
";",
"}",
"init",
"(",
"options",
",",
"$that",
")",
";",
"return",
"true",
";",
"}"
] |
Try doing init if proper conditions are met.
|
[
"Try",
"doing",
"init",
"if",
"proper",
"conditions",
"are",
"met",
"."
] |
8f13b3ce686c824d52118e73a812d374c5c00656
|
https://github.com/WeCodePixels/theia-sticky-sidebar/blob/8f13b3ce686c824d52118e73a812d374c5c00656/js/theia-sticky-sidebar.js#L61-L73
|
13,074
|
WeCodePixels/theia-sticky-sidebar
|
js/theia-sticky-sidebar.js
|
getClearedHeight
|
function getClearedHeight(e) {
var height = e.height();
e.children().each(function () {
height = Math.max(height, $(this).height());
});
return height;
}
|
javascript
|
function getClearedHeight(e) {
var height = e.height();
e.children().each(function () {
height = Math.max(height, $(this).height());
});
return height;
}
|
[
"function",
"getClearedHeight",
"(",
"e",
")",
"{",
"var",
"height",
"=",
"e",
".",
"height",
"(",
")",
";",
"e",
".",
"children",
"(",
")",
".",
"each",
"(",
"function",
"(",
")",
"{",
"height",
"=",
"Math",
".",
"max",
"(",
"height",
",",
"$",
"(",
"this",
")",
".",
"height",
"(",
")",
")",
";",
"}",
")",
";",
"return",
"height",
";",
"}"
] |
Get the height of a div as if its floated children were cleared. Note that this function fails if the floats are more than one level deep.
|
[
"Get",
"the",
"height",
"of",
"a",
"div",
"as",
"if",
"its",
"floated",
"children",
"were",
"cleared",
".",
"Note",
"that",
"this",
"function",
"fails",
"if",
"the",
"floats",
"are",
"more",
"than",
"one",
"level",
"deep",
"."
] |
8f13b3ce686c824d52118e73a812d374c5c00656
|
https://github.com/WeCodePixels/theia-sticky-sidebar/blob/8f13b3ce686c824d52118e73a812d374c5c00656/js/theia-sticky-sidebar.js#L341-L349
|
13,075
|
survivejs/webpack-merge
|
src/join-arrays-smart.js
|
isSameValue
|
function isSameValue(a, b) {
const [propA, propB] = [a, b].map(value => (
isArray(value) ? [...value].sort() : value
));
return isEqual(propA, propB);
}
|
javascript
|
function isSameValue(a, b) {
const [propA, propB] = [a, b].map(value => (
isArray(value) ? [...value].sort() : value
));
return isEqual(propA, propB);
}
|
[
"function",
"isSameValue",
"(",
"a",
",",
"b",
")",
"{",
"const",
"[",
"propA",
",",
"propB",
"]",
"=",
"[",
"a",
",",
"b",
"]",
".",
"map",
"(",
"value",
"=>",
"(",
"isArray",
"(",
"value",
")",
"?",
"[",
"...",
"value",
"]",
".",
"sort",
"(",
")",
":",
"value",
")",
")",
";",
"return",
"isEqual",
"(",
"propA",
",",
"propB",
")",
";",
"}"
] |
Check equality of two values using lodash's isEqual
Arrays need to be sorted for equality checking
but clone them first so as not to disrupt the sort order in tests
|
[
"Check",
"equality",
"of",
"two",
"values",
"using",
"lodash",
"s",
"isEqual",
"Arrays",
"need",
"to",
"be",
"sorted",
"for",
"equality",
"checking",
"but",
"clone",
"them",
"first",
"so",
"as",
"not",
"to",
"disrupt",
"the",
"sort",
"order",
"in",
"tests"
] |
c3a515687844ab97a416efebb2bdeadc802b0668
|
https://github.com/survivejs/webpack-merge/blob/c3a515687844ab97a416efebb2bdeadc802b0668/src/join-arrays-smart.js#L110-L116
|
13,076
|
WebReflection/hyperHTML
|
cjs/hyper/render.js
|
upgrade
|
function upgrade(template) {
const type = OWNER_SVG_ELEMENT in this ? 'svg' : 'html';
const tagger = new Tagger(type);
bewitched.set(this, {tagger, template: template});
this.textContent = '';
this.appendChild(tagger.apply(null, arguments));
}
|
javascript
|
function upgrade(template) {
const type = OWNER_SVG_ELEMENT in this ? 'svg' : 'html';
const tagger = new Tagger(type);
bewitched.set(this, {tagger, template: template});
this.textContent = '';
this.appendChild(tagger.apply(null, arguments));
}
|
[
"function",
"upgrade",
"(",
"template",
")",
"{",
"const",
"type",
"=",
"OWNER_SVG_ELEMENT",
"in",
"this",
"?",
"'svg'",
":",
"'html'",
";",
"const",
"tagger",
"=",
"new",
"Tagger",
"(",
"type",
")",
";",
"bewitched",
".",
"set",
"(",
"this",
",",
"{",
"tagger",
",",
"template",
":",
"template",
"}",
")",
";",
"this",
".",
"textContent",
"=",
"''",
";",
"this",
".",
"appendChild",
"(",
"tagger",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
")",
";",
"}"
] |
an upgrade is in charge of collecting template info, parse it once, if unknown, to map all interpolations as single DOM callbacks, relate such template to the current context, and render it after cleaning the context up
|
[
"an",
"upgrade",
"is",
"in",
"charge",
"of",
"collecting",
"template",
"info",
"parse",
"it",
"once",
"if",
"unknown",
"to",
"map",
"all",
"interpolations",
"as",
"single",
"DOM",
"callbacks",
"relate",
"such",
"template",
"to",
"the",
"current",
"context",
"and",
"render",
"it",
"after",
"cleaning",
"the",
"context",
"up"
] |
34f1006a9803c28cecd757a55f023752a6cfb8e1
|
https://github.com/WebReflection/hyperHTML/blob/34f1006a9803c28cecd757a55f023752a6cfb8e1/cjs/hyper/render.js#L31-L37
|
13,077
|
WebReflection/hyperHTML
|
cjs/index.js
|
hyper
|
function hyper(HTML) {
return arguments.length < 2 ?
(HTML == null ?
content('html') :
(typeof HTML === 'string' ?
hyper.wire(null, HTML) :
('raw' in HTML ?
content('html')(HTML) :
('nodeType' in HTML ?
hyper.bind(HTML) :
weakly(HTML, 'html')
)
)
)) :
('raw' in HTML ?
content('html') : hyper.wire
).apply(null, arguments);
}
|
javascript
|
function hyper(HTML) {
return arguments.length < 2 ?
(HTML == null ?
content('html') :
(typeof HTML === 'string' ?
hyper.wire(null, HTML) :
('raw' in HTML ?
content('html')(HTML) :
('nodeType' in HTML ?
hyper.bind(HTML) :
weakly(HTML, 'html')
)
)
)) :
('raw' in HTML ?
content('html') : hyper.wire
).apply(null, arguments);
}
|
[
"function",
"hyper",
"(",
"HTML",
")",
"{",
"return",
"arguments",
".",
"length",
"<",
"2",
"?",
"(",
"HTML",
"==",
"null",
"?",
"content",
"(",
"'html'",
")",
":",
"(",
"typeof",
"HTML",
"===",
"'string'",
"?",
"hyper",
".",
"wire",
"(",
"null",
",",
"HTML",
")",
":",
"(",
"'raw'",
"in",
"HTML",
"?",
"content",
"(",
"'html'",
")",
"(",
"HTML",
")",
":",
"(",
"'nodeType'",
"in",
"HTML",
"?",
"hyper",
".",
"bind",
"(",
"HTML",
")",
":",
"weakly",
"(",
"HTML",
",",
"'html'",
")",
")",
")",
")",
")",
":",
"(",
"'raw'",
"in",
"HTML",
"?",
"content",
"(",
"'html'",
")",
":",
"hyper",
".",
"wire",
")",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"}"
] |
by default, hyperHTML is a smart function that "magically" understands what's the best thing to do with passed arguments
|
[
"by",
"default",
"hyperHTML",
"is",
"a",
"smart",
"function",
"that",
"magically",
"understands",
"what",
"s",
"the",
"best",
"thing",
"to",
"do",
"with",
"passed",
"arguments"
] |
34f1006a9803c28cecd757a55f023752a6cfb8e1
|
https://github.com/WebReflection/hyperHTML/blob/34f1006a9803c28cecd757a55f023752a6cfb8e1/cjs/index.js#L59-L76
|
13,078
|
scottdejonge/map-icons
|
dist/js/map-icons.js
|
function (options) {
google.maps.Marker.prototype.setMap.apply(this, [options]);
(this.MarkerLabel) && this.MarkerLabel.setMap.apply(this.MarkerLabel, [options]);
}
|
javascript
|
function (options) {
google.maps.Marker.prototype.setMap.apply(this, [options]);
(this.MarkerLabel) && this.MarkerLabel.setMap.apply(this.MarkerLabel, [options]);
}
|
[
"function",
"(",
"options",
")",
"{",
"google",
".",
"maps",
".",
"Marker",
".",
"prototype",
".",
"setMap",
".",
"apply",
"(",
"this",
",",
"[",
"options",
"]",
")",
";",
"(",
"this",
".",
"MarkerLabel",
")",
"&&",
"this",
".",
"MarkerLabel",
".",
"setMap",
".",
"apply",
"(",
"this",
".",
"MarkerLabel",
",",
"[",
"options",
"]",
")",
";",
"}"
] |
Custom Marker SetMap
|
[
"Custom",
"Marker",
"SetMap"
] |
dbf6fd7caedd60d11b5bfb5f267a114a6847d012
|
https://github.com/scottdejonge/map-icons/blob/dbf6fd7caedd60d11b5bfb5f267a114a6847d012/dist/js/map-icons.js#L95-L98
|
|
13,079
|
scottdejonge/map-icons
|
dist/js/map-icons.js
|
function () {
this.div.parentNode.removeChild(this.div);
for (var i = 0, I = this.listeners.length; i < I; ++i) {
google.maps.event.removeListener(this.listeners[i]);
}
}
|
javascript
|
function () {
this.div.parentNode.removeChild(this.div);
for (var i = 0, I = this.listeners.length; i < I; ++i) {
google.maps.event.removeListener(this.listeners[i]);
}
}
|
[
"function",
"(",
")",
"{",
"this",
".",
"div",
".",
"parentNode",
".",
"removeChild",
"(",
"this",
".",
"div",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"I",
"=",
"this",
".",
"listeners",
".",
"length",
";",
"i",
"<",
"I",
";",
"++",
"i",
")",
"{",
"google",
".",
"maps",
".",
"event",
".",
"removeListener",
"(",
"this",
".",
"listeners",
"[",
"i",
"]",
")",
";",
"}",
"}"
] |
Marker Label onRemove
|
[
"Marker",
"Label",
"onRemove"
] |
dbf6fd7caedd60d11b5bfb5f267a114a6847d012
|
https://github.com/scottdejonge/map-icons/blob/dbf6fd7caedd60d11b5bfb5f267a114a6847d012/dist/js/map-icons.js#L119-L125
|
|
13,080
|
c9/architect
|
demos/calculator/plugins/calculator/calculator.js
|
basicAuth
|
function basicAuth(checker, realm) {
realm = realm || 'Authorization Required';
function unauthorized(res) {
res.writeHead(401, {
'WWW-Authenticate': 'Basic realm="' + realm + '"',
'Content-Length': 13
});
res.end("Unauthorized\n");
}
function badRequest(res) {
res.writeHead(400, {
"Content-Length": 12
});
res.end('Bad Request\n');
}
return function(req, res, next) {
var authorization = req.headers.authorization;
if (!authorization) return unauthorized(res);
var parts = authorization.split(' ');
var scheme = parts[0];
var credentials = new Buffer(parts[1], 'base64').toString().split(':');
if ('Basic' != scheme) return badRequest(res);
checker(req, credentials[0], credentials[1], function (user) {
if (!user) return unauthorized(res);
req.remoteUser = user;
next();
});
}
}
|
javascript
|
function basicAuth(checker, realm) {
realm = realm || 'Authorization Required';
function unauthorized(res) {
res.writeHead(401, {
'WWW-Authenticate': 'Basic realm="' + realm + '"',
'Content-Length': 13
});
res.end("Unauthorized\n");
}
function badRequest(res) {
res.writeHead(400, {
"Content-Length": 12
});
res.end('Bad Request\n');
}
return function(req, res, next) {
var authorization = req.headers.authorization;
if (!authorization) return unauthorized(res);
var parts = authorization.split(' ');
var scheme = parts[0];
var credentials = new Buffer(parts[1], 'base64').toString().split(':');
if ('Basic' != scheme) return badRequest(res);
checker(req, credentials[0], credentials[1], function (user) {
if (!user) return unauthorized(res);
req.remoteUser = user;
next();
});
}
}
|
[
"function",
"basicAuth",
"(",
"checker",
",",
"realm",
")",
"{",
"realm",
"=",
"realm",
"||",
"'Authorization Required'",
";",
"function",
"unauthorized",
"(",
"res",
")",
"{",
"res",
".",
"writeHead",
"(",
"401",
",",
"{",
"'WWW-Authenticate'",
":",
"'Basic realm=\"'",
"+",
"realm",
"+",
"'\"'",
",",
"'Content-Length'",
":",
"13",
"}",
")",
";",
"res",
".",
"end",
"(",
"\"Unauthorized\\n\"",
")",
";",
"}",
"function",
"badRequest",
"(",
"res",
")",
"{",
"res",
".",
"writeHead",
"(",
"400",
",",
"{",
"\"Content-Length\"",
":",
"12",
"}",
")",
";",
"res",
".",
"end",
"(",
"'Bad Request\\n'",
")",
";",
"}",
"return",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"authorization",
"=",
"req",
".",
"headers",
".",
"authorization",
";",
"if",
"(",
"!",
"authorization",
")",
"return",
"unauthorized",
"(",
"res",
")",
";",
"var",
"parts",
"=",
"authorization",
".",
"split",
"(",
"' '",
")",
";",
"var",
"scheme",
"=",
"parts",
"[",
"0",
"]",
";",
"var",
"credentials",
"=",
"new",
"Buffer",
"(",
"parts",
"[",
"1",
"]",
",",
"'base64'",
")",
".",
"toString",
"(",
")",
".",
"split",
"(",
"':'",
")",
";",
"if",
"(",
"'Basic'",
"!=",
"scheme",
")",
"return",
"badRequest",
"(",
"res",
")",
";",
"checker",
"(",
"req",
",",
"credentials",
"[",
"0",
"]",
",",
"credentials",
"[",
"1",
"]",
",",
"function",
"(",
"user",
")",
"{",
"if",
"(",
"!",
"user",
")",
"return",
"unauthorized",
"(",
"res",
")",
";",
"req",
".",
"remoteUser",
"=",
"user",
";",
"next",
"(",
")",
";",
"}",
")",
";",
"}",
"}"
] |
Based loosly on basicAuth from Connect Checker takes username and password and returns a user if valid Will force redirect if requested over HTTP instead of HTTPS
|
[
"Based",
"loosly",
"on",
"basicAuth",
"from",
"Connect",
"Checker",
"takes",
"username",
"and",
"password",
"and",
"returns",
"a",
"user",
"if",
"valid",
"Will",
"force",
"redirect",
"if",
"requested",
"over",
"HTTP",
"instead",
"of",
"HTTPS"
] |
aee3404bc6da8591858c5807b49ac66bc6ad2280
|
https://github.com/c9/architect/blob/aee3404bc6da8591858c5807b49ac66bc6ad2280/demos/calculator/plugins/calculator/calculator.js#L36-L68
|
13,081
|
team-gryff/react-monocle
|
src/reactParser.js
|
getReactProps
|
function getReactProps(node, parent) {
if (node.openingElement.attributes.length === 0 ||
htmlElements.indexOf(node.openingElement.name.name) > 0) return {};
const result = node.openingElement.attributes
.map(attribute => {
const name = attribute.name.name;
let valueName;
if (attribute.value === null) valueName = undefined;
else if (attribute.value.type === 'Literal') valueName = attribute.value.value;
else if (attribute.value.expression.type === 'Literal') {
valueName = attribute.value.expression.value;
} else if (attribute.value.expression.type === 'Identifier') {
valueName = attribute.value.expression.name;
} else if (attribute.value.expression.type === 'CallExpression') {
valueName = attribute.value.expression.callee.object.property.name;
} else if (attribute.value.expression.type === 'BinaryExpression') {
valueName = attribute.value.expression.left.name
+ attribute.value.expression.operator
+ (attribute.value.expression.right.name
|| attribute.value.expression.right.value);
} else if (attribute.value.expression.type === 'MemberExpression') {
let current = attribute.value.expression;
while (current && current.property) {
// && !current.property.name.match(/(state|props)/)
valueName = `.${current.property.name}${valueName || ''}`;
current = current.object;
if (current.type === 'Identifier') {
valueName = `.${current.name}${valueName || ''}`;
break;
}
}
valueName = valueName.replace('.', '');
} else if (attribute.value.expression.type === 'LogicalExpression') {
valueName = attribute.value.expression.left.property.name;
// valueType = attribute.value.expression.left.object.name;
} else if (attribute.value.expression.type === 'JSXElement') {
const nodez = attribute.value.expression;
const output = {
name: nodez.openingElement.name.name,
children: getChildJSXElements(nodez, parent),
props: getReactProps(nodez, parent),
state: {},
methods: [],
};
valueName = output;
} else valueName = escodegen.generate(attribute.value);
return {
name,
value: valueName,
parent,
};
});
return result;
}
|
javascript
|
function getReactProps(node, parent) {
if (node.openingElement.attributes.length === 0 ||
htmlElements.indexOf(node.openingElement.name.name) > 0) return {};
const result = node.openingElement.attributes
.map(attribute => {
const name = attribute.name.name;
let valueName;
if (attribute.value === null) valueName = undefined;
else if (attribute.value.type === 'Literal') valueName = attribute.value.value;
else if (attribute.value.expression.type === 'Literal') {
valueName = attribute.value.expression.value;
} else if (attribute.value.expression.type === 'Identifier') {
valueName = attribute.value.expression.name;
} else if (attribute.value.expression.type === 'CallExpression') {
valueName = attribute.value.expression.callee.object.property.name;
} else if (attribute.value.expression.type === 'BinaryExpression') {
valueName = attribute.value.expression.left.name
+ attribute.value.expression.operator
+ (attribute.value.expression.right.name
|| attribute.value.expression.right.value);
} else if (attribute.value.expression.type === 'MemberExpression') {
let current = attribute.value.expression;
while (current && current.property) {
// && !current.property.name.match(/(state|props)/)
valueName = `.${current.property.name}${valueName || ''}`;
current = current.object;
if (current.type === 'Identifier') {
valueName = `.${current.name}${valueName || ''}`;
break;
}
}
valueName = valueName.replace('.', '');
} else if (attribute.value.expression.type === 'LogicalExpression') {
valueName = attribute.value.expression.left.property.name;
// valueType = attribute.value.expression.left.object.name;
} else if (attribute.value.expression.type === 'JSXElement') {
const nodez = attribute.value.expression;
const output = {
name: nodez.openingElement.name.name,
children: getChildJSXElements(nodez, parent),
props: getReactProps(nodez, parent),
state: {},
methods: [],
};
valueName = output;
} else valueName = escodegen.generate(attribute.value);
return {
name,
value: valueName,
parent,
};
});
return result;
}
|
[
"function",
"getReactProps",
"(",
"node",
",",
"parent",
")",
"{",
"if",
"(",
"node",
".",
"openingElement",
".",
"attributes",
".",
"length",
"===",
"0",
"||",
"htmlElements",
".",
"indexOf",
"(",
"node",
".",
"openingElement",
".",
"name",
".",
"name",
")",
">",
"0",
")",
"return",
"{",
"}",
";",
"const",
"result",
"=",
"node",
".",
"openingElement",
".",
"attributes",
".",
"map",
"(",
"attribute",
"=>",
"{",
"const",
"name",
"=",
"attribute",
".",
"name",
".",
"name",
";",
"let",
"valueName",
";",
"if",
"(",
"attribute",
".",
"value",
"===",
"null",
")",
"valueName",
"=",
"undefined",
";",
"else",
"if",
"(",
"attribute",
".",
"value",
".",
"type",
"===",
"'Literal'",
")",
"valueName",
"=",
"attribute",
".",
"value",
".",
"value",
";",
"else",
"if",
"(",
"attribute",
".",
"value",
".",
"expression",
".",
"type",
"===",
"'Literal'",
")",
"{",
"valueName",
"=",
"attribute",
".",
"value",
".",
"expression",
".",
"value",
";",
"}",
"else",
"if",
"(",
"attribute",
".",
"value",
".",
"expression",
".",
"type",
"===",
"'Identifier'",
")",
"{",
"valueName",
"=",
"attribute",
".",
"value",
".",
"expression",
".",
"name",
";",
"}",
"else",
"if",
"(",
"attribute",
".",
"value",
".",
"expression",
".",
"type",
"===",
"'CallExpression'",
")",
"{",
"valueName",
"=",
"attribute",
".",
"value",
".",
"expression",
".",
"callee",
".",
"object",
".",
"property",
".",
"name",
";",
"}",
"else",
"if",
"(",
"attribute",
".",
"value",
".",
"expression",
".",
"type",
"===",
"'BinaryExpression'",
")",
"{",
"valueName",
"=",
"attribute",
".",
"value",
".",
"expression",
".",
"left",
".",
"name",
"+",
"attribute",
".",
"value",
".",
"expression",
".",
"operator",
"+",
"(",
"attribute",
".",
"value",
".",
"expression",
".",
"right",
".",
"name",
"||",
"attribute",
".",
"value",
".",
"expression",
".",
"right",
".",
"value",
")",
";",
"}",
"else",
"if",
"(",
"attribute",
".",
"value",
".",
"expression",
".",
"type",
"===",
"'MemberExpression'",
")",
"{",
"let",
"current",
"=",
"attribute",
".",
"value",
".",
"expression",
";",
"while",
"(",
"current",
"&&",
"current",
".",
"property",
")",
"{",
"// && !current.property.name.match(/(state|props)/)",
"valueName",
"=",
"`",
"${",
"current",
".",
"property",
".",
"name",
"}",
"${",
"valueName",
"||",
"''",
"}",
"`",
";",
"current",
"=",
"current",
".",
"object",
";",
"if",
"(",
"current",
".",
"type",
"===",
"'Identifier'",
")",
"{",
"valueName",
"=",
"`",
"${",
"current",
".",
"name",
"}",
"${",
"valueName",
"||",
"''",
"}",
"`",
";",
"break",
";",
"}",
"}",
"valueName",
"=",
"valueName",
".",
"replace",
"(",
"'.'",
",",
"''",
")",
";",
"}",
"else",
"if",
"(",
"attribute",
".",
"value",
".",
"expression",
".",
"type",
"===",
"'LogicalExpression'",
")",
"{",
"valueName",
"=",
"attribute",
".",
"value",
".",
"expression",
".",
"left",
".",
"property",
".",
"name",
";",
"// valueType = attribute.value.expression.left.object.name;",
"}",
"else",
"if",
"(",
"attribute",
".",
"value",
".",
"expression",
".",
"type",
"===",
"'JSXElement'",
")",
"{",
"const",
"nodez",
"=",
"attribute",
".",
"value",
".",
"expression",
";",
"const",
"output",
"=",
"{",
"name",
":",
"nodez",
".",
"openingElement",
".",
"name",
".",
"name",
",",
"children",
":",
"getChildJSXElements",
"(",
"nodez",
",",
"parent",
")",
",",
"props",
":",
"getReactProps",
"(",
"nodez",
",",
"parent",
")",
",",
"state",
":",
"{",
"}",
",",
"methods",
":",
"[",
"]",
",",
"}",
";",
"valueName",
"=",
"output",
";",
"}",
"else",
"valueName",
"=",
"escodegen",
".",
"generate",
"(",
"attribute",
".",
"value",
")",
";",
"return",
"{",
"name",
",",
"value",
":",
"valueName",
",",
"parent",
",",
"}",
";",
"}",
")",
";",
"return",
"result",
";",
"}"
] |
Returns array of props from React component passed to input
@param {Node} node
@returns {Array} Array of all JSX props on React component
|
[
"Returns",
"array",
"of",
"props",
"from",
"React",
"component",
"passed",
"to",
"input"
] |
b90f26e2e6440d7e8f2e596237ec1ed598827453
|
https://github.com/team-gryff/react-monocle/blob/b90f26e2e6440d7e8f2e596237ec1ed598827453/src/reactParser.js#L33-L87
|
13,082
|
team-gryff/react-monocle
|
src/reactParser.js
|
getChildJSXElements
|
function getChildJSXElements(node, parent) {
if (node.children.length === 0) return [];
const childJsxComponentsArr = node
.children
.filter(jsx => jsx.type === 'JSXElement'
&& htmlElements.indexOf(jsx.openingElement.name.name) < 0);
return childJsxComponentsArr
.map(child => {
return {
name: child.openingElement.name.name,
children: getChildJSXElements(child, parent),
props: getReactProps(child, parent),
state: {},
methods: [],
};
});
}
|
javascript
|
function getChildJSXElements(node, parent) {
if (node.children.length === 0) return [];
const childJsxComponentsArr = node
.children
.filter(jsx => jsx.type === 'JSXElement'
&& htmlElements.indexOf(jsx.openingElement.name.name) < 0);
return childJsxComponentsArr
.map(child => {
return {
name: child.openingElement.name.name,
children: getChildJSXElements(child, parent),
props: getReactProps(child, parent),
state: {},
methods: [],
};
});
}
|
[
"function",
"getChildJSXElements",
"(",
"node",
",",
"parent",
")",
"{",
"if",
"(",
"node",
".",
"children",
".",
"length",
"===",
"0",
")",
"return",
"[",
"]",
";",
"const",
"childJsxComponentsArr",
"=",
"node",
".",
"children",
".",
"filter",
"(",
"jsx",
"=>",
"jsx",
".",
"type",
"===",
"'JSXElement'",
"&&",
"htmlElements",
".",
"indexOf",
"(",
"jsx",
".",
"openingElement",
".",
"name",
".",
"name",
")",
"<",
"0",
")",
";",
"return",
"childJsxComponentsArr",
".",
"map",
"(",
"child",
"=>",
"{",
"return",
"{",
"name",
":",
"child",
".",
"openingElement",
".",
"name",
".",
"name",
",",
"children",
":",
"getChildJSXElements",
"(",
"child",
",",
"parent",
")",
",",
"props",
":",
"getReactProps",
"(",
"child",
",",
"parent",
")",
",",
"state",
":",
"{",
"}",
",",
"methods",
":",
"[",
"]",
",",
"}",
";",
"}",
")",
";",
"}"
] |
Returns array of children components of React component passed to input
@param {Node} node
@returns {Array} Array of (nested) children of React component passed in
|
[
"Returns",
"array",
"of",
"children",
"components",
"of",
"React",
"component",
"passed",
"to",
"input"
] |
b90f26e2e6440d7e8f2e596237ec1ed598827453
|
https://github.com/team-gryff/react-monocle/blob/b90f26e2e6440d7e8f2e596237ec1ed598827453/src/reactParser.js#L94-L110
|
13,083
|
team-gryff/react-monocle
|
src/reactParser.js
|
isES6ReactComponent
|
function isES6ReactComponent(node) {
return (node.superClass.property && node.superClass.property.name === 'Component')
|| node.superClass.name === 'Component';
}
|
javascript
|
function isES6ReactComponent(node) {
return (node.superClass.property && node.superClass.property.name === 'Component')
|| node.superClass.name === 'Component';
}
|
[
"function",
"isES6ReactComponent",
"(",
"node",
")",
"{",
"return",
"(",
"node",
".",
"superClass",
".",
"property",
"&&",
"node",
".",
"superClass",
".",
"property",
".",
"name",
"===",
"'Component'",
")",
"||",
"node",
".",
"superClass",
".",
"name",
"===",
"'Component'",
";",
"}"
] |
Returns if AST node is an ES6 React component
@param {Node} node
@return {Boolean} Determines if AST node is a React component node
|
[
"Returns",
"if",
"AST",
"node",
"is",
"an",
"ES6",
"React",
"component"
] |
b90f26e2e6440d7e8f2e596237ec1ed598827453
|
https://github.com/team-gryff/react-monocle/blob/b90f26e2e6440d7e8f2e596237ec1ed598827453/src/reactParser.js#L275-L278
|
13,084
|
team-gryff/react-monocle
|
src/reactParser.js
|
jsToAst
|
function jsToAst(js) {
const ast = acorn.parse(js, {
plugins: { jsx: true },
});
if (ast.body.length === 0) throw new Error('Empty AST input');
return ast;
}
|
javascript
|
function jsToAst(js) {
const ast = acorn.parse(js, {
plugins: { jsx: true },
});
if (ast.body.length === 0) throw new Error('Empty AST input');
return ast;
}
|
[
"function",
"jsToAst",
"(",
"js",
")",
"{",
"const",
"ast",
"=",
"acorn",
".",
"parse",
"(",
"js",
",",
"{",
"plugins",
":",
"{",
"jsx",
":",
"true",
"}",
",",
"}",
")",
";",
"if",
"(",
"ast",
".",
"body",
".",
"length",
"===",
"0",
")",
"throw",
"new",
"Error",
"(",
"'Empty AST input'",
")",
";",
"return",
"ast",
";",
"}"
] |
Helper function to convert Javascript stringified code to an AST using acorn-jsx library
@param js
|
[
"Helper",
"function",
"to",
"convert",
"Javascript",
"stringified",
"code",
"to",
"an",
"AST",
"using",
"acorn",
"-",
"jsx",
"library"
] |
b90f26e2e6440d7e8f2e596237ec1ed598827453
|
https://github.com/team-gryff/react-monocle/blob/b90f26e2e6440d7e8f2e596237ec1ed598827453/src/reactParser.js#L549-L555
|
13,085
|
team-gryff/react-monocle
|
src/d3DataBuilder.js
|
d3DataBuilder
|
function d3DataBuilder(obj) {
if (!obj.ENTRY) throw new Error('Entry component not found');
const formatted = {};
// parsing AST into formatted objects based on ES5/ES6 syntax
Object.entries(obj).forEach(entry => {
if (entry[0] === 'ENTRY') return;
const componentChecker = reactParser.componentChecker(entry[1]);
switch (componentChecker) {
case 'ES6':
formatted[entry[0]] = reactParser.getES6ReactComponents(entry[1]);
break;
case 'ES5':
formatted[entry[0]] = reactParser.getES5ReactComponents(entry[1]);
break;
default:
formatted[entry[0]] = reactParser.getStatelessFunctionalComponents(entry[1], entry[0]);
break;
}
});
Object.values(formatted).forEach(node => {
node.children.forEach(ele => {
if (Array.isArray(ele.props)) {
ele.props.forEach((propped, i) => {
if (typeof propped.value === 'object' && propped.value.name && propped.value.children) {
formatted[propped.parent].children.push(propped.value);
ele.props.splice(i, 1);
}
});
}
});
});
formatted.monocleENTRY = obj.ENTRY;
fs.writeFileSync('data.js', JSON.stringify(formatted, null, 2));
return formatted;
}
|
javascript
|
function d3DataBuilder(obj) {
if (!obj.ENTRY) throw new Error('Entry component not found');
const formatted = {};
// parsing AST into formatted objects based on ES5/ES6 syntax
Object.entries(obj).forEach(entry => {
if (entry[0] === 'ENTRY') return;
const componentChecker = reactParser.componentChecker(entry[1]);
switch (componentChecker) {
case 'ES6':
formatted[entry[0]] = reactParser.getES6ReactComponents(entry[1]);
break;
case 'ES5':
formatted[entry[0]] = reactParser.getES5ReactComponents(entry[1]);
break;
default:
formatted[entry[0]] = reactParser.getStatelessFunctionalComponents(entry[1], entry[0]);
break;
}
});
Object.values(formatted).forEach(node => {
node.children.forEach(ele => {
if (Array.isArray(ele.props)) {
ele.props.forEach((propped, i) => {
if (typeof propped.value === 'object' && propped.value.name && propped.value.children) {
formatted[propped.parent].children.push(propped.value);
ele.props.splice(i, 1);
}
});
}
});
});
formatted.monocleENTRY = obj.ENTRY;
fs.writeFileSync('data.js', JSON.stringify(formatted, null, 2));
return formatted;
}
|
[
"function",
"d3DataBuilder",
"(",
"obj",
")",
"{",
"if",
"(",
"!",
"obj",
".",
"ENTRY",
")",
"throw",
"new",
"Error",
"(",
"'Entry component not found'",
")",
";",
"const",
"formatted",
"=",
"{",
"}",
";",
"// parsing AST into formatted objects based on ES5/ES6 syntax",
"Object",
".",
"entries",
"(",
"obj",
")",
".",
"forEach",
"(",
"entry",
"=>",
"{",
"if",
"(",
"entry",
"[",
"0",
"]",
"===",
"'ENTRY'",
")",
"return",
";",
"const",
"componentChecker",
"=",
"reactParser",
".",
"componentChecker",
"(",
"entry",
"[",
"1",
"]",
")",
";",
"switch",
"(",
"componentChecker",
")",
"{",
"case",
"'ES6'",
":",
"formatted",
"[",
"entry",
"[",
"0",
"]",
"]",
"=",
"reactParser",
".",
"getES6ReactComponents",
"(",
"entry",
"[",
"1",
"]",
")",
";",
"break",
";",
"case",
"'ES5'",
":",
"formatted",
"[",
"entry",
"[",
"0",
"]",
"]",
"=",
"reactParser",
".",
"getES5ReactComponents",
"(",
"entry",
"[",
"1",
"]",
")",
";",
"break",
";",
"default",
":",
"formatted",
"[",
"entry",
"[",
"0",
"]",
"]",
"=",
"reactParser",
".",
"getStatelessFunctionalComponents",
"(",
"entry",
"[",
"1",
"]",
",",
"entry",
"[",
"0",
"]",
")",
";",
"break",
";",
"}",
"}",
")",
";",
"Object",
".",
"values",
"(",
"formatted",
")",
".",
"forEach",
"(",
"node",
"=>",
"{",
"node",
".",
"children",
".",
"forEach",
"(",
"ele",
"=>",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"ele",
".",
"props",
")",
")",
"{",
"ele",
".",
"props",
".",
"forEach",
"(",
"(",
"propped",
",",
"i",
")",
"=>",
"{",
"if",
"(",
"typeof",
"propped",
".",
"value",
"===",
"'object'",
"&&",
"propped",
".",
"value",
".",
"name",
"&&",
"propped",
".",
"value",
".",
"children",
")",
"{",
"formatted",
"[",
"propped",
".",
"parent",
"]",
".",
"children",
".",
"push",
"(",
"propped",
".",
"value",
")",
";",
"ele",
".",
"props",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"formatted",
".",
"monocleENTRY",
"=",
"obj",
".",
"ENTRY",
";",
"fs",
".",
"writeFileSync",
"(",
"'data.js'",
",",
"JSON",
".",
"stringify",
"(",
"formatted",
",",
"null",
",",
"2",
")",
")",
";",
"return",
"formatted",
";",
"}"
] |
Takes in a formatted object and returns the tree object that D3 will need
@param {obj} Object
@return {Object} Tree object for D3
|
[
"Takes",
"in",
"a",
"formatted",
"object",
"and",
"returns",
"the",
"tree",
"object",
"that",
"D3",
"will",
"need"
] |
b90f26e2e6440d7e8f2e596237ec1ed598827453
|
https://github.com/team-gryff/react-monocle/blob/b90f26e2e6440d7e8f2e596237ec1ed598827453/src/d3DataBuilder.js#L10-L48
|
13,086
|
brandonmowat/react-chat-ui
|
demo/bundle.js
|
assignFiberPropertiesInDEV
|
function assignFiberPropertiesInDEV(target, source) {
if (target === null) {
// This Fiber's initial properties will always be overwritten.
// We only use a Fiber to ensure the same hidden class so DEV isn't slow.
target = createFiber(IndeterminateComponent, null, null, NoContext);
}
// This is intentionally written as a list of all properties.
// We tried to use Object.assign() instead but this is called in
// the hottest path, and Object.assign() was too slow:
// https://github.com/facebook/react/issues/12502
// This code is DEV-only so size is not a concern.
target.tag = source.tag;
target.key = source.key;
target.elementType = source.elementType;
target.type = source.type;
target.stateNode = source.stateNode;
target.return = source.return;
target.child = source.child;
target.sibling = source.sibling;
target.index = source.index;
target.ref = source.ref;
target.pendingProps = source.pendingProps;
target.memoizedProps = source.memoizedProps;
target.updateQueue = source.updateQueue;
target.memoizedState = source.memoizedState;
target.contextDependencies = source.contextDependencies;
target.mode = source.mode;
target.effectTag = source.effectTag;
target.nextEffect = source.nextEffect;
target.firstEffect = source.firstEffect;
target.lastEffect = source.lastEffect;
target.expirationTime = source.expirationTime;
target.childExpirationTime = source.childExpirationTime;
target.alternate = source.alternate;
if (enableProfilerTimer) {
target.actualDuration = source.actualDuration;
target.actualStartTime = source.actualStartTime;
target.selfBaseDuration = source.selfBaseDuration;
target.treeBaseDuration = source.treeBaseDuration;
}
target._debugID = source._debugID;
target._debugSource = source._debugSource;
target._debugOwner = source._debugOwner;
target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
target._debugHookTypes = source._debugHookTypes;
return target;
}
|
javascript
|
function assignFiberPropertiesInDEV(target, source) {
if (target === null) {
// This Fiber's initial properties will always be overwritten.
// We only use a Fiber to ensure the same hidden class so DEV isn't slow.
target = createFiber(IndeterminateComponent, null, null, NoContext);
}
// This is intentionally written as a list of all properties.
// We tried to use Object.assign() instead but this is called in
// the hottest path, and Object.assign() was too slow:
// https://github.com/facebook/react/issues/12502
// This code is DEV-only so size is not a concern.
target.tag = source.tag;
target.key = source.key;
target.elementType = source.elementType;
target.type = source.type;
target.stateNode = source.stateNode;
target.return = source.return;
target.child = source.child;
target.sibling = source.sibling;
target.index = source.index;
target.ref = source.ref;
target.pendingProps = source.pendingProps;
target.memoizedProps = source.memoizedProps;
target.updateQueue = source.updateQueue;
target.memoizedState = source.memoizedState;
target.contextDependencies = source.contextDependencies;
target.mode = source.mode;
target.effectTag = source.effectTag;
target.nextEffect = source.nextEffect;
target.firstEffect = source.firstEffect;
target.lastEffect = source.lastEffect;
target.expirationTime = source.expirationTime;
target.childExpirationTime = source.childExpirationTime;
target.alternate = source.alternate;
if (enableProfilerTimer) {
target.actualDuration = source.actualDuration;
target.actualStartTime = source.actualStartTime;
target.selfBaseDuration = source.selfBaseDuration;
target.treeBaseDuration = source.treeBaseDuration;
}
target._debugID = source._debugID;
target._debugSource = source._debugSource;
target._debugOwner = source._debugOwner;
target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
target._debugHookTypes = source._debugHookTypes;
return target;
}
|
[
"function",
"assignFiberPropertiesInDEV",
"(",
"target",
",",
"source",
")",
"{",
"if",
"(",
"target",
"===",
"null",
")",
"{",
"// This Fiber's initial properties will always be overwritten.",
"// We only use a Fiber to ensure the same hidden class so DEV isn't slow.",
"target",
"=",
"createFiber",
"(",
"IndeterminateComponent",
",",
"null",
",",
"null",
",",
"NoContext",
")",
";",
"}",
"// This is intentionally written as a list of all properties.",
"// We tried to use Object.assign() instead but this is called in",
"// the hottest path, and Object.assign() was too slow:",
"// https://github.com/facebook/react/issues/12502",
"// This code is DEV-only so size is not a concern.",
"target",
".",
"tag",
"=",
"source",
".",
"tag",
";",
"target",
".",
"key",
"=",
"source",
".",
"key",
";",
"target",
".",
"elementType",
"=",
"source",
".",
"elementType",
";",
"target",
".",
"type",
"=",
"source",
".",
"type",
";",
"target",
".",
"stateNode",
"=",
"source",
".",
"stateNode",
";",
"target",
".",
"return",
"=",
"source",
".",
"return",
";",
"target",
".",
"child",
"=",
"source",
".",
"child",
";",
"target",
".",
"sibling",
"=",
"source",
".",
"sibling",
";",
"target",
".",
"index",
"=",
"source",
".",
"index",
";",
"target",
".",
"ref",
"=",
"source",
".",
"ref",
";",
"target",
".",
"pendingProps",
"=",
"source",
".",
"pendingProps",
";",
"target",
".",
"memoizedProps",
"=",
"source",
".",
"memoizedProps",
";",
"target",
".",
"updateQueue",
"=",
"source",
".",
"updateQueue",
";",
"target",
".",
"memoizedState",
"=",
"source",
".",
"memoizedState",
";",
"target",
".",
"contextDependencies",
"=",
"source",
".",
"contextDependencies",
";",
"target",
".",
"mode",
"=",
"source",
".",
"mode",
";",
"target",
".",
"effectTag",
"=",
"source",
".",
"effectTag",
";",
"target",
".",
"nextEffect",
"=",
"source",
".",
"nextEffect",
";",
"target",
".",
"firstEffect",
"=",
"source",
".",
"firstEffect",
";",
"target",
".",
"lastEffect",
"=",
"source",
".",
"lastEffect",
";",
"target",
".",
"expirationTime",
"=",
"source",
".",
"expirationTime",
";",
"target",
".",
"childExpirationTime",
"=",
"source",
".",
"childExpirationTime",
";",
"target",
".",
"alternate",
"=",
"source",
".",
"alternate",
";",
"if",
"(",
"enableProfilerTimer",
")",
"{",
"target",
".",
"actualDuration",
"=",
"source",
".",
"actualDuration",
";",
"target",
".",
"actualStartTime",
"=",
"source",
".",
"actualStartTime",
";",
"target",
".",
"selfBaseDuration",
"=",
"source",
".",
"selfBaseDuration",
";",
"target",
".",
"treeBaseDuration",
"=",
"source",
".",
"treeBaseDuration",
";",
"}",
"target",
".",
"_debugID",
"=",
"source",
".",
"_debugID",
";",
"target",
".",
"_debugSource",
"=",
"source",
".",
"_debugSource",
";",
"target",
".",
"_debugOwner",
"=",
"source",
".",
"_debugOwner",
";",
"target",
".",
"_debugIsCurrentlyTiming",
"=",
"source",
".",
"_debugIsCurrentlyTiming",
";",
"target",
".",
"_debugHookTypes",
"=",
"source",
".",
"_debugHookTypes",
";",
"return",
"target",
";",
"}"
] |
Used for stashing WIP properties to replay failed work in DEV.
|
[
"Used",
"for",
"stashing",
"WIP",
"properties",
"to",
"replay",
"failed",
"work",
"in",
"DEV",
"."
] |
de554aa20b8751fbe389585bb7bade581ce63659
|
https://github.com/brandonmowat/react-chat-ui/blob/de554aa20b8751fbe389585bb7bade581ce63659/demo/bundle.js#L11329-L11377
|
13,087
|
unifiedjs/unified
|
index.js
|
processor
|
function processor() {
var destination = unified()
var length = attachers.length
var index = -1
while (++index < length) {
destination.use.apply(null, attachers[index])
}
destination.data(extend(true, {}, namespace))
return destination
}
|
javascript
|
function processor() {
var destination = unified()
var length = attachers.length
var index = -1
while (++index < length) {
destination.use.apply(null, attachers[index])
}
destination.data(extend(true, {}, namespace))
return destination
}
|
[
"function",
"processor",
"(",
")",
"{",
"var",
"destination",
"=",
"unified",
"(",
")",
"var",
"length",
"=",
"attachers",
".",
"length",
"var",
"index",
"=",
"-",
"1",
"while",
"(",
"++",
"index",
"<",
"length",
")",
"{",
"destination",
".",
"use",
".",
"apply",
"(",
"null",
",",
"attachers",
"[",
"index",
"]",
")",
"}",
"destination",
".",
"data",
"(",
"extend",
"(",
"true",
",",
"{",
"}",
",",
"namespace",
")",
")",
"return",
"destination",
"}"
] |
Create a new processor based on the processor in the current scope.
|
[
"Create",
"a",
"new",
"processor",
"based",
"on",
"the",
"processor",
"in",
"the",
"current",
"scope",
"."
] |
0dc92d6397a7fbbe70a93475db1bd585e12d1845
|
https://github.com/unifiedjs/unified/blob/0dc92d6397a7fbbe70a93475db1bd585e12d1845/index.js#L74-L86
|
13,088
|
tradle/react-native-udp
|
examples/rctsockets/index.ios.js
|
toByteArray
|
function toByteArray(obj) {
var uint = new Uint8Array(obj.length);
for (var i = 0, l = obj.length; i < l; i++){
uint[i] = obj.charCodeAt(i);
}
return new Uint8Array(uint);
}
|
javascript
|
function toByteArray(obj) {
var uint = new Uint8Array(obj.length);
for (var i = 0, l = obj.length; i < l; i++){
uint[i] = obj.charCodeAt(i);
}
return new Uint8Array(uint);
}
|
[
"function",
"toByteArray",
"(",
"obj",
")",
"{",
"var",
"uint",
"=",
"new",
"Uint8Array",
"(",
"obj",
".",
"length",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"obj",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"uint",
"[",
"i",
"]",
"=",
"obj",
".",
"charCodeAt",
"(",
"i",
")",
";",
"}",
"return",
"new",
"Uint8Array",
"(",
"uint",
")",
";",
"}"
] |
only works for 8-bit chars
|
[
"only",
"works",
"for",
"8",
"-",
"bit",
"chars"
] |
9d55560d28a3a4603bca79329185aa4ce86a7e99
|
https://github.com/tradle/react-native-udp/blob/9d55560d28a3a4603bca79329185aa4ce86a7e99/examples/rctsockets/index.ios.js#L24-L31
|
13,089
|
smartcar/node-sdk
|
lib/vehicle.js
|
Vehicle
|
function Vehicle(id, token, unitSystem) {
if (!(this instanceof Vehicle)) {
// eslint-disable-next-line max-len
throw new TypeError("Class constructor Vehicle cannot be invoked without 'new'");
}
this.id = id;
this.token = token;
this.request = util.request.defaults({
baseUrl: util.getUrl(this.id),
auth: {
bearer: this.token,
},
});
this.setUnitSystem(unitSystem || 'metric');
}
|
javascript
|
function Vehicle(id, token, unitSystem) {
if (!(this instanceof Vehicle)) {
// eslint-disable-next-line max-len
throw new TypeError("Class constructor Vehicle cannot be invoked without 'new'");
}
this.id = id;
this.token = token;
this.request = util.request.defaults({
baseUrl: util.getUrl(this.id),
auth: {
bearer: this.token,
},
});
this.setUnitSystem(unitSystem || 'metric');
}
|
[
"function",
"Vehicle",
"(",
"id",
",",
"token",
",",
"unitSystem",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Vehicle",
")",
")",
"{",
"// eslint-disable-next-line max-len",
"throw",
"new",
"TypeError",
"(",
"\"Class constructor Vehicle cannot be invoked without 'new'\"",
")",
";",
"}",
"this",
".",
"id",
"=",
"id",
";",
"this",
".",
"token",
"=",
"token",
";",
"this",
".",
"request",
"=",
"util",
".",
"request",
".",
"defaults",
"(",
"{",
"baseUrl",
":",
"util",
".",
"getUrl",
"(",
"this",
".",
"id",
")",
",",
"auth",
":",
"{",
"bearer",
":",
"this",
".",
"token",
",",
"}",
",",
"}",
")",
";",
"this",
".",
"setUnitSystem",
"(",
"unitSystem",
"||",
"'metric'",
")",
";",
"}"
] |
Initializes a new Vehicle to use for making requests to the Smartcar API.
@constructor
@param {String} id - The vehicle's unique identifier. Retrieve a user's
vehicle id using {@link module:smartcar.getVehicleIds}.
@param {String} token - A valid access token
@param {String} [unitSystem=metric] - The unit system to use for vehicle data
, must be either `metric` or `imperial`.
|
[
"Initializes",
"a",
"new",
"Vehicle",
"to",
"use",
"for",
"making",
"requests",
"to",
"the",
"Smartcar",
"API",
"."
] |
b783137f2e98abf97bbb199d9de7ed597f7dec81
|
https://github.com/smartcar/node-sdk/blob/b783137f2e98abf97bbb199d9de7ed597f7dec81/lib/vehicle.js#L28-L43
|
13,090
|
gruntjs/grunt-contrib-uglify
|
tasks/uglify.js
|
relativePath
|
function relativePath(file1, file2) {
var file1Dirname = path.dirname(file1);
var file2Dirname = path.dirname(file2);
if (file1Dirname !== file2Dirname) {
return path.relative(file1Dirname, file2Dirname);
}
return '';
}
|
javascript
|
function relativePath(file1, file2) {
var file1Dirname = path.dirname(file1);
var file2Dirname = path.dirname(file2);
if (file1Dirname !== file2Dirname) {
return path.relative(file1Dirname, file2Dirname);
}
return '';
}
|
[
"function",
"relativePath",
"(",
"file1",
",",
"file2",
")",
"{",
"var",
"file1Dirname",
"=",
"path",
".",
"dirname",
"(",
"file1",
")",
";",
"var",
"file2Dirname",
"=",
"path",
".",
"dirname",
"(",
"file2",
")",
";",
"if",
"(",
"file1Dirname",
"!==",
"file2Dirname",
")",
"{",
"return",
"path",
".",
"relative",
"(",
"file1Dirname",
",",
"file2Dirname",
")",
";",
"}",
"return",
"''",
";",
"}"
] |
Return the relative path from file1 => file2
|
[
"Return",
"the",
"relative",
"path",
"from",
"file1",
"=",
">",
"file2"
] |
f65dbb96ec0e080ae5892d5144b0048379d1fec0
|
https://github.com/gruntjs/grunt-contrib-uglify/blob/f65dbb96ec0e080ae5892d5144b0048379d1fec0/tasks/uglify.js#L18-L26
|
13,091
|
kswedberg/jquery-smooth-scroll
|
lib/jquery.ba-bbq.js
|
curry
|
function curry( func ) {
var args = aps.call( arguments, 1 );
return function() {
return func.apply( this, args.concat( aps.call( arguments ) ) );
};
}
|
javascript
|
function curry( func ) {
var args = aps.call( arguments, 1 );
return function() {
return func.apply( this, args.concat( aps.call( arguments ) ) );
};
}
|
[
"function",
"curry",
"(",
"func",
")",
"{",
"var",
"args",
"=",
"aps",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"return",
"function",
"(",
")",
"{",
"return",
"func",
".",
"apply",
"(",
"this",
",",
"args",
".",
"concat",
"(",
"aps",
".",
"call",
"(",
"arguments",
")",
")",
")",
";",
"}",
";",
"}"
] |
Why write the same function twice? Let's curry! Mmmm, curry..
|
[
"Why",
"write",
"the",
"same",
"function",
"twice?",
"Let",
"s",
"curry!",
"Mmmm",
"curry",
".."
] |
965affd7edd2dffb034bf5b706c93d6a56d8ab97
|
https://github.com/kswedberg/jquery-smooth-scroll/blob/965affd7edd2dffb034bf5b706c93d6a56d8ab97/lib/jquery.ba-bbq.js#L124-L130
|
13,092
|
benfred/venn.js
|
src/diagram.js
|
function(d) {
return function(t) {
var c = d.sets.map(function(set) {
var start = previous[set], end = circles[set];
if (!start) {
start = {x : width/2, y : height/2, radius : 1};
}
if (!end) {
end = {x : width/2, y : height/2, radius : 1};
}
return {'x' : start.x * (1 - t) + end.x * t,
'y' : start.y * (1 - t) + end.y * t,
'radius' : start.radius * (1 - t) + end.radius * t};
});
return intersectionAreaPath(c);
};
}
|
javascript
|
function(d) {
return function(t) {
var c = d.sets.map(function(set) {
var start = previous[set], end = circles[set];
if (!start) {
start = {x : width/2, y : height/2, radius : 1};
}
if (!end) {
end = {x : width/2, y : height/2, radius : 1};
}
return {'x' : start.x * (1 - t) + end.x * t,
'y' : start.y * (1 - t) + end.y * t,
'radius' : start.radius * (1 - t) + end.radius * t};
});
return intersectionAreaPath(c);
};
}
|
[
"function",
"(",
"d",
")",
"{",
"return",
"function",
"(",
"t",
")",
"{",
"var",
"c",
"=",
"d",
".",
"sets",
".",
"map",
"(",
"function",
"(",
"set",
")",
"{",
"var",
"start",
"=",
"previous",
"[",
"set",
"]",
",",
"end",
"=",
"circles",
"[",
"set",
"]",
";",
"if",
"(",
"!",
"start",
")",
"{",
"start",
"=",
"{",
"x",
":",
"width",
"/",
"2",
",",
"y",
":",
"height",
"/",
"2",
",",
"radius",
":",
"1",
"}",
";",
"}",
"if",
"(",
"!",
"end",
")",
"{",
"end",
"=",
"{",
"x",
":",
"width",
"/",
"2",
",",
"y",
":",
"height",
"/",
"2",
",",
"radius",
":",
"1",
"}",
";",
"}",
"return",
"{",
"'x'",
":",
"start",
".",
"x",
"*",
"(",
"1",
"-",
"t",
")",
"+",
"end",
".",
"x",
"*",
"t",
",",
"'y'",
":",
"start",
".",
"y",
"*",
"(",
"1",
"-",
"t",
")",
"+",
"end",
".",
"y",
"*",
"t",
",",
"'radius'",
":",
"start",
".",
"radius",
"*",
"(",
"1",
"-",
"t",
")",
"+",
"end",
".",
"radius",
"*",
"t",
"}",
";",
"}",
")",
";",
"return",
"intersectionAreaPath",
"(",
"c",
")",
";",
"}",
";",
"}"
] |
interpolate intersection area paths between previous and current paths
|
[
"interpolate",
"intersection",
"area",
"paths",
"between",
"previous",
"and",
"current",
"paths"
] |
5ff0ef3ff450803a50c69493cd2bb6ce8b04f9fb
|
https://github.com/benfred/venn.js/blob/5ff0ef3ff450803a50c69493cd2bb6ce8b04f9fb/src/diagram.js#L114-L130
|
|
13,093
|
benfred/venn.js
|
src/diagram.js
|
shouldExclude
|
function shouldExclude(sets) {
for (var i = 0; i < sets.length; ++i) {
if (!(sets[i] in exclude)) {
return false;
}
}
return true;
}
|
javascript
|
function shouldExclude(sets) {
for (var i = 0; i < sets.length; ++i) {
if (!(sets[i] in exclude)) {
return false;
}
}
return true;
}
|
[
"function",
"shouldExclude",
"(",
"sets",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"sets",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"!",
"(",
"sets",
"[",
"i",
"]",
"in",
"exclude",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] |
checks that all sets are in exclude;
|
[
"checks",
"that",
"all",
"sets",
"are",
"in",
"exclude",
";"
] |
5ff0ef3ff450803a50c69493cd2bb6ce8b04f9fb
|
https://github.com/benfred/venn.js/blob/5ff0ef3ff450803a50c69493cd2bb6ce8b04f9fb/src/diagram.js#L535-L542
|
13,094
|
benfred/venn.js
|
venn.js
|
containedInCircles
|
function containedInCircles(point, circles) {
for (var i = 0; i < circles.length; ++i) {
if (distance(point, circles[i]) > circles[i].radius + SMALL) {
return false;
}
}
return true;
}
|
javascript
|
function containedInCircles(point, circles) {
for (var i = 0; i < circles.length; ++i) {
if (distance(point, circles[i]) > circles[i].radius + SMALL) {
return false;
}
}
return true;
}
|
[
"function",
"containedInCircles",
"(",
"point",
",",
"circles",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"circles",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"distance",
"(",
"point",
",",
"circles",
"[",
"i",
"]",
")",
">",
"circles",
"[",
"i",
"]",
".",
"radius",
"+",
"SMALL",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] |
returns whether a point is contained by all of a list of circles
|
[
"returns",
"whether",
"a",
"point",
"is",
"contained",
"by",
"all",
"of",
"a",
"list",
"of",
"circles"
] |
5ff0ef3ff450803a50c69493cd2bb6ce8b04f9fb
|
https://github.com/benfred/venn.js/blob/5ff0ef3ff450803a50c69493cd2bb6ce8b04f9fb/venn.js#L137-L144
|
13,095
|
benfred/venn.js
|
venn.js
|
getIntersectionPoints
|
function getIntersectionPoints(circles) {
var ret = [];
for (var i = 0; i < circles.length; ++i) {
for (var j = i + 1; j < circles.length; ++j) {
var intersect = circleCircleIntersection(circles[i],
circles[j]);
for (var k = 0; k < intersect.length; ++k) {
var p = intersect[k];
p.parentIndex = [i,j];
ret.push(p);
}
}
}
return ret;
}
|
javascript
|
function getIntersectionPoints(circles) {
var ret = [];
for (var i = 0; i < circles.length; ++i) {
for (var j = i + 1; j < circles.length; ++j) {
var intersect = circleCircleIntersection(circles[i],
circles[j]);
for (var k = 0; k < intersect.length; ++k) {
var p = intersect[k];
p.parentIndex = [i,j];
ret.push(p);
}
}
}
return ret;
}
|
[
"function",
"getIntersectionPoints",
"(",
"circles",
")",
"{",
"var",
"ret",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"circles",
".",
"length",
";",
"++",
"i",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"i",
"+",
"1",
";",
"j",
"<",
"circles",
".",
"length",
";",
"++",
"j",
")",
"{",
"var",
"intersect",
"=",
"circleCircleIntersection",
"(",
"circles",
"[",
"i",
"]",
",",
"circles",
"[",
"j",
"]",
")",
";",
"for",
"(",
"var",
"k",
"=",
"0",
";",
"k",
"<",
"intersect",
".",
"length",
";",
"++",
"k",
")",
"{",
"var",
"p",
"=",
"intersect",
"[",
"k",
"]",
";",
"p",
".",
"parentIndex",
"=",
"[",
"i",
",",
"j",
"]",
";",
"ret",
".",
"push",
"(",
"p",
")",
";",
"}",
"}",
"}",
"return",
"ret",
";",
"}"
] |
Gets all intersection points between a bunch of circles
|
[
"Gets",
"all",
"intersection",
"points",
"between",
"a",
"bunch",
"of",
"circles"
] |
5ff0ef3ff450803a50c69493cd2bb6ce8b04f9fb
|
https://github.com/benfred/venn.js/blob/5ff0ef3ff450803a50c69493cd2bb6ce8b04f9fb/venn.js#L147-L161
|
13,096
|
benfred/venn.js
|
venn.js
|
distance
|
function distance(p1, p2) {
return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) +
(p1.y - p2.y) * (p1.y - p2.y));
}
|
javascript
|
function distance(p1, p2) {
return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) +
(p1.y - p2.y) * (p1.y - p2.y));
}
|
[
"function",
"distance",
"(",
"p1",
",",
"p2",
")",
"{",
"return",
"Math",
".",
"sqrt",
"(",
"(",
"p1",
".",
"x",
"-",
"p2",
".",
"x",
")",
"*",
"(",
"p1",
".",
"x",
"-",
"p2",
".",
"x",
")",
"+",
"(",
"p1",
".",
"y",
"-",
"p2",
".",
"y",
")",
"*",
"(",
"p1",
".",
"y",
"-",
"p2",
".",
"y",
")",
")",
";",
"}"
] |
euclidean distance between two points
|
[
"euclidean",
"distance",
"between",
"two",
"points"
] |
5ff0ef3ff450803a50c69493cd2bb6ce8b04f9fb
|
https://github.com/benfred/venn.js/blob/5ff0ef3ff450803a50c69493cd2bb6ce8b04f9fb/venn.js#L169-L172
|
13,097
|
benfred/venn.js
|
venn.js
|
circleOverlap
|
function circleOverlap(r1, r2, d) {
// no overlap
if (d >= r1 + r2) {
return 0;
}
// completely overlapped
if (d <= Math.abs(r1 - r2)) {
return Math.PI * Math.min(r1, r2) * Math.min(r1, r2);
}
var w1 = r1 - (d * d - r2 * r2 + r1 * r1) / (2 * d),
w2 = r2 - (d * d - r1 * r1 + r2 * r2) / (2 * d);
return circleArea(r1, w1) + circleArea(r2, w2);
}
|
javascript
|
function circleOverlap(r1, r2, d) {
// no overlap
if (d >= r1 + r2) {
return 0;
}
// completely overlapped
if (d <= Math.abs(r1 - r2)) {
return Math.PI * Math.min(r1, r2) * Math.min(r1, r2);
}
var w1 = r1 - (d * d - r2 * r2 + r1 * r1) / (2 * d),
w2 = r2 - (d * d - r1 * r1 + r2 * r2) / (2 * d);
return circleArea(r1, w1) + circleArea(r2, w2);
}
|
[
"function",
"circleOverlap",
"(",
"r1",
",",
"r2",
",",
"d",
")",
"{",
"// no overlap",
"if",
"(",
"d",
">=",
"r1",
"+",
"r2",
")",
"{",
"return",
"0",
";",
"}",
"// completely overlapped",
"if",
"(",
"d",
"<=",
"Math",
".",
"abs",
"(",
"r1",
"-",
"r2",
")",
")",
"{",
"return",
"Math",
".",
"PI",
"*",
"Math",
".",
"min",
"(",
"r1",
",",
"r2",
")",
"*",
"Math",
".",
"min",
"(",
"r1",
",",
"r2",
")",
";",
"}",
"var",
"w1",
"=",
"r1",
"-",
"(",
"d",
"*",
"d",
"-",
"r2",
"*",
"r2",
"+",
"r1",
"*",
"r1",
")",
"/",
"(",
"2",
"*",
"d",
")",
",",
"w2",
"=",
"r2",
"-",
"(",
"d",
"*",
"d",
"-",
"r1",
"*",
"r1",
"+",
"r2",
"*",
"r2",
")",
"/",
"(",
"2",
"*",
"d",
")",
";",
"return",
"circleArea",
"(",
"r1",
",",
"w1",
")",
"+",
"circleArea",
"(",
"r2",
",",
"w2",
")",
";",
"}"
] |
Returns the overlap area of two circles of radius r1 and r2 - that
have their centers separated by distance d. Simpler faster
circle intersection for only two circles
|
[
"Returns",
"the",
"overlap",
"area",
"of",
"two",
"circles",
"of",
"radius",
"r1",
"and",
"r2",
"-",
"that",
"have",
"their",
"centers",
"separated",
"by",
"distance",
"d",
".",
"Simpler",
"faster",
"circle",
"intersection",
"for",
"only",
"two",
"circles"
] |
5ff0ef3ff450803a50c69493cd2bb6ce8b04f9fb
|
https://github.com/benfred/venn.js/blob/5ff0ef3ff450803a50c69493cd2bb6ce8b04f9fb/venn.js#L178-L192
|
13,098
|
benfred/venn.js
|
venn.js
|
getCenter
|
function getCenter(points) {
var center = {x: 0, y: 0};
for (var i =0; i < points.length; ++i ) {
center.x += points[i].x;
center.y += points[i].y;
}
center.x /= points.length;
center.y /= points.length;
return center;
}
|
javascript
|
function getCenter(points) {
var center = {x: 0, y: 0};
for (var i =0; i < points.length; ++i ) {
center.x += points[i].x;
center.y += points[i].y;
}
center.x /= points.length;
center.y /= points.length;
return center;
}
|
[
"function",
"getCenter",
"(",
"points",
")",
"{",
"var",
"center",
"=",
"{",
"x",
":",
"0",
",",
"y",
":",
"0",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"points",
".",
"length",
";",
"++",
"i",
")",
"{",
"center",
".",
"x",
"+=",
"points",
"[",
"i",
"]",
".",
"x",
";",
"center",
".",
"y",
"+=",
"points",
"[",
"i",
"]",
".",
"y",
";",
"}",
"center",
".",
"x",
"/=",
"points",
".",
"length",
";",
"center",
".",
"y",
"/=",
"points",
".",
"length",
";",
"return",
"center",
";",
"}"
] |
Returns the center of a bunch of points
|
[
"Returns",
"the",
"center",
"of",
"a",
"bunch",
"of",
"points"
] |
5ff0ef3ff450803a50c69493cd2bb6ce8b04f9fb
|
https://github.com/benfred/venn.js/blob/5ff0ef3ff450803a50c69493cd2bb6ce8b04f9fb/venn.js#L220-L229
|
13,099
|
benfred/venn.js
|
venn.js
|
bisect
|
function bisect(f, a, b, parameters) {
parameters = parameters || {};
var maxIterations = parameters.maxIterations || 100,
tolerance = parameters.tolerance || 1e-10,
fA = f(a),
fB = f(b),
delta = b - a;
if (fA * fB > 0) {
throw "Initial bisect points must have opposite signs";
}
if (fA === 0) return a;
if (fB === 0) return b;
for (var i = 0; i < maxIterations; ++i) {
delta /= 2;
var mid = a + delta,
fMid = f(mid);
if (fMid * fA >= 0) {
a = mid;
}
if ((Math.abs(delta) < tolerance) || (fMid === 0)) {
return mid;
}
}
return a + delta;
}
|
javascript
|
function bisect(f, a, b, parameters) {
parameters = parameters || {};
var maxIterations = parameters.maxIterations || 100,
tolerance = parameters.tolerance || 1e-10,
fA = f(a),
fB = f(b),
delta = b - a;
if (fA * fB > 0) {
throw "Initial bisect points must have opposite signs";
}
if (fA === 0) return a;
if (fB === 0) return b;
for (var i = 0; i < maxIterations; ++i) {
delta /= 2;
var mid = a + delta,
fMid = f(mid);
if (fMid * fA >= 0) {
a = mid;
}
if ((Math.abs(delta) < tolerance) || (fMid === 0)) {
return mid;
}
}
return a + delta;
}
|
[
"function",
"bisect",
"(",
"f",
",",
"a",
",",
"b",
",",
"parameters",
")",
"{",
"parameters",
"=",
"parameters",
"||",
"{",
"}",
";",
"var",
"maxIterations",
"=",
"parameters",
".",
"maxIterations",
"||",
"100",
",",
"tolerance",
"=",
"parameters",
".",
"tolerance",
"||",
"1e-10",
",",
"fA",
"=",
"f",
"(",
"a",
")",
",",
"fB",
"=",
"f",
"(",
"b",
")",
",",
"delta",
"=",
"b",
"-",
"a",
";",
"if",
"(",
"fA",
"*",
"fB",
">",
"0",
")",
"{",
"throw",
"\"Initial bisect points must have opposite signs\"",
";",
"}",
"if",
"(",
"fA",
"===",
"0",
")",
"return",
"a",
";",
"if",
"(",
"fB",
"===",
"0",
")",
"return",
"b",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"maxIterations",
";",
"++",
"i",
")",
"{",
"delta",
"/=",
"2",
";",
"var",
"mid",
"=",
"a",
"+",
"delta",
",",
"fMid",
"=",
"f",
"(",
"mid",
")",
";",
"if",
"(",
"fMid",
"*",
"fA",
">=",
"0",
")",
"{",
"a",
"=",
"mid",
";",
"}",
"if",
"(",
"(",
"Math",
".",
"abs",
"(",
"delta",
")",
"<",
"tolerance",
")",
"||",
"(",
"fMid",
"===",
"0",
")",
")",
"{",
"return",
"mid",
";",
"}",
"}",
"return",
"a",
"+",
"delta",
";",
"}"
] |
finds the zeros of a function, given two starting points (which must
have opposite signs
|
[
"finds",
"the",
"zeros",
"of",
"a",
"function",
"given",
"two",
"starting",
"points",
"(",
"which",
"must",
"have",
"opposite",
"signs"
] |
5ff0ef3ff450803a50c69493cd2bb6ce8b04f9fb
|
https://github.com/benfred/venn.js/blob/5ff0ef3ff450803a50c69493cd2bb6ce8b04f9fb/venn.js#L233-L262
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.