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
|
---|---|---|---|---|---|---|---|---|---|---|---|
36,300 |
aMarCruz/jspreproc
|
spec/uglify/core.js
|
parseAttrs
|
function parseAttrs(str, pcex) {
var
list = [],
match,
k, v, t, e,
DQ = '"'
HTML_ATTR.lastIndex = 0
str = str.replace(/\s+/g, ' ')
while (match = HTML_ATTR.exec(str)) {
// all attribute names are converted to lower case
k = match[1].toLowerCase()
v = match[2]
if (!v) {
list.push(k) // boolean attribute without explicit value
}
else {
// attribute values must be enclosed in double quotes
if (v[0] !== DQ)
v = DQ + (v[0] === "'" ? v.slice(1, -1) : v) + DQ
if (k === 'type' && SPEC_TYPES.test(v)) {
t = v
}
else {
if (/\u0001\d/.test(v)) {
// renames special attributes with expressiones in their value.
if (k === 'value') e = 1
else if (BOOL_ATTRS.test(k)) k = '__' + k
else if (~RIOT_ATTRS.indexOf(k)) k = 'riot-' + k
}
// join the key-value pair, with no spaces between the parts
list.push(k + '=' + v)
}
}
}
// update() will evaluate `type` after the value, avoiding warnings
if (t) {
if (e) t = DQ + pcex._bp[0] + "'" + v.slice(1, -1) + "'" + pcex._bp[1] + DQ
list.push('type=' + t)
}
return list.join(' ') // returns the attribute list
}
|
javascript
|
function parseAttrs(str, pcex) {
var
list = [],
match,
k, v, t, e,
DQ = '"'
HTML_ATTR.lastIndex = 0
str = str.replace(/\s+/g, ' ')
while (match = HTML_ATTR.exec(str)) {
// all attribute names are converted to lower case
k = match[1].toLowerCase()
v = match[2]
if (!v) {
list.push(k) // boolean attribute without explicit value
}
else {
// attribute values must be enclosed in double quotes
if (v[0] !== DQ)
v = DQ + (v[0] === "'" ? v.slice(1, -1) : v) + DQ
if (k === 'type' && SPEC_TYPES.test(v)) {
t = v
}
else {
if (/\u0001\d/.test(v)) {
// renames special attributes with expressiones in their value.
if (k === 'value') e = 1
else if (BOOL_ATTRS.test(k)) k = '__' + k
else if (~RIOT_ATTRS.indexOf(k)) k = 'riot-' + k
}
// join the key-value pair, with no spaces between the parts
list.push(k + '=' + v)
}
}
}
// update() will evaluate `type` after the value, avoiding warnings
if (t) {
if (e) t = DQ + pcex._bp[0] + "'" + v.slice(1, -1) + "'" + pcex._bp[1] + DQ
list.push('type=' + t)
}
return list.join(' ') // returns the attribute list
}
|
[
"function",
"parseAttrs",
"(",
"str",
",",
"pcex",
")",
"{",
"var",
"list",
"=",
"[",
"]",
",",
"match",
",",
"k",
",",
"v",
",",
"t",
",",
"e",
",",
"DQ",
"=",
"'\"'",
"HTML_ATTR",
".",
"lastIndex",
"=",
"0",
"str",
"=",
"str",
".",
"replace",
"(",
"/",
"\\s+",
"/",
"g",
",",
"' '",
")",
"while",
"(",
"match",
"=",
"HTML_ATTR",
".",
"exec",
"(",
"str",
")",
")",
"{",
"// all attribute names are converted to lower case",
"k",
"=",
"match",
"[",
"1",
"]",
".",
"toLowerCase",
"(",
")",
"v",
"=",
"match",
"[",
"2",
"]",
"if",
"(",
"!",
"v",
")",
"{",
"list",
".",
"push",
"(",
"k",
")",
"// boolean attribute without explicit value",
"}",
"else",
"{",
"// attribute values must be enclosed in double quotes",
"if",
"(",
"v",
"[",
"0",
"]",
"!==",
"DQ",
")",
"v",
"=",
"DQ",
"+",
"(",
"v",
"[",
"0",
"]",
"===",
"\"'\"",
"?",
"v",
".",
"slice",
"(",
"1",
",",
"-",
"1",
")",
":",
"v",
")",
"+",
"DQ",
"if",
"(",
"k",
"===",
"'type'",
"&&",
"SPEC_TYPES",
".",
"test",
"(",
"v",
")",
")",
"{",
"t",
"=",
"v",
"}",
"else",
"{",
"if",
"(",
"/",
"\\u0001\\d",
"/",
".",
"test",
"(",
"v",
")",
")",
"{",
"// renames special attributes with expressiones in their value.",
"if",
"(",
"k",
"===",
"'value'",
")",
"e",
"=",
"1",
"else",
"if",
"(",
"BOOL_ATTRS",
".",
"test",
"(",
"k",
")",
")",
"k",
"=",
"'__'",
"+",
"k",
"else",
"if",
"(",
"~",
"RIOT_ATTRS",
".",
"indexOf",
"(",
"k",
")",
")",
"k",
"=",
"'riot-'",
"+",
"k",
"}",
"// join the key-value pair, with no spaces between the parts",
"list",
".",
"push",
"(",
"k",
"+",
"'='",
"+",
"v",
")",
"}",
"}",
"}",
"// update() will evaluate `type` after the value, avoiding warnings",
"if",
"(",
"t",
")",
"{",
"if",
"(",
"e",
")",
"t",
"=",
"DQ",
"+",
"pcex",
".",
"_bp",
"[",
"0",
"]",
"+",
"\"'\"",
"+",
"v",
".",
"slice",
"(",
"1",
",",
"-",
"1",
")",
"+",
"\"'\"",
"+",
"pcex",
".",
"_bp",
"[",
"1",
"]",
"+",
"DQ",
"list",
".",
"push",
"(",
"'type='",
"+",
"t",
")",
"}",
"return",
"list",
".",
"join",
"(",
"' '",
")",
"// returns the attribute list",
"}"
] |
Parses and format attributes.
@param {string} str - Attributes, with expressions replaced by their hash
@param {Array} pcex - Has a _bp property with info about brackets
@returns {string} Formated attributes
|
[
"Parses",
"and",
"format",
"attributes",
"."
] |
5f31820d702a329e8aa25f0f3983f13097610250
|
https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/spec/uglify/core.js#L96-L142
|
36,301 |
aMarCruz/jspreproc
|
spec/uglify/core.js
|
splitHtml
|
function splitHtml(html, opts, pcex) {
var _bp = pcex._bp
// `brackets.split` is a heavy function, so don't call it if not necessary
if (html && _bp[4].test(html)) {
var
jsfn = opts.expr && (opts.parser || opts.type) ? _compileJS : 0,
list = brackets.split(html, 0, _bp),
expr
for (var i = 1; i < list.length; i += 2) {
expr = list[i]
if (expr[0] === '^')
expr = expr.slice(1)
else if (jsfn) {
var israw = expr[0] === '='
expr = jsfn(israw ? expr.slice(1) : expr, opts).trim()
if (expr.slice(-1) === ';') expr = expr.slice(0, -1)
if (israw) expr = '=' + expr
}
list[i] = '\u0001' + (pcex.push(expr.replace(/[\r\n]+/g, ' ').trim()) - 1) + _bp[1]
}
html = list.join('')
}
return html
}
|
javascript
|
function splitHtml(html, opts, pcex) {
var _bp = pcex._bp
// `brackets.split` is a heavy function, so don't call it if not necessary
if (html && _bp[4].test(html)) {
var
jsfn = opts.expr && (opts.parser || opts.type) ? _compileJS : 0,
list = brackets.split(html, 0, _bp),
expr
for (var i = 1; i < list.length; i += 2) {
expr = list[i]
if (expr[0] === '^')
expr = expr.slice(1)
else if (jsfn) {
var israw = expr[0] === '='
expr = jsfn(israw ? expr.slice(1) : expr, opts).trim()
if (expr.slice(-1) === ';') expr = expr.slice(0, -1)
if (israw) expr = '=' + expr
}
list[i] = '\u0001' + (pcex.push(expr.replace(/[\r\n]+/g, ' ').trim()) - 1) + _bp[1]
}
html = list.join('')
}
return html
}
|
[
"function",
"splitHtml",
"(",
"html",
",",
"opts",
",",
"pcex",
")",
"{",
"var",
"_bp",
"=",
"pcex",
".",
"_bp",
"// `brackets.split` is a heavy function, so don't call it if not necessary",
"if",
"(",
"html",
"&&",
"_bp",
"[",
"4",
"]",
".",
"test",
"(",
"html",
")",
")",
"{",
"var",
"jsfn",
"=",
"opts",
".",
"expr",
"&&",
"(",
"opts",
".",
"parser",
"||",
"opts",
".",
"type",
")",
"?",
"_compileJS",
":",
"0",
",",
"list",
"=",
"brackets",
".",
"split",
"(",
"html",
",",
"0",
",",
"_bp",
")",
",",
"expr",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"list",
".",
"length",
";",
"i",
"+=",
"2",
")",
"{",
"expr",
"=",
"list",
"[",
"i",
"]",
"if",
"(",
"expr",
"[",
"0",
"]",
"===",
"'^'",
")",
"expr",
"=",
"expr",
".",
"slice",
"(",
"1",
")",
"else",
"if",
"(",
"jsfn",
")",
"{",
"var",
"israw",
"=",
"expr",
"[",
"0",
"]",
"===",
"'='",
"expr",
"=",
"jsfn",
"(",
"israw",
"?",
"expr",
".",
"slice",
"(",
"1",
")",
":",
"expr",
",",
"opts",
")",
".",
"trim",
"(",
")",
"if",
"(",
"expr",
".",
"slice",
"(",
"-",
"1",
")",
"===",
"';'",
")",
"expr",
"=",
"expr",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
"if",
"(",
"israw",
")",
"expr",
"=",
"'='",
"+",
"expr",
"}",
"list",
"[",
"i",
"]",
"=",
"'\\u0001'",
"+",
"(",
"pcex",
".",
"push",
"(",
"expr",
".",
"replace",
"(",
"/",
"[\\r\\n]+",
"/",
"g",
",",
"' '",
")",
".",
"trim",
"(",
")",
")",
"-",
"1",
")",
"+",
"_bp",
"[",
"1",
"]",
"}",
"html",
"=",
"list",
".",
"join",
"(",
"''",
")",
"}",
"return",
"html",
"}"
] |
Replaces expressions in the HTML with a marker, and runs expressions through the parser, except those beginning with `{^`.
|
[
"Replaces",
"expressions",
"in",
"the",
"HTML",
"with",
"a",
"marker",
"and",
"runs",
"expressions",
"through",
"the",
"parser",
"except",
"those",
"beginning",
"with",
"{",
"^",
"."
] |
5f31820d702a329e8aa25f0f3983f13097610250
|
https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/spec/uglify/core.js#L146-L171
|
36,302 |
aMarCruz/jspreproc
|
spec/uglify/core.js
|
restoreExpr
|
function restoreExpr(html, pcex) {
if (pcex.length) {
html = html
.replace(/\u0001(\d+)/g, function (_, d) {
var expr = pcex[d]
if (expr[0] === '=') {
expr = expr.replace(brackets.R_STRINGS, function (qs) {
return qs //.replace(/&/g, '&') // I don't know if this make sense
.replace(/</g, '<')
.replace(/>/g, '>')
})
}
return pcex._bp[0] + expr.replace(/"/g, '\u2057')
})
}
return html
}
|
javascript
|
function restoreExpr(html, pcex) {
if (pcex.length) {
html = html
.replace(/\u0001(\d+)/g, function (_, d) {
var expr = pcex[d]
if (expr[0] === '=') {
expr = expr.replace(brackets.R_STRINGS, function (qs) {
return qs //.replace(/&/g, '&') // I don't know if this make sense
.replace(/</g, '<')
.replace(/>/g, '>')
})
}
return pcex._bp[0] + expr.replace(/"/g, '\u2057')
})
}
return html
}
|
[
"function",
"restoreExpr",
"(",
"html",
",",
"pcex",
")",
"{",
"if",
"(",
"pcex",
".",
"length",
")",
"{",
"html",
"=",
"html",
".",
"replace",
"(",
"/",
"\\u0001(\\d+)",
"/",
"g",
",",
"function",
"(",
"_",
",",
"d",
")",
"{",
"var",
"expr",
"=",
"pcex",
"[",
"d",
"]",
"if",
"(",
"expr",
"[",
"0",
"]",
"===",
"'='",
")",
"{",
"expr",
"=",
"expr",
".",
"replace",
"(",
"brackets",
".",
"R_STRINGS",
",",
"function",
"(",
"qs",
")",
"{",
"return",
"qs",
"//.replace(/&/g, '&') // I don't know if this make sense",
".",
"replace",
"(",
"/",
"<",
"/",
"g",
",",
"'<'",
")",
".",
"replace",
"(",
"/",
">",
"/",
"g",
",",
"'>'",
")",
"}",
")",
"}",
"return",
"pcex",
".",
"_bp",
"[",
"0",
"]",
"+",
"expr",
".",
"replace",
"(",
"/",
"\"",
"/",
"g",
",",
"'\\u2057'",
")",
"}",
")",
"}",
"return",
"html",
"}"
] |
Restores expressions hidden by splitHtml and escape literal internal brackets
|
[
"Restores",
"expressions",
"hidden",
"by",
"splitHtml",
"and",
"escape",
"literal",
"internal",
"brackets"
] |
5f31820d702a329e8aa25f0f3983f13097610250
|
https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/spec/uglify/core.js#L174-L190
|
36,303 |
aMarCruz/jspreproc
|
spec/uglify/core.js
|
compileHTML
|
function compileHTML(html, opts, pcex) {
if (Array.isArray(opts)) {
pcex = opts
opts = {}
}
else {
if (!pcex) pcex = []
if (!opts) opts = {}
}
html = html.replace(/\r\n?/g, '\n').replace(HTML_COMMENT,
function (s) { return s[0] === '<' ? '' : s }).replace(TRIM_TRAIL, '')
// `_bp` is undefined when `compileHTML` is not called by compile
if (!pcex._bp) pcex._bp = brackets.array(opts.brackets)
return _compileHTML(html, opts, pcex)
}
|
javascript
|
function compileHTML(html, opts, pcex) {
if (Array.isArray(opts)) {
pcex = opts
opts = {}
}
else {
if (!pcex) pcex = []
if (!opts) opts = {}
}
html = html.replace(/\r\n?/g, '\n').replace(HTML_COMMENT,
function (s) { return s[0] === '<' ? '' : s }).replace(TRIM_TRAIL, '')
// `_bp` is undefined when `compileHTML` is not called by compile
if (!pcex._bp) pcex._bp = brackets.array(opts.brackets)
return _compileHTML(html, opts, pcex)
}
|
[
"function",
"compileHTML",
"(",
"html",
",",
"opts",
",",
"pcex",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"opts",
")",
")",
"{",
"pcex",
"=",
"opts",
"opts",
"=",
"{",
"}",
"}",
"else",
"{",
"if",
"(",
"!",
"pcex",
")",
"pcex",
"=",
"[",
"]",
"if",
"(",
"!",
"opts",
")",
"opts",
"=",
"{",
"}",
"}",
"html",
"=",
"html",
".",
"replace",
"(",
"/",
"\\r\\n?",
"/",
"g",
",",
"'\\n'",
")",
".",
"replace",
"(",
"HTML_COMMENT",
",",
"function",
"(",
"s",
")",
"{",
"return",
"s",
"[",
"0",
"]",
"===",
"'<'",
"?",
"''",
":",
"s",
"}",
")",
".",
"replace",
"(",
"TRIM_TRAIL",
",",
"''",
")",
"// `_bp` is undefined when `compileHTML` is not called by compile",
"if",
"(",
"!",
"pcex",
".",
"_bp",
")",
"pcex",
".",
"_bp",
"=",
"brackets",
".",
"array",
"(",
"opts",
".",
"brackets",
")",
"return",
"_compileHTML",
"(",
"html",
",",
"opts",
",",
"pcex",
")",
"}"
] |
Parses and formats the HTML text.
@param {string} html - Can contain embedded HTML comments and literal whitespace
@param {Object} opts - Collected user options. Includes the brackets array in `_bp`
@param {Array} [pcex] - Keeps precompiled expressions
@returns {string} The parsed HTML text
@see http://www.w3.org/TR/html5/syntax.html
istanbul ignore next
|
[
"Parses",
"and",
"formats",
"the",
"HTML",
"text",
"."
] |
5f31820d702a329e8aa25f0f3983f13097610250
|
https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/spec/uglify/core.js#L248-L265
|
36,304 |
aMarCruz/jspreproc
|
spec/uglify/core.js
|
riotjs
|
function riotjs(js) {
var
match,
toes5,
parts = [], // parsed code
pos
// remove comments
js = js.replace(JS_RMCOMMS, function (m, q) { return q ? m : ' ' })
// $1: indentation,
// $2: method name,
// $3: parameters
while (match = js.match(JS_ES6SIGN)) {
// save remaining part now -- IE9 changes `rightContext` in `RegExp.test`
parts.push(RegExp.leftContext)
js = RegExp.rightContext
pos = skipBlock(js) // find the closing bracket
// convert ES6 method signature to ES5 function
toes5 = !/^(?:if|while|for|switch|catch|function)$/.test(match[2])
if (toes5)
match[0] = match[1] + 'this.' + match[2] + ' = function' + match[3]
parts.push(match[0], js.slice(0, pos))
js = js.slice(pos)
if (toes5 && !/^\s*.\s*bind\b/.test(js)) parts.push('.bind(this)')
}
return parts.length ? parts.join('') + js : js
// Inner helper - find the position following the closing bracket for the current block
function skipBlock(str) {
var
re = _regEx('([{}])|' + brackets.S_QBLOCKS, 'g'),
level = 1,
match
while (level && (match = re.exec(str))) {
if (match[1])
match[1] === '{' ? ++level : --level
}
return level ? str.length : re.lastIndex
}
}
|
javascript
|
function riotjs(js) {
var
match,
toes5,
parts = [], // parsed code
pos
// remove comments
js = js.replace(JS_RMCOMMS, function (m, q) { return q ? m : ' ' })
// $1: indentation,
// $2: method name,
// $3: parameters
while (match = js.match(JS_ES6SIGN)) {
// save remaining part now -- IE9 changes `rightContext` in `RegExp.test`
parts.push(RegExp.leftContext)
js = RegExp.rightContext
pos = skipBlock(js) // find the closing bracket
// convert ES6 method signature to ES5 function
toes5 = !/^(?:if|while|for|switch|catch|function)$/.test(match[2])
if (toes5)
match[0] = match[1] + 'this.' + match[2] + ' = function' + match[3]
parts.push(match[0], js.slice(0, pos))
js = js.slice(pos)
if (toes5 && !/^\s*.\s*bind\b/.test(js)) parts.push('.bind(this)')
}
return parts.length ? parts.join('') + js : js
// Inner helper - find the position following the closing bracket for the current block
function skipBlock(str) {
var
re = _regEx('([{}])|' + brackets.S_QBLOCKS, 'g'),
level = 1,
match
while (level && (match = re.exec(str))) {
if (match[1])
match[1] === '{' ? ++level : --level
}
return level ? str.length : re.lastIndex
}
}
|
[
"function",
"riotjs",
"(",
"js",
")",
"{",
"var",
"match",
",",
"toes5",
",",
"parts",
"=",
"[",
"]",
",",
"// parsed code",
"pos",
"// remove comments",
"js",
"=",
"js",
".",
"replace",
"(",
"JS_RMCOMMS",
",",
"function",
"(",
"m",
",",
"q",
")",
"{",
"return",
"q",
"?",
"m",
":",
"' '",
"}",
")",
"// $1: indentation,",
"// $2: method name,",
"// $3: parameters",
"while",
"(",
"match",
"=",
"js",
".",
"match",
"(",
"JS_ES6SIGN",
")",
")",
"{",
"// save remaining part now -- IE9 changes `rightContext` in `RegExp.test`",
"parts",
".",
"push",
"(",
"RegExp",
".",
"leftContext",
")",
"js",
"=",
"RegExp",
".",
"rightContext",
"pos",
"=",
"skipBlock",
"(",
"js",
")",
"// find the closing bracket",
"// convert ES6 method signature to ES5 function",
"toes5",
"=",
"!",
"/",
"^(?:if|while|for|switch|catch|function)$",
"/",
".",
"test",
"(",
"match",
"[",
"2",
"]",
")",
"if",
"(",
"toes5",
")",
"match",
"[",
"0",
"]",
"=",
"match",
"[",
"1",
"]",
"+",
"'this.'",
"+",
"match",
"[",
"2",
"]",
"+",
"' = function'",
"+",
"match",
"[",
"3",
"]",
"parts",
".",
"push",
"(",
"match",
"[",
"0",
"]",
",",
"js",
".",
"slice",
"(",
"0",
",",
"pos",
")",
")",
"js",
"=",
"js",
".",
"slice",
"(",
"pos",
")",
"if",
"(",
"toes5",
"&&",
"!",
"/",
"^\\s*.\\s*bind\\b",
"/",
".",
"test",
"(",
"js",
")",
")",
"parts",
".",
"push",
"(",
"'.bind(this)'",
")",
"}",
"return",
"parts",
".",
"length",
"?",
"parts",
".",
"join",
"(",
"''",
")",
"+",
"js",
":",
"js",
"// Inner helper - find the position following the closing bracket for the current block",
"function",
"skipBlock",
"(",
"str",
")",
"{",
"var",
"re",
"=",
"_regEx",
"(",
"'([{}])|'",
"+",
"brackets",
".",
"S_QBLOCKS",
",",
"'g'",
")",
",",
"level",
"=",
"1",
",",
"match",
"while",
"(",
"level",
"&&",
"(",
"match",
"=",
"re",
".",
"exec",
"(",
"str",
")",
")",
")",
"{",
"if",
"(",
"match",
"[",
"1",
"]",
")",
"match",
"[",
"1",
"]",
"===",
"'{'",
"?",
"++",
"level",
":",
"--",
"level",
"}",
"return",
"level",
"?",
"str",
".",
"length",
":",
"re",
".",
"lastIndex",
"}",
"}"
] |
Default parser for JavaScript code
|
[
"Default",
"parser",
"for",
"JavaScript",
"code"
] |
5f31820d702a329e8aa25f0f3983f13097610250
|
https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/spec/uglify/core.js#L278-L323
|
36,305 |
ascartabelli/lamb
|
src/privates/_groupWith.js
|
_groupWith
|
function _groupWith (makeValue) {
return function (arrayLike, iteratee) {
var result = {};
var len = arrayLike.length;
for (var i = 0, element, key; i < len; i++) {
element = arrayLike[i];
key = iteratee(element, i, arrayLike);
result[key] = makeValue(result[key], element);
}
return result;
};
}
|
javascript
|
function _groupWith (makeValue) {
return function (arrayLike, iteratee) {
var result = {};
var len = arrayLike.length;
for (var i = 0, element, key; i < len; i++) {
element = arrayLike[i];
key = iteratee(element, i, arrayLike);
result[key] = makeValue(result[key], element);
}
return result;
};
}
|
[
"function",
"_groupWith",
"(",
"makeValue",
")",
"{",
"return",
"function",
"(",
"arrayLike",
",",
"iteratee",
")",
"{",
"var",
"result",
"=",
"{",
"}",
";",
"var",
"len",
"=",
"arrayLike",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"element",
",",
"key",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"element",
"=",
"arrayLike",
"[",
"i",
"]",
";",
"key",
"=",
"iteratee",
"(",
"element",
",",
"i",
",",
"arrayLike",
")",
";",
"result",
"[",
"key",
"]",
"=",
"makeValue",
"(",
"result",
"[",
"key",
"]",
",",
"element",
")",
";",
"}",
"return",
"result",
";",
"}",
";",
"}"
] |
Builds a "grouping function" for an array-like object.
@private
@param {Function} makeValue
@returns {Function}
|
[
"Builds",
"a",
"grouping",
"function",
"for",
"an",
"array",
"-",
"like",
"object",
"."
] |
d36e45945c4789e4f1a2d8805936514b53f32362
|
https://github.com/ascartabelli/lamb/blob/d36e45945c4789e4f1a2d8805936514b53f32362/src/privates/_groupWith.js#L7-L20
|
36,306 |
ascartabelli/lamb
|
src/privates/_curry3.js
|
_curry3
|
function _curry3 (fn, isRightCurry) {
return function (a) {
return function (b) {
return function (c) {
return isRightCurry ? fn.call(this, c, b, a) : fn.call(this, a, b, c);
};
};
};
}
|
javascript
|
function _curry3 (fn, isRightCurry) {
return function (a) {
return function (b) {
return function (c) {
return isRightCurry ? fn.call(this, c, b, a) : fn.call(this, a, b, c);
};
};
};
}
|
[
"function",
"_curry3",
"(",
"fn",
",",
"isRightCurry",
")",
"{",
"return",
"function",
"(",
"a",
")",
"{",
"return",
"function",
"(",
"b",
")",
"{",
"return",
"function",
"(",
"c",
")",
"{",
"return",
"isRightCurry",
"?",
"fn",
".",
"call",
"(",
"this",
",",
"c",
",",
"b",
",",
"a",
")",
":",
"fn",
".",
"call",
"(",
"this",
",",
"a",
",",
"b",
",",
"c",
")",
";",
"}",
";",
"}",
";",
"}",
";",
"}"
] |
Curries a function of arity 3.
@private
@param {Function} fn
@param {Boolean} [isRightCurry=false]
@returns {Function}
|
[
"Curries",
"a",
"function",
"of",
"arity",
"3",
"."
] |
d36e45945c4789e4f1a2d8805936514b53f32362
|
https://github.com/ascartabelli/lamb/blob/d36e45945c4789e4f1a2d8805936514b53f32362/src/privates/_curry3.js#L8-L16
|
36,307 |
ILLGrenoble/guacamole-common-js
|
src/AudioContextFactory.js
|
getAudioContext
|
function getAudioContext() {
// Fallback to Webkit-specific AudioContext implementation
var AudioContext = window.AudioContext || window.webkitAudioContext;
// Get new AudioContext instance if Web Audio API is supported
if (AudioContext) {
try {
// Create new instance if none yet exists
if (!Guacamole.AudioContextFactory.singleton)
Guacamole.AudioContextFactory.singleton = new AudioContext();
// Return singleton instance
return Guacamole.AudioContextFactory.singleton;
}
catch (e) {
// Do not use Web Audio API if not allowed by browser
}
}
// Web Audio API not supported
return null;
}
|
javascript
|
function getAudioContext() {
// Fallback to Webkit-specific AudioContext implementation
var AudioContext = window.AudioContext || window.webkitAudioContext;
// Get new AudioContext instance if Web Audio API is supported
if (AudioContext) {
try {
// Create new instance if none yet exists
if (!Guacamole.AudioContextFactory.singleton)
Guacamole.AudioContextFactory.singleton = new AudioContext();
// Return singleton instance
return Guacamole.AudioContextFactory.singleton;
}
catch (e) {
// Do not use Web Audio API if not allowed by browser
}
}
// Web Audio API not supported
return null;
}
|
[
"function",
"getAudioContext",
"(",
")",
"{",
"// Fallback to Webkit-specific AudioContext implementation",
"var",
"AudioContext",
"=",
"window",
".",
"AudioContext",
"||",
"window",
".",
"webkitAudioContext",
";",
"// Get new AudioContext instance if Web Audio API is supported",
"if",
"(",
"AudioContext",
")",
"{",
"try",
"{",
"// Create new instance if none yet exists",
"if",
"(",
"!",
"Guacamole",
".",
"AudioContextFactory",
".",
"singleton",
")",
"Guacamole",
".",
"AudioContextFactory",
".",
"singleton",
"=",
"new",
"AudioContext",
"(",
")",
";",
"// Return singleton instance",
"return",
"Guacamole",
".",
"AudioContextFactory",
".",
"singleton",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// Do not use Web Audio API if not allowed by browser",
"}",
"}",
"// Web Audio API not supported",
"return",
"null",
";",
"}"
] |
Returns a singleton instance of a Web Audio API AudioContext object.
@return {AudioContext}
A singleton instance of a Web Audio API AudioContext object, or null
if the Web Audio API is not supported.
|
[
"Returns",
"a",
"singleton",
"instance",
"of",
"a",
"Web",
"Audio",
"API",
"AudioContext",
"object",
"."
] |
71925794155ea3fc37d2a125adbca6f8be532887
|
https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/AudioContextFactory.js#L52-L77
|
36,308 |
jorisvervuurt/JVSDisplayOTron
|
lib/dot3k/dot3k.js
|
DOT3k
|
function DOT3k() {
if (!(this instanceof DOT3k)) {
return new DOT3k();
}
this.displayOTron = new DisplayOTron('3k');
this.lcd = new LCD(this.displayOTron);
this.backlight = new Backlight(this.displayOTron);
this.barGraph = new BarGraph(this.displayOTron);
this.joystick = new Joystick(this.displayOTron);
}
|
javascript
|
function DOT3k() {
if (!(this instanceof DOT3k)) {
return new DOT3k();
}
this.displayOTron = new DisplayOTron('3k');
this.lcd = new LCD(this.displayOTron);
this.backlight = new Backlight(this.displayOTron);
this.barGraph = new BarGraph(this.displayOTron);
this.joystick = new Joystick(this.displayOTron);
}
|
[
"function",
"DOT3k",
"(",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"DOT3k",
")",
")",
"{",
"return",
"new",
"DOT3k",
"(",
")",
";",
"}",
"this",
".",
"displayOTron",
"=",
"new",
"DisplayOTron",
"(",
"'3k'",
")",
";",
"this",
".",
"lcd",
"=",
"new",
"LCD",
"(",
"this",
".",
"displayOTron",
")",
";",
"this",
".",
"backlight",
"=",
"new",
"Backlight",
"(",
"this",
".",
"displayOTron",
")",
";",
"this",
".",
"barGraph",
"=",
"new",
"BarGraph",
"(",
"this",
".",
"displayOTron",
")",
";",
"this",
".",
"joystick",
"=",
"new",
"Joystick",
"(",
"this",
".",
"displayOTron",
")",
";",
"}"
] |
Creates a new `DOT3k` object.
@constructor
|
[
"Creates",
"a",
"new",
"DOT3k",
"object",
"."
] |
c8f9bfdbf4e2658bb12fc83bbf49853c938e7dcc
|
https://github.com/jorisvervuurt/JVSDisplayOTron/blob/c8f9bfdbf4e2658bb12fc83bbf49853c938e7dcc/lib/dot3k/dot3k.js#L44-L54
|
36,309 |
ascartabelli/lamb
|
src/privates/_isEnumerable.js
|
_isEnumerable
|
function _isEnumerable (obj, key) {
return key in Object(obj) && (_isOwnEnumerable(obj, key) || ~_safeEnumerables(obj).indexOf(key));
}
|
javascript
|
function _isEnumerable (obj, key) {
return key in Object(obj) && (_isOwnEnumerable(obj, key) || ~_safeEnumerables(obj).indexOf(key));
}
|
[
"function",
"_isEnumerable",
"(",
"obj",
",",
"key",
")",
"{",
"return",
"key",
"in",
"Object",
"(",
"obj",
")",
"&&",
"(",
"_isOwnEnumerable",
"(",
"obj",
",",
"key",
")",
"||",
"~",
"_safeEnumerables",
"(",
"obj",
")",
".",
"indexOf",
"(",
"key",
")",
")",
";",
"}"
] |
Checks whether the specified key is an enumerable property of the given object or not.
@private
@param {Object} obj
@param {String} key
@returns {Boolean}
|
[
"Checks",
"whether",
"the",
"specified",
"key",
"is",
"an",
"enumerable",
"property",
"of",
"the",
"given",
"object",
"or",
"not",
"."
] |
d36e45945c4789e4f1a2d8805936514b53f32362
|
https://github.com/ascartabelli/lamb/blob/d36e45945c4789e4f1a2d8805936514b53f32362/src/privates/_isEnumerable.js#L11-L13
|
36,310 |
ascartabelli/lamb
|
src/privates/_compareWith.js
|
_compareWith
|
function _compareWith (criteria) {
return function (a, b) {
var len = criteria.length;
var criterion = criteria[0];
var result = criterion.compare(a.value, b.value);
for (var i = 1; result === 0 && i < len; i++) {
criterion = criteria[i];
result = criterion.compare(a.value, b.value);
}
if (result === 0) {
result = a.index - b.index;
}
return criterion.isDescending ? -result : result;
};
}
|
javascript
|
function _compareWith (criteria) {
return function (a, b) {
var len = criteria.length;
var criterion = criteria[0];
var result = criterion.compare(a.value, b.value);
for (var i = 1; result === 0 && i < len; i++) {
criterion = criteria[i];
result = criterion.compare(a.value, b.value);
}
if (result === 0) {
result = a.index - b.index;
}
return criterion.isDescending ? -result : result;
};
}
|
[
"function",
"_compareWith",
"(",
"criteria",
")",
"{",
"return",
"function",
"(",
"a",
",",
"b",
")",
"{",
"var",
"len",
"=",
"criteria",
".",
"length",
";",
"var",
"criterion",
"=",
"criteria",
"[",
"0",
"]",
";",
"var",
"result",
"=",
"criterion",
".",
"compare",
"(",
"a",
".",
"value",
",",
"b",
".",
"value",
")",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"result",
"===",
"0",
"&&",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"criterion",
"=",
"criteria",
"[",
"i",
"]",
";",
"result",
"=",
"criterion",
".",
"compare",
"(",
"a",
".",
"value",
",",
"b",
".",
"value",
")",
";",
"}",
"if",
"(",
"result",
"===",
"0",
")",
"{",
"result",
"=",
"a",
".",
"index",
"-",
"b",
".",
"index",
";",
"}",
"return",
"criterion",
".",
"isDescending",
"?",
"-",
"result",
":",
"result",
";",
"}",
";",
"}"
] |
Accepts a list of sorting criteria with at least one element
and builds a function that compares two values with such criteria.
@private
@param {Sorter[]} criteria
@returns {Function}
|
[
"Accepts",
"a",
"list",
"of",
"sorting",
"criteria",
"with",
"at",
"least",
"one",
"element",
"and",
"builds",
"a",
"function",
"that",
"compares",
"two",
"values",
"with",
"such",
"criteria",
"."
] |
d36e45945c4789e4f1a2d8805936514b53f32362
|
https://github.com/ascartabelli/lamb/blob/d36e45945c4789e4f1a2d8805936514b53f32362/src/privates/_compareWith.js#L8-L25
|
36,311 |
ascartabelli/lamb
|
src/privates/_currier.js
|
_currier
|
function _currier (fn, arity, isRightCurry, isAutoCurry, argsHolder) {
return function () {
var holderLen = argsHolder.length;
var argsLen = arguments.length;
var newArgsLen = holderLen + (argsLen > 1 && isAutoCurry ? argsLen : 1);
var newArgs = Array(newArgsLen);
for (var i = 0; i < holderLen; i++) {
newArgs[i] = argsHolder[i];
}
for (; i < newArgsLen; i++) {
newArgs[i] = arguments[i - holderLen];
}
if (newArgsLen >= arity) {
return fn.apply(this, isRightCurry ? newArgs.reverse() : newArgs);
} else {
return _currier(fn, arity, isRightCurry, isAutoCurry, newArgs);
}
};
}
|
javascript
|
function _currier (fn, arity, isRightCurry, isAutoCurry, argsHolder) {
return function () {
var holderLen = argsHolder.length;
var argsLen = arguments.length;
var newArgsLen = holderLen + (argsLen > 1 && isAutoCurry ? argsLen : 1);
var newArgs = Array(newArgsLen);
for (var i = 0; i < holderLen; i++) {
newArgs[i] = argsHolder[i];
}
for (; i < newArgsLen; i++) {
newArgs[i] = arguments[i - holderLen];
}
if (newArgsLen >= arity) {
return fn.apply(this, isRightCurry ? newArgs.reverse() : newArgs);
} else {
return _currier(fn, arity, isRightCurry, isAutoCurry, newArgs);
}
};
}
|
[
"function",
"_currier",
"(",
"fn",
",",
"arity",
",",
"isRightCurry",
",",
"isAutoCurry",
",",
"argsHolder",
")",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"holderLen",
"=",
"argsHolder",
".",
"length",
";",
"var",
"argsLen",
"=",
"arguments",
".",
"length",
";",
"var",
"newArgsLen",
"=",
"holderLen",
"+",
"(",
"argsLen",
">",
"1",
"&&",
"isAutoCurry",
"?",
"argsLen",
":",
"1",
")",
";",
"var",
"newArgs",
"=",
"Array",
"(",
"newArgsLen",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"holderLen",
";",
"i",
"++",
")",
"{",
"newArgs",
"[",
"i",
"]",
"=",
"argsHolder",
"[",
"i",
"]",
";",
"}",
"for",
"(",
";",
"i",
"<",
"newArgsLen",
";",
"i",
"++",
")",
"{",
"newArgs",
"[",
"i",
"]",
"=",
"arguments",
"[",
"i",
"-",
"holderLen",
"]",
";",
"}",
"if",
"(",
"newArgsLen",
">=",
"arity",
")",
"{",
"return",
"fn",
".",
"apply",
"(",
"this",
",",
"isRightCurry",
"?",
"newArgs",
".",
"reverse",
"(",
")",
":",
"newArgs",
")",
";",
"}",
"else",
"{",
"return",
"_currier",
"(",
"fn",
",",
"arity",
",",
"isRightCurry",
",",
"isAutoCurry",
",",
"newArgs",
")",
";",
"}",
"}",
";",
"}"
] |
Used by curry functions to collect arguments until the arity is consumed,
then applies the original function.
@private
@param {Function} fn
@param {Number} arity
@param {Boolean} isRightCurry
@param {Boolean} isAutoCurry
@param {Array} argsHolder
@returns {Function}
|
[
"Used",
"by",
"curry",
"functions",
"to",
"collect",
"arguments",
"until",
"the",
"arity",
"is",
"consumed",
"then",
"applies",
"the",
"original",
"function",
"."
] |
d36e45945c4789e4f1a2d8805936514b53f32362
|
https://github.com/ascartabelli/lamb/blob/d36e45945c4789e4f1a2d8805936514b53f32362/src/privates/_currier.js#L12-L33
|
36,312 |
mrsteele/ng-alerts
|
dist/ng-alerts.js
|
reset
|
function reset() {
$scope.count = ngAlertsMngr.get().length;
$scope.badge = ($attrs.badge);
if ($scope.count === 0 && $attrs.hideEmpty) {
$scope.count = '';
}
}
|
javascript
|
function reset() {
$scope.count = ngAlertsMngr.get().length;
$scope.badge = ($attrs.badge);
if ($scope.count === 0 && $attrs.hideEmpty) {
$scope.count = '';
}
}
|
[
"function",
"reset",
"(",
")",
"{",
"$scope",
".",
"count",
"=",
"ngAlertsMngr",
".",
"get",
"(",
")",
".",
"length",
";",
"$scope",
".",
"badge",
"=",
"(",
"$attrs",
".",
"badge",
")",
";",
"if",
"(",
"$scope",
".",
"count",
"===",
"0",
"&&",
"$attrs",
".",
"hideEmpty",
")",
"{",
"$scope",
".",
"count",
"=",
"''",
";",
"}",
"}"
] |
Resets the alert count view.
|
[
"Resets",
"the",
"alert",
"count",
"view",
"."
] |
8f4a811a62d331d6286ce01aaf88479f3cdf181c
|
https://github.com/mrsteele/ng-alerts/blob/8f4a811a62d331d6286ce01aaf88479f3cdf181c/dist/ng-alerts.js#L55-L62
|
36,313 |
mrsteele/ng-alerts
|
dist/ng-alerts.js
|
remove
|
function remove(id) {
var i;
for (i = 0; i < $scope.alerts.length; i += 1) {
if ($scope.alerts[i].id === id) {
$scope.alerts.splice(i, 1);
return;
}
}
}
|
javascript
|
function remove(id) {
var i;
for (i = 0; i < $scope.alerts.length; i += 1) {
if ($scope.alerts[i].id === id) {
$scope.alerts.splice(i, 1);
return;
}
}
}
|
[
"function",
"remove",
"(",
"id",
")",
"{",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"$scope",
".",
"alerts",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"if",
"(",
"$scope",
".",
"alerts",
"[",
"i",
"]",
".",
"id",
"===",
"id",
")",
"{",
"$scope",
".",
"alerts",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"return",
";",
"}",
"}",
"}"
] |
Removes a specific alert by id.
|
[
"Removes",
"a",
"specific",
"alert",
"by",
"id",
"."
] |
8f4a811a62d331d6286ce01aaf88479f3cdf181c
|
https://github.com/mrsteele/ng-alerts/blob/8f4a811a62d331d6286ce01aaf88479f3cdf181c/dist/ng-alerts.js#L225-L233
|
36,314 |
mrsteele/ng-alerts
|
dist/ng-alerts.js
|
function (args) {
var params = angular.extend({
id: ngAlertsId.create(),
msg: '',
type: 'default',
time: Date.now()
}, args);
this.id = params.id;
this.msg = params.msg;
this.type = params.type;
this.time = params.time;
}
|
javascript
|
function (args) {
var params = angular.extend({
id: ngAlertsId.create(),
msg: '',
type: 'default',
time: Date.now()
}, args);
this.id = params.id;
this.msg = params.msg;
this.type = params.type;
this.time = params.time;
}
|
[
"function",
"(",
"args",
")",
"{",
"var",
"params",
"=",
"angular",
".",
"extend",
"(",
"{",
"id",
":",
"ngAlertsId",
".",
"create",
"(",
")",
",",
"msg",
":",
"''",
",",
"type",
":",
"'default'",
",",
"time",
":",
"Date",
".",
"now",
"(",
")",
"}",
",",
"args",
")",
";",
"this",
".",
"id",
"=",
"params",
".",
"id",
";",
"this",
".",
"msg",
"=",
"params",
".",
"msg",
";",
"this",
".",
"type",
"=",
"params",
".",
"type",
";",
"this",
".",
"time",
"=",
"params",
".",
"time",
";",
"}"
] |
The alert object.
@param {Object} args - The argument object.
@param {Number} args.id - The unique id.
@param {String} args.msg - The message.
@param {String} [args.type=default] - The type of alert.
@param {Number} [args.time=Date.now()] - The time of the notification (Miliseconds since Jan 1 1970).
|
[
"The",
"alert",
"object",
"."
] |
8f4a811a62d331d6286ce01aaf88479f3cdf181c
|
https://github.com/mrsteele/ng-alerts/blob/8f4a811a62d331d6286ce01aaf88479f3cdf181c/dist/ng-alerts.js#L281-L293
|
|
36,315 |
mrsteele/ng-alerts
|
dist/ng-alerts.js
|
fire
|
function fire(name, args) {
ngAlertsEvent.fire(name, args);
ngAlertsEvent.fire('change', args);
}
|
javascript
|
function fire(name, args) {
ngAlertsEvent.fire(name, args);
ngAlertsEvent.fire('change', args);
}
|
[
"function",
"fire",
"(",
"name",
",",
"args",
")",
"{",
"ngAlertsEvent",
".",
"fire",
"(",
"name",
",",
"args",
")",
";",
"ngAlertsEvent",
".",
"fire",
"(",
"'change'",
",",
"args",
")",
";",
"}"
] |
Fires an alert event.
@param {String} name - The name of the event.
@param {Object=} args - Any optional arguments.
|
[
"Fires",
"an",
"alert",
"event",
"."
] |
8f4a811a62d331d6286ce01aaf88479f3cdf181c
|
https://github.com/mrsteele/ng-alerts/blob/8f4a811a62d331d6286ce01aaf88479f3cdf181c/dist/ng-alerts.js#L355-L358
|
36,316 |
ILLGrenoble/guacamole-common-js
|
src/StringWriter.js
|
__expand
|
function __expand(bytes) {
// Resize buffer if more space needed
if (length+bytes >= buffer.length) {
var new_buffer = new Uint8Array((length+bytes)*2);
new_buffer.set(buffer);
buffer = new_buffer;
}
length += bytes;
}
|
javascript
|
function __expand(bytes) {
// Resize buffer if more space needed
if (length+bytes >= buffer.length) {
var new_buffer = new Uint8Array((length+bytes)*2);
new_buffer.set(buffer);
buffer = new_buffer;
}
length += bytes;
}
|
[
"function",
"__expand",
"(",
"bytes",
")",
"{",
"// Resize buffer if more space needed",
"if",
"(",
"length",
"+",
"bytes",
">=",
"buffer",
".",
"length",
")",
"{",
"var",
"new_buffer",
"=",
"new",
"Uint8Array",
"(",
"(",
"length",
"+",
"bytes",
")",
"*",
"2",
")",
";",
"new_buffer",
".",
"set",
"(",
"buffer",
")",
";",
"buffer",
"=",
"new_buffer",
";",
"}",
"length",
"+=",
"bytes",
";",
"}"
] |
Expands the size of the underlying buffer by the given number of bytes,
updating the length appropriately.
@private
@param {Number} bytes The number of bytes to add to the underlying
buffer.
|
[
"Expands",
"the",
"size",
"of",
"the",
"underlying",
"buffer",
"by",
"the",
"given",
"number",
"of",
"bytes",
"updating",
"the",
"length",
"appropriately",
"."
] |
71925794155ea3fc37d2a125adbca6f8be532887
|
https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/StringWriter.js#L71-L82
|
36,317 |
ILLGrenoble/guacamole-common-js
|
src/StringWriter.js
|
__append_utf8
|
function __append_utf8(codepoint) {
var mask;
var bytes;
// 1 byte
if (codepoint <= 0x7F) {
mask = 0x00;
bytes = 1;
}
// 2 byte
else if (codepoint <= 0x7FF) {
mask = 0xC0;
bytes = 2;
}
// 3 byte
else if (codepoint <= 0xFFFF) {
mask = 0xE0;
bytes = 3;
}
// 4 byte
else if (codepoint <= 0x1FFFFF) {
mask = 0xF0;
bytes = 4;
}
// If invalid codepoint, append replacement character
else {
__append_utf8(0xFFFD);
return;
}
// Offset buffer by size
__expand(bytes);
var offset = length - 1;
// Add trailing bytes, if any
for (var i=1; i<bytes; i++) {
buffer[offset--] = 0x80 | (codepoint & 0x3F);
codepoint >>= 6;
}
// Set initial byte
buffer[offset] = mask | codepoint;
}
|
javascript
|
function __append_utf8(codepoint) {
var mask;
var bytes;
// 1 byte
if (codepoint <= 0x7F) {
mask = 0x00;
bytes = 1;
}
// 2 byte
else if (codepoint <= 0x7FF) {
mask = 0xC0;
bytes = 2;
}
// 3 byte
else if (codepoint <= 0xFFFF) {
mask = 0xE0;
bytes = 3;
}
// 4 byte
else if (codepoint <= 0x1FFFFF) {
mask = 0xF0;
bytes = 4;
}
// If invalid codepoint, append replacement character
else {
__append_utf8(0xFFFD);
return;
}
// Offset buffer by size
__expand(bytes);
var offset = length - 1;
// Add trailing bytes, if any
for (var i=1; i<bytes; i++) {
buffer[offset--] = 0x80 | (codepoint & 0x3F);
codepoint >>= 6;
}
// Set initial byte
buffer[offset] = mask | codepoint;
}
|
[
"function",
"__append_utf8",
"(",
"codepoint",
")",
"{",
"var",
"mask",
";",
"var",
"bytes",
";",
"// 1 byte",
"if",
"(",
"codepoint",
"<=",
"0x7F",
")",
"{",
"mask",
"=",
"0x00",
";",
"bytes",
"=",
"1",
";",
"}",
"// 2 byte",
"else",
"if",
"(",
"codepoint",
"<=",
"0x7FF",
")",
"{",
"mask",
"=",
"0xC0",
";",
"bytes",
"=",
"2",
";",
"}",
"// 3 byte",
"else",
"if",
"(",
"codepoint",
"<=",
"0xFFFF",
")",
"{",
"mask",
"=",
"0xE0",
";",
"bytes",
"=",
"3",
";",
"}",
"// 4 byte",
"else",
"if",
"(",
"codepoint",
"<=",
"0x1FFFFF",
")",
"{",
"mask",
"=",
"0xF0",
";",
"bytes",
"=",
"4",
";",
"}",
"// If invalid codepoint, append replacement character",
"else",
"{",
"__append_utf8",
"(",
"0xFFFD",
")",
";",
"return",
";",
"}",
"// Offset buffer by size",
"__expand",
"(",
"bytes",
")",
";",
"var",
"offset",
"=",
"length",
"-",
"1",
";",
"// Add trailing bytes, if any",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"bytes",
";",
"i",
"++",
")",
"{",
"buffer",
"[",
"offset",
"--",
"]",
"=",
"0x80",
"|",
"(",
"codepoint",
"&",
"0x3F",
")",
";",
"codepoint",
">>=",
"6",
";",
"}",
"// Set initial byte",
"buffer",
"[",
"offset",
"]",
"=",
"mask",
"|",
"codepoint",
";",
"}"
] |
Appends a single Unicode character to the current buffer, resizing the
buffer if necessary. The character will be encoded as UTF-8.
@private
@param {Number} codepoint The codepoint of the Unicode character to
append.
|
[
"Appends",
"a",
"single",
"Unicode",
"character",
"to",
"the",
"current",
"buffer",
"resizing",
"the",
"buffer",
"if",
"necessary",
".",
"The",
"character",
"will",
"be",
"encoded",
"as",
"UTF",
"-",
"8",
"."
] |
71925794155ea3fc37d2a125adbca6f8be532887
|
https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/StringWriter.js#L92-L140
|
36,318 |
ILLGrenoble/guacamole-common-js
|
src/StringWriter.js
|
__encode_utf8
|
function __encode_utf8(text) {
// Fill buffer with UTF-8
for (var i=0; i<text.length; i++) {
var codepoint = text.charCodeAt(i);
__append_utf8(codepoint);
}
// Flush buffer
if (length > 0) {
var out_buffer = buffer.subarray(0, length);
length = 0;
return out_buffer;
}
}
|
javascript
|
function __encode_utf8(text) {
// Fill buffer with UTF-8
for (var i=0; i<text.length; i++) {
var codepoint = text.charCodeAt(i);
__append_utf8(codepoint);
}
// Flush buffer
if (length > 0) {
var out_buffer = buffer.subarray(0, length);
length = 0;
return out_buffer;
}
}
|
[
"function",
"__encode_utf8",
"(",
"text",
")",
"{",
"// Fill buffer with UTF-8",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"text",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"codepoint",
"=",
"text",
".",
"charCodeAt",
"(",
"i",
")",
";",
"__append_utf8",
"(",
"codepoint",
")",
";",
"}",
"// Flush buffer",
"if",
"(",
"length",
">",
"0",
")",
"{",
"var",
"out_buffer",
"=",
"buffer",
".",
"subarray",
"(",
"0",
",",
"length",
")",
";",
"length",
"=",
"0",
";",
"return",
"out_buffer",
";",
"}",
"}"
] |
Encodes the given string as UTF-8, returning an ArrayBuffer containing
the resulting bytes.
@private
@param {String} text The string to encode as UTF-8.
@return {Uint8Array} The encoded UTF-8 data.
|
[
"Encodes",
"the",
"given",
"string",
"as",
"UTF",
"-",
"8",
"returning",
"an",
"ArrayBuffer",
"containing",
"the",
"resulting",
"bytes",
"."
] |
71925794155ea3fc37d2a125adbca6f8be532887
|
https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/StringWriter.js#L150-L165
|
36,319 |
octet-stream/object-to-form-data
|
serialize.js
|
set
|
function set(prefix, value) {
for (const key of keys(value)) {
const name = prefix ? `${prefix}[${key}]` : key
const field = value[key]
if (isArray(field) || isPlainObject(field)) {
set(name, field)
} else {
if (options.strict && (isBoolean(field) && field === false)) {
continue
}
fd[method](name, field)
}
}
}
|
javascript
|
function set(prefix, value) {
for (const key of keys(value)) {
const name = prefix ? `${prefix}[${key}]` : key
const field = value[key]
if (isArray(field) || isPlainObject(field)) {
set(name, field)
} else {
if (options.strict && (isBoolean(field) && field === false)) {
continue
}
fd[method](name, field)
}
}
}
|
[
"function",
"set",
"(",
"prefix",
",",
"value",
")",
"{",
"for",
"(",
"const",
"key",
"of",
"keys",
"(",
"value",
")",
")",
"{",
"const",
"name",
"=",
"prefix",
"?",
"`",
"${",
"prefix",
"}",
"${",
"key",
"}",
"`",
":",
"key",
"const",
"field",
"=",
"value",
"[",
"key",
"]",
"if",
"(",
"isArray",
"(",
"field",
")",
"||",
"isPlainObject",
"(",
"field",
")",
")",
"{",
"set",
"(",
"name",
",",
"field",
")",
"}",
"else",
"{",
"if",
"(",
"options",
".",
"strict",
"&&",
"(",
"isBoolean",
"(",
"field",
")",
"&&",
"field",
"===",
"false",
")",
")",
"{",
"continue",
"}",
"fd",
"[",
"method",
"]",
"(",
"name",
",",
"field",
")",
"}",
"}",
"}"
] |
Set object fields to FormData instance
@param {string} [prefix = undefined] – parent field key
@param {any} value – A value of the current field
@api private
|
[
"Set",
"object",
"fields",
"to",
"FormData",
"instance"
] |
a6cbb2accc5df56be1266f8e21c7510c12fc3304
|
https://github.com/octet-stream/object-to-form-data/blob/a6cbb2accc5df56be1266f8e21c7510c12fc3304/serialize.js#L61-L76
|
36,320 |
ILLGrenoble/guacamole-common-js
|
src/AudioRecorder.js
|
getValueAt
|
function getValueAt(audioData, t) {
// Convert [0, 1] range to [0, audioData.length - 1]
var index = (audioData.length - 1) * t;
// Determine the start and end points for the summation used by the
// Lanczos interpolation algorithm (see: https://en.wikipedia.org/wiki/Lanczos_resampling)
var start = Math.floor(index) - LANCZOS_WINDOW_SIZE + 1;
var end = Math.floor(index) + LANCZOS_WINDOW_SIZE;
// Calculate the value of the Lanczos interpolation function for the
// required range
var sum = 0;
for (var i = start; i <= end; i++) {
sum += (audioData[i] || 0) * lanczos(index - i, LANCZOS_WINDOW_SIZE);
}
return sum;
}
|
javascript
|
function getValueAt(audioData, t) {
// Convert [0, 1] range to [0, audioData.length - 1]
var index = (audioData.length - 1) * t;
// Determine the start and end points for the summation used by the
// Lanczos interpolation algorithm (see: https://en.wikipedia.org/wiki/Lanczos_resampling)
var start = Math.floor(index) - LANCZOS_WINDOW_SIZE + 1;
var end = Math.floor(index) + LANCZOS_WINDOW_SIZE;
// Calculate the value of the Lanczos interpolation function for the
// required range
var sum = 0;
for (var i = start; i <= end; i++) {
sum += (audioData[i] || 0) * lanczos(index - i, LANCZOS_WINDOW_SIZE);
}
return sum;
}
|
[
"function",
"getValueAt",
"(",
"audioData",
",",
"t",
")",
"{",
"// Convert [0, 1] range to [0, audioData.length - 1]",
"var",
"index",
"=",
"(",
"audioData",
".",
"length",
"-",
"1",
")",
"*",
"t",
";",
"// Determine the start and end points for the summation used by the",
"// Lanczos interpolation algorithm (see: https://en.wikipedia.org/wiki/Lanczos_resampling)",
"var",
"start",
"=",
"Math",
".",
"floor",
"(",
"index",
")",
"-",
"LANCZOS_WINDOW_SIZE",
"+",
"1",
";",
"var",
"end",
"=",
"Math",
".",
"floor",
"(",
"index",
")",
"+",
"LANCZOS_WINDOW_SIZE",
";",
"// Calculate the value of the Lanczos interpolation function for the",
"// required range",
"var",
"sum",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"start",
";",
"i",
"<=",
"end",
";",
"i",
"++",
")",
"{",
"sum",
"+=",
"(",
"audioData",
"[",
"i",
"]",
"||",
"0",
")",
"*",
"lanczos",
"(",
"index",
"-",
"i",
",",
"LANCZOS_WINDOW_SIZE",
")",
";",
"}",
"return",
"sum",
";",
"}"
] |
Determines the value of the waveform represented by the audio data at
the given location. If the value cannot be determined exactly as it does
not correspond to an exact sample within the audio data, the value will
be derived through interpolating nearby samples.
@private
@param {Float32Array} audioData
An array of audio data, as returned by AudioBuffer.getChannelData().
@param {Number} t
The relative location within the waveform from which the value
should be retrieved, represented as a floating point number between
0 and 1 inclusive, where 0 represents the earliest point in time and
1 represents the latest.
@returns {Number}
The value of the waveform at the given location.
|
[
"Determines",
"the",
"value",
"of",
"the",
"waveform",
"represented",
"by",
"the",
"audio",
"data",
"at",
"the",
"given",
"location",
".",
"If",
"the",
"value",
"cannot",
"be",
"determined",
"exactly",
"as",
"it",
"does",
"not",
"correspond",
"to",
"an",
"exact",
"sample",
"within",
"the",
"audio",
"data",
"the",
"value",
"will",
"be",
"derived",
"through",
"interpolating",
"nearby",
"samples",
"."
] |
71925794155ea3fc37d2a125adbca6f8be532887
|
https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/AudioRecorder.js#L342-L361
|
36,321 |
ILLGrenoble/guacamole-common-js
|
src/AudioRecorder.js
|
toSampleArray
|
function toSampleArray(audioBuffer) {
// Track overall amount of data read
var inSamples = audioBuffer.length;
readSamples += inSamples;
// Calculate the total number of samples that should be written as of
// the audio data just received and adjust the size of the output
// packet accordingly
var expectedWrittenSamples = Math.round(readSamples * format.rate / audioBuffer.sampleRate);
var outSamples = expectedWrittenSamples - writtenSamples;
// Update number of samples written
writtenSamples += outSamples;
// Get array for raw PCM storage
var data = new SampleArray(outSamples * format.channels);
// Convert each channel
for (var channel = 0; channel < format.channels; channel++) {
var audioData = audioBuffer.getChannelData(channel);
// Fill array with data from audio buffer channel
var offset = channel;
for (var i = 0; i < outSamples; i++) {
data[offset] = interpolateSample(audioData, i / (outSamples - 1)) * maxSampleValue;
offset += format.channels;
}
}
return data;
}
|
javascript
|
function toSampleArray(audioBuffer) {
// Track overall amount of data read
var inSamples = audioBuffer.length;
readSamples += inSamples;
// Calculate the total number of samples that should be written as of
// the audio data just received and adjust the size of the output
// packet accordingly
var expectedWrittenSamples = Math.round(readSamples * format.rate / audioBuffer.sampleRate);
var outSamples = expectedWrittenSamples - writtenSamples;
// Update number of samples written
writtenSamples += outSamples;
// Get array for raw PCM storage
var data = new SampleArray(outSamples * format.channels);
// Convert each channel
for (var channel = 0; channel < format.channels; channel++) {
var audioData = audioBuffer.getChannelData(channel);
// Fill array with data from audio buffer channel
var offset = channel;
for (var i = 0; i < outSamples; i++) {
data[offset] = interpolateSample(audioData, i / (outSamples - 1)) * maxSampleValue;
offset += format.channels;
}
}
return data;
}
|
[
"function",
"toSampleArray",
"(",
"audioBuffer",
")",
"{",
"// Track overall amount of data read",
"var",
"inSamples",
"=",
"audioBuffer",
".",
"length",
";",
"readSamples",
"+=",
"inSamples",
";",
"// Calculate the total number of samples that should be written as of",
"// the audio data just received and adjust the size of the output",
"// packet accordingly",
"var",
"expectedWrittenSamples",
"=",
"Math",
".",
"round",
"(",
"readSamples",
"*",
"format",
".",
"rate",
"/",
"audioBuffer",
".",
"sampleRate",
")",
";",
"var",
"outSamples",
"=",
"expectedWrittenSamples",
"-",
"writtenSamples",
";",
"// Update number of samples written",
"writtenSamples",
"+=",
"outSamples",
";",
"// Get array for raw PCM storage",
"var",
"data",
"=",
"new",
"SampleArray",
"(",
"outSamples",
"*",
"format",
".",
"channels",
")",
";",
"// Convert each channel",
"for",
"(",
"var",
"channel",
"=",
"0",
";",
"channel",
"<",
"format",
".",
"channels",
";",
"channel",
"++",
")",
"{",
"var",
"audioData",
"=",
"audioBuffer",
".",
"getChannelData",
"(",
"channel",
")",
";",
"// Fill array with data from audio buffer channel",
"var",
"offset",
"=",
"channel",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"outSamples",
";",
"i",
"++",
")",
"{",
"data",
"[",
"offset",
"]",
"=",
"interpolateSample",
"(",
"audioData",
",",
"i",
"/",
"(",
"outSamples",
"-",
"1",
")",
")",
"*",
"maxSampleValue",
";",
"offset",
"+=",
"format",
".",
"channels",
";",
"}",
"}",
"return",
"data",
";",
"}"
] |
Converts the given AudioBuffer into an audio packet, ready for streaming
along the underlying output stream. Unlike the raw audio packets used by
this audio recorder, AudioBuffers require floating point samples and are
split into isolated planes of channel-specific data.
@private
@param {AudioBuffer} audioBuffer
The Web Audio API AudioBuffer that should be converted to a raw
audio packet.
@returns {SampleArray}
A new raw audio packet containing the audio data from the provided
AudioBuffer.
|
[
"Converts",
"the",
"given",
"AudioBuffer",
"into",
"an",
"audio",
"packet",
"ready",
"for",
"streaming",
"along",
"the",
"underlying",
"output",
"stream",
".",
"Unlike",
"the",
"raw",
"audio",
"packets",
"used",
"by",
"this",
"audio",
"recorder",
"AudioBuffers",
"require",
"floating",
"point",
"samples",
"and",
"are",
"split",
"into",
"isolated",
"planes",
"of",
"channel",
"-",
"specific",
"data",
"."
] |
71925794155ea3fc37d2a125adbca6f8be532887
|
https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/AudioRecorder.js#L378-L412
|
36,322 |
ILLGrenoble/guacamole-common-js
|
src/AudioRecorder.js
|
beginAudioCapture
|
function beginAudioCapture() {
// Attempt to retrieve an audio input stream from the browser
navigator.mediaDevices.getUserMedia({ 'audio' : true }, function streamReceived(stream) {
// Create processing node which receives appropriately-sized audio buffers
processor = context.createScriptProcessor(BUFFER_SIZE, format.channels, format.channels);
processor.connect(context.destination);
// Send blobs when audio buffers are received
processor.onaudioprocess = function processAudio(e) {
writer.sendData(toSampleArray(e.inputBuffer).buffer);
};
// Connect processing node to user's audio input source
source = context.createMediaStreamSource(stream);
source.connect(processor);
// Save stream for later cleanup
mediaStream = stream;
}, function streamDenied() {
// Simply end stream if audio access is not allowed
writer.sendEnd();
// Notify of closure
if (recorder.onerror)
recorder.onerror();
});
}
|
javascript
|
function beginAudioCapture() {
// Attempt to retrieve an audio input stream from the browser
navigator.mediaDevices.getUserMedia({ 'audio' : true }, function streamReceived(stream) {
// Create processing node which receives appropriately-sized audio buffers
processor = context.createScriptProcessor(BUFFER_SIZE, format.channels, format.channels);
processor.connect(context.destination);
// Send blobs when audio buffers are received
processor.onaudioprocess = function processAudio(e) {
writer.sendData(toSampleArray(e.inputBuffer).buffer);
};
// Connect processing node to user's audio input source
source = context.createMediaStreamSource(stream);
source.connect(processor);
// Save stream for later cleanup
mediaStream = stream;
}, function streamDenied() {
// Simply end stream if audio access is not allowed
writer.sendEnd();
// Notify of closure
if (recorder.onerror)
recorder.onerror();
});
}
|
[
"function",
"beginAudioCapture",
"(",
")",
"{",
"// Attempt to retrieve an audio input stream from the browser",
"navigator",
".",
"mediaDevices",
".",
"getUserMedia",
"(",
"{",
"'audio'",
":",
"true",
"}",
",",
"function",
"streamReceived",
"(",
"stream",
")",
"{",
"// Create processing node which receives appropriately-sized audio buffers",
"processor",
"=",
"context",
".",
"createScriptProcessor",
"(",
"BUFFER_SIZE",
",",
"format",
".",
"channels",
",",
"format",
".",
"channels",
")",
";",
"processor",
".",
"connect",
"(",
"context",
".",
"destination",
")",
";",
"// Send blobs when audio buffers are received",
"processor",
".",
"onaudioprocess",
"=",
"function",
"processAudio",
"(",
"e",
")",
"{",
"writer",
".",
"sendData",
"(",
"toSampleArray",
"(",
"e",
".",
"inputBuffer",
")",
".",
"buffer",
")",
";",
"}",
";",
"// Connect processing node to user's audio input source",
"source",
"=",
"context",
".",
"createMediaStreamSource",
"(",
"stream",
")",
";",
"source",
".",
"connect",
"(",
"processor",
")",
";",
"// Save stream for later cleanup",
"mediaStream",
"=",
"stream",
";",
"}",
",",
"function",
"streamDenied",
"(",
")",
"{",
"// Simply end stream if audio access is not allowed",
"writer",
".",
"sendEnd",
"(",
")",
";",
"// Notify of closure",
"if",
"(",
"recorder",
".",
"onerror",
")",
"recorder",
".",
"onerror",
"(",
")",
";",
"}",
")",
";",
"}"
] |
Requests access to the user's microphone and begins capturing audio. All
received audio data is resampled as necessary and forwarded to the
Guacamole stream underlying this Guacamole.RawAudioRecorder. This
function must be invoked ONLY ONCE per instance of
Guacamole.RawAudioRecorder.
@private
|
[
"Requests",
"access",
"to",
"the",
"user",
"s",
"microphone",
"and",
"begins",
"capturing",
"audio",
".",
"All",
"received",
"audio",
"data",
"is",
"resampled",
"as",
"necessary",
"and",
"forwarded",
"to",
"the",
"Guacamole",
"stream",
"underlying",
"this",
"Guacamole",
".",
"RawAudioRecorder",
".",
"This",
"function",
"must",
"be",
"invoked",
"ONLY",
"ONCE",
"per",
"instance",
"of",
"Guacamole",
".",
"RawAudioRecorder",
"."
] |
71925794155ea3fc37d2a125adbca6f8be532887
|
https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/AudioRecorder.js#L423-L455
|
36,323 |
ILLGrenoble/guacamole-common-js
|
src/AudioRecorder.js
|
stopAudioCapture
|
function stopAudioCapture() {
// Disconnect media source node from script processor
if (source)
source.disconnect();
// Disconnect associated script processor node
if (processor)
processor.disconnect();
// Stop capture
if (mediaStream) {
var tracks = mediaStream.getTracks();
for (var i = 0; i < tracks.length; i++)
tracks[i].stop();
}
// Remove references to now-unneeded components
processor = null;
source = null;
mediaStream = null;
// End stream
writer.sendEnd();
}
|
javascript
|
function stopAudioCapture() {
// Disconnect media source node from script processor
if (source)
source.disconnect();
// Disconnect associated script processor node
if (processor)
processor.disconnect();
// Stop capture
if (mediaStream) {
var tracks = mediaStream.getTracks();
for (var i = 0; i < tracks.length; i++)
tracks[i].stop();
}
// Remove references to now-unneeded components
processor = null;
source = null;
mediaStream = null;
// End stream
writer.sendEnd();
}
|
[
"function",
"stopAudioCapture",
"(",
")",
"{",
"// Disconnect media source node from script processor",
"if",
"(",
"source",
")",
"source",
".",
"disconnect",
"(",
")",
";",
"// Disconnect associated script processor node",
"if",
"(",
"processor",
")",
"processor",
".",
"disconnect",
"(",
")",
";",
"// Stop capture",
"if",
"(",
"mediaStream",
")",
"{",
"var",
"tracks",
"=",
"mediaStream",
".",
"getTracks",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"tracks",
".",
"length",
";",
"i",
"++",
")",
"tracks",
"[",
"i",
"]",
".",
"stop",
"(",
")",
";",
"}",
"// Remove references to now-unneeded components",
"processor",
"=",
"null",
";",
"source",
"=",
"null",
";",
"mediaStream",
"=",
"null",
";",
"// End stream",
"writer",
".",
"sendEnd",
"(",
")",
";",
"}"
] |
Stops capturing audio, if the capture has started, freeing all associated
resources. If the capture has not started, this function simply ends the
underlying Guacamole stream.
@private
|
[
"Stops",
"capturing",
"audio",
"if",
"the",
"capture",
"has",
"started",
"freeing",
"all",
"associated",
"resources",
".",
"If",
"the",
"capture",
"has",
"not",
"started",
"this",
"function",
"simply",
"ends",
"the",
"underlying",
"Guacamole",
"stream",
"."
] |
71925794155ea3fc37d2a125adbca6f8be532887
|
https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/AudioRecorder.js#L464-L489
|
36,324 |
ILLGrenoble/guacamole-common-js
|
guacamole.js
|
__decode_utf8
|
function __decode_utf8(buffer) {
var text = "";
var bytes = new Uint8Array(buffer);
for (var i=0; i<bytes.length; i++) {
// Get current byte
var value = bytes[i];
// Start new codepoint if nothing yet read
if (bytes_remaining === 0) {
// 1 byte (0xxxxxxx)
if ((value | 0x7F) === 0x7F)
text += String.fromCharCode(value);
// 2 byte (110xxxxx)
else if ((value | 0x1F) === 0xDF) {
codepoint = value & 0x1F;
bytes_remaining = 1;
}
// 3 byte (1110xxxx)
else if ((value | 0x0F )=== 0xEF) {
codepoint = value & 0x0F;
bytes_remaining = 2;
}
// 4 byte (11110xxx)
else if ((value | 0x07) === 0xF7) {
codepoint = value & 0x07;
bytes_remaining = 3;
}
// Invalid byte
else
text += "\uFFFD";
}
// Continue existing codepoint (10xxxxxx)
else if ((value | 0x3F) === 0xBF) {
codepoint = (codepoint << 6) | (value & 0x3F);
bytes_remaining--;
// Write codepoint if finished
if (bytes_remaining === 0)
text += String.fromCharCode(codepoint);
}
// Invalid byte
else {
bytes_remaining = 0;
text += "\uFFFD";
}
}
return text;
}
|
javascript
|
function __decode_utf8(buffer) {
var text = "";
var bytes = new Uint8Array(buffer);
for (var i=0; i<bytes.length; i++) {
// Get current byte
var value = bytes[i];
// Start new codepoint if nothing yet read
if (bytes_remaining === 0) {
// 1 byte (0xxxxxxx)
if ((value | 0x7F) === 0x7F)
text += String.fromCharCode(value);
// 2 byte (110xxxxx)
else if ((value | 0x1F) === 0xDF) {
codepoint = value & 0x1F;
bytes_remaining = 1;
}
// 3 byte (1110xxxx)
else if ((value | 0x0F )=== 0xEF) {
codepoint = value & 0x0F;
bytes_remaining = 2;
}
// 4 byte (11110xxx)
else if ((value | 0x07) === 0xF7) {
codepoint = value & 0x07;
bytes_remaining = 3;
}
// Invalid byte
else
text += "\uFFFD";
}
// Continue existing codepoint (10xxxxxx)
else if ((value | 0x3F) === 0xBF) {
codepoint = (codepoint << 6) | (value & 0x3F);
bytes_remaining--;
// Write codepoint if finished
if (bytes_remaining === 0)
text += String.fromCharCode(codepoint);
}
// Invalid byte
else {
bytes_remaining = 0;
text += "\uFFFD";
}
}
return text;
}
|
[
"function",
"__decode_utf8",
"(",
"buffer",
")",
"{",
"var",
"text",
"=",
"\"\"",
";",
"var",
"bytes",
"=",
"new",
"Uint8Array",
"(",
"buffer",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"bytes",
".",
"length",
";",
"i",
"++",
")",
"{",
"// Get current byte",
"var",
"value",
"=",
"bytes",
"[",
"i",
"]",
";",
"// Start new codepoint if nothing yet read",
"if",
"(",
"bytes_remaining",
"===",
"0",
")",
"{",
"// 1 byte (0xxxxxxx)",
"if",
"(",
"(",
"value",
"|",
"0x7F",
")",
"===",
"0x7F",
")",
"text",
"+=",
"String",
".",
"fromCharCode",
"(",
"value",
")",
";",
"// 2 byte (110xxxxx)",
"else",
"if",
"(",
"(",
"value",
"|",
"0x1F",
")",
"===",
"0xDF",
")",
"{",
"codepoint",
"=",
"value",
"&",
"0x1F",
";",
"bytes_remaining",
"=",
"1",
";",
"}",
"// 3 byte (1110xxxx)",
"else",
"if",
"(",
"(",
"value",
"|",
"0x0F",
")",
"===",
"0xEF",
")",
"{",
"codepoint",
"=",
"value",
"&",
"0x0F",
";",
"bytes_remaining",
"=",
"2",
";",
"}",
"// 4 byte (11110xxx)",
"else",
"if",
"(",
"(",
"value",
"|",
"0x07",
")",
"===",
"0xF7",
")",
"{",
"codepoint",
"=",
"value",
"&",
"0x07",
";",
"bytes_remaining",
"=",
"3",
";",
"}",
"// Invalid byte",
"else",
"text",
"+=",
"\"\\uFFFD\"",
";",
"}",
"// Continue existing codepoint (10xxxxxx)",
"else",
"if",
"(",
"(",
"value",
"|",
"0x3F",
")",
"===",
"0xBF",
")",
"{",
"codepoint",
"=",
"(",
"codepoint",
"<<",
"6",
")",
"|",
"(",
"value",
"&",
"0x3F",
")",
";",
"bytes_remaining",
"--",
";",
"// Write codepoint if finished",
"if",
"(",
"bytes_remaining",
"===",
"0",
")",
"text",
"+=",
"String",
".",
"fromCharCode",
"(",
"codepoint",
")",
";",
"}",
"// Invalid byte",
"else",
"{",
"bytes_remaining",
"=",
"0",
";",
"text",
"+=",
"\"\\uFFFD\"",
";",
"}",
"}",
"return",
"text",
";",
"}"
] |
Decodes the given UTF-8 data into a Unicode string. The data may end in
the middle of a multibyte character.
@private
@param {ArrayBuffer} buffer Arbitrary UTF-8 data.
@return {String} A decoded Unicode string.
|
[
"Decodes",
"the",
"given",
"UTF",
"-",
"8",
"data",
"into",
"a",
"Unicode",
"string",
".",
"The",
"data",
"may",
"end",
"in",
"the",
"middle",
"of",
"a",
"multibyte",
"character",
"."
] |
71925794155ea3fc37d2a125adbca6f8be532887
|
https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/guacamole.js#L10731-L10794
|
36,325 |
egislook/fucss
|
fucss.js
|
extractMediaQuery
|
function extractMediaQuery(props){
var mediaValue = props.length && props[0];
if(Object.keys(fucss.media).indexOf(mediaValue) !== -1){
return props.shift();
}
}
|
javascript
|
function extractMediaQuery(props){
var mediaValue = props.length && props[0];
if(Object.keys(fucss.media).indexOf(mediaValue) !== -1){
return props.shift();
}
}
|
[
"function",
"extractMediaQuery",
"(",
"props",
")",
"{",
"var",
"mediaValue",
"=",
"props",
".",
"length",
"&&",
"props",
"[",
"0",
"]",
";",
"if",
"(",
"Object",
".",
"keys",
"(",
"fucss",
".",
"media",
")",
".",
"indexOf",
"(",
"mediaValue",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"props",
".",
"shift",
"(",
")",
";",
"}",
"}"
] |
from class to css rule
|
[
"from",
"class",
"to",
"css",
"rule"
] |
e0dd7941092ee3f2da44704027c233149ed4e9f1
|
https://github.com/egislook/fucss/blob/e0dd7941092ee3f2da44704027c233149ed4e9f1/fucss.js#L722-L727
|
36,326 |
aMarCruz/jspreproc
|
lib/ccparser.js
|
include
|
function include(ckey, file) {
var
match = file.match(INCNAME)
file = match && match[1]
if (file) {
var ch = file[0]
if ((ch === '"' || ch === "'") && ch === file.slice(-1))
file = file.slice(1, -1).trim()
}
if (file) {
result.insert = file
result.once = !!ckey[8]
}
else
emitError('Expected filename for #' + ckey + ' in @')
}
|
javascript
|
function include(ckey, file) {
var
match = file.match(INCNAME)
file = match && match[1]
if (file) {
var ch = file[0]
if ((ch === '"' || ch === "'") && ch === file.slice(-1))
file = file.slice(1, -1).trim()
}
if (file) {
result.insert = file
result.once = !!ckey[8]
}
else
emitError('Expected filename for #' + ckey + ' in @')
}
|
[
"function",
"include",
"(",
"ckey",
",",
"file",
")",
"{",
"var",
"match",
"=",
"file",
".",
"match",
"(",
"INCNAME",
")",
"file",
"=",
"match",
"&&",
"match",
"[",
"1",
"]",
"if",
"(",
"file",
")",
"{",
"var",
"ch",
"=",
"file",
"[",
"0",
"]",
"if",
"(",
"(",
"ch",
"===",
"'\"'",
"||",
"ch",
"===",
"\"'\"",
")",
"&&",
"ch",
"===",
"file",
".",
"slice",
"(",
"-",
"1",
")",
")",
"file",
"=",
"file",
".",
"slice",
"(",
"1",
",",
"-",
"1",
")",
".",
"trim",
"(",
")",
"}",
"if",
"(",
"file",
")",
"{",
"result",
".",
"insert",
"=",
"file",
"result",
".",
"once",
"=",
"!",
"!",
"ckey",
"[",
"8",
"]",
"}",
"else",
"emitError",
"(",
"'Expected filename for #'",
"+",
"ckey",
"+",
"' in @'",
")",
"}"
] |
Prepares `cc` for file insertion setting the `insert` and `once` properties of `cc`. Accepts quoted or unquoted filenames
|
[
"Prepares",
"cc",
"for",
"file",
"insertion",
"setting",
"the",
"insert",
"and",
"once",
"properties",
"of",
"cc",
".",
"Accepts",
"quoted",
"or",
"unquoted",
"filenames"
] |
5f31820d702a329e8aa25f0f3983f13097610250
|
https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/lib/ccparser.js#L53-L69
|
36,327 |
aMarCruz/jspreproc
|
lib/ccparser.js
|
normalize
|
function normalize(key, expr) {
if (key.slice(0, 4) !== 'incl') {
expr = expr.replace(/[/\*]\/.*/, '').trim()
// all keywords must have an expression, except `#else/#endif`
if (!expr && key !== 'else' && key !== 'endif') {
emitError('Expected expression for #' + key + ' in @')
return false
}
}
return expr
}
|
javascript
|
function normalize(key, expr) {
if (key.slice(0, 4) !== 'incl') {
expr = expr.replace(/[/\*]\/.*/, '').trim()
// all keywords must have an expression, except `#else/#endif`
if (!expr && key !== 'else' && key !== 'endif') {
emitError('Expected expression for #' + key + ' in @')
return false
}
}
return expr
}
|
[
"function",
"normalize",
"(",
"key",
",",
"expr",
")",
"{",
"if",
"(",
"key",
".",
"slice",
"(",
"0",
",",
"4",
")",
"!==",
"'incl'",
")",
"{",
"expr",
"=",
"expr",
".",
"replace",
"(",
"/",
"[/\\*]\\/.*",
"/",
",",
"''",
")",
".",
"trim",
"(",
")",
"// all keywords must have an expression, except `#else/#endif`",
"if",
"(",
"!",
"expr",
"&&",
"key",
"!==",
"'else'",
"&&",
"key",
"!==",
"'endif'",
")",
"{",
"emitError",
"(",
"'Expected expression for #'",
"+",
"key",
"+",
"' in @'",
")",
"return",
"false",
"}",
"}",
"return",
"expr",
"}"
] |
Removes any one-line comment and checks if expression is present
|
[
"Removes",
"any",
"one",
"-",
"line",
"comment",
"and",
"checks",
"if",
"expression",
"is",
"present"
] |
5f31820d702a329e8aa25f0f3983f13097610250
|
https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/lib/ccparser.js#L72-L84
|
36,328 |
aMarCruz/jspreproc
|
lib/ccparser.js
|
checkInBlock
|
function checkInBlock(mask) {
var block = cc.block[last]
if (block && block === (block & mask))
return true
emitError('Unexpected #' + key + ' in @')
return false
}
|
javascript
|
function checkInBlock(mask) {
var block = cc.block[last]
if (block && block === (block & mask))
return true
emitError('Unexpected #' + key + ' in @')
return false
}
|
[
"function",
"checkInBlock",
"(",
"mask",
")",
"{",
"var",
"block",
"=",
"cc",
".",
"block",
"[",
"last",
"]",
"if",
"(",
"block",
"&&",
"block",
"===",
"(",
"block",
"&",
"mask",
")",
")",
"return",
"true",
"emitError",
"(",
"'Unexpected #'",
"+",
"key",
"+",
"' in @'",
")",
"return",
"false",
"}"
] |
Inner helper - throws if the current block is not of the expected type
|
[
"Inner",
"helper",
"-",
"throws",
"if",
"the",
"current",
"block",
"is",
"not",
"of",
"the",
"expected",
"type"
] |
5f31820d702a329e8aa25f0f3983f13097610250
|
https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/lib/ccparser.js#L170-L176
|
36,329 |
ascartabelli/lamb
|
src/privates/_repeat.js
|
_repeat
|
function _repeat (source, times) {
var result = "";
for (var i = 0; i < times; i++) {
result += source;
}
return result;
}
|
javascript
|
function _repeat (source, times) {
var result = "";
for (var i = 0; i < times; i++) {
result += source;
}
return result;
}
|
[
"function",
"_repeat",
"(",
"source",
",",
"times",
")",
"{",
"var",
"result",
"=",
"\"\"",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"times",
";",
"i",
"++",
")",
"{",
"result",
"+=",
"source",
";",
"}",
"return",
"result",
";",
"}"
] |
A null-safe function to repeat the source string the desired amount of times.
@private
@param {String} source
@param {Number} times
@returns {String}
|
[
"A",
"null",
"-",
"safe",
"function",
"to",
"repeat",
"the",
"source",
"string",
"the",
"desired",
"amount",
"of",
"times",
"."
] |
d36e45945c4789e4f1a2d8805936514b53f32362
|
https://github.com/ascartabelli/lamb/blob/d36e45945c4789e4f1a2d8805936514b53f32362/src/privates/_repeat.js#L8-L16
|
36,330 |
buttercup/credentials
|
source/Credentials.js
|
unsignEncryptedContent
|
function unsignEncryptedContent(content) {
const newIndex = content.indexOf(SIGNING_KEY);
const oldIndex = content.indexOf(SIGNING_KEY_OLD);
if (newIndex === -1 && oldIndex === -1) {
throw new Error("Invalid credentials content (unknown signature)");
}
return newIndex >= 0
? content.substr(SIGNING_KEY.length)
: content.substr(SIGNING_KEY_OLD.length);
}
|
javascript
|
function unsignEncryptedContent(content) {
const newIndex = content.indexOf(SIGNING_KEY);
const oldIndex = content.indexOf(SIGNING_KEY_OLD);
if (newIndex === -1 && oldIndex === -1) {
throw new Error("Invalid credentials content (unknown signature)");
}
return newIndex >= 0
? content.substr(SIGNING_KEY.length)
: content.substr(SIGNING_KEY_OLD.length);
}
|
[
"function",
"unsignEncryptedContent",
"(",
"content",
")",
"{",
"const",
"newIndex",
"=",
"content",
".",
"indexOf",
"(",
"SIGNING_KEY",
")",
";",
"const",
"oldIndex",
"=",
"content",
".",
"indexOf",
"(",
"SIGNING_KEY_OLD",
")",
";",
"if",
"(",
"newIndex",
"===",
"-",
"1",
"&&",
"oldIndex",
"===",
"-",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Invalid credentials content (unknown signature)\"",
")",
";",
"}",
"return",
"newIndex",
">=",
"0",
"?",
"content",
".",
"substr",
"(",
"SIGNING_KEY",
".",
"length",
")",
":",
"content",
".",
"substr",
"(",
"SIGNING_KEY_OLD",
".",
"length",
")",
";",
"}"
] |
Remove the signature from encrypted content
@private
@param {String} content The encrypted text
@returns {String} The unsigned encrypted key
@throws {Error} Throws if no SIGNING_KEY is detected
@see SIGNING_KEY
|
[
"Remove",
"the",
"signature",
"from",
"encrypted",
"content"
] |
4296c9b36a313fa42e72d80cf8565148a5e26b47
|
https://github.com/buttercup/credentials/blob/4296c9b36a313fa42e72d80cf8565148a5e26b47/source/Credentials.js#L45-L54
|
36,331 |
Inspired-by-Boredom/generator-vintage-frontend
|
generators/app/templates/gulp/tasks/styles.js
|
compileCss
|
function compileCss(src, dest) {
gulp
.src(src)
.pipe(plumber(config.plumberOptions))
.pipe(gulpif(!config.production, sourcemaps.init()))
.pipe(sass({
outputStyle: config.production ? 'compressed' : 'expanded',
precision: 5
}))
.pipe(postcss(processors))
.pipe(gulpif(config.production, rename({
suffix: '.min',
extname: '.css'
})))
.pipe(gulpif(!config.production, sourcemaps.write()))
.pipe(gulp.dest(dest));
}
|
javascript
|
function compileCss(src, dest) {
gulp
.src(src)
.pipe(plumber(config.plumberOptions))
.pipe(gulpif(!config.production, sourcemaps.init()))
.pipe(sass({
outputStyle: config.production ? 'compressed' : 'expanded',
precision: 5
}))
.pipe(postcss(processors))
.pipe(gulpif(config.production, rename({
suffix: '.min',
extname: '.css'
})))
.pipe(gulpif(!config.production, sourcemaps.write()))
.pipe(gulp.dest(dest));
}
|
[
"function",
"compileCss",
"(",
"src",
",",
"dest",
")",
"{",
"gulp",
".",
"src",
"(",
"src",
")",
".",
"pipe",
"(",
"plumber",
"(",
"config",
".",
"plumberOptions",
")",
")",
".",
"pipe",
"(",
"gulpif",
"(",
"!",
"config",
".",
"production",
",",
"sourcemaps",
".",
"init",
"(",
")",
")",
")",
".",
"pipe",
"(",
"sass",
"(",
"{",
"outputStyle",
":",
"config",
".",
"production",
"?",
"'compressed'",
":",
"'expanded'",
",",
"precision",
":",
"5",
"}",
")",
")",
".",
"pipe",
"(",
"postcss",
"(",
"processors",
")",
")",
".",
"pipe",
"(",
"gulpif",
"(",
"config",
".",
"production",
",",
"rename",
"(",
"{",
"suffix",
":",
"'.min'",
",",
"extname",
":",
"'.css'",
"}",
")",
")",
")",
".",
"pipe",
"(",
"gulpif",
"(",
"!",
"config",
".",
"production",
",",
"sourcemaps",
".",
"write",
"(",
")",
")",
")",
".",
"pipe",
"(",
"gulp",
".",
"dest",
"(",
"dest",
")",
")",
";",
"}"
] |
Default CSS compilation function.
@param {String} src
@param {String} dest
|
[
"Default",
"CSS",
"compilation",
"function",
"."
] |
316ebc981961a39d3c47ba830f377350d529452b
|
https://github.com/Inspired-by-Boredom/generator-vintage-frontend/blob/316ebc981961a39d3c47ba830f377350d529452b/generators/app/templates/gulp/tasks/styles.js#L51-L67
|
36,332 |
jorisvervuurt/JVSDisplayOTron
|
examples/dothat/bar_graph.js
|
setEnabledStateOfLed
|
function setEnabledStateOfLed(callback) {
var index = 0;
var setEnabledStateOfLedInterval = setInterval(function() {
if (index <= 5) {
dothat.barGraph.setEnabledStateOfLed(index, false);
index++;
} else {
clearInterval(setEnabledStateOfLedInterval);
if (callback) {
callback();
}
}
}, 500);
}
|
javascript
|
function setEnabledStateOfLed(callback) {
var index = 0;
var setEnabledStateOfLedInterval = setInterval(function() {
if (index <= 5) {
dothat.barGraph.setEnabledStateOfLed(index, false);
index++;
} else {
clearInterval(setEnabledStateOfLedInterval);
if (callback) {
callback();
}
}
}, 500);
}
|
[
"function",
"setEnabledStateOfLed",
"(",
"callback",
")",
"{",
"var",
"index",
"=",
"0",
";",
"var",
"setEnabledStateOfLedInterval",
"=",
"setInterval",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"index",
"<=",
"5",
")",
"{",
"dothat",
".",
"barGraph",
".",
"setEnabledStateOfLed",
"(",
"index",
",",
"false",
")",
";",
"index",
"++",
";",
"}",
"else",
"{",
"clearInterval",
"(",
"setEnabledStateOfLedInterval",
")",
";",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
")",
";",
"}",
"}",
"}",
",",
"500",
")",
";",
"}"
] |
Sets the enabled state of each individual LED in the bar graph.
@param {Function} callback A function to call when the operation has finished.
|
[
"Sets",
"the",
"enabled",
"state",
"of",
"each",
"individual",
"LED",
"in",
"the",
"bar",
"graph",
"."
] |
c8f9bfdbf4e2658bb12fc83bbf49853c938e7dcc
|
https://github.com/jorisvervuurt/JVSDisplayOTron/blob/c8f9bfdbf4e2658bb12fc83bbf49853c938e7dcc/examples/dothat/bar_graph.js#L33-L49
|
36,333 |
ascartabelli/lamb
|
src/privates/_setIn.js
|
_setIn
|
function _setIn (source, key, value) {
var result = {};
for (var prop in source) {
result[prop] = source[prop];
}
result[key] = value;
return result;
}
|
javascript
|
function _setIn (source, key, value) {
var result = {};
for (var prop in source) {
result[prop] = source[prop];
}
result[key] = value;
return result;
}
|
[
"function",
"_setIn",
"(",
"source",
",",
"key",
",",
"value",
")",
"{",
"var",
"result",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"prop",
"in",
"source",
")",
"{",
"result",
"[",
"prop",
"]",
"=",
"source",
"[",
"prop",
"]",
";",
"}",
"result",
"[",
"key",
"]",
"=",
"value",
";",
"return",
"result",
";",
"}"
] |
Sets, or creates, a property in a copy of the provided object to the desired value.
@private
@param {Object} source
@param {String} key
@param {*} value
@returns {Object}
|
[
"Sets",
"or",
"creates",
"a",
"property",
"in",
"a",
"copy",
"of",
"the",
"provided",
"object",
"to",
"the",
"desired",
"value",
"."
] |
d36e45945c4789e4f1a2d8805936514b53f32362
|
https://github.com/ascartabelli/lamb/blob/d36e45945c4789e4f1a2d8805936514b53f32362/src/privates/_setIn.js#L9-L19
|
36,334 |
FINRAOS/MSL
|
msl-server-node/mslMiddleware.js
|
getInterceptedXHR
|
function getInterceptedXHR(req) {
var requestPath = req.requestPath;
var interceptedXHRs = interceptXHRMap[requestPath];
var interceptedXHRsObj = {};
var counter = 1;
if (interceptedXHRs != undefined) {
for (var i = 0; i < interceptedXHRs.length; i++) {
interceptedXHRsObj["xhr_" + counter] = interceptedXHRs[i];
counter++;
}
}
return interceptedXHRsObj;
}
|
javascript
|
function getInterceptedXHR(req) {
var requestPath = req.requestPath;
var interceptedXHRs = interceptXHRMap[requestPath];
var interceptedXHRsObj = {};
var counter = 1;
if (interceptedXHRs != undefined) {
for (var i = 0; i < interceptedXHRs.length; i++) {
interceptedXHRsObj["xhr_" + counter] = interceptedXHRs[i];
counter++;
}
}
return interceptedXHRsObj;
}
|
[
"function",
"getInterceptedXHR",
"(",
"req",
")",
"{",
"var",
"requestPath",
"=",
"req",
".",
"requestPath",
";",
"var",
"interceptedXHRs",
"=",
"interceptXHRMap",
"[",
"requestPath",
"]",
";",
"var",
"interceptedXHRsObj",
"=",
"{",
"}",
";",
"var",
"counter",
"=",
"1",
";",
"if",
"(",
"interceptedXHRs",
"!=",
"undefined",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"interceptedXHRs",
".",
"length",
";",
"i",
"++",
")",
"{",
"interceptedXHRsObj",
"[",
"\"xhr_\"",
"+",
"counter",
"]",
"=",
"interceptedXHRs",
"[",
"i",
"]",
";",
"counter",
"++",
";",
"}",
"}",
"return",
"interceptedXHRsObj",
";",
"}"
] |
Returns the intercepted XHRs
@param req => XHR containing request path to look up (request query string contains request path)
@return returns object containing list of XHRs with key xhr_#
|
[
"Returns",
"the",
"intercepted",
"XHRs"
] |
c8e2d79749551c551fc42b8ed80d3321141df845
|
https://github.com/FINRAOS/MSL/blob/c8e2d79749551c551fc42b8ed80d3321141df845/msl-server-node/mslMiddleware.js#L375-L389
|
36,335 |
FINRAOS/MSL
|
msl-server-node/mslMiddleware.js
|
isFakeRespond
|
function isFakeRespond(req) {
var temp = req.url.toString();
var uniqueID = md5(JSON.stringify(req.body));
if (temp.indexOf("?") >= 0)
req.url = reparsePath(temp);
if (req.method === 'POST' && ((req.url in mockReqRespMap) && (mockReqRespMap[req.url] !== undefined)) &&
((!((req.url + uniqueID) in mockReqRespMap)) && (mockReqRespMap[req.url + uniqueID] === undefined))) {
mockReqRespMap[req.url + uniqueID] = mockReqRespMap[req.url];
delete mockReqRespMap[req.url];
console.log('This is POST call, but we are mocking it as a GET method, please use setMockPOSTRespond function to mock the data!!');
}
if (((req.url in mockReqRespMap) && (mockReqRespMap[req.url] !== undefined)) ||
((req._parsedUrl.pathname in mockReqRespMap) && (mockReqRespMap[req._parsedUrl.pathname] !== undefined)) ||
(((req.url + uniqueID) in mockReqRespMap) && (mockReqRespMap[req.url + uniqueID] !== undefined))) {
return true;
} else {
return false;
}
}
|
javascript
|
function isFakeRespond(req) {
var temp = req.url.toString();
var uniqueID = md5(JSON.stringify(req.body));
if (temp.indexOf("?") >= 0)
req.url = reparsePath(temp);
if (req.method === 'POST' && ((req.url in mockReqRespMap) && (mockReqRespMap[req.url] !== undefined)) &&
((!((req.url + uniqueID) in mockReqRespMap)) && (mockReqRespMap[req.url + uniqueID] === undefined))) {
mockReqRespMap[req.url + uniqueID] = mockReqRespMap[req.url];
delete mockReqRespMap[req.url];
console.log('This is POST call, but we are mocking it as a GET method, please use setMockPOSTRespond function to mock the data!!');
}
if (((req.url in mockReqRespMap) && (mockReqRespMap[req.url] !== undefined)) ||
((req._parsedUrl.pathname in mockReqRespMap) && (mockReqRespMap[req._parsedUrl.pathname] !== undefined)) ||
(((req.url + uniqueID) in mockReqRespMap) && (mockReqRespMap[req.url + uniqueID] !== undefined))) {
return true;
} else {
return false;
}
}
|
[
"function",
"isFakeRespond",
"(",
"req",
")",
"{",
"var",
"temp",
"=",
"req",
".",
"url",
".",
"toString",
"(",
")",
";",
"var",
"uniqueID",
"=",
"md5",
"(",
"JSON",
".",
"stringify",
"(",
"req",
".",
"body",
")",
")",
";",
"if",
"(",
"temp",
".",
"indexOf",
"(",
"\"?\"",
")",
">=",
"0",
")",
"req",
".",
"url",
"=",
"reparsePath",
"(",
"temp",
")",
";",
"if",
"(",
"req",
".",
"method",
"===",
"'POST'",
"&&",
"(",
"(",
"req",
".",
"url",
"in",
"mockReqRespMap",
")",
"&&",
"(",
"mockReqRespMap",
"[",
"req",
".",
"url",
"]",
"!==",
"undefined",
")",
")",
"&&",
"(",
"(",
"!",
"(",
"(",
"req",
".",
"url",
"+",
"uniqueID",
")",
"in",
"mockReqRespMap",
")",
")",
"&&",
"(",
"mockReqRespMap",
"[",
"req",
".",
"url",
"+",
"uniqueID",
"]",
"===",
"undefined",
")",
")",
")",
"{",
"mockReqRespMap",
"[",
"req",
".",
"url",
"+",
"uniqueID",
"]",
"=",
"mockReqRespMap",
"[",
"req",
".",
"url",
"]",
";",
"delete",
"mockReqRespMap",
"[",
"req",
".",
"url",
"]",
";",
"console",
".",
"log",
"(",
"'This is POST call, but we are mocking it as a GET method, please use setMockPOSTRespond function to mock the data!!'",
")",
";",
"}",
"if",
"(",
"(",
"(",
"req",
".",
"url",
"in",
"mockReqRespMap",
")",
"&&",
"(",
"mockReqRespMap",
"[",
"req",
".",
"url",
"]",
"!==",
"undefined",
")",
")",
"||",
"(",
"(",
"req",
".",
"_parsedUrl",
".",
"pathname",
"in",
"mockReqRespMap",
")",
"&&",
"(",
"mockReqRespMap",
"[",
"req",
".",
"_parsedUrl",
".",
"pathname",
"]",
"!==",
"undefined",
")",
")",
"||",
"(",
"(",
"(",
"req",
".",
"url",
"+",
"uniqueID",
")",
"in",
"mockReqRespMap",
")",
"&&",
"(",
"mockReqRespMap",
"[",
"req",
".",
"url",
"+",
"uniqueID",
"]",
"!==",
"undefined",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] |
Determines whether the request made by the path requires mock response by
checking mockReqRespMap.
@param req => XHR
@return true/false
|
[
"Determines",
"whether",
"the",
"request",
"made",
"by",
"the",
"path",
"requires",
"mock",
"response",
"by",
"checking",
"mockReqRespMap",
"."
] |
c8e2d79749551c551fc42b8ed80d3321141df845
|
https://github.com/FINRAOS/MSL/blob/c8e2d79749551c551fc42b8ed80d3321141df845/msl-server-node/mslMiddleware.js#L398-L416
|
36,336 |
FINRAOS/MSL
|
msl-server-node/mslMiddleware.js
|
isInterceptXHR
|
function isInterceptXHR(req) {
if (((req.url in interceptXHRMap) && (interceptXHRMap[req.url] !== undefined)) ||
((req._parsedUrl.pathname in interceptXHRMap) && (interceptXHRMap[req._parsedUrl.pathname] !== undefined))) {
return true;
} else {
return false;
}
}
|
javascript
|
function isInterceptXHR(req) {
if (((req.url in interceptXHRMap) && (interceptXHRMap[req.url] !== undefined)) ||
((req._parsedUrl.pathname in interceptXHRMap) && (interceptXHRMap[req._parsedUrl.pathname] !== undefined))) {
return true;
} else {
return false;
}
}
|
[
"function",
"isInterceptXHR",
"(",
"req",
")",
"{",
"if",
"(",
"(",
"(",
"req",
".",
"url",
"in",
"interceptXHRMap",
")",
"&&",
"(",
"interceptXHRMap",
"[",
"req",
".",
"url",
"]",
"!==",
"undefined",
")",
")",
"||",
"(",
"(",
"req",
".",
"_parsedUrl",
".",
"pathname",
"in",
"interceptXHRMap",
")",
"&&",
"(",
"interceptXHRMap",
"[",
"req",
".",
"_parsedUrl",
".",
"pathname",
"]",
"!==",
"undefined",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] |
Determines whether the request made by the path requires interception.
@param req => XHR
@return true/false
|
[
"Determines",
"whether",
"the",
"request",
"made",
"by",
"the",
"path",
"requires",
"interception",
"."
] |
c8e2d79749551c551fc42b8ed80d3321141df845
|
https://github.com/FINRAOS/MSL/blob/c8e2d79749551c551fc42b8ed80d3321141df845/msl-server-node/mslMiddleware.js#L424-L431
|
36,337 |
FINRAOS/MSL
|
msl-server-node/mslMiddleware.js
|
reparsePath
|
function reparsePath(oldpath) {
if (oldpath.indexOf("?") >= 0) {
var vars = oldpath.split("?")[1].split("&");
var result = oldpath.split("?")[0] + '?';
var firstFlag = 0;
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (ignoredParams.search(pair[0]) < 0) {
if (firstFlag === 0) {
result = result + pair[0] + '=' + pair[1];
firstFlag = 1;
}
else {
result = result + '&' + pair[0] + '=' + pair[1];
}
}
}
return result;
}
else {
return oldpath;
}
}
|
javascript
|
function reparsePath(oldpath) {
if (oldpath.indexOf("?") >= 0) {
var vars = oldpath.split("?")[1].split("&");
var result = oldpath.split("?")[0] + '?';
var firstFlag = 0;
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (ignoredParams.search(pair[0]) < 0) {
if (firstFlag === 0) {
result = result + pair[0] + '=' + pair[1];
firstFlag = 1;
}
else {
result = result + '&' + pair[0] + '=' + pair[1];
}
}
}
return result;
}
else {
return oldpath;
}
}
|
[
"function",
"reparsePath",
"(",
"oldpath",
")",
"{",
"if",
"(",
"oldpath",
".",
"indexOf",
"(",
"\"?\"",
")",
">=",
"0",
")",
"{",
"var",
"vars",
"=",
"oldpath",
".",
"split",
"(",
"\"?\"",
")",
"[",
"1",
"]",
".",
"split",
"(",
"\"&\"",
")",
";",
"var",
"result",
"=",
"oldpath",
".",
"split",
"(",
"\"?\"",
")",
"[",
"0",
"]",
"+",
"'?'",
";",
"var",
"firstFlag",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"vars",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"pair",
"=",
"vars",
"[",
"i",
"]",
".",
"split",
"(",
"\"=\"",
")",
";",
"if",
"(",
"ignoredParams",
".",
"search",
"(",
"pair",
"[",
"0",
"]",
")",
"<",
"0",
")",
"{",
"if",
"(",
"firstFlag",
"===",
"0",
")",
"{",
"result",
"=",
"result",
"+",
"pair",
"[",
"0",
"]",
"+",
"'='",
"+",
"pair",
"[",
"1",
"]",
";",
"firstFlag",
"=",
"1",
";",
"}",
"else",
"{",
"result",
"=",
"result",
"+",
"'&'",
"+",
"pair",
"[",
"0",
"]",
"+",
"'='",
"+",
"pair",
"[",
"1",
"]",
";",
"}",
"}",
"}",
"return",
"result",
";",
"}",
"else",
"{",
"return",
"oldpath",
";",
"}",
"}"
] |
Supporting function to parse the the URL to ignore the parameters that user don't need. Not exposed to the client.
|
[
"Supporting",
"function",
"to",
"parse",
"the",
"the",
"URL",
"to",
"ignore",
"the",
"parameters",
"that",
"user",
"don",
"t",
"need",
".",
"Not",
"exposed",
"to",
"the",
"client",
"."
] |
c8e2d79749551c551fc42b8ed80d3321141df845
|
https://github.com/FINRAOS/MSL/blob/c8e2d79749551c551fc42b8ed80d3321141df845/msl-server-node/mslMiddleware.js#L468-L490
|
36,338 |
datanews/tables
|
lib/db.js
|
modelMethod
|
function modelMethod(model, method, data, done) {
model[method](data).then(function(results) {
done(null, results);
})
.catch(function(error) {
// Try again on timeout
if (error.message == "connect ETIMEDOUT") {
modelMethod(model, method, data, done);
return;
}
done(error);
});
}
|
javascript
|
function modelMethod(model, method, data, done) {
model[method](data).then(function(results) {
done(null, results);
})
.catch(function(error) {
// Try again on timeout
if (error.message == "connect ETIMEDOUT") {
modelMethod(model, method, data, done);
return;
}
done(error);
});
}
|
[
"function",
"modelMethod",
"(",
"model",
",",
"method",
",",
"data",
",",
"done",
")",
"{",
"model",
"[",
"method",
"]",
"(",
"data",
")",
".",
"then",
"(",
"function",
"(",
"results",
")",
"{",
"done",
"(",
"null",
",",
"results",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"error",
")",
"{",
"// Try again on timeout",
"if",
"(",
"error",
".",
"message",
"==",
"\"connect ETIMEDOUT\"",
")",
"{",
"modelMethod",
"(",
"model",
",",
"method",
",",
"data",
",",
"done",
")",
";",
"return",
";",
"}",
"done",
"(",
"error",
")",
";",
"}",
")",
";",
"}"
] |
Queue-ify db request
|
[
"Queue",
"-",
"ify",
"db",
"request"
] |
4b33aa7a944a93260c49baecbb90345211cac789
|
https://github.com/datanews/tables/blob/4b33aa7a944a93260c49baecbb90345211cac789/lib/db.js#L15-L27
|
36,339 |
datanews/tables
|
lib/db.js
|
runQuery
|
function runQuery(connection, query, options, done) {
options = _.isObject(options) ? options :
connection.QueryTypes[options] ? { type: connection.QueryTypes[options] } : {};
connection.query(query, options)
.then(function(results) {
done(null, results);
})
.catch(function(error) {
if (error) {
output.error("Query error. SQL has been written to .tables.debug. Use a smaller batchSize to more easily find the issue.");
output.error(error);
fs.writeFileSync(".tables.debug", query);
}
done(error);
});
}
|
javascript
|
function runQuery(connection, query, options, done) {
options = _.isObject(options) ? options :
connection.QueryTypes[options] ? { type: connection.QueryTypes[options] } : {};
connection.query(query, options)
.then(function(results) {
done(null, results);
})
.catch(function(error) {
if (error) {
output.error("Query error. SQL has been written to .tables.debug. Use a smaller batchSize to more easily find the issue.");
output.error(error);
fs.writeFileSync(".tables.debug", query);
}
done(error);
});
}
|
[
"function",
"runQuery",
"(",
"connection",
",",
"query",
",",
"options",
",",
"done",
")",
"{",
"options",
"=",
"_",
".",
"isObject",
"(",
"options",
")",
"?",
"options",
":",
"connection",
".",
"QueryTypes",
"[",
"options",
"]",
"?",
"{",
"type",
":",
"connection",
".",
"QueryTypes",
"[",
"options",
"]",
"}",
":",
"{",
"}",
";",
"connection",
".",
"query",
"(",
"query",
",",
"options",
")",
".",
"then",
"(",
"function",
"(",
"results",
")",
"{",
"done",
"(",
"null",
",",
"results",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
")",
"{",
"output",
".",
"error",
"(",
"\"Query error. SQL has been written to .tables.debug. Use a smaller batchSize to more easily find the issue.\"",
")",
";",
"output",
".",
"error",
"(",
"error",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"\".tables.debug\"",
",",
"query",
")",
";",
"}",
"done",
"(",
"error",
")",
";",
"}",
")",
";",
"}"
] |
Queue-ify db query
|
[
"Queue",
"-",
"ify",
"db",
"query"
] |
4b33aa7a944a93260c49baecbb90345211cac789
|
https://github.com/datanews/tables/blob/4b33aa7a944a93260c49baecbb90345211cac789/lib/db.js#L30-L47
|
36,340 |
datanews/tables
|
lib/db.js
|
mysqlBulkUpsert
|
function mysqlBulkUpsert(model, data) {
var mysql = require("mysql");
var queries = ["SET AUTOCOMMIT = 0"];
// Transform data
_.each(data, function(d) {
var query = "REPLACE INTO " + model.tableName + " ([[COLUMNS]]) VALUES (?)";
query = query.replace("[[COLUMNS]]", _.keys(d).join(", "));
query = mysql.format(query, [ _.values(d) ]);
queries.push(query);
});
// Create final output and format
queries.push("COMMIT");
queries.push("SET AUTOCOMMIT = 1");
return queries.join("; ");
}
|
javascript
|
function mysqlBulkUpsert(model, data) {
var mysql = require("mysql");
var queries = ["SET AUTOCOMMIT = 0"];
// Transform data
_.each(data, function(d) {
var query = "REPLACE INTO " + model.tableName + " ([[COLUMNS]]) VALUES (?)";
query = query.replace("[[COLUMNS]]", _.keys(d).join(", "));
query = mysql.format(query, [ _.values(d) ]);
queries.push(query);
});
// Create final output and format
queries.push("COMMIT");
queries.push("SET AUTOCOMMIT = 1");
return queries.join("; ");
}
|
[
"function",
"mysqlBulkUpsert",
"(",
"model",
",",
"data",
")",
"{",
"var",
"mysql",
"=",
"require",
"(",
"\"mysql\"",
")",
";",
"var",
"queries",
"=",
"[",
"\"SET AUTOCOMMIT = 0\"",
"]",
";",
"// Transform data",
"_",
".",
"each",
"(",
"data",
",",
"function",
"(",
"d",
")",
"{",
"var",
"query",
"=",
"\"REPLACE INTO \"",
"+",
"model",
".",
"tableName",
"+",
"\" ([[COLUMNS]]) VALUES (?)\"",
";",
"query",
"=",
"query",
".",
"replace",
"(",
"\"[[COLUMNS]]\"",
",",
"_",
".",
"keys",
"(",
"d",
")",
".",
"join",
"(",
"\", \"",
")",
")",
";",
"query",
"=",
"mysql",
".",
"format",
"(",
"query",
",",
"[",
"_",
".",
"values",
"(",
"d",
")",
"]",
")",
";",
"queries",
".",
"push",
"(",
"query",
")",
";",
"}",
")",
";",
"// Create final output and format",
"queries",
".",
"push",
"(",
"\"COMMIT\"",
")",
";",
"queries",
".",
"push",
"(",
"\"SET AUTOCOMMIT = 1\"",
")",
";",
"return",
"queries",
".",
"join",
"(",
"\"; \"",
")",
";",
"}"
] |
Mysql query format bulk upsert
|
[
"Mysql",
"query",
"format",
"bulk",
"upsert"
] |
4b33aa7a944a93260c49baecbb90345211cac789
|
https://github.com/datanews/tables/blob/4b33aa7a944a93260c49baecbb90345211cac789/lib/db.js#L86-L102
|
36,341 |
datanews/tables
|
lib/db.js
|
sqliteBulkUpsert
|
function sqliteBulkUpsert(model, data) {
var queries = ["BEGIN"];
var values = [];
// Transform data
_.each(data, function(d) {
var query = "INSERT OR REPLACE INTO " + model.tableName + " ([[COLUMNS]]) VALUES ([[VALUES]])";
query = query.replace("[[COLUMNS]]", _.keys(d).join(", "));
// Put in ?'s
query = query.replace("[[VALUES]]", _.map(d, function(v) {
return "?";
}).join(", "));
// Get values
values = values.concat(_.values(d));
queries.push(query);
});
// Create final output and format
queries.push("COMMIT");
return {
query: queries.join("; "),
replacements: values
};
}
|
javascript
|
function sqliteBulkUpsert(model, data) {
var queries = ["BEGIN"];
var values = [];
// Transform data
_.each(data, function(d) {
var query = "INSERT OR REPLACE INTO " + model.tableName + " ([[COLUMNS]]) VALUES ([[VALUES]])";
query = query.replace("[[COLUMNS]]", _.keys(d).join(", "));
// Put in ?'s
query = query.replace("[[VALUES]]", _.map(d, function(v) {
return "?";
}).join(", "));
// Get values
values = values.concat(_.values(d));
queries.push(query);
});
// Create final output and format
queries.push("COMMIT");
return {
query: queries.join("; "),
replacements: values
};
}
|
[
"function",
"sqliteBulkUpsert",
"(",
"model",
",",
"data",
")",
"{",
"var",
"queries",
"=",
"[",
"\"BEGIN\"",
"]",
";",
"var",
"values",
"=",
"[",
"]",
";",
"// Transform data",
"_",
".",
"each",
"(",
"data",
",",
"function",
"(",
"d",
")",
"{",
"var",
"query",
"=",
"\"INSERT OR REPLACE INTO \"",
"+",
"model",
".",
"tableName",
"+",
"\" ([[COLUMNS]]) VALUES ([[VALUES]])\"",
";",
"query",
"=",
"query",
".",
"replace",
"(",
"\"[[COLUMNS]]\"",
",",
"_",
".",
"keys",
"(",
"d",
")",
".",
"join",
"(",
"\", \"",
")",
")",
";",
"// Put in ?'s",
"query",
"=",
"query",
".",
"replace",
"(",
"\"[[VALUES]]\"",
",",
"_",
".",
"map",
"(",
"d",
",",
"function",
"(",
"v",
")",
"{",
"return",
"\"?\"",
";",
"}",
")",
".",
"join",
"(",
"\", \"",
")",
")",
";",
"// Get values",
"values",
"=",
"values",
".",
"concat",
"(",
"_",
".",
"values",
"(",
"d",
")",
")",
";",
"queries",
".",
"push",
"(",
"query",
")",
";",
"}",
")",
";",
"// Create final output and format",
"queries",
".",
"push",
"(",
"\"COMMIT\"",
")",
";",
"return",
"{",
"query",
":",
"queries",
".",
"join",
"(",
"\"; \"",
")",
",",
"replacements",
":",
"values",
"}",
";",
"}"
] |
SQLite query format bulk upsert. SQLite uses a bind function that automatically replaces ?
|
[
"SQLite",
"query",
"format",
"bulk",
"upsert",
".",
"SQLite",
"uses",
"a",
"bind",
"function",
"that",
"automatically",
"replaces",
"?"
] |
4b33aa7a944a93260c49baecbb90345211cac789
|
https://github.com/datanews/tables/blob/4b33aa7a944a93260c49baecbb90345211cac789/lib/db.js#L106-L131
|
36,342 |
datanews/tables
|
lib/db.js
|
pgsqlBulkUpsert
|
function pgsqlBulkUpsert(model, data) {
var queries = [];
// Transform data
_.each(data, function(d) {
// TODO: Postgres does not have easy UPSERT syntax, the ON CONFLICT UPDATE requires specific columns
var query = "INSERT INTO " + model.tableName + " ([[COLUMNS]]) VALUES ([[VALUES]])";
query = query.replace("[[COLUMNS]]", _.keys(d).join(", "));
query = query.replace("[[VALUES]]", _.map(d, function(v) {
return sequelizeSS.escape(v, undefined, "postgres");
}).join(", "));
queries.push(query);
});
// Create final output and format
return queries.join("; ");
}
|
javascript
|
function pgsqlBulkUpsert(model, data) {
var queries = [];
// Transform data
_.each(data, function(d) {
// TODO: Postgres does not have easy UPSERT syntax, the ON CONFLICT UPDATE requires specific columns
var query = "INSERT INTO " + model.tableName + " ([[COLUMNS]]) VALUES ([[VALUES]])";
query = query.replace("[[COLUMNS]]", _.keys(d).join(", "));
query = query.replace("[[VALUES]]", _.map(d, function(v) {
return sequelizeSS.escape(v, undefined, "postgres");
}).join(", "));
queries.push(query);
});
// Create final output and format
return queries.join("; ");
}
|
[
"function",
"pgsqlBulkUpsert",
"(",
"model",
",",
"data",
")",
"{",
"var",
"queries",
"=",
"[",
"]",
";",
"// Transform data",
"_",
".",
"each",
"(",
"data",
",",
"function",
"(",
"d",
")",
"{",
"// TODO: Postgres does not have easy UPSERT syntax, the ON CONFLICT UPDATE requires specific columns",
"var",
"query",
"=",
"\"INSERT INTO \"",
"+",
"model",
".",
"tableName",
"+",
"\" ([[COLUMNS]]) VALUES ([[VALUES]])\"",
";",
"query",
"=",
"query",
".",
"replace",
"(",
"\"[[COLUMNS]]\"",
",",
"_",
".",
"keys",
"(",
"d",
")",
".",
"join",
"(",
"\", \"",
")",
")",
";",
"query",
"=",
"query",
".",
"replace",
"(",
"\"[[VALUES]]\"",
",",
"_",
".",
"map",
"(",
"d",
",",
"function",
"(",
"v",
")",
"{",
"return",
"sequelizeSS",
".",
"escape",
"(",
"v",
",",
"undefined",
",",
"\"postgres\"",
")",
";",
"}",
")",
".",
"join",
"(",
"\", \"",
")",
")",
";",
"queries",
".",
"push",
"(",
"query",
")",
";",
"}",
")",
";",
"// Create final output and format",
"return",
"queries",
".",
"join",
"(",
"\"; \"",
")",
";",
"}"
] |
PGSQL query format bulk upsert
|
[
"PGSQL",
"query",
"format",
"bulk",
"upsert"
] |
4b33aa7a944a93260c49baecbb90345211cac789
|
https://github.com/datanews/tables/blob/4b33aa7a944a93260c49baecbb90345211cac789/lib/db.js#L134-L150
|
36,343 |
datanews/tables
|
lib/db.js
|
vacuum
|
function vacuum(connection, done) {
var n = connection.connectionManager.dialectName;
var query;
// Make query based on dialiect
if (n === "mysql" || n === "mariadb" || n === "mysqli") {
query = "SELECT 1";
}
else if (n === "sqlite") {
query = "VACUUM";
}
else if (n === "pgsql" || n === "postgres") {
query = "VACUUM";
}
runQuery(connection, query, { type: connection.QueryTypes.UPSERT, raw: true }, done);
}
|
javascript
|
function vacuum(connection, done) {
var n = connection.connectionManager.dialectName;
var query;
// Make query based on dialiect
if (n === "mysql" || n === "mariadb" || n === "mysqli") {
query = "SELECT 1";
}
else if (n === "sqlite") {
query = "VACUUM";
}
else if (n === "pgsql" || n === "postgres") {
query = "VACUUM";
}
runQuery(connection, query, { type: connection.QueryTypes.UPSERT, raw: true }, done);
}
|
[
"function",
"vacuum",
"(",
"connection",
",",
"done",
")",
"{",
"var",
"n",
"=",
"connection",
".",
"connectionManager",
".",
"dialectName",
";",
"var",
"query",
";",
"// Make query based on dialiect",
"if",
"(",
"n",
"===",
"\"mysql\"",
"||",
"n",
"===",
"\"mariadb\"",
"||",
"n",
"===",
"\"mysqli\"",
")",
"{",
"query",
"=",
"\"SELECT 1\"",
";",
"}",
"else",
"if",
"(",
"n",
"===",
"\"sqlite\"",
")",
"{",
"query",
"=",
"\"VACUUM\"",
";",
"}",
"else",
"if",
"(",
"n",
"===",
"\"pgsql\"",
"||",
"n",
"===",
"\"postgres\"",
")",
"{",
"query",
"=",
"\"VACUUM\"",
";",
"}",
"runQuery",
"(",
"connection",
",",
"query",
",",
"{",
"type",
":",
"connection",
".",
"QueryTypes",
".",
"UPSERT",
",",
"raw",
":",
"true",
"}",
",",
"done",
")",
";",
"}"
] |
Run vaccume query
|
[
"Run",
"vaccume",
"query"
] |
4b33aa7a944a93260c49baecbb90345211cac789
|
https://github.com/datanews/tables/blob/4b33aa7a944a93260c49baecbb90345211cac789/lib/db.js#L153-L169
|
36,344 |
catbee/catbee
|
lib/providers/URLArgsProvider.js
|
getUriMappers
|
function getUriMappers (serviceLocator) {
var routeDefinitions;
try {
routeDefinitions = serviceLocator.resolveAll('routeDefinition');
} catch (e) {
routeDefinitions = [];
}
return routeDefinitions
.map(route => {
var mapper = routeHelper.compileRoute(route.expression);
return {
expression: mapper.expression,
map: route.map || noop,
argsMap: uri => {
var args = mapper.map(uri);
Object.assign(args, route.args);
return args;
}
};
});
}
|
javascript
|
function getUriMappers (serviceLocator) {
var routeDefinitions;
try {
routeDefinitions = serviceLocator.resolveAll('routeDefinition');
} catch (e) {
routeDefinitions = [];
}
return routeDefinitions
.map(route => {
var mapper = routeHelper.compileRoute(route.expression);
return {
expression: mapper.expression,
map: route.map || noop,
argsMap: uri => {
var args = mapper.map(uri);
Object.assign(args, route.args);
return args;
}
};
});
}
|
[
"function",
"getUriMappers",
"(",
"serviceLocator",
")",
"{",
"var",
"routeDefinitions",
";",
"try",
"{",
"routeDefinitions",
"=",
"serviceLocator",
".",
"resolveAll",
"(",
"'routeDefinition'",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"routeDefinitions",
"=",
"[",
"]",
";",
"}",
"return",
"routeDefinitions",
".",
"map",
"(",
"route",
"=>",
"{",
"var",
"mapper",
"=",
"routeHelper",
".",
"compileRoute",
"(",
"route",
".",
"expression",
")",
";",
"return",
"{",
"expression",
":",
"mapper",
".",
"expression",
",",
"map",
":",
"route",
".",
"map",
"||",
"noop",
",",
"argsMap",
":",
"uri",
"=>",
"{",
"var",
"args",
"=",
"mapper",
".",
"map",
"(",
"uri",
")",
";",
"Object",
".",
"assign",
"(",
"args",
",",
"route",
".",
"args",
")",
";",
"return",
"args",
";",
"}",
"}",
";",
"}",
")",
";",
"}"
] |
Gets list of URI mappers.
@param {ServiceLocator} serviceLocator Service locator to get route
definitions.
@returns {Array} List of URI mappers.
|
[
"Gets",
"list",
"of",
"URI",
"mappers",
"."
] |
bddc7012d973ec3e147b07cee02bf3ad52fc99cd
|
https://github.com/catbee/catbee/blob/bddc7012d973ec3e147b07cee02bf3ad52fc99cd/lib/providers/URLArgsProvider.js#L45-L68
|
36,345 |
catbee/catbee
|
lib/providers/URLArgsProvider.js
|
runPostMapping
|
function runPostMapping (args, uriMappers, location) {
uriMappers.some(mapper => {
if (mapper.expression.test(location.path)) {
args = mapper.map(args);
return true;
}
return false;
});
return args;
}
|
javascript
|
function runPostMapping (args, uriMappers, location) {
uriMappers.some(mapper => {
if (mapper.expression.test(location.path)) {
args = mapper.map(args);
return true;
}
return false;
});
return args;
}
|
[
"function",
"runPostMapping",
"(",
"args",
",",
"uriMappers",
",",
"location",
")",
"{",
"uriMappers",
".",
"some",
"(",
"mapper",
"=>",
"{",
"if",
"(",
"mapper",
".",
"expression",
".",
"test",
"(",
"location",
".",
"path",
")",
")",
"{",
"args",
"=",
"mapper",
".",
"map",
"(",
"args",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}",
")",
";",
"return",
"args",
";",
"}"
] |
Run handler after signal and args was get
@param {Object} args
@param {Array} uriMappers
@param {URI} location
@return {Object}
|
[
"Run",
"handler",
"after",
"signal",
"and",
"args",
"was",
"get"
] |
bddc7012d973ec3e147b07cee02bf3ad52fc99cd
|
https://github.com/catbee/catbee/blob/bddc7012d973ec3e147b07cee02bf3ad52fc99cd/lib/providers/URLArgsProvider.js#L97-L107
|
36,346 |
wiresjs/async-watch
|
dist/async-watch.js
|
dotNotation
|
function dotNotation(path) {
if (path instanceof Array) {
return {
path: path,
str: path.join('.')
}
}
if (typeof path !== 'string') {
return;
}
return {
path: path.split('\.'),
str: path
}
}
|
javascript
|
function dotNotation(path) {
if (path instanceof Array) {
return {
path: path,
str: path.join('.')
}
}
if (typeof path !== 'string') {
return;
}
return {
path: path.split('\.'),
str: path
}
}
|
[
"function",
"dotNotation",
"(",
"path",
")",
"{",
"if",
"(",
"path",
"instanceof",
"Array",
")",
"{",
"return",
"{",
"path",
":",
"path",
",",
"str",
":",
"path",
".",
"join",
"(",
"'.'",
")",
"}",
"}",
"if",
"(",
"typeof",
"path",
"!==",
"'string'",
")",
"{",
"return",
";",
"}",
"return",
"{",
"path",
":",
"path",
".",
"split",
"(",
"'\\.'",
")",
",",
"str",
":",
"path",
"}",
"}"
] |
dotNotation - A helper to extract dot notation
@param {type} path string or array
@return {type} Object { path : ['a','b'], str : 'a.b'}
|
[
"dotNotation",
"-",
"A",
"helper",
"to",
"extract",
"dot",
"notation"
] |
4f813c2b747a64db6ade9053637d813a75a04c03
|
https://github.com/wiresjs/async-watch/blob/4f813c2b747a64db6ade9053637d813a75a04c03/dist/async-watch.js#L116-L130
|
36,347 |
wiresjs/async-watch
|
dist/async-watch.js
|
getPropertyValue
|
function getPropertyValue(obj, path) {
if (path.length === 0 || obj === undefined) {
return undefined;
}
var notation = dotNotation(path);
if (!notation) {
return;
}
path = notation.path;
for (var i = 0; i < path.length; i++) {
obj = obj[path[i]];
if (obj === undefined) {
return undefined;
}
}
return obj;
}
|
javascript
|
function getPropertyValue(obj, path) {
if (path.length === 0 || obj === undefined) {
return undefined;
}
var notation = dotNotation(path);
if (!notation) {
return;
}
path = notation.path;
for (var i = 0; i < path.length; i++) {
obj = obj[path[i]];
if (obj === undefined) {
return undefined;
}
}
return obj;
}
|
[
"function",
"getPropertyValue",
"(",
"obj",
",",
"path",
")",
"{",
"if",
"(",
"path",
".",
"length",
"===",
"0",
"||",
"obj",
"===",
"undefined",
")",
"{",
"return",
"undefined",
";",
"}",
"var",
"notation",
"=",
"dotNotation",
"(",
"path",
")",
";",
"if",
"(",
"!",
"notation",
")",
"{",
"return",
";",
"}",
"path",
"=",
"notation",
".",
"path",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"path",
".",
"length",
";",
"i",
"++",
")",
"{",
"obj",
"=",
"obj",
"[",
"path",
"[",
"i",
"]",
"]",
";",
"if",
"(",
"obj",
"===",
"undefined",
")",
"{",
"return",
"undefined",
";",
"}",
"}",
"return",
"obj",
";",
"}"
] |
getPropertyValue - get a value from an object with dot notation
@param {type} obj Target object
@param {type} path dot notation
@return {type} Target object
|
[
"getPropertyValue",
"-",
"get",
"a",
"value",
"from",
"an",
"object",
"with",
"dot",
"notation"
] |
4f813c2b747a64db6ade9053637d813a75a04c03
|
https://github.com/wiresjs/async-watch/blob/4f813c2b747a64db6ade9053637d813a75a04c03/dist/async-watch.js#L139-L156
|
36,348 |
wiresjs/async-watch
|
dist/async-watch.js
|
setHiddenProperty
|
function setHiddenProperty(obj, key, value) {
Object.defineProperty(obj, key, {
enumerable: false,
value: value
});
return value;
}
|
javascript
|
function setHiddenProperty(obj, key, value) {
Object.defineProperty(obj, key, {
enumerable: false,
value: value
});
return value;
}
|
[
"function",
"setHiddenProperty",
"(",
"obj",
",",
"key",
",",
"value",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"obj",
",",
"key",
",",
"{",
"enumerable",
":",
"false",
",",
"value",
":",
"value",
"}",
")",
";",
"return",
"value",
";",
"}"
] |
setHiddenProperty - description
@param {type} obj target object
@param {type} key property name
@param {type} value default value
@return {type} target object
|
[
"setHiddenProperty",
"-",
"description"
] |
4f813c2b747a64db6ade9053637d813a75a04c03
|
https://github.com/wiresjs/async-watch/blob/4f813c2b747a64db6ade9053637d813a75a04c03/dist/async-watch.js#L166-L172
|
36,349 |
vectree/JS-jail
|
index.js
|
tryToCoverWindow
|
function tryToCoverWindow(code) {
if (typeof window === "object") {
var variables = Object.getOwnPropertyNames(window);
if (!window.hasOwnProperty('window')) {
variables.push('window');
}
var stubDeclarations = '';
variables.forEach(function(name) {
// If the name really can be the name of variable.
if (lodash.isString(name)) {
var stub = 'var ' + name + '; \n';
stubDeclarations = stubDeclarations + stub;
}
});
code = stubDeclarations + code;
}
return code;
}
|
javascript
|
function tryToCoverWindow(code) {
if (typeof window === "object") {
var variables = Object.getOwnPropertyNames(window);
if (!window.hasOwnProperty('window')) {
variables.push('window');
}
var stubDeclarations = '';
variables.forEach(function(name) {
// If the name really can be the name of variable.
if (lodash.isString(name)) {
var stub = 'var ' + name + '; \n';
stubDeclarations = stubDeclarations + stub;
}
});
code = stubDeclarations + code;
}
return code;
}
|
[
"function",
"tryToCoverWindow",
"(",
"code",
")",
"{",
"if",
"(",
"typeof",
"window",
"===",
"\"object\"",
")",
"{",
"var",
"variables",
"=",
"Object",
".",
"getOwnPropertyNames",
"(",
"window",
")",
";",
"if",
"(",
"!",
"window",
".",
"hasOwnProperty",
"(",
"'window'",
")",
")",
"{",
"variables",
".",
"push",
"(",
"'window'",
")",
";",
"}",
"var",
"stubDeclarations",
"=",
"''",
";",
"variables",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"// If the name really can be the name of variable.",
"if",
"(",
"lodash",
".",
"isString",
"(",
"name",
")",
")",
"{",
"var",
"stub",
"=",
"'var '",
"+",
"name",
"+",
"'; \\n'",
";",
"stubDeclarations",
"=",
"stubDeclarations",
"+",
"stub",
";",
"}",
"}",
")",
";",
"code",
"=",
"stubDeclarations",
"+",
"code",
";",
"}",
"return",
"code",
";",
"}"
] |
Makes stubs of variables for avoid the changing of outside environment which has these variables too.
TODO need to take this function into a separate module.
@private
@param {String} code The source code.
|
[
"Makes",
"stubs",
"of",
"variables",
"for",
"avoid",
"the",
"changing",
"of",
"outside",
"environment",
"which",
"has",
"these",
"variables",
"too",
"."
] |
c650fbc8dc14459d44d6a6e2592302945171b2ee
|
https://github.com/vectree/JS-jail/blob/c650fbc8dc14459d44d6a6e2592302945171b2ee/index.js#L65-L97
|
36,350 |
spreadshirt/rAppid.js-sprd
|
sprd/lib/raygun.js
|
createCORSRequest
|
function createCORSRequest (method, url) {
var xhr;
xhr = new window.XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (window.XDomainRequest) {
// XDomainRequest for IE.
if (_allowInsecureSubmissions) {
// remove 'https:' and use relative protocol
// this allows IE8 to post messages when running
// on http
url = url.slice(6);
}
xhr = new window.XDomainRequest();
xhr.open(method, url);
}
xhr.timeout = 10000;
return xhr;
}
|
javascript
|
function createCORSRequest (method, url) {
var xhr;
xhr = new window.XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (window.XDomainRequest) {
// XDomainRequest for IE.
if (_allowInsecureSubmissions) {
// remove 'https:' and use relative protocol
// this allows IE8 to post messages when running
// on http
url = url.slice(6);
}
xhr = new window.XDomainRequest();
xhr.open(method, url);
}
xhr.timeout = 10000;
return xhr;
}
|
[
"function",
"createCORSRequest",
"(",
"method",
",",
"url",
")",
"{",
"var",
"xhr",
";",
"xhr",
"=",
"new",
"window",
".",
"XMLHttpRequest",
"(",
")",
";",
"if",
"(",
"\"withCredentials\"",
"in",
"xhr",
")",
"{",
"// XHR for Chrome/Firefox/Opera/Safari.",
"xhr",
".",
"open",
"(",
"method",
",",
"url",
",",
"true",
")",
";",
"}",
"else",
"if",
"(",
"window",
".",
"XDomainRequest",
")",
"{",
"// XDomainRequest for IE.",
"if",
"(",
"_allowInsecureSubmissions",
")",
"{",
"// remove 'https:' and use relative protocol",
"// this allows IE8 to post messages when running",
"// on http",
"url",
"=",
"url",
".",
"slice",
"(",
"6",
")",
";",
"}",
"xhr",
"=",
"new",
"window",
".",
"XDomainRequest",
"(",
")",
";",
"xhr",
".",
"open",
"(",
"method",
",",
"url",
")",
";",
"}",
"xhr",
".",
"timeout",
"=",
"10000",
";",
"return",
"xhr",
";",
"}"
] |
Create the XHR object.
|
[
"Create",
"the",
"XHR",
"object",
"."
] |
b56f9f47fe01332f5bf885eaf4db59014f099019
|
https://github.com/spreadshirt/rAppid.js-sprd/blob/b56f9f47fe01332f5bf885eaf4db59014f099019/sprd/lib/raygun.js#L1968-L1993
|
36,351 |
spreadshirt/rAppid.js-sprd
|
sprd/lib/raygun.js
|
makePostCorsRequest
|
function makePostCorsRequest (url, data) {
var xhr = createCORSRequest('POST', url, data);
if (typeof _beforeXHRCallback === 'function') {
_beforeXHRCallback(xhr);
}
if ('withCredentials' in xhr) {
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 202) {
sendSavedErrors();
} else if (_enableOfflineSave && xhr.status !== 403 && xhr.status !== 400 && xhr.status !== 429) {
offlineSave(url, data);
}
};
xhr.onload = function() {
_private.log('posted to Raygun');
callAfterSend(this);
};
} else if (window.XDomainRequest) {
xhr.ontimeout = function() {
if (_enableOfflineSave) {
_private.log('Raygun: saved locally');
offlineSave(url, data);
}
};
xhr.onload = function() {
_private.log('posted to Raygun');
sendSavedErrors();
callAfterSend(this);
};
}
xhr.onerror = function() {
_private.log('failed to post to Raygun');
callAfterSend(this);
};
if (!xhr) {
_private.log('CORS not supported');
return;
}
xhr.send(data);
}
|
javascript
|
function makePostCorsRequest (url, data) {
var xhr = createCORSRequest('POST', url, data);
if (typeof _beforeXHRCallback === 'function') {
_beforeXHRCallback(xhr);
}
if ('withCredentials' in xhr) {
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 202) {
sendSavedErrors();
} else if (_enableOfflineSave && xhr.status !== 403 && xhr.status !== 400 && xhr.status !== 429) {
offlineSave(url, data);
}
};
xhr.onload = function() {
_private.log('posted to Raygun');
callAfterSend(this);
};
} else if (window.XDomainRequest) {
xhr.ontimeout = function() {
if (_enableOfflineSave) {
_private.log('Raygun: saved locally');
offlineSave(url, data);
}
};
xhr.onload = function() {
_private.log('posted to Raygun');
sendSavedErrors();
callAfterSend(this);
};
}
xhr.onerror = function() {
_private.log('failed to post to Raygun');
callAfterSend(this);
};
if (!xhr) {
_private.log('CORS not supported');
return;
}
xhr.send(data);
}
|
[
"function",
"makePostCorsRequest",
"(",
"url",
",",
"data",
")",
"{",
"var",
"xhr",
"=",
"createCORSRequest",
"(",
"'POST'",
",",
"url",
",",
"data",
")",
";",
"if",
"(",
"typeof",
"_beforeXHRCallback",
"===",
"'function'",
")",
"{",
"_beforeXHRCallback",
"(",
"xhr",
")",
";",
"}",
"if",
"(",
"'withCredentials'",
"in",
"xhr",
")",
"{",
"xhr",
".",
"onreadystatechange",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"xhr",
".",
"readyState",
"!==",
"4",
")",
"{",
"return",
";",
"}",
"if",
"(",
"xhr",
".",
"status",
"===",
"202",
")",
"{",
"sendSavedErrors",
"(",
")",
";",
"}",
"else",
"if",
"(",
"_enableOfflineSave",
"&&",
"xhr",
".",
"status",
"!==",
"403",
"&&",
"xhr",
".",
"status",
"!==",
"400",
"&&",
"xhr",
".",
"status",
"!==",
"429",
")",
"{",
"offlineSave",
"(",
"url",
",",
"data",
")",
";",
"}",
"}",
";",
"xhr",
".",
"onload",
"=",
"function",
"(",
")",
"{",
"_private",
".",
"log",
"(",
"'posted to Raygun'",
")",
";",
"callAfterSend",
"(",
"this",
")",
";",
"}",
";",
"}",
"else",
"if",
"(",
"window",
".",
"XDomainRequest",
")",
"{",
"xhr",
".",
"ontimeout",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"_enableOfflineSave",
")",
"{",
"_private",
".",
"log",
"(",
"'Raygun: saved locally'",
")",
";",
"offlineSave",
"(",
"url",
",",
"data",
")",
";",
"}",
"}",
";",
"xhr",
".",
"onload",
"=",
"function",
"(",
")",
"{",
"_private",
".",
"log",
"(",
"'posted to Raygun'",
")",
";",
"sendSavedErrors",
"(",
")",
";",
"callAfterSend",
"(",
"this",
")",
";",
"}",
";",
"}",
"xhr",
".",
"onerror",
"=",
"function",
"(",
")",
"{",
"_private",
".",
"log",
"(",
"'failed to post to Raygun'",
")",
";",
"callAfterSend",
"(",
"this",
")",
";",
"}",
";",
"if",
"(",
"!",
"xhr",
")",
"{",
"_private",
".",
"log",
"(",
"'CORS not supported'",
")",
";",
"return",
";",
"}",
"xhr",
".",
"send",
"(",
"data",
")",
";",
"}"
] |
Make the actual CORS request.
|
[
"Make",
"the",
"actual",
"CORS",
"request",
"."
] |
b56f9f47fe01332f5bf885eaf4db59014f099019
|
https://github.com/spreadshirt/rAppid.js-sprd/blob/b56f9f47fe01332f5bf885eaf4db59014f099019/sprd/lib/raygun.js#L1996-L2051
|
36,352 |
catbee/catbee
|
lib/helpers/routeHelper.js
|
createUriPathMapper
|
function createUriPathMapper (expression, parameters) {
return (uriPath, args) => {
var matches = uriPath.match(expression);
if (!matches || matches.length < 2) {
return args;
}
// start with second match because first match is always
// the whole URI path
matches = matches.splice(1);
parameters.forEach((parameter, index) => {
var value = matches[index];
try {
value = decodeURIComponent(value);
} catch (e) {
// nothing to do
}
args[parameter.name] = value;
});
};
}
|
javascript
|
function createUriPathMapper (expression, parameters) {
return (uriPath, args) => {
var matches = uriPath.match(expression);
if (!matches || matches.length < 2) {
return args;
}
// start with second match because first match is always
// the whole URI path
matches = matches.splice(1);
parameters.forEach((parameter, index) => {
var value = matches[index];
try {
value = decodeURIComponent(value);
} catch (e) {
// nothing to do
}
args[parameter.name] = value;
});
};
}
|
[
"function",
"createUriPathMapper",
"(",
"expression",
",",
"parameters",
")",
"{",
"return",
"(",
"uriPath",
",",
"args",
")",
"=>",
"{",
"var",
"matches",
"=",
"uriPath",
".",
"match",
"(",
"expression",
")",
";",
"if",
"(",
"!",
"matches",
"||",
"matches",
".",
"length",
"<",
"2",
")",
"{",
"return",
"args",
";",
"}",
"// start with second match because first match is always",
"// the whole URI path",
"matches",
"=",
"matches",
".",
"splice",
"(",
"1",
")",
";",
"parameters",
".",
"forEach",
"(",
"(",
"parameter",
",",
"index",
")",
"=>",
"{",
"var",
"value",
"=",
"matches",
"[",
"index",
"]",
";",
"try",
"{",
"value",
"=",
"decodeURIComponent",
"(",
"value",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// nothing to do",
"}",
"args",
"[",
"parameter",
".",
"name",
"]",
"=",
"value",
";",
"}",
")",
";",
"}",
";",
"}"
] |
Creates new URI path-to-state object mapper.
@param {RegExp} expression Regular expression to match URI path.
@param {Array} parameters List of parameter descriptors.
@returns {Function} URI mapper function.
|
[
"Creates",
"new",
"URI",
"path",
"-",
"to",
"-",
"state",
"object",
"mapper",
"."
] |
bddc7012d973ec3e147b07cee02bf3ad52fc99cd
|
https://github.com/catbee/catbee/blob/bddc7012d973ec3e147b07cee02bf3ad52fc99cd/lib/helpers/routeHelper.js#L59-L82
|
36,353 |
catbee/catbee
|
lib/helpers/routeHelper.js
|
createUriQueryMapper
|
function createUriQueryMapper (query) {
var parameters = extractQueryParameters(query);
return (queryValues, args) => {
queryValues = queryValues || Object.create(null);
Object.keys(queryValues)
.forEach(queryKey => {
var parameter = parameters[queryKey];
if (!parameter) {
return;
}
var value = util.isArray(queryValues[queryKey]) ?
queryValues[queryKey]
.map(parameter.map)
.filter(value => value !== null) :
parameter.map(queryValues[queryKey]);
if (value === null) {
return;
}
args[parameter.name] = value;
});
};
}
|
javascript
|
function createUriQueryMapper (query) {
var parameters = extractQueryParameters(query);
return (queryValues, args) => {
queryValues = queryValues || Object.create(null);
Object.keys(queryValues)
.forEach(queryKey => {
var parameter = parameters[queryKey];
if (!parameter) {
return;
}
var value = util.isArray(queryValues[queryKey]) ?
queryValues[queryKey]
.map(parameter.map)
.filter(value => value !== null) :
parameter.map(queryValues[queryKey]);
if (value === null) {
return;
}
args[parameter.name] = value;
});
};
}
|
[
"function",
"createUriQueryMapper",
"(",
"query",
")",
"{",
"var",
"parameters",
"=",
"extractQueryParameters",
"(",
"query",
")",
";",
"return",
"(",
"queryValues",
",",
"args",
")",
"=>",
"{",
"queryValues",
"=",
"queryValues",
"||",
"Object",
".",
"create",
"(",
"null",
")",
";",
"Object",
".",
"keys",
"(",
"queryValues",
")",
".",
"forEach",
"(",
"queryKey",
"=>",
"{",
"var",
"parameter",
"=",
"parameters",
"[",
"queryKey",
"]",
";",
"if",
"(",
"!",
"parameter",
")",
"{",
"return",
";",
"}",
"var",
"value",
"=",
"util",
".",
"isArray",
"(",
"queryValues",
"[",
"queryKey",
"]",
")",
"?",
"queryValues",
"[",
"queryKey",
"]",
".",
"map",
"(",
"parameter",
".",
"map",
")",
".",
"filter",
"(",
"value",
"=>",
"value",
"!==",
"null",
")",
":",
"parameter",
".",
"map",
"(",
"queryValues",
"[",
"queryKey",
"]",
")",
";",
"if",
"(",
"value",
"===",
"null",
")",
"{",
"return",
";",
"}",
"args",
"[",
"parameter",
".",
"name",
"]",
"=",
"value",
";",
"}",
")",
";",
"}",
";",
"}"
] |
Creates new URI query-to-args object mapper.
@param {String} query Query string from uri mapping
query parameter names.
@returns {Function} URI mapper function.
|
[
"Creates",
"new",
"URI",
"query",
"-",
"to",
"-",
"args",
"object",
"mapper",
"."
] |
bddc7012d973ec3e147b07cee02bf3ad52fc99cd
|
https://github.com/catbee/catbee/blob/bddc7012d973ec3e147b07cee02bf3ad52fc99cd/lib/helpers/routeHelper.js#L91-L117
|
36,354 |
catbee/catbee
|
lib/helpers/routeHelper.js
|
createUriQueryValueMapper
|
function createUriQueryValueMapper (expression) {
return value => {
value = value.toString();
var matches = value.match(expression);
if (!matches || matches.length === 0) {
return null;
}
// the value is the second item, the first is a whole string
var mappedValue = matches[matches.length - 1];
try {
mappedValue = decodeURIComponent(mappedValue);
} catch (e) {
// nothing to do
}
return mappedValue;
};
}
|
javascript
|
function createUriQueryValueMapper (expression) {
return value => {
value = value.toString();
var matches = value.match(expression);
if (!matches || matches.length === 0) {
return null;
}
// the value is the second item, the first is a whole string
var mappedValue = matches[matches.length - 1];
try {
mappedValue = decodeURIComponent(mappedValue);
} catch (e) {
// nothing to do
}
return mappedValue;
};
}
|
[
"function",
"createUriQueryValueMapper",
"(",
"expression",
")",
"{",
"return",
"value",
"=>",
"{",
"value",
"=",
"value",
".",
"toString",
"(",
")",
";",
"var",
"matches",
"=",
"value",
".",
"match",
"(",
"expression",
")",
";",
"if",
"(",
"!",
"matches",
"||",
"matches",
".",
"length",
"===",
"0",
")",
"{",
"return",
"null",
";",
"}",
"// the value is the second item, the first is a whole string",
"var",
"mappedValue",
"=",
"matches",
"[",
"matches",
".",
"length",
"-",
"1",
"]",
";",
"try",
"{",
"mappedValue",
"=",
"decodeURIComponent",
"(",
"mappedValue",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// nothing to do",
"}",
"return",
"mappedValue",
";",
"}",
";",
"}"
] |
Maps query parameter value using the parameters expression.
@param {RegExp} expression Regular expression to get parameter value.
@returns {Function} URI query string parameter value mapper function.
|
[
"Maps",
"query",
"parameter",
"value",
"using",
"the",
"parameters",
"expression",
"."
] |
bddc7012d973ec3e147b07cee02bf3ad52fc99cd
|
https://github.com/catbee/catbee/blob/bddc7012d973ec3e147b07cee02bf3ad52fc99cd/lib/helpers/routeHelper.js#L124-L142
|
36,355 |
catbee/catbee
|
lib/helpers/routeHelper.js
|
getParameterDescriptor
|
function getParameterDescriptor (parameter) {
var parts = parameter.split(SLASHED_BRACKETS_REG_EXP);
return {
name: parts[0].trim().substring(1)
};
}
|
javascript
|
function getParameterDescriptor (parameter) {
var parts = parameter.split(SLASHED_BRACKETS_REG_EXP);
return {
name: parts[0].trim().substring(1)
};
}
|
[
"function",
"getParameterDescriptor",
"(",
"parameter",
")",
"{",
"var",
"parts",
"=",
"parameter",
".",
"split",
"(",
"SLASHED_BRACKETS_REG_EXP",
")",
";",
"return",
"{",
"name",
":",
"parts",
"[",
"0",
"]",
".",
"trim",
"(",
")",
".",
"substring",
"(",
"1",
")",
"}",
";",
"}"
] |
Gets description of parameters from its expression.
@param {string} parameter Parameter expression.
@returns {{name: string}} Parameter descriptor.
|
[
"Gets",
"description",
"of",
"parameters",
"from",
"its",
"expression",
"."
] |
bddc7012d973ec3e147b07cee02bf3ad52fc99cd
|
https://github.com/catbee/catbee/blob/bddc7012d973ec3e147b07cee02bf3ad52fc99cd/lib/helpers/routeHelper.js#L149-L155
|
36,356 |
catbee/catbee
|
lib/helpers/routeHelper.js
|
extractQueryParameters
|
function extractQueryParameters (query) {
return Object.keys(query.values)
.reduce((queryParameters, name) => {
// arrays in routing definitions are not supported
if (util.isArray(query.values[name])) {
return queryParameters;
}
// escape regular expression characters
var escaped = query.values[name].replace(EXPRESSION_ESCAPE_REG_EXP, '\\$&');
// get all occurrences of routing parameters in URI path
var regExpSource = '^' + escaped.replace(PARAMETER_REG_EXP, URI_QUERY_REPLACEMENT_REG_EXP_SOURCE) + '$';
var queryParameterMatches = escaped.match(PARAMETER_REG_EXP);
if (!queryParameterMatches ||
queryParameterMatches.length === 0) {
return;
}
var parameter = getParameterDescriptor(queryParameterMatches[queryParameterMatches.length - 1]);
var expression = new RegExp(regExpSource, 'i');
parameter.map = createUriQueryValueMapper(expression);
queryParameters[name] = parameter;
return queryParameters;
}, Object.create(null));
}
|
javascript
|
function extractQueryParameters (query) {
return Object.keys(query.values)
.reduce((queryParameters, name) => {
// arrays in routing definitions are not supported
if (util.isArray(query.values[name])) {
return queryParameters;
}
// escape regular expression characters
var escaped = query.values[name].replace(EXPRESSION_ESCAPE_REG_EXP, '\\$&');
// get all occurrences of routing parameters in URI path
var regExpSource = '^' + escaped.replace(PARAMETER_REG_EXP, URI_QUERY_REPLACEMENT_REG_EXP_SOURCE) + '$';
var queryParameterMatches = escaped.match(PARAMETER_REG_EXP);
if (!queryParameterMatches ||
queryParameterMatches.length === 0) {
return;
}
var parameter = getParameterDescriptor(queryParameterMatches[queryParameterMatches.length - 1]);
var expression = new RegExp(regExpSource, 'i');
parameter.map = createUriQueryValueMapper(expression);
queryParameters[name] = parameter;
return queryParameters;
}, Object.create(null));
}
|
[
"function",
"extractQueryParameters",
"(",
"query",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"query",
".",
"values",
")",
".",
"reduce",
"(",
"(",
"queryParameters",
",",
"name",
")",
"=>",
"{",
"// arrays in routing definitions are not supported",
"if",
"(",
"util",
".",
"isArray",
"(",
"query",
".",
"values",
"[",
"name",
"]",
")",
")",
"{",
"return",
"queryParameters",
";",
"}",
"// escape regular expression characters",
"var",
"escaped",
"=",
"query",
".",
"values",
"[",
"name",
"]",
".",
"replace",
"(",
"EXPRESSION_ESCAPE_REG_EXP",
",",
"'\\\\$&'",
")",
";",
"// get all occurrences of routing parameters in URI path",
"var",
"regExpSource",
"=",
"'^'",
"+",
"escaped",
".",
"replace",
"(",
"PARAMETER_REG_EXP",
",",
"URI_QUERY_REPLACEMENT_REG_EXP_SOURCE",
")",
"+",
"'$'",
";",
"var",
"queryParameterMatches",
"=",
"escaped",
".",
"match",
"(",
"PARAMETER_REG_EXP",
")",
";",
"if",
"(",
"!",
"queryParameterMatches",
"||",
"queryParameterMatches",
".",
"length",
"===",
"0",
")",
"{",
"return",
";",
"}",
"var",
"parameter",
"=",
"getParameterDescriptor",
"(",
"queryParameterMatches",
"[",
"queryParameterMatches",
".",
"length",
"-",
"1",
"]",
")",
";",
"var",
"expression",
"=",
"new",
"RegExp",
"(",
"regExpSource",
",",
"'i'",
")",
";",
"parameter",
".",
"map",
"=",
"createUriQueryValueMapper",
"(",
"expression",
")",
";",
"queryParameters",
"[",
"name",
"]",
"=",
"parameter",
";",
"return",
"queryParameters",
";",
"}",
",",
"Object",
".",
"create",
"(",
"null",
")",
")",
";",
"}"
] |
Extracts query parameters to a key-value object
@param {String} query
@returns {Object} key-value query parameter map
|
[
"Extracts",
"query",
"parameters",
"to",
"a",
"key",
"-",
"value",
"object"
] |
bddc7012d973ec3e147b07cee02bf3ad52fc99cd
|
https://github.com/catbee/catbee/blob/bddc7012d973ec3e147b07cee02bf3ad52fc99cd/lib/helpers/routeHelper.js#L162-L188
|
36,357 |
catbee/catbee
|
lib/helpers/routeHelper.js
|
compileStringRouteExpression
|
function compileStringRouteExpression (routeExpression) {
var routeUri = new URI(routeExpression);
routeUri.path = module.exports.removeEndSlash(routeUri.path);
if (!routeUri) {
return null;
}
// escape regular expression characters
var escaped = routeUri.path.replace(
EXPRESSION_ESCAPE_REG_EXP, '\\$&'
);
// get all occurrences of routing parameters in URI path
var regExpSource = '^' + escaped.replace(PARAMETER_REG_EXP, URI_PATH_REPLACEMENT_REG_EXP_SOURCE) + '$';
var expression = new RegExp(regExpSource, 'i');
var pathParameterMatches = escaped.match(PARAMETER_REG_EXP);
var pathParameters = pathParameterMatches ? pathParameterMatches.map(getParameterDescriptor) : null;
var pathMapper = pathParameters ? createUriPathMapper(expression, pathParameters) : null;
var queryMapper = routeUri.query ? createUriQueryMapper(routeUri.query) : null;
return {
expression: expression,
map: uri => {
var args = Object.create(null);
if (pathMapper) {
pathMapper(uri.path, args);
}
if (queryMapper && uri.query) {
queryMapper(uri.query.values, args);
}
return args;
}
};
}
|
javascript
|
function compileStringRouteExpression (routeExpression) {
var routeUri = new URI(routeExpression);
routeUri.path = module.exports.removeEndSlash(routeUri.path);
if (!routeUri) {
return null;
}
// escape regular expression characters
var escaped = routeUri.path.replace(
EXPRESSION_ESCAPE_REG_EXP, '\\$&'
);
// get all occurrences of routing parameters in URI path
var regExpSource = '^' + escaped.replace(PARAMETER_REG_EXP, URI_PATH_REPLACEMENT_REG_EXP_SOURCE) + '$';
var expression = new RegExp(regExpSource, 'i');
var pathParameterMatches = escaped.match(PARAMETER_REG_EXP);
var pathParameters = pathParameterMatches ? pathParameterMatches.map(getParameterDescriptor) : null;
var pathMapper = pathParameters ? createUriPathMapper(expression, pathParameters) : null;
var queryMapper = routeUri.query ? createUriQueryMapper(routeUri.query) : null;
return {
expression: expression,
map: uri => {
var args = Object.create(null);
if (pathMapper) {
pathMapper(uri.path, args);
}
if (queryMapper && uri.query) {
queryMapper(uri.query.values, args);
}
return args;
}
};
}
|
[
"function",
"compileStringRouteExpression",
"(",
"routeExpression",
")",
"{",
"var",
"routeUri",
"=",
"new",
"URI",
"(",
"routeExpression",
")",
";",
"routeUri",
".",
"path",
"=",
"module",
".",
"exports",
".",
"removeEndSlash",
"(",
"routeUri",
".",
"path",
")",
";",
"if",
"(",
"!",
"routeUri",
")",
"{",
"return",
"null",
";",
"}",
"// escape regular expression characters",
"var",
"escaped",
"=",
"routeUri",
".",
"path",
".",
"replace",
"(",
"EXPRESSION_ESCAPE_REG_EXP",
",",
"'\\\\$&'",
")",
";",
"// get all occurrences of routing parameters in URI path",
"var",
"regExpSource",
"=",
"'^'",
"+",
"escaped",
".",
"replace",
"(",
"PARAMETER_REG_EXP",
",",
"URI_PATH_REPLACEMENT_REG_EXP_SOURCE",
")",
"+",
"'$'",
";",
"var",
"expression",
"=",
"new",
"RegExp",
"(",
"regExpSource",
",",
"'i'",
")",
";",
"var",
"pathParameterMatches",
"=",
"escaped",
".",
"match",
"(",
"PARAMETER_REG_EXP",
")",
";",
"var",
"pathParameters",
"=",
"pathParameterMatches",
"?",
"pathParameterMatches",
".",
"map",
"(",
"getParameterDescriptor",
")",
":",
"null",
";",
"var",
"pathMapper",
"=",
"pathParameters",
"?",
"createUriPathMapper",
"(",
"expression",
",",
"pathParameters",
")",
":",
"null",
";",
"var",
"queryMapper",
"=",
"routeUri",
".",
"query",
"?",
"createUriQueryMapper",
"(",
"routeUri",
".",
"query",
")",
":",
"null",
";",
"return",
"{",
"expression",
":",
"expression",
",",
"map",
":",
"uri",
"=>",
"{",
"var",
"args",
"=",
"Object",
".",
"create",
"(",
"null",
")",
";",
"if",
"(",
"pathMapper",
")",
"{",
"pathMapper",
"(",
"uri",
".",
"path",
",",
"args",
")",
";",
"}",
"if",
"(",
"queryMapper",
"&&",
"uri",
".",
"query",
")",
"{",
"queryMapper",
"(",
"uri",
".",
"query",
".",
"values",
",",
"args",
")",
";",
"}",
"return",
"args",
";",
"}",
"}",
";",
"}"
] |
Creates a mapper for string route definition
@param {String} routeExpression string route uri definition
@returns {{expression: RegExp, map: Function}|null} URI mapper object.
|
[
"Creates",
"a",
"mapper",
"for",
"string",
"route",
"definition"
] |
bddc7012d973ec3e147b07cee02bf3ad52fc99cd
|
https://github.com/catbee/catbee/blob/bddc7012d973ec3e147b07cee02bf3ad52fc99cd/lib/helpers/routeHelper.js#L195-L232
|
36,358 |
datanews/tables
|
lib/utils.js
|
toSQLName
|
function toSQLName(input) {
return !input || _.isObject(input) || _.isArray(input) || _.isNaN(input) ? undefined :
input.toString().toLowerCase()
.replace(/\W+/g, " ")
.trim()
.replace(/\s+/g, "_")
.replace(/_+/g, "_")
.substring(0, 64);
}
|
javascript
|
function toSQLName(input) {
return !input || _.isObject(input) || _.isArray(input) || _.isNaN(input) ? undefined :
input.toString().toLowerCase()
.replace(/\W+/g, " ")
.trim()
.replace(/\s+/g, "_")
.replace(/_+/g, "_")
.substring(0, 64);
}
|
[
"function",
"toSQLName",
"(",
"input",
")",
"{",
"return",
"!",
"input",
"||",
"_",
".",
"isObject",
"(",
"input",
")",
"||",
"_",
".",
"isArray",
"(",
"input",
")",
"||",
"_",
".",
"isNaN",
"(",
"input",
")",
"?",
"undefined",
":",
"input",
".",
"toString",
"(",
")",
".",
"toLowerCase",
"(",
")",
".",
"replace",
"(",
"/",
"\\W+",
"/",
"g",
",",
"\" \"",
")",
".",
"trim",
"(",
")",
".",
"replace",
"(",
"/",
"\\s+",
"/",
"g",
",",
"\"_\"",
")",
".",
"replace",
"(",
"/",
"_+",
"/",
"g",
",",
"\"_\"",
")",
".",
"substring",
"(",
"0",
",",
"64",
")",
";",
"}"
] |
Make into a standardize name for SQL tables or columns
|
[
"Make",
"into",
"a",
"standardize",
"name",
"for",
"SQL",
"tables",
"or",
"columns"
] |
4b33aa7a944a93260c49baecbb90345211cac789
|
https://github.com/datanews/tables/blob/4b33aa7a944a93260c49baecbb90345211cac789/lib/utils.js#L11-L19
|
36,359 |
datanews/tables
|
lib/utils.js
|
standardizeInput
|
function standardizeInput(input) {
if ([undefined, null].indexOf(input) !== -1) {
input = null;
}
else if (_.isNaN(input)) {
input = null;
}
else if (_.isString(input)) {
input = input.trim();
// Written empty values
if (["unspecified", "unknown", "none", "null", "empty", ""].indexOf(input.toLowerCase()) !== -1) {
input = null;
}
}
return input;
}
|
javascript
|
function standardizeInput(input) {
if ([undefined, null].indexOf(input) !== -1) {
input = null;
}
else if (_.isNaN(input)) {
input = null;
}
else if (_.isString(input)) {
input = input.trim();
// Written empty values
if (["unspecified", "unknown", "none", "null", "empty", ""].indexOf(input.toLowerCase()) !== -1) {
input = null;
}
}
return input;
}
|
[
"function",
"standardizeInput",
"(",
"input",
")",
"{",
"if",
"(",
"[",
"undefined",
",",
"null",
"]",
".",
"indexOf",
"(",
"input",
")",
"!==",
"-",
"1",
")",
"{",
"input",
"=",
"null",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isNaN",
"(",
"input",
")",
")",
"{",
"input",
"=",
"null",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isString",
"(",
"input",
")",
")",
"{",
"input",
"=",
"input",
".",
"trim",
"(",
")",
";",
"// Written empty values",
"if",
"(",
"[",
"\"unspecified\"",
",",
"\"unknown\"",
",",
"\"none\"",
",",
"\"null\"",
",",
"\"empty\"",
",",
"\"\"",
"]",
".",
"indexOf",
"(",
"input",
".",
"toLowerCase",
"(",
")",
")",
"!==",
"-",
"1",
")",
"{",
"input",
"=",
"null",
";",
"}",
"}",
"return",
"input",
";",
"}"
] |
Standardize input, like handling empty
|
[
"Standardize",
"input",
"like",
"handling",
"empty"
] |
4b33aa7a944a93260c49baecbb90345211cac789
|
https://github.com/datanews/tables/blob/4b33aa7a944a93260c49baecbb90345211cac789/lib/utils.js#L31-L48
|
36,360 |
suitcss/rework-suit
|
index.js
|
suit
|
function suit(options) {
options = options || {};
// for backwards compatibility with rework-npm < 1.0.0
options.root = options.root || options.dir;
return function (ast, reworkObj) {
reworkObj
// inline imports
.use(inliner({
alias: options.alias,
prefilter: function (css) {
// per-file conformance checks
return rework(css).use(conformance).toString();
},
root: options.root,
shim: options.shim,
}))
// check if the number of selectors exceeds the IE limit
.use(limits)
// custom media queries
.use(customMedia)
// variables
.use(vars())
// calc
.use(calc);
};
}
|
javascript
|
function suit(options) {
options = options || {};
// for backwards compatibility with rework-npm < 1.0.0
options.root = options.root || options.dir;
return function (ast, reworkObj) {
reworkObj
// inline imports
.use(inliner({
alias: options.alias,
prefilter: function (css) {
// per-file conformance checks
return rework(css).use(conformance).toString();
},
root: options.root,
shim: options.shim,
}))
// check if the number of selectors exceeds the IE limit
.use(limits)
// custom media queries
.use(customMedia)
// variables
.use(vars())
// calc
.use(calc);
};
}
|
[
"function",
"suit",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"// for backwards compatibility with rework-npm < 1.0.0",
"options",
".",
"root",
"=",
"options",
".",
"root",
"||",
"options",
".",
"dir",
";",
"return",
"function",
"(",
"ast",
",",
"reworkObj",
")",
"{",
"reworkObj",
"// inline imports",
".",
"use",
"(",
"inliner",
"(",
"{",
"alias",
":",
"options",
".",
"alias",
",",
"prefilter",
":",
"function",
"(",
"css",
")",
"{",
"// per-file conformance checks",
"return",
"rework",
"(",
"css",
")",
".",
"use",
"(",
"conformance",
")",
".",
"toString",
"(",
")",
";",
"}",
",",
"root",
":",
"options",
".",
"root",
",",
"shim",
":",
"options",
".",
"shim",
",",
"}",
")",
")",
"// check if the number of selectors exceeds the IE limit",
".",
"use",
"(",
"limits",
")",
"// custom media queries",
".",
"use",
"(",
"customMedia",
")",
"// variables",
".",
"use",
"(",
"vars",
"(",
")",
")",
"// calc",
".",
"use",
"(",
"calc",
")",
";",
"}",
";",
"}"
] |
Apply rework plugins to a rework instance; export as a rework plugin
@param {String} ast Rework AST
@param {Object} reworkObj Rework instance
|
[
"Apply",
"rework",
"plugins",
"to",
"a",
"rework",
"instance",
";",
"export",
"as",
"a",
"rework",
"plugin"
] |
49eb81ab749d839c0410066eef7c71d2b7d8bd0c
|
https://github.com/suitcss/rework-suit/blob/49eb81ab749d839c0410066eef7c71d2b7d8bd0c/index.js#L28-L54
|
36,361 |
sebpiq/backbone.statemachine
|
backbone.statemachine.js
|
function(leaveState, event, data) {
// If `data` is a string, it is the destination state of the transition
if (_.isString(data)) data = {enterState: data}
else data = _.clone(data)
if (leaveState !== ANY_STATE && !this._states.hasOwnProperty(leaveState))
this.state(leaveState, {})
if (!this._states.hasOwnProperty(data.enterState))
this.state(data.enterState, {})
if (!this._transitions.hasOwnProperty(leaveState))
this._transitions[leaveState] = {}
data.callbacks = this._collectMethods((data.callbacks || []))
this._transitions[leaveState][event] = data
}
|
javascript
|
function(leaveState, event, data) {
// If `data` is a string, it is the destination state of the transition
if (_.isString(data)) data = {enterState: data}
else data = _.clone(data)
if (leaveState !== ANY_STATE && !this._states.hasOwnProperty(leaveState))
this.state(leaveState, {})
if (!this._states.hasOwnProperty(data.enterState))
this.state(data.enterState, {})
if (!this._transitions.hasOwnProperty(leaveState))
this._transitions[leaveState] = {}
data.callbacks = this._collectMethods((data.callbacks || []))
this._transitions[leaveState][event] = data
}
|
[
"function",
"(",
"leaveState",
",",
"event",
",",
"data",
")",
"{",
"// If `data` is a string, it is the destination state of the transition",
"if",
"(",
"_",
".",
"isString",
"(",
"data",
")",
")",
"data",
"=",
"{",
"enterState",
":",
"data",
"}",
"else",
"data",
"=",
"_",
".",
"clone",
"(",
"data",
")",
"if",
"(",
"leaveState",
"!==",
"ANY_STATE",
"&&",
"!",
"this",
".",
"_states",
".",
"hasOwnProperty",
"(",
"leaveState",
")",
")",
"this",
".",
"state",
"(",
"leaveState",
",",
"{",
"}",
")",
"if",
"(",
"!",
"this",
".",
"_states",
".",
"hasOwnProperty",
"(",
"data",
".",
"enterState",
")",
")",
"this",
".",
"state",
"(",
"data",
".",
"enterState",
",",
"{",
"}",
")",
"if",
"(",
"!",
"this",
".",
"_transitions",
".",
"hasOwnProperty",
"(",
"leaveState",
")",
")",
"this",
".",
"_transitions",
"[",
"leaveState",
"]",
"=",
"{",
"}",
"data",
".",
"callbacks",
"=",
"this",
".",
"_collectMethods",
"(",
"(",
"data",
".",
"callbacks",
"||",
"[",
"]",
")",
")",
"this",
".",
"_transitions",
"[",
"leaveState",
"]",
"[",
"event",
"]",
"=",
"data",
"}"
] |
Declares a new transition on the state machine.
|
[
"Declares",
"a",
"new",
"transition",
"on",
"the",
"state",
"machine",
"."
] |
6ba1852f077bad4f09994ad2c8e93d2f3a0a17af
|
https://github.com/sebpiq/backbone.statemachine/blob/6ba1852f077bad4f09994ad2c8e93d2f3a0a17af/backbone.statemachine.js#L69-L85
|
|
36,362 |
sebpiq/backbone.statemachine
|
backbone.statemachine.js
|
function(name, data) {
if (name === ANY_STATE)
throw new Error('state name "' + ANY_STATE + '" is forbidden')
data = _.clone(data)
data.enter = this._collectMethods((data.enter || []))
data.leave = this._collectMethods((data.leave || []))
this._states[name] = data
}
|
javascript
|
function(name, data) {
if (name === ANY_STATE)
throw new Error('state name "' + ANY_STATE + '" is forbidden')
data = _.clone(data)
data.enter = this._collectMethods((data.enter || []))
data.leave = this._collectMethods((data.leave || []))
this._states[name] = data
}
|
[
"function",
"(",
"name",
",",
"data",
")",
"{",
"if",
"(",
"name",
"===",
"ANY_STATE",
")",
"throw",
"new",
"Error",
"(",
"'state name \"'",
"+",
"ANY_STATE",
"+",
"'\" is forbidden'",
")",
"data",
"=",
"_",
".",
"clone",
"(",
"data",
")",
"data",
".",
"enter",
"=",
"this",
".",
"_collectMethods",
"(",
"(",
"data",
".",
"enter",
"||",
"[",
"]",
")",
")",
"data",
".",
"leave",
"=",
"this",
".",
"_collectMethods",
"(",
"(",
"data",
".",
"leave",
"||",
"[",
"]",
")",
")",
"this",
".",
"_states",
"[",
"name",
"]",
"=",
"data",
"}"
] |
Declares a new state on the state machine
|
[
"Declares",
"a",
"new",
"state",
"on",
"the",
"state",
"machine"
] |
6ba1852f077bad4f09994ad2c8e93d2f3a0a17af
|
https://github.com/sebpiq/backbone.statemachine/blob/6ba1852f077bad4f09994ad2c8e93d2f3a0a17af/backbone.statemachine.js#L88-L96
|
|
36,363 |
sebpiq/backbone.statemachine
|
backbone.statemachine.js
|
function() {
var events = _.reduce(_.values(this._transitions), function(memo, transitions) {
return memo.concat(_.keys(transitions))
}, [])
return _.uniq(events)
}
|
javascript
|
function() {
var events = _.reduce(_.values(this._transitions), function(memo, transitions) {
return memo.concat(_.keys(transitions))
}, [])
return _.uniq(events)
}
|
[
"function",
"(",
")",
"{",
"var",
"events",
"=",
"_",
".",
"reduce",
"(",
"_",
".",
"values",
"(",
"this",
".",
"_transitions",
")",
",",
"function",
"(",
"memo",
",",
"transitions",
")",
"{",
"return",
"memo",
".",
"concat",
"(",
"_",
".",
"keys",
"(",
"transitions",
")",
")",
"}",
",",
"[",
"]",
")",
"return",
"_",
".",
"uniq",
"(",
"events",
")",
"}"
] |
Returns the list of all events that can trigger a transition
|
[
"Returns",
"the",
"list",
"of",
"all",
"events",
"that",
"can",
"trigger",
"a",
"transition"
] |
6ba1852f077bad4f09994ad2c8e93d2f3a0a17af
|
https://github.com/sebpiq/backbone.statemachine/blob/6ba1852f077bad4f09994ad2c8e93d2f3a0a17af/backbone.statemachine.js#L110-L115
|
|
36,364 |
sebpiq/backbone.statemachine
|
backbone.statemachine.js
|
function(event) {
var data, extraArgs, key, transitions = this._transitions
if (transitions.hasOwnProperty((key = this.currentState)) &&
transitions[key].hasOwnProperty(event)) {
data = transitions[key][event]
} else if (transitions.hasOwnProperty(ANY_STATE) &&
transitions[ANY_STATE].hasOwnProperty(event)) {
data = transitions[ANY_STATE][event]
} else return
extraArgs = _.toArray(arguments).slice(1)
this._doTransition.apply(this, [data, event].concat(extraArgs))
}
|
javascript
|
function(event) {
var data, extraArgs, key, transitions = this._transitions
if (transitions.hasOwnProperty((key = this.currentState)) &&
transitions[key].hasOwnProperty(event)) {
data = transitions[key][event]
} else if (transitions.hasOwnProperty(ANY_STATE) &&
transitions[ANY_STATE].hasOwnProperty(event)) {
data = transitions[ANY_STATE][event]
} else return
extraArgs = _.toArray(arguments).slice(1)
this._doTransition.apply(this, [data, event].concat(extraArgs))
}
|
[
"function",
"(",
"event",
")",
"{",
"var",
"data",
",",
"extraArgs",
",",
"key",
",",
"transitions",
"=",
"this",
".",
"_transitions",
"if",
"(",
"transitions",
".",
"hasOwnProperty",
"(",
"(",
"key",
"=",
"this",
".",
"currentState",
")",
")",
"&&",
"transitions",
"[",
"key",
"]",
".",
"hasOwnProperty",
"(",
"event",
")",
")",
"{",
"data",
"=",
"transitions",
"[",
"key",
"]",
"[",
"event",
"]",
"}",
"else",
"if",
"(",
"transitions",
".",
"hasOwnProperty",
"(",
"ANY_STATE",
")",
"&&",
"transitions",
"[",
"ANY_STATE",
"]",
".",
"hasOwnProperty",
"(",
"event",
")",
")",
"{",
"data",
"=",
"transitions",
"[",
"ANY_STATE",
"]",
"[",
"event",
"]",
"}",
"else",
"return",
"extraArgs",
"=",
"_",
".",
"toArray",
"(",
"arguments",
")",
".",
"slice",
"(",
"1",
")",
"this",
".",
"_doTransition",
".",
"apply",
"(",
"this",
",",
"[",
"data",
",",
"event",
"]",
".",
"concat",
"(",
"extraArgs",
")",
")",
"}"
] |
Callback bound to all events. If no transition available, do nothing. Otherwise, starts the transition.
|
[
"Callback",
"bound",
"to",
"all",
"events",
".",
"If",
"no",
"transition",
"available",
"do",
"nothing",
".",
"Otherwise",
"starts",
"the",
"transition",
"."
] |
6ba1852f077bad4f09994ad2c8e93d2f3a0a17af
|
https://github.com/sebpiq/backbone.statemachine/blob/6ba1852f077bad4f09994ad2c8e93d2f3a0a17af/backbone.statemachine.js#L119-L131
|
|
36,365 |
sebpiq/backbone.statemachine
|
backbone.statemachine.js
|
function(data, event) {
var extraArgs = _.toArray(arguments).slice(2),
leaveState = this.currentState,
enterState = data.enterState,
triggers = data.triggers
if (!this.silent)
this.trigger.apply(this, ['leaveState:' + leaveState].concat(extraArgs))
this._callCallbacks(this._states[leaveState].leave, extraArgs)
if (!this.silent) {
this.trigger.apply(this, ['transition', leaveState, enterState].concat(extraArgs))
if (triggers)
this.trigger.apply(this, [triggers].concat(extraArgs))
}
this._callCallbacks(data.callbacks, extraArgs)
if (!this.silent)
this.trigger.apply(this, ['enterState:' + enterState].concat(extraArgs))
this.toState.apply(this, [enterState].concat(extraArgs))
}
|
javascript
|
function(data, event) {
var extraArgs = _.toArray(arguments).slice(2),
leaveState = this.currentState,
enterState = data.enterState,
triggers = data.triggers
if (!this.silent)
this.trigger.apply(this, ['leaveState:' + leaveState].concat(extraArgs))
this._callCallbacks(this._states[leaveState].leave, extraArgs)
if (!this.silent) {
this.trigger.apply(this, ['transition', leaveState, enterState].concat(extraArgs))
if (triggers)
this.trigger.apply(this, [triggers].concat(extraArgs))
}
this._callCallbacks(data.callbacks, extraArgs)
if (!this.silent)
this.trigger.apply(this, ['enterState:' + enterState].concat(extraArgs))
this.toState.apply(this, [enterState].concat(extraArgs))
}
|
[
"function",
"(",
"data",
",",
"event",
")",
"{",
"var",
"extraArgs",
"=",
"_",
".",
"toArray",
"(",
"arguments",
")",
".",
"slice",
"(",
"2",
")",
",",
"leaveState",
"=",
"this",
".",
"currentState",
",",
"enterState",
"=",
"data",
".",
"enterState",
",",
"triggers",
"=",
"data",
".",
"triggers",
"if",
"(",
"!",
"this",
".",
"silent",
")",
"this",
".",
"trigger",
".",
"apply",
"(",
"this",
",",
"[",
"'leaveState:'",
"+",
"leaveState",
"]",
".",
"concat",
"(",
"extraArgs",
")",
")",
"this",
".",
"_callCallbacks",
"(",
"this",
".",
"_states",
"[",
"leaveState",
"]",
".",
"leave",
",",
"extraArgs",
")",
"if",
"(",
"!",
"this",
".",
"silent",
")",
"{",
"this",
".",
"trigger",
".",
"apply",
"(",
"this",
",",
"[",
"'transition'",
",",
"leaveState",
",",
"enterState",
"]",
".",
"concat",
"(",
"extraArgs",
")",
")",
"if",
"(",
"triggers",
")",
"this",
".",
"trigger",
".",
"apply",
"(",
"this",
",",
"[",
"triggers",
"]",
".",
"concat",
"(",
"extraArgs",
")",
")",
"}",
"this",
".",
"_callCallbacks",
"(",
"data",
".",
"callbacks",
",",
"extraArgs",
")",
"if",
"(",
"!",
"this",
".",
"silent",
")",
"this",
".",
"trigger",
".",
"apply",
"(",
"this",
",",
"[",
"'enterState:'",
"+",
"enterState",
"]",
".",
"concat",
"(",
"extraArgs",
")",
")",
"this",
".",
"toState",
".",
"apply",
"(",
"this",
",",
"[",
"enterState",
"]",
".",
"concat",
"(",
"extraArgs",
")",
")",
"}"
] |
Executes a transition.
|
[
"Executes",
"a",
"transition",
"."
] |
6ba1852f077bad4f09994ad2c8e93d2f3a0a17af
|
https://github.com/sebpiq/backbone.statemachine/blob/6ba1852f077bad4f09994ad2c8e93d2f3a0a17af/backbone.statemachine.js#L134-L155
|
|
36,366 |
sebpiq/backbone.statemachine
|
backbone.statemachine.js
|
function(methodNames) {
var methods = [], i, length, method
for (i = 0, length = methodNames.length; i < length; i++) {
// first, check if this is an anonymous function
if (_.isFunction(methodNames[i]))
method = methodNames[i]
else {
// else, get the function from the View
method = this[methodNames[i]]
if (!method)
throw new Error('Method "' + methodNames[i] + '" does not exist')
}
methods.push(method)
}
return methods
}
|
javascript
|
function(methodNames) {
var methods = [], i, length, method
for (i = 0, length = methodNames.length; i < length; i++) {
// first, check if this is an anonymous function
if (_.isFunction(methodNames[i]))
method = methodNames[i]
else {
// else, get the function from the View
method = this[methodNames[i]]
if (!method)
throw new Error('Method "' + methodNames[i] + '" does not exist')
}
methods.push(method)
}
return methods
}
|
[
"function",
"(",
"methodNames",
")",
"{",
"var",
"methods",
"=",
"[",
"]",
",",
"i",
",",
"length",
",",
"method",
"for",
"(",
"i",
"=",
"0",
",",
"length",
"=",
"methodNames",
".",
"length",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"// first, check if this is an anonymous function",
"if",
"(",
"_",
".",
"isFunction",
"(",
"methodNames",
"[",
"i",
"]",
")",
")",
"method",
"=",
"methodNames",
"[",
"i",
"]",
"else",
"{",
"// else, get the function from the View",
"method",
"=",
"this",
"[",
"methodNames",
"[",
"i",
"]",
"]",
"if",
"(",
"!",
"method",
")",
"throw",
"new",
"Error",
"(",
"'Method \"'",
"+",
"methodNames",
"[",
"i",
"]",
"+",
"'\" does not exist'",
")",
"}",
"methods",
".",
"push",
"(",
"method",
")",
"}",
"return",
"methods",
"}"
] |
Helper for collecting callbacks provided as strings.
|
[
"Helper",
"for",
"collecting",
"callbacks",
"provided",
"as",
"strings",
"."
] |
6ba1852f077bad4f09994ad2c8e93d2f3a0a17af
|
https://github.com/sebpiq/backbone.statemachine/blob/6ba1852f077bad4f09994ad2c8e93d2f3a0a17af/backbone.statemachine.js#L187-L203
|
|
36,367 |
sebpiq/backbone.statemachine
|
backbone.statemachine.js
|
function(cbArray, extraArgs) {
var i, length
for (i = 0, length = cbArray.length; i < length; i++)
cbArray[i].apply(this, extraArgs)
}
|
javascript
|
function(cbArray, extraArgs) {
var i, length
for (i = 0, length = cbArray.length; i < length; i++)
cbArray[i].apply(this, extraArgs)
}
|
[
"function",
"(",
"cbArray",
",",
"extraArgs",
")",
"{",
"var",
"i",
",",
"length",
"for",
"(",
"i",
"=",
"0",
",",
"length",
"=",
"cbArray",
".",
"length",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"cbArray",
"[",
"i",
"]",
".",
"apply",
"(",
"this",
",",
"extraArgs",
")",
"}"
] |
Helper for calling a list of callbacks.
|
[
"Helper",
"for",
"calling",
"a",
"list",
"of",
"callbacks",
"."
] |
6ba1852f077bad4f09994ad2c8e93d2f3a0a17af
|
https://github.com/sebpiq/backbone.statemachine/blob/6ba1852f077bad4f09994ad2c8e93d2f3a0a17af/backbone.statemachine.js#L206-L211
|
|
36,368 |
sebpiq/backbone.statemachine
|
backbone.statemachine.js
|
function(instance) {
// If this is the first state machine registered in the debugger,
// we create the debugger's html.
if (this.viewsArray.length === 0) {
var container = this.el = $('<div id="backbone-statemachine-debug-container">'+
'<h3>backbone.statemachine: DEBUGGER</h3>'+
'<a id="backbone-statemachine-debug-hideshow">hide</a>'+
'<style>'+
'#backbone-statemachine-debug-container{background-color:rgba(0,0,0,0.5);position:absolute;height:300px;width:300px;right:0;top:0;padding:10px;z-index:10;-moz-border-radius-bottomleft:30px;-webkit-border-radius-bottomleft:30px;border-bottom-left-radius:30px;}'+
'#backbone-statemachine-debug-container.collapsed{height:20px;width:60px;}'+
'#backbone-statemachine-debug-container a{color:blue;cursor:pointer;}'+
'#backbone-statemachine-debug-container h3{margin:0;text-align:center;color:white;margin-bottom:0.5em;}'+
'.backbone-statemachine-debug{width:60px;height:60px;-moz-border-radius:30px;-webkit-border-radius:30px;border-radius:30px;text-align:center;}'+
'.backbone-statemachine-debug .state{font-weight:bold;}'+
'a#backbone-statemachine-debug-hideshow{position:absolute;bottom:12px;left:12px;font-weight:bold;color:white;}'+
'</style></div>'
).appendTo($('body'))
$('#backbone-statemachine-debug-hideshow', this.el).click(function(event){
event.preventDefault()
if (this.collapsed) {
$(container).removeClass('collapsed').children().show()
$(this).html('hide')
this.collapsed = false
} else {
$(container).addClass('collapsed').children().hide()
$(this).html('show').show()
this.collapsed = true
}
})
}
// create the debug view, pick a random color for it, and add it to the debugger.
var debugView = new this({model: instance})
var bgColor = this.pickColor()
$(debugView.el).appendTo(this.el).css({'background-color': bgColor})
debugView.render()
if (this.collapsed) $(debugView.el).hide()
this.viewsArray.push(debugView)
}
|
javascript
|
function(instance) {
// If this is the first state machine registered in the debugger,
// we create the debugger's html.
if (this.viewsArray.length === 0) {
var container = this.el = $('<div id="backbone-statemachine-debug-container">'+
'<h3>backbone.statemachine: DEBUGGER</h3>'+
'<a id="backbone-statemachine-debug-hideshow">hide</a>'+
'<style>'+
'#backbone-statemachine-debug-container{background-color:rgba(0,0,0,0.5);position:absolute;height:300px;width:300px;right:0;top:0;padding:10px;z-index:10;-moz-border-radius-bottomleft:30px;-webkit-border-radius-bottomleft:30px;border-bottom-left-radius:30px;}'+
'#backbone-statemachine-debug-container.collapsed{height:20px;width:60px;}'+
'#backbone-statemachine-debug-container a{color:blue;cursor:pointer;}'+
'#backbone-statemachine-debug-container h3{margin:0;text-align:center;color:white;margin-bottom:0.5em;}'+
'.backbone-statemachine-debug{width:60px;height:60px;-moz-border-radius:30px;-webkit-border-radius:30px;border-radius:30px;text-align:center;}'+
'.backbone-statemachine-debug .state{font-weight:bold;}'+
'a#backbone-statemachine-debug-hideshow{position:absolute;bottom:12px;left:12px;font-weight:bold;color:white;}'+
'</style></div>'
).appendTo($('body'))
$('#backbone-statemachine-debug-hideshow', this.el).click(function(event){
event.preventDefault()
if (this.collapsed) {
$(container).removeClass('collapsed').children().show()
$(this).html('hide')
this.collapsed = false
} else {
$(container).addClass('collapsed').children().hide()
$(this).html('show').show()
this.collapsed = true
}
})
}
// create the debug view, pick a random color for it, and add it to the debugger.
var debugView = new this({model: instance})
var bgColor = this.pickColor()
$(debugView.el).appendTo(this.el).css({'background-color': bgColor})
debugView.render()
if (this.collapsed) $(debugView.el).hide()
this.viewsArray.push(debugView)
}
|
[
"function",
"(",
"instance",
")",
"{",
"// If this is the first state machine registered in the debugger,",
"// we create the debugger's html.",
"if",
"(",
"this",
".",
"viewsArray",
".",
"length",
"===",
"0",
")",
"{",
"var",
"container",
"=",
"this",
".",
"el",
"=",
"$",
"(",
"'<div id=\"backbone-statemachine-debug-container\">'",
"+",
"'<h3>backbone.statemachine: DEBUGGER</h3>'",
"+",
"'<a id=\"backbone-statemachine-debug-hideshow\">hide</a>'",
"+",
"'<style>'",
"+",
"'#backbone-statemachine-debug-container{background-color:rgba(0,0,0,0.5);position:absolute;height:300px;width:300px;right:0;top:0;padding:10px;z-index:10;-moz-border-radius-bottomleft:30px;-webkit-border-radius-bottomleft:30px;border-bottom-left-radius:30px;}'",
"+",
"'#backbone-statemachine-debug-container.collapsed{height:20px;width:60px;}'",
"+",
"'#backbone-statemachine-debug-container a{color:blue;cursor:pointer;}'",
"+",
"'#backbone-statemachine-debug-container h3{margin:0;text-align:center;color:white;margin-bottom:0.5em;}'",
"+",
"'.backbone-statemachine-debug{width:60px;height:60px;-moz-border-radius:30px;-webkit-border-radius:30px;border-radius:30px;text-align:center;}'",
"+",
"'.backbone-statemachine-debug .state{font-weight:bold;}'",
"+",
"'a#backbone-statemachine-debug-hideshow{position:absolute;bottom:12px;left:12px;font-weight:bold;color:white;}'",
"+",
"'</style></div>'",
")",
".",
"appendTo",
"(",
"$",
"(",
"'body'",
")",
")",
"$",
"(",
"'#backbone-statemachine-debug-hideshow'",
",",
"this",
".",
"el",
")",
".",
"click",
"(",
"function",
"(",
"event",
")",
"{",
"event",
".",
"preventDefault",
"(",
")",
"if",
"(",
"this",
".",
"collapsed",
")",
"{",
"$",
"(",
"container",
")",
".",
"removeClass",
"(",
"'collapsed'",
")",
".",
"children",
"(",
")",
".",
"show",
"(",
")",
"$",
"(",
"this",
")",
".",
"html",
"(",
"'hide'",
")",
"this",
".",
"collapsed",
"=",
"false",
"}",
"else",
"{",
"$",
"(",
"container",
")",
".",
"addClass",
"(",
"'collapsed'",
")",
".",
"children",
"(",
")",
".",
"hide",
"(",
")",
"$",
"(",
"this",
")",
".",
"html",
"(",
"'show'",
")",
".",
"show",
"(",
")",
"this",
".",
"collapsed",
"=",
"true",
"}",
"}",
")",
"}",
"// create the debug view, pick a random color for it, and add it to the debugger.",
"var",
"debugView",
"=",
"new",
"this",
"(",
"{",
"model",
":",
"instance",
"}",
")",
"var",
"bgColor",
"=",
"this",
".",
"pickColor",
"(",
")",
"$",
"(",
"debugView",
".",
"el",
")",
".",
"appendTo",
"(",
"this",
".",
"el",
")",
".",
"css",
"(",
"{",
"'background-color'",
":",
"bgColor",
"}",
")",
"debugView",
".",
"render",
"(",
")",
"if",
"(",
"this",
".",
"collapsed",
")",
"$",
"(",
"debugView",
".",
"el",
")",
".",
"hide",
"(",
")",
"this",
".",
"viewsArray",
".",
"push",
"(",
"debugView",
")",
"}"
] |
Registers a state machine in the debugger, so that a debug view will be created for it.
|
[
"Registers",
"a",
"state",
"machine",
"in",
"the",
"debugger",
"so",
"that",
"a",
"debug",
"view",
"will",
"be",
"created",
"for",
"it",
"."
] |
6ba1852f077bad4f09994ad2c8e93d2f3a0a17af
|
https://github.com/sebpiq/backbone.statemachine/blob/6ba1852f077bad4f09994ad2c8e93d2f3a0a17af/backbone.statemachine.js#L340-L378
|
|
36,369 |
hex7c0/basic-authentication
|
index.js
|
basic_medium
|
function basic_medium(req, res, next) {
var auth = basic_small(req);
if (auth !== '') {
if (check(auth, my.hash, my.file) === true) { // check if different
return setHeader(res, 'WWW-Authenticate', my.realms) === true
? end_work(err, next, 401) : null;
}
if (my.agent === '' || my.agent === req.headers['user-agent']) { // check UA
return end_work(err, next);
}
return end_work(err, next, 403);
}
// first attempt
res.writeHead(401, my.realm);
res.end();
}
|
javascript
|
function basic_medium(req, res, next) {
var auth = basic_small(req);
if (auth !== '') {
if (check(auth, my.hash, my.file) === true) { // check if different
return setHeader(res, 'WWW-Authenticate', my.realms) === true
? end_work(err, next, 401) : null;
}
if (my.agent === '' || my.agent === req.headers['user-agent']) { // check UA
return end_work(err, next);
}
return end_work(err, next, 403);
}
// first attempt
res.writeHead(401, my.realm);
res.end();
}
|
[
"function",
"basic_medium",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"auth",
"=",
"basic_small",
"(",
"req",
")",
";",
"if",
"(",
"auth",
"!==",
"''",
")",
"{",
"if",
"(",
"check",
"(",
"auth",
",",
"my",
".",
"hash",
",",
"my",
".",
"file",
")",
"===",
"true",
")",
"{",
"// check if different",
"return",
"setHeader",
"(",
"res",
",",
"'WWW-Authenticate'",
",",
"my",
".",
"realms",
")",
"===",
"true",
"?",
"end_work",
"(",
"err",
",",
"next",
",",
"401",
")",
":",
"null",
";",
"}",
"if",
"(",
"my",
".",
"agent",
"===",
"''",
"||",
"my",
".",
"agent",
"===",
"req",
".",
"headers",
"[",
"'user-agent'",
"]",
")",
"{",
"// check UA",
"return",
"end_work",
"(",
"err",
",",
"next",
")",
";",
"}",
"return",
"end_work",
"(",
"err",
",",
"next",
",",
"403",
")",
";",
"}",
"// first attempt",
"res",
".",
"writeHead",
"(",
"401",
",",
"my",
".",
"realm",
")",
";",
"res",
".",
"end",
"(",
")",
";",
"}"
] |
protection middleware with basic authentication without res.end
@function basic_medium
@param {Object} req - client request
@param {Object} res - response to client
@param {next} [next] - continue routes
|
[
"protection",
"middleware",
"with",
"basic",
"authentication",
"without",
"res",
".",
"end"
] |
2eacf41a3e54c9fce884b3acfe057f77942a30e5
|
https://github.com/hex7c0/basic-authentication/blob/2eacf41a3e54c9fce884b3acfe057f77942a30e5/index.js#L234-L253
|
36,370 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
pad
|
function pad(number, size) {
var stringNum = String(number);
while (stringNum.length < (size || 2)) {
stringNum = '0' + stringNum;
}
return stringNum;
}
|
javascript
|
function pad(number, size) {
var stringNum = String(number);
while (stringNum.length < (size || 2)) {
stringNum = '0' + stringNum;
}
return stringNum;
}
|
[
"function",
"pad",
"(",
"number",
",",
"size",
")",
"{",
"var",
"stringNum",
"=",
"String",
"(",
"number",
")",
";",
"while",
"(",
"stringNum",
".",
"length",
"<",
"(",
"size",
"||",
"2",
")",
")",
"{",
"stringNum",
"=",
"'0'",
"+",
"stringNum",
";",
"}",
"return",
"stringNum",
";",
"}"
] |
Zero padding number
@param {integer} number Number to format
@param {integer} [size=2] Digits limit
@return {string} Formatted num with zero padding
|
[
"Zero",
"padding",
"number"
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L702-L710
|
36,371 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
strCompact
|
function strCompact(str) {
return this.trim(str).replace(/([\r\n\s])+/g, function (match, whitespace) {
return whitespace === ' ' ? whitespace : ' ';
});
}
|
javascript
|
function strCompact(str) {
return this.trim(str).replace(/([\r\n\s])+/g, function (match, whitespace) {
return whitespace === ' ' ? whitespace : ' ';
});
}
|
[
"function",
"strCompact",
"(",
"str",
")",
"{",
"return",
"this",
".",
"trim",
"(",
"str",
")",
".",
"replace",
"(",
"/",
"([\\r\\n\\s])+",
"/",
"g",
",",
"function",
"(",
"match",
",",
"whitespace",
")",
"{",
"return",
"whitespace",
"===",
"' ' ?",
"w",
"itespace :",
"'",
"';",
"",
"}",
")",
";",
"}"
] |
Compacts whitespace in the string to a single space and trims the ends.
@param {String} [str] String to remove spaces
@return {String}
@example
strCompact(' Foo Bar Baz ') // 'Foo Bar Baz'
|
[
"Compacts",
"whitespace",
"in",
"the",
"string",
"to",
"a",
"single",
"space",
"and",
"trims",
"the",
"ends",
"."
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L772-L776
|
36,372 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
strReplace
|
function strReplace(search, replace, subject) {
var regex = void 0;
if (validateHelpers.isArray(search)) {
for (var i = 0; i < search.length; i++) {
search[i] = search[i].replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
regex = new RegExp(search[i], 'g');
subject = subject.replace(regex, validateHelpers.isArray(replace) ? replace[i] : replace);
}
} else {
search = search.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
regex = new RegExp(search, 'g');
subject = subject.replace(regex, validateHelpers.isArray(replace) ? replace[0] : replace);
}
return subject;
}
|
javascript
|
function strReplace(search, replace, subject) {
var regex = void 0;
if (validateHelpers.isArray(search)) {
for (var i = 0; i < search.length; i++) {
search[i] = search[i].replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
regex = new RegExp(search[i], 'g');
subject = subject.replace(regex, validateHelpers.isArray(replace) ? replace[i] : replace);
}
} else {
search = search.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
regex = new RegExp(search, 'g');
subject = subject.replace(regex, validateHelpers.isArray(replace) ? replace[0] : replace);
}
return subject;
}
|
[
"function",
"strReplace",
"(",
"search",
",",
"replace",
",",
"subject",
")",
"{",
"var",
"regex",
"=",
"void",
"0",
";",
"if",
"(",
"validateHelpers",
".",
"isArray",
"(",
"search",
")",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"search",
".",
"length",
";",
"i",
"++",
")",
"{",
"search",
"[",
"i",
"]",
"=",
"search",
"[",
"i",
"]",
".",
"replace",
"(",
"/",
"[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]",
"/",
"g",
",",
"'\\\\$&'",
")",
";",
"regex",
"=",
"new",
"RegExp",
"(",
"search",
"[",
"i",
"]",
",",
"'g'",
")",
";",
"subject",
"=",
"subject",
".",
"replace",
"(",
"regex",
",",
"validateHelpers",
".",
"isArray",
"(",
"replace",
")",
"?",
"replace",
"[",
"i",
"]",
":",
"replace",
")",
";",
"}",
"}",
"else",
"{",
"search",
"=",
"search",
".",
"replace",
"(",
"/",
"[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]",
"/",
"g",
",",
"'\\\\$&'",
")",
";",
"regex",
"=",
"new",
"RegExp",
"(",
"search",
",",
"'g'",
")",
";",
"subject",
"=",
"subject",
".",
"replace",
"(",
"regex",
",",
"validateHelpers",
".",
"isArray",
"(",
"replace",
")",
"?",
"replace",
"[",
"0",
"]",
":",
"replace",
")",
";",
"}",
"return",
"subject",
";",
"}"
] |
Multiple string replace, PHP str_replace clone
@param {string|Array} search - The value being searched for, otherwise known as the needle.
An array may be used to designate multiple needles.
@param {string|Array} replace - The replacement value that replaces found search values.
An array may be used to designate multiple replacements.
@param {string} subject - The subject of the replacement
@return {string} The modified string
@example
strReplace(['olá', 'mundo'], ['hello', 'world'], 'olá mundo'); // 'hello world'
strReplace(['um', 'dois'], 'olá', 'um dois três'); // Output 'olá olá três'
|
[
"Multiple",
"string",
"replace",
"PHP",
"str_replace",
"clone"
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L791-L807
|
36,373 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
underscore
|
function underscore(str) {
return str.replace(/[-\s]+/g, '_').replace(/([A-Z\d]+)([A-Z][a-z])/g, '$1_$2').replace(/([a-z\d])([A-Z])/g, '$1_$2').toLowerCase();
}
|
javascript
|
function underscore(str) {
return str.replace(/[-\s]+/g, '_').replace(/([A-Z\d]+)([A-Z][a-z])/g, '$1_$2').replace(/([a-z\d])([A-Z])/g, '$1_$2').toLowerCase();
}
|
[
"function",
"underscore",
"(",
"str",
")",
"{",
"return",
"str",
".",
"replace",
"(",
"/",
"[-\\s]+",
"/",
"g",
",",
"'_'",
")",
".",
"replace",
"(",
"/",
"([A-Z\\d]+)([A-Z][a-z])",
"/",
"g",
",",
"'$1_$2'",
")",
".",
"replace",
"(",
"/",
"([a-z\\d])([A-Z])",
"/",
"g",
",",
"'$1_$2'",
")",
".",
"toLowerCase",
"(",
")",
";",
"}"
] |
Converts hyphens and camel casing to underscores.
@param {String} str String to convert
@return {String}
|
[
"Converts",
"hyphens",
"and",
"camel",
"casing",
"to",
"underscores",
"."
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L850-L852
|
36,374 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
camelize
|
function camelize(obj) {
var _this = this;
var _camelize = function _camelize(str) {
str = stringHelpers.underscore(str);
str = stringHelpers.slugifyText(str);
return str.replace(/[_.-\s](\w|$)/g, function (_, x) {
return x.toUpperCase();
});
};
if (validateHelpers.isDate(obj) || validateHelpers.isRegExp(obj)) {
return obj;
}
if (validateHelpers.isArray(obj)) {
return obj.map(function (item, index) {
if (validateHelpers.isObject(item)) {
return _this.camelize(item);
}
return item;
});
}
if (validateHelpers.isString(obj)) {
return _camelize(obj);
}
return Object.keys(obj).reduce(function (acc, key) {
var camel = _camelize(key);
acc[camel] = obj[key];
if (validateHelpers.isObject(obj[key])) {
acc[camel] = _this.camelize(obj[key]);
}
return acc;
}, {});
}
|
javascript
|
function camelize(obj) {
var _this = this;
var _camelize = function _camelize(str) {
str = stringHelpers.underscore(str);
str = stringHelpers.slugifyText(str);
return str.replace(/[_.-\s](\w|$)/g, function (_, x) {
return x.toUpperCase();
});
};
if (validateHelpers.isDate(obj) || validateHelpers.isRegExp(obj)) {
return obj;
}
if (validateHelpers.isArray(obj)) {
return obj.map(function (item, index) {
if (validateHelpers.isObject(item)) {
return _this.camelize(item);
}
return item;
});
}
if (validateHelpers.isString(obj)) {
return _camelize(obj);
}
return Object.keys(obj).reduce(function (acc, key) {
var camel = _camelize(key);
acc[camel] = obj[key];
if (validateHelpers.isObject(obj[key])) {
acc[camel] = _this.camelize(obj[key]);
}
return acc;
}, {});
}
|
[
"function",
"camelize",
"(",
"obj",
")",
"{",
"var",
"_this",
"=",
"this",
";",
"var",
"_camelize",
"=",
"function",
"_camelize",
"(",
"str",
")",
"{",
"str",
"=",
"stringHelpers",
".",
"underscore",
"(",
"str",
")",
";",
"str",
"=",
"stringHelpers",
".",
"slugifyText",
"(",
"str",
")",
";",
"return",
"str",
".",
"replace",
"(",
"/",
"[_.-\\s](\\w|$)",
"/",
"g",
",",
"function",
"(",
"_",
",",
"x",
")",
"{",
"return",
"x",
".",
"toUpperCase",
"(",
")",
";",
"}",
")",
";",
"}",
";",
"if",
"(",
"validateHelpers",
".",
"isDate",
"(",
"obj",
")",
"||",
"validateHelpers",
".",
"isRegExp",
"(",
"obj",
")",
")",
"{",
"return",
"obj",
";",
"}",
"if",
"(",
"validateHelpers",
".",
"isArray",
"(",
"obj",
")",
")",
"{",
"return",
"obj",
".",
"map",
"(",
"function",
"(",
"item",
",",
"index",
")",
"{",
"if",
"(",
"validateHelpers",
".",
"isObject",
"(",
"item",
")",
")",
"{",
"return",
"_this",
".",
"camelize",
"(",
"item",
")",
";",
"}",
"return",
"item",
";",
"}",
")",
";",
"}",
"if",
"(",
"validateHelpers",
".",
"isString",
"(",
"obj",
")",
")",
"{",
"return",
"_camelize",
"(",
"obj",
")",
";",
"}",
"return",
"Object",
".",
"keys",
"(",
"obj",
")",
".",
"reduce",
"(",
"function",
"(",
"acc",
",",
"key",
")",
"{",
"var",
"camel",
"=",
"_camelize",
"(",
"key",
")",
";",
"acc",
"[",
"camel",
"]",
"=",
"obj",
"[",
"key",
"]",
";",
"if",
"(",
"validateHelpers",
".",
"isObject",
"(",
"obj",
"[",
"key",
"]",
")",
")",
"{",
"acc",
"[",
"camel",
"]",
"=",
"_this",
".",
"camelize",
"(",
"obj",
"[",
"key",
"]",
")",
";",
"}",
"return",
"acc",
";",
"}",
",",
"{",
"}",
")",
";",
"}"
] |
Recursively transform key strings to camelCase if param is an Object.
If param is string, return an camel cased string.
@param {Object|String} obj Object or string to transform
@returns {Object|String}
|
[
"Recursively",
"transform",
"key",
"strings",
"to",
"camelCase",
"if",
"param",
"is",
"an",
"Object",
".",
"If",
"param",
"is",
"string",
"return",
"an",
"camel",
"cased",
"string",
"."
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L873-L913
|
36,375 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
contains
|
function contains(value, elem) {
if (validateHelpers.isArray(elem)) {
for (var i = 0, len = elem.length; i < len; i += 1) {
if (elem[i] === value) {
return true;
}
}
}
if (validateHelpers.isString(elem)) {
return elem.indexOf(value) >= 0;
}
return false;
}
|
javascript
|
function contains(value, elem) {
if (validateHelpers.isArray(elem)) {
for (var i = 0, len = elem.length; i < len; i += 1) {
if (elem[i] === value) {
return true;
}
}
}
if (validateHelpers.isString(elem)) {
return elem.indexOf(value) >= 0;
}
return false;
}
|
[
"function",
"contains",
"(",
"value",
",",
"elem",
")",
"{",
"if",
"(",
"validateHelpers",
".",
"isArray",
"(",
"elem",
")",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"elem",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"1",
")",
"{",
"if",
"(",
"elem",
"[",
"i",
"]",
"===",
"value",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
"if",
"(",
"validateHelpers",
".",
"isString",
"(",
"elem",
")",
")",
"{",
"return",
"elem",
".",
"indexOf",
"(",
"value",
")",
">=",
"0",
";",
"}",
"return",
"false",
";",
"}"
] |
Check if value contains in an element
@category Global
@param {String} value - Value to check
@param {String|Array} elem - String or array
@return {Boolean} - Return true if element contains a value
|
[
"Check",
"if",
"value",
"contains",
"in",
"an",
"element"
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L924-L938
|
36,376 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
getUrlParameter
|
function getUrlParameter(name, entryPoint) {
entryPoint = !validateHelpers.isString(entryPoint) ? window.location.href : entryPoint.substring(0, 1) === '?' ? entryPoint : '?' + entryPoint;
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(entryPoint);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
|
javascript
|
function getUrlParameter(name, entryPoint) {
entryPoint = !validateHelpers.isString(entryPoint) ? window.location.href : entryPoint.substring(0, 1) === '?' ? entryPoint : '?' + entryPoint;
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(entryPoint);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
|
[
"function",
"getUrlParameter",
"(",
"name",
",",
"entryPoint",
")",
"{",
"entryPoint",
"=",
"!",
"validateHelpers",
".",
"isString",
"(",
"entryPoint",
")",
"?",
"window",
".",
"location",
".",
"href",
":",
"entryPoint",
".",
"substring",
"(",
"0",
",",
"1",
")",
"===",
"'?'",
"?",
"entryPoint",
":",
"'?'",
"+",
"entryPoint",
";",
"name",
"=",
"name",
".",
"replace",
"(",
"/",
"[\\[]",
"/",
",",
"'\\\\['",
")",
".",
"replace",
"(",
"/",
"[\\]]",
"/",
",",
"'\\\\]'",
")",
";",
"var",
"regex",
"=",
"new",
"RegExp",
"(",
"'[\\\\?&]'",
"+",
"name",
"+",
"'=([^&#]*)'",
")",
";",
"var",
"results",
"=",
"regex",
".",
"exec",
"(",
"entryPoint",
")",
";",
"return",
"results",
"===",
"null",
"?",
"''",
":",
"decodeURIComponent",
"(",
"results",
"[",
"1",
"]",
".",
"replace",
"(",
"/",
"\\+",
"/",
"g",
",",
"' '",
")",
")",
";",
"}"
] |
Get url params from a query string
@category Global
@param {string} name - Param name
@param {string} entryPoint - Full url or query string
@return {string} Value query string param
@example
// URL: https://site.com?param1=foo¶m2=bar
getUrlParameter('param1'); // foo
getUrlParameter('param2'); // bar
// Given entry point
var url = 'http://www.site.com?param1=foo¶m2=bar¶m3=baz';
getUrlParameter('param3', url); // baz
|
[
"Get",
"url",
"params",
"from",
"a",
"query",
"string"
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1203-L1211
|
36,377 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
resizeImageByRatio
|
function resizeImageByRatio(type, newSize, aspectRatio, decimal) {
if (!validateHelpers.isNumber(newSize) || !validateHelpers.isNumber(aspectRatio)) {
newSize = parseFloat(newSize, 10);
aspectRatio = parseFloat(aspectRatio, 10);
}
var dimensions = {};
decimal = decimal || 4;
switch (type) {
case 'width':
dimensions.width = parseFloat(newSize, 10);
dimensions.height = parseFloat((newSize / aspectRatio).toFixed(decimal), 10);
break;
case 'height':
dimensions.width = parseFloat((newSize * aspectRatio).toFixed(decimal), 10);
dimensions.height = parseFloat(newSize, 10);
break;
default:
throw new Error('\'type\' needs to be \'width\' or \'height\'');
}
return dimensions;
}
|
javascript
|
function resizeImageByRatio(type, newSize, aspectRatio, decimal) {
if (!validateHelpers.isNumber(newSize) || !validateHelpers.isNumber(aspectRatio)) {
newSize = parseFloat(newSize, 10);
aspectRatio = parseFloat(aspectRatio, 10);
}
var dimensions = {};
decimal = decimal || 4;
switch (type) {
case 'width':
dimensions.width = parseFloat(newSize, 10);
dimensions.height = parseFloat((newSize / aspectRatio).toFixed(decimal), 10);
break;
case 'height':
dimensions.width = parseFloat((newSize * aspectRatio).toFixed(decimal), 10);
dimensions.height = parseFloat(newSize, 10);
break;
default:
throw new Error('\'type\' needs to be \'width\' or \'height\'');
}
return dimensions;
}
|
[
"function",
"resizeImageByRatio",
"(",
"type",
",",
"newSize",
",",
"aspectRatio",
",",
"decimal",
")",
"{",
"if",
"(",
"!",
"validateHelpers",
".",
"isNumber",
"(",
"newSize",
")",
"||",
"!",
"validateHelpers",
".",
"isNumber",
"(",
"aspectRatio",
")",
")",
"{",
"newSize",
"=",
"parseFloat",
"(",
"newSize",
",",
"10",
")",
";",
"aspectRatio",
"=",
"parseFloat",
"(",
"aspectRatio",
",",
"10",
")",
";",
"}",
"var",
"dimensions",
"=",
"{",
"}",
";",
"decimal",
"=",
"decimal",
"||",
"4",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"'width'",
":",
"dimensions",
".",
"width",
"=",
"parseFloat",
"(",
"newSize",
",",
"10",
")",
";",
"dimensions",
".",
"height",
"=",
"parseFloat",
"(",
"(",
"newSize",
"/",
"aspectRatio",
")",
".",
"toFixed",
"(",
"decimal",
")",
",",
"10",
")",
";",
"break",
";",
"case",
"'height'",
":",
"dimensions",
".",
"width",
"=",
"parseFloat",
"(",
"(",
"newSize",
"*",
"aspectRatio",
")",
".",
"toFixed",
"(",
"decimal",
")",
",",
"10",
")",
";",
"dimensions",
".",
"height",
"=",
"parseFloat",
"(",
"newSize",
",",
"10",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'\\'type\\' needs to be \\'width\\' or \\'height\\''",
")",
";",
"}",
"return",
"dimensions",
";",
"}"
] |
Resize image by aspect ratio
@category Global
@param {String} type Resize by 'width' or 'height'
@param {Number} newSize New value to resize
@param {Number} aspectRatio Image aspect ratio (calculate by (width / height))
@return {Object} Object with new 'width' and 'height'
|
[
"Resize",
"image",
"by",
"aspect",
"ratio"
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1231-L1258
|
36,378 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
semverCompare
|
function semverCompare(v1, v2) {
var semver = /^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
var validate = function validate(version) {
if (!validateHelpers.isString(version)) {
throw new TypeError('Invalid argument: expected string');
}
if (!semver.test(version)) {
throw new Error('Invalid argument: not valid semver');
}
};
[v1, v2].forEach(validate);
var pa = v1.split('.');
var pb = v2.split('.');
for (var i = 0; i < 3; i++) {
var na = Number(pa[i]);
var nb = Number(pb[i]);
if (na > nb) {
return 1;
}
if (nb > na) {
return -1;
}
if (!isNaN(na) && isNaN(nb)) {
return 1;
}
if (isNaN(na) && !isNaN(nb)) {
return -1;
}
}
return 0;
}
|
javascript
|
function semverCompare(v1, v2) {
var semver = /^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
var validate = function validate(version) {
if (!validateHelpers.isString(version)) {
throw new TypeError('Invalid argument: expected string');
}
if (!semver.test(version)) {
throw new Error('Invalid argument: not valid semver');
}
};
[v1, v2].forEach(validate);
var pa = v1.split('.');
var pb = v2.split('.');
for (var i = 0; i < 3; i++) {
var na = Number(pa[i]);
var nb = Number(pb[i]);
if (na > nb) {
return 1;
}
if (nb > na) {
return -1;
}
if (!isNaN(na) && isNaN(nb)) {
return 1;
}
if (isNaN(na) && !isNaN(nb)) {
return -1;
}
}
return 0;
}
|
[
"function",
"semverCompare",
"(",
"v1",
",",
"v2",
")",
"{",
"var",
"semver",
"=",
"/",
"^v?(?:\\d+)(\\.(?:[x*]|\\d+)(\\.(?:[x*]|\\d+)(\\.(?:[x*]|\\d+))?(?:-[\\da-z\\-]+(?:\\.[\\da-z\\-]+)*)?(?:\\+[\\da-z\\-]+(?:\\.[\\da-z\\-]+)*)?)?)?$",
"/",
"i",
";",
"var",
"validate",
"=",
"function",
"validate",
"(",
"version",
")",
"{",
"if",
"(",
"!",
"validateHelpers",
".",
"isString",
"(",
"version",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Invalid argument: expected string'",
")",
";",
"}",
"if",
"(",
"!",
"semver",
".",
"test",
"(",
"version",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid argument: not valid semver'",
")",
";",
"}",
"}",
";",
"[",
"v1",
",",
"v2",
"]",
".",
"forEach",
"(",
"validate",
")",
";",
"var",
"pa",
"=",
"v1",
".",
"split",
"(",
"'.'",
")",
";",
"var",
"pb",
"=",
"v2",
".",
"split",
"(",
"'.'",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"3",
";",
"i",
"++",
")",
"{",
"var",
"na",
"=",
"Number",
"(",
"pa",
"[",
"i",
"]",
")",
";",
"var",
"nb",
"=",
"Number",
"(",
"pb",
"[",
"i",
"]",
")",
";",
"if",
"(",
"na",
">",
"nb",
")",
"{",
"return",
"1",
";",
"}",
"if",
"(",
"nb",
">",
"na",
")",
"{",
"return",
"-",
"1",
";",
"}",
"if",
"(",
"!",
"isNaN",
"(",
"na",
")",
"&&",
"isNaN",
"(",
"nb",
")",
")",
"{",
"return",
"1",
";",
"}",
"if",
"(",
"isNaN",
"(",
"na",
")",
"&&",
"!",
"isNaN",
"(",
"nb",
")",
")",
"{",
"return",
"-",
"1",
";",
"}",
"}",
"return",
"0",
";",
"}"
] |
Compare two semver version strings, returning -1, 0, or 1
If the semver string `v1` is greater than `v2`, return 1. If the semver string `v2` is greater than `v1`, return -1. If `v1` equals `v2`, return 0
@from @semver-compare
@category Global
@param {String} v1 Your semver to compare
@param {String} v2 Compared semver
@return {Number} -1, 0, 1
|
[
"Compare",
"two",
"semver",
"version",
"strings",
"returning",
"-",
"1",
"0",
"or",
"1",
"If",
"the",
"semver",
"string",
"v1",
"is",
"greater",
"than",
"v2",
"return",
"1",
".",
"If",
"the",
"semver",
"string",
"v2",
"is",
"greater",
"than",
"v1",
"return",
"-",
"1",
".",
"If",
"v1",
"equals",
"v2",
"return",
"0"
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1271-L1309
|
36,379 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
stripTags
|
function stripTags(input, allowed) {
allowed = (((allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // Making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
var commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return stringHelpers.strCompact(input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ' ';
}));
}
|
javascript
|
function stripTags(input, allowed) {
allowed = (((allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // Making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
var commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return stringHelpers.strCompact(input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ' ';
}));
}
|
[
"function",
"stripTags",
"(",
"input",
",",
"allowed",
")",
"{",
"allowed",
"=",
"(",
"(",
"(",
"allowed",
"||",
"''",
")",
"+",
"''",
")",
".",
"toLowerCase",
"(",
")",
".",
"match",
"(",
"/",
"<[a-z][a-z0-9]*>",
"/",
"g",
")",
"||",
"[",
"]",
")",
".",
"join",
"(",
"''",
")",
";",
"// Making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)",
"var",
"tags",
"=",
"/",
"<\\/?([a-z][a-z0-9]*)\\b[^>]*>",
"/",
"gi",
";",
"var",
"commentsAndPhpTags",
"=",
"/",
"<!--[\\s\\S]*?-->|<\\?(?:php)?[\\s\\S]*?\\?>",
"/",
"gi",
";",
"return",
"stringHelpers",
".",
"strCompact",
"(",
"input",
".",
"replace",
"(",
"commentsAndPhpTags",
",",
"''",
")",
".",
"replace",
"(",
"tags",
",",
"function",
"(",
"$0",
",",
"$1",
")",
"{",
"return",
"allowed",
".",
"indexOf",
"(",
"'<'",
"+",
"$1",
".",
"toLowerCase",
"(",
")",
"+",
"'>'",
")",
">",
"-",
"1",
"?",
"$0",
":",
"' '",
";",
"}",
")",
")",
";",
"}"
] |
Native javascript function to emulate the PHP function strip_tags.
@param {String} str The original HTML string to filter.
@param {String|Array} allowed A tag name or array of tag names to keep
@returns {string} The filtered HTML string.
@example
|
[
"Native",
"javascript",
"function",
"to",
"emulate",
"the",
"PHP",
"function",
"strip_tags",
"."
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1350-L1359
|
36,380 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
times
|
function times(n, iteratee) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295;
if (n < 1 || n > MAX_SAFE_INTEGER) {
return [];
}
var index = -1;
var length = Math.min(n, MAX_ARRAY_LENGTH);
var result = new Array(length);
while (++index < length) {
result[index] = iteratee(index);
}
index = MAX_ARRAY_LENGTH;
n -= MAX_ARRAY_LENGTH;
while (++index < n) {
iteratee(index);
}
return result;
}
|
javascript
|
function times(n, iteratee) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295;
if (n < 1 || n > MAX_SAFE_INTEGER) {
return [];
}
var index = -1;
var length = Math.min(n, MAX_ARRAY_LENGTH);
var result = new Array(length);
while (++index < length) {
result[index] = iteratee(index);
}
index = MAX_ARRAY_LENGTH;
n -= MAX_ARRAY_LENGTH;
while (++index < n) {
iteratee(index);
}
return result;
}
|
[
"function",
"times",
"(",
"n",
",",
"iteratee",
")",
"{",
"/** Used as references for various `Number` constants. */",
"var",
"MAX_SAFE_INTEGER",
"=",
"9007199254740991",
";",
"/** Used as references for the maximum length and index of an array. */",
"var",
"MAX_ARRAY_LENGTH",
"=",
"4294967295",
";",
"if",
"(",
"n",
"<",
"1",
"||",
"n",
">",
"MAX_SAFE_INTEGER",
")",
"{",
"return",
"[",
"]",
";",
"}",
"var",
"index",
"=",
"-",
"1",
";",
"var",
"length",
"=",
"Math",
".",
"min",
"(",
"n",
",",
"MAX_ARRAY_LENGTH",
")",
";",
"var",
"result",
"=",
"new",
"Array",
"(",
"length",
")",
";",
"while",
"(",
"++",
"index",
"<",
"length",
")",
"{",
"result",
"[",
"index",
"]",
"=",
"iteratee",
"(",
"index",
")",
";",
"}",
"index",
"=",
"MAX_ARRAY_LENGTH",
";",
"n",
"-=",
"MAX_ARRAY_LENGTH",
";",
"while",
"(",
"++",
"index",
"<",
"n",
")",
"{",
"iteratee",
"(",
"index",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
Invokes the iteratee `n` times, returning an array of the results of
each invocation. The iteratee is invoked with one argumentindex).
@from Lodash
@category Global
@param {number} n The number of times to invoke `iteratee`.
@param {Function} iteratee The function invoked per iteration.
@returns {Array} Returns the array of results.
@example
times(3, String)
// => ['0', '1', '2']
times(4, () => 0)
// => [0, 0, 0, 0]
|
[
"Invokes",
"the",
"iteratee",
"n",
"times",
"returning",
"an",
"array",
"of",
"the",
"results",
"of",
"each",
"invocation",
".",
"The",
"iteratee",
"is",
"invoked",
"with",
"one",
"argumentindex",
")",
"."
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1442-L1468
|
36,381 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
unserialize
|
function unserialize(str) {
str = !validateHelpers.isString(str) ? window.location.href : str;
if (str.indexOf('?') < 0) {
return {};
}
str = str.indexOf('?') === 0 ? str.substr(1) : str.slice(str.indexOf('?') + 1);
var query = {};
var parts = str.split('&');
for (var i = 0, len = parts.length; i < len; i += 1) {
var part = parts[i].split('=');
query[decodeURIComponent(part[0])] = decodeURIComponent(part[1] || '');
}
return query;
}
|
javascript
|
function unserialize(str) {
str = !validateHelpers.isString(str) ? window.location.href : str;
if (str.indexOf('?') < 0) {
return {};
}
str = str.indexOf('?') === 0 ? str.substr(1) : str.slice(str.indexOf('?') + 1);
var query = {};
var parts = str.split('&');
for (var i = 0, len = parts.length; i < len; i += 1) {
var part = parts[i].split('=');
query[decodeURIComponent(part[0])] = decodeURIComponent(part[1] || '');
}
return query;
}
|
[
"function",
"unserialize",
"(",
"str",
")",
"{",
"str",
"=",
"!",
"validateHelpers",
".",
"isString",
"(",
"str",
")",
"?",
"window",
".",
"location",
".",
"href",
":",
"str",
";",
"if",
"(",
"str",
".",
"indexOf",
"(",
"'?'",
")",
"<",
"0",
")",
"{",
"return",
"{",
"}",
";",
"}",
"str",
"=",
"str",
".",
"indexOf",
"(",
"'?'",
")",
"===",
"0",
"?",
"str",
".",
"substr",
"(",
"1",
")",
":",
"str",
".",
"slice",
"(",
"str",
".",
"indexOf",
"(",
"'?'",
")",
"+",
"1",
")",
";",
"var",
"query",
"=",
"{",
"}",
";",
"var",
"parts",
"=",
"str",
".",
"split",
"(",
"'&'",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"parts",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"1",
")",
"{",
"var",
"part",
"=",
"parts",
"[",
"i",
"]",
".",
"split",
"(",
"'='",
")",
";",
"query",
"[",
"decodeURIComponent",
"(",
"part",
"[",
"0",
"]",
")",
"]",
"=",
"decodeURIComponent",
"(",
"part",
"[",
"1",
"]",
"||",
"''",
")",
";",
"}",
"return",
"query",
";",
"}"
] |
Unserialize a query string into an object.
@category Global
@param {string} [str = actual url] - The string that will be converted into a object
@return {object}
@example
// str can be '?param1=foo¶m2=bar¶m3=baz', 'param1=foo¶m2=bar¶m3=baz' or a full url
// If no provided, will get actual url
var url = 'http://www.site.com?param1=foo¶m2=bar¶m3=baz';
unserialize(url); // {param1: 'foo', param2: 'bar', param3: 'baz'}
|
[
"Unserialize",
"a",
"query",
"string",
"into",
"an",
"object",
"."
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1483-L1501
|
36,382 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
isArguments
|
function isArguments(value) {
// fallback check is for IE
return toString.call(value) === '[object Arguments]' || value != null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && 'callee' in value;
}
|
javascript
|
function isArguments(value) {
// fallback check is for IE
return toString.call(value) === '[object Arguments]' || value != null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && 'callee' in value;
}
|
[
"function",
"isArguments",
"(",
"value",
")",
"{",
"// fallback check is for IE",
"return",
"toString",
".",
"call",
"(",
"value",
")",
"===",
"'[object Arguments]'",
"||",
"value",
"!=",
"null",
"&&",
"(",
"typeof",
"value",
"===",
"'undefined'",
"?",
"'undefined'",
":",
"_typeof",
"(",
"value",
")",
")",
"===",
"'object'",
"&&",
"'callee'",
"in",
"value",
";",
"}"
] |
is a given value Arguments?
@category Validate
|
[
"is",
"a",
"given",
"value",
"Arguments?"
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1512-L1515
|
36,383 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
isArray
|
function isArray(value) {
// check native isArray first
if (Array.isArray) {
return Array.isArray(value);
}
return toString.call(value) === '[object Array]';
}
|
javascript
|
function isArray(value) {
// check native isArray first
if (Array.isArray) {
return Array.isArray(value);
}
return toString.call(value) === '[object Array]';
}
|
[
"function",
"isArray",
"(",
"value",
")",
"{",
"// check native isArray first",
"if",
"(",
"Array",
".",
"isArray",
")",
"{",
"return",
"Array",
".",
"isArray",
"(",
"value",
")",
";",
"}",
"return",
"toString",
".",
"call",
"(",
"value",
")",
"===",
"'[object Array]'",
";",
"}"
] |
Check if the given value is an array.
@category Validate
@param {*} value - The value to check.
@return {boolean} Returns 'true' if the given value is a string, else 'false'.
|
[
"Check",
"if",
"the",
"given",
"value",
"is",
"an",
"array",
"."
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1525-L1532
|
36,384 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
isEmpty
|
function isEmpty(variable) {
var emptyVariables = {
'undefined': true,
'null': true,
'number': false,
'boolean': false,
'function': false,
'regexp': false,
'date': false,
'error': false
};
var strType = globalHelpers.getType(variable);
var boolReturn = void 0;
if (emptyVariables.hasOwnProperty(strType)) {
boolReturn = emptyVariables[strType];
} else {
switch (strType) {
case 'object':
boolReturn = this.isObjectEmpty(variable);
break;
case 'string':
boolReturn = variable ? false : true;
break;
case 'array':
boolReturn = variable.length ? false : true;
break;
}
}
return boolReturn;
}
|
javascript
|
function isEmpty(variable) {
var emptyVariables = {
'undefined': true,
'null': true,
'number': false,
'boolean': false,
'function': false,
'regexp': false,
'date': false,
'error': false
};
var strType = globalHelpers.getType(variable);
var boolReturn = void 0;
if (emptyVariables.hasOwnProperty(strType)) {
boolReturn = emptyVariables[strType];
} else {
switch (strType) {
case 'object':
boolReturn = this.isObjectEmpty(variable);
break;
case 'string':
boolReturn = variable ? false : true;
break;
case 'array':
boolReturn = variable.length ? false : true;
break;
}
}
return boolReturn;
}
|
[
"function",
"isEmpty",
"(",
"variable",
")",
"{",
"var",
"emptyVariables",
"=",
"{",
"'undefined'",
":",
"true",
",",
"'null'",
":",
"true",
",",
"'number'",
":",
"false",
",",
"'boolean'",
":",
"false",
",",
"'function'",
":",
"false",
",",
"'regexp'",
":",
"false",
",",
"'date'",
":",
"false",
",",
"'error'",
":",
"false",
"}",
";",
"var",
"strType",
"=",
"globalHelpers",
".",
"getType",
"(",
"variable",
")",
";",
"var",
"boolReturn",
"=",
"void",
"0",
";",
"if",
"(",
"emptyVariables",
".",
"hasOwnProperty",
"(",
"strType",
")",
")",
"{",
"boolReturn",
"=",
"emptyVariables",
"[",
"strType",
"]",
";",
"}",
"else",
"{",
"switch",
"(",
"strType",
")",
"{",
"case",
"'object'",
":",
"boolReturn",
"=",
"this",
".",
"isObjectEmpty",
"(",
"variable",
")",
";",
"break",
";",
"case",
"'string'",
":",
"boolReturn",
"=",
"variable",
"?",
"false",
":",
"true",
";",
"break",
";",
"case",
"'array'",
":",
"boolReturn",
"=",
"variable",
".",
"length",
"?",
"false",
":",
"true",
";",
"break",
";",
"}",
"}",
"return",
"boolReturn",
";",
"}"
] |
is a given value empty? Objects, arrays, strings
@category Validate
|
[
"is",
"a",
"given",
"value",
"empty?",
"Objects",
"arrays",
"strings"
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1633-L1667
|
36,385 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
isJson
|
function isJson(str) {
try {
var obj = JSON.parse(str);
return this.isObject(obj);
} catch (e) {/* ignore */}
return false;
}
|
javascript
|
function isJson(str) {
try {
var obj = JSON.parse(str);
return this.isObject(obj);
} catch (e) {/* ignore */}
return false;
}
|
[
"function",
"isJson",
"(",
"str",
")",
"{",
"try",
"{",
"var",
"obj",
"=",
"JSON",
".",
"parse",
"(",
"str",
")",
";",
"return",
"this",
".",
"isObject",
"(",
"obj",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"/* ignore */",
"}",
"return",
"false",
";",
"}"
] |
Check if a string is a valid JSON.
@category Validate
@param {string} str - The string to check
@return {boolean}
|
[
"Check",
"if",
"a",
"string",
"is",
"a",
"valid",
"JSON",
"."
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1700-L1707
|
36,386 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
isNumber
|
function isNumber(value) {
var isNaN = Number.isNaN || window.isNaN;
return typeof value === 'number' && !isNaN(value);
}
|
javascript
|
function isNumber(value) {
var isNaN = Number.isNaN || window.isNaN;
return typeof value === 'number' && !isNaN(value);
}
|
[
"function",
"isNumber",
"(",
"value",
")",
"{",
"var",
"isNaN",
"=",
"Number",
".",
"isNaN",
"||",
"window",
".",
"isNaN",
";",
"return",
"typeof",
"value",
"===",
"'number'",
"&&",
"!",
"isNaN",
"(",
"value",
")",
";",
"}"
] |
Check if the given value is a number.
@category Validate
@param {*} value - The value to check.
@return {boolean} Returns 'true' if the given value is a number, else 'false'.
|
[
"Check",
"if",
"the",
"given",
"value",
"is",
"a",
"number",
"."
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1727-L1731
|
36,387 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
isObjectEmpty
|
function isObjectEmpty(obj) {
if (!this.isObject(obj)) {
return false;
}
for (var x in obj) {
if ({}.hasOwnProperty.call(obj, x)) {
return false;
}
}
return true;
}
|
javascript
|
function isObjectEmpty(obj) {
if (!this.isObject(obj)) {
return false;
}
for (var x in obj) {
if ({}.hasOwnProperty.call(obj, x)) {
return false;
}
}
return true;
}
|
[
"function",
"isObjectEmpty",
"(",
"obj",
")",
"{",
"if",
"(",
"!",
"this",
".",
"isObject",
"(",
"obj",
")",
")",
"{",
"return",
"false",
";",
"}",
"for",
"(",
"var",
"x",
"in",
"obj",
")",
"{",
"if",
"(",
"{",
"}",
".",
"hasOwnProperty",
".",
"call",
"(",
"obj",
",",
"x",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] |
Verify if as objects is empty
@category Validate
@param {object} obj - The object to verify
@return {boolean}
@example
isObjectEmpty({}); // true
|
[
"Verify",
"if",
"as",
"objects",
"is",
"empty"
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1768-L1780
|
36,388 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
isSameType
|
function isSameType(value, other) {
var tag = toString.call(value);
if (tag !== toString.call(other)) {
return false;
}
return true;
}
|
javascript
|
function isSameType(value, other) {
var tag = toString.call(value);
if (tag !== toString.call(other)) {
return false;
}
return true;
}
|
[
"function",
"isSameType",
"(",
"value",
",",
"other",
")",
"{",
"var",
"tag",
"=",
"toString",
".",
"call",
"(",
"value",
")",
";",
"if",
"(",
"tag",
"!==",
"toString",
".",
"call",
"(",
"other",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] |
are given values same type?
@category Validate
|
[
"are",
"given",
"values",
"same",
"type?"
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1843-L1851
|
36,389 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
arrayClone
|
function arrayClone(arr) {
var clone = new Array(arr.length);
this._forEach(arr, function (el, i) {
clone[i] = el;
});
return clone;
}
|
javascript
|
function arrayClone(arr) {
var clone = new Array(arr.length);
this._forEach(arr, function (el, i) {
clone[i] = el;
});
return clone;
}
|
[
"function",
"arrayClone",
"(",
"arr",
")",
"{",
"var",
"clone",
"=",
"new",
"Array",
"(",
"arr",
".",
"length",
")",
";",
"this",
".",
"_forEach",
"(",
"arr",
",",
"function",
"(",
"el",
",",
"i",
")",
"{",
"clone",
"[",
"i",
"]",
"=",
"el",
";",
"}",
")",
";",
"return",
"clone",
";",
"}"
] |
Creates a shallow clone of the array.
@param {Array} arr Array to clone
@return {Array} Array cloned
|
[
"Creates",
"a",
"shallow",
"clone",
"of",
"the",
"array",
"."
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1929-L1937
|
36,390 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
arrayFlatten
|
function arrayFlatten(arr, level) {
var self = this;
var result = [];
var current = 0;
level = level || Infinity;
self._forEach(arr, function (el) {
if (validateHelpers.isArray(el) && current < level) {
result = result.concat(self.arrayFlatten(el, level, current + 1));
} else {
result.push(el);
}
});
return result;
}
|
javascript
|
function arrayFlatten(arr, level) {
var self = this;
var result = [];
var current = 0;
level = level || Infinity;
self._forEach(arr, function (el) {
if (validateHelpers.isArray(el) && current < level) {
result = result.concat(self.arrayFlatten(el, level, current + 1));
} else {
result.push(el);
}
});
return result;
}
|
[
"function",
"arrayFlatten",
"(",
"arr",
",",
"level",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"result",
"=",
"[",
"]",
";",
"var",
"current",
"=",
"0",
";",
"level",
"=",
"level",
"||",
"Infinity",
";",
"self",
".",
"_forEach",
"(",
"arr",
",",
"function",
"(",
"el",
")",
"{",
"if",
"(",
"validateHelpers",
".",
"isArray",
"(",
"el",
")",
"&&",
"current",
"<",
"level",
")",
"{",
"result",
"=",
"result",
".",
"concat",
"(",
"self",
".",
"arrayFlatten",
"(",
"el",
",",
"level",
",",
"current",
"+",
"1",
")",
")",
";",
"}",
"else",
"{",
"result",
".",
"push",
"(",
"el",
")",
";",
"}",
"}",
")",
";",
"return",
"result",
";",
"}"
] |
Returns a flattened, one-dimensional copy of the array.
You can optionally specify a limit, which will only flatten to that depth.
@param {Array} arr Array to flatten
@param {Integer} level[Infinity] Depth
@return {Array}
|
[
"Returns",
"a",
"flattened",
"one",
"-",
"dimensional",
"copy",
"of",
"the",
"array",
".",
"You",
"can",
"optionally",
"specify",
"a",
"limit",
"which",
"will",
"only",
"flatten",
"to",
"that",
"depth",
"."
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1965-L1979
|
36,391 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
arraySample
|
function arraySample(arr, num, remove) {
var result = [];
var _num = void 0;
var _remove = void 0;
var single = void 0;
if (validateHelpers.isBoolean(num)) {
_remove = num;
} else {
_num = num;
_remove = remove;
}
if (validateHelpers.isUndefined(_num)) {
_num = 1;
single = true;
}
if (!_remove) {
arr = this.arrayClone(arr);
}
_num = Math.min(_num, arr.length);
for (var i = 0, index; i < _num; i += 1) {
index = Math.trunc(Math.random() * arr.length);
result.push(arr[index]);
arr.splice(index, 1);
}
return single ? result[0] : result;
}
|
javascript
|
function arraySample(arr, num, remove) {
var result = [];
var _num = void 0;
var _remove = void 0;
var single = void 0;
if (validateHelpers.isBoolean(num)) {
_remove = num;
} else {
_num = num;
_remove = remove;
}
if (validateHelpers.isUndefined(_num)) {
_num = 1;
single = true;
}
if (!_remove) {
arr = this.arrayClone(arr);
}
_num = Math.min(_num, arr.length);
for (var i = 0, index; i < _num; i += 1) {
index = Math.trunc(Math.random() * arr.length);
result.push(arr[index]);
arr.splice(index, 1);
}
return single ? result[0] : result;
}
|
[
"function",
"arraySample",
"(",
"arr",
",",
"num",
",",
"remove",
")",
"{",
"var",
"result",
"=",
"[",
"]",
";",
"var",
"_num",
"=",
"void",
"0",
";",
"var",
"_remove",
"=",
"void",
"0",
";",
"var",
"single",
"=",
"void",
"0",
";",
"if",
"(",
"validateHelpers",
".",
"isBoolean",
"(",
"num",
")",
")",
"{",
"_remove",
"=",
"num",
";",
"}",
"else",
"{",
"_num",
"=",
"num",
";",
"_remove",
"=",
"remove",
";",
"}",
"if",
"(",
"validateHelpers",
".",
"isUndefined",
"(",
"_num",
")",
")",
"{",
"_num",
"=",
"1",
";",
"single",
"=",
"true",
";",
"}",
"if",
"(",
"!",
"_remove",
")",
"{",
"arr",
"=",
"this",
".",
"arrayClone",
"(",
"arr",
")",
";",
"}",
"_num",
"=",
"Math",
".",
"min",
"(",
"_num",
",",
"arr",
".",
"length",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"index",
";",
"i",
"<",
"_num",
";",
"i",
"+=",
"1",
")",
"{",
"index",
"=",
"Math",
".",
"trunc",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"arr",
".",
"length",
")",
";",
"result",
".",
"push",
"(",
"arr",
"[",
"index",
"]",
")",
";",
"arr",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"}",
"return",
"single",
"?",
"result",
"[",
"0",
"]",
":",
"result",
";",
"}"
] |
Returns a random element from the array.
If num is passed, will return an array of num elements.
If remove is true, sampled elements will also be removed from the array.
remove can also be passed in place of num.
@param {Array} [arr] Array to sample
@param {Integer|Boolean} [num=1] Num of elements
@param {Boolean} [remove=false] Remove sampled elements
@return {String|Array}
|
[
"Returns",
"a",
"random",
"element",
"from",
"the",
"array",
".",
"If",
"num",
"is",
"passed",
"will",
"return",
"an",
"array",
"of",
"num",
"elements",
".",
"If",
"remove",
"is",
"true",
"sampled",
"elements",
"will",
"also",
"be",
"removed",
"from",
"the",
"array",
".",
"remove",
"can",
"also",
"be",
"passed",
"in",
"place",
"of",
"num",
"."
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2010-L2041
|
36,392 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
chunk
|
function chunk(array, size) {
size = Math.max(size, 0);
var length = array === null ? 0 : array.length;
if (!length || size < 1) {
return [];
}
var index = 0;
var resIndex = 0;
var result = new Array(Math.ceil(length / size));
while (index < length) {
result[resIndex++] = this.slice(array, index, index += size);
}
return result;
}
|
javascript
|
function chunk(array, size) {
size = Math.max(size, 0);
var length = array === null ? 0 : array.length;
if (!length || size < 1) {
return [];
}
var index = 0;
var resIndex = 0;
var result = new Array(Math.ceil(length / size));
while (index < length) {
result[resIndex++] = this.slice(array, index, index += size);
}
return result;
}
|
[
"function",
"chunk",
"(",
"array",
",",
"size",
")",
"{",
"size",
"=",
"Math",
".",
"max",
"(",
"size",
",",
"0",
")",
";",
"var",
"length",
"=",
"array",
"===",
"null",
"?",
"0",
":",
"array",
".",
"length",
";",
"if",
"(",
"!",
"length",
"||",
"size",
"<",
"1",
")",
"{",
"return",
"[",
"]",
";",
"}",
"var",
"index",
"=",
"0",
";",
"var",
"resIndex",
"=",
"0",
";",
"var",
"result",
"=",
"new",
"Array",
"(",
"Math",
".",
"ceil",
"(",
"length",
"/",
"size",
")",
")",
";",
"while",
"(",
"index",
"<",
"length",
")",
"{",
"result",
"[",
"resIndex",
"++",
"]",
"=",
"this",
".",
"slice",
"(",
"array",
",",
"index",
",",
"index",
"+=",
"size",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
Creates an array of elements split into groups the length of size.
If array can't be split evenly, the final chunk will be the remaining elements.
@category Array
@param {Array} array The array to proccess.
@param {Integer} [size=1] The length of each chunk.
@return {Array} Returns the new array of chunks.
@example
chunk(['a', 'b', 'c', 'd'], 2)
// => [['a', 'b'], ['c', 'd']]
chunk(['a', 'b', 'c', 'd'], 3)
// => [['a', 'b', 'c'], ['d']]
|
[
"Creates",
"an",
"array",
"of",
"elements",
"split",
"into",
"groups",
"the",
"length",
"of",
"size",
".",
"If",
"array",
"can",
"t",
"be",
"split",
"evenly",
"the",
"final",
"chunk",
"will",
"be",
"the",
"remaining",
"elements",
"."
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2073-L2090
|
36,393 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
cleanArray
|
function cleanArray(array) {
var newArray = [];
for (var i = 0, len = array.length; i < len; i += 1) {
if (array[i]) {
newArray.push(array[i]);
}
}
return newArray;
}
|
javascript
|
function cleanArray(array) {
var newArray = [];
for (var i = 0, len = array.length; i < len; i += 1) {
if (array[i]) {
newArray.push(array[i]);
}
}
return newArray;
}
|
[
"function",
"cleanArray",
"(",
"array",
")",
"{",
"var",
"newArray",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"array",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"1",
")",
"{",
"if",
"(",
"array",
"[",
"i",
"]",
")",
"{",
"newArray",
".",
"push",
"(",
"array",
"[",
"i",
"]",
")",
";",
"}",
"}",
"return",
"newArray",
";",
"}"
] |
Removes empty index from a array.
@category Array
@param {Array} arr - The array
@return {Array}
|
[
"Removes",
"empty",
"index",
"from",
"a",
"array",
"."
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2100-L2110
|
36,394 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
explode
|
function explode(str, separator, limit) {
if (!validateHelpers.isString(str)) {
throw new Error('\'str\' must be a String');
}
var arr = str.split(separator);
if (limit !== undefined && arr.length >= limit) {
arr.push(arr.splice(limit - 1).join(separator));
}
return arr;
}
|
javascript
|
function explode(str, separator, limit) {
if (!validateHelpers.isString(str)) {
throw new Error('\'str\' must be a String');
}
var arr = str.split(separator);
if (limit !== undefined && arr.length >= limit) {
arr.push(arr.splice(limit - 1).join(separator));
}
return arr;
}
|
[
"function",
"explode",
"(",
"str",
",",
"separator",
",",
"limit",
")",
"{",
"if",
"(",
"!",
"validateHelpers",
".",
"isString",
"(",
"str",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'\\'str\\' must be a String'",
")",
";",
"}",
"var",
"arr",
"=",
"str",
".",
"split",
"(",
"separator",
")",
";",
"if",
"(",
"limit",
"!==",
"undefined",
"&&",
"arr",
".",
"length",
">=",
"limit",
")",
"{",
"arr",
".",
"push",
"(",
"arr",
".",
"splice",
"(",
"limit",
"-",
"1",
")",
".",
"join",
"(",
"separator",
")",
")",
";",
"}",
"return",
"arr",
";",
"}"
] |
Split array elements by separator - PHP implode alike
@category Array
@param {String} str - String to split
@param {string} separator - The separator
@param {Number} limit - Limit splitted elements
@return {Array} The array with values
@example
explode('a', '.', 2); // ['a']
explode('a.b', '.', 2); // ['a', 'b']
explode('a.b.c', '.', 2); // ['a', 'b.c']
|
[
"Split",
"array",
"elements",
"by",
"separator",
"-",
"PHP",
"implode",
"alike"
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2126-L2138
|
36,395 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
implode
|
function implode(pieces, glue) {
if (validateHelpers.isArray(pieces)) {
return pieces.join(glue || ',');
} else if (validateHelpers.isObject(pieces)) {
var arr = [];
for (var o in pieces) {
if (object.hasOwnProperty(o)) {
arr.push(pieces[o]);
}
}
return arr.join(glue || ',');
}
return '';
}
|
javascript
|
function implode(pieces, glue) {
if (validateHelpers.isArray(pieces)) {
return pieces.join(glue || ',');
} else if (validateHelpers.isObject(pieces)) {
var arr = [];
for (var o in pieces) {
if (object.hasOwnProperty(o)) {
arr.push(pieces[o]);
}
}
return arr.join(glue || ',');
}
return '';
}
|
[
"function",
"implode",
"(",
"pieces",
",",
"glue",
")",
"{",
"if",
"(",
"validateHelpers",
".",
"isArray",
"(",
"pieces",
")",
")",
"{",
"return",
"pieces",
".",
"join",
"(",
"glue",
"||",
"','",
")",
";",
"}",
"else",
"if",
"(",
"validateHelpers",
".",
"isObject",
"(",
"pieces",
")",
")",
"{",
"var",
"arr",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"o",
"in",
"pieces",
")",
"{",
"if",
"(",
"object",
".",
"hasOwnProperty",
"(",
"o",
")",
")",
"{",
"arr",
".",
"push",
"(",
"pieces",
"[",
"o",
"]",
")",
";",
"}",
"}",
"return",
"arr",
".",
"join",
"(",
"glue",
"||",
"','",
")",
";",
"}",
"return",
"''",
";",
"}"
] |
Join array elements with glue string - PHP implode alike
@category Array
@param {object|array} pieces - The array|object to implode. If object it will implode the values, not the keys.
@param {string} [glue=','] - The glue
@return {string} The imploded array|object
@example
implode(['Foo', 'Bar']); // 'Foo,Bar'
|
[
"Join",
"array",
"elements",
"with",
"glue",
"string",
"-",
"PHP",
"implode",
"alike"
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2151-L2166
|
36,396 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
toNumber
|
function toNumber(value) {
var _this = this;
if (validateHelpers.isArray(value)) {
return value.map(function (a) {
return _this.toNumber(a);
});
}
var number = parseFloat(value);
if (number === undefined) {
return value;
}
if (number.toString().length !== value.toString().length && !validateHelpers.isNumeric(value)) {
return value;
}
return validateHelpers.isNumber(number) ? value : number;
}
|
javascript
|
function toNumber(value) {
var _this = this;
if (validateHelpers.isArray(value)) {
return value.map(function (a) {
return _this.toNumber(a);
});
}
var number = parseFloat(value);
if (number === undefined) {
return value;
}
if (number.toString().length !== value.toString().length && !validateHelpers.isNumeric(value)) {
return value;
}
return validateHelpers.isNumber(number) ? value : number;
}
|
[
"function",
"toNumber",
"(",
"value",
")",
"{",
"var",
"_this",
"=",
"this",
";",
"if",
"(",
"validateHelpers",
".",
"isArray",
"(",
"value",
")",
")",
"{",
"return",
"value",
".",
"map",
"(",
"function",
"(",
"a",
")",
"{",
"return",
"_this",
".",
"toNumber",
"(",
"a",
")",
";",
"}",
")",
";",
"}",
"var",
"number",
"=",
"parseFloat",
"(",
"value",
")",
";",
"if",
"(",
"number",
"===",
"undefined",
")",
"{",
"return",
"value",
";",
"}",
"if",
"(",
"number",
".",
"toString",
"(",
")",
".",
"length",
"!==",
"value",
".",
"toString",
"(",
")",
".",
"length",
"&&",
"!",
"validateHelpers",
".",
"isNumeric",
"(",
"value",
")",
")",
"{",
"return",
"value",
";",
"}",
"return",
"validateHelpers",
".",
"isNumber",
"(",
"number",
")",
"?",
"value",
":",
"number",
";",
"}"
] |
Converts a value to a number if possible.
@category Global
@param {Mix} value The value to convert.
@returns {Number} The converted number, otherwise the original value.
@example
toNumber('123') // 123
toNumber('123.456') // 123.456
|
[
"Converts",
"a",
"value",
"to",
"a",
"number",
"if",
"possible",
"."
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2414-L2434
|
36,397 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
extend
|
function extend(obj) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (validateHelpers.isObject(obj) && args.length > 0) {
if (Object.assign) {
return Object.assign.apply(Object, [obj].concat(toConsumableArray(args)));
}
args.forEach(function (arg) {
if (validateHelpers.isObject(arg)) {
Object.keys(arg).forEach(function (key) {
obj[key] = arg[key];
});
}
});
}
return obj;
}
|
javascript
|
function extend(obj) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (validateHelpers.isObject(obj) && args.length > 0) {
if (Object.assign) {
return Object.assign.apply(Object, [obj].concat(toConsumableArray(args)));
}
args.forEach(function (arg) {
if (validateHelpers.isObject(arg)) {
Object.keys(arg).forEach(function (key) {
obj[key] = arg[key];
});
}
});
}
return obj;
}
|
[
"function",
"extend",
"(",
"obj",
")",
"{",
"for",
"(",
"var",
"_len",
"=",
"arguments",
".",
"length",
",",
"args",
"=",
"Array",
"(",
"_len",
">",
"1",
"?",
"_len",
"-",
"1",
":",
"0",
")",
",",
"_key",
"=",
"1",
";",
"_key",
"<",
"_len",
";",
"_key",
"++",
")",
"{",
"args",
"[",
"_key",
"-",
"1",
"]",
"=",
"arguments",
"[",
"_key",
"]",
";",
"}",
"if",
"(",
"validateHelpers",
".",
"isObject",
"(",
"obj",
")",
"&&",
"args",
".",
"length",
">",
"0",
")",
"{",
"if",
"(",
"Object",
".",
"assign",
")",
"{",
"return",
"Object",
".",
"assign",
".",
"apply",
"(",
"Object",
",",
"[",
"obj",
"]",
".",
"concat",
"(",
"toConsumableArray",
"(",
"args",
")",
")",
")",
";",
"}",
"args",
".",
"forEach",
"(",
"function",
"(",
"arg",
")",
"{",
"if",
"(",
"validateHelpers",
".",
"isObject",
"(",
"arg",
")",
")",
"{",
"Object",
".",
"keys",
"(",
"arg",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"obj",
"[",
"key",
"]",
"=",
"arg",
"[",
"key",
"]",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
"return",
"obj",
";",
"}"
] |
Extend the given object
@param {object} obj - The object to be extended
@param {*} args - The rest objects which will be merged to the first object
@return {object} The extended object
|
[
"Extend",
"the",
"given",
"object"
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2466-L2486
|
36,398 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
getDescendantProp
|
function getDescendantProp(obj, path) {
if (!validateHelpers.isPlainObject(obj)) {
throw new TypeError('\'obj\' param must be an plain object');
}
return path.split('.').reduce(function (acc, part) {
return acc && acc[part];
}, obj);
}
|
javascript
|
function getDescendantProp(obj, path) {
if (!validateHelpers.isPlainObject(obj)) {
throw new TypeError('\'obj\' param must be an plain object');
}
return path.split('.').reduce(function (acc, part) {
return acc && acc[part];
}, obj);
}
|
[
"function",
"getDescendantProp",
"(",
"obj",
",",
"path",
")",
"{",
"if",
"(",
"!",
"validateHelpers",
".",
"isPlainObject",
"(",
"obj",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'\\'obj\\' param must be an plain object'",
")",
";",
"}",
"return",
"path",
".",
"split",
"(",
"'.'",
")",
".",
"reduce",
"(",
"function",
"(",
"acc",
",",
"part",
")",
"{",
"return",
"acc",
"&&",
"acc",
"[",
"part",
"]",
";",
"}",
",",
"obj",
")",
";",
"}"
] |
A function to take a string written in dot notation style, and use it to
find a nested object property inside of an object.
@param {Object} obj The object to search
@param {String} path A dot notation style parameter reference (ie 'a.b.c')
@returns the value of the property in question
|
[
"A",
"function",
"to",
"take",
"a",
"string",
"written",
"in",
"dot",
"notation",
"style",
"and",
"use",
"it",
"to",
"find",
"a",
"nested",
"object",
"property",
"inside",
"of",
"an",
"object",
"."
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2498-L2506
|
36,399 |
Zeindelf/utilify-js
|
dist/utilify.esm.js
|
groupObjectByValue
|
function groupObjectByValue(item, key) {
var camelize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (!validateHelpers.isArray(item)) {
throw new Error('\'item\' must be an array of objects');
}
var grouped = item.reduce(function (r, a) {
r[a[key]] = r[a[key]] || [];
r[a[key]].push(a);
return r;
}, Object.create(null));
return camelize ? globalHelpers.camelize(grouped) : grouped;
}
|
javascript
|
function groupObjectByValue(item, key) {
var camelize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (!validateHelpers.isArray(item)) {
throw new Error('\'item\' must be an array of objects');
}
var grouped = item.reduce(function (r, a) {
r[a[key]] = r[a[key]] || [];
r[a[key]].push(a);
return r;
}, Object.create(null));
return camelize ? globalHelpers.camelize(grouped) : grouped;
}
|
[
"function",
"groupObjectByValue",
"(",
"item",
",",
"key",
")",
"{",
"var",
"camelize",
"=",
"arguments",
".",
"length",
">",
"2",
"&&",
"arguments",
"[",
"2",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"2",
"]",
":",
"false",
";",
"if",
"(",
"!",
"validateHelpers",
".",
"isArray",
"(",
"item",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'\\'item\\' must be an array of objects'",
")",
";",
"}",
"var",
"grouped",
"=",
"item",
".",
"reduce",
"(",
"function",
"(",
"r",
",",
"a",
")",
"{",
"r",
"[",
"a",
"[",
"key",
"]",
"]",
"=",
"r",
"[",
"a",
"[",
"key",
"]",
"]",
"||",
"[",
"]",
";",
"r",
"[",
"a",
"[",
"key",
"]",
"]",
".",
"push",
"(",
"a",
")",
";",
"return",
"r",
";",
"}",
",",
"Object",
".",
"create",
"(",
"null",
")",
")",
";",
"return",
"camelize",
"?",
"globalHelpers",
".",
"camelize",
"(",
"grouped",
")",
":",
"grouped",
";",
"}"
] |
Group an array of objects by same properties value
Returns new object with a key grouped values
@param {Array} item An array of objects
@param {String} key The key where the values are grouped
@param {Boolean} camelize Camlize key (e.g. 'John Smith' or 'john-smith' turn into johnSmith)
@returns {Object}
@example
const objToGroup = [
{ name: 'John', age: 20 },
{ name: 'Mary', age: 20 },
{ name: 'Smith', age: 18 },
{ name: 'John', age: 22 }
];
groupObjectByValue(objToGroup, 'age') // { 18: [{ name: 'Smith', age: 18 }], 20: [{ name: 'John', age: 20 }, { name: 'Mary', age: 20 }], 22: { name: 'John', age: 22 } }
groupObjectByValue(objToGroup, 'name', true) // { john: [{ name: 'John', age: 22 }, { name: 'John', age: 20 }], mary: [{ name: 'Mary', age: 20 }], smith: [{ name: 'Smith', age: 18 }] }
|
[
"Group",
"an",
"array",
"of",
"objects",
"by",
"same",
"properties",
"value",
"Returns",
"new",
"object",
"with",
"a",
"key",
"grouped",
"values"
] |
a16f6e578c953b10cec5ca89c06aeba73ff6674f
|
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2528-L2542
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.