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
20,300
infusion/Polynomial.js
polynomial.js
degree
function degree(x) { var i = Number.NEGATIVE_INFINITY; for (var k in x) { if (!FIELD['empty'](x[k])) i = Math.max(k, i); } return i; }
javascript
function degree(x) { var i = Number.NEGATIVE_INFINITY; for (var k in x) { if (!FIELD['empty'](x[k])) i = Math.max(k, i); } return i; }
[ "function", "degree", "(", "x", ")", "{", "var", "i", "=", "Number", ".", "NEGATIVE_INFINITY", ";", "for", "(", "var", "k", "in", "x", ")", "{", "if", "(", "!", "FIELD", "[", "'empty'", "]", "(", "x", "[", "k", "]", ")", ")", "i", "=", "Math", ".", "max", "(", "k", ",", "i", ")", ";", "}", "return", "i", ";", "}" ]
Gets the degree of the actual polynomial @param {Object} x @returns {number}
[ "Gets", "the", "degree", "of", "the", "actual", "polynomial" ]
c291420de240107695ad1799d8947e85be416bed
https://github.com/infusion/Polynomial.js/blob/c291420de240107695ad1799d8947e85be416bed/polynomial.js#L228-L237
20,301
infusion/Polynomial.js
polynomial.js
function(x, y) { var r = {}; var i = degree(x); var j = degree(y); var trace = []; while (i >= j) { var tmp = r[i - j] = FIELD['div'](x[i] || 0, y[j] || 0); for (var k in y) { x[+k + i - j] = FIELD['sub'](x[+k + i - j] || 0, FIELD['mul'](y[k] || 0, tmp)); } if (Polynomial['trace'] !== null) { var tr = {}; for (var k in y) { tr[+k + i - j] = FIELD['mul'](y[k] || 0, tmp); } trace.push(new Polynomial(tr)); } i = degree(x); } // Add rest if (Polynomial['trace'] !== null) { trace.push(new Polynomial(x)); Polynomial['trace'] = trace; } return r; }
javascript
function(x, y) { var r = {}; var i = degree(x); var j = degree(y); var trace = []; while (i >= j) { var tmp = r[i - j] = FIELD['div'](x[i] || 0, y[j] || 0); for (var k in y) { x[+k + i - j] = FIELD['sub'](x[+k + i - j] || 0, FIELD['mul'](y[k] || 0, tmp)); } if (Polynomial['trace'] !== null) { var tr = {}; for (var k in y) { tr[+k + i - j] = FIELD['mul'](y[k] || 0, tmp); } trace.push(new Polynomial(tr)); } i = degree(x); } // Add rest if (Polynomial['trace'] !== null) { trace.push(new Polynomial(x)); Polynomial['trace'] = trace; } return r; }
[ "function", "(", "x", ",", "y", ")", "{", "var", "r", "=", "{", "}", ";", "var", "i", "=", "degree", "(", "x", ")", ";", "var", "j", "=", "degree", "(", "y", ")", ";", "var", "trace", "=", "[", "]", ";", "while", "(", "i", ">=", "j", ")", "{", "var", "tmp", "=", "r", "[", "i", "-", "j", "]", "=", "FIELD", "[", "'div'", "]", "(", "x", "[", "i", "]", "||", "0", ",", "y", "[", "j", "]", "||", "0", ")", ";", "for", "(", "var", "k", "in", "y", ")", "{", "x", "[", "+", "k", "+", "i", "-", "j", "]", "=", "FIELD", "[", "'sub'", "]", "(", "x", "[", "+", "k", "+", "i", "-", "j", "]", "||", "0", ",", "FIELD", "[", "'mul'", "]", "(", "y", "[", "k", "]", "||", "0", ",", "tmp", ")", ")", ";", "}", "if", "(", "Polynomial", "[", "'trace'", "]", "!==", "null", ")", "{", "var", "tr", "=", "{", "}", ";", "for", "(", "var", "k", "in", "y", ")", "{", "tr", "[", "+", "k", "+", "i", "-", "j", "]", "=", "FIELD", "[", "'mul'", "]", "(", "y", "[", "k", "]", "||", "0", ",", "tmp", ")", ";", "}", "trace", ".", "push", "(", "new", "Polynomial", "(", "tr", ")", ")", ";", "}", "i", "=", "degree", "(", "x", ")", ";", "}", "// Add rest", "if", "(", "Polynomial", "[", "'trace'", "]", "!==", "null", ")", "{", "trace", ".", "push", "(", "new", "Polynomial", "(", "x", ")", ")", ";", "Polynomial", "[", "'trace'", "]", "=", "trace", ";", "}", "return", "r", ";", "}" ]
Helper function for division @param {Object} x The numerator coefficients @param {Object} y The denominator coefficients @returns {Object}
[ "Helper", "function", "for", "division" ]
c291420de240107695ad1799d8947e85be416bed
https://github.com/infusion/Polynomial.js/blob/c291420de240107695ad1799d8947e85be416bed/polynomial.js#L246-L280
20,302
infusion/Polynomial.js
polynomial.js
function(x) { var ret = {}; if (x === null || x === undefined) { x = 0; } switch (typeof x) { case "object": if (x['coeff']) { x = x['coeff']; } if (Fraction && x instanceof Fraction || Complex && x instanceof Complex || Quaternion && x instanceof Quaternion) { ret[0] = x; } else // Handles Arrays the same way for (var i in x) { if (!FIELD['empty'](x[i])) { ret[i] = FIELD['parse'](x[i]); } } return ret; case "number": return {'0': FIELD['parse'](x)}; case "string": var tmp; while (null !== (tmp = STR_REGEXP['exec'](x))) { var num = 1; var exp = 1; if (tmp[4] !== undefined) { num = tmp[4]; exp = 0; } else if (tmp[2] !== undefined) { num = tmp[2]; } num = parseExp(tmp[1], num); // Parse exponent if (tmp[3] !== undefined) { exp = parseInt(tmp[3], 10); } if (ret[exp] === undefined) { ret[exp] = num; } else { ret[exp] = FIELD['add'](ret[exp], num); } } return ret; } throw "Invalid Param"; }
javascript
function(x) { var ret = {}; if (x === null || x === undefined) { x = 0; } switch (typeof x) { case "object": if (x['coeff']) { x = x['coeff']; } if (Fraction && x instanceof Fraction || Complex && x instanceof Complex || Quaternion && x instanceof Quaternion) { ret[0] = x; } else // Handles Arrays the same way for (var i in x) { if (!FIELD['empty'](x[i])) { ret[i] = FIELD['parse'](x[i]); } } return ret; case "number": return {'0': FIELD['parse'](x)}; case "string": var tmp; while (null !== (tmp = STR_REGEXP['exec'](x))) { var num = 1; var exp = 1; if (tmp[4] !== undefined) { num = tmp[4]; exp = 0; } else if (tmp[2] !== undefined) { num = tmp[2]; } num = parseExp(tmp[1], num); // Parse exponent if (tmp[3] !== undefined) { exp = parseInt(tmp[3], 10); } if (ret[exp] === undefined) { ret[exp] = num; } else { ret[exp] = FIELD['add'](ret[exp], num); } } return ret; } throw "Invalid Param"; }
[ "function", "(", "x", ")", "{", "var", "ret", "=", "{", "}", ";", "if", "(", "x", "===", "null", "||", "x", "===", "undefined", ")", "{", "x", "=", "0", ";", "}", "switch", "(", "typeof", "x", ")", "{", "case", "\"object\"", ":", "if", "(", "x", "[", "'coeff'", "]", ")", "{", "x", "=", "x", "[", "'coeff'", "]", ";", "}", "if", "(", "Fraction", "&&", "x", "instanceof", "Fraction", "||", "Complex", "&&", "x", "instanceof", "Complex", "||", "Quaternion", "&&", "x", "instanceof", "Quaternion", ")", "{", "ret", "[", "0", "]", "=", "x", ";", "}", "else", "// Handles Arrays the same way", "for", "(", "var", "i", "in", "x", ")", "{", "if", "(", "!", "FIELD", "[", "'empty'", "]", "(", "x", "[", "i", "]", ")", ")", "{", "ret", "[", "i", "]", "=", "FIELD", "[", "'parse'", "]", "(", "x", "[", "i", "]", ")", ";", "}", "}", "return", "ret", ";", "case", "\"number\"", ":", "return", "{", "'0'", ":", "FIELD", "[", "'parse'", "]", "(", "x", ")", "}", ";", "case", "\"string\"", ":", "var", "tmp", ";", "while", "(", "null", "!==", "(", "tmp", "=", "STR_REGEXP", "[", "'exec'", "]", "(", "x", ")", ")", ")", "{", "var", "num", "=", "1", ";", "var", "exp", "=", "1", ";", "if", "(", "tmp", "[", "4", "]", "!==", "undefined", ")", "{", "num", "=", "tmp", "[", "4", "]", ";", "exp", "=", "0", ";", "}", "else", "if", "(", "tmp", "[", "2", "]", "!==", "undefined", ")", "{", "num", "=", "tmp", "[", "2", "]", ";", "}", "num", "=", "parseExp", "(", "tmp", "[", "1", "]", ",", "num", ")", ";", "// Parse exponent", "if", "(", "tmp", "[", "3", "]", "!==", "undefined", ")", "{", "exp", "=", "parseInt", "(", "tmp", "[", "3", "]", ",", "10", ")", ";", "}", "if", "(", "ret", "[", "exp", "]", "===", "undefined", ")", "{", "ret", "[", "exp", "]", "=", "num", ";", "}", "else", "{", "ret", "[", "exp", "]", "=", "FIELD", "[", "'add'", "]", "(", "ret", "[", "exp", "]", ",", "num", ")", ";", "}", "}", "return", "ret", ";", "}", "throw", "\"Invalid Param\"", ";", "}" ]
Parses the actual number @param {String|Object|null|number} x The polynomial to be parsed @returns {Object}
[ "Parses", "the", "actual", "number" ]
c291420de240107695ad1799d8947e85be416bed
https://github.com/infusion/Polynomial.js/blob/c291420de240107695ad1799d8947e85be416bed/polynomial.js#L305-L368
20,303
infusion/Polynomial.js
polynomial.js
function(fn) { /** * The actual to string function * * @returns {string|null} */ var Str = function() { var poly = this['coeff']; var keys = []; for (var i in poly) { keys.push(+i); } if (keys.length === 0) return "0"; keys.sort(function(a, b) { return a - b; }); var str = ""; for (var k = keys.length; k--; ) { var i = keys[k]; var cur = poly[i]; var val = cur; if (val === null || val === undefined) continue; if (Complex && val instanceof Complex) { // Add real part if (val['re'] !== 0) { if (str !== "" && val['re'] > 0) { str += "+"; } if (val['re'] === -1 && i !== 0) { str += "-"; } else if (val['re'] !== 1 || i === 0) { str += val['re']; } // Add exponent if necessary, no DRY, let's feed gzip if (i === 1) str += "x"; else if (i !== 0) str += "x^" + i; } // Add imaginary part if (val['im'] !== 0) { if (str !== "" && val['im'] > 0) { str += "+"; } if (val['im'] === -1) { str += "-"; } else if (val['im'] !== 1) { str += val['im']; } str += "i"; // Add exponent if necessary, no DRY, let's feed gzip if (i === 1) str += "x"; else if (i !== 0) str += "x^" + i; } } else { val = val.valueOf(); // Skip if it's zero if (val === 0) continue; // Separate by + if (str !== "" && val > 0) { str += "+"; } if (val === -1 && i !== 0) str += "-"; else // Add number if it's not a "1" or the first position if (val !== 1 || i === 0) str += cur[fn] ? cur[fn]() : cur['toString'](); // Add exponent if necessary, no DRY, let's feed gzip if (i === 1) str += "x"; else if (i !== 0) str += "x^" + i; } } if (str === "") return cur[fn] ? cur[fn]() : cur['toString'](); return str; }; return Str; }
javascript
function(fn) { /** * The actual to string function * * @returns {string|null} */ var Str = function() { var poly = this['coeff']; var keys = []; for (var i in poly) { keys.push(+i); } if (keys.length === 0) return "0"; keys.sort(function(a, b) { return a - b; }); var str = ""; for (var k = keys.length; k--; ) { var i = keys[k]; var cur = poly[i]; var val = cur; if (val === null || val === undefined) continue; if (Complex && val instanceof Complex) { // Add real part if (val['re'] !== 0) { if (str !== "" && val['re'] > 0) { str += "+"; } if (val['re'] === -1 && i !== 0) { str += "-"; } else if (val['re'] !== 1 || i === 0) { str += val['re']; } // Add exponent if necessary, no DRY, let's feed gzip if (i === 1) str += "x"; else if (i !== 0) str += "x^" + i; } // Add imaginary part if (val['im'] !== 0) { if (str !== "" && val['im'] > 0) { str += "+"; } if (val['im'] === -1) { str += "-"; } else if (val['im'] !== 1) { str += val['im']; } str += "i"; // Add exponent if necessary, no DRY, let's feed gzip if (i === 1) str += "x"; else if (i !== 0) str += "x^" + i; } } else { val = val.valueOf(); // Skip if it's zero if (val === 0) continue; // Separate by + if (str !== "" && val > 0) { str += "+"; } if (val === -1 && i !== 0) str += "-"; else // Add number if it's not a "1" or the first position if (val !== 1 || i === 0) str += cur[fn] ? cur[fn]() : cur['toString'](); // Add exponent if necessary, no DRY, let's feed gzip if (i === 1) str += "x"; else if (i !== 0) str += "x^" + i; } } if (str === "") return cur[fn] ? cur[fn]() : cur['toString'](); return str; }; return Str; }
[ "function", "(", "fn", ")", "{", "/**\n * The actual to string function \n * \n * @returns {string|null}\n */", "var", "Str", "=", "function", "(", ")", "{", "var", "poly", "=", "this", "[", "'coeff'", "]", ";", "var", "keys", "=", "[", "]", ";", "for", "(", "var", "i", "in", "poly", ")", "{", "keys", ".", "push", "(", "+", "i", ")", ";", "}", "if", "(", "keys", ".", "length", "===", "0", ")", "return", "\"0\"", ";", "keys", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", "-", "b", ";", "}", ")", ";", "var", "str", "=", "\"\"", ";", "for", "(", "var", "k", "=", "keys", ".", "length", ";", "k", "--", ";", ")", "{", "var", "i", "=", "keys", "[", "k", "]", ";", "var", "cur", "=", "poly", "[", "i", "]", ";", "var", "val", "=", "cur", ";", "if", "(", "val", "===", "null", "||", "val", "===", "undefined", ")", "continue", ";", "if", "(", "Complex", "&&", "val", "instanceof", "Complex", ")", "{", "// Add real part", "if", "(", "val", "[", "'re'", "]", "!==", "0", ")", "{", "if", "(", "str", "!==", "\"\"", "&&", "val", "[", "'re'", "]", ">", "0", ")", "{", "str", "+=", "\"+\"", ";", "}", "if", "(", "val", "[", "'re'", "]", "===", "-", "1", "&&", "i", "!==", "0", ")", "{", "str", "+=", "\"-\"", ";", "}", "else", "if", "(", "val", "[", "'re'", "]", "!==", "1", "||", "i", "===", "0", ")", "{", "str", "+=", "val", "[", "'re'", "]", ";", "}", "// Add exponent if necessary, no DRY, let's feed gzip", "if", "(", "i", "===", "1", ")", "str", "+=", "\"x\"", ";", "else", "if", "(", "i", "!==", "0", ")", "str", "+=", "\"x^\"", "+", "i", ";", "}", "// Add imaginary part", "if", "(", "val", "[", "'im'", "]", "!==", "0", ")", "{", "if", "(", "str", "!==", "\"\"", "&&", "val", "[", "'im'", "]", ">", "0", ")", "{", "str", "+=", "\"+\"", ";", "}", "if", "(", "val", "[", "'im'", "]", "===", "-", "1", ")", "{", "str", "+=", "\"-\"", ";", "}", "else", "if", "(", "val", "[", "'im'", "]", "!==", "1", ")", "{", "str", "+=", "val", "[", "'im'", "]", ";", "}", "str", "+=", "\"i\"", ";", "// Add exponent if necessary, no DRY, let's feed gzip", "if", "(", "i", "===", "1", ")", "str", "+=", "\"x\"", ";", "else", "if", "(", "i", "!==", "0", ")", "str", "+=", "\"x^\"", "+", "i", ";", "}", "}", "else", "{", "val", "=", "val", ".", "valueOf", "(", ")", ";", "// Skip if it's zero", "if", "(", "val", "===", "0", ")", "continue", ";", "// Separate by +", "if", "(", "str", "!==", "\"\"", "&&", "val", ">", "0", ")", "{", "str", "+=", "\"+\"", ";", "}", "if", "(", "val", "===", "-", "1", "&&", "i", "!==", "0", ")", "str", "+=", "\"-\"", ";", "else", "// Add number if it's not a \"1\" or the first position", "if", "(", "val", "!==", "1", "||", "i", "===", "0", ")", "str", "+=", "cur", "[", "fn", "]", "?", "cur", "[", "fn", "]", "(", ")", ":", "cur", "[", "'toString'", "]", "(", ")", ";", "// Add exponent if necessary, no DRY, let's feed gzip", "if", "(", "i", "===", "1", ")", "str", "+=", "\"x\"", ";", "else", "if", "(", "i", "!==", "0", ")", "str", "+=", "\"x^\"", "+", "i", ";", "}", "}", "if", "(", "str", "===", "\"\"", ")", "return", "cur", "[", "fn", "]", "?", "cur", "[", "fn", "]", "(", ")", ":", "cur", "[", "'toString'", "]", "(", ")", ";", "return", "str", ";", "}", ";", "return", "Str", ";", "}" ]
Helper method to stringify @param {string} fn the callback name @returns {Function}
[ "Helper", "method", "to", "stringify" ]
c291420de240107695ad1799d8947e85be416bed
https://github.com/infusion/Polynomial.js/blob/c291420de240107695ad1799d8947e85be416bed/polynomial.js#L776-L890
20,304
infusion/Polynomial.js
examples/factor.js
factor
function factor(P) { var xn = 1; var F = Polynomial(P); // f(x) var f = F['derive'](); // f'(x) var res = []; do { var prev, xn = Polynomial(1).coeff[0]; var k = 0; do { prev = xn; //xn = FIELD['sub'](xn, FIELD.div(F.result(xn), f.result(xn))); xn = xn.sub(F.result(xn).div(f.result(xn))); } while (k++ === 0 || Math.abs(xn.valueOf() - prev.valueOf()) > 1e-8); var p = Polynomial("x").sub(xn); // x-x0 F = F.div(p); f = F.derive(); res.push(xn); } while (f.degree() >= 0); return res; }
javascript
function factor(P) { var xn = 1; var F = Polynomial(P); // f(x) var f = F['derive'](); // f'(x) var res = []; do { var prev, xn = Polynomial(1).coeff[0]; var k = 0; do { prev = xn; //xn = FIELD['sub'](xn, FIELD.div(F.result(xn), f.result(xn))); xn = xn.sub(F.result(xn).div(f.result(xn))); } while (k++ === 0 || Math.abs(xn.valueOf() - prev.valueOf()) > 1e-8); var p = Polynomial("x").sub(xn); // x-x0 F = F.div(p); f = F.derive(); res.push(xn); } while (f.degree() >= 0); return res; }
[ "function", "factor", "(", "P", ")", "{", "var", "xn", "=", "1", ";", "var", "F", "=", "Polynomial", "(", "P", ")", ";", "// f(x)", "var", "f", "=", "F", "[", "'derive'", "]", "(", ")", ";", "// f'(x)", "var", "res", "=", "[", "]", ";", "do", "{", "var", "prev", ",", "xn", "=", "Polynomial", "(", "1", ")", ".", "coeff", "[", "0", "]", ";", "var", "k", "=", "0", ";", "do", "{", "prev", "=", "xn", ";", "//xn = FIELD['sub'](xn, FIELD.div(F.result(xn), f.result(xn)));", "xn", "=", "xn", ".", "sub", "(", "F", ".", "result", "(", "xn", ")", ".", "div", "(", "f", ".", "result", "(", "xn", ")", ")", ")", ";", "}", "while", "(", "k", "++", "===", "0", "||", "Math", ".", "abs", "(", "xn", ".", "valueOf", "(", ")", "-", "prev", ".", "valueOf", "(", ")", ")", ">", "1e-8", ")", ";", "var", "p", "=", "Polynomial", "(", "\"x\"", ")", ".", "sub", "(", "xn", ")", ";", "// x-x0", "F", "=", "F", ".", "div", "(", "p", ")", ";", "f", "=", "F", ".", "derive", "(", ")", ";", "res", ".", "push", "(", "xn", ")", ";", "}", "while", "(", "f", ".", "degree", "(", ")", ">=", "0", ")", ";", "return", "res", ";", "}" ]
This implements Newton's method on top of a rational polynomial. The code is highly experimental!
[ "This", "implements", "Newton", "s", "method", "on", "top", "of", "a", "rational", "polynomial", ".", "The", "code", "is", "highly", "experimental!" ]
c291420de240107695ad1799d8947e85be416bed
https://github.com/infusion/Polynomial.js/blob/c291420de240107695ad1799d8947e85be416bed/examples/factor.js#L8-L39
20,305
gerard2p/koaton
src/middleware/router.js
serveapp
function serveapp (directory) { /* istanbul ignore next */ return async function serveEmberAPP (ctx, next) { await next(); if (!ctx.body) { await ctx.render(directory); } }; }
javascript
function serveapp (directory) { /* istanbul ignore next */ return async function serveEmberAPP (ctx, next) { await next(); if (!ctx.body) { await ctx.render(directory); } }; }
[ "function", "serveapp", "(", "directory", ")", "{", "/* istanbul ignore next */", "return", "async", "function", "serveEmberAPP", "(", "ctx", ",", "next", ")", "{", "await", "next", "(", ")", ";", "if", "(", "!", "ctx", ".", "body", ")", "{", "await", "ctx", ".", "render", "(", "directory", ")", ";", "}", "}", ";", "}" ]
Creates the public handler for a EmberApp. @private @param {string} directory - The path where the EmberApp is located relative to public folder @return {async function(ctx: KoaContext, next: KoaNext)} renders the view
[ "Creates", "the", "public", "handler", "for", "a", "EmberApp", "." ]
4e38d30d4fc576c8949126bca70bbb812f80c3ec
https://github.com/gerard2p/koaton/blob/4e38d30d4fc576c8949126bca70bbb812f80c3ec/src/middleware/router.js#L16-L24
20,306
gerard2p/koaton
src/middleware/router.js
EvalRoute
function EvalRoute (ctx, next) { let router = this; let matched = router.match(router.opts.routerPath || ctx.routerPath || ctx.path, ctx.method); /* istanbul ignore else */ if (ctx.matched) { ctx.matched.push.apply(ctx.matched, matched.path); } else { ctx.matched = matched.path; } if (matched.route) { return this.middleware()(ctx, next); } else { return Promise.resolve('koaton-no-route'); } }
javascript
function EvalRoute (ctx, next) { let router = this; let matched = router.match(router.opts.routerPath || ctx.routerPath || ctx.path, ctx.method); /* istanbul ignore else */ if (ctx.matched) { ctx.matched.push.apply(ctx.matched, matched.path); } else { ctx.matched = matched.path; } if (matched.route) { return this.middleware()(ctx, next); } else { return Promise.resolve('koaton-no-route'); } }
[ "function", "EvalRoute", "(", "ctx", ",", "next", ")", "{", "let", "router", "=", "this", ";", "let", "matched", "=", "router", ".", "match", "(", "router", ".", "opts", ".", "routerPath", "||", "ctx", ".", "routerPath", "||", "ctx", ".", "path", ",", "ctx", ".", "method", ")", ";", "/* istanbul ignore else */", "if", "(", "ctx", ".", "matched", ")", "{", "ctx", ".", "matched", ".", "push", ".", "apply", "(", "ctx", ".", "matched", ",", "matched", ".", "path", ")", ";", "}", "else", "{", "ctx", ".", "matched", "=", "matched", ".", "path", ";", "}", "if", "(", "matched", ".", "route", ")", "{", "return", "this", ".", "middleware", "(", ")", "(", "ctx", ",", "next", ")", ";", "}", "else", "{", "return", "Promise", ".", "resolve", "(", "'koaton-no-route'", ")", ";", "}", "}" ]
Checks if the current route is valid matches with the given router @private @param {KoaContext} ctx @param {KoaNext} next @return {Object|String} if route does not math it will return 'koa-no-route'
[ "Checks", "if", "the", "current", "route", "is", "valid", "matches", "with", "the", "given", "router" ]
4e38d30d4fc576c8949126bca70bbb812f80c3ec
https://github.com/gerard2p/koaton/blob/4e38d30d4fc576c8949126bca70bbb812f80c3ec/src/middleware/router.js#L32-L46
20,307
gerard2p/koaton
src/support/secret.js
handle
function handle (fn) { return function (...args) { return new Promise((resolve) => { fn.bind(this)(...args, function (err, result) { /* istanbul ignore if */ if (err) { debug(err); } else { resolve(result); } }); }); }; }
javascript
function handle (fn) { return function (...args) { return new Promise((resolve) => { fn.bind(this)(...args, function (err, result) { /* istanbul ignore if */ if (err) { debug(err); } else { resolve(result); } }); }); }; }
[ "function", "handle", "(", "fn", ")", "{", "return", "function", "(", "...", "args", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ")", "=>", "{", "fn", ".", "bind", "(", "this", ")", "(", "...", "args", ",", "function", "(", "err", ",", "result", ")", "{", "/* istanbul ignore if */", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "}", "else", "{", "resolve", "(", "result", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", ";", "}" ]
If an error happes send it to debug function.
[ "If", "an", "error", "happes", "send", "it", "to", "debug", "function", "." ]
4e38d30d4fc576c8949126bca70bbb812f80c3ec
https://github.com/gerard2p/koaton/blob/4e38d30d4fc576c8949126bca70bbb812f80c3ec/src/support/secret.js#L7-L20
20,308
gerard2p/koaton
src/support/configuration.js
DeepDevOrProd
function DeepDevOrProd (object, prop) { let target = object[prop]; if (Object.keys(target).indexOf('dev') === -1 && typeof target === 'object') { for (const deep of Object.keys(target)) { DeepDevOrProd(object[prop], deep); } } else { if (Object.keys(target).indexOf('dev') === -1) { object[prop] = target; } else { object[prop] = isDev ? target.dev : /* istanbul ignore next */ target.prod; } } }
javascript
function DeepDevOrProd (object, prop) { let target = object[prop]; if (Object.keys(target).indexOf('dev') === -1 && typeof target === 'object') { for (const deep of Object.keys(target)) { DeepDevOrProd(object[prop], deep); } } else { if (Object.keys(target).indexOf('dev') === -1) { object[prop] = target; } else { object[prop] = isDev ? target.dev : /* istanbul ignore next */ target.prod; } } }
[ "function", "DeepDevOrProd", "(", "object", ",", "prop", ")", "{", "let", "target", "=", "object", "[", "prop", "]", ";", "if", "(", "Object", ".", "keys", "(", "target", ")", ".", "indexOf", "(", "'dev'", ")", "===", "-", "1", "&&", "typeof", "target", "===", "'object'", ")", "{", "for", "(", "const", "deep", "of", "Object", ".", "keys", "(", "target", ")", ")", "{", "DeepDevOrProd", "(", "object", "[", "prop", "]", ",", "deep", ")", ";", "}", "}", "else", "{", "if", "(", "Object", ".", "keys", "(", "target", ")", ".", "indexOf", "(", "'dev'", ")", "===", "-", "1", ")", "{", "object", "[", "prop", "]", "=", "target", ";", "}", "else", "{", "object", "[", "prop", "]", "=", "isDev", "?", "target", ".", "dev", ":", "/* istanbul ignore next */", "target", ".", "prod", ";", "}", "}", "}" ]
Creates an object based on its dev prod properties and merges them accordint to the current NODE_ENV This function is recursive and will transform the hole object @private @param {Object} object - target object to transform @param {String} prop - the property to look at @example {a:{dev:0,prod:1}} if NODE_ENV = 'development' -> {a:0}
[ "Creates", "an", "object", "based", "on", "its", "dev", "prod", "properties", "and", "merges", "them", "accordint", "to", "the", "current", "NODE_ENV", "This", "function", "is", "recursive", "and", "will", "transform", "the", "hole", "object" ]
4e38d30d4fc576c8949126bca70bbb812f80c3ec
https://github.com/gerard2p/koaton/blob/4e38d30d4fc576c8949126bca70bbb812f80c3ec/src/support/configuration.js#L16-L29
20,309
gerard2p/koaton
src/views/setup.js
handlebars
function handlebars () { const Handlebars = require(ProyPath('node_modules', 'handlebars')); const layouts = require(ProyPath('node_modules', 'handlebars-layouts')); Handlebars.registerHelper(layouts(Handlebars)); Handlebars.registerHelper('link', function (url, helper) { return makeLink(helper.data.root, url, helper.fn); }); // Bundles Handlebars.registerHelper('bundle', function (bundle) { if (Kmetadata.bundles[bundle] === undefined) { return ''; } return Kmetadata.bundles[bundle].toString(); }); // Localition Handlebars.registerHelper('i18n', _i18n); Handlebars.registerHelper('t', translate); const layoutFiles = glob(ProyPath('views', 'layouts', '*.handlebars')).concat(glob(ProyPath('koaton_modules', '**', 'views', 'layouts', '*.handlebars'))); for (const file of layoutFiles) { Handlebars.registerPartial(basename(file).replace('.handlebars', ''), fs.readFileSync(file, 'utf8')); } return Handlebars; }
javascript
function handlebars () { const Handlebars = require(ProyPath('node_modules', 'handlebars')); const layouts = require(ProyPath('node_modules', 'handlebars-layouts')); Handlebars.registerHelper(layouts(Handlebars)); Handlebars.registerHelper('link', function (url, helper) { return makeLink(helper.data.root, url, helper.fn); }); // Bundles Handlebars.registerHelper('bundle', function (bundle) { if (Kmetadata.bundles[bundle] === undefined) { return ''; } return Kmetadata.bundles[bundle].toString(); }); // Localition Handlebars.registerHelper('i18n', _i18n); Handlebars.registerHelper('t', translate); const layoutFiles = glob(ProyPath('views', 'layouts', '*.handlebars')).concat(glob(ProyPath('koaton_modules', '**', 'views', 'layouts', '*.handlebars'))); for (const file of layoutFiles) { Handlebars.registerPartial(basename(file).replace('.handlebars', ''), fs.readFileSync(file, 'utf8')); } return Handlebars; }
[ "function", "handlebars", "(", ")", "{", "const", "Handlebars", "=", "require", "(", "ProyPath", "(", "'node_modules'", ",", "'handlebars'", ")", ")", ";", "const", "layouts", "=", "require", "(", "ProyPath", "(", "'node_modules'", ",", "'handlebars-layouts'", ")", ")", ";", "Handlebars", ".", "registerHelper", "(", "layouts", "(", "Handlebars", ")", ")", ";", "Handlebars", ".", "registerHelper", "(", "'link'", ",", "function", "(", "url", ",", "helper", ")", "{", "return", "makeLink", "(", "helper", ".", "data", ".", "root", ",", "url", ",", "helper", ".", "fn", ")", ";", "}", ")", ";", "// Bundles", "Handlebars", ".", "registerHelper", "(", "'bundle'", ",", "function", "(", "bundle", ")", "{", "if", "(", "Kmetadata", ".", "bundles", "[", "bundle", "]", "===", "undefined", ")", "{", "return", "''", ";", "}", "return", "Kmetadata", ".", "bundles", "[", "bundle", "]", ".", "toString", "(", ")", ";", "}", ")", ";", "// Localition", "Handlebars", ".", "registerHelper", "(", "'i18n'", ",", "_i18n", ")", ";", "Handlebars", ".", "registerHelper", "(", "'t'", ",", "translate", ")", ";", "const", "layoutFiles", "=", "glob", "(", "ProyPath", "(", "'views'", ",", "'layouts'", ",", "'*.handlebars'", ")", ")", ".", "concat", "(", "glob", "(", "ProyPath", "(", "'koaton_modules'", ",", "'**'", ",", "'views'", ",", "'layouts'", ",", "'*.handlebars'", ")", ")", ")", ";", "for", "(", "const", "file", "of", "layoutFiles", ")", "{", "Handlebars", ".", "registerPartial", "(", "basename", "(", "file", ")", ".", "replace", "(", "'.handlebars'", ",", "''", ")", ",", "fs", ".", "readFileSync", "(", "file", ",", "'utf8'", ")", ")", ";", "}", "return", "Handlebars", ";", "}" ]
Initialize layout support for handlebars, bundle helper, i18n helpers @type {function} handlebars - returns the handlebars instance
[ "Initialize", "layout", "support", "for", "handlebars", "bundle", "helper", "i18n", "helpers" ]
4e38d30d4fc576c8949126bca70bbb812f80c3ec
https://github.com/gerard2p/koaton/blob/4e38d30d4fc576c8949126bca70bbb812f80c3ec/src/views/setup.js#L54-L76
20,310
gerard2p/koaton
src/support/KoatonRouter.js
findmodel
async function findmodel (ctx, next) { let pmodel = ctx.request.url.split('?')[0].split('/')[1]; ctx.model = ctx.db[pmodel]; ctx.state.model = ctx.state.db[pmodel]; await next(); }
javascript
async function findmodel (ctx, next) { let pmodel = ctx.request.url.split('?')[0].split('/')[1]; ctx.model = ctx.db[pmodel]; ctx.state.model = ctx.state.db[pmodel]; await next(); }
[ "async", "function", "findmodel", "(", "ctx", ",", "next", ")", "{", "let", "pmodel", "=", "ctx", ".", "request", ".", "url", ".", "split", "(", "'?'", ")", "[", "0", "]", ".", "split", "(", "'/'", ")", "[", "1", "]", ";", "ctx", ".", "model", "=", "ctx", ".", "db", "[", "pmodel", "]", ";", "ctx", ".", "state", ".", "model", "=", "ctx", ".", "state", ".", "db", "[", "pmodel", "]", ";", "await", "next", "(", ")", ";", "}" ]
Reads the model that is requested based on the route and appends model to ctx.state @param {KoaContext} ctx @param {KoaNext} next @param {JSURL} ctx.model - reference attached. DEPRECATED. @param {JSURL} ctx.state.model - reference attached.
[ "Reads", "the", "model", "that", "is", "requested", "based", "on", "the", "route", "and", "appends", "model", "to", "ctx", ".", "state" ]
4e38d30d4fc576c8949126bca70bbb812f80c3ec
https://github.com/gerard2p/koaton/blob/4e38d30d4fc576c8949126bca70bbb812f80c3ec/src/support/KoatonRouter.js#L18-L23
20,311
gerard2p/koaton
src/support/KoatonRouter.js
protect
async function protect (ctx, next) { if (ctx.isAuthenticated()) { await next(); } else { await passport.authenticate('bearer', { session: false }, async function (err, user) { // console.log(err, user); /* istanbul ignore if */ if (err) { throw err; } if (user === false) { ctx.body = null; ctx.status = 401; } else { ctx.state.user = user; await next(); } })(ctx); } }
javascript
async function protect (ctx, next) { if (ctx.isAuthenticated()) { await next(); } else { await passport.authenticate('bearer', { session: false }, async function (err, user) { // console.log(err, user); /* istanbul ignore if */ if (err) { throw err; } if (user === false) { ctx.body = null; ctx.status = 401; } else { ctx.state.user = user; await next(); } })(ctx); } }
[ "async", "function", "protect", "(", "ctx", ",", "next", ")", "{", "if", "(", "ctx", ".", "isAuthenticated", "(", ")", ")", "{", "await", "next", "(", ")", ";", "}", "else", "{", "await", "passport", ".", "authenticate", "(", "'bearer'", ",", "{", "session", ":", "false", "}", ",", "async", "function", "(", "err", ",", "user", ")", "{", "// console.log(err, user);", "/* istanbul ignore if */", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "if", "(", "user", "===", "false", ")", "{", "ctx", ".", "body", "=", "null", ";", "ctx", ".", "status", "=", "401", ";", "}", "else", "{", "ctx", ".", "state", ".", "user", "=", "user", ";", "await", "next", "(", ")", ";", "}", "}", ")", "(", "ctx", ")", ";", "}", "}" ]
Makes a route only accessible if user is logged in and appends model to ctx.state @param {KoaContext} ctx @param {KoaNext} next @return {Object} {status:401, body: null}
[ "Makes", "a", "route", "only", "accessible", "if", "user", "is", "logged", "in", "and", "appends", "model", "to", "ctx", ".", "state" ]
4e38d30d4fc576c8949126bca70bbb812f80c3ec
https://github.com/gerard2p/koaton/blob/4e38d30d4fc576c8949126bca70bbb812f80c3ec/src/support/KoatonRouter.js#L31-L52
20,312
gerard2p/koaton
src/middleware/orm.js
makerelation
function makerelation (model, relation) { let options = { as: relation.As, foreignKey: relation.key }; let target = exp.databases[inflector.pluralize(relation.Children)]; if (relation.Rel !== 'manyToMany') { exp.databases[model][relation.Rel](target, options); } else { exp.databases[model].prototype.many2many = exp.databases[model].prototype.many2many || {}; exp.databases[model].prototype.many2many[relation.Parent] = function (id, id2) { if (id && id2) { return exp.databases[relation.Children].findcre({ [`${model}ID`]: id, [`${relation.Parent}ID`]: id2 }); } return exp.databases[relation.Children].find({ where: { [`${model}ID`]: id } }).then(records => { let all = []; for (const record of records) { all.push(exp.databases[relation.Parent].findById(record[`${relation.Parent}ID`])); } return Promise.all(all); }); }; } }
javascript
function makerelation (model, relation) { let options = { as: relation.As, foreignKey: relation.key }; let target = exp.databases[inflector.pluralize(relation.Children)]; if (relation.Rel !== 'manyToMany') { exp.databases[model][relation.Rel](target, options); } else { exp.databases[model].prototype.many2many = exp.databases[model].prototype.many2many || {}; exp.databases[model].prototype.many2many[relation.Parent] = function (id, id2) { if (id && id2) { return exp.databases[relation.Children].findcre({ [`${model}ID`]: id, [`${relation.Parent}ID`]: id2 }); } return exp.databases[relation.Children].find({ where: { [`${model}ID`]: id } }).then(records => { let all = []; for (const record of records) { all.push(exp.databases[relation.Parent].findById(record[`${relation.Parent}ID`])); } return Promise.all(all); }); }; } }
[ "function", "makerelation", "(", "model", ",", "relation", ")", "{", "let", "options", "=", "{", "as", ":", "relation", ".", "As", ",", "foreignKey", ":", "relation", ".", "key", "}", ";", "let", "target", "=", "exp", ".", "databases", "[", "inflector", ".", "pluralize", "(", "relation", ".", "Children", ")", "]", ";", "if", "(", "relation", ".", "Rel", "!==", "'manyToMany'", ")", "{", "exp", ".", "databases", "[", "model", "]", "[", "relation", ".", "Rel", "]", "(", "target", ",", "options", ")", ";", "}", "else", "{", "exp", ".", "databases", "[", "model", "]", ".", "prototype", ".", "many2many", "=", "exp", ".", "databases", "[", "model", "]", ".", "prototype", ".", "many2many", "||", "{", "}", ";", "exp", ".", "databases", "[", "model", "]", ".", "prototype", ".", "many2many", "[", "relation", ".", "Parent", "]", "=", "function", "(", "id", ",", "id2", ")", "{", "if", "(", "id", "&&", "id2", ")", "{", "return", "exp", ".", "databases", "[", "relation", ".", "Children", "]", ".", "findcre", "(", "{", "[", "`", "${", "model", "}", "`", "]", ":", "id", ",", "[", "`", "${", "relation", ".", "Parent", "}", "`", "]", ":", "id2", "}", ")", ";", "}", "return", "exp", ".", "databases", "[", "relation", ".", "Children", "]", ".", "find", "(", "{", "where", ":", "{", "[", "`", "${", "model", "}", "`", "]", ":", "id", "}", "}", ")", ".", "then", "(", "records", "=>", "{", "let", "all", "=", "[", "]", ";", "for", "(", "const", "record", "of", "records", ")", "{", "all", ".", "push", "(", "exp", ".", "databases", "[", "relation", ".", "Parent", "]", ".", "findById", "(", "record", "[", "`", "${", "relation", ".", "Parent", "}", "`", "]", ")", ")", ";", "}", "return", "Promise", ".", "all", "(", "all", ")", ";", "}", ")", ";", "}", ";", "}", "}" ]
This function extends the CaminteJS relations, adding Many to Many support
[ "This", "function", "extends", "the", "CaminteJS", "relations", "adding", "Many", "to", "Many", "support" ]
4e38d30d4fc576c8949126bca70bbb812f80c3ec
https://github.com/gerard2p/koaton/blob/4e38d30d4fc576c8949126bca70bbb812f80c3ec/src/middleware/orm.js#L49-L79
20,313
gerard2p/koaton
src/middleware/auth.js
createUser
async function createUser (username, password, /* istanbul ignore next */ body = {}) { const user = await getUser(username, password); body[configuration.security.username] = username; body[configuration.security.password] = await hash(password, 5); if (user === null) { return AuthModel.create(body); } else { return Promise.resolve({ error: 'User Already Extis' }); } }
javascript
async function createUser (username, password, /* istanbul ignore next */ body = {}) { const user = await getUser(username, password); body[configuration.security.username] = username; body[configuration.security.password] = await hash(password, 5); if (user === null) { return AuthModel.create(body); } else { return Promise.resolve({ error: 'User Already Extis' }); } }
[ "async", "function", "createUser", "(", "username", ",", "password", ",", "/* istanbul ignore next */", "body", "=", "{", "}", ")", "{", "const", "user", "=", "await", "getUser", "(", "username", ",", "password", ")", ";", "body", "[", "configuration", ".", "security", ".", "username", "]", "=", "username", ";", "body", "[", "configuration", ".", "security", ".", "password", "]", "=", "await", "hash", "(", "password", ",", "5", ")", ";", "if", "(", "user", "===", "null", ")", "{", "return", "AuthModel", ".", "create", "(", "body", ")", ";", "}", "else", "{", "return", "Promise", ".", "resolve", "(", "{", "error", ":", "'User Already Extis'", "}", ")", ";", "}", "}" ]
Creates and user if it does not exits in the database. @param {String} username - Data that represents the username field in the target model. @param {String} passowrd - Unencrypted data that represents the username field in the target model. @param {Object} [body={}] - Information that might be passed to the model creation. @return {Promise<AuthModel>} - if callback is not set it will return a promise
[ "Creates", "and", "user", "if", "it", "does", "not", "exits", "in", "the", "database", "." ]
4e38d30d4fc576c8949126bca70bbb812f80c3ec
https://github.com/gerard2p/koaton/blob/4e38d30d4fc576c8949126bca70bbb812f80c3ec/src/middleware/auth.js#L57-L68
20,314
crystal-ball/componentry
demo/registry.js
deepRegister
function deepRegister(r) { r.keys().forEach(key => { const component = r(key) registry.register(component.default, component.registryName) }) }
javascript
function deepRegister(r) { r.keys().forEach(key => { const component = r(key) registry.register(component.default, component.registryName) }) }
[ "function", "deepRegister", "(", "r", ")", "{", "r", ".", "keys", "(", ")", ".", "forEach", "(", "key", "=>", "{", "const", "component", "=", "r", "(", "key", ")", "registry", ".", "register", "(", "component", ".", "default", ",", "component", ".", "registryName", ")", "}", ")", "}" ]
The require context passed to deepRegister has a keys method for iterating through all matched imports. Calling require on a key returns a cjs module that we use to register the component
[ "The", "require", "context", "passed", "to", "deepRegister", "has", "a", "keys", "method", "for", "iterating", "through", "all", "matched", "imports", ".", "Calling", "require", "on", "a", "key", "returns", "a", "cjs", "module", "that", "we", "use", "to", "register", "the", "component" ]
f76e0b4dcf86353fdd0fec4e4e50c75e7a93f8be
https://github.com/crystal-ball/componentry/blob/f76e0b4dcf86353fdd0fec4e4e50c75e7a93f8be/demo/registry.js#L31-L36
20,315
npm/gauge
progress-bar.js
repeat
function repeat (string, width) { var result = '' var n = width do { if (n % 2) { result += string } n = Math.floor(n / 2) /* eslint no-self-assign: 0 */ string += string } while (n && stringWidth(result) < width) return wideTruncate(result, width) }
javascript
function repeat (string, width) { var result = '' var n = width do { if (n % 2) { result += string } n = Math.floor(n / 2) /* eslint no-self-assign: 0 */ string += string } while (n && stringWidth(result) < width) return wideTruncate(result, width) }
[ "function", "repeat", "(", "string", ",", "width", ")", "{", "var", "result", "=", "''", "var", "n", "=", "width", "do", "{", "if", "(", "n", "%", "2", ")", "{", "result", "+=", "string", "}", "n", "=", "Math", ".", "floor", "(", "n", "/", "2", ")", "/* eslint no-self-assign: 0 */", "string", "+=", "string", "}", "while", "(", "n", "&&", "stringWidth", "(", "result", ")", "<", "width", ")", "return", "wideTruncate", "(", "result", ",", "width", ")", "}" ]
lodash's way of repeating
[ "lodash", "s", "way", "of", "repeating" ]
d10739021f85125abb04112d721d17e600746004
https://github.com/npm/gauge/blob/d10739021f85125abb04112d721d17e600746004/progress-bar.js#L22-L35
20,316
hebcal/hebcal-js
compile.js
compile
function compile(inFile, outFile, sourceMap, cb) { console.log('Compiling ' + inFile + ' to ' + outFile); var outStream = fs.createWriteStream(outFile, 'utf8'); outStream.on('close', cb); browserify({debug: true}) .require(inFile, { entry: true }) .bundle() .pipe(exorcist(sourceMap)) .pipe(outStream); }
javascript
function compile(inFile, outFile, sourceMap, cb) { console.log('Compiling ' + inFile + ' to ' + outFile); var outStream = fs.createWriteStream(outFile, 'utf8'); outStream.on('close', cb); browserify({debug: true}) .require(inFile, { entry: true }) .bundle() .pipe(exorcist(sourceMap)) .pipe(outStream); }
[ "function", "compile", "(", "inFile", ",", "outFile", ",", "sourceMap", ",", "cb", ")", "{", "console", ".", "log", "(", "'Compiling '", "+", "inFile", "+", "' to '", "+", "outFile", ")", ";", "var", "outStream", "=", "fs", ".", "createWriteStream", "(", "outFile", ",", "'utf8'", ")", ";", "outStream", ".", "on", "(", "'close'", ",", "cb", ")", ";", "browserify", "(", "{", "debug", ":", "true", "}", ")", ".", "require", "(", "inFile", ",", "{", "entry", ":", "true", "}", ")", ".", "bundle", "(", ")", ".", "pipe", "(", "exorcist", "(", "sourceMap", ")", ")", ".", "pipe", "(", "outStream", ")", ";", "}" ]
all the functions get hoisted
[ "all", "the", "functions", "get", "hoisted" ]
22b6a2ee7266f712865f02ccda1cbdb10e29927d
https://github.com/hebcal/hebcal-js/blob/22b6a2ee7266f712865f02ccda1cbdb10e29927d/compile.js#L17-L26
20,317
hebcal/hebcal-js
src/hebcal.js
Hebcal
function Hebcal(year, month) { var me = this; // whenever this is done, it is for optimizations. if (!year) { year = (new HDate())[getFullYear](); // this year; } if (typeof year !== 'number') { throw new TE('year to Hebcal() is not a number'); } me.year = year; if (month) { if (typeof month == 'string') { month = c.monthFromName(month); } if (typeof month == 'number') { month = [month]; } if (Array.isArray(month)) { me.months = month[map](function(i){ var m = new Month(i, year); defProp(m, '__year', { configurable: true, writable: true, value: me }); return m; }); me.holidays = holidays.year(year); } else { throw new TE('month to Hebcal is not a valid type'); } } else { return new Hebcal(year, c.range(1, c.MONTH_CNT(year))); } me[length] = c.daysInYear(year); defProp(me, 'il', getset(function() { return me[getMonth](1).il; }, function(il) { me.months.forEach(function(m){ m.il = il; }); })); defProp(me, 'lat', getset(function() { return me[getMonth](1).lat; }, function(lat) { me.months.forEach(function(m){ m.lat = lat; }); })); defProp(me, 'long', getset(function() { return me[getMonth](1).long; }, function(lon) { me.months.forEach(function(m){ m.long = lon; }); })); }
javascript
function Hebcal(year, month) { var me = this; // whenever this is done, it is for optimizations. if (!year) { year = (new HDate())[getFullYear](); // this year; } if (typeof year !== 'number') { throw new TE('year to Hebcal() is not a number'); } me.year = year; if (month) { if (typeof month == 'string') { month = c.monthFromName(month); } if (typeof month == 'number') { month = [month]; } if (Array.isArray(month)) { me.months = month[map](function(i){ var m = new Month(i, year); defProp(m, '__year', { configurable: true, writable: true, value: me }); return m; }); me.holidays = holidays.year(year); } else { throw new TE('month to Hebcal is not a valid type'); } } else { return new Hebcal(year, c.range(1, c.MONTH_CNT(year))); } me[length] = c.daysInYear(year); defProp(me, 'il', getset(function() { return me[getMonth](1).il; }, function(il) { me.months.forEach(function(m){ m.il = il; }); })); defProp(me, 'lat', getset(function() { return me[getMonth](1).lat; }, function(lat) { me.months.forEach(function(m){ m.lat = lat; }); })); defProp(me, 'long', getset(function() { return me[getMonth](1).long; }, function(lon) { me.months.forEach(function(m){ m.long = lon; }); })); }
[ "function", "Hebcal", "(", "year", ",", "month", ")", "{", "var", "me", "=", "this", ";", "// whenever this is done, it is for optimizations.", "if", "(", "!", "year", ")", "{", "year", "=", "(", "new", "HDate", "(", ")", ")", "[", "getFullYear", "]", "(", ")", ";", "// this year;", "}", "if", "(", "typeof", "year", "!==", "'number'", ")", "{", "throw", "new", "TE", "(", "'year to Hebcal() is not a number'", ")", ";", "}", "me", ".", "year", "=", "year", ";", "if", "(", "month", ")", "{", "if", "(", "typeof", "month", "==", "'string'", ")", "{", "month", "=", "c", ".", "monthFromName", "(", "month", ")", ";", "}", "if", "(", "typeof", "month", "==", "'number'", ")", "{", "month", "=", "[", "month", "]", ";", "}", "if", "(", "Array", ".", "isArray", "(", "month", ")", ")", "{", "me", ".", "months", "=", "month", "[", "map", "]", "(", "function", "(", "i", ")", "{", "var", "m", "=", "new", "Month", "(", "i", ",", "year", ")", ";", "defProp", "(", "m", ",", "'__year'", ",", "{", "configurable", ":", "true", ",", "writable", ":", "true", ",", "value", ":", "me", "}", ")", ";", "return", "m", ";", "}", ")", ";", "me", ".", "holidays", "=", "holidays", ".", "year", "(", "year", ")", ";", "}", "else", "{", "throw", "new", "TE", "(", "'month to Hebcal is not a valid type'", ")", ";", "}", "}", "else", "{", "return", "new", "Hebcal", "(", "year", ",", "c", ".", "range", "(", "1", ",", "c", ".", "MONTH_CNT", "(", "year", ")", ")", ")", ";", "}", "me", "[", "length", "]", "=", "c", ".", "daysInYear", "(", "year", ")", ";", "defProp", "(", "me", ",", "'il'", ",", "getset", "(", "function", "(", ")", "{", "return", "me", "[", "getMonth", "]", "(", "1", ")", ".", "il", ";", "}", ",", "function", "(", "il", ")", "{", "me", ".", "months", ".", "forEach", "(", "function", "(", "m", ")", "{", "m", ".", "il", "=", "il", ";", "}", ")", ";", "}", ")", ")", ";", "defProp", "(", "me", ",", "'lat'", ",", "getset", "(", "function", "(", ")", "{", "return", "me", "[", "getMonth", "]", "(", "1", ")", ".", "lat", ";", "}", ",", "function", "(", "lat", ")", "{", "me", ".", "months", ".", "forEach", "(", "function", "(", "m", ")", "{", "m", ".", "lat", "=", "lat", ";", "}", ")", ";", "}", ")", ")", ";", "defProp", "(", "me", ",", "'long'", ",", "getset", "(", "function", "(", ")", "{", "return", "me", "[", "getMonth", "]", "(", "1", ")", ".", "long", ";", "}", ",", "function", "(", "lon", ")", "{", "me", ".", "months", ".", "forEach", "(", "function", "(", "m", ")", "{", "m", ".", "long", "=", "lon", ";", "}", ")", ";", "}", ")", ")", ";", "}" ]
Main Hebcal function
[ "Main", "Hebcal", "function" ]
22b6a2ee7266f712865f02ccda1cbdb10e29927d
https://github.com/hebcal/hebcal-js/blob/22b6a2ee7266f712865f02ccda1cbdb10e29927d/src/hebcal.js#L80-L140
20,318
hebcal/hebcal-js
src/sedra.js
abs
function abs(year, absDate) { // find the first saturday on or after today's date absDate = c.dayOnOrBefore(6, absDate + 6); var weekNum = (absDate - year.first_saturday) / 7; var index = year.theSedraArray[weekNum]; if (undefined === index) { return abs(new Sedra(year.year + 1, year.il), absDate); // must be next year } if (typeof index == 'object') { // Shabbat has a chag. Return a description return {parsha: [index], chag: true}; } if (index >= 0) { return {parsha: [parshiot[index]], chag: false}; } index = D(index); // undouble the parsha return {parsha: [parshiot[index], parshiot[index + 1]], chag: false}; }
javascript
function abs(year, absDate) { // find the first saturday on or after today's date absDate = c.dayOnOrBefore(6, absDate + 6); var weekNum = (absDate - year.first_saturday) / 7; var index = year.theSedraArray[weekNum]; if (undefined === index) { return abs(new Sedra(year.year + 1, year.il), absDate); // must be next year } if (typeof index == 'object') { // Shabbat has a chag. Return a description return {parsha: [index], chag: true}; } if (index >= 0) { return {parsha: [parshiot[index]], chag: false}; } index = D(index); // undouble the parsha return {parsha: [parshiot[index], parshiot[index + 1]], chag: false}; }
[ "function", "abs", "(", "year", ",", "absDate", ")", "{", "// find the first saturday on or after today's date", "absDate", "=", "c", ".", "dayOnOrBefore", "(", "6", ",", "absDate", "+", "6", ")", ";", "var", "weekNum", "=", "(", "absDate", "-", "year", ".", "first_saturday", ")", "/", "7", ";", "var", "index", "=", "year", ".", "theSedraArray", "[", "weekNum", "]", ";", "if", "(", "undefined", "===", "index", ")", "{", "return", "abs", "(", "new", "Sedra", "(", "year", ".", "year", "+", "1", ",", "year", ".", "il", ")", ",", "absDate", ")", ";", "// must be next year", "}", "if", "(", "typeof", "index", "==", "'object'", ")", "{", "// Shabbat has a chag. Return a description", "return", "{", "parsha", ":", "[", "index", "]", ",", "chag", ":", "true", "}", ";", "}", "if", "(", "index", ">=", "0", ")", "{", "return", "{", "parsha", ":", "[", "parshiot", "[", "index", "]", "]", ",", "chag", ":", "false", "}", ";", "}", "index", "=", "D", "(", "index", ")", ";", "// undouble the parsha", "return", "{", "parsha", ":", "[", "parshiot", "[", "index", "]", ",", "parshiot", "[", "index", "+", "1", "]", "]", ",", "chag", ":", "false", "}", ";", "}" ]
returns an array describing the parsha on the first Saturday on or after absdate
[ "returns", "an", "array", "describing", "the", "parsha", "on", "the", "first", "Saturday", "on", "or", "after", "absdate" ]
22b6a2ee7266f712865f02ccda1cbdb10e29927d
https://github.com/hebcal/hebcal-js/blob/22b6a2ee7266f712865f02ccda1cbdb10e29927d/src/sedra.js#L307-L328
20,319
novocaine/sourcemapped-stacktrace
sourcemapped-stacktrace.js
function(stack, done, opts) { var lines; var line; var mapForUri = {}; var rows = {}; var fields; var uri; var expected_fields; var regex; var skip_lines; var fetcher = new Fetcher(opts); if (isChromeOrEdge() || isIE11Plus()) { regex = /^ +at.+\((.*):([0-9]+):([0-9]+)/; expected_fields = 4; // (skip first line containing exception message) skip_lines = 1; } else if (isFirefox() || isSafari()) { regex = /@(.*):([0-9]+):([0-9]+)/; expected_fields = 4; skip_lines = 0; } else { throw new Error("unknown browser :("); } lines = stack.split("\n").slice(skip_lines); for (var i=0; i < lines.length; i++) { line = lines[i]; if ( opts && opts.filter && !opts.filter(line) ) continue; fields = line.match(regex); if (fields && fields.length === expected_fields) { rows[i] = fields; uri = fields[1]; if (!uri.match(/<anonymous>/)) { fetcher.fetchScript(uri); } } } fetcher.sem.whenReady(function() { var result = processSourceMaps(lines, rows, fetcher.mapForUri); done(result); }); }
javascript
function(stack, done, opts) { var lines; var line; var mapForUri = {}; var rows = {}; var fields; var uri; var expected_fields; var regex; var skip_lines; var fetcher = new Fetcher(opts); if (isChromeOrEdge() || isIE11Plus()) { regex = /^ +at.+\((.*):([0-9]+):([0-9]+)/; expected_fields = 4; // (skip first line containing exception message) skip_lines = 1; } else if (isFirefox() || isSafari()) { regex = /@(.*):([0-9]+):([0-9]+)/; expected_fields = 4; skip_lines = 0; } else { throw new Error("unknown browser :("); } lines = stack.split("\n").slice(skip_lines); for (var i=0; i < lines.length; i++) { line = lines[i]; if ( opts && opts.filter && !opts.filter(line) ) continue; fields = line.match(regex); if (fields && fields.length === expected_fields) { rows[i] = fields; uri = fields[1]; if (!uri.match(/<anonymous>/)) { fetcher.fetchScript(uri); } } } fetcher.sem.whenReady(function() { var result = processSourceMaps(lines, rows, fetcher.mapForUri); done(result); }); }
[ "function", "(", "stack", ",", "done", ",", "opts", ")", "{", "var", "lines", ";", "var", "line", ";", "var", "mapForUri", "=", "{", "}", ";", "var", "rows", "=", "{", "}", ";", "var", "fields", ";", "var", "uri", ";", "var", "expected_fields", ";", "var", "regex", ";", "var", "skip_lines", ";", "var", "fetcher", "=", "new", "Fetcher", "(", "opts", ")", ";", "if", "(", "isChromeOrEdge", "(", ")", "||", "isIE11Plus", "(", ")", ")", "{", "regex", "=", "/", "^ +at.+\\((.*):([0-9]+):([0-9]+)", "/", ";", "expected_fields", "=", "4", ";", "// (skip first line containing exception message)", "skip_lines", "=", "1", ";", "}", "else", "if", "(", "isFirefox", "(", ")", "||", "isSafari", "(", ")", ")", "{", "regex", "=", "/", "@(.*):([0-9]+):([0-9]+)", "/", ";", "expected_fields", "=", "4", ";", "skip_lines", "=", "0", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"unknown browser :(\"", ")", ";", "}", "lines", "=", "stack", ".", "split", "(", "\"\\n\"", ")", ".", "slice", "(", "skip_lines", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "lines", ".", "length", ";", "i", "++", ")", "{", "line", "=", "lines", "[", "i", "]", ";", "if", "(", "opts", "&&", "opts", ".", "filter", "&&", "!", "opts", ".", "filter", "(", "line", ")", ")", "continue", ";", "fields", "=", "line", ".", "match", "(", "regex", ")", ";", "if", "(", "fields", "&&", "fields", ".", "length", "===", "expected_fields", ")", "{", "rows", "[", "i", "]", "=", "fields", ";", "uri", "=", "fields", "[", "1", "]", ";", "if", "(", "!", "uri", ".", "match", "(", "/", "<anonymous>", "/", ")", ")", "{", "fetcher", ".", "fetchScript", "(", "uri", ")", ";", "}", "}", "}", "fetcher", ".", "sem", ".", "whenReady", "(", "function", "(", ")", "{", "var", "result", "=", "processSourceMaps", "(", "lines", ",", "rows", ",", "fetcher", ".", "mapForUri", ")", ";", "done", "(", "result", ")", ";", "}", ")", ";", "}" ]
Re-map entries in a stacktrace using sourcemaps if available. @param {str} stack - The stacktrace from the browser. @param {function} done - Callback invoked with the transformed stacktrace (an Array of Strings) passed as the first argument @param {Object} [opts] - Optional options object. @param {Function} [opts.filter] - Filter function applied to each stackTrace line. Lines which do not pass the filter won't be processesd. @param {boolean} [opts.cacheGlobally] - Whether to cache sourcemaps globally across multiple calls. @param {boolean} [opts.sync] - Whether to use synchronous ajax to load the sourcemaps.
[ "Re", "-", "map", "entries", "in", "a", "stacktrace", "using", "sourcemaps", "if", "available", "." ]
4f30877c6095e111f2dcffffae76af90549b8468
https://github.com/novocaine/sourcemapped-stacktrace/blob/4f30877c6095e111f2dcffffae76af90549b8468/sourcemapped-stacktrace.js#L33-L79
20,320
dial-once/node-cache-manager-redis
index.js
handleResponse
function handleResponse(conn, cb, opts) { opts = opts || {}; return function(err, result) { pool.release(conn); if (err) { return cb && cb(err); } if (opts.parse) { if (result && opts.compress) { return zlib.gunzip(result, opts.compress.params || {}, function (gzErr, gzResult) { if (gzErr) { return cb && cb(gzErr); } try { gzResult = JSON.parse(gzResult); } catch (e) { return cb && cb(e); } return cb && cb(null, gzResult); }); } try { result = JSON.parse(result); } catch (e) { return cb && cb(e); } } return cb && cb(null, result); }; }
javascript
function handleResponse(conn, cb, opts) { opts = opts || {}; return function(err, result) { pool.release(conn); if (err) { return cb && cb(err); } if (opts.parse) { if (result && opts.compress) { return zlib.gunzip(result, opts.compress.params || {}, function (gzErr, gzResult) { if (gzErr) { return cb && cb(gzErr); } try { gzResult = JSON.parse(gzResult); } catch (e) { return cb && cb(e); } return cb && cb(null, gzResult); }); } try { result = JSON.parse(result); } catch (e) { return cb && cb(e); } } return cb && cb(null, result); }; }
[ "function", "handleResponse", "(", "conn", ",", "cb", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "return", "function", "(", "err", ",", "result", ")", "{", "pool", ".", "release", "(", "conn", ")", ";", "if", "(", "err", ")", "{", "return", "cb", "&&", "cb", "(", "err", ")", ";", "}", "if", "(", "opts", ".", "parse", ")", "{", "if", "(", "result", "&&", "opts", ".", "compress", ")", "{", "return", "zlib", ".", "gunzip", "(", "result", ",", "opts", ".", "compress", ".", "params", "||", "{", "}", ",", "function", "(", "gzErr", ",", "gzResult", ")", "{", "if", "(", "gzErr", ")", "{", "return", "cb", "&&", "cb", "(", "gzErr", ")", ";", "}", "try", "{", "gzResult", "=", "JSON", ".", "parse", "(", "gzResult", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "cb", "&&", "cb", "(", "e", ")", ";", "}", "return", "cb", "&&", "cb", "(", "null", ",", "gzResult", ")", ";", "}", ")", ";", "}", "try", "{", "result", "=", "JSON", ".", "parse", "(", "result", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "cb", "&&", "cb", "(", "e", ")", ";", "}", "}", "return", "cb", "&&", "cb", "(", "null", ",", "result", ")", ";", "}", ";", "}" ]
Helper to handle callback and release the connection @private @param {Object} conn - The Redis connection @param {Function} [cb] - A callback that returns a potential error and the result @param {Object} [opts] - The options (optional)
[ "Helper", "to", "handle", "callback", "and", "release", "the", "connection" ]
e73902ebe398b2f637e78358df2d2baa6725ebd5
https://github.com/dial-once/node-cache-manager-redis/blob/e73902ebe398b2f637e78358df2d2baa6725ebd5/index.js#L74-L110
20,321
dial-once/node-cache-manager-redis
index.js
getFromUrl
function getFromUrl(args) { if (!args || typeof args.url !== 'string') { return args; } try { var options = redisUrl.parse(args.url); // make a clone so we don't change input args return applyOptionsToArgs(args, options); } catch (e) { //url is unparsable so returning original return args; } }
javascript
function getFromUrl(args) { if (!args || typeof args.url !== 'string') { return args; } try { var options = redisUrl.parse(args.url); // make a clone so we don't change input args return applyOptionsToArgs(args, options); } catch (e) { //url is unparsable so returning original return args; } }
[ "function", "getFromUrl", "(", "args", ")", "{", "if", "(", "!", "args", "||", "typeof", "args", ".", "url", "!==", "'string'", ")", "{", "return", "args", ";", "}", "try", "{", "var", "options", "=", "redisUrl", ".", "parse", "(", "args", ".", "url", ")", ";", "// make a clone so we don't change input args", "return", "applyOptionsToArgs", "(", "args", ",", "options", ")", ";", "}", "catch", "(", "e", ")", "{", "//url is unparsable so returning original", "return", "args", ";", "}", "}" ]
Extracts options from an args.url @param {Object} args @param {String} args.url a string in format of redis://[:password@]host[:port][/db-number][?option=value] @returns {Object} the input object args if it is falsy, does not contain url or url is not string, otherwise a new object with own properties of args but with host, port, db, ttl and auth_pass properties overridden by those provided in args.url.
[ "Extracts", "options", "from", "an", "args", ".", "url" ]
e73902ebe398b2f637e78358df2d2baa6725ebd5
https://github.com/dial-once/node-cache-manager-redis/blob/e73902ebe398b2f637e78358df2d2baa6725ebd5/index.js#L119-L133
20,322
dial-once/node-cache-manager-redis
index.js
cloneArgs
function cloneArgs(args) { var newArgs = {}; for(var key in args){ if (key && args.hasOwnProperty(key)) { newArgs[key] = args[key]; } } newArgs.isCacheableValue = args.isCacheableValue && args.isCacheableValue.bind(newArgs); return newArgs; }
javascript
function cloneArgs(args) { var newArgs = {}; for(var key in args){ if (key && args.hasOwnProperty(key)) { newArgs[key] = args[key]; } } newArgs.isCacheableValue = args.isCacheableValue && args.isCacheableValue.bind(newArgs); return newArgs; }
[ "function", "cloneArgs", "(", "args", ")", "{", "var", "newArgs", "=", "{", "}", ";", "for", "(", "var", "key", "in", "args", ")", "{", "if", "(", "key", "&&", "args", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "newArgs", "[", "key", "]", "=", "args", "[", "key", "]", ";", "}", "}", "newArgs", ".", "isCacheableValue", "=", "args", ".", "isCacheableValue", "&&", "args", ".", "isCacheableValue", ".", "bind", "(", "newArgs", ")", ";", "return", "newArgs", ";", "}" ]
Clones args'es own properties to a new object and sets isCacheableValue on the new object @param {Object} args @returns {Object} a clone of the args object
[ "Clones", "args", "es", "own", "properties", "to", "a", "new", "object", "and", "sets", "isCacheableValue", "on", "the", "new", "object" ]
e73902ebe398b2f637e78358df2d2baa6725ebd5
https://github.com/dial-once/node-cache-manager-redis/blob/e73902ebe398b2f637e78358df2d2baa6725ebd5/index.js#L140-L149
20,323
dial-once/node-cache-manager-redis
index.js
applyOptionsToArgs
function applyOptionsToArgs(args, options) { var newArgs = cloneArgs(args); newArgs.host = options.hostname; newArgs.port = parseInt(options.port, 10); newArgs.db = parseInt(options.database, 10); newArgs.auth_pass = options.password; newArgs.password = options.password; if(options.query && options.query.ttl){ newArgs.ttl = parseInt(options.query.ttl, 10); } return newArgs; }
javascript
function applyOptionsToArgs(args, options) { var newArgs = cloneArgs(args); newArgs.host = options.hostname; newArgs.port = parseInt(options.port, 10); newArgs.db = parseInt(options.database, 10); newArgs.auth_pass = options.password; newArgs.password = options.password; if(options.query && options.query.ttl){ newArgs.ttl = parseInt(options.query.ttl, 10); } return newArgs; }
[ "function", "applyOptionsToArgs", "(", "args", ",", "options", ")", "{", "var", "newArgs", "=", "cloneArgs", "(", "args", ")", ";", "newArgs", ".", "host", "=", "options", ".", "hostname", ";", "newArgs", ".", "port", "=", "parseInt", "(", "options", ".", "port", ",", "10", ")", ";", "newArgs", ".", "db", "=", "parseInt", "(", "options", ".", "database", ",", "10", ")", ";", "newArgs", ".", "auth_pass", "=", "options", ".", "password", ";", "newArgs", ".", "password", "=", "options", ".", "password", ";", "if", "(", "options", ".", "query", "&&", "options", ".", "query", ".", "ttl", ")", "{", "newArgs", ".", "ttl", "=", "parseInt", "(", "options", ".", "query", ".", "ttl", ",", "10", ")", ";", "}", "return", "newArgs", ";", "}" ]
Apply some options like hostname, port, db, ttl, auth_pass, password from options to newArgs host, port, db, auth_pass, password and ttl and return clone of args @param {Object} args @param {Object} options @returns {Object} clone of args param with properties set to those of options
[ "Apply", "some", "options", "like", "hostname", "port", "db", "ttl", "auth_pass", "password", "from", "options", "to", "newArgs", "host", "port", "db", "auth_pass", "password", "and", "ttl", "and", "return", "clone", "of", "args" ]
e73902ebe398b2f637e78358df2d2baa6725ebd5
https://github.com/dial-once/node-cache-manager-redis/blob/e73902ebe398b2f637e78358df2d2baa6725ebd5/index.js#L158-L169
20,324
dial-once/node-cache-manager-redis
index.js
persist
function persist(pErr, pVal) { if (pErr) { return cb(pErr); } if (ttl) { conn.setex(key, ttl, pVal, handleResponse(conn, cb)); } else { conn.set(key, pVal, handleResponse(conn, cb)); } }
javascript
function persist(pErr, pVal) { if (pErr) { return cb(pErr); } if (ttl) { conn.setex(key, ttl, pVal, handleResponse(conn, cb)); } else { conn.set(key, pVal, handleResponse(conn, cb)); } }
[ "function", "persist", "(", "pErr", ",", "pVal", ")", "{", "if", "(", "pErr", ")", "{", "return", "cb", "(", "pErr", ")", ";", "}", "if", "(", "ttl", ")", "{", "conn", ".", "setex", "(", "key", ",", "ttl", ",", "pVal", ",", "handleResponse", "(", "conn", ",", "cb", ")", ")", ";", "}", "else", "{", "conn", ".", "set", "(", "key", ",", "pVal", ",", "handleResponse", "(", "conn", ",", "cb", ")", ")", ";", "}", "}" ]
Refactored to remove duplicate code.
[ "Refactored", "to", "remove", "duplicate", "code", "." ]
e73902ebe398b2f637e78358df2d2baa6725ebd5
https://github.com/dial-once/node-cache-manager-redis/blob/e73902ebe398b2f637e78358df2d2baa6725ebd5/index.js#L244-L254
20,325
cyclejs-community/create-cycle-app
packages/cycle-scripts/scripts/eject.js
copyScript
function copyScript (script) { fs.copySync(path.join(__dirname, script), path.join(appScriptsPath, script)) }
javascript
function copyScript (script) { fs.copySync(path.join(__dirname, script), path.join(appScriptsPath, script)) }
[ "function", "copyScript", "(", "script", ")", "{", "fs", ".", "copySync", "(", "path", ".", "join", "(", "__dirname", ",", "script", ")", ",", "path", ".", "join", "(", "appScriptsPath", ",", "script", ")", ")", "}" ]
STEP 2 - Copy scripts
[ "STEP", "2", "-", "Copy", "scripts" ]
32d60a5b6ac9fd9b4fab31eaf469d3e197036b90
https://github.com/cyclejs-community/create-cycle-app/blob/32d60a5b6ac9fd9b4fab31eaf469d3e197036b90/packages/cycle-scripts/scripts/eject.js#L63-L65
20,326
derek-watson/jsUri
Uri.js
decode
function decode(s) { if (s) { s = s.toString().replace(re.pluses, '%20'); s = decodeURIComponent(s); } return s; }
javascript
function decode(s) { if (s) { s = s.toString().replace(re.pluses, '%20'); s = decodeURIComponent(s); } return s; }
[ "function", "decode", "(", "s", ")", "{", "if", "(", "s", ")", "{", "s", "=", "s", ".", "toString", "(", ")", ".", "replace", "(", "re", ".", "pluses", ",", "'%20'", ")", ";", "s", "=", "decodeURIComponent", "(", "s", ")", ";", "}", "return", "s", ";", "}" ]
unescape a query param value @param {string} s encoded value @return {string} decoded value
[ "unescape", "a", "query", "param", "value" ]
8d85d3109d88ba6ca83194ca1ff101485baef03d
https://github.com/derek-watson/jsUri/blob/8d85d3109d88ba6ca83194ca1ff101485baef03d/Uri.js#L67-L73
20,327
derek-watson/jsUri
Uri.js
parseUri
function parseUri(str) { var parser = re.uri_parser; var parserKeys = ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "isColonUri", "relative", "path", "directory", "file", "query", "anchor"]; var m = parser.exec(str || ''); var parts = {}; parserKeys.forEach(function(key, i) { parts[key] = m[i] || ''; }); return parts; }
javascript
function parseUri(str) { var parser = re.uri_parser; var parserKeys = ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "isColonUri", "relative", "path", "directory", "file", "query", "anchor"]; var m = parser.exec(str || ''); var parts = {}; parserKeys.forEach(function(key, i) { parts[key] = m[i] || ''; }); return parts; }
[ "function", "parseUri", "(", "str", ")", "{", "var", "parser", "=", "re", ".", "uri_parser", ";", "var", "parserKeys", "=", "[", "\"source\"", ",", "\"protocol\"", ",", "\"authority\"", ",", "\"userInfo\"", ",", "\"user\"", ",", "\"password\"", ",", "\"host\"", ",", "\"port\"", ",", "\"isColonUri\"", ",", "\"relative\"", ",", "\"path\"", ",", "\"directory\"", ",", "\"file\"", ",", "\"query\"", ",", "\"anchor\"", "]", ";", "var", "m", "=", "parser", ".", "exec", "(", "str", "||", "''", ")", ";", "var", "parts", "=", "{", "}", ";", "parserKeys", ".", "forEach", "(", "function", "(", "key", ",", "i", ")", "{", "parts", "[", "key", "]", "=", "m", "[", "i", "]", "||", "''", ";", "}", ")", ";", "return", "parts", ";", "}" ]
Breaks a uri string down into its individual parts @param {string} str uri @return {object} parts
[ "Breaks", "a", "uri", "string", "down", "into", "its", "individual", "parts" ]
8d85d3109d88ba6ca83194ca1ff101485baef03d
https://github.com/derek-watson/jsUri/blob/8d85d3109d88ba6ca83194ca1ff101485baef03d/Uri.js#L80-L91
20,328
derek-watson/jsUri
Uri.js
Uri
function Uri(str) { this.uriParts = parseUri(str); this.queryPairs = parseQuery(this.uriParts.query); this.hasAuthorityPrefixUserPref = null; }
javascript
function Uri(str) { this.uriParts = parseUri(str); this.queryPairs = parseQuery(this.uriParts.query); this.hasAuthorityPrefixUserPref = null; }
[ "function", "Uri", "(", "str", ")", "{", "this", ".", "uriParts", "=", "parseUri", "(", "str", ")", ";", "this", ".", "queryPairs", "=", "parseQuery", "(", "this", ".", "uriParts", ".", "query", ")", ";", "this", ".", "hasAuthorityPrefixUserPref", "=", "null", ";", "}" ]
Creates a new Uri object @constructor @param {string} str
[ "Creates", "a", "new", "Uri", "object" ]
8d85d3109d88ba6ca83194ca1ff101485baef03d
https://github.com/derek-watson/jsUri/blob/8d85d3109d88ba6ca83194ca1ff101485baef03d/Uri.js#L131-L135
20,329
Requarks/connect-loki
lib/connect-loki.js
LokiStore
function LokiStore (options) { if (!(this instanceof LokiStore)) { throw new TypeError('Cannot call LokiStore constructor as a function') } let self = this // Parse options options = options || {} Store.call(this, options) this.autosave = options.autosave !== false this.storePath = options.path || './session-store.db' this.ttl = options.ttl || 1209600 if (this.ttl === 0) { this.ttl = null } // Initialize Loki.js this.client = new Loki(this.storePath, { env: 'NODEJS', autosave: self.autosave, autosaveInterval: 5000 }) // Setup error logging if (options.logErrors) { if (typeof options.logErrors !== 'function') { options.logErrors = function (err) { console.error('Warning: connect-loki reported a client error: ' + err) } } this.logger = options.logErrors } else { this.logger = _.noop } // Get / Create collection this.client.loadDatabase({}, () => { self.collection = self.client.getCollection('Sessions') if (_.isNil(self.collection)) { self.collection = self.client.addCollection('Sessions', { indices: ['sid'], ttlInterval: self.ttl }) } self.collection.on('error', (err) => { return self.logger(err) }) self.emit('connect') }) }
javascript
function LokiStore (options) { if (!(this instanceof LokiStore)) { throw new TypeError('Cannot call LokiStore constructor as a function') } let self = this // Parse options options = options || {} Store.call(this, options) this.autosave = options.autosave !== false this.storePath = options.path || './session-store.db' this.ttl = options.ttl || 1209600 if (this.ttl === 0) { this.ttl = null } // Initialize Loki.js this.client = new Loki(this.storePath, { env: 'NODEJS', autosave: self.autosave, autosaveInterval: 5000 }) // Setup error logging if (options.logErrors) { if (typeof options.logErrors !== 'function') { options.logErrors = function (err) { console.error('Warning: connect-loki reported a client error: ' + err) } } this.logger = options.logErrors } else { this.logger = _.noop } // Get / Create collection this.client.loadDatabase({}, () => { self.collection = self.client.getCollection('Sessions') if (_.isNil(self.collection)) { self.collection = self.client.addCollection('Sessions', { indices: ['sid'], ttlInterval: self.ttl }) } self.collection.on('error', (err) => { return self.logger(err) }) self.emit('connect') }) }
[ "function", "LokiStore", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "LokiStore", ")", ")", "{", "throw", "new", "TypeError", "(", "'Cannot call LokiStore constructor as a function'", ")", "}", "let", "self", "=", "this", "// Parse options", "options", "=", "options", "||", "{", "}", "Store", ".", "call", "(", "this", ",", "options", ")", "this", ".", "autosave", "=", "options", ".", "autosave", "!==", "false", "this", ".", "storePath", "=", "options", ".", "path", "||", "'./session-store.db'", "this", ".", "ttl", "=", "options", ".", "ttl", "||", "1209600", "if", "(", "this", ".", "ttl", "===", "0", ")", "{", "this", ".", "ttl", "=", "null", "}", "// Initialize Loki.js", "this", ".", "client", "=", "new", "Loki", "(", "this", ".", "storePath", ",", "{", "env", ":", "'NODEJS'", ",", "autosave", ":", "self", ".", "autosave", ",", "autosaveInterval", ":", "5000", "}", ")", "// Setup error logging", "if", "(", "options", ".", "logErrors", ")", "{", "if", "(", "typeof", "options", ".", "logErrors", "!==", "'function'", ")", "{", "options", ".", "logErrors", "=", "function", "(", "err", ")", "{", "console", ".", "error", "(", "'Warning: connect-loki reported a client error: '", "+", "err", ")", "}", "}", "this", ".", "logger", "=", "options", ".", "logErrors", "}", "else", "{", "this", ".", "logger", "=", "_", ".", "noop", "}", "// Get / Create collection", "this", ".", "client", ".", "loadDatabase", "(", "{", "}", ",", "(", ")", "=>", "{", "self", ".", "collection", "=", "self", ".", "client", ".", "getCollection", "(", "'Sessions'", ")", "if", "(", "_", ".", "isNil", "(", "self", ".", "collection", ")", ")", "{", "self", ".", "collection", "=", "self", ".", "client", ".", "addCollection", "(", "'Sessions'", ",", "{", "indices", ":", "[", "'sid'", "]", ",", "ttlInterval", ":", "self", ".", "ttl", "}", ")", "}", "self", ".", "collection", ".", "on", "(", "'error'", ",", "(", "err", ")", "=>", "{", "return", "self", ".", "logger", "(", "err", ")", "}", ")", "self", ".", "emit", "(", "'connect'", ")", "}", ")", "}" ]
Initialize LokiStore with the given `options`. @param {Object} options @api public
[ "Initialize", "LokiStore", "with", "the", "given", "options", "." ]
8838f64fd50b3c4cc11250dafd604df22c969e01
https://github.com/Requarks/connect-loki/blob/8838f64fd50b3c4cc11250dafd604df22c969e01/lib/connect-loki.js#L28-L81
20,330
alfredobarron/smoke
docs/v2.2.4/bower_components/ngScrollSpy/src/pagemenu.js
function(data) { // parse basic info from the dom item var item = { link: data.id, text: data.textContent || data.innerText, parent: '' }; // build type identifier var level = data.tagName; for (var i = 0; i < data.classList.length; i++) { level += ',' + data.classList[i]; } // here be dragons var stacksize = stack.length; if (stacksize === 0) { // we are at the top level and will stay there stack.push(level); } else if (level !== stack[stacksize - 1]) { // traverse the ancestry, looking for a match for (var j = stacksize - 1; j >= 0; j--) { if (level == stack[j]) { break; // found an ancestor } } if (j < 0) { // this is a new submenu item, lets push the stack stack.push(level); item.push = true; parentstack.push(lastitem); } else { // we are either a sibling or higher up the tree, // lets pop the stack if needed item.pop = stacksize - 1 - j; while (stack.length > j + 1) { stack.pop(); parentstack.pop(); } } } // if we have a parent, lets record it if(parentstack.length > 0) { item.parent= parentstack[parentstack.length-1]; } // for next iteration lastitem= item.link; return item; }
javascript
function(data) { // parse basic info from the dom item var item = { link: data.id, text: data.textContent || data.innerText, parent: '' }; // build type identifier var level = data.tagName; for (var i = 0; i < data.classList.length; i++) { level += ',' + data.classList[i]; } // here be dragons var stacksize = stack.length; if (stacksize === 0) { // we are at the top level and will stay there stack.push(level); } else if (level !== stack[stacksize - 1]) { // traverse the ancestry, looking for a match for (var j = stacksize - 1; j >= 0; j--) { if (level == stack[j]) { break; // found an ancestor } } if (j < 0) { // this is a new submenu item, lets push the stack stack.push(level); item.push = true; parentstack.push(lastitem); } else { // we are either a sibling or higher up the tree, // lets pop the stack if needed item.pop = stacksize - 1 - j; while (stack.length > j + 1) { stack.pop(); parentstack.pop(); } } } // if we have a parent, lets record it if(parentstack.length > 0) { item.parent= parentstack[parentstack.length-1]; } // for next iteration lastitem= item.link; return item; }
[ "function", "(", "data", ")", "{", "// parse basic info from the dom item", "var", "item", "=", "{", "link", ":", "data", ".", "id", ",", "text", ":", "data", ".", "textContent", "||", "data", ".", "innerText", ",", "parent", ":", "''", "}", ";", "// build type identifier", "var", "level", "=", "data", ".", "tagName", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "data", ".", "classList", ".", "length", ";", "i", "++", ")", "{", "level", "+=", "','", "+", "data", ".", "classList", "[", "i", "]", ";", "}", "// here be dragons", "var", "stacksize", "=", "stack", ".", "length", ";", "if", "(", "stacksize", "===", "0", ")", "{", "// we are at the top level and will stay there", "stack", ".", "push", "(", "level", ")", ";", "}", "else", "if", "(", "level", "!==", "stack", "[", "stacksize", "-", "1", "]", ")", "{", "// traverse the ancestry, looking for a match", "for", "(", "var", "j", "=", "stacksize", "-", "1", ";", "j", ">=", "0", ";", "j", "--", ")", "{", "if", "(", "level", "==", "stack", "[", "j", "]", ")", "{", "break", ";", "// found an ancestor", "}", "}", "if", "(", "j", "<", "0", ")", "{", "// this is a new submenu item, lets push the stack", "stack", ".", "push", "(", "level", ")", ";", "item", ".", "push", "=", "true", ";", "parentstack", ".", "push", "(", "lastitem", ")", ";", "}", "else", "{", "// we are either a sibling or higher up the tree,", "// lets pop the stack if needed", "item", ".", "pop", "=", "stacksize", "-", "1", "-", "j", ";", "while", "(", "stack", ".", "length", ">", "j", "+", "1", ")", "{", "stack", ".", "pop", "(", ")", ";", "parentstack", ".", "pop", "(", ")", ";", "}", "}", "}", "// if we have a parent, lets record it", "if", "(", "parentstack", ".", "length", ">", "0", ")", "{", "item", ".", "parent", "=", "parentstack", "[", "parentstack", ".", "length", "-", "1", "]", ";", "}", "// for next iteration", "lastitem", "=", "item", ".", "link", ";", "return", "item", ";", "}" ]
used to build the tree
[ "used", "to", "build", "the", "tree" ]
9c3079a8a5de84a9180eb22d26ca447569e98e79
https://github.com/alfredobarron/smoke/blob/9c3079a8a5de84a9180eb22d26ca447569e98e79/docs/v2.2.4/bower_components/ngScrollSpy/src/pagemenu.js#L7-L57
20,331
alfredobarron/smoke
docs/v2.2.4/bower_components/angular-translate/angular-translate.js
function (translationId) { var deferred = $q.defer(); var regardless = function (value) { results[translationId] = value; deferred.resolve([translationId, value]); }; // we don't care whether the promise was resolved or rejected; just store the values $translate(translationId, interpolateParams, interpolationId, defaultTranslationText).then(regardless, regardless); return deferred.promise; }
javascript
function (translationId) { var deferred = $q.defer(); var regardless = function (value) { results[translationId] = value; deferred.resolve([translationId, value]); }; // we don't care whether the promise was resolved or rejected; just store the values $translate(translationId, interpolateParams, interpolationId, defaultTranslationText).then(regardless, regardless); return deferred.promise; }
[ "function", "(", "translationId", ")", "{", "var", "deferred", "=", "$q", ".", "defer", "(", ")", ";", "var", "regardless", "=", "function", "(", "value", ")", "{", "results", "[", "translationId", "]", "=", "value", ";", "deferred", ".", "resolve", "(", "[", "translationId", ",", "value", "]", ")", ";", "}", ";", "// we don't care whether the promise was resolved or rejected; just store the values", "$translate", "(", "translationId", ",", "interpolateParams", ",", "interpolationId", ",", "defaultTranslationText", ")", ".", "then", "(", "regardless", ",", "regardless", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
promises to wait for Wraps the promise a) being always resolved and b) storing the link id->value
[ "promises", "to", "wait", "for", "Wraps", "the", "promise", "a", ")", "being", "always", "resolved", "and", "b", ")", "storing", "the", "link", "id", "-", ">", "value" ]
9c3079a8a5de84a9180eb22d26ca447569e98e79
https://github.com/alfredobarron/smoke/blob/9c3079a8a5de84a9180eb22d26ca447569e98e79/docs/v2.2.4/bower_components/angular-translate/angular-translate.js#L881-L890
20,332
twitter/css-flip
index.js
isFlippable
function isFlippable(node, prevNode) { if (node.type == 'comment') { return false; } if (prevNode && prevNode.type == 'comment') { return !RE_NOFLIP.test(prevNode.comment); } return true; }
javascript
function isFlippable(node, prevNode) { if (node.type == 'comment') { return false; } if (prevNode && prevNode.type == 'comment') { return !RE_NOFLIP.test(prevNode.comment); } return true; }
[ "function", "isFlippable", "(", "node", ",", "prevNode", ")", "{", "if", "(", "node", ".", "type", "==", "'comment'", ")", "{", "return", "false", ";", "}", "if", "(", "prevNode", "&&", "prevNode", ".", "type", "==", "'comment'", ")", "{", "return", "!", "RE_NOFLIP", ".", "test", "(", "prevNode", ".", "comment", ")", ";", "}", "return", "true", ";", "}" ]
Return whether the given `node` is flippable. @param {Object} node @param {Object} prevNode used for @noflip detection @returns {Boolean}
[ "Return", "whether", "the", "given", "node", "is", "flippable", "." ]
81a5899007c58acd81700aa8f182d9c53cb6bf81
https://github.com/twitter/css-flip/blob/81a5899007c58acd81700aa8f182d9c53cb6bf81/index.js#L26-L36
20,333
twitter/css-flip
index.js
isReplaceable
function isReplaceable(node, prevNode) { if (node.type == 'comment') { return false; } if (prevNode && prevNode.type == 'comment') { return RE_REPLACE.test(prevNode.comment); } return false; }
javascript
function isReplaceable(node, prevNode) { if (node.type == 'comment') { return false; } if (prevNode && prevNode.type == 'comment') { return RE_REPLACE.test(prevNode.comment); } return false; }
[ "function", "isReplaceable", "(", "node", ",", "prevNode", ")", "{", "if", "(", "node", ".", "type", "==", "'comment'", ")", "{", "return", "false", ";", "}", "if", "(", "prevNode", "&&", "prevNode", ".", "type", "==", "'comment'", ")", "{", "return", "RE_REPLACE", ".", "test", "(", "prevNode", ".", "comment", ")", ";", "}", "return", "false", ";", "}" ]
Return whether the given `node` is replaceable. @param {Object} node @param {Object} prevNode used for @replace detection @returns {Boolean}
[ "Return", "whether", "the", "given", "node", "is", "replaceable", "." ]
81a5899007c58acd81700aa8f182d9c53cb6bf81
https://github.com/twitter/css-flip/blob/81a5899007c58acd81700aa8f182d9c53cb6bf81/index.js#L46-L56
20,334
twitter/css-flip
index.js
flip
function flip(str, options) { if (typeof str != 'string') { throw new Error('input is not a String.'); } var node = css.parse(str, options); flipNode(node.stylesheet); return css.stringify(node, options); }
javascript
function flip(str, options) { if (typeof str != 'string') { throw new Error('input is not a String.'); } var node = css.parse(str, options); flipNode(node.stylesheet); return css.stringify(node, options); }
[ "function", "flip", "(", "str", ",", "options", ")", "{", "if", "(", "typeof", "str", "!=", "'string'", ")", "{", "throw", "new", "Error", "(", "'input is not a String.'", ")", ";", "}", "var", "node", "=", "css", ".", "parse", "(", "str", ",", "options", ")", ";", "flipNode", "(", "node", ".", "stylesheet", ")", ";", "return", "css", ".", "stringify", "(", "node", ",", "options", ")", ";", "}" ]
BiDi flip a CSS string. @param {String} str @param {Object} [options] @param {Boolean} [options.compress] Whether to slightly compress output. Some newlines and indentation are removed. Comments stay intact. @param {String} [options.indent] Default is `' '` (two spaces). @returns {String}
[ "BiDi", "flip", "a", "CSS", "string", "." ]
81a5899007c58acd81700aa8f182d9c53cb6bf81
https://github.com/twitter/css-flip/blob/81a5899007c58acd81700aa8f182d9c53cb6bf81/index.js#L114-L124
20,335
twitter/css-flip
lib/transition.js
transition
function transition(value) { var RE_PROP = /^\s*([a-zA-z\-]+)/; var parts = value.split(/\s*,\s*/); return parts.map(function (part) { // extract the property if the value is for the `transition` shorthand if (RE_PROP.test(part)) { var prop = part.match(RE_PROP)[1]; var newProp = flipProperty(prop); part = part.replace(RE_PROP, newProp); } return part; }).join(', '); }
javascript
function transition(value) { var RE_PROP = /^\s*([a-zA-z\-]+)/; var parts = value.split(/\s*,\s*/); return parts.map(function (part) { // extract the property if the value is for the `transition` shorthand if (RE_PROP.test(part)) { var prop = part.match(RE_PROP)[1]; var newProp = flipProperty(prop); part = part.replace(RE_PROP, newProp); } return part; }).join(', '); }
[ "function", "transition", "(", "value", ")", "{", "var", "RE_PROP", "=", "/", "^\\s*([a-zA-z\\-]+)", "/", ";", "var", "parts", "=", "value", ".", "split", "(", "/", "\\s*,\\s*", "/", ")", ";", "return", "parts", ".", "map", "(", "function", "(", "part", ")", "{", "// extract the property if the value is for the `transition` shorthand", "if", "(", "RE_PROP", ".", "test", "(", "part", ")", ")", "{", "var", "prop", "=", "part", ".", "match", "(", "RE_PROP", ")", "[", "1", "]", ";", "var", "newProp", "=", "flipProperty", "(", "prop", ")", ";", "part", "=", "part", ".", "replace", "(", "RE_PROP", ",", "newProp", ")", ";", "}", "return", "part", ";", "}", ")", ".", "join", "(", "', '", ")", ";", "}" ]
Flip properties in transitions. @param {String} value Value @return {String}
[ "Flip", "properties", "in", "transitions", "." ]
81a5899007c58acd81700aa8f182d9c53cb6bf81
https://github.com/twitter/css-flip/blob/81a5899007c58acd81700aa8f182d9c53cb6bf81/lib/transition.js#L14-L28
20,336
twitter/css-flip
lib/flipProperty.js
flipProperty
function flipProperty(prop) { var normalizedProperty = prop.toLowerCase(); return PROPERTIES.hasOwnProperty(normalizedProperty) ? PROPERTIES[normalizedProperty] : prop; }
javascript
function flipProperty(prop) { var normalizedProperty = prop.toLowerCase(); return PROPERTIES.hasOwnProperty(normalizedProperty) ? PROPERTIES[normalizedProperty] : prop; }
[ "function", "flipProperty", "(", "prop", ")", "{", "var", "normalizedProperty", "=", "prop", ".", "toLowerCase", "(", ")", ";", "return", "PROPERTIES", ".", "hasOwnProperty", "(", "normalizedProperty", ")", "?", "PROPERTIES", "[", "normalizedProperty", "]", ":", "prop", ";", "}" ]
BiDi flip the given property. @param {String} prop @return {String}
[ "BiDi", "flip", "the", "given", "property", "." ]
81a5899007c58acd81700aa8f182d9c53cb6bf81
https://github.com/twitter/css-flip/blob/81a5899007c58acd81700aa8f182d9c53cb6bf81/lib/flipProperty.js#L33-L37
20,337
twitter/css-flip
lib/border-radius.js
flipCorners
function flipCorners(value) { var elements = value.split(/\s+/); if (!elements) { return value; } switch (elements.length) { // 5px 10px 15px 20px => 10px 5px 20px 15px case 4: return [elements[1], elements[0], elements[3], elements[2]].join(' '); // 5px 10px 20px => 10px 5px 10px 20px case 3: return [elements[1], elements[0], elements[1], elements[2]].join(' '); // 5px 10px => 10px 5px case 2: return [elements[1], elements[0]].join(' '); } return value; }
javascript
function flipCorners(value) { var elements = value.split(/\s+/); if (!elements) { return value; } switch (elements.length) { // 5px 10px 15px 20px => 10px 5px 20px 15px case 4: return [elements[1], elements[0], elements[3], elements[2]].join(' '); // 5px 10px 20px => 10px 5px 10px 20px case 3: return [elements[1], elements[0], elements[1], elements[2]].join(' '); // 5px 10px => 10px 5px case 2: return [elements[1], elements[0]].join(' '); } return value; }
[ "function", "flipCorners", "(", "value", ")", "{", "var", "elements", "=", "value", ".", "split", "(", "/", "\\s+", "/", ")", ";", "if", "(", "!", "elements", ")", "{", "return", "value", ";", "}", "switch", "(", "elements", ".", "length", ")", "{", "// 5px 10px 15px 20px => 10px 5px 20px 15px", "case", "4", ":", "return", "[", "elements", "[", "1", "]", ",", "elements", "[", "0", "]", ",", "elements", "[", "3", "]", ",", "elements", "[", "2", "]", "]", ".", "join", "(", "' '", ")", ";", "// 5px 10px 20px => 10px 5px 10px 20px", "case", "3", ":", "return", "[", "elements", "[", "1", "]", ",", "elements", "[", "0", "]", ",", "elements", "[", "1", "]", ",", "elements", "[", "2", "]", "]", ".", "join", "(", "' '", ")", ";", "// 5px 10px => 10px 5px", "case", "2", ":", "return", "[", "elements", "[", "1", "]", ",", "elements", "[", "0", "]", "]", ".", "join", "(", "' '", ")", ";", "}", "return", "value", ";", "}" ]
Flip the corners of a `border-radius` value. @param {String} value Value @return {String}
[ "Flip", "the", "corners", "of", "a", "border", "-", "radius", "value", "." ]
81a5899007c58acd81700aa8f182d9c53cb6bf81
https://github.com/twitter/css-flip/blob/81a5899007c58acd81700aa8f182d9c53cb6bf81/lib/border-radius.js#L33-L50
20,338
twitter/css-flip
lib/flipValueOf.js
flipValueOf
function flipValueOf(prop, value) { var RE_IMPORTANT = /\s*!important/; var RE_PREFIX = /^-[a-zA-Z]+-/; // find normalized property name (removing any vendor prefixes) var normalizedProperty = prop.toLowerCase().trim(); normalizedProperty = (RE_PREFIX.test(normalizedProperty) ? normalizedProperty.split(RE_PREFIX)[1] : normalizedProperty); var flipFn = VALUES.hasOwnProperty(normalizedProperty) ? VALUES[normalizedProperty] : false; if (!flipFn) { return value; } var important = value.match(RE_IMPORTANT); var newValue = flipFn(value.replace(RE_IMPORTANT, '').trim(), prop); if (important && !RE_IMPORTANT.test(newValue)) { newValue += important[0]; } return newValue; }
javascript
function flipValueOf(prop, value) { var RE_IMPORTANT = /\s*!important/; var RE_PREFIX = /^-[a-zA-Z]+-/; // find normalized property name (removing any vendor prefixes) var normalizedProperty = prop.toLowerCase().trim(); normalizedProperty = (RE_PREFIX.test(normalizedProperty) ? normalizedProperty.split(RE_PREFIX)[1] : normalizedProperty); var flipFn = VALUES.hasOwnProperty(normalizedProperty) ? VALUES[normalizedProperty] : false; if (!flipFn) { return value; } var important = value.match(RE_IMPORTANT); var newValue = flipFn(value.replace(RE_IMPORTANT, '').trim(), prop); if (important && !RE_IMPORTANT.test(newValue)) { newValue += important[0]; } return newValue; }
[ "function", "flipValueOf", "(", "prop", ",", "value", ")", "{", "var", "RE_IMPORTANT", "=", "/", "\\s*!important", "/", ";", "var", "RE_PREFIX", "=", "/", "^-[a-zA-Z]+-", "/", ";", "// find normalized property name (removing any vendor prefixes)", "var", "normalizedProperty", "=", "prop", ".", "toLowerCase", "(", ")", ".", "trim", "(", ")", ";", "normalizedProperty", "=", "(", "RE_PREFIX", ".", "test", "(", "normalizedProperty", ")", "?", "normalizedProperty", ".", "split", "(", "RE_PREFIX", ")", "[", "1", "]", ":", "normalizedProperty", ")", ";", "var", "flipFn", "=", "VALUES", ".", "hasOwnProperty", "(", "normalizedProperty", ")", "?", "VALUES", "[", "normalizedProperty", "]", ":", "false", ";", "if", "(", "!", "flipFn", ")", "{", "return", "value", ";", "}", "var", "important", "=", "value", ".", "match", "(", "RE_IMPORTANT", ")", ";", "var", "newValue", "=", "flipFn", "(", "value", ".", "replace", "(", "RE_IMPORTANT", ",", "''", ")", ".", "trim", "(", ")", ",", "prop", ")", ";", "if", "(", "important", "&&", "!", "RE_IMPORTANT", ".", "test", "(", "newValue", ")", ")", "{", "newValue", "+=", "important", "[", "0", "]", ";", "}", "return", "newValue", ";", "}" ]
BiDi flip the value of a property. @param {String} prop @param {String} value @return {String}
[ "BiDi", "flip", "the", "value", "of", "a", "property", "." ]
81a5899007c58acd81700aa8f182d9c53cb6bf81
https://github.com/twitter/css-flip/blob/81a5899007c58acd81700aa8f182d9c53cb6bf81/lib/flipValueOf.js#L43-L63
20,339
twitter/css-flip
lib/box-shadow.js
flipShadow
function flipShadow(value) { var elements = value.split(/\s+/); if (!elements) { return value; } var inset = (elements[0] == 'inset') ? elements.shift() + ' ' : ''; var property = elements[0].match(/^([-+]?\d+)(\w*)$/); if (!property) { return value; } return inset + [(-1 * +property[1]) + property[2]] .concat(elements.splice(1)).join(' '); }
javascript
function flipShadow(value) { var elements = value.split(/\s+/); if (!elements) { return value; } var inset = (elements[0] == 'inset') ? elements.shift() + ' ' : ''; var property = elements[0].match(/^([-+]?\d+)(\w*)$/); if (!property) { return value; } return inset + [(-1 * +property[1]) + property[2]] .concat(elements.splice(1)).join(' '); }
[ "function", "flipShadow", "(", "value", ")", "{", "var", "elements", "=", "value", ".", "split", "(", "/", "\\s+", "/", ")", ";", "if", "(", "!", "elements", ")", "{", "return", "value", ";", "}", "var", "inset", "=", "(", "elements", "[", "0", "]", "==", "'inset'", ")", "?", "elements", ".", "shift", "(", ")", "+", "' '", ":", "''", ";", "var", "property", "=", "elements", "[", "0", "]", ".", "match", "(", "/", "^([-+]?\\d+)(\\w*)$", "/", ")", ";", "if", "(", "!", "property", ")", "{", "return", "value", ";", "}", "return", "inset", "+", "[", "(", "-", "1", "*", "+", "property", "[", "1", "]", ")", "+", "property", "[", "2", "]", "]", ".", "concat", "(", "elements", ".", "splice", "(", "1", ")", ")", ".", "join", "(", "' '", ")", ";", "}" ]
Flip a single `box-shadow` value. @param {String} value Value @return {String}
[ "Flip", "a", "single", "box", "-", "shadow", "value", "." ]
81a5899007c58acd81700aa8f182d9c53cb6bf81
https://github.com/twitter/css-flip/blob/81a5899007c58acd81700aa8f182d9c53cb6bf81/lib/box-shadow.js#L25-L37
20,340
alfredobarron/smoke
docs/v2.2.4/bower_components/ngScrollSpy/dist/ngScrollSpy.debug.js
function(state1, state2) { // if state1 is undefined, return state2 + isEqual=false and velocity=0 as delta if(!state1 || !state2) return angular.extend( {isEqual: false, velocityX: 0, velocityY: 0}, state2 ); // calculate delta of state1 and state2 var delta= { posX: state2.posX - state1.posX, posY: state2.posY - state1.posY, width: state2.width - state1.width, height: state2.height - state1.height, maxWidth: state2.maxWidth - state1.maxWidth, maxHeight: state2.maxHeight - state1.maxHeight, }; // add velocity information if(state2.width > 0) delta.velocityX= delta.posX / state2.width; if(state2.height > 0) delta.velocityY= delta.posY / state2.height; // if any property is not 0, the delta is not zero delta.isEqual= !( delta.posX !== 0 || delta.posY !== 0 || delta.width !== 0 || delta.height !== 0 || delta.maxWidth !== 0 || delta.maxHeight !== 0 ); return delta; }
javascript
function(state1, state2) { // if state1 is undefined, return state2 + isEqual=false and velocity=0 as delta if(!state1 || !state2) return angular.extend( {isEqual: false, velocityX: 0, velocityY: 0}, state2 ); // calculate delta of state1 and state2 var delta= { posX: state2.posX - state1.posX, posY: state2.posY - state1.posY, width: state2.width - state1.width, height: state2.height - state1.height, maxWidth: state2.maxWidth - state1.maxWidth, maxHeight: state2.maxHeight - state1.maxHeight, }; // add velocity information if(state2.width > 0) delta.velocityX= delta.posX / state2.width; if(state2.height > 0) delta.velocityY= delta.posY / state2.height; // if any property is not 0, the delta is not zero delta.isEqual= !( delta.posX !== 0 || delta.posY !== 0 || delta.width !== 0 || delta.height !== 0 || delta.maxWidth !== 0 || delta.maxHeight !== 0 ); return delta; }
[ "function", "(", "state1", ",", "state2", ")", "{", "// if state1 is undefined, return state2 + isEqual=false and velocity=0 as delta", "if", "(", "!", "state1", "||", "!", "state2", ")", "return", "angular", ".", "extend", "(", "{", "isEqual", ":", "false", ",", "velocityX", ":", "0", ",", "velocityY", ":", "0", "}", ",", "state2", ")", ";", "// calculate delta of state1 and state2", "var", "delta", "=", "{", "posX", ":", "state2", ".", "posX", "-", "state1", ".", "posX", ",", "posY", ":", "state2", ".", "posY", "-", "state1", ".", "posY", ",", "width", ":", "state2", ".", "width", "-", "state1", ".", "width", ",", "height", ":", "state2", ".", "height", "-", "state1", ".", "height", ",", "maxWidth", ":", "state2", ".", "maxWidth", "-", "state1", ".", "maxWidth", ",", "maxHeight", ":", "state2", ".", "maxHeight", "-", "state1", ".", "maxHeight", ",", "}", ";", "// add velocity information", "if", "(", "state2", ".", "width", ">", "0", ")", "delta", ".", "velocityX", "=", "delta", ".", "posX", "/", "state2", ".", "width", ";", "if", "(", "state2", ".", "height", ">", "0", ")", "delta", ".", "velocityY", "=", "delta", ".", "posY", "/", "state2", ".", "height", ";", "// if any property is not 0, the delta is not zero", "delta", ".", "isEqual", "=", "!", "(", "delta", ".", "posX", "!==", "0", "||", "delta", ".", "posY", "!==", "0", "||", "delta", ".", "width", "!==", "0", "||", "delta", ".", "height", "!==", "0", "||", "delta", ".", "maxWidth", "!==", "0", "||", "delta", ".", "maxHeight", "!==", "0", ")", ";", "return", "delta", ";", "}" ]
calculate difference between last state and current state
[ "calculate", "difference", "between", "last", "state", "and", "current", "state" ]
9c3079a8a5de84a9180eb22d26ca447569e98e79
https://github.com/alfredobarron/smoke/blob/9c3079a8a5de84a9180eb22d26ca447569e98e79/docs/v2.2.4/bower_components/ngScrollSpy/dist/ngScrollSpy.debug.js#L44-L80
20,341
vitaliy-bobrov/ionic-img-cache
ionic-img-cache.js
get
function get(src) { var defer = $q.defer(); _checkImgCacheReady() .then(function() { ImgCache.isCached(src, function(path, success) { if (success) { defer.resolve(path); } else { defer.reject(); } }, defer.reject); }) .catch(defer.reject); return defer.promise; }
javascript
function get(src) { var defer = $q.defer(); _checkImgCacheReady() .then(function() { ImgCache.isCached(src, function(path, success) { if (success) { defer.resolve(path); } else { defer.reject(); } }, defer.reject); }) .catch(defer.reject); return defer.promise; }
[ "function", "get", "(", "src", ")", "{", "var", "defer", "=", "$q", ".", "defer", "(", ")", ";", "_checkImgCacheReady", "(", ")", ".", "then", "(", "function", "(", ")", "{", "ImgCache", ".", "isCached", "(", "src", ",", "function", "(", "path", ",", "success", ")", "{", "if", "(", "success", ")", "{", "defer", ".", "resolve", "(", "path", ")", ";", "}", "else", "{", "defer", ".", "reject", "(", ")", ";", "}", "}", ",", "defer", ".", "reject", ")", ";", "}", ")", ".", "catch", "(", "defer", ".", "reject", ")", ";", "return", "defer", ".", "promise", ";", "}" ]
Gets file local url if it present in cache. @param {string} src - image source url.
[ "Gets", "file", "local", "url", "if", "it", "present", "in", "cache", "." ]
007f290429eaeb42b22700c4c2e6c67a57807f44
https://github.com/vitaliy-bobrov/ionic-img-cache/blob/007f290429eaeb42b22700c4c2e6c67a57807f44/ionic-img-cache.js#L112-L128
20,342
vitaliy-bobrov/ionic-img-cache
ionic-img-cache.js
remove
function remove(src) { var defer = $q.defer(); _checkImgCacheReady() .then(function() { ImgCache.isCached(src, function(path, success) { ImgCache.removeFile(src, function() { defer.resolve(); }, defer.reject); }, defer.reject); }) .catch(defer.reject); return defer.promise; }
javascript
function remove(src) { var defer = $q.defer(); _checkImgCacheReady() .then(function() { ImgCache.isCached(src, function(path, success) { ImgCache.removeFile(src, function() { defer.resolve(); }, defer.reject); }, defer.reject); }) .catch(defer.reject); return defer.promise; }
[ "function", "remove", "(", "src", ")", "{", "var", "defer", "=", "$q", ".", "defer", "(", ")", ";", "_checkImgCacheReady", "(", ")", ".", "then", "(", "function", "(", ")", "{", "ImgCache", ".", "isCached", "(", "src", ",", "function", "(", "path", ",", "success", ")", "{", "ImgCache", ".", "removeFile", "(", "src", ",", "function", "(", ")", "{", "defer", ".", "resolve", "(", ")", ";", "}", ",", "defer", ".", "reject", ")", ";", "}", ",", "defer", ".", "reject", ")", ";", "}", ")", ".", "catch", "(", "defer", ".", "reject", ")", ";", "return", "defer", ".", "promise", ";", "}" ]
Removes file from local cache if it present. @param {string} src - image source url.
[ "Removes", "file", "from", "local", "cache", "if", "it", "present", "." ]
007f290429eaeb42b22700c4c2e6c67a57807f44
https://github.com/vitaliy-bobrov/ionic-img-cache/blob/007f290429eaeb42b22700c4c2e6c67a57807f44/ionic-img-cache.js#L134-L148
20,343
vitaliy-bobrov/ionic-img-cache
ionic-img-cache.js
checkCacheStatus
function checkCacheStatus(src) { var defer = $q.defer(); _checkImgCacheReady() .then(function() { ImgCache.isCached(src, function(path, success) { if (success) { defer.resolve(path); } else { ImgCache.cacheFile(src, function() { ImgCache.isCached(src, function(path, success) { defer.resolve(path); }, defer.reject); }, defer.reject); } }, defer.reject); }) .catch(defer.reject); return defer.promise; }
javascript
function checkCacheStatus(src) { var defer = $q.defer(); _checkImgCacheReady() .then(function() { ImgCache.isCached(src, function(path, success) { if (success) { defer.resolve(path); } else { ImgCache.cacheFile(src, function() { ImgCache.isCached(src, function(path, success) { defer.resolve(path); }, defer.reject); }, defer.reject); } }, defer.reject); }) .catch(defer.reject); return defer.promise; }
[ "function", "checkCacheStatus", "(", "src", ")", "{", "var", "defer", "=", "$q", ".", "defer", "(", ")", ";", "_checkImgCacheReady", "(", ")", ".", "then", "(", "function", "(", ")", "{", "ImgCache", ".", "isCached", "(", "src", ",", "function", "(", "path", ",", "success", ")", "{", "if", "(", "success", ")", "{", "defer", ".", "resolve", "(", "path", ")", ";", "}", "else", "{", "ImgCache", ".", "cacheFile", "(", "src", ",", "function", "(", ")", "{", "ImgCache", ".", "isCached", "(", "src", ",", "function", "(", "path", ",", "success", ")", "{", "defer", ".", "resolve", "(", "path", ")", ";", "}", ",", "defer", ".", "reject", ")", ";", "}", ",", "defer", ".", "reject", ")", ";", "}", "}", ",", "defer", ".", "reject", ")", ";", "}", ")", ".", "catch", "(", "defer", ".", "reject", ")", ";", "return", "defer", ".", "promise", ";", "}" ]
Checks file cache status by url. @param {string} src - image source url.
[ "Checks", "file", "cache", "status", "by", "url", "." ]
007f290429eaeb42b22700c4c2e6c67a57807f44
https://github.com/vitaliy-bobrov/ionic-img-cache/blob/007f290429eaeb42b22700c4c2e6c67a57807f44/ionic-img-cache.js#L154-L174
20,344
vitaliy-bobrov/ionic-img-cache
ionic-img-cache.js
checkBgCacheStatus
function checkBgCacheStatus(element) { var defer = $q.defer(); _checkImgCacheReady() .then(function() { ImgCache.isBackgroundCached(element, function(path, success) { if (success) { defer.resolve(path); } else { ImgCache.cacheBackground(element, function() { ImgCache.isBackgroundCached(element, function(path, success) { defer.resolve(path); }, defer.reject); }, defer.reject); } }, defer.reject); }) .catch(defer.reject); return defer.promise; }
javascript
function checkBgCacheStatus(element) { var defer = $q.defer(); _checkImgCacheReady() .then(function() { ImgCache.isBackgroundCached(element, function(path, success) { if (success) { defer.resolve(path); } else { ImgCache.cacheBackground(element, function() { ImgCache.isBackgroundCached(element, function(path, success) { defer.resolve(path); }, defer.reject); }, defer.reject); } }, defer.reject); }) .catch(defer.reject); return defer.promise; }
[ "function", "checkBgCacheStatus", "(", "element", ")", "{", "var", "defer", "=", "$q", ".", "defer", "(", ")", ";", "_checkImgCacheReady", "(", ")", ".", "then", "(", "function", "(", ")", "{", "ImgCache", ".", "isBackgroundCached", "(", "element", ",", "function", "(", "path", ",", "success", ")", "{", "if", "(", "success", ")", "{", "defer", ".", "resolve", "(", "path", ")", ";", "}", "else", "{", "ImgCache", ".", "cacheBackground", "(", "element", ",", "function", "(", ")", "{", "ImgCache", ".", "isBackgroundCached", "(", "element", ",", "function", "(", "path", ",", "success", ")", "{", "defer", ".", "resolve", "(", "path", ")", ";", "}", ",", "defer", ".", "reject", ")", ";", "}", ",", "defer", ".", "reject", ")", ";", "}", "}", ",", "defer", ".", "reject", ")", ";", "}", ")", ".", "catch", "(", "defer", ".", "reject", ")", ";", "return", "defer", ".", "promise", ";", "}" ]
Checks elements background file cache status by element. @param {HTMLElement} element - element with background image.
[ "Checks", "elements", "background", "file", "cache", "status", "by", "element", "." ]
007f290429eaeb42b22700c4c2e6c67a57807f44
https://github.com/vitaliy-bobrov/ionic-img-cache/blob/007f290429eaeb42b22700c4c2e6c67a57807f44/ionic-img-cache.js#L180-L200
20,345
vitaliy-bobrov/ionic-img-cache
ionic-img-cache.js
clearCache
function clearCache() { var defer = $q.defer(); _checkImgCacheReady() .then(function() { ImgCache.clearCache(defer.resolve, defer.reject); }) .catch(defer.reject); return defer.promise; }
javascript
function clearCache() { var defer = $q.defer(); _checkImgCacheReady() .then(function() { ImgCache.clearCache(defer.resolve, defer.reject); }) .catch(defer.reject); return defer.promise; }
[ "function", "clearCache", "(", ")", "{", "var", "defer", "=", "$q", ".", "defer", "(", ")", ";", "_checkImgCacheReady", "(", ")", ".", "then", "(", "function", "(", ")", "{", "ImgCache", ".", "clearCache", "(", "defer", ".", "resolve", ",", "defer", ".", "reject", ")", ";", "}", ")", ".", "catch", "(", "defer", ".", "reject", ")", ";", "return", "defer", ".", "promise", ";", "}" ]
Clears all cahced files.
[ "Clears", "all", "cahced", "files", "." ]
007f290429eaeb42b22700c4c2e6c67a57807f44
https://github.com/vitaliy-bobrov/ionic-img-cache/blob/007f290429eaeb42b22700c4c2e6c67a57807f44/ionic-img-cache.js#L205-L215
20,346
vitaliy-bobrov/ionic-img-cache
ionic-img-cache.js
getCacheSize
function getCacheSize() { var defer = $q.defer(); _checkImgCacheReady() .then(function() { defer.resolve(ImgCache.getCurrentSize()); }) .catch(defer.reject); return defer.promise; }
javascript
function getCacheSize() { var defer = $q.defer(); _checkImgCacheReady() .then(function() { defer.resolve(ImgCache.getCurrentSize()); }) .catch(defer.reject); return defer.promise; }
[ "function", "getCacheSize", "(", ")", "{", "var", "defer", "=", "$q", ".", "defer", "(", ")", ";", "_checkImgCacheReady", "(", ")", ".", "then", "(", "function", "(", ")", "{", "defer", ".", "resolve", "(", "ImgCache", ".", "getCurrentSize", "(", ")", ")", ";", "}", ")", ".", "catch", "(", "defer", ".", "reject", ")", ";", "return", "defer", ".", "promise", ";", "}" ]
Gets local cache size in bytes.
[ "Gets", "local", "cache", "size", "in", "bytes", "." ]
007f290429eaeb42b22700c4c2e6c67a57807f44
https://github.com/vitaliy-bobrov/ionic-img-cache/blob/007f290429eaeb42b22700c4c2e6c67a57807f44/ionic-img-cache.js#L220-L230
20,347
vitaliy-bobrov/ionic-img-cache
ionic-img-cache.js
_checkImgCacheReady
function _checkImgCacheReady() { var defer = $q.defer(); if (ImgCache.ready) { defer.resolve(); } else{ document.addEventListener('ImgCacheReady', function() { // eslint-disable-line defer.resolve(); }, false); } return defer.promise; }
javascript
function _checkImgCacheReady() { var defer = $q.defer(); if (ImgCache.ready) { defer.resolve(); } else{ document.addEventListener('ImgCacheReady', function() { // eslint-disable-line defer.resolve(); }, false); } return defer.promise; }
[ "function", "_checkImgCacheReady", "(", ")", "{", "var", "defer", "=", "$q", ".", "defer", "(", ")", ";", "if", "(", "ImgCache", ".", "ready", ")", "{", "defer", ".", "resolve", "(", ")", ";", "}", "else", "{", "document", ".", "addEventListener", "(", "'ImgCacheReady'", ",", "function", "(", ")", "{", "// eslint-disable-line", "defer", ".", "resolve", "(", ")", ";", "}", ",", "false", ")", ";", "}", "return", "defer", ".", "promise", ";", "}" ]
Checks if imgcache library initialized. @private
[ "Checks", "if", "imgcache", "library", "initialized", "." ]
007f290429eaeb42b22700c4c2e6c67a57807f44
https://github.com/vitaliy-bobrov/ionic-img-cache/blob/007f290429eaeb42b22700c4c2e6c67a57807f44/ionic-img-cache.js#L236-L249
20,348
vincentbernat/nodecastor
lib/channel.js
randomString
function randomString(length) { var bits = 36, tmp, out = ""; while (out.length < length) { tmp = Math.random().toString(bits).slice(2); out += tmp.slice(0, Math.min(tmp.length, (length - out.length))); } return out.toUpperCase(); }
javascript
function randomString(length) { var bits = 36, tmp, out = ""; while (out.length < length) { tmp = Math.random().toString(bits).slice(2); out += tmp.slice(0, Math.min(tmp.length, (length - out.length))); } return out.toUpperCase(); }
[ "function", "randomString", "(", "length", ")", "{", "var", "bits", "=", "36", ",", "tmp", ",", "out", "=", "\"\"", ";", "while", "(", "out", ".", "length", "<", "length", ")", "{", "tmp", "=", "Math", ".", "random", "(", ")", ".", "toString", "(", "bits", ")", ".", "slice", "(", "2", ")", ";", "out", "+=", "tmp", ".", "slice", "(", "0", ",", "Math", ".", "min", "(", "tmp", ".", "length", ",", "(", "length", "-", "out", ".", "length", ")", ")", ")", ";", "}", "return", "out", ".", "toUpperCase", "(", ")", ";", "}" ]
Provide a random string
[ "Provide", "a", "random", "string" ]
808a74c3ae0e2bfec6cdd441c53fa2050648b3d9
https://github.com/vincentbernat/nodecastor/blob/808a74c3ae0e2bfec6cdd441c53fa2050648b3d9/lib/channel.js#L16-L25
20,349
vincentbernat/nodecastor
lib/channel.js
logtap
function logtap(logger, message, data) { data = _.clone(data); if (data.payload_binary) { data.payload_binary = '... (' + data.payload_binary.length + ' bytes)'; } logger.debug(message, data); }
javascript
function logtap(logger, message, data) { data = _.clone(data); if (data.payload_binary) { data.payload_binary = '... (' + data.payload_binary.length + ' bytes)'; } logger.debug(message, data); }
[ "function", "logtap", "(", "logger", ",", "message", ",", "data", ")", "{", "data", "=", "_", ".", "clone", "(", "data", ")", ";", "if", "(", "data", ".", "payload_binary", ")", "{", "data", ".", "payload_binary", "=", "'... ('", "+", "data", ".", "payload_binary", ".", "length", "+", "' bytes)'", ";", "}", "logger", ".", "debug", "(", "message", ",", "data", ")", ";", "}" ]
Log some protobuf message
[ "Log", "some", "protobuf", "message" ]
808a74c3ae0e2bfec6cdd441c53fa2050648b3d9
https://github.com/vincentbernat/nodecastor/blob/808a74c3ae0e2bfec6cdd441c53fa2050648b3d9/lib/channel.js#L28-L34
20,350
vincentbernat/nodecastor
lib/channel.js
function(message) { if (message.namespace === data.namespace && message.data.requestId === data.data.requestId) { if (timer) { clearTimeout(timer); } self.removeListener('message', answer); self.removeListener('disconnect', cancel); cb(null, message); } }
javascript
function(message) { if (message.namespace === data.namespace && message.data.requestId === data.data.requestId) { if (timer) { clearTimeout(timer); } self.removeListener('message', answer); self.removeListener('disconnect', cancel); cb(null, message); } }
[ "function", "(", "message", ")", "{", "if", "(", "message", ".", "namespace", "===", "data", ".", "namespace", "&&", "message", ".", "data", ".", "requestId", "===", "data", ".", "data", ".", "requestId", ")", "{", "if", "(", "timer", ")", "{", "clearTimeout", "(", "timer", ")", ";", "}", "self", ".", "removeListener", "(", "'message'", ",", "answer", ")", ";", "self", ".", "removeListener", "(", "'disconnect'", ",", "cancel", ")", ";", "cb", "(", "null", ",", "message", ")", ";", "}", "}" ]
Invoked when we get an answer
[ "Invoked", "when", "we", "get", "an", "answer" ]
808a74c3ae0e2bfec6cdd441c53fa2050648b3d9
https://github.com/vincentbernat/nodecastor/blob/808a74c3ae0e2bfec6cdd441c53fa2050648b3d9/lib/channel.js#L213-L223
20,351
benweier/blizzard.js
lib/endpoints.js
getPathHostName
function getPathHostName(origin, path) { const pathOverride = { '/oauth/userinfo': `https://${origin}.battle.net`, }; return Object.prototype.hasOwnProperty.call(pathOverride, path) ? pathOverride[path] : endpoints[origin].hostname; }
javascript
function getPathHostName(origin, path) { const pathOverride = { '/oauth/userinfo': `https://${origin}.battle.net`, }; return Object.prototype.hasOwnProperty.call(pathOverride, path) ? pathOverride[path] : endpoints[origin].hostname; }
[ "function", "getPathHostName", "(", "origin", ",", "path", ")", "{", "const", "pathOverride", "=", "{", "'/oauth/userinfo'", ":", "`", "${", "origin", "}", "`", ",", "}", ";", "return", "Object", ".", "prototype", ".", "hasOwnProperty", ".", "call", "(", "pathOverride", ",", "path", ")", "?", "pathOverride", "[", "path", "]", ":", "endpoints", "[", "origin", "]", ".", "hostname", ";", "}" ]
Get the hostname of a path that may be overridden. @param {String} origin A regional origin @param {String} [path] The requested API path @return {String} The valid hostname for the current path
[ "Get", "the", "hostname", "of", "a", "path", "that", "may", "be", "overridden", "." ]
145f72704f3b2fb7cb864d50519d526c2708a84c
https://github.com/benweier/blizzard.js/blob/145f72704f3b2fb7cb864d50519d526c2708a84c/lib/endpoints.js#L49-L55
20,352
benweier/blizzard.js
lib/endpoints.js
getEndpoint
function getEndpoint(origin, locale, path) { const validOrigin = Object.prototype.hasOwnProperty.call(endpoints, origin) ? origin : 'us'; const endpoint = endpoints[validOrigin]; return Object.assign( {}, { origin: validOrigin }, { hostname: origin === 'cn' ? endpoint.hostname : getPathHostName(validOrigin, path) }, { locale: endpoint.locales.find(item => item === locale) || endpoint.defaultLocale }, ); }
javascript
function getEndpoint(origin, locale, path) { const validOrigin = Object.prototype.hasOwnProperty.call(endpoints, origin) ? origin : 'us'; const endpoint = endpoints[validOrigin]; return Object.assign( {}, { origin: validOrigin }, { hostname: origin === 'cn' ? endpoint.hostname : getPathHostName(validOrigin, path) }, { locale: endpoint.locales.find(item => item === locale) || endpoint.defaultLocale }, ); }
[ "function", "getEndpoint", "(", "origin", ",", "locale", ",", "path", ")", "{", "const", "validOrigin", "=", "Object", ".", "prototype", ".", "hasOwnProperty", ".", "call", "(", "endpoints", ",", "origin", ")", "?", "origin", ":", "'us'", ";", "const", "endpoint", "=", "endpoints", "[", "validOrigin", "]", ";", "return", "Object", ".", "assign", "(", "{", "}", ",", "{", "origin", ":", "validOrigin", "}", ",", "{", "hostname", ":", "origin", "===", "'cn'", "?", "endpoint", ".", "hostname", ":", "getPathHostName", "(", "validOrigin", ",", "path", ")", "}", ",", "{", "locale", ":", "endpoint", ".", "locales", ".", "find", "(", "item", "=>", "item", "===", "locale", ")", "||", "endpoint", ".", "defaultLocale", "}", ",", ")", ";", "}" ]
Get the endpoint for a given region. @param {String} [origin] A regional origin @param {String} [locale] A regional locale @param {String} [path] A requested API path @return {Object} The endpoint data object
[ "Get", "the", "endpoint", "for", "a", "given", "region", "." ]
145f72704f3b2fb7cb864d50519d526c2708a84c
https://github.com/benweier/blizzard.js/blob/145f72704f3b2fb7cb864d50519d526c2708a84c/lib/endpoints.js#L65-L75
20,353
benweier/blizzard.js
lib/blizzard.js
Blizzard
function Blizzard(args, instance) { const { key, secret, token } = args; const { origin, locale } = endpoints.getEndpoint(args.origin, args.locale); this.version = pkg.version; this.defaults = { origin, locale, key, secret, token, }; this.axios = axios.create(instance); /** * Account API methods. * * @member {Object} * @see {@link lib/account} */ this.account = new Account(this); /** * Profile API methods. * * @member {Object} * @see {@link lib/profile} */ this.profile = new Profile(this); /** * Diablo 3 API methods. * * @member {Object} * @see {@link lib/d3} */ this.d3 = new Diablo3(this); /** * Starcraft 2 API methods. * * @member {Object} * @see {@link lib/sc2} */ this.sc2 = new Starcraft2(this); /** * World of Warcraft API methods. * * @member {Object} * @see {@link lib/wow} */ this.wow = new WorldOfWarcraft(this); }
javascript
function Blizzard(args, instance) { const { key, secret, token } = args; const { origin, locale } = endpoints.getEndpoint(args.origin, args.locale); this.version = pkg.version; this.defaults = { origin, locale, key, secret, token, }; this.axios = axios.create(instance); /** * Account API methods. * * @member {Object} * @see {@link lib/account} */ this.account = new Account(this); /** * Profile API methods. * * @member {Object} * @see {@link lib/profile} */ this.profile = new Profile(this); /** * Diablo 3 API methods. * * @member {Object} * @see {@link lib/d3} */ this.d3 = new Diablo3(this); /** * Starcraft 2 API methods. * * @member {Object} * @see {@link lib/sc2} */ this.sc2 = new Starcraft2(this); /** * World of Warcraft API methods. * * @member {Object} * @see {@link lib/wow} */ this.wow = new WorldOfWarcraft(this); }
[ "function", "Blizzard", "(", "args", ",", "instance", ")", "{", "const", "{", "key", ",", "secret", ",", "token", "}", "=", "args", ";", "const", "{", "origin", ",", "locale", "}", "=", "endpoints", ".", "getEndpoint", "(", "args", ".", "origin", ",", "args", ".", "locale", ")", ";", "this", ".", "version", "=", "pkg", ".", "version", ";", "this", ".", "defaults", "=", "{", "origin", ",", "locale", ",", "key", ",", "secret", ",", "token", ",", "}", ";", "this", ".", "axios", "=", "axios", ".", "create", "(", "instance", ")", ";", "/**\n * Account API methods.\n *\n * @member {Object}\n * @see {@link lib/account}\n */", "this", ".", "account", "=", "new", "Account", "(", "this", ")", ";", "/**\n * Profile API methods.\n *\n * @member {Object}\n * @see {@link lib/profile}\n */", "this", ".", "profile", "=", "new", "Profile", "(", "this", ")", ";", "/**\n * Diablo 3 API methods.\n *\n * @member {Object}\n * @see {@link lib/d3}\n */", "this", ".", "d3", "=", "new", "Diablo3", "(", "this", ")", ";", "/**\n * Starcraft 2 API methods.\n *\n * @member {Object}\n * @see {@link lib/sc2}\n */", "this", ".", "sc2", "=", "new", "Starcraft2", "(", "this", ")", ";", "/**\n * World of Warcraft API methods.\n *\n * @member {Object}\n * @see {@link lib/wow}\n */", "this", ".", "wow", "=", "new", "WorldOfWarcraft", "(", "this", ")", ";", "}" ]
Blizzard.js class constructor. @constructor @param {Object} [args] Blizzard.js configuration @param {String} [args.origin] The API region @param {String} [args.locale] The API locale @param {String} [args.key] The API client ID @param {String} [args.secret] The API client secret @param {String} [args.token] The API access token @param {Object} [instance] An [axios](https://github.com/mzabriskie/axios) compatible instance configuration
[ "Blizzard", ".", "js", "class", "constructor", "." ]
145f72704f3b2fb7cb864d50519d526c2708a84c
https://github.com/benweier/blizzard.js/blob/145f72704f3b2fb7cb864d50519d526c2708a84c/lib/blizzard.js#L37-L90
20,354
jonschlinkert/unescape
index.js
unescape
function unescape(str, type) { if (!isString(str)) return ''; var chars = charSets[type || 'default']; var regex = toRegex(type, chars); return str.replace(regex, function(m) { return chars[m]; }); }
javascript
function unescape(str, type) { if (!isString(str)) return ''; var chars = charSets[type || 'default']; var regex = toRegex(type, chars); return str.replace(regex, function(m) { return chars[m]; }); }
[ "function", "unescape", "(", "str", ",", "type", ")", "{", "if", "(", "!", "isString", "(", "str", ")", ")", "return", "''", ";", "var", "chars", "=", "charSets", "[", "type", "||", "'default'", "]", ";", "var", "regex", "=", "toRegex", "(", "type", ",", "chars", ")", ";", "return", "str", ".", "replace", "(", "regex", ",", "function", "(", "m", ")", "{", "return", "chars", "[", "m", "]", ";", "}", ")", ";", "}" ]
Convert HTML entities to HTML characters. @param {String} `str` String with HTML entities to un-escape. @return {String}
[ "Convert", "HTML", "entities", "to", "HTML", "characters", "." ]
98d1e52e7aaba2b1fcd982c8424b1121c8ae37c2
https://github.com/jonschlinkert/unescape/blob/98d1e52e7aaba2b1fcd982c8424b1121c8ae37c2/index.js#L59-L66
20,355
soanvig/jsr
src/helpers/roundToStepRatio.js
roundToStepRatio
function roundToStepRatio (value, stepRatio) { const stepRatioDecimals = calculateDecimals(stepRatio); const stepDecimalsMultiplier = Math.pow(10, stepRatioDecimals); value = Math.round(value / stepRatio) * stepRatio; return Math.round(value * stepDecimalsMultiplier) / stepDecimalsMultiplier; }
javascript
function roundToStepRatio (value, stepRatio) { const stepRatioDecimals = calculateDecimals(stepRatio); const stepDecimalsMultiplier = Math.pow(10, stepRatioDecimals); value = Math.round(value / stepRatio) * stepRatio; return Math.round(value * stepDecimalsMultiplier) / stepDecimalsMultiplier; }
[ "function", "roundToStepRatio", "(", "value", ",", "stepRatio", ")", "{", "const", "stepRatioDecimals", "=", "calculateDecimals", "(", "stepRatio", ")", ";", "const", "stepDecimalsMultiplier", "=", "Math", ".", "pow", "(", "10", ",", "stepRatioDecimals", ")", ";", "value", "=", "Math", ".", "round", "(", "value", "/", "stepRatio", ")", "*", "stepRatio", ";", "return", "Math", ".", "round", "(", "value", "*", "stepDecimalsMultiplier", ")", "/", "stepDecimalsMultiplier", ";", "}" ]
Rounds value to step ratio
[ "Rounds", "value", "to", "step", "ratio" ]
620112ac3095623526db067e739a5916c6b1153f
https://github.com/soanvig/jsr/blob/620112ac3095623526db067e739a5916c6b1153f/src/helpers/roundToStepRatio.js#L4-L11
20,356
soanvig/jsr
src/helpers/findSameInArray.js
findSameInArray
function findSameInArray (array, compareIndex) { const sliders = []; array.forEach((value, index) => { if (value === array[compareIndex]) { sliders.push(index); } }); return sliders; }
javascript
function findSameInArray (array, compareIndex) { const sliders = []; array.forEach((value, index) => { if (value === array[compareIndex]) { sliders.push(index); } }); return sliders; }
[ "function", "findSameInArray", "(", "array", ",", "compareIndex", ")", "{", "const", "sliders", "=", "[", "]", ";", "array", ".", "forEach", "(", "(", "value", ",", "index", ")", "=>", "{", "if", "(", "value", "===", "array", "[", "compareIndex", "]", ")", "{", "sliders", ".", "push", "(", "index", ")", ";", "}", "}", ")", ";", "return", "sliders", ";", "}" ]
Returns ids of items with the same value as value of item with 'compareIndex' index
[ "Returns", "ids", "of", "items", "with", "the", "same", "value", "as", "value", "of", "item", "with", "compareIndex", "index" ]
620112ac3095623526db067e739a5916c6b1153f
https://github.com/soanvig/jsr/blob/620112ac3095623526db067e739a5916c6b1153f/src/helpers/findSameInArray.js#L2-L12
20,357
soanvig/jsr
src/helpers/findClosestValue.js
findClosestValue
function findClosestValue (values, lookupVal) { let diff = 1; let id = 0; values.forEach((value, index) => { const actualDiff = Math.abs(value - lookupVal); if (actualDiff < diff) { id = index; diff = actualDiff; } }); return id; }
javascript
function findClosestValue (values, lookupVal) { let diff = 1; let id = 0; values.forEach((value, index) => { const actualDiff = Math.abs(value - lookupVal); if (actualDiff < diff) { id = index; diff = actualDiff; } }); return id; }
[ "function", "findClosestValue", "(", "values", ",", "lookupVal", ")", "{", "let", "diff", "=", "1", ";", "let", "id", "=", "0", ";", "values", ".", "forEach", "(", "(", "value", ",", "index", ")", "=>", "{", "const", "actualDiff", "=", "Math", ".", "abs", "(", "value", "-", "lookupVal", ")", ";", "if", "(", "actualDiff", "<", "diff", ")", "{", "id", "=", "index", ";", "diff", "=", "actualDiff", ";", "}", "}", ")", ";", "return", "id", ";", "}" ]
Returns id of value in this.values, which is closest to `lookupVal`
[ "Returns", "id", "of", "value", "in", "this", ".", "values", "which", "is", "closest", "to", "lookupVal" ]
620112ac3095623526db067e739a5916c6b1153f
https://github.com/soanvig/jsr/blob/620112ac3095623526db067e739a5916c6b1153f/src/helpers/findClosestValue.js#L2-L15
20,358
soanvig/jsr
src/helpers/roundToStep.js
roundToStep
function roundToStep (value, step) { const stepDecimals = calculateDecimals(step); const stepDecimalsMultiplier = Math.pow(10, stepDecimals); value = Math.round(value / step) * step; return Math.round(value * stepDecimalsMultiplier) / stepDecimalsMultiplier; }
javascript
function roundToStep (value, step) { const stepDecimals = calculateDecimals(step); const stepDecimalsMultiplier = Math.pow(10, stepDecimals); value = Math.round(value / step) * step; return Math.round(value * stepDecimalsMultiplier) / stepDecimalsMultiplier; }
[ "function", "roundToStep", "(", "value", ",", "step", ")", "{", "const", "stepDecimals", "=", "calculateDecimals", "(", "step", ")", ";", "const", "stepDecimalsMultiplier", "=", "Math", ".", "pow", "(", "10", ",", "stepDecimals", ")", ";", "value", "=", "Math", ".", "round", "(", "value", "/", "step", ")", "*", "step", ";", "return", "Math", ".", "round", "(", "value", "*", "stepDecimalsMultiplier", ")", "/", "stepDecimalsMultiplier", ";", "}" ]
Rounds value to step
[ "Rounds", "value", "to", "step" ]
620112ac3095623526db067e739a5916c6b1153f
https://github.com/soanvig/jsr/blob/620112ac3095623526db067e739a5916c6b1153f/src/helpers/roundToStep.js#L4-L11
20,359
danielstjules/redislock
spec/lockSpec.js
function(lock) { lock.acquire = function(key, fn) { Lock._acquiredLocks[lock._id] = lock; lock._locked = true; lock._key = key; return client.setAsync(key, lock._id).nodeify(fn); }; }
javascript
function(lock) { lock.acquire = function(key, fn) { Lock._acquiredLocks[lock._id] = lock; lock._locked = true; lock._key = key; return client.setAsync(key, lock._id).nodeify(fn); }; }
[ "function", "(", "lock", ")", "{", "lock", ".", "acquire", "=", "function", "(", "key", ",", "fn", ")", "{", "Lock", ".", "_acquiredLocks", "[", "lock", ".", "_id", "]", "=", "lock", ";", "lock", ".", "_locked", "=", "true", ";", "lock", ".", "_key", "=", "key", ";", "return", "client", ".", "setAsync", "(", "key", ",", "lock", ".", "_id", ")", ".", "nodeify", "(", "fn", ")", ";", "}", ";", "}" ]
Used to mock a Lock's acquire method
[ "Used", "to", "mock", "a", "Lock", "s", "acquire", "method" ]
a8241e6ff057b843cf376d9f9edd143079c753ab
https://github.com/danielstjules/redislock/blob/a8241e6ff057b843cf376d9f9edd143079c753ab/spec/lockSpec.js#L24-L31
20,360
cssjanus/cssjanus
src/cssjanus.js
Tokenizer
function Tokenizer( regex, token ) { var matches = [], index = 0; /** * Add a match. * * @private * @param {string} match Matched string * @return {string} Token to leave in the matched string's place */ function tokenizeCallback( match ) { matches.push( match ); return token; } /** * Get a match. * * @private * @return {string} Original matched string to restore */ function detokenizeCallback() { return matches[ index++ ]; } return { /** * Replace matching strings with tokens. * * @param {string} str String to tokenize * @return {string} Tokenized string */ tokenize: function ( str ) { return str.replace( regex, tokenizeCallback ); }, /** * Restores tokens to their original values. * * @param {string} str String previously run through tokenize() * @return {string} Original string */ detokenize: function ( str ) { return str.replace( new RegExp( '(' + token + ')', 'g' ), detokenizeCallback ); } }; }
javascript
function Tokenizer( regex, token ) { var matches = [], index = 0; /** * Add a match. * * @private * @param {string} match Matched string * @return {string} Token to leave in the matched string's place */ function tokenizeCallback( match ) { matches.push( match ); return token; } /** * Get a match. * * @private * @return {string} Original matched string to restore */ function detokenizeCallback() { return matches[ index++ ]; } return { /** * Replace matching strings with tokens. * * @param {string} str String to tokenize * @return {string} Tokenized string */ tokenize: function ( str ) { return str.replace( regex, tokenizeCallback ); }, /** * Restores tokens to their original values. * * @param {string} str String previously run through tokenize() * @return {string} Original string */ detokenize: function ( str ) { return str.replace( new RegExp( '(' + token + ')', 'g' ), detokenizeCallback ); } }; }
[ "function", "Tokenizer", "(", "regex", ",", "token", ")", "{", "var", "matches", "=", "[", "]", ",", "index", "=", "0", ";", "/**\n\t * Add a match.\n\t *\n\t * @private\n\t * @param {string} match Matched string\n\t * @return {string} Token to leave in the matched string's place\n\t */", "function", "tokenizeCallback", "(", "match", ")", "{", "matches", ".", "push", "(", "match", ")", ";", "return", "token", ";", "}", "/**\n\t * Get a match.\n\t *\n\t * @private\n\t * @return {string} Original matched string to restore\n\t */", "function", "detokenizeCallback", "(", ")", "{", "return", "matches", "[", "index", "++", "]", ";", "}", "return", "{", "/**\n\t\t * Replace matching strings with tokens.\n\t\t *\n\t\t * @param {string} str String to tokenize\n\t\t * @return {string} Tokenized string\n\t\t */", "tokenize", ":", "function", "(", "str", ")", "{", "return", "str", ".", "replace", "(", "regex", ",", "tokenizeCallback", ")", ";", "}", ",", "/**\n\t\t * Restores tokens to their original values.\n\t\t *\n\t\t * @param {string} str String previously run through tokenize()\n\t\t * @return {string} Original string\n\t\t */", "detokenize", ":", "function", "(", "str", ")", "{", "return", "str", ".", "replace", "(", "new", "RegExp", "(", "'('", "+", "token", "+", "')'", ",", "'g'", ")", ",", "detokenizeCallback", ")", ";", "}", "}", ";", "}" ]
Create a tokenizer object. This utility class is used by CSSJanus to protect strings by replacing them temporarily with tokens and later transforming them back. @author Trevor Parscal @author Roan Kattouw @class @constructor @param {RegExp} regex Regular expression whose matches to replace by a token @param {string} token Placeholder text
[ "Create", "a", "tokenizer", "object", "." ]
9ffc4051601bafdd410f65448ec445f21148581c
https://github.com/cssjanus/cssjanus/blob/9ffc4051601bafdd410f65448ec445f21148581c/src/cssjanus.js#L25-L73
20,361
cssjanus/cssjanus
src/cssjanus.js
CSSJanus
function CSSJanus() { var // Tokens temporaryToken = '`TMP`', noFlipSingleToken = '`NOFLIP_SINGLE`', noFlipClassToken = '`NOFLIP_CLASS`', commentToken = '`COMMENT`', // Patterns nonAsciiPattern = '[^\\u0020-\\u007e]', unicodePattern = '(?:(?:\\\\[0-9a-f]{1,6})(?:\\r\\n|\\s)?)', numPattern = '(?:[0-9]*\\.[0-9]+|[0-9]+)', unitPattern = '(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)', directionPattern = 'direction\\s*:\\s*', urlSpecialCharsPattern = '[!#$%&*-~]', validAfterUriCharsPattern = '[\'"]?\\s*', nonLetterPattern = '(^|[^a-zA-Z])', charsWithinSelectorPattern = '[^\\}]*?', noFlipPattern = '\\/\\*\\!?\\s*@noflip\\s*\\*\\/', commentPattern = '\\/\\*[^*]*\\*+([^\\/*][^*]*\\*+)*\\/', escapePattern = '(?:' + unicodePattern + '|\\\\[^\\r\\n\\f0-9a-f])', nmstartPattern = '(?:[_a-z]|' + nonAsciiPattern + '|' + escapePattern + ')', nmcharPattern = '(?:[_a-z0-9-]|' + nonAsciiPattern + '|' + escapePattern + ')', identPattern = '-?' + nmstartPattern + nmcharPattern + '*', quantPattern = numPattern + '(?:\\s*' + unitPattern + '|' + identPattern + ')?', signedQuantPattern = '((?:-?' + quantPattern + ')|(?:inherit|auto))', fourNotationQuantPropsPattern = '((?:margin|padding|border-width)\\s*:\\s*)', fourNotationColorPropsPattern = '((?:-color|border-style)\\s*:\\s*)', colorPattern = '(#?' + nmcharPattern + '+|(?:rgba?|hsla?)\\([ \\d.,%-]+\\))', urlCharsPattern = '(?:' + urlSpecialCharsPattern + '|' + nonAsciiPattern + '|' + escapePattern + ')*', lookAheadNotLetterPattern = '(?![a-zA-Z])', lookAheadNotOpenBracePattern = '(?!(' + nmcharPattern + '|\\r?\\n|\\s|#|\\:|\\.|\\,|\\+|>|\\(|\\)|\\[|\\]|=|\\*=|~=|\\^=|\'[^\']*\'])*?{)', lookAheadNotClosingParenPattern = '(?!' + urlCharsPattern + '?' + validAfterUriCharsPattern + '\\))', lookAheadForClosingParenPattern = '(?=' + urlCharsPattern + '?' + validAfterUriCharsPattern + '\\))', suffixPattern = '(\\s*(?:!important\\s*)?[;}])', // Regular expressions temporaryTokenRegExp = new RegExp( '`TMP`', 'g' ), commentRegExp = new RegExp( commentPattern, 'gi' ), noFlipSingleRegExp = new RegExp( '(' + noFlipPattern + lookAheadNotOpenBracePattern + '[^;}]+;?)', 'gi' ), noFlipClassRegExp = new RegExp( '(' + noFlipPattern + charsWithinSelectorPattern + '})', 'gi' ), directionLtrRegExp = new RegExp( '(' + directionPattern + ')ltr', 'gi' ), directionRtlRegExp = new RegExp( '(' + directionPattern + ')rtl', 'gi' ), leftRegExp = new RegExp( nonLetterPattern + '(left)' + lookAheadNotLetterPattern + lookAheadNotClosingParenPattern + lookAheadNotOpenBracePattern, 'gi' ), rightRegExp = new RegExp( nonLetterPattern + '(right)' + lookAheadNotLetterPattern + lookAheadNotClosingParenPattern + lookAheadNotOpenBracePattern, 'gi' ), leftInUrlRegExp = new RegExp( nonLetterPattern + '(left)' + lookAheadForClosingParenPattern, 'gi' ), rightInUrlRegExp = new RegExp( nonLetterPattern + '(right)' + lookAheadForClosingParenPattern, 'gi' ), ltrInUrlRegExp = new RegExp( nonLetterPattern + '(ltr)' + lookAheadForClosingParenPattern, 'gi' ), rtlInUrlRegExp = new RegExp( nonLetterPattern + '(rtl)' + lookAheadForClosingParenPattern, 'gi' ), cursorEastRegExp = new RegExp( nonLetterPattern + '([ns]?)e-resize', 'gi' ), cursorWestRegExp = new RegExp( nonLetterPattern + '([ns]?)w-resize', 'gi' ), fourNotationQuantRegExp = new RegExp( fourNotationQuantPropsPattern + signedQuantPattern + '(\\s+)' + signedQuantPattern + '(\\s+)' + signedQuantPattern + '(\\s+)' + signedQuantPattern + suffixPattern, 'gi' ), fourNotationColorRegExp = new RegExp( fourNotationColorPropsPattern + colorPattern + '(\\s+)' + colorPattern + '(\\s+)' + colorPattern + '(\\s+)' + colorPattern + suffixPattern, 'gi' ), bgHorizontalPercentageRegExp = new RegExp( '(background(?:-position)?\\s*:\\s*(?:[^:;}\\s]+\\s+)*?)(' + quantPattern + ')', 'gi' ), bgHorizontalPercentageXRegExp = new RegExp( '(background-position-x\\s*:\\s*)(-?' + numPattern + '%)', 'gi' ), // border-radius: <length or percentage>{1,4} [optional: / <length or percentage>{1,4} ] borderRadiusRegExp = new RegExp( '(border-radius\\s*:\\s*)' + signedQuantPattern + '(?:(?:\\s+' + signedQuantPattern + ')(?:\\s+' + signedQuantPattern + ')?(?:\\s+' + signedQuantPattern + ')?)?' + '(?:(?:(?:\\s*\\/\\s*)' + signedQuantPattern + ')(?:\\s+' + signedQuantPattern + ')?(?:\\s+' + signedQuantPattern + ')?(?:\\s+' + signedQuantPattern + ')?)?' + suffixPattern, 'gi' ), boxShadowRegExp = new RegExp( '(box-shadow\\s*:\\s*(?:inset\\s*)?)' + signedQuantPattern, 'gi' ), textShadow1RegExp = new RegExp( '(text-shadow\\s*:\\s*)' + signedQuantPattern + '(\\s*)' + colorPattern, 'gi' ), textShadow2RegExp = new RegExp( '(text-shadow\\s*:\\s*)' + colorPattern + '(\\s*)' + signedQuantPattern, 'gi' ), textShadow3RegExp = new RegExp( '(text-shadow\\s*:\\s*)' + signedQuantPattern, 'gi' ), translateXRegExp = new RegExp( '(transform\\s*:[^;}]*)(translateX\\s*\\(\\s*)' + signedQuantPattern + '(\\s*\\))', 'gi' ), translateRegExp = new RegExp( '(transform\\s*:[^;}]*)(translate\\s*\\(\\s*)' + signedQuantPattern + '((?:\\s*,\\s*' + signedQuantPattern + '){0,2}\\s*\\))', 'gi' ); /** * Invert the horizontal value of a background position property. * * @private * @param {string} match Matched property * @param {string} pre Text before value * @param {string} value Horizontal value * @return {string} Inverted property */ function calculateNewBackgroundPosition( match, pre, value ) { var idx, len; if ( value.slice( -1 ) === '%' ) { idx = value.indexOf( '.' ); if ( idx !== -1 ) { // Two off, one for the "%" at the end, one for the dot itself len = value.length - idx - 2; value = 100 - parseFloat( value ); value = value.toFixed( len ) + '%'; } else { value = 100 - parseFloat( value ) + '%'; } } return pre + value; } /** * Invert a set of border radius values. * * @private * @param {Array} values Matched values * @return {string} Inverted values */ function flipBorderRadiusValues( values ) { switch ( values.length ) { case 4: values = [ values[ 1 ], values[ 0 ], values[ 3 ], values[ 2 ] ]; break; case 3: values = [ values[ 1 ], values[ 0 ], values[ 1 ], values[ 2 ] ]; break; case 2: values = [ values[ 1 ], values[ 0 ] ]; break; case 1: values = [ values[ 0 ] ]; break; } return values.join( ' ' ); } /** * Invert a set of border radius values. * * @private * @param {string} match Matched property * @param {string} pre Text before value * @param {string} [firstGroup1] * @param {string} [firstGroup2] * @param {string} [firstGroup3] * @param {string} [firstGroup4] * @param {string} [secondGroup1] * @param {string} [secondGroup2] * @param {string} [secondGroup3] * @param {string} [secondGroup4] * @param {string} [post] Text after value * @return {string} Inverted property */ function calculateNewBorderRadius( match, pre ) { var values, args = [].slice.call( arguments ), firstGroup = args.slice( 2, 6 ).filter( function ( val ) { return val; } ), secondGroup = args.slice( 6, 10 ).filter( function ( val ) { return val; } ), post = args[ 10 ] || ''; if ( secondGroup.length ) { values = flipBorderRadiusValues( firstGroup ) + ' / ' + flipBorderRadiusValues( secondGroup ); } else { values = flipBorderRadiusValues( firstGroup ); } return pre + values + post; } /** * Flip the sign of a CSS value, possibly with a unit. * * We can't just negate the value with unary minus due to the units. * * @private * @param {string} value * @return {string} */ function flipSign( value ) { if ( parseFloat( value ) === 0 ) { // Don't mangle zeroes return value; } if ( value[ 0 ] === '-' ) { return value.slice( 1 ); } return '-' + value; } /** * @private * @param {string} match * @param {string} property * @param {string} offset * @return {string} */ function calculateNewShadow( match, property, offset ) { return property + flipSign( offset ); } /** * @private * @param {string} match * @param {string} property * @param {string} prefix * @param {string} offset * @param {string} suffix * @return {string} */ function calculateNewTranslate( match, property, prefix, offset, suffix ) { return property + prefix + flipSign( offset ) + suffix; } /** * @private * @param {string} match * @param {string} property * @param {string} color * @param {string} space * @param {string} offset * @return {string} */ function calculateNewFourTextShadow( match, property, color, space, offset ) { return property + color + space + flipSign( offset ); } return { /** * Transform a left-to-right stylesheet to right-to-left. * * @param {string} css Stylesheet to transform * @param {Object} options Options * @param {boolean} [options.transformDirInUrl=false] Transform directions in URLs (e.g. 'ltr', 'rtl') * @param {boolean} [options.transformEdgeInUrl=false] Transform edges in URLs (e.g. 'left', 'right') * @return {string} Transformed stylesheet */ 'transform': function ( css, options ) { // eslint-disable-line quote-props, (for closure compiler) // Tokenizers var noFlipSingleTokenizer = new Tokenizer( noFlipSingleRegExp, noFlipSingleToken ), noFlipClassTokenizer = new Tokenizer( noFlipClassRegExp, noFlipClassToken ), commentTokenizer = new Tokenizer( commentRegExp, commentToken ); // Tokenize css = commentTokenizer.tokenize( noFlipClassTokenizer.tokenize( noFlipSingleTokenizer.tokenize( // We wrap tokens in ` , not ~ like the original implementation does. // This was done because ` is not a legal character in CSS and can only // occur in URLs, where we escape it to %60 before inserting our tokens. css.replace( '`', '%60' ) ) ) ); // Transform URLs if ( options.transformDirInUrl ) { // Replace 'ltr' with 'rtl' and vice versa in background URLs css = css .replace( ltrInUrlRegExp, '$1' + temporaryToken ) .replace( rtlInUrlRegExp, '$1ltr' ) .replace( temporaryTokenRegExp, 'rtl' ); } if ( options.transformEdgeInUrl ) { // Replace 'left' with 'right' and vice versa in background URLs css = css .replace( leftInUrlRegExp, '$1' + temporaryToken ) .replace( rightInUrlRegExp, '$1left' ) .replace( temporaryTokenRegExp, 'right' ); } // Transform rules css = css // Replace direction: ltr; with direction: rtl; and vice versa. .replace( directionLtrRegExp, '$1' + temporaryToken ) .replace( directionRtlRegExp, '$1ltr' ) .replace( temporaryTokenRegExp, 'rtl' ) // Flip rules like left: , padding-right: , etc. .replace( leftRegExp, '$1' + temporaryToken ) .replace( rightRegExp, '$1left' ) .replace( temporaryTokenRegExp, 'right' ) // Flip East and West in rules like cursor: nw-resize; .replace( cursorEastRegExp, '$1$2' + temporaryToken ) .replace( cursorWestRegExp, '$1$2e-resize' ) .replace( temporaryTokenRegExp, 'w-resize' ) // Border radius .replace( borderRadiusRegExp, calculateNewBorderRadius ) // Shadows .replace( boxShadowRegExp, calculateNewShadow ) .replace( textShadow1RegExp, calculateNewFourTextShadow ) .replace( textShadow2RegExp, calculateNewFourTextShadow ) .replace( textShadow3RegExp, calculateNewShadow ) // Translate .replace( translateXRegExp, calculateNewTranslate ) .replace( translateRegExp, calculateNewTranslate ) // Swap the second and fourth parts in four-part notation rules // like padding: 1px 2px 3px 4px; .replace( fourNotationQuantRegExp, '$1$2$3$8$5$6$7$4$9' ) .replace( fourNotationColorRegExp, '$1$2$3$8$5$6$7$4$9' ) // Flip horizontal background percentages .replace( bgHorizontalPercentageRegExp, calculateNewBackgroundPosition ) .replace( bgHorizontalPercentageXRegExp, calculateNewBackgroundPosition ); // Detokenize css = noFlipSingleTokenizer.detokenize( noFlipClassTokenizer.detokenize( commentTokenizer.detokenize( css ) ) ); return css; } }; }
javascript
function CSSJanus() { var // Tokens temporaryToken = '`TMP`', noFlipSingleToken = '`NOFLIP_SINGLE`', noFlipClassToken = '`NOFLIP_CLASS`', commentToken = '`COMMENT`', // Patterns nonAsciiPattern = '[^\\u0020-\\u007e]', unicodePattern = '(?:(?:\\\\[0-9a-f]{1,6})(?:\\r\\n|\\s)?)', numPattern = '(?:[0-9]*\\.[0-9]+|[0-9]+)', unitPattern = '(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)', directionPattern = 'direction\\s*:\\s*', urlSpecialCharsPattern = '[!#$%&*-~]', validAfterUriCharsPattern = '[\'"]?\\s*', nonLetterPattern = '(^|[^a-zA-Z])', charsWithinSelectorPattern = '[^\\}]*?', noFlipPattern = '\\/\\*\\!?\\s*@noflip\\s*\\*\\/', commentPattern = '\\/\\*[^*]*\\*+([^\\/*][^*]*\\*+)*\\/', escapePattern = '(?:' + unicodePattern + '|\\\\[^\\r\\n\\f0-9a-f])', nmstartPattern = '(?:[_a-z]|' + nonAsciiPattern + '|' + escapePattern + ')', nmcharPattern = '(?:[_a-z0-9-]|' + nonAsciiPattern + '|' + escapePattern + ')', identPattern = '-?' + nmstartPattern + nmcharPattern + '*', quantPattern = numPattern + '(?:\\s*' + unitPattern + '|' + identPattern + ')?', signedQuantPattern = '((?:-?' + quantPattern + ')|(?:inherit|auto))', fourNotationQuantPropsPattern = '((?:margin|padding|border-width)\\s*:\\s*)', fourNotationColorPropsPattern = '((?:-color|border-style)\\s*:\\s*)', colorPattern = '(#?' + nmcharPattern + '+|(?:rgba?|hsla?)\\([ \\d.,%-]+\\))', urlCharsPattern = '(?:' + urlSpecialCharsPattern + '|' + nonAsciiPattern + '|' + escapePattern + ')*', lookAheadNotLetterPattern = '(?![a-zA-Z])', lookAheadNotOpenBracePattern = '(?!(' + nmcharPattern + '|\\r?\\n|\\s|#|\\:|\\.|\\,|\\+|>|\\(|\\)|\\[|\\]|=|\\*=|~=|\\^=|\'[^\']*\'])*?{)', lookAheadNotClosingParenPattern = '(?!' + urlCharsPattern + '?' + validAfterUriCharsPattern + '\\))', lookAheadForClosingParenPattern = '(?=' + urlCharsPattern + '?' + validAfterUriCharsPattern + '\\))', suffixPattern = '(\\s*(?:!important\\s*)?[;}])', // Regular expressions temporaryTokenRegExp = new RegExp( '`TMP`', 'g' ), commentRegExp = new RegExp( commentPattern, 'gi' ), noFlipSingleRegExp = new RegExp( '(' + noFlipPattern + lookAheadNotOpenBracePattern + '[^;}]+;?)', 'gi' ), noFlipClassRegExp = new RegExp( '(' + noFlipPattern + charsWithinSelectorPattern + '})', 'gi' ), directionLtrRegExp = new RegExp( '(' + directionPattern + ')ltr', 'gi' ), directionRtlRegExp = new RegExp( '(' + directionPattern + ')rtl', 'gi' ), leftRegExp = new RegExp( nonLetterPattern + '(left)' + lookAheadNotLetterPattern + lookAheadNotClosingParenPattern + lookAheadNotOpenBracePattern, 'gi' ), rightRegExp = new RegExp( nonLetterPattern + '(right)' + lookAheadNotLetterPattern + lookAheadNotClosingParenPattern + lookAheadNotOpenBracePattern, 'gi' ), leftInUrlRegExp = new RegExp( nonLetterPattern + '(left)' + lookAheadForClosingParenPattern, 'gi' ), rightInUrlRegExp = new RegExp( nonLetterPattern + '(right)' + lookAheadForClosingParenPattern, 'gi' ), ltrInUrlRegExp = new RegExp( nonLetterPattern + '(ltr)' + lookAheadForClosingParenPattern, 'gi' ), rtlInUrlRegExp = new RegExp( nonLetterPattern + '(rtl)' + lookAheadForClosingParenPattern, 'gi' ), cursorEastRegExp = new RegExp( nonLetterPattern + '([ns]?)e-resize', 'gi' ), cursorWestRegExp = new RegExp( nonLetterPattern + '([ns]?)w-resize', 'gi' ), fourNotationQuantRegExp = new RegExp( fourNotationQuantPropsPattern + signedQuantPattern + '(\\s+)' + signedQuantPattern + '(\\s+)' + signedQuantPattern + '(\\s+)' + signedQuantPattern + suffixPattern, 'gi' ), fourNotationColorRegExp = new RegExp( fourNotationColorPropsPattern + colorPattern + '(\\s+)' + colorPattern + '(\\s+)' + colorPattern + '(\\s+)' + colorPattern + suffixPattern, 'gi' ), bgHorizontalPercentageRegExp = new RegExp( '(background(?:-position)?\\s*:\\s*(?:[^:;}\\s]+\\s+)*?)(' + quantPattern + ')', 'gi' ), bgHorizontalPercentageXRegExp = new RegExp( '(background-position-x\\s*:\\s*)(-?' + numPattern + '%)', 'gi' ), // border-radius: <length or percentage>{1,4} [optional: / <length or percentage>{1,4} ] borderRadiusRegExp = new RegExp( '(border-radius\\s*:\\s*)' + signedQuantPattern + '(?:(?:\\s+' + signedQuantPattern + ')(?:\\s+' + signedQuantPattern + ')?(?:\\s+' + signedQuantPattern + ')?)?' + '(?:(?:(?:\\s*\\/\\s*)' + signedQuantPattern + ')(?:\\s+' + signedQuantPattern + ')?(?:\\s+' + signedQuantPattern + ')?(?:\\s+' + signedQuantPattern + ')?)?' + suffixPattern, 'gi' ), boxShadowRegExp = new RegExp( '(box-shadow\\s*:\\s*(?:inset\\s*)?)' + signedQuantPattern, 'gi' ), textShadow1RegExp = new RegExp( '(text-shadow\\s*:\\s*)' + signedQuantPattern + '(\\s*)' + colorPattern, 'gi' ), textShadow2RegExp = new RegExp( '(text-shadow\\s*:\\s*)' + colorPattern + '(\\s*)' + signedQuantPattern, 'gi' ), textShadow3RegExp = new RegExp( '(text-shadow\\s*:\\s*)' + signedQuantPattern, 'gi' ), translateXRegExp = new RegExp( '(transform\\s*:[^;}]*)(translateX\\s*\\(\\s*)' + signedQuantPattern + '(\\s*\\))', 'gi' ), translateRegExp = new RegExp( '(transform\\s*:[^;}]*)(translate\\s*\\(\\s*)' + signedQuantPattern + '((?:\\s*,\\s*' + signedQuantPattern + '){0,2}\\s*\\))', 'gi' ); /** * Invert the horizontal value of a background position property. * * @private * @param {string} match Matched property * @param {string} pre Text before value * @param {string} value Horizontal value * @return {string} Inverted property */ function calculateNewBackgroundPosition( match, pre, value ) { var idx, len; if ( value.slice( -1 ) === '%' ) { idx = value.indexOf( '.' ); if ( idx !== -1 ) { // Two off, one for the "%" at the end, one for the dot itself len = value.length - idx - 2; value = 100 - parseFloat( value ); value = value.toFixed( len ) + '%'; } else { value = 100 - parseFloat( value ) + '%'; } } return pre + value; } /** * Invert a set of border radius values. * * @private * @param {Array} values Matched values * @return {string} Inverted values */ function flipBorderRadiusValues( values ) { switch ( values.length ) { case 4: values = [ values[ 1 ], values[ 0 ], values[ 3 ], values[ 2 ] ]; break; case 3: values = [ values[ 1 ], values[ 0 ], values[ 1 ], values[ 2 ] ]; break; case 2: values = [ values[ 1 ], values[ 0 ] ]; break; case 1: values = [ values[ 0 ] ]; break; } return values.join( ' ' ); } /** * Invert a set of border radius values. * * @private * @param {string} match Matched property * @param {string} pre Text before value * @param {string} [firstGroup1] * @param {string} [firstGroup2] * @param {string} [firstGroup3] * @param {string} [firstGroup4] * @param {string} [secondGroup1] * @param {string} [secondGroup2] * @param {string} [secondGroup3] * @param {string} [secondGroup4] * @param {string} [post] Text after value * @return {string} Inverted property */ function calculateNewBorderRadius( match, pre ) { var values, args = [].slice.call( arguments ), firstGroup = args.slice( 2, 6 ).filter( function ( val ) { return val; } ), secondGroup = args.slice( 6, 10 ).filter( function ( val ) { return val; } ), post = args[ 10 ] || ''; if ( secondGroup.length ) { values = flipBorderRadiusValues( firstGroup ) + ' / ' + flipBorderRadiusValues( secondGroup ); } else { values = flipBorderRadiusValues( firstGroup ); } return pre + values + post; } /** * Flip the sign of a CSS value, possibly with a unit. * * We can't just negate the value with unary minus due to the units. * * @private * @param {string} value * @return {string} */ function flipSign( value ) { if ( parseFloat( value ) === 0 ) { // Don't mangle zeroes return value; } if ( value[ 0 ] === '-' ) { return value.slice( 1 ); } return '-' + value; } /** * @private * @param {string} match * @param {string} property * @param {string} offset * @return {string} */ function calculateNewShadow( match, property, offset ) { return property + flipSign( offset ); } /** * @private * @param {string} match * @param {string} property * @param {string} prefix * @param {string} offset * @param {string} suffix * @return {string} */ function calculateNewTranslate( match, property, prefix, offset, suffix ) { return property + prefix + flipSign( offset ) + suffix; } /** * @private * @param {string} match * @param {string} property * @param {string} color * @param {string} space * @param {string} offset * @return {string} */ function calculateNewFourTextShadow( match, property, color, space, offset ) { return property + color + space + flipSign( offset ); } return { /** * Transform a left-to-right stylesheet to right-to-left. * * @param {string} css Stylesheet to transform * @param {Object} options Options * @param {boolean} [options.transformDirInUrl=false] Transform directions in URLs (e.g. 'ltr', 'rtl') * @param {boolean} [options.transformEdgeInUrl=false] Transform edges in URLs (e.g. 'left', 'right') * @return {string} Transformed stylesheet */ 'transform': function ( css, options ) { // eslint-disable-line quote-props, (for closure compiler) // Tokenizers var noFlipSingleTokenizer = new Tokenizer( noFlipSingleRegExp, noFlipSingleToken ), noFlipClassTokenizer = new Tokenizer( noFlipClassRegExp, noFlipClassToken ), commentTokenizer = new Tokenizer( commentRegExp, commentToken ); // Tokenize css = commentTokenizer.tokenize( noFlipClassTokenizer.tokenize( noFlipSingleTokenizer.tokenize( // We wrap tokens in ` , not ~ like the original implementation does. // This was done because ` is not a legal character in CSS and can only // occur in URLs, where we escape it to %60 before inserting our tokens. css.replace( '`', '%60' ) ) ) ); // Transform URLs if ( options.transformDirInUrl ) { // Replace 'ltr' with 'rtl' and vice versa in background URLs css = css .replace( ltrInUrlRegExp, '$1' + temporaryToken ) .replace( rtlInUrlRegExp, '$1ltr' ) .replace( temporaryTokenRegExp, 'rtl' ); } if ( options.transformEdgeInUrl ) { // Replace 'left' with 'right' and vice versa in background URLs css = css .replace( leftInUrlRegExp, '$1' + temporaryToken ) .replace( rightInUrlRegExp, '$1left' ) .replace( temporaryTokenRegExp, 'right' ); } // Transform rules css = css // Replace direction: ltr; with direction: rtl; and vice versa. .replace( directionLtrRegExp, '$1' + temporaryToken ) .replace( directionRtlRegExp, '$1ltr' ) .replace( temporaryTokenRegExp, 'rtl' ) // Flip rules like left: , padding-right: , etc. .replace( leftRegExp, '$1' + temporaryToken ) .replace( rightRegExp, '$1left' ) .replace( temporaryTokenRegExp, 'right' ) // Flip East and West in rules like cursor: nw-resize; .replace( cursorEastRegExp, '$1$2' + temporaryToken ) .replace( cursorWestRegExp, '$1$2e-resize' ) .replace( temporaryTokenRegExp, 'w-resize' ) // Border radius .replace( borderRadiusRegExp, calculateNewBorderRadius ) // Shadows .replace( boxShadowRegExp, calculateNewShadow ) .replace( textShadow1RegExp, calculateNewFourTextShadow ) .replace( textShadow2RegExp, calculateNewFourTextShadow ) .replace( textShadow3RegExp, calculateNewShadow ) // Translate .replace( translateXRegExp, calculateNewTranslate ) .replace( translateRegExp, calculateNewTranslate ) // Swap the second and fourth parts in four-part notation rules // like padding: 1px 2px 3px 4px; .replace( fourNotationQuantRegExp, '$1$2$3$8$5$6$7$4$9' ) .replace( fourNotationColorRegExp, '$1$2$3$8$5$6$7$4$9' ) // Flip horizontal background percentages .replace( bgHorizontalPercentageRegExp, calculateNewBackgroundPosition ) .replace( bgHorizontalPercentageXRegExp, calculateNewBackgroundPosition ); // Detokenize css = noFlipSingleTokenizer.detokenize( noFlipClassTokenizer.detokenize( commentTokenizer.detokenize( css ) ) ); return css; } }; }
[ "function", "CSSJanus", "(", ")", "{", "var", "// Tokens", "temporaryToken", "=", "'`TMP`'", ",", "noFlipSingleToken", "=", "'`NOFLIP_SINGLE`'", ",", "noFlipClassToken", "=", "'`NOFLIP_CLASS`'", ",", "commentToken", "=", "'`COMMENT`'", ",", "// Patterns", "nonAsciiPattern", "=", "'[^\\\\u0020-\\\\u007e]'", ",", "unicodePattern", "=", "'(?:(?:\\\\\\\\[0-9a-f]{1,6})(?:\\\\r\\\\n|\\\\s)?)'", ",", "numPattern", "=", "'(?:[0-9]*\\\\.[0-9]+|[0-9]+)'", ",", "unitPattern", "=", "'(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)'", ",", "directionPattern", "=", "'direction\\\\s*:\\\\s*'", ",", "urlSpecialCharsPattern", "=", "'[!#$%&*-~]'", ",", "validAfterUriCharsPattern", "=", "'[\\'\"]?\\\\s*'", ",", "nonLetterPattern", "=", "'(^|[^a-zA-Z])'", ",", "charsWithinSelectorPattern", "=", "'[^\\\\}]*?'", ",", "noFlipPattern", "=", "'\\\\/\\\\*\\\\!?\\\\s*@noflip\\\\s*\\\\*\\\\/'", ",", "commentPattern", "=", "'\\\\/\\\\*[^*]*\\\\*+([^\\\\/*][^*]*\\\\*+)*\\\\/'", ",", "escapePattern", "=", "'(?:'", "+", "unicodePattern", "+", "'|\\\\\\\\[^\\\\r\\\\n\\\\f0-9a-f])'", ",", "nmstartPattern", "=", "'(?:[_a-z]|'", "+", "nonAsciiPattern", "+", "'|'", "+", "escapePattern", "+", "')'", ",", "nmcharPattern", "=", "'(?:[_a-z0-9-]|'", "+", "nonAsciiPattern", "+", "'|'", "+", "escapePattern", "+", "')'", ",", "identPattern", "=", "'-?'", "+", "nmstartPattern", "+", "nmcharPattern", "+", "'*'", ",", "quantPattern", "=", "numPattern", "+", "'(?:\\\\s*'", "+", "unitPattern", "+", "'|'", "+", "identPattern", "+", "')?'", ",", "signedQuantPattern", "=", "'((?:-?'", "+", "quantPattern", "+", "')|(?:inherit|auto))'", ",", "fourNotationQuantPropsPattern", "=", "'((?:margin|padding|border-width)\\\\s*:\\\\s*)'", ",", "fourNotationColorPropsPattern", "=", "'((?:-color|border-style)\\\\s*:\\\\s*)'", ",", "colorPattern", "=", "'(#?'", "+", "nmcharPattern", "+", "'+|(?:rgba?|hsla?)\\\\([ \\\\d.,%-]+\\\\))'", ",", "urlCharsPattern", "=", "'(?:'", "+", "urlSpecialCharsPattern", "+", "'|'", "+", "nonAsciiPattern", "+", "'|'", "+", "escapePattern", "+", "')*'", ",", "lookAheadNotLetterPattern", "=", "'(?![a-zA-Z])'", ",", "lookAheadNotOpenBracePattern", "=", "'(?!('", "+", "nmcharPattern", "+", "'|\\\\r?\\\\n|\\\\s|#|\\\\:|\\\\.|\\\\,|\\\\+|>|\\\\(|\\\\)|\\\\[|\\\\]|=|\\\\*=|~=|\\\\^=|\\'[^\\']*\\'])*?{)'", ",", "lookAheadNotClosingParenPattern", "=", "'(?!'", "+", "urlCharsPattern", "+", "'?'", "+", "validAfterUriCharsPattern", "+", "'\\\\))'", ",", "lookAheadForClosingParenPattern", "=", "'(?='", "+", "urlCharsPattern", "+", "'?'", "+", "validAfterUriCharsPattern", "+", "'\\\\))'", ",", "suffixPattern", "=", "'(\\\\s*(?:!important\\\\s*)?[;}])'", ",", "// Regular expressions", "temporaryTokenRegExp", "=", "new", "RegExp", "(", "'`TMP`'", ",", "'g'", ")", ",", "commentRegExp", "=", "new", "RegExp", "(", "commentPattern", ",", "'gi'", ")", ",", "noFlipSingleRegExp", "=", "new", "RegExp", "(", "'('", "+", "noFlipPattern", "+", "lookAheadNotOpenBracePattern", "+", "'[^;}]+;?)'", ",", "'gi'", ")", ",", "noFlipClassRegExp", "=", "new", "RegExp", "(", "'('", "+", "noFlipPattern", "+", "charsWithinSelectorPattern", "+", "'})'", ",", "'gi'", ")", ",", "directionLtrRegExp", "=", "new", "RegExp", "(", "'('", "+", "directionPattern", "+", "')ltr'", ",", "'gi'", ")", ",", "directionRtlRegExp", "=", "new", "RegExp", "(", "'('", "+", "directionPattern", "+", "')rtl'", ",", "'gi'", ")", ",", "leftRegExp", "=", "new", "RegExp", "(", "nonLetterPattern", "+", "'(left)'", "+", "lookAheadNotLetterPattern", "+", "lookAheadNotClosingParenPattern", "+", "lookAheadNotOpenBracePattern", ",", "'gi'", ")", ",", "rightRegExp", "=", "new", "RegExp", "(", "nonLetterPattern", "+", "'(right)'", "+", "lookAheadNotLetterPattern", "+", "lookAheadNotClosingParenPattern", "+", "lookAheadNotOpenBracePattern", ",", "'gi'", ")", ",", "leftInUrlRegExp", "=", "new", "RegExp", "(", "nonLetterPattern", "+", "'(left)'", "+", "lookAheadForClosingParenPattern", ",", "'gi'", ")", ",", "rightInUrlRegExp", "=", "new", "RegExp", "(", "nonLetterPattern", "+", "'(right)'", "+", "lookAheadForClosingParenPattern", ",", "'gi'", ")", ",", "ltrInUrlRegExp", "=", "new", "RegExp", "(", "nonLetterPattern", "+", "'(ltr)'", "+", "lookAheadForClosingParenPattern", ",", "'gi'", ")", ",", "rtlInUrlRegExp", "=", "new", "RegExp", "(", "nonLetterPattern", "+", "'(rtl)'", "+", "lookAheadForClosingParenPattern", ",", "'gi'", ")", ",", "cursorEastRegExp", "=", "new", "RegExp", "(", "nonLetterPattern", "+", "'([ns]?)e-resize'", ",", "'gi'", ")", ",", "cursorWestRegExp", "=", "new", "RegExp", "(", "nonLetterPattern", "+", "'([ns]?)w-resize'", ",", "'gi'", ")", ",", "fourNotationQuantRegExp", "=", "new", "RegExp", "(", "fourNotationQuantPropsPattern", "+", "signedQuantPattern", "+", "'(\\\\s+)'", "+", "signedQuantPattern", "+", "'(\\\\s+)'", "+", "signedQuantPattern", "+", "'(\\\\s+)'", "+", "signedQuantPattern", "+", "suffixPattern", ",", "'gi'", ")", ",", "fourNotationColorRegExp", "=", "new", "RegExp", "(", "fourNotationColorPropsPattern", "+", "colorPattern", "+", "'(\\\\s+)'", "+", "colorPattern", "+", "'(\\\\s+)'", "+", "colorPattern", "+", "'(\\\\s+)'", "+", "colorPattern", "+", "suffixPattern", ",", "'gi'", ")", ",", "bgHorizontalPercentageRegExp", "=", "new", "RegExp", "(", "'(background(?:-position)?\\\\s*:\\\\s*(?:[^:;}\\\\s]+\\\\s+)*?)('", "+", "quantPattern", "+", "')'", ",", "'gi'", ")", ",", "bgHorizontalPercentageXRegExp", "=", "new", "RegExp", "(", "'(background-position-x\\\\s*:\\\\s*)(-?'", "+", "numPattern", "+", "'%)'", ",", "'gi'", ")", ",", "// border-radius: <length or percentage>{1,4} [optional: / <length or percentage>{1,4} ]", "borderRadiusRegExp", "=", "new", "RegExp", "(", "'(border-radius\\\\s*:\\\\s*)'", "+", "signedQuantPattern", "+", "'(?:(?:\\\\s+'", "+", "signedQuantPattern", "+", "')(?:\\\\s+'", "+", "signedQuantPattern", "+", "')?(?:\\\\s+'", "+", "signedQuantPattern", "+", "')?)?'", "+", "'(?:(?:(?:\\\\s*\\\\/\\\\s*)'", "+", "signedQuantPattern", "+", "')(?:\\\\s+'", "+", "signedQuantPattern", "+", "')?(?:\\\\s+'", "+", "signedQuantPattern", "+", "')?(?:\\\\s+'", "+", "signedQuantPattern", "+", "')?)?'", "+", "suffixPattern", ",", "'gi'", ")", ",", "boxShadowRegExp", "=", "new", "RegExp", "(", "'(box-shadow\\\\s*:\\\\s*(?:inset\\\\s*)?)'", "+", "signedQuantPattern", ",", "'gi'", ")", ",", "textShadow1RegExp", "=", "new", "RegExp", "(", "'(text-shadow\\\\s*:\\\\s*)'", "+", "signedQuantPattern", "+", "'(\\\\s*)'", "+", "colorPattern", ",", "'gi'", ")", ",", "textShadow2RegExp", "=", "new", "RegExp", "(", "'(text-shadow\\\\s*:\\\\s*)'", "+", "colorPattern", "+", "'(\\\\s*)'", "+", "signedQuantPattern", ",", "'gi'", ")", ",", "textShadow3RegExp", "=", "new", "RegExp", "(", "'(text-shadow\\\\s*:\\\\s*)'", "+", "signedQuantPattern", ",", "'gi'", ")", ",", "translateXRegExp", "=", "new", "RegExp", "(", "'(transform\\\\s*:[^;}]*)(translateX\\\\s*\\\\(\\\\s*)'", "+", "signedQuantPattern", "+", "'(\\\\s*\\\\))'", ",", "'gi'", ")", ",", "translateRegExp", "=", "new", "RegExp", "(", "'(transform\\\\s*:[^;}]*)(translate\\\\s*\\\\(\\\\s*)'", "+", "signedQuantPattern", "+", "'((?:\\\\s*,\\\\s*'", "+", "signedQuantPattern", "+", "'){0,2}\\\\s*\\\\))'", ",", "'gi'", ")", ";", "/**\n\t * Invert the horizontal value of a background position property.\n\t *\n\t * @private\n\t * @param {string} match Matched property\n\t * @param {string} pre Text before value\n\t * @param {string} value Horizontal value\n\t * @return {string} Inverted property\n\t */", "function", "calculateNewBackgroundPosition", "(", "match", ",", "pre", ",", "value", ")", "{", "var", "idx", ",", "len", ";", "if", "(", "value", ".", "slice", "(", "-", "1", ")", "===", "'%'", ")", "{", "idx", "=", "value", ".", "indexOf", "(", "'.'", ")", ";", "if", "(", "idx", "!==", "-", "1", ")", "{", "// Two off, one for the \"%\" at the end, one for the dot itself", "len", "=", "value", ".", "length", "-", "idx", "-", "2", ";", "value", "=", "100", "-", "parseFloat", "(", "value", ")", ";", "value", "=", "value", ".", "toFixed", "(", "len", ")", "+", "'%'", ";", "}", "else", "{", "value", "=", "100", "-", "parseFloat", "(", "value", ")", "+", "'%'", ";", "}", "}", "return", "pre", "+", "value", ";", "}", "/**\n\t * Invert a set of border radius values.\n\t *\n\t * @private\n\t * @param {Array} values Matched values\n\t * @return {string} Inverted values\n\t */", "function", "flipBorderRadiusValues", "(", "values", ")", "{", "switch", "(", "values", ".", "length", ")", "{", "case", "4", ":", "values", "=", "[", "values", "[", "1", "]", ",", "values", "[", "0", "]", ",", "values", "[", "3", "]", ",", "values", "[", "2", "]", "]", ";", "break", ";", "case", "3", ":", "values", "=", "[", "values", "[", "1", "]", ",", "values", "[", "0", "]", ",", "values", "[", "1", "]", ",", "values", "[", "2", "]", "]", ";", "break", ";", "case", "2", ":", "values", "=", "[", "values", "[", "1", "]", ",", "values", "[", "0", "]", "]", ";", "break", ";", "case", "1", ":", "values", "=", "[", "values", "[", "0", "]", "]", ";", "break", ";", "}", "return", "values", ".", "join", "(", "' '", ")", ";", "}", "/**\n\t * Invert a set of border radius values.\n\t *\n\t * @private\n\t * @param {string} match Matched property\n\t * @param {string} pre Text before value\n\t * @param {string} [firstGroup1]\n\t * @param {string} [firstGroup2]\n\t * @param {string} [firstGroup3]\n\t * @param {string} [firstGroup4]\n\t * @param {string} [secondGroup1]\n\t * @param {string} [secondGroup2]\n\t * @param {string} [secondGroup3]\n\t * @param {string} [secondGroup4]\n\t * @param {string} [post] Text after value\n\t * @return {string} Inverted property\n\t */", "function", "calculateNewBorderRadius", "(", "match", ",", "pre", ")", "{", "var", "values", ",", "args", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", ",", "firstGroup", "=", "args", ".", "slice", "(", "2", ",", "6", ")", ".", "filter", "(", "function", "(", "val", ")", "{", "return", "val", ";", "}", ")", ",", "secondGroup", "=", "args", ".", "slice", "(", "6", ",", "10", ")", ".", "filter", "(", "function", "(", "val", ")", "{", "return", "val", ";", "}", ")", ",", "post", "=", "args", "[", "10", "]", "||", "''", ";", "if", "(", "secondGroup", ".", "length", ")", "{", "values", "=", "flipBorderRadiusValues", "(", "firstGroup", ")", "+", "' / '", "+", "flipBorderRadiusValues", "(", "secondGroup", ")", ";", "}", "else", "{", "values", "=", "flipBorderRadiusValues", "(", "firstGroup", ")", ";", "}", "return", "pre", "+", "values", "+", "post", ";", "}", "/**\n\t * Flip the sign of a CSS value, possibly with a unit.\n\t *\n\t * We can't just negate the value with unary minus due to the units.\n\t *\n\t * @private\n\t * @param {string} value\n\t * @return {string}\n\t */", "function", "flipSign", "(", "value", ")", "{", "if", "(", "parseFloat", "(", "value", ")", "===", "0", ")", "{", "// Don't mangle zeroes", "return", "value", ";", "}", "if", "(", "value", "[", "0", "]", "===", "'-'", ")", "{", "return", "value", ".", "slice", "(", "1", ")", ";", "}", "return", "'-'", "+", "value", ";", "}", "/**\n\t * @private\n\t * @param {string} match\n\t * @param {string} property\n\t * @param {string} offset\n\t * @return {string}\n\t */", "function", "calculateNewShadow", "(", "match", ",", "property", ",", "offset", ")", "{", "return", "property", "+", "flipSign", "(", "offset", ")", ";", "}", "/**\n\t * @private\n\t * @param {string} match\n\t * @param {string} property\n\t * @param {string} prefix\n\t * @param {string} offset\n\t * @param {string} suffix\n\t * @return {string}\n\t */", "function", "calculateNewTranslate", "(", "match", ",", "property", ",", "prefix", ",", "offset", ",", "suffix", ")", "{", "return", "property", "+", "prefix", "+", "flipSign", "(", "offset", ")", "+", "suffix", ";", "}", "/**\n\t * @private\n\t * @param {string} match\n\t * @param {string} property\n\t * @param {string} color\n\t * @param {string} space\n\t * @param {string} offset\n\t * @return {string}\n\t */", "function", "calculateNewFourTextShadow", "(", "match", ",", "property", ",", "color", ",", "space", ",", "offset", ")", "{", "return", "property", "+", "color", "+", "space", "+", "flipSign", "(", "offset", ")", ";", "}", "return", "{", "/**\n\t\t * Transform a left-to-right stylesheet to right-to-left.\n\t\t *\n\t\t * @param {string} css Stylesheet to transform\n\t\t * @param {Object} options Options\n\t\t * @param {boolean} [options.transformDirInUrl=false] Transform directions in URLs (e.g. 'ltr', 'rtl')\n\t\t * @param {boolean} [options.transformEdgeInUrl=false] Transform edges in URLs (e.g. 'left', 'right')\n\t\t * @return {string} Transformed stylesheet\n\t\t */", "'transform'", ":", "function", "(", "css", ",", "options", ")", "{", "// eslint-disable-line quote-props, (for closure compiler)", "// Tokenizers", "var", "noFlipSingleTokenizer", "=", "new", "Tokenizer", "(", "noFlipSingleRegExp", ",", "noFlipSingleToken", ")", ",", "noFlipClassTokenizer", "=", "new", "Tokenizer", "(", "noFlipClassRegExp", ",", "noFlipClassToken", ")", ",", "commentTokenizer", "=", "new", "Tokenizer", "(", "commentRegExp", ",", "commentToken", ")", ";", "// Tokenize", "css", "=", "commentTokenizer", ".", "tokenize", "(", "noFlipClassTokenizer", ".", "tokenize", "(", "noFlipSingleTokenizer", ".", "tokenize", "(", "// We wrap tokens in ` , not ~ like the original implementation does.", "// This was done because ` is not a legal character in CSS and can only", "// occur in URLs, where we escape it to %60 before inserting our tokens.", "css", ".", "replace", "(", "'`'", ",", "'%60'", ")", ")", ")", ")", ";", "// Transform URLs", "if", "(", "options", ".", "transformDirInUrl", ")", "{", "// Replace 'ltr' with 'rtl' and vice versa in background URLs", "css", "=", "css", ".", "replace", "(", "ltrInUrlRegExp", ",", "'$1'", "+", "temporaryToken", ")", ".", "replace", "(", "rtlInUrlRegExp", ",", "'$1ltr'", ")", ".", "replace", "(", "temporaryTokenRegExp", ",", "'rtl'", ")", ";", "}", "if", "(", "options", ".", "transformEdgeInUrl", ")", "{", "// Replace 'left' with 'right' and vice versa in background URLs", "css", "=", "css", ".", "replace", "(", "leftInUrlRegExp", ",", "'$1'", "+", "temporaryToken", ")", ".", "replace", "(", "rightInUrlRegExp", ",", "'$1left'", ")", ".", "replace", "(", "temporaryTokenRegExp", ",", "'right'", ")", ";", "}", "// Transform rules", "css", "=", "css", "// Replace direction: ltr; with direction: rtl; and vice versa.", ".", "replace", "(", "directionLtrRegExp", ",", "'$1'", "+", "temporaryToken", ")", ".", "replace", "(", "directionRtlRegExp", ",", "'$1ltr'", ")", ".", "replace", "(", "temporaryTokenRegExp", ",", "'rtl'", ")", "// Flip rules like left: , padding-right: , etc.", ".", "replace", "(", "leftRegExp", ",", "'$1'", "+", "temporaryToken", ")", ".", "replace", "(", "rightRegExp", ",", "'$1left'", ")", ".", "replace", "(", "temporaryTokenRegExp", ",", "'right'", ")", "// Flip East and West in rules like cursor: nw-resize;", ".", "replace", "(", "cursorEastRegExp", ",", "'$1$2'", "+", "temporaryToken", ")", ".", "replace", "(", "cursorWestRegExp", ",", "'$1$2e-resize'", ")", ".", "replace", "(", "temporaryTokenRegExp", ",", "'w-resize'", ")", "// Border radius", ".", "replace", "(", "borderRadiusRegExp", ",", "calculateNewBorderRadius", ")", "// Shadows", ".", "replace", "(", "boxShadowRegExp", ",", "calculateNewShadow", ")", ".", "replace", "(", "textShadow1RegExp", ",", "calculateNewFourTextShadow", ")", ".", "replace", "(", "textShadow2RegExp", ",", "calculateNewFourTextShadow", ")", ".", "replace", "(", "textShadow3RegExp", ",", "calculateNewShadow", ")", "// Translate", ".", "replace", "(", "translateXRegExp", ",", "calculateNewTranslate", ")", ".", "replace", "(", "translateRegExp", ",", "calculateNewTranslate", ")", "// Swap the second and fourth parts in four-part notation rules", "// like padding: 1px 2px 3px 4px;", ".", "replace", "(", "fourNotationQuantRegExp", ",", "'$1$2$3$8$5$6$7$4$9'", ")", ".", "replace", "(", "fourNotationColorRegExp", ",", "'$1$2$3$8$5$6$7$4$9'", ")", "// Flip horizontal background percentages", ".", "replace", "(", "bgHorizontalPercentageRegExp", ",", "calculateNewBackgroundPosition", ")", ".", "replace", "(", "bgHorizontalPercentageXRegExp", ",", "calculateNewBackgroundPosition", ")", ";", "// Detokenize", "css", "=", "noFlipSingleTokenizer", ".", "detokenize", "(", "noFlipClassTokenizer", ".", "detokenize", "(", "commentTokenizer", ".", "detokenize", "(", "css", ")", ")", ")", ";", "return", "css", ";", "}", "}", ";", "}" ]
Create a CSSJanus object. CSSJanus transforms CSS rules with horizontal relevance so that a left-to-right stylesheet can become a right-to-left stylesheet automatically. Processing can be bypassed for an entire rule or a single property by adding a / * @noflip * / comment above the rule or property. @author Trevor Parscal <trevorparscal@gmail.com> @author Roan Kattouw <roankattouw@gmail.com> @author Lindsey Simon <elsigh@google.com> @author Roozbeh Pournader <roozbeh@gmail.com> @author Bryon Engelhardt <ebryon77@gmail.com> @class @constructor
[ "Create", "a", "CSSJanus", "object", "." ]
9ffc4051601bafdd410f65448ec445f21148581c
https://github.com/cssjanus/cssjanus/blob/9ffc4051601bafdd410f65448ec445f21148581c/src/cssjanus.js#L91-L384
20,362
cssjanus/cssjanus
src/cssjanus.js
calculateNewBackgroundPosition
function calculateNewBackgroundPosition( match, pre, value ) { var idx, len; if ( value.slice( -1 ) === '%' ) { idx = value.indexOf( '.' ); if ( idx !== -1 ) { // Two off, one for the "%" at the end, one for the dot itself len = value.length - idx - 2; value = 100 - parseFloat( value ); value = value.toFixed( len ) + '%'; } else { value = 100 - parseFloat( value ) + '%'; } } return pre + value; }
javascript
function calculateNewBackgroundPosition( match, pre, value ) { var idx, len; if ( value.slice( -1 ) === '%' ) { idx = value.indexOf( '.' ); if ( idx !== -1 ) { // Two off, one for the "%" at the end, one for the dot itself len = value.length - idx - 2; value = 100 - parseFloat( value ); value = value.toFixed( len ) + '%'; } else { value = 100 - parseFloat( value ) + '%'; } } return pre + value; }
[ "function", "calculateNewBackgroundPosition", "(", "match", ",", "pre", ",", "value", ")", "{", "var", "idx", ",", "len", ";", "if", "(", "value", ".", "slice", "(", "-", "1", ")", "===", "'%'", ")", "{", "idx", "=", "value", ".", "indexOf", "(", "'.'", ")", ";", "if", "(", "idx", "!==", "-", "1", ")", "{", "// Two off, one for the \"%\" at the end, one for the dot itself", "len", "=", "value", ".", "length", "-", "idx", "-", "2", ";", "value", "=", "100", "-", "parseFloat", "(", "value", ")", ";", "value", "=", "value", ".", "toFixed", "(", "len", ")", "+", "'%'", ";", "}", "else", "{", "value", "=", "100", "-", "parseFloat", "(", "value", ")", "+", "'%'", ";", "}", "}", "return", "pre", "+", "value", ";", "}" ]
Invert the horizontal value of a background position property. @private @param {string} match Matched property @param {string} pre Text before value @param {string} value Horizontal value @return {string} Inverted property
[ "Invert", "the", "horizontal", "value", "of", "a", "background", "position", "property", "." ]
9ffc4051601bafdd410f65448ec445f21148581c
https://github.com/cssjanus/cssjanus/blob/9ffc4051601bafdd410f65448ec445f21148581c/src/cssjanus.js#L164-L178
20,363
cssjanus/cssjanus
src/cssjanus.js
function ( css, options ) { // eslint-disable-line quote-props, (for closure compiler) // Tokenizers var noFlipSingleTokenizer = new Tokenizer( noFlipSingleRegExp, noFlipSingleToken ), noFlipClassTokenizer = new Tokenizer( noFlipClassRegExp, noFlipClassToken ), commentTokenizer = new Tokenizer( commentRegExp, commentToken ); // Tokenize css = commentTokenizer.tokenize( noFlipClassTokenizer.tokenize( noFlipSingleTokenizer.tokenize( // We wrap tokens in ` , not ~ like the original implementation does. // This was done because ` is not a legal character in CSS and can only // occur in URLs, where we escape it to %60 before inserting our tokens. css.replace( '`', '%60' ) ) ) ); // Transform URLs if ( options.transformDirInUrl ) { // Replace 'ltr' with 'rtl' and vice versa in background URLs css = css .replace( ltrInUrlRegExp, '$1' + temporaryToken ) .replace( rtlInUrlRegExp, '$1ltr' ) .replace( temporaryTokenRegExp, 'rtl' ); } if ( options.transformEdgeInUrl ) { // Replace 'left' with 'right' and vice versa in background URLs css = css .replace( leftInUrlRegExp, '$1' + temporaryToken ) .replace( rightInUrlRegExp, '$1left' ) .replace( temporaryTokenRegExp, 'right' ); } // Transform rules css = css // Replace direction: ltr; with direction: rtl; and vice versa. .replace( directionLtrRegExp, '$1' + temporaryToken ) .replace( directionRtlRegExp, '$1ltr' ) .replace( temporaryTokenRegExp, 'rtl' ) // Flip rules like left: , padding-right: , etc. .replace( leftRegExp, '$1' + temporaryToken ) .replace( rightRegExp, '$1left' ) .replace( temporaryTokenRegExp, 'right' ) // Flip East and West in rules like cursor: nw-resize; .replace( cursorEastRegExp, '$1$2' + temporaryToken ) .replace( cursorWestRegExp, '$1$2e-resize' ) .replace( temporaryTokenRegExp, 'w-resize' ) // Border radius .replace( borderRadiusRegExp, calculateNewBorderRadius ) // Shadows .replace( boxShadowRegExp, calculateNewShadow ) .replace( textShadow1RegExp, calculateNewFourTextShadow ) .replace( textShadow2RegExp, calculateNewFourTextShadow ) .replace( textShadow3RegExp, calculateNewShadow ) // Translate .replace( translateXRegExp, calculateNewTranslate ) .replace( translateRegExp, calculateNewTranslate ) // Swap the second and fourth parts in four-part notation rules // like padding: 1px 2px 3px 4px; .replace( fourNotationQuantRegExp, '$1$2$3$8$5$6$7$4$9' ) .replace( fourNotationColorRegExp, '$1$2$3$8$5$6$7$4$9' ) // Flip horizontal background percentages .replace( bgHorizontalPercentageRegExp, calculateNewBackgroundPosition ) .replace( bgHorizontalPercentageXRegExp, calculateNewBackgroundPosition ); // Detokenize css = noFlipSingleTokenizer.detokenize( noFlipClassTokenizer.detokenize( commentTokenizer.detokenize( css ) ) ); return css; }
javascript
function ( css, options ) { // eslint-disable-line quote-props, (for closure compiler) // Tokenizers var noFlipSingleTokenizer = new Tokenizer( noFlipSingleRegExp, noFlipSingleToken ), noFlipClassTokenizer = new Tokenizer( noFlipClassRegExp, noFlipClassToken ), commentTokenizer = new Tokenizer( commentRegExp, commentToken ); // Tokenize css = commentTokenizer.tokenize( noFlipClassTokenizer.tokenize( noFlipSingleTokenizer.tokenize( // We wrap tokens in ` , not ~ like the original implementation does. // This was done because ` is not a legal character in CSS and can only // occur in URLs, where we escape it to %60 before inserting our tokens. css.replace( '`', '%60' ) ) ) ); // Transform URLs if ( options.transformDirInUrl ) { // Replace 'ltr' with 'rtl' and vice versa in background URLs css = css .replace( ltrInUrlRegExp, '$1' + temporaryToken ) .replace( rtlInUrlRegExp, '$1ltr' ) .replace( temporaryTokenRegExp, 'rtl' ); } if ( options.transformEdgeInUrl ) { // Replace 'left' with 'right' and vice versa in background URLs css = css .replace( leftInUrlRegExp, '$1' + temporaryToken ) .replace( rightInUrlRegExp, '$1left' ) .replace( temporaryTokenRegExp, 'right' ); } // Transform rules css = css // Replace direction: ltr; with direction: rtl; and vice versa. .replace( directionLtrRegExp, '$1' + temporaryToken ) .replace( directionRtlRegExp, '$1ltr' ) .replace( temporaryTokenRegExp, 'rtl' ) // Flip rules like left: , padding-right: , etc. .replace( leftRegExp, '$1' + temporaryToken ) .replace( rightRegExp, '$1left' ) .replace( temporaryTokenRegExp, 'right' ) // Flip East and West in rules like cursor: nw-resize; .replace( cursorEastRegExp, '$1$2' + temporaryToken ) .replace( cursorWestRegExp, '$1$2e-resize' ) .replace( temporaryTokenRegExp, 'w-resize' ) // Border radius .replace( borderRadiusRegExp, calculateNewBorderRadius ) // Shadows .replace( boxShadowRegExp, calculateNewShadow ) .replace( textShadow1RegExp, calculateNewFourTextShadow ) .replace( textShadow2RegExp, calculateNewFourTextShadow ) .replace( textShadow3RegExp, calculateNewShadow ) // Translate .replace( translateXRegExp, calculateNewTranslate ) .replace( translateRegExp, calculateNewTranslate ) // Swap the second and fourth parts in four-part notation rules // like padding: 1px 2px 3px 4px; .replace( fourNotationQuantRegExp, '$1$2$3$8$5$6$7$4$9' ) .replace( fourNotationColorRegExp, '$1$2$3$8$5$6$7$4$9' ) // Flip horizontal background percentages .replace( bgHorizontalPercentageRegExp, calculateNewBackgroundPosition ) .replace( bgHorizontalPercentageXRegExp, calculateNewBackgroundPosition ); // Detokenize css = noFlipSingleTokenizer.detokenize( noFlipClassTokenizer.detokenize( commentTokenizer.detokenize( css ) ) ); return css; }
[ "function", "(", "css", ",", "options", ")", "{", "// eslint-disable-line quote-props, (for closure compiler)", "// Tokenizers", "var", "noFlipSingleTokenizer", "=", "new", "Tokenizer", "(", "noFlipSingleRegExp", ",", "noFlipSingleToken", ")", ",", "noFlipClassTokenizer", "=", "new", "Tokenizer", "(", "noFlipClassRegExp", ",", "noFlipClassToken", ")", ",", "commentTokenizer", "=", "new", "Tokenizer", "(", "commentRegExp", ",", "commentToken", ")", ";", "// Tokenize", "css", "=", "commentTokenizer", ".", "tokenize", "(", "noFlipClassTokenizer", ".", "tokenize", "(", "noFlipSingleTokenizer", ".", "tokenize", "(", "// We wrap tokens in ` , not ~ like the original implementation does.", "// This was done because ` is not a legal character in CSS and can only", "// occur in URLs, where we escape it to %60 before inserting our tokens.", "css", ".", "replace", "(", "'`'", ",", "'%60'", ")", ")", ")", ")", ";", "// Transform URLs", "if", "(", "options", ".", "transformDirInUrl", ")", "{", "// Replace 'ltr' with 'rtl' and vice versa in background URLs", "css", "=", "css", ".", "replace", "(", "ltrInUrlRegExp", ",", "'$1'", "+", "temporaryToken", ")", ".", "replace", "(", "rtlInUrlRegExp", ",", "'$1ltr'", ")", ".", "replace", "(", "temporaryTokenRegExp", ",", "'rtl'", ")", ";", "}", "if", "(", "options", ".", "transformEdgeInUrl", ")", "{", "// Replace 'left' with 'right' and vice versa in background URLs", "css", "=", "css", ".", "replace", "(", "leftInUrlRegExp", ",", "'$1'", "+", "temporaryToken", ")", ".", "replace", "(", "rightInUrlRegExp", ",", "'$1left'", ")", ".", "replace", "(", "temporaryTokenRegExp", ",", "'right'", ")", ";", "}", "// Transform rules", "css", "=", "css", "// Replace direction: ltr; with direction: rtl; and vice versa.", ".", "replace", "(", "directionLtrRegExp", ",", "'$1'", "+", "temporaryToken", ")", ".", "replace", "(", "directionRtlRegExp", ",", "'$1ltr'", ")", ".", "replace", "(", "temporaryTokenRegExp", ",", "'rtl'", ")", "// Flip rules like left: , padding-right: , etc.", ".", "replace", "(", "leftRegExp", ",", "'$1'", "+", "temporaryToken", ")", ".", "replace", "(", "rightRegExp", ",", "'$1left'", ")", ".", "replace", "(", "temporaryTokenRegExp", ",", "'right'", ")", "// Flip East and West in rules like cursor: nw-resize;", ".", "replace", "(", "cursorEastRegExp", ",", "'$1$2'", "+", "temporaryToken", ")", ".", "replace", "(", "cursorWestRegExp", ",", "'$1$2e-resize'", ")", ".", "replace", "(", "temporaryTokenRegExp", ",", "'w-resize'", ")", "// Border radius", ".", "replace", "(", "borderRadiusRegExp", ",", "calculateNewBorderRadius", ")", "// Shadows", ".", "replace", "(", "boxShadowRegExp", ",", "calculateNewShadow", ")", ".", "replace", "(", "textShadow1RegExp", ",", "calculateNewFourTextShadow", ")", ".", "replace", "(", "textShadow2RegExp", ",", "calculateNewFourTextShadow", ")", ".", "replace", "(", "textShadow3RegExp", ",", "calculateNewShadow", ")", "// Translate", ".", "replace", "(", "translateXRegExp", ",", "calculateNewTranslate", ")", ".", "replace", "(", "translateRegExp", ",", "calculateNewTranslate", ")", "// Swap the second and fourth parts in four-part notation rules", "// like padding: 1px 2px 3px 4px;", ".", "replace", "(", "fourNotationQuantRegExp", ",", "'$1$2$3$8$5$6$7$4$9'", ")", ".", "replace", "(", "fourNotationColorRegExp", ",", "'$1$2$3$8$5$6$7$4$9'", ")", "// Flip horizontal background percentages", ".", "replace", "(", "bgHorizontalPercentageRegExp", ",", "calculateNewBackgroundPosition", ")", ".", "replace", "(", "bgHorizontalPercentageXRegExp", ",", "calculateNewBackgroundPosition", ")", ";", "// Detokenize", "css", "=", "noFlipSingleTokenizer", ".", "detokenize", "(", "noFlipClassTokenizer", ".", "detokenize", "(", "commentTokenizer", ".", "detokenize", "(", "css", ")", ")", ")", ";", "return", "css", ";", "}" ]
Transform a left-to-right stylesheet to right-to-left. @param {string} css Stylesheet to transform @param {Object} options Options @param {boolean} [options.transformDirInUrl=false] Transform directions in URLs (e.g. 'ltr', 'rtl') @param {boolean} [options.transformEdgeInUrl=false] Transform edges in URLs (e.g. 'left', 'right') @return {string} Transformed stylesheet
[ "Transform", "a", "left", "-", "to", "-", "right", "stylesheet", "to", "right", "-", "to", "-", "left", "." ]
9ffc4051601bafdd410f65448ec445f21148581c
https://github.com/cssjanus/cssjanus/blob/9ffc4051601bafdd410f65448ec445f21148581c/src/cssjanus.js#L308-L382
20,364
Heymdall/vcard
lib/vcard.js
tryToSplit
function tryToSplit(value) { if (value.match(HAS_SEMICOLON_SEPARATOR)) { value = value.replace(/\\,/g, ','); return splitValue(value, ';'); } else if (value.match(HAS_COMMA_SEPARATOR)) { value = value.replace(/\\;/g, ';'); return splitValue(value, ','); } else { return value .replace(/\\,/g, ',') .replace(/\\;/g, ';'); } }
javascript
function tryToSplit(value) { if (value.match(HAS_SEMICOLON_SEPARATOR)) { value = value.replace(/\\,/g, ','); return splitValue(value, ';'); } else if (value.match(HAS_COMMA_SEPARATOR)) { value = value.replace(/\\;/g, ';'); return splitValue(value, ','); } else { return value .replace(/\\,/g, ',') .replace(/\\;/g, ';'); } }
[ "function", "tryToSplit", "(", "value", ")", "{", "if", "(", "value", ".", "match", "(", "HAS_SEMICOLON_SEPARATOR", ")", ")", "{", "value", "=", "value", ".", "replace", "(", "/", "\\\\,", "/", "g", ",", "','", ")", ";", "return", "splitValue", "(", "value", ",", "';'", ")", ";", "}", "else", "if", "(", "value", ".", "match", "(", "HAS_COMMA_SEPARATOR", ")", ")", "{", "value", "=", "value", ".", "replace", "(", "/", "\\\\;", "/", "g", ",", "';'", ")", ";", "return", "splitValue", "(", "value", ",", "','", ")", ";", "}", "else", "{", "return", "value", ".", "replace", "(", "/", "\\\\,", "/", "g", ",", "','", ")", ".", "replace", "(", "/", "\\\\;", "/", "g", ",", "';'", ")", ";", "}", "}" ]
Split value by "," or ";" and remove escape sequences for this separators @param {string} value @returns {string|string[]
[ "Split", "value", "by", "or", ";", "and", "remove", "escape", "sequences", "for", "this", "separators" ]
60dd362f2310cf48f2b3c1267f1123d0531fe664
https://github.com/Heymdall/vcard/blob/60dd362f2310cf48f2b3c1267f1123d0531fe664/lib/vcard.js#L119-L131
20,365
ebaauw/homebridge-lib
lib/UpnpClient.js
convert
function convert (message) { const obj = {} const lines = message.toString().trim().split('\r\n') if (lines && lines[0]) { obj.status = lines[0] for (const line of lines) { const fields = line.split(': ') if (fields.length === 2) { obj[fields[0].toLowerCase()] = fields[1] } } } return obj }
javascript
function convert (message) { const obj = {} const lines = message.toString().trim().split('\r\n') if (lines && lines[0]) { obj.status = lines[0] for (const line of lines) { const fields = line.split(': ') if (fields.length === 2) { obj[fields[0].toLowerCase()] = fields[1] } } } return obj }
[ "function", "convert", "(", "message", ")", "{", "const", "obj", "=", "{", "}", "const", "lines", "=", "message", ".", "toString", "(", ")", ".", "trim", "(", ")", ".", "split", "(", "'\\r\\n'", ")", "if", "(", "lines", "&&", "lines", "[", "0", "]", ")", "{", "obj", ".", "status", "=", "lines", "[", "0", "]", "for", "(", "const", "line", "of", "lines", ")", "{", "const", "fields", "=", "line", ".", "split", "(", "': '", ")", "if", "(", "fields", ".", "length", "===", "2", ")", "{", "obj", "[", "fields", "[", "0", "]", ".", "toLowerCase", "(", ")", "]", "=", "fields", "[", "1", "]", "}", "}", "}", "return", "obj", "}" ]
Convert UPnP message to object.
[ "Convert", "UPnP", "message", "to", "object", "." ]
08a7ed1da89d2e4fff1e2531e5a59dc218bc0633
https://github.com/ebaauw/homebridge-lib/blob/08a7ed1da89d2e4fff1e2531e5a59dc218bc0633/lib/UpnpClient.js#L19-L32
20,366
ebaauw/homebridge-lib
lib/TypeParser.js
keyOptions
function keyOptions (key, options) { const _key = options._key == null ? key : options._key + '.' + key return Object.assign({}, options, { _key: _key }) }
javascript
function keyOptions (key, options) { const _key = options._key == null ? key : options._key + '.' + key return Object.assign({}, options, { _key: _key }) }
[ "function", "keyOptions", "(", "key", ",", "options", ")", "{", "const", "_key", "=", "options", ".", "_key", "==", "null", "?", "key", ":", "options", ".", "_key", "+", "'.'", "+", "key", "return", "Object", ".", "assign", "(", "{", "}", ",", "options", ",", "{", "_key", ":", "_key", "}", ")", "}" ]
Add property key to options.
[ "Add", "property", "key", "to", "options", "." ]
08a7ed1da89d2e4fff1e2531e5a59dc218bc0633
https://github.com/ebaauw/homebridge-lib/blob/08a7ed1da89d2e4fff1e2531e5a59dc218bc0633/lib/TypeParser.js#L45-L50
20,367
ebaauw/homebridge-lib
lib/TypeParser.js
idOptions
function idOptions (id, options) { const _key = options._key == null ? '[' + id + ']' : options._key + '[' + id + ']' return Object.assign({}, options, { _key: _key }) }
javascript
function idOptions (id, options) { const _key = options._key == null ? '[' + id + ']' : options._key + '[' + id + ']' return Object.assign({}, options, { _key: _key }) }
[ "function", "idOptions", "(", "id", ",", "options", ")", "{", "const", "_key", "=", "options", ".", "_key", "==", "null", "?", "'['", "+", "id", "+", "']'", ":", "options", ".", "_key", "+", "'['", "+", "id", "+", "']'", "return", "Object", ".", "assign", "(", "{", "}", ",", "options", ",", "{", "_key", ":", "_key", "}", ")", "}" ]
Add array index to options.
[ "Add", "array", "index", "to", "options", "." ]
08a7ed1da89d2e4fff1e2531e5a59dc218bc0633
https://github.com/ebaauw/homebridge-lib/blob/08a7ed1da89d2e4fff1e2531e5a59dc218bc0633/lib/TypeParser.js#L53-L58
20,368
vlazh/node-hot-loader
src/loader.js
tweakWebpackConfig
function tweakWebpackConfig(module) { const { default: webpackConfig = module } = module; const config = handleWebpackConfig(webpackConfig); if (!config) { throw new Error( 'Not found webpack configuration. For multiple configurations in single file you must provide config with target "node".' ); } const hmrClientEntry = require.resolve('./HmrClient'); const addHmrClientEntry = (entry, entryOwner) => { const owner = entryOwner; if (Array.isArray(owner[entry])) { owner[entry].splice(-1, 0, hmrClientEntry); } else if (typeof owner[entry] === 'string') { owner[entry] = [hmrClientEntry, owner[entry]]; } else if (typeof owner[entry] === 'function') { // Call function and try again with function result. owner[entry] = owner[entry](); addHmrClientEntry(entry, owner); } else if (typeof owner[entry] === 'object') { Object.getOwnPropertyNames(owner[entry]).forEach(name => addHmrClientEntry(name, owner[entry]) ); } }; // Add HmrClient to every entries. addHmrClientEntry('entry', config); if (!config.plugins) { config.plugins = []; } // Add source-map support if configured. if (config.devtool && config.devtool.indexOf('source-map') >= 0) { config.plugins.push( new webpack.BannerPlugin({ banner: `;require('${require .resolve('source-map-support') .replace(/\\/g, '/')}').install();`, raw: true, entryOnly: false, }) ); } // Enable HMR globally if not. if (!config.plugins.find(p => p instanceof webpack.HotModuleReplacementPlugin)) { config.plugins.push(new webpack.HotModuleReplacementPlugin()); } return config; }
javascript
function tweakWebpackConfig(module) { const { default: webpackConfig = module } = module; const config = handleWebpackConfig(webpackConfig); if (!config) { throw new Error( 'Not found webpack configuration. For multiple configurations in single file you must provide config with target "node".' ); } const hmrClientEntry = require.resolve('./HmrClient'); const addHmrClientEntry = (entry, entryOwner) => { const owner = entryOwner; if (Array.isArray(owner[entry])) { owner[entry].splice(-1, 0, hmrClientEntry); } else if (typeof owner[entry] === 'string') { owner[entry] = [hmrClientEntry, owner[entry]]; } else if (typeof owner[entry] === 'function') { // Call function and try again with function result. owner[entry] = owner[entry](); addHmrClientEntry(entry, owner); } else if (typeof owner[entry] === 'object') { Object.getOwnPropertyNames(owner[entry]).forEach(name => addHmrClientEntry(name, owner[entry]) ); } }; // Add HmrClient to every entries. addHmrClientEntry('entry', config); if (!config.plugins) { config.plugins = []; } // Add source-map support if configured. if (config.devtool && config.devtool.indexOf('source-map') >= 0) { config.plugins.push( new webpack.BannerPlugin({ banner: `;require('${require .resolve('source-map-support') .replace(/\\/g, '/')}').install();`, raw: true, entryOnly: false, }) ); } // Enable HMR globally if not. if (!config.plugins.find(p => p instanceof webpack.HotModuleReplacementPlugin)) { config.plugins.push(new webpack.HotModuleReplacementPlugin()); } return config; }
[ "function", "tweakWebpackConfig", "(", "module", ")", "{", "const", "{", "default", ":", "webpackConfig", "=", "module", "}", "=", "module", ";", "const", "config", "=", "handleWebpackConfig", "(", "webpackConfig", ")", ";", "if", "(", "!", "config", ")", "{", "throw", "new", "Error", "(", "'Not found webpack configuration. For multiple configurations in single file you must provide config with target \"node\".'", ")", ";", "}", "const", "hmrClientEntry", "=", "require", ".", "resolve", "(", "'./HmrClient'", ")", ";", "const", "addHmrClientEntry", "=", "(", "entry", ",", "entryOwner", ")", "=>", "{", "const", "owner", "=", "entryOwner", ";", "if", "(", "Array", ".", "isArray", "(", "owner", "[", "entry", "]", ")", ")", "{", "owner", "[", "entry", "]", ".", "splice", "(", "-", "1", ",", "0", ",", "hmrClientEntry", ")", ";", "}", "else", "if", "(", "typeof", "owner", "[", "entry", "]", "===", "'string'", ")", "{", "owner", "[", "entry", "]", "=", "[", "hmrClientEntry", ",", "owner", "[", "entry", "]", "]", ";", "}", "else", "if", "(", "typeof", "owner", "[", "entry", "]", "===", "'function'", ")", "{", "// Call function and try again with function result.", "owner", "[", "entry", "]", "=", "owner", "[", "entry", "]", "(", ")", ";", "addHmrClientEntry", "(", "entry", ",", "owner", ")", ";", "}", "else", "if", "(", "typeof", "owner", "[", "entry", "]", "===", "'object'", ")", "{", "Object", ".", "getOwnPropertyNames", "(", "owner", "[", "entry", "]", ")", ".", "forEach", "(", "name", "=>", "addHmrClientEntry", "(", "name", ",", "owner", "[", "entry", "]", ")", ")", ";", "}", "}", ";", "// Add HmrClient to every entries.", "addHmrClientEntry", "(", "'entry'", ",", "config", ")", ";", "if", "(", "!", "config", ".", "plugins", ")", "{", "config", ".", "plugins", "=", "[", "]", ";", "}", "// Add source-map support if configured.", "if", "(", "config", ".", "devtool", "&&", "config", ".", "devtool", ".", "indexOf", "(", "'source-map'", ")", ">=", "0", ")", "{", "config", ".", "plugins", ".", "push", "(", "new", "webpack", ".", "BannerPlugin", "(", "{", "banner", ":", "`", "${", "require", ".", "resolve", "(", "'source-map-support'", ")", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "'/'", ")", "}", "`", ",", "raw", ":", "true", ",", "entryOnly", ":", "false", ",", "}", ")", ")", ";", "}", "// Enable HMR globally if not.", "if", "(", "!", "config", ".", "plugins", ".", "find", "(", "p", "=>", "p", "instanceof", "webpack", ".", "HotModuleReplacementPlugin", ")", ")", "{", "config", ".", "plugins", ".", "push", "(", "new", "webpack", ".", "HotModuleReplacementPlugin", "(", ")", ")", ";", "}", "return", "config", ";", "}" ]
Add hmrClient to all entries. @param module @returns {Promise.<config>}
[ "Add", "hmrClient", "to", "all", "entries", "." ]
ad53c9e47cdf29d637edc035b383a47ebc8a401f
https://github.com/vlazh/node-hot-loader/blob/ad53c9e47cdf29d637edc035b383a47ebc8a401f/src/loader.js#L21-L77
20,369
saguijs/sagui
src/configure-webpack/loaders/javascript.js
buildExcludeCheck
function buildExcludeCheck (transpileDependencies = []) { const dependencyChecks = transpileDependencies.map((dependency) => ( new RegExp(`node_modules.${dependency}`) )) // see: https://webpack.js.org/configuration/module/#condition return function (assetPath) { const shouldTranspile = dependencyChecks .reduce((result, check) => result || assetPath.match(check), false) if (shouldTranspile) { return false } return !!assetPath.match(/node_modules/) } }
javascript
function buildExcludeCheck (transpileDependencies = []) { const dependencyChecks = transpileDependencies.map((dependency) => ( new RegExp(`node_modules.${dependency}`) )) // see: https://webpack.js.org/configuration/module/#condition return function (assetPath) { const shouldTranspile = dependencyChecks .reduce((result, check) => result || assetPath.match(check), false) if (shouldTranspile) { return false } return !!assetPath.match(/node_modules/) } }
[ "function", "buildExcludeCheck", "(", "transpileDependencies", "=", "[", "]", ")", "{", "const", "dependencyChecks", "=", "transpileDependencies", ".", "map", "(", "(", "dependency", ")", "=>", "(", "new", "RegExp", "(", "`", "${", "dependency", "}", "`", ")", ")", ")", "// see: https://webpack.js.org/configuration/module/#condition", "return", "function", "(", "assetPath", ")", "{", "const", "shouldTranspile", "=", "dependencyChecks", ".", "reduce", "(", "(", "result", ",", "check", ")", "=>", "result", "||", "assetPath", ".", "match", "(", "check", ")", ",", "false", ")", "if", "(", "shouldTranspile", ")", "{", "return", "false", "}", "return", "!", "!", "assetPath", ".", "match", "(", "/", "node_modules", "/", ")", "}", "}" ]
Take into consideration if the user wants any dependency to be transpiled with Babel and returns an exclude check function that can be used by Webpack
[ "Take", "into", "consideration", "if", "the", "user", "wants", "any", "dependency", "to", "be", "transpiled", "with", "Babel", "and", "returns", "an", "exclude", "check", "function", "that", "can", "be", "used", "by", "Webpack" ]
a5fae777eba82a0bbb53e49cf373351d5e3c4428
https://github.com/saguijs/sagui/blob/a5fae777eba82a0bbb53e49cf373351d5e3c4428/src/configure-webpack/loaders/javascript.js#L109-L122
20,370
radiovisual/get-video-id
index.js
vimeo
function vimeo(str) { if (str.indexOf('#') > -1) { str = str.split('#')[0]; } if (str.indexOf('?') > -1 && str.indexOf('clip_id=') === -1) { str = str.split('?')[0]; } var id; var arr; if (/https?:\/\/vimeo\.com\/[0-9]+$|https?:\/\/player\.vimeo\.com\/video\/[0-9]+$|https?:\/\/vimeo\.com\/channels|groups|album/igm.test(str)) { arr = str.split('/'); if (arr && arr.length) { id = arr.pop(); } } else if (/clip_id=/igm.test(str)) { arr = str.split('clip_id='); if (arr && arr.length) { id = arr[1].split('&')[0]; } } return id; }
javascript
function vimeo(str) { if (str.indexOf('#') > -1) { str = str.split('#')[0]; } if (str.indexOf('?') > -1 && str.indexOf('clip_id=') === -1) { str = str.split('?')[0]; } var id; var arr; if (/https?:\/\/vimeo\.com\/[0-9]+$|https?:\/\/player\.vimeo\.com\/video\/[0-9]+$|https?:\/\/vimeo\.com\/channels|groups|album/igm.test(str)) { arr = str.split('/'); if (arr && arr.length) { id = arr.pop(); } } else if (/clip_id=/igm.test(str)) { arr = str.split('clip_id='); if (arr && arr.length) { id = arr[1].split('&')[0]; } } return id; }
[ "function", "vimeo", "(", "str", ")", "{", "if", "(", "str", ".", "indexOf", "(", "'#'", ")", ">", "-", "1", ")", "{", "str", "=", "str", ".", "split", "(", "'#'", ")", "[", "0", "]", ";", "}", "if", "(", "str", ".", "indexOf", "(", "'?'", ")", ">", "-", "1", "&&", "str", ".", "indexOf", "(", "'clip_id='", ")", "===", "-", "1", ")", "{", "str", "=", "str", ".", "split", "(", "'?'", ")", "[", "0", "]", ";", "}", "var", "id", ";", "var", "arr", ";", "if", "(", "/", "https?:\\/\\/vimeo\\.com\\/[0-9]+$|https?:\\/\\/player\\.vimeo\\.com\\/video\\/[0-9]+$|https?:\\/\\/vimeo\\.com\\/channels|groups|album", "/", "igm", ".", "test", "(", "str", ")", ")", "{", "arr", "=", "str", ".", "split", "(", "'/'", ")", ";", "if", "(", "arr", "&&", "arr", ".", "length", ")", "{", "id", "=", "arr", ".", "pop", "(", ")", ";", "}", "}", "else", "if", "(", "/", "clip_id=", "/", "igm", ".", "test", "(", "str", ")", ")", "{", "arr", "=", "str", ".", "split", "(", "'clip_id='", ")", ";", "if", "(", "arr", "&&", "arr", ".", "length", ")", "{", "id", "=", "arr", "[", "1", "]", ".", "split", "(", "'&'", ")", "[", "0", "]", ";", "}", "}", "return", "id", ";", "}" ]
Get the vimeo id. @param {string} str - the url from which you want to extract the id @returns {string|undefined}
[ "Get", "the", "vimeo", "id", "." ]
a47ad75dfbbce64c0046ff273973ac205f086c38
https://github.com/radiovisual/get-video-id/blob/a47ad75dfbbce64c0046ff273973ac205f086c38/index.js#L65-L89
20,371
radiovisual/get-video-id
index.js
vine
function vine(str) { var regex = /https:\/\/vine\.co\/v\/([a-zA-Z0-9]*)\/?/; var matches = regex.exec(str); return matches && matches[1]; }
javascript
function vine(str) { var regex = /https:\/\/vine\.co\/v\/([a-zA-Z0-9]*)\/?/; var matches = regex.exec(str); return matches && matches[1]; }
[ "function", "vine", "(", "str", ")", "{", "var", "regex", "=", "/", "https:\\/\\/vine\\.co\\/v\\/([a-zA-Z0-9]*)\\/?", "/", ";", "var", "matches", "=", "regex", ".", "exec", "(", "str", ")", ";", "return", "matches", "&&", "matches", "[", "1", "]", ";", "}" ]
Get the vine id. @param {string} str - the url from which you want to extract the id @returns {string|undefined}
[ "Get", "the", "vine", "id", "." ]
a47ad75dfbbce64c0046ff273973ac205f086c38
https://github.com/radiovisual/get-video-id/blob/a47ad75dfbbce64c0046ff273973ac205f086c38/index.js#L96-L100
20,372
radiovisual/get-video-id
index.js
youtube
function youtube(str) { // shortcode var shortcode = /youtube:\/\/|https?:\/\/youtu\.be\//g; if (shortcode.test(str)) { var shortcodeid = str.split(shortcode)[1]; return stripParameters(shortcodeid); } // /v/ or /vi/ var inlinev = /\/v\/|\/vi\//g; if (inlinev.test(str)) { var inlineid = str.split(inlinev)[1]; return stripParameters(inlineid); } // v= or vi= var parameterv = /v=|vi=/g; if (parameterv.test(str)) { var arr = str.split(parameterv); return arr[1].split('&')[0]; } // v= or vi= var parameterwebp = /\/an_webp\//g; if (parameterwebp.test(str)) { var webp = str.split(parameterwebp)[1]; return stripParameters(webp); } // embed var embedreg = /\/embed\//g; if (embedreg.test(str)) { var embedid = str.split(embedreg)[1]; return stripParameters(embedid); } // user var userreg = /\/user\/(?!.*videos)/g; if (userreg.test(str)) { var elements = str.split('/'); return stripParameters(elements.pop()); } // attribution_link var attrreg = /\/attribution_link\?.*v%3D([^%&]*)(%26|&|$)/; if (attrreg.test(str)) { return str.match(attrreg)[1]; } }
javascript
function youtube(str) { // shortcode var shortcode = /youtube:\/\/|https?:\/\/youtu\.be\//g; if (shortcode.test(str)) { var shortcodeid = str.split(shortcode)[1]; return stripParameters(shortcodeid); } // /v/ or /vi/ var inlinev = /\/v\/|\/vi\//g; if (inlinev.test(str)) { var inlineid = str.split(inlinev)[1]; return stripParameters(inlineid); } // v= or vi= var parameterv = /v=|vi=/g; if (parameterv.test(str)) { var arr = str.split(parameterv); return arr[1].split('&')[0]; } // v= or vi= var parameterwebp = /\/an_webp\//g; if (parameterwebp.test(str)) { var webp = str.split(parameterwebp)[1]; return stripParameters(webp); } // embed var embedreg = /\/embed\//g; if (embedreg.test(str)) { var embedid = str.split(embedreg)[1]; return stripParameters(embedid); } // user var userreg = /\/user\/(?!.*videos)/g; if (userreg.test(str)) { var elements = str.split('/'); return stripParameters(elements.pop()); } // attribution_link var attrreg = /\/attribution_link\?.*v%3D([^%&]*)(%26|&|$)/; if (attrreg.test(str)) { return str.match(attrreg)[1]; } }
[ "function", "youtube", "(", "str", ")", "{", "// shortcode", "var", "shortcode", "=", "/", "youtube:\\/\\/|https?:\\/\\/youtu\\.be\\/", "/", "g", ";", "if", "(", "shortcode", ".", "test", "(", "str", ")", ")", "{", "var", "shortcodeid", "=", "str", ".", "split", "(", "shortcode", ")", "[", "1", "]", ";", "return", "stripParameters", "(", "shortcodeid", ")", ";", "}", "// /v/ or /vi/", "var", "inlinev", "=", "/", "\\/v\\/|\\/vi\\/", "/", "g", ";", "if", "(", "inlinev", ".", "test", "(", "str", ")", ")", "{", "var", "inlineid", "=", "str", ".", "split", "(", "inlinev", ")", "[", "1", "]", ";", "return", "stripParameters", "(", "inlineid", ")", ";", "}", "// v= or vi=", "var", "parameterv", "=", "/", "v=|vi=", "/", "g", ";", "if", "(", "parameterv", ".", "test", "(", "str", ")", ")", "{", "var", "arr", "=", "str", ".", "split", "(", "parameterv", ")", ";", "return", "arr", "[", "1", "]", ".", "split", "(", "'&'", ")", "[", "0", "]", ";", "}", "// v= or vi=", "var", "parameterwebp", "=", "/", "\\/an_webp\\/", "/", "g", ";", "if", "(", "parameterwebp", ".", "test", "(", "str", ")", ")", "{", "var", "webp", "=", "str", ".", "split", "(", "parameterwebp", ")", "[", "1", "]", ";", "return", "stripParameters", "(", "webp", ")", ";", "}", "// embed", "var", "embedreg", "=", "/", "\\/embed\\/", "/", "g", ";", "if", "(", "embedreg", ".", "test", "(", "str", ")", ")", "{", "var", "embedid", "=", "str", ".", "split", "(", "embedreg", ")", "[", "1", "]", ";", "return", "stripParameters", "(", "embedid", ")", ";", "}", "// user", "var", "userreg", "=", "/", "\\/user\\/(?!.*videos)", "/", "g", ";", "if", "(", "userreg", ".", "test", "(", "str", ")", ")", "{", "var", "elements", "=", "str", ".", "split", "(", "'/'", ")", ";", "return", "stripParameters", "(", "elements", ".", "pop", "(", ")", ")", ";", "}", "// attribution_link", "var", "attrreg", "=", "/", "\\/attribution_link\\?.*v%3D([^%&]*)(%26|&|$)", "/", ";", "if", "(", "attrreg", ".", "test", "(", "str", ")", ")", "{", "return", "str", ".", "match", "(", "attrreg", ")", "[", "1", "]", ";", "}", "}" ]
Get the Youtube Video id. @param {string} str - the url from which you want to extract the id @returns {string|undefined}
[ "Get", "the", "Youtube", "Video", "id", "." ]
a47ad75dfbbce64c0046ff273973ac205f086c38
https://github.com/radiovisual/get-video-id/blob/a47ad75dfbbce64c0046ff273973ac205f086c38/index.js#L107-L162
20,373
radiovisual/get-video-id
index.js
videopress
function videopress(str) { var idRegex; if (str.indexOf('embed') > -1) { idRegex = /embed\/(\w{8})/; return str.match(idRegex)[1]; } idRegex = /\/v\/(\w{8})/; var match = str.match(idRegex); if (match && match.length > 0) { return str.match(idRegex)[1]; } return undefined; }
javascript
function videopress(str) { var idRegex; if (str.indexOf('embed') > -1) { idRegex = /embed\/(\w{8})/; return str.match(idRegex)[1]; } idRegex = /\/v\/(\w{8})/; var match = str.match(idRegex); if (match && match.length > 0) { return str.match(idRegex)[1]; } return undefined; }
[ "function", "videopress", "(", "str", ")", "{", "var", "idRegex", ";", "if", "(", "str", ".", "indexOf", "(", "'embed'", ")", ">", "-", "1", ")", "{", "idRegex", "=", "/", "embed\\/(\\w{8})", "/", ";", "return", "str", ".", "match", "(", "idRegex", ")", "[", "1", "]", ";", "}", "idRegex", "=", "/", "\\/v\\/(\\w{8})", "/", ";", "var", "match", "=", "str", ".", "match", "(", "idRegex", ")", ";", "if", "(", "match", "&&", "match", ".", "length", ">", "0", ")", "{", "return", "str", ".", "match", "(", "idRegex", ")", "[", "1", "]", ";", "}", "return", "undefined", ";", "}" ]
Get the VideoPress id. @param {string} str - the url from which you want to extract the id @returns {string|undefined}
[ "Get", "the", "VideoPress", "id", "." ]
a47ad75dfbbce64c0046ff273973ac205f086c38
https://github.com/radiovisual/get-video-id/blob/a47ad75dfbbce64c0046ff273973ac205f086c38/index.js#L169-L184
20,374
postmanlabs/uvm
lib/uvm/index.js
function (name) { (Array.isArray(this._pending) ? this._pending : (this._pending = [])).push(arguments); this.emit(DISPATCHQUEUE_EVENT, name); }
javascript
function (name) { (Array.isArray(this._pending) ? this._pending : (this._pending = [])).push(arguments); this.emit(DISPATCHQUEUE_EVENT, name); }
[ "function", "(", "name", ")", "{", "(", "Array", ".", "isArray", "(", "this", ".", "_pending", ")", "?", "this", ".", "_pending", ":", "(", "this", ".", "_pending", "=", "[", "]", ")", ")", ".", "push", "(", "arguments", ")", ";", "this", ".", "emit", "(", "DISPATCHQUEUE_EVENT", ",", "name", ")", ";", "}" ]
Stub dispatch handler to queue dispatched messages until bridge is ready. @param {String} name
[ "Stub", "dispatch", "handler", "to", "queue", "dispatched", "messages", "until", "bridge", "is", "ready", "." ]
3cf2de22c17b202f15681ecbe51a1a0ba7cfe5ac
https://github.com/postmanlabs/uvm/blob/3cf2de22c17b202f15681ecbe51a1a0ba7cfe5ac/lib/uvm/index.js#L121-L124
20,375
AltSchool/ember-cli-react
blueprints/ember-cli-react/index.js
function() { const packages = [ { name: 'ember-auto-import', target: getDependencyVersion(pkg, 'ember-auto-import'), }, { name: 'react', target: getPeerDependencyVersion(pkg, 'react'), }, { name: 'react-dom', target: getPeerDependencyVersion(pkg, 'react-dom'), }, ]; return this.addPackagesToProject(packages); }
javascript
function() { const packages = [ { name: 'ember-auto-import', target: getDependencyVersion(pkg, 'ember-auto-import'), }, { name: 'react', target: getPeerDependencyVersion(pkg, 'react'), }, { name: 'react-dom', target: getPeerDependencyVersion(pkg, 'react-dom'), }, ]; return this.addPackagesToProject(packages); }
[ "function", "(", ")", "{", "const", "packages", "=", "[", "{", "name", ":", "'ember-auto-import'", ",", "target", ":", "getDependencyVersion", "(", "pkg", ",", "'ember-auto-import'", ")", ",", "}", ",", "{", "name", ":", "'react'", ",", "target", ":", "getPeerDependencyVersion", "(", "pkg", ",", "'react'", ")", ",", "}", ",", "{", "name", ":", "'react-dom'", ",", "target", ":", "getPeerDependencyVersion", "(", "pkg", ",", "'react-dom'", ")", ",", "}", ",", "]", ";", "return", "this", ".", "addPackagesToProject", "(", "packages", ")", ";", "}" ]
Install react into host app
[ "Install", "react", "into", "host", "app" ]
caee6ceeb338d8985fffc177e8e1d8f21c1f51c9
https://github.com/AltSchool/ember-cli-react/blob/caee6ceeb338d8985fffc177e8e1d8f21c1f51c9/blueprints/ember-cli-react/index.js#L24-L40
20,376
LarryBattle/YASMIJ.js
src/YASMIJ.Simplex.js
function () { this.input = new YASMIJ.Input(); this.output = new YASMIJ.Output(); this.tableau = new YASMIJ.Tableau(); this.state = null; }
javascript
function () { this.input = new YASMIJ.Input(); this.output = new YASMIJ.Output(); this.tableau = new YASMIJ.Tableau(); this.state = null; }
[ "function", "(", ")", "{", "this", ".", "input", "=", "new", "YASMIJ", ".", "Input", "(", ")", ";", "this", ".", "output", "=", "new", "YASMIJ", ".", "Output", "(", ")", ";", "this", ".", "tableau", "=", "new", "YASMIJ", ".", "Tableau", "(", ")", ";", "this", ".", "state", "=", "null", ";", "}" ]
Simplex Class - not sure if this class is needed. @constructor
[ "Simplex", "Class", "-", "not", "sure", "if", "this", "class", "is", "needed", "." ]
c1335f0bd734bd0fc50e21958f460fd791dc16b3
https://github.com/LarryBattle/YASMIJ.js/blob/c1335f0bd734bd0fc50e21958f460fd791dc16b3/src/YASMIJ.Simplex.js#L13-L18
20,377
LarryBattle/YASMIJ.js
demo/js/demo.js
function(msg){ var logs = document.getElementById("logs"); logs.innerHTML += Funcs.util.getTimeStamp() + ": " + msg + "\n"; }
javascript
function(msg){ var logs = document.getElementById("logs"); logs.innerHTML += Funcs.util.getTimeStamp() + ": " + msg + "\n"; }
[ "function", "(", "msg", ")", "{", "var", "logs", "=", "document", ".", "getElementById", "(", "\"logs\"", ")", ";", "logs", ".", "innerHTML", "+=", "Funcs", ".", "util", ".", "getTimeStamp", "(", ")", "+", "\": \"", "+", "msg", "+", "\"\\n\"", ";", "}" ]
adds log message
[ "adds", "log", "message" ]
c1335f0bd734bd0fc50e21958f460fd791dc16b3
https://github.com/LarryBattle/YASMIJ.js/blob/c1335f0bd734bd0fc50e21958f460fd791dc16b3/demo/js/demo.js#L25-L28
20,378
LarryBattle/YASMIJ.js
demo/js/demo.js
function(){ return { type : document.getElementById("problemType").value, objective : document.getElementById("problemObjective").value, constraints : $(".input_constraint").filter(function(){ return /\w/.test( $(this).val() ); }).map(function(){ return $(this).val(); }).toArray() }; }
javascript
function(){ return { type : document.getElementById("problemType").value, objective : document.getElementById("problemObjective").value, constraints : $(".input_constraint").filter(function(){ return /\w/.test( $(this).val() ); }).map(function(){ return $(this).val(); }).toArray() }; }
[ "function", "(", ")", "{", "return", "{", "type", ":", "document", ".", "getElementById", "(", "\"problemType\"", ")", ".", "value", ",", "objective", ":", "document", ".", "getElementById", "(", "\"problemObjective\"", ")", ".", "value", ",", "constraints", ":", "$", "(", "\".input_constraint\"", ")", ".", "filter", "(", "function", "(", ")", "{", "return", "/", "\\w", "/", ".", "test", "(", "$", "(", "this", ")", ".", "val", "(", ")", ")", ";", "}", ")", ".", "map", "(", "function", "(", ")", "{", "return", "$", "(", "this", ")", ".", "val", "(", ")", ";", "}", ")", ".", "toArray", "(", ")", "}", ";", "}" ]
returns object needs to create a input object for YASMIJ.
[ "returns", "object", "needs", "to", "create", "a", "input", "object", "for", "YASMIJ", "." ]
c1335f0bd734bd0fc50e21958f460fd791dc16b3
https://github.com/LarryBattle/YASMIJ.js/blob/c1335f0bd734bd0fc50e21958f460fd791dc16b3/demo/js/demo.js#L48-L58
20,379
syntax-tree/hast-to-hyperscript
index.js
react
function react(h) { var node = h && h('div') return Boolean( node && ('_owner' in node || '_store' in node) && node.key === null ) }
javascript
function react(h) { var node = h && h('div') return Boolean( node && ('_owner' in node || '_store' in node) && node.key === null ) }
[ "function", "react", "(", "h", ")", "{", "var", "node", "=", "h", "&&", "h", "(", "'div'", ")", "return", "Boolean", "(", "node", "&&", "(", "'_owner'", "in", "node", "||", "'_store'", "in", "node", ")", "&&", "node", ".", "key", "===", "null", ")", "}" ]
Check if `h` is `react.createElement`.
[ "Check", "if", "h", "is", "react", ".", "createElement", "." ]
d7940b41819c3818388ce15a2b24312e511a7e70
https://github.com/syntax-tree/hast-to-hyperscript/blob/d7940b41819c3818388ce15a2b24312e511a7e70/index.js#L197-L202
20,380
bestiejs/spotlight.js
spotlight.js
crawl
function crawl(callback, callbackArg, options) { options || (options = {}); if (callback == 'custom') { var isCustom = true; } else { isCustom = false; callback = filters[callback]; } var data, index, pool, pooled, queue, separator, roots = defaultRoots.slice(), object = options.object, path = options.path, result = []; // Resolve object roots. if (object) { // Resolve `undefined` path. if (path == null) { path = _.result(_.find(roots, { 'object': object }), 'path') || '<object>'; } roots = [{ 'object': object, 'path': path }]; } // Crawl all root objects. while ((data = roots.pop())) { index = 0; object = data.object; path = data.path; data = { 'object': object, 'path': path, 'pool': [object] }; queue = []; // A non-recursive solution to avoid call stack limits. // See http://www.jslab.dk/articles/non.recursive.preorder.traversal.part4 // for more details. do { object = data.object; path = data.path; separator = path ? '.' : ''; forOwn(object, function(value, key) { // IE may throw errors coercing properties like `window.external` or `window.navigator`. try { // Inspect objects. if (_.isPlainObject(value)) { // Clone current pool per prop on the current `object` to avoid // sibling properties from polluting each others object pools. pool = data.pool.slice(); // Check if already pooled (prevents infinite loops when handling circular references). pooled = _.find(pool, function(data) { return value == data.object; }); // Add to the "call" queue. if (!pooled) { pool.push({ 'object': value, 'path': path + separator + key, 'pool': pool }); queue.push(_.last(pool)); } } // If filter passed, log it. if ( isCustom ? callbackArg.call(data, value, key, object) : callback(callbackArg, key, object) ) { value = [ path + separator + key + ' -> (' + (pooled ? '<' + pooled.path + '>' : getKindOf(value).toLowerCase()) + ')', value ]; result.push(value); log('text', value[0], value[1]); } } catch(e) {} }); } while ((data = queue[index++])); } return result; }
javascript
function crawl(callback, callbackArg, options) { options || (options = {}); if (callback == 'custom') { var isCustom = true; } else { isCustom = false; callback = filters[callback]; } var data, index, pool, pooled, queue, separator, roots = defaultRoots.slice(), object = options.object, path = options.path, result = []; // Resolve object roots. if (object) { // Resolve `undefined` path. if (path == null) { path = _.result(_.find(roots, { 'object': object }), 'path') || '<object>'; } roots = [{ 'object': object, 'path': path }]; } // Crawl all root objects. while ((data = roots.pop())) { index = 0; object = data.object; path = data.path; data = { 'object': object, 'path': path, 'pool': [object] }; queue = []; // A non-recursive solution to avoid call stack limits. // See http://www.jslab.dk/articles/non.recursive.preorder.traversal.part4 // for more details. do { object = data.object; path = data.path; separator = path ? '.' : ''; forOwn(object, function(value, key) { // IE may throw errors coercing properties like `window.external` or `window.navigator`. try { // Inspect objects. if (_.isPlainObject(value)) { // Clone current pool per prop on the current `object` to avoid // sibling properties from polluting each others object pools. pool = data.pool.slice(); // Check if already pooled (prevents infinite loops when handling circular references). pooled = _.find(pool, function(data) { return value == data.object; }); // Add to the "call" queue. if (!pooled) { pool.push({ 'object': value, 'path': path + separator + key, 'pool': pool }); queue.push(_.last(pool)); } } // If filter passed, log it. if ( isCustom ? callbackArg.call(data, value, key, object) : callback(callbackArg, key, object) ) { value = [ path + separator + key + ' -> (' + (pooled ? '<' + pooled.path + '>' : getKindOf(value).toLowerCase()) + ')', value ]; result.push(value); log('text', value[0], value[1]); } } catch(e) {} }); } while ((data = queue[index++])); } return result; }
[ "function", "crawl", "(", "callback", ",", "callbackArg", ",", "options", ")", "{", "options", "||", "(", "options", "=", "{", "}", ")", ";", "if", "(", "callback", "==", "'custom'", ")", "{", "var", "isCustom", "=", "true", ";", "}", "else", "{", "isCustom", "=", "false", ";", "callback", "=", "filters", "[", "callback", "]", ";", "}", "var", "data", ",", "index", ",", "pool", ",", "pooled", ",", "queue", ",", "separator", ",", "roots", "=", "defaultRoots", ".", "slice", "(", ")", ",", "object", "=", "options", ".", "object", ",", "path", "=", "options", ".", "path", ",", "result", "=", "[", "]", ";", "// Resolve object roots.", "if", "(", "object", ")", "{", "// Resolve `undefined` path.", "if", "(", "path", "==", "null", ")", "{", "path", "=", "_", ".", "result", "(", "_", ".", "find", "(", "roots", ",", "{", "'object'", ":", "object", "}", ")", ",", "'path'", ")", "||", "'<object>'", ";", "}", "roots", "=", "[", "{", "'object'", ":", "object", ",", "'path'", ":", "path", "}", "]", ";", "}", "// Crawl all root objects.", "while", "(", "(", "data", "=", "roots", ".", "pop", "(", ")", ")", ")", "{", "index", "=", "0", ";", "object", "=", "data", ".", "object", ";", "path", "=", "data", ".", "path", ";", "data", "=", "{", "'object'", ":", "object", ",", "'path'", ":", "path", ",", "'pool'", ":", "[", "object", "]", "}", ";", "queue", "=", "[", "]", ";", "// A non-recursive solution to avoid call stack limits.", "// See http://www.jslab.dk/articles/non.recursive.preorder.traversal.part4", "// for more details.", "do", "{", "object", "=", "data", ".", "object", ";", "path", "=", "data", ".", "path", ";", "separator", "=", "path", "?", "'.'", ":", "''", ";", "forOwn", "(", "object", ",", "function", "(", "value", ",", "key", ")", "{", "// IE may throw errors coercing properties like `window.external` or `window.navigator`.", "try", "{", "// Inspect objects.", "if", "(", "_", ".", "isPlainObject", "(", "value", ")", ")", "{", "// Clone current pool per prop on the current `object` to avoid", "// sibling properties from polluting each others object pools.", "pool", "=", "data", ".", "pool", ".", "slice", "(", ")", ";", "// Check if already pooled (prevents infinite loops when handling circular references).", "pooled", "=", "_", ".", "find", "(", "pool", ",", "function", "(", "data", ")", "{", "return", "value", "==", "data", ".", "object", ";", "}", ")", ";", "// Add to the \"call\" queue.", "if", "(", "!", "pooled", ")", "{", "pool", ".", "push", "(", "{", "'object'", ":", "value", ",", "'path'", ":", "path", "+", "separator", "+", "key", ",", "'pool'", ":", "pool", "}", ")", ";", "queue", ".", "push", "(", "_", ".", "last", "(", "pool", ")", ")", ";", "}", "}", "// If filter passed, log it.", "if", "(", "isCustom", "?", "callbackArg", ".", "call", "(", "data", ",", "value", ",", "key", ",", "object", ")", ":", "callback", "(", "callbackArg", ",", "key", ",", "object", ")", ")", "{", "value", "=", "[", "path", "+", "separator", "+", "key", "+", "' -> ('", "+", "(", "pooled", "?", "'<'", "+", "pooled", ".", "path", "+", "'>'", ":", "getKindOf", "(", "value", ")", ".", "toLowerCase", "(", ")", ")", "+", "')'", ",", "value", "]", ";", "result", ".", "push", "(", "value", ")", ";", "log", "(", "'text'", ",", "value", "[", "0", "]", ",", "value", "[", "1", "]", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "}", "}", ")", ";", "}", "while", "(", "(", "data", "=", "queue", "[", "index", "++", "]", ")", ")", ";", "}", "return", "result", ";", "}" ]
Crawls environment objects logging all properties that pass the callback filter. @private @param {Function|string} callback A function executed per object encountered. @param {*} callbackArg An argument passed to the callback. @param {Object} [options={}] The options object. @returns {Array} An array of arguments passed to each `console.log()` call.
[ "Crawls", "environment", "objects", "logging", "all", "properties", "that", "pass", "the", "callback", "filter", "." ]
06ce0bd22f8a1c5695e933c8d954425b6533618c
https://github.com/bestiejs/spotlight.js/blob/06ce0bd22f8a1c5695e933c8d954425b6533618c/spotlight.js#L359-L441
20,381
bestiejs/spotlight.js
spotlight.js
log
function log() { var defaultCount = 2, console = isHostType(context, 'console') && context.console, document = isHostType(context, 'document') && context.document, phantom = isHostType(context, 'phantom') && context.phantom, JSON = isHostType(context, 'JSON') && _.isFunction(context.JSON && context.JSON.stringify) && context.JSON; // Lazy define `log`. log = function(type, message, value) { var argCount = defaultCount, method = 'log'; if (type == 'error') { argCount = 1; if (isHostType(console, type)) { method = type; } else { message = type + ': ' + message; } } // Avoid logging if in debug mode and running from the CLI. if (!isDebug || (document && !phantom)) { // Because `console.log` is a host method we don't assume `apply` exists. if (argCount < 2) { if (JSON) { value = [JSON.stringify(value), value]; value = value[0] == 'null' ? value[1] : value[0]; } console[method](message + (type == 'error' ? '' : ' ' + value)); } else { console[method](message, value); } } }; // For Rhino or RingoJS. if (!console && !document && _.isFunction(context.print)) { console = { 'log': print }; } // Use noop for no log support. if (!isHostType(console, 'log')) { log = function() {}; } // Avoid Safari 2 crash bug when passing more than 1 argument. else if (console.log.length == 1) { defaultCount = 1; } return log.apply(null, arguments); }
javascript
function log() { var defaultCount = 2, console = isHostType(context, 'console') && context.console, document = isHostType(context, 'document') && context.document, phantom = isHostType(context, 'phantom') && context.phantom, JSON = isHostType(context, 'JSON') && _.isFunction(context.JSON && context.JSON.stringify) && context.JSON; // Lazy define `log`. log = function(type, message, value) { var argCount = defaultCount, method = 'log'; if (type == 'error') { argCount = 1; if (isHostType(console, type)) { method = type; } else { message = type + ': ' + message; } } // Avoid logging if in debug mode and running from the CLI. if (!isDebug || (document && !phantom)) { // Because `console.log` is a host method we don't assume `apply` exists. if (argCount < 2) { if (JSON) { value = [JSON.stringify(value), value]; value = value[0] == 'null' ? value[1] : value[0]; } console[method](message + (type == 'error' ? '' : ' ' + value)); } else { console[method](message, value); } } }; // For Rhino or RingoJS. if (!console && !document && _.isFunction(context.print)) { console = { 'log': print }; } // Use noop for no log support. if (!isHostType(console, 'log')) { log = function() {}; } // Avoid Safari 2 crash bug when passing more than 1 argument. else if (console.log.length == 1) { defaultCount = 1; } return log.apply(null, arguments); }
[ "function", "log", "(", ")", "{", "var", "defaultCount", "=", "2", ",", "console", "=", "isHostType", "(", "context", ",", "'console'", ")", "&&", "context", ".", "console", ",", "document", "=", "isHostType", "(", "context", ",", "'document'", ")", "&&", "context", ".", "document", ",", "phantom", "=", "isHostType", "(", "context", ",", "'phantom'", ")", "&&", "context", ".", "phantom", ",", "JSON", "=", "isHostType", "(", "context", ",", "'JSON'", ")", "&&", "_", ".", "isFunction", "(", "context", ".", "JSON", "&&", "context", ".", "JSON", ".", "stringify", ")", "&&", "context", ".", "JSON", ";", "// Lazy define `log`.", "log", "=", "function", "(", "type", ",", "message", ",", "value", ")", "{", "var", "argCount", "=", "defaultCount", ",", "method", "=", "'log'", ";", "if", "(", "type", "==", "'error'", ")", "{", "argCount", "=", "1", ";", "if", "(", "isHostType", "(", "console", ",", "type", ")", ")", "{", "method", "=", "type", ";", "}", "else", "{", "message", "=", "type", "+", "': '", "+", "message", ";", "}", "}", "// Avoid logging if in debug mode and running from the CLI.", "if", "(", "!", "isDebug", "||", "(", "document", "&&", "!", "phantom", ")", ")", "{", "// Because `console.log` is a host method we don't assume `apply` exists.", "if", "(", "argCount", "<", "2", ")", "{", "if", "(", "JSON", ")", "{", "value", "=", "[", "JSON", ".", "stringify", "(", "value", ")", ",", "value", "]", ";", "value", "=", "value", "[", "0", "]", "==", "'null'", "?", "value", "[", "1", "]", ":", "value", "[", "0", "]", ";", "}", "console", "[", "method", "]", "(", "message", "+", "(", "type", "==", "'error'", "?", "''", ":", "' '", "+", "value", ")", ")", ";", "}", "else", "{", "console", "[", "method", "]", "(", "message", ",", "value", ")", ";", "}", "}", "}", ";", "// For Rhino or RingoJS.", "if", "(", "!", "console", "&&", "!", "document", "&&", "_", ".", "isFunction", "(", "context", ".", "print", ")", ")", "{", "console", "=", "{", "'log'", ":", "print", "}", ";", "}", "// Use noop for no log support.", "if", "(", "!", "isHostType", "(", "console", ",", "'log'", ")", ")", "{", "log", "=", "function", "(", ")", "{", "}", ";", "}", "// Avoid Safari 2 crash bug when passing more than 1 argument.", "else", "if", "(", "console", ".", "log", ".", "length", "==", "1", ")", "{", "defaultCount", "=", "1", ";", "}", "return", "log", ".", "apply", "(", "null", ",", "arguments", ")", ";", "}" ]
Logs a message to the console. @private @param {string} type The log type, either "text" or "error". @param {string} message The log message. @param {*} value An additional value to log.
[ "Logs", "a", "message", "to", "the", "console", "." ]
06ce0bd22f8a1c5695e933c8d954425b6533618c
https://github.com/bestiejs/spotlight.js/blob/06ce0bd22f8a1c5695e933c8d954425b6533618c/spotlight.js#L451-L499
20,382
RonenNess/ExpiredStorage
dist/expired_storage.js
function(key, value, expiration) { // set item var ret = this._storage.setItem(key, value); // set expiration timestamp (only if defined) if (expiration) { this.updateExpiration(key, expiration); } // return set value return value return ret; }
javascript
function(key, value, expiration) { // set item var ret = this._storage.setItem(key, value); // set expiration timestamp (only if defined) if (expiration) { this.updateExpiration(key, expiration); } // return set value return value return ret; }
[ "function", "(", "key", ",", "value", ",", "expiration", ")", "{", "// set item", "var", "ret", "=", "this", ".", "_storage", ".", "setItem", "(", "key", ",", "value", ")", ";", "// set expiration timestamp (only if defined)", "if", "(", "expiration", ")", "{", "this", ".", "updateExpiration", "(", "key", ",", "expiration", ")", ";", "}", "// return set value return value", "return", "ret", ";", "}" ]
Set item. @param key: Item key to set (string). @param value: Value to store (string). @param expiration: Expiration time, in seconds. If not provided, will not set expiration time. @param return: Storage.setItem() return code.
[ "Set", "item", "." ]
8cac6e89a473519475071fd16812c57ef756aa08
https://github.com/RonenNess/ExpiredStorage/blob/8cac6e89a473519475071fd16812c57ef756aa08/dist/expired_storage.js#L55-L67
20,383
RonenNess/ExpiredStorage
dist/expired_storage.js
function(key) { // get value and time left var ret = { value: this._storage.getItem(key), timeLeft: this.getTimeLeft(key), }; // set if expired ret.isExpired = ret.timeLeft !== null && ret.timeLeft <= 0; // return data return ret; }
javascript
function(key) { // get value and time left var ret = { value: this._storage.getItem(key), timeLeft: this.getTimeLeft(key), }; // set if expired ret.isExpired = ret.timeLeft !== null && ret.timeLeft <= 0; // return data return ret; }
[ "function", "(", "key", ")", "{", "// get value and time left", "var", "ret", "=", "{", "value", ":", "this", ".", "_storage", ".", "getItem", "(", "key", ")", ",", "timeLeft", ":", "this", ".", "getTimeLeft", "(", "key", ")", ",", "}", ";", "// set if expired", "ret", ".", "isExpired", "=", "ret", ".", "timeLeft", "!==", "null", "&&", "ret", ".", "timeLeft", "<=", "0", ";", "// return data", "return", "ret", ";", "}" ]
Get item + metadata such as time left and if expired. Even if item expired, will not remove it. @param key: Item key to get (string). @return: Dictionary with: {value, timeLeft, isExpired}
[ "Get", "item", "+", "metadata", "such", "as", "time", "left", "and", "if", "expired", ".", "Even", "if", "item", "expired", "will", "not", "remove", "it", "." ]
8cac6e89a473519475071fd16812c57ef756aa08
https://github.com/RonenNess/ExpiredStorage/blob/8cac6e89a473519475071fd16812c57ef756aa08/dist/expired_storage.js#L92-L105
20,384
RonenNess/ExpiredStorage
dist/expired_storage.js
function(key) { // try to fetch expiration time for key var expireTime = parseInt(this._storage.getItem(this._expiration_key_prefix + key)); // if got expiration time return how much left to live if (expireTime && !isNaN(expireTime)) { return expireTime - this.getTimestamp(); } // if don't have expiration time return null return null; }
javascript
function(key) { // try to fetch expiration time for key var expireTime = parseInt(this._storage.getItem(this._expiration_key_prefix + key)); // if got expiration time return how much left to live if (expireTime && !isNaN(expireTime)) { return expireTime - this.getTimestamp(); } // if don't have expiration time return null return null; }
[ "function", "(", "key", ")", "{", "// try to fetch expiration time for key", "var", "expireTime", "=", "parseInt", "(", "this", ".", "_storage", ".", "getItem", "(", "this", ".", "_expiration_key_prefix", "+", "key", ")", ")", ";", "// if got expiration time return how much left to live", "if", "(", "expireTime", "&&", "!", "isNaN", "(", "expireTime", ")", ")", "{", "return", "expireTime", "-", "this", ".", "getTimestamp", "(", ")", ";", "}", "// if don't have expiration time return null", "return", "null", ";", "}" ]
Get item time left to live. @param key: Item key to get (string). @return: Time left to expire (in seconds), or null if don't have expiration date.
[ "Get", "item", "time", "left", "to", "live", "." ]
8cac6e89a473519475071fd16812c57ef756aa08
https://github.com/RonenNess/ExpiredStorage/blob/8cac6e89a473519475071fd16812c57ef756aa08/dist/expired_storage.js#L112-L125
20,385
RonenNess/ExpiredStorage
dist/expired_storage.js
function(key, val, expiration) { // special case - make sure not undefined, because it would just write "undefined" and crash on reading. if (val === undefined) { throw new Error("Cannot set undefined value as JSON!"); } // set stringified value return this.setItem(key, JSON.stringify(val), expiration); }
javascript
function(key, val, expiration) { // special case - make sure not undefined, because it would just write "undefined" and crash on reading. if (val === undefined) { throw new Error("Cannot set undefined value as JSON!"); } // set stringified value return this.setItem(key, JSON.stringify(val), expiration); }
[ "function", "(", "key", ",", "val", ",", "expiration", ")", "{", "// special case - make sure not undefined, because it would just write \"undefined\" and crash on reading.", "if", "(", "val", "===", "undefined", ")", "{", "throw", "new", "Error", "(", "\"Cannot set undefined value as JSON!\"", ")", ";", "}", "// set stringified value", "return", "this", ".", "setItem", "(", "key", ",", "JSON", ".", "stringify", "(", "val", ")", ",", "expiration", ")", ";", "}" ]
Set a json serializable value. This basically calls JSON.stringify on 'val' before setting it. @param key: Item key to set (string). @param value: Value to store (object, will be stringified). @param expiration: Expiration time, in seconds. If not provided, will not set expiration time. @param return: Storage.setItem() return code.
[ "Set", "a", "json", "serializable", "value", ".", "This", "basically", "calls", "JSON", ".", "stringify", "on", "val", "before", "setting", "it", "." ]
8cac6e89a473519475071fd16812c57ef756aa08
https://github.com/RonenNess/ExpiredStorage/blob/8cac6e89a473519475071fd16812c57ef756aa08/dist/expired_storage.js#L173-L182
20,386
RonenNess/ExpiredStorage
dist/expired_storage.js
function(key) { // get value var val = this.getItem(key); // if null, return null if (val === null) { return null; } // parse and return value return JSON.parse(val); }
javascript
function(key) { // get value var val = this.getItem(key); // if null, return null if (val === null) { return null; } // parse and return value return JSON.parse(val); }
[ "function", "(", "key", ")", "{", "// get value", "var", "val", "=", "this", ".", "getItem", "(", "key", ")", ";", "// if null, return null", "if", "(", "val", "===", "null", ")", "{", "return", "null", ";", "}", "// parse and return value", "return", "JSON", ".", "parse", "(", "val", ")", ";", "}" ]
Get a json serializable value. This basically calls JSON.parse on the returned value. @param key: Item key to get (string). @return: Stored value, or undefined if not set / expired.
[ "Get", "a", "json", "serializable", "value", ".", "This", "basically", "calls", "JSON", ".", "parse", "on", "the", "returned", "value", "." ]
8cac6e89a473519475071fd16812c57ef756aa08
https://github.com/RonenNess/ExpiredStorage/blob/8cac6e89a473519475071fd16812c57ef756aa08/dist/expired_storage.js#L189-L201
20,387
RonenNess/ExpiredStorage
dist/expired_storage.js
function(callback) { // first check if storage define a 'keys()' function. if it does, use it if (typeof this._storage.keys === "function") { var keys = this._storage.keys(); for (var i = 0; i < keys.length; ++i) { callback(keys[i]); } } // if not supported try to use object.keys else if (typeof Object === "function" && Object.keys) { var keys = Object.keys(this._storage); for (var i = 0; i < keys.length; ++i) { callback(keys[i]); } } // if not supported try to use iteration via length else if (this._storage.length !== undefined && typeof this._storage.key === "function") { // first build keys array, so this function will be delete-safe (eg if callback remove keys it won't cause problems due to index change) var keys = []; for (var i = 0, len = this._storage.length; i < len; ++i) { keys.push(this._storage.key(i)); } // now actually iterate keys for (var i = 0; i < keys.length; ++i) { callback(keys[i]); } } // if both methods above didn't work, iterate on all keys in storage class hoping for the best.. else { for (var storageKey in this._storage) { callback(storageKey); } } }
javascript
function(callback) { // first check if storage define a 'keys()' function. if it does, use it if (typeof this._storage.keys === "function") { var keys = this._storage.keys(); for (var i = 0; i < keys.length; ++i) { callback(keys[i]); } } // if not supported try to use object.keys else if (typeof Object === "function" && Object.keys) { var keys = Object.keys(this._storage); for (var i = 0; i < keys.length; ++i) { callback(keys[i]); } } // if not supported try to use iteration via length else if (this._storage.length !== undefined && typeof this._storage.key === "function") { // first build keys array, so this function will be delete-safe (eg if callback remove keys it won't cause problems due to index change) var keys = []; for (var i = 0, len = this._storage.length; i < len; ++i) { keys.push(this._storage.key(i)); } // now actually iterate keys for (var i = 0; i < keys.length; ++i) { callback(keys[i]); } } // if both methods above didn't work, iterate on all keys in storage class hoping for the best.. else { for (var storageKey in this._storage) { callback(storageKey); } } }
[ "function", "(", "callback", ")", "{", "// first check if storage define a 'keys()' function. if it does, use it", "if", "(", "typeof", "this", ".", "_storage", ".", "keys", "===", "\"function\"", ")", "{", "var", "keys", "=", "this", ".", "_storage", ".", "keys", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "{", "callback", "(", "keys", "[", "i", "]", ")", ";", "}", "}", "// if not supported try to use object.keys", "else", "if", "(", "typeof", "Object", "===", "\"function\"", "&&", "Object", ".", "keys", ")", "{", "var", "keys", "=", "Object", ".", "keys", "(", "this", ".", "_storage", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "{", "callback", "(", "keys", "[", "i", "]", ")", ";", "}", "}", "// if not supported try to use iteration via length", "else", "if", "(", "this", ".", "_storage", ".", "length", "!==", "undefined", "&&", "typeof", "this", ".", "_storage", ".", "key", "===", "\"function\"", ")", "{", "// first build keys array, so this function will be delete-safe (eg if callback remove keys it won't cause problems due to index change)", "var", "keys", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "this", ".", "_storage", ".", "length", ";", "i", "<", "len", ";", "++", "i", ")", "{", "keys", ".", "push", "(", "this", ".", "_storage", ".", "key", "(", "i", ")", ")", ";", "}", "// now actually iterate keys", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "{", "callback", "(", "keys", "[", "i", "]", ")", ";", "}", "}", "// if both methods above didn't work, iterate on all keys in storage class hoping for the best..", "else", "{", "for", "(", "var", "storageKey", "in", "this", ".", "_storage", ")", "{", "callback", "(", "storageKey", ")", ";", "}", "}", "}" ]
Iterate all keys in storage class. @param callback: Function to call for every key, with a single param: key.
[ "Iterate", "all", "keys", "in", "storage", "class", "." ]
8cac6e89a473519475071fd16812c57ef756aa08
https://github.com/RonenNess/ExpiredStorage/blob/8cac6e89a473519475071fd16812c57ef756aa08/dist/expired_storage.js#L234-L272
20,388
zuixjs/zuix
src/js/zuix/ContextController.js
ContextController
function ContextController(context) { const _t = this; this._view = null; this.context = context; /** * @package * @type {!Array.<ZxQuery>} **/ this._fieldCache = []; // Interface methods /** @type {function} */ this.init = null; /** @type {function} */ this.create = null; /** @type {function} */ this.update = null; /** @type {function} */ this.destroy = null; /** * @protected * @type {!Array.<Element>} * */ this._childNodes = []; /** @type {function} */ this.saveView = function() { this.restoreView(); this.view().children().each(function(i, el) { _t._childNodes.push(el); }); }; this.restoreView = function() { if (this._childNodes.length > 0) { _t.view().html(''); z$.each(_t._childNodes, function(i, el) { _t.view().append(el); }); this._childNodes.length = 0; } }; this.on = function(eventPath, handler) { this.addEvent(eventPath, handler); return this; }; /** @protected */ this.mapEvent = function(eventMap, target, eventPath, handler) { if (target != null) { target.off(eventPath, this.eventRouter); eventMap[eventPath] = handler; target.on(eventPath, this.eventRouter); } else { // TODO: should report missing target } }; /** @protected */ this.eventRouter = function(e) { const v = _t.view(); if (typeof context._behaviorMap[e.type] === 'function') { context._behaviorMap[e.type].call(v, e, e.detail, v); } if (typeof context._eventMap[e.type] === 'function') { context._eventMap[e.type].call(v, e, e.detail, v); } // TODO: else-> should report anomaly }; // create event map from context options const options = context.options(); let handler = null; if (options.on != null) { for (let ep in options.on) { if (options.on.hasOwnProperty(ep)) { handler = options.on[ep]; _t.addEvent(ep, handler); } } } // create behavior map from context options if (options.behavior != null) { for (let bp in options.behavior) { if (options.behavior.hasOwnProperty(bp)) { handler = options.behavior[bp]; _t.addBehavior(bp, handler); } } } context.controller().call(this, this); return this; }
javascript
function ContextController(context) { const _t = this; this._view = null; this.context = context; /** * @package * @type {!Array.<ZxQuery>} **/ this._fieldCache = []; // Interface methods /** @type {function} */ this.init = null; /** @type {function} */ this.create = null; /** @type {function} */ this.update = null; /** @type {function} */ this.destroy = null; /** * @protected * @type {!Array.<Element>} * */ this._childNodes = []; /** @type {function} */ this.saveView = function() { this.restoreView(); this.view().children().each(function(i, el) { _t._childNodes.push(el); }); }; this.restoreView = function() { if (this._childNodes.length > 0) { _t.view().html(''); z$.each(_t._childNodes, function(i, el) { _t.view().append(el); }); this._childNodes.length = 0; } }; this.on = function(eventPath, handler) { this.addEvent(eventPath, handler); return this; }; /** @protected */ this.mapEvent = function(eventMap, target, eventPath, handler) { if (target != null) { target.off(eventPath, this.eventRouter); eventMap[eventPath] = handler; target.on(eventPath, this.eventRouter); } else { // TODO: should report missing target } }; /** @protected */ this.eventRouter = function(e) { const v = _t.view(); if (typeof context._behaviorMap[e.type] === 'function') { context._behaviorMap[e.type].call(v, e, e.detail, v); } if (typeof context._eventMap[e.type] === 'function') { context._eventMap[e.type].call(v, e, e.detail, v); } // TODO: else-> should report anomaly }; // create event map from context options const options = context.options(); let handler = null; if (options.on != null) { for (let ep in options.on) { if (options.on.hasOwnProperty(ep)) { handler = options.on[ep]; _t.addEvent(ep, handler); } } } // create behavior map from context options if (options.behavior != null) { for (let bp in options.behavior) { if (options.behavior.hasOwnProperty(bp)) { handler = options.behavior[bp]; _t.addBehavior(bp, handler); } } } context.controller().call(this, this); return this; }
[ "function", "ContextController", "(", "context", ")", "{", "const", "_t", "=", "this", ";", "this", ".", "_view", "=", "null", ";", "this", ".", "context", "=", "context", ";", "/**\n * @package\n * @type {!Array.<ZxQuery>}\n **/", "this", ".", "_fieldCache", "=", "[", "]", ";", "// Interface methods", "/** @type {function} */", "this", ".", "init", "=", "null", ";", "/** @type {function} */", "this", ".", "create", "=", "null", ";", "/** @type {function} */", "this", ".", "update", "=", "null", ";", "/** @type {function} */", "this", ".", "destroy", "=", "null", ";", "/**\n * @protected\n * @type {!Array.<Element>}\n * */", "this", ".", "_childNodes", "=", "[", "]", ";", "/** @type {function} */", "this", ".", "saveView", "=", "function", "(", ")", "{", "this", ".", "restoreView", "(", ")", ";", "this", ".", "view", "(", ")", ".", "children", "(", ")", ".", "each", "(", "function", "(", "i", ",", "el", ")", "{", "_t", ".", "_childNodes", ".", "push", "(", "el", ")", ";", "}", ")", ";", "}", ";", "this", ".", "restoreView", "=", "function", "(", ")", "{", "if", "(", "this", ".", "_childNodes", ".", "length", ">", "0", ")", "{", "_t", ".", "view", "(", ")", ".", "html", "(", "''", ")", ";", "z$", ".", "each", "(", "_t", ".", "_childNodes", ",", "function", "(", "i", ",", "el", ")", "{", "_t", ".", "view", "(", ")", ".", "append", "(", "el", ")", ";", "}", ")", ";", "this", ".", "_childNodes", ".", "length", "=", "0", ";", "}", "}", ";", "this", ".", "on", "=", "function", "(", "eventPath", ",", "handler", ")", "{", "this", ".", "addEvent", "(", "eventPath", ",", "handler", ")", ";", "return", "this", ";", "}", ";", "/** @protected */", "this", ".", "mapEvent", "=", "function", "(", "eventMap", ",", "target", ",", "eventPath", ",", "handler", ")", "{", "if", "(", "target", "!=", "null", ")", "{", "target", ".", "off", "(", "eventPath", ",", "this", ".", "eventRouter", ")", ";", "eventMap", "[", "eventPath", "]", "=", "handler", ";", "target", ".", "on", "(", "eventPath", ",", "this", ".", "eventRouter", ")", ";", "}", "else", "{", "// TODO: should report missing target", "}", "}", ";", "/** @protected */", "this", ".", "eventRouter", "=", "function", "(", "e", ")", "{", "const", "v", "=", "_t", ".", "view", "(", ")", ";", "if", "(", "typeof", "context", ".", "_behaviorMap", "[", "e", ".", "type", "]", "===", "'function'", ")", "{", "context", ".", "_behaviorMap", "[", "e", ".", "type", "]", ".", "call", "(", "v", ",", "e", ",", "e", ".", "detail", ",", "v", ")", ";", "}", "if", "(", "typeof", "context", ".", "_eventMap", "[", "e", ".", "type", "]", "===", "'function'", ")", "{", "context", ".", "_eventMap", "[", "e", ".", "type", "]", ".", "call", "(", "v", ",", "e", ",", "e", ".", "detail", ",", "v", ")", ";", "}", "// TODO: else-> should report anomaly", "}", ";", "// create event map from context options", "const", "options", "=", "context", ".", "options", "(", ")", ";", "let", "handler", "=", "null", ";", "if", "(", "options", ".", "on", "!=", "null", ")", "{", "for", "(", "let", "ep", "in", "options", ".", "on", ")", "{", "if", "(", "options", ".", "on", ".", "hasOwnProperty", "(", "ep", ")", ")", "{", "handler", "=", "options", ".", "on", "[", "ep", "]", ";", "_t", ".", "addEvent", "(", "ep", ",", "handler", ")", ";", "}", "}", "}", "// create behavior map from context options", "if", "(", "options", ".", "behavior", "!=", "null", ")", "{", "for", "(", "let", "bp", "in", "options", ".", "behavior", ")", "{", "if", "(", "options", ".", "behavior", ".", "hasOwnProperty", "(", "bp", ")", ")", "{", "handler", "=", "options", ".", "behavior", "[", "bp", "]", ";", "_t", ".", "addBehavior", "(", "bp", ",", "handler", ")", ";", "}", "}", "}", "context", ".", "controller", "(", ")", ".", "call", "(", "this", ",", "this", ")", ";", "return", "this", ";", "}" ]
ContextController user-defined handlers definition @typedef {Object} ContextController @property {function} init Function that gets called after loading and before the component is created. @property {function} create Function that gets called after loading, when the component is actually created and ready. @property {function} update Function called when the data model of the component is updated. @property {function} destroy Function called when the component is destroyed. ContextController constructor. @param {ComponentContext} context @return {ContextController} @constructor
[ "ContextController", "user", "-", "defined", "handlers", "definition" ]
d7c88a5137342ee2918e2a70aa3c01c1c285aea2
https://github.com/zuixjs/zuix/blob/d7c88a5137342ee2918e2a70aa3c01c1c285aea2/src/js/zuix/ContextController.js#L49-L145
20,389
zuixjs/zuix
src/js/helpers/TaskQueue.js
TaskQueue
function TaskQueue(listener) { const _t = this; _t._worker = null; _t._taskList = []; _t._requests = []; if (listener == null) { listener = function() { }; } _t.taskQueue = function(tid, fn, pri) { _t._taskList.push({ tid: tid, fn: fn, status: 0, priority: pri, step: function(tid) { // var _h = this; // _h.tid = tid; _log.t(tid, 'load:step'); listener(_t, 'load:step', { task: tid }); }, end: function() { this.status = 2; let _h = this; _log.t(_h.tid, 'load:next', 'timer:task:stop'); listener(_t, 'load:next', { task: _h.tid }); _t._taskList.splice(this.index, 1); _t.taskCheck(); if (this._callback != null) { this._callback.call(this); } }, callback: function(callback) { this._callback = callback; } }); _log.t(tid, 'task added', pri, 'priority'); _t._taskList.sort(function(a, b) { return (a.priority > b.priority) ? 1 : ((b.priority > a.priority) ? -1 : 0); } ); _t.taskCheck(); }; _t.taskCheck = function() { for (let i = 0; i < _t._taskList.length; i++) { if (_t._taskList[i].status === 0) { _t._taskList[i].status = 1; _log.t(_t._taskList[i].tid, 'load:begin', 'timer:task:start'); listener(_t, 'load:begin', { task: _t._taskList[i].tid }); _t._taskList[i].index = i; (_t._taskList[i].fn).call(_t._taskList[i]); return; } else if (_t._taskList[i].status === 1) { // currently running return; } else if (_t._taskList[i].status === 2) { // TODO: _!!!-! return; } } _log.t('load:end'); listener(_t, 'load:end'); }; }
javascript
function TaskQueue(listener) { const _t = this; _t._worker = null; _t._taskList = []; _t._requests = []; if (listener == null) { listener = function() { }; } _t.taskQueue = function(tid, fn, pri) { _t._taskList.push({ tid: tid, fn: fn, status: 0, priority: pri, step: function(tid) { // var _h = this; // _h.tid = tid; _log.t(tid, 'load:step'); listener(_t, 'load:step', { task: tid }); }, end: function() { this.status = 2; let _h = this; _log.t(_h.tid, 'load:next', 'timer:task:stop'); listener(_t, 'load:next', { task: _h.tid }); _t._taskList.splice(this.index, 1); _t.taskCheck(); if (this._callback != null) { this._callback.call(this); } }, callback: function(callback) { this._callback = callback; } }); _log.t(tid, 'task added', pri, 'priority'); _t._taskList.sort(function(a, b) { return (a.priority > b.priority) ? 1 : ((b.priority > a.priority) ? -1 : 0); } ); _t.taskCheck(); }; _t.taskCheck = function() { for (let i = 0; i < _t._taskList.length; i++) { if (_t._taskList[i].status === 0) { _t._taskList[i].status = 1; _log.t(_t._taskList[i].tid, 'load:begin', 'timer:task:start'); listener(_t, 'load:begin', { task: _t._taskList[i].tid }); _t._taskList[i].index = i; (_t._taskList[i].fn).call(_t._taskList[i]); return; } else if (_t._taskList[i].status === 1) { // currently running return; } else if (_t._taskList[i].status === 2) { // TODO: _!!!-! return; } } _log.t('load:end'); listener(_t, 'load:end'); }; }
[ "function", "TaskQueue", "(", "listener", ")", "{", "const", "_t", "=", "this", ";", "_t", ".", "_worker", "=", "null", ";", "_t", ".", "_taskList", "=", "[", "]", ";", "_t", ".", "_requests", "=", "[", "]", ";", "if", "(", "listener", "==", "null", ")", "{", "listener", "=", "function", "(", ")", "{", "}", ";", "}", "_t", ".", "taskQueue", "=", "function", "(", "tid", ",", "fn", ",", "pri", ")", "{", "_t", ".", "_taskList", ".", "push", "(", "{", "tid", ":", "tid", ",", "fn", ":", "fn", ",", "status", ":", "0", ",", "priority", ":", "pri", ",", "step", ":", "function", "(", "tid", ")", "{", "// var _h = this;", "// _h.tid = tid;", "_log", ".", "t", "(", "tid", ",", "'load:step'", ")", ";", "listener", "(", "_t", ",", "'load:step'", ",", "{", "task", ":", "tid", "}", ")", ";", "}", ",", "end", ":", "function", "(", ")", "{", "this", ".", "status", "=", "2", ";", "let", "_h", "=", "this", ";", "_log", ".", "t", "(", "_h", ".", "tid", ",", "'load:next'", ",", "'timer:task:stop'", ")", ";", "listener", "(", "_t", ",", "'load:next'", ",", "{", "task", ":", "_h", ".", "tid", "}", ")", ";", "_t", ".", "_taskList", ".", "splice", "(", "this", ".", "index", ",", "1", ")", ";", "_t", ".", "taskCheck", "(", ")", ";", "if", "(", "this", ".", "_callback", "!=", "null", ")", "{", "this", ".", "_callback", ".", "call", "(", "this", ")", ";", "}", "}", ",", "callback", ":", "function", "(", "callback", ")", "{", "this", ".", "_callback", "=", "callback", ";", "}", "}", ")", ";", "_log", ".", "t", "(", "tid", ",", "'task added'", ",", "pri", ",", "'priority'", ")", ";", "_t", ".", "_taskList", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "(", "a", ".", "priority", ">", "b", ".", "priority", ")", "?", "1", ":", "(", "(", "b", ".", "priority", ">", "a", ".", "priority", ")", "?", "-", "1", ":", "0", ")", ";", "}", ")", ";", "_t", ".", "taskCheck", "(", ")", ";", "}", ";", "_t", ".", "taskCheck", "=", "function", "(", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "_t", ".", "_taskList", ".", "length", ";", "i", "++", ")", "{", "if", "(", "_t", ".", "_taskList", "[", "i", "]", ".", "status", "===", "0", ")", "{", "_t", ".", "_taskList", "[", "i", "]", ".", "status", "=", "1", ";", "_log", ".", "t", "(", "_t", ".", "_taskList", "[", "i", "]", ".", "tid", ",", "'load:begin'", ",", "'timer:task:start'", ")", ";", "listener", "(", "_t", ",", "'load:begin'", ",", "{", "task", ":", "_t", ".", "_taskList", "[", "i", "]", ".", "tid", "}", ")", ";", "_t", ".", "_taskList", "[", "i", "]", ".", "index", "=", "i", ";", "(", "_t", ".", "_taskList", "[", "i", "]", ".", "fn", ")", ".", "call", "(", "_t", ".", "_taskList", "[", "i", "]", ")", ";", "return", ";", "}", "else", "if", "(", "_t", ".", "_taskList", "[", "i", "]", ".", "status", "===", "1", ")", "{", "// currently running", "return", ";", "}", "else", "if", "(", "_t", ".", "_taskList", "[", "i", "]", ".", "status", "===", "2", ")", "{", "// TODO: _!!!-!", "return", ";", "}", "}", "_log", ".", "t", "(", "'load:end'", ")", ";", "listener", "(", "_t", ",", "'load:end'", ")", ";", "}", ";", "}" ]
Task Queue Manager @class TaskQueue @constructor
[ "Task", "Queue", "Manager" ]
d7c88a5137342ee2918e2a70aa3c01c1c285aea2
https://github.com/zuixjs/zuix/blob/d7c88a5137342ee2918e2a70aa3c01c1c285aea2/src/js/helpers/TaskQueue.js#L38-L108
20,390
zuixjs/zuix
src/js/helpers/ZxQuery.js
ZxQuery
function ZxQuery(element) { /** @protected */ this._selection = []; if (typeof element === 'undefined') { element = document.documentElement; } if (element instanceof ZxQuery) { return element; } else if (element instanceof HTMLCollection || element instanceof NodeList) { const list = this._selection = []; z$.each(element, function(i, el) { list.push(el); }); } else if (Array.isArray(element)) { this._selection = element; } else if (element === window || element instanceof HTMLElement || element instanceof Node) { this._selection = [element]; } else if (typeof element === 'string') { this._selection = document.documentElement.querySelectorAll(element); } else if (element !== null) { // if (typeof element === 'string') { _log.e('ZxQuery cannot wrap object of this type.', (typeof element), element); throw new Error('ZxQuery cannot wrap object of this type.'); } return this; }
javascript
function ZxQuery(element) { /** @protected */ this._selection = []; if (typeof element === 'undefined') { element = document.documentElement; } if (element instanceof ZxQuery) { return element; } else if (element instanceof HTMLCollection || element instanceof NodeList) { const list = this._selection = []; z$.each(element, function(i, el) { list.push(el); }); } else if (Array.isArray(element)) { this._selection = element; } else if (element === window || element instanceof HTMLElement || element instanceof Node) { this._selection = [element]; } else if (typeof element === 'string') { this._selection = document.documentElement.querySelectorAll(element); } else if (element !== null) { // if (typeof element === 'string') { _log.e('ZxQuery cannot wrap object of this type.', (typeof element), element); throw new Error('ZxQuery cannot wrap object of this type.'); } return this; }
[ "function", "ZxQuery", "(", "element", ")", "{", "/** @protected */", "this", ".", "_selection", "=", "[", "]", ";", "if", "(", "typeof", "element", "===", "'undefined'", ")", "{", "element", "=", "document", ".", "documentElement", ";", "}", "if", "(", "element", "instanceof", "ZxQuery", ")", "{", "return", "element", ";", "}", "else", "if", "(", "element", "instanceof", "HTMLCollection", "||", "element", "instanceof", "NodeList", ")", "{", "const", "list", "=", "this", ".", "_selection", "=", "[", "]", ";", "z$", ".", "each", "(", "element", ",", "function", "(", "i", ",", "el", ")", "{", "list", ".", "push", "(", "el", ")", ";", "}", ")", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "element", ")", ")", "{", "this", ".", "_selection", "=", "element", ";", "}", "else", "if", "(", "element", "===", "window", "||", "element", "instanceof", "HTMLElement", "||", "element", "instanceof", "Node", ")", "{", "this", ".", "_selection", "=", "[", "element", "]", ";", "}", "else", "if", "(", "typeof", "element", "===", "'string'", ")", "{", "this", ".", "_selection", "=", "document", ".", "documentElement", ".", "querySelectorAll", "(", "element", ")", ";", "}", "else", "if", "(", "element", "!==", "null", ")", "{", "// if (typeof element === 'string') {", "_log", ".", "e", "(", "'ZxQuery cannot wrap object of this type.'", ",", "(", "typeof", "element", ")", ",", "element", ")", ";", "throw", "new", "Error", "(", "'ZxQuery cannot wrap object of this type.'", ")", ";", "}", "return", "this", ";", "}" ]
ZxQuery, a very lite subset of jQuery-like functions internally used in Zuix for DOM operations. The constructor takes one optional argument that can be a DOM element, a node list or a valid DOM query selector string expression. If no parameter is given, the resulting ZxQuery object will wrap the root *document* element. @class ZxQuery @param {Object|ZxQuery|Array<Node>|Node|NodeList|string|undefined} [element] Element or list of elements to include in the ZxQuery object. @return {ZxQuery} The *ZxQuery* object containing the given element(s). @constructor
[ "ZxQuery", "a", "very", "lite", "subset", "of", "jQuery", "-", "like", "functions", "internally", "used", "in", "Zuix", "for", "DOM", "operations", "." ]
d7c88a5137342ee2918e2a70aa3c01c1c285aea2
https://github.com/zuixjs/zuix/blob/d7c88a5137342ee2918e2a70aa3c01c1c285aea2/src/js/helpers/ZxQuery.js#L135-L161
20,391
zuixjs/zuix
src/js/zuix/ComponentContext.js
ComponentContext
function ComponentContext(zuixInstance, options, eventCallback) { zuix = zuixInstance; this._options = null; this.contextId = (options == null || options.contextId == null) ? null : options.contextId; this.componentId = null; this.trigger = function(context, eventPath, eventValue) { if (typeof eventCallback === 'function') { eventCallback(context, eventPath, eventValue); } }; /** @protected */ this._container = null; /** @protected */ this._model = null; /** @protected */ this._view = null; /** @protected */ this._css = null; /** @protected */ this._style = null; /** * @protected * @type {ContextControllerHandler} */ this._controller = null; /** * Define the local behavior handler for this context instance only. * Any global behavior matching the same `componentId` will be overridden. * * @function behavior * @param handler_fn {function} */ this.behavior = null; /** @package */ this._eventMap = []; /** @package */ this._behaviorMap = []; /** * @package * @type {ContextController} */ this._c = null; this.options(options); return this; }
javascript
function ComponentContext(zuixInstance, options, eventCallback) { zuix = zuixInstance; this._options = null; this.contextId = (options == null || options.contextId == null) ? null : options.contextId; this.componentId = null; this.trigger = function(context, eventPath, eventValue) { if (typeof eventCallback === 'function') { eventCallback(context, eventPath, eventValue); } }; /** @protected */ this._container = null; /** @protected */ this._model = null; /** @protected */ this._view = null; /** @protected */ this._css = null; /** @protected */ this._style = null; /** * @protected * @type {ContextControllerHandler} */ this._controller = null; /** * Define the local behavior handler for this context instance only. * Any global behavior matching the same `componentId` will be overridden. * * @function behavior * @param handler_fn {function} */ this.behavior = null; /** @package */ this._eventMap = []; /** @package */ this._behaviorMap = []; /** * @package * @type {ContextController} */ this._c = null; this.options(options); return this; }
[ "function", "ComponentContext", "(", "zuixInstance", ",", "options", ",", "eventCallback", ")", "{", "zuix", "=", "zuixInstance", ";", "this", ".", "_options", "=", "null", ";", "this", ".", "contextId", "=", "(", "options", "==", "null", "||", "options", ".", "contextId", "==", "null", ")", "?", "null", ":", "options", ".", "contextId", ";", "this", ".", "componentId", "=", "null", ";", "this", ".", "trigger", "=", "function", "(", "context", ",", "eventPath", ",", "eventValue", ")", "{", "if", "(", "typeof", "eventCallback", "===", "'function'", ")", "{", "eventCallback", "(", "context", ",", "eventPath", ",", "eventValue", ")", ";", "}", "}", ";", "/** @protected */", "this", ".", "_container", "=", "null", ";", "/** @protected */", "this", ".", "_model", "=", "null", ";", "/** @protected */", "this", ".", "_view", "=", "null", ";", "/** @protected */", "this", ".", "_css", "=", "null", ";", "/** @protected */", "this", ".", "_style", "=", "null", ";", "/**\n * @protected\n * @type {ContextControllerHandler}\n */", "this", ".", "_controller", "=", "null", ";", "/**\n * Define the local behavior handler for this context instance only.\n * Any global behavior matching the same `componentId` will be overridden.\n *\n * @function behavior\n * @param handler_fn {function}\n */", "this", ".", "behavior", "=", "null", ";", "/** @package */", "this", ".", "_eventMap", "=", "[", "]", ";", "/** @package */", "this", ".", "_behaviorMap", "=", "[", "]", ";", "/**\n * @package\n * @type {ContextController}\n */", "this", ".", "_c", "=", "null", ";", "this", ".", "options", "(", "options", ")", ";", "return", "this", ";", "}" ]
The component context object. @param {Zuix} zuixInstance @param {ContextOptions} options The context options. @param {function} [eventCallback] Event routing callback. @return {ComponentContext} The component context instance. @constructor
[ "The", "component", "context", "object", "." ]
d7c88a5137342ee2918e2a70aa3c01c1c285aea2
https://github.com/zuixjs/zuix/blob/d7c88a5137342ee2918e2a70aa3c01c1c285aea2/src/js/zuix/ComponentContext.js#L73-L124
20,392
zuixjs/zuix
src/js/zuix/Zuix.js
trigger
function trigger(context, path, data) { if (util.isFunction(_hooksCallbacks[path])) { _hooksCallbacks[path].call(context, data, context); } }
javascript
function trigger(context, path, data) { if (util.isFunction(_hooksCallbacks[path])) { _hooksCallbacks[path].call(context, data, context); } }
[ "function", "trigger", "(", "context", ",", "path", ",", "data", ")", "{", "if", "(", "util", ".", "isFunction", "(", "_hooksCallbacks", "[", "path", "]", ")", ")", "{", "_hooksCallbacks", "[", "path", "]", ".", "call", "(", "context", ",", "data", ",", "context", ")", ";", "}", "}" ]
Fires a zUIx hook. @private @param {object} context @param {string} path @param {object|undefined} data
[ "Fires", "a", "zUIx", "hook", "." ]
d7c88a5137342ee2918e2a70aa3c01c1c285aea2
https://github.com/zuixjs/zuix/blob/d7c88a5137342ee2918e2a70aa3c01c1c285aea2/src/js/zuix/Zuix.js#L484-L488
20,393
zuixjs/zuix
src/js/helpers/Logger.js
Logger
function Logger(ctx) { _console = window ? window.console : {}; _global = window ? window : {}; this._timers = {}; this.args = function(context, level, args) { let logHeader = '%c '+level+' %c'+(new Date().toISOString())+' %c'+context; const colors = [_bc+_c1, _bc+_c2, _bc+_c3]; for (let i = 0; i < args.length; i++) { if (typeof args[i] == 'string' && args[i].indexOf('timer:') === 0) { const t = args[i].split(':'); if (t.length === 3) { let elapsed; switch (t[2]) { case 'start': this._timers[t[1]] = new Date().getTime(); logHeader += ' %cSTART '+t[1]; colors.push(_bc+_c_start); break; case 'stop': elapsed = (new Date().getTime() - this._timers[t[1]]); logHeader += ' %cSTOP '+t[1]+' '+elapsed+' ms'; if (elapsed > 200) { colors.push(_bc+_c_end_very_slow); } else if (elapsed > 100) { colors.push(_bc+_c_end_slow); } else { colors.push(_bc+_c_end); } break; } } } } logHeader += ' \n%c '; colors.push(_bt+'color:inherit;'); // if (typeof args[0] == 'string') { // logHeader += ' %c' + args[0]; // Array.prototype.shift.call(args); // } for (let c = colors.length-1; c >= 0; c--) { Array.prototype.unshift.call(args, colors[c]); } Array.prototype.unshift.call(args, logHeader); Array.prototype.push.call(args, '\n\n'); }; this.log = function(level, args) { if (typeof _callback === 'function') { _callback.call(ctx, level, args); } // route event if (!_global.zuixNoConsoleOutput) { this.args(ctx, level, args); _console.log.apply(_console, args); } }; }
javascript
function Logger(ctx) { _console = window ? window.console : {}; _global = window ? window : {}; this._timers = {}; this.args = function(context, level, args) { let logHeader = '%c '+level+' %c'+(new Date().toISOString())+' %c'+context; const colors = [_bc+_c1, _bc+_c2, _bc+_c3]; for (let i = 0; i < args.length; i++) { if (typeof args[i] == 'string' && args[i].indexOf('timer:') === 0) { const t = args[i].split(':'); if (t.length === 3) { let elapsed; switch (t[2]) { case 'start': this._timers[t[1]] = new Date().getTime(); logHeader += ' %cSTART '+t[1]; colors.push(_bc+_c_start); break; case 'stop': elapsed = (new Date().getTime() - this._timers[t[1]]); logHeader += ' %cSTOP '+t[1]+' '+elapsed+' ms'; if (elapsed > 200) { colors.push(_bc+_c_end_very_slow); } else if (elapsed > 100) { colors.push(_bc+_c_end_slow); } else { colors.push(_bc+_c_end); } break; } } } } logHeader += ' \n%c '; colors.push(_bt+'color:inherit;'); // if (typeof args[0] == 'string') { // logHeader += ' %c' + args[0]; // Array.prototype.shift.call(args); // } for (let c = colors.length-1; c >= 0; c--) { Array.prototype.unshift.call(args, colors[c]); } Array.prototype.unshift.call(args, logHeader); Array.prototype.push.call(args, '\n\n'); }; this.log = function(level, args) { if (typeof _callback === 'function') { _callback.call(ctx, level, args); } // route event if (!_global.zuixNoConsoleOutput) { this.args(ctx, level, args); _console.log.apply(_console, args); } }; }
[ "function", "Logger", "(", "ctx", ")", "{", "_console", "=", "window", "?", "window", ".", "console", ":", "{", "}", ";", "_global", "=", "window", "?", "window", ":", "{", "}", ";", "this", ".", "_timers", "=", "{", "}", ";", "this", ".", "args", "=", "function", "(", "context", ",", "level", ",", "args", ")", "{", "let", "logHeader", "=", "'%c '", "+", "level", "+", "' %c'", "+", "(", "new", "Date", "(", ")", ".", "toISOString", "(", ")", ")", "+", "' %c'", "+", "context", ";", "const", "colors", "=", "[", "_bc", "+", "_c1", ",", "_bc", "+", "_c2", ",", "_bc", "+", "_c3", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "args", ".", "length", ";", "i", "++", ")", "{", "if", "(", "typeof", "args", "[", "i", "]", "==", "'string'", "&&", "args", "[", "i", "]", ".", "indexOf", "(", "'timer:'", ")", "===", "0", ")", "{", "const", "t", "=", "args", "[", "i", "]", ".", "split", "(", "':'", ")", ";", "if", "(", "t", ".", "length", "===", "3", ")", "{", "let", "elapsed", ";", "switch", "(", "t", "[", "2", "]", ")", "{", "case", "'start'", ":", "this", ".", "_timers", "[", "t", "[", "1", "]", "]", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", ";", "logHeader", "+=", "' %cSTART '", "+", "t", "[", "1", "]", ";", "colors", ".", "push", "(", "_bc", "+", "_c_start", ")", ";", "break", ";", "case", "'stop'", ":", "elapsed", "=", "(", "new", "Date", "(", ")", ".", "getTime", "(", ")", "-", "this", ".", "_timers", "[", "t", "[", "1", "]", "]", ")", ";", "logHeader", "+=", "' %cSTOP '", "+", "t", "[", "1", "]", "+", "' '", "+", "elapsed", "+", "' ms'", ";", "if", "(", "elapsed", ">", "200", ")", "{", "colors", ".", "push", "(", "_bc", "+", "_c_end_very_slow", ")", ";", "}", "else", "if", "(", "elapsed", ">", "100", ")", "{", "colors", ".", "push", "(", "_bc", "+", "_c_end_slow", ")", ";", "}", "else", "{", "colors", ".", "push", "(", "_bc", "+", "_c_end", ")", ";", "}", "break", ";", "}", "}", "}", "}", "logHeader", "+=", "' \\n%c '", ";", "colors", ".", "push", "(", "_bt", "+", "'color:inherit;'", ")", ";", "// if (typeof args[0] == 'string') {", "// logHeader += ' %c' + args[0];", "// Array.prototype.shift.call(args);", "// }", "for", "(", "let", "c", "=", "colors", ".", "length", "-", "1", ";", "c", ">=", "0", ";", "c", "--", ")", "{", "Array", ".", "prototype", ".", "unshift", ".", "call", "(", "args", ",", "colors", "[", "c", "]", ")", ";", "}", "Array", ".", "prototype", ".", "unshift", ".", "call", "(", "args", ",", "logHeader", ")", ";", "Array", ".", "prototype", ".", "push", ".", "call", "(", "args", ",", "'\\n\\n'", ")", ";", "}", ";", "this", ".", "log", "=", "function", "(", "level", ",", "args", ")", "{", "if", "(", "typeof", "_callback", "===", "'function'", ")", "{", "_callback", ".", "call", "(", "ctx", ",", "level", ",", "args", ")", ";", "}", "// route event", "if", "(", "!", "_global", ".", "zuixNoConsoleOutput", ")", "{", "this", ".", "args", "(", "ctx", ",", "level", ",", "args", ")", ";", "_console", ".", "log", ".", "apply", "(", "_console", ",", "args", ")", ";", "}", "}", ";", "}" ]
Simple Logging Helper @class Logger @constructor
[ "Simple", "Logging", "Helper" ]
d7c88a5137342ee2918e2a70aa3c01c1c285aea2
https://github.com/zuixjs/zuix/blob/d7c88a5137342ee2918e2a70aa3c01c1c285aea2/src/js/helpers/Logger.js#L54-L108
20,394
zuixjs/zuix
src/js/zuix/Componentizer.js
lazyLoad
function lazyLoad(enable, threshold) { if (enable != null) { _disableLazyLoading = !enable; } if (threshold != null) { _lazyLoadingThreshold = threshold; } return !_isCrawlerBotClient && !_disableLazyLoading; }
javascript
function lazyLoad(enable, threshold) { if (enable != null) { _disableLazyLoading = !enable; } if (threshold != null) { _lazyLoadingThreshold = threshold; } return !_isCrawlerBotClient && !_disableLazyLoading; }
[ "function", "lazyLoad", "(", "enable", ",", "threshold", ")", "{", "if", "(", "enable", "!=", "null", ")", "{", "_disableLazyLoading", "=", "!", "enable", ";", "}", "if", "(", "threshold", "!=", "null", ")", "{", "_lazyLoadingThreshold", "=", "threshold", ";", "}", "return", "!", "_isCrawlerBotClient", "&&", "!", "_disableLazyLoading", ";", "}" ]
Lazy Loading settings. @param {boolean} [enable] Enable or disable lazy loading. @param {number} [threshold] Read ahead tolerance (default is 1.0 => 100% of view size). @return {boolean}
[ "Lazy", "Loading", "settings", "." ]
d7c88a5137342ee2918e2a70aa3c01c1c285aea2
https://github.com/zuixjs/zuix/blob/d7c88a5137342ee2918e2a70aa3c01c1c285aea2/src/js/zuix/Componentizer.js#L196-L204
20,395
greenlikeorange/knayi-myscript
library/normalization.js
applyReplacementRules
function applyReplacementRules(rulesset, content) { return rulesset.reduce((a,b) => { return a.replace(b[0], b[1]); }, content); }
javascript
function applyReplacementRules(rulesset, content) { return rulesset.reduce((a,b) => { return a.replace(b[0], b[1]); }, content); }
[ "function", "applyReplacementRules", "(", "rulesset", ",", "content", ")", "{", "return", "rulesset", ".", "reduce", "(", "(", "a", ",", "b", ")", "=>", "{", "return", "a", ".", "replace", "(", "b", "[", "0", "]", ",", "b", "[", "1", "]", ")", ";", "}", ",", "content", ")", ";", "}" ]
Apply replecement rules
[ "Apply", "replecement", "rules" ]
098dbc1cbeccfdda428e55aa37e04b413dc8619b
https://github.com/greenlikeorange/knayi-myscript/blob/098dbc1cbeccfdda428e55aa37e04b413dc8619b/library/normalization.js#L110-L114
20,396
greenlikeorange/knayi-myscript
library/normalization.js
normalize
function normalize(content) { if (!content) { if (!globalOptions.isSilentMode()) console.warn('Content must be specified on knayi.normalize.'); return ''; } const result = content .replace(/\u200B/g, '') .replace(brakePointRegex, (m, g1, g2) => { let chunk = g1 || ''; // Re-ordering uniquify(g2) .sort((a,b) => rankingMap[a] - rankingMap[b]) .forEach((v) => chunk += v); return applyReplacementRules(extendedRules, chunk); }); return applyReplacementRules(postExtendedRules, result); }
javascript
function normalize(content) { if (!content) { if (!globalOptions.isSilentMode()) console.warn('Content must be specified on knayi.normalize.'); return ''; } const result = content .replace(/\u200B/g, '') .replace(brakePointRegex, (m, g1, g2) => { let chunk = g1 || ''; // Re-ordering uniquify(g2) .sort((a,b) => rankingMap[a] - rankingMap[b]) .forEach((v) => chunk += v); return applyReplacementRules(extendedRules, chunk); }); return applyReplacementRules(postExtendedRules, result); }
[ "function", "normalize", "(", "content", ")", "{", "if", "(", "!", "content", ")", "{", "if", "(", "!", "globalOptions", ".", "isSilentMode", "(", ")", ")", "console", ".", "warn", "(", "'Content must be specified on knayi.normalize.'", ")", ";", "return", "''", ";", "}", "const", "result", "=", "content", ".", "replace", "(", "/", "\\u200B", "/", "g", ",", "''", ")", ".", "replace", "(", "brakePointRegex", ",", "(", "m", ",", "g1", ",", "g2", ")", "=>", "{", "let", "chunk", "=", "g1", "||", "''", ";", "// Re-ordering", "uniquify", "(", "g2", ")", ".", "sort", "(", "(", "a", ",", "b", ")", "=>", "rankingMap", "[", "a", "]", "-", "rankingMap", "[", "b", "]", ")", ".", "forEach", "(", "(", "v", ")", "=>", "chunk", "+=", "v", ")", ";", "return", "applyReplacementRules", "(", "extendedRules", ",", "chunk", ")", ";", "}", ")", ";", "return", "applyReplacementRules", "(", "postExtendedRules", ",", "result", ")", ";", "}" ]
Normalization basically do transforming text into a single canonical form @param {String} content Context to normalize
[ "Normalization", "basically", "do", "transforming", "text", "into", "a", "single", "canonical", "form" ]
098dbc1cbeccfdda428e55aa37e04b413dc8619b
https://github.com/greenlikeorange/knayi-myscript/blob/098dbc1cbeccfdda428e55aa37e04b413dc8619b/library/normalization.js#L120-L140
20,397
greenlikeorange/knayi-myscript
library/spellingCheck.js
spellingFix
function spellingFix(content, fontType){ if (!content) { if (!globalOptions.isSilentMode()) console.warn('Content must be specified on knayi.spellingFix.'); return ''; } if (content === '' || !mmCharacterRange.test(content)) return content; if (!fontType) fontType = fontDetect(content); content = content.trim().replace(/\u200B/g, ''); switch (fontType) { case 'zawgyi': for (var i = 0; i < library.spellingFix.zawgyi.length; i++) { var rule = library.spellingFix.zawgyi[i]; content = content.replace(rule[0], rule[1]); } return content; case 'unicode': default: for (var i = 0; i < library.spellingFix.unicode.length; i++) { var rule = library.spellingFix.unicode[i]; content = content.replace(rule[0], rule[1]); } return content; } }
javascript
function spellingFix(content, fontType){ if (!content) { if (!globalOptions.isSilentMode()) console.warn('Content must be specified on knayi.spellingFix.'); return ''; } if (content === '' || !mmCharacterRange.test(content)) return content; if (!fontType) fontType = fontDetect(content); content = content.trim().replace(/\u200B/g, ''); switch (fontType) { case 'zawgyi': for (var i = 0; i < library.spellingFix.zawgyi.length; i++) { var rule = library.spellingFix.zawgyi[i]; content = content.replace(rule[0], rule[1]); } return content; case 'unicode': default: for (var i = 0; i < library.spellingFix.unicode.length; i++) { var rule = library.spellingFix.unicode[i]; content = content.replace(rule[0], rule[1]); } return content; } }
[ "function", "spellingFix", "(", "content", ",", "fontType", ")", "{", "if", "(", "!", "content", ")", "{", "if", "(", "!", "globalOptions", ".", "isSilentMode", "(", ")", ")", "console", ".", "warn", "(", "'Content must be specified on knayi.spellingFix.'", ")", ";", "return", "''", ";", "}", "if", "(", "content", "===", "''", "||", "!", "mmCharacterRange", ".", "test", "(", "content", ")", ")", "return", "content", ";", "if", "(", "!", "fontType", ")", "fontType", "=", "fontDetect", "(", "content", ")", ";", "content", "=", "content", ".", "trim", "(", ")", ".", "replace", "(", "/", "\\u200B", "/", "g", ",", "''", ")", ";", "switch", "(", "fontType", ")", "{", "case", "'zawgyi'", ":", "for", "(", "var", "i", "=", "0", ";", "i", "<", "library", ".", "spellingFix", ".", "zawgyi", ".", "length", ";", "i", "++", ")", "{", "var", "rule", "=", "library", ".", "spellingFix", ".", "zawgyi", "[", "i", "]", ";", "content", "=", "content", ".", "replace", "(", "rule", "[", "0", "]", ",", "rule", "[", "1", "]", ")", ";", "}", "return", "content", ";", "case", "'unicode'", ":", "default", ":", "for", "(", "var", "i", "=", "0", ";", "i", "<", "library", ".", "spellingFix", ".", "unicode", ".", "length", ";", "i", "++", ")", "{", "var", "rule", "=", "library", ".", "spellingFix", ".", "unicode", "[", "i", "]", ";", "content", "=", "content", ".", "replace", "(", "rule", "[", "0", "]", ",", "rule", "[", "1", "]", ")", ";", "}", "return", "content", ";", "}", "}" ]
Spelling Check agent @param content Text to process @param fontType Type of font of content @return edited text
[ "Spelling", "Check", "agent" ]
098dbc1cbeccfdda428e55aa37e04b413dc8619b
https://github.com/greenlikeorange/knayi-myscript/blob/098dbc1cbeccfdda428e55aa37e04b413dc8619b/library/spellingCheck.js#L26-L55
20,398
greenlikeorange/knayi-myscript
library/detector.js
fontDetect
function fontDetect(content, fallback_font_type, options = {}){ if (!content) { if (!globalOptions.isSilentMode()) console.warn('Content must be specified on knayi.fontDetect.'); return fallback_font_type || 'en'; } if (content === '') return content; if (!mmCharacterRange.test(content)) return fallback_font_type || 'en'; content = content.trim().replace(/\u200B/g, ''); fallback_font_type = fallback_font_type || 'zawgyi'; options = globalOptions.detector(options); if (options.use_myanmartools) { var myanmartools_zg_probability = myanmartoolZawgyiDetector.getZawgyiProbability(content); if (myanmartools_zg_probability < options.myanmartools_zg_threshold[0]) { return 'unicode'; } else if (myanmartools_zg_probability > options.myanmartools_zg_threshold[1]) { return 'zawgyi'; } else { return fallback_font_type; } } else { var match = {}; for (var type in library.detect) { match[type] = 0; for (var i = 0; i < library.detect[type].length; i++) { var rule = library.detect[type][i] var m = content.match(rule); match[type] += (m && m.length) || 0; } } if (match.unicode > match.zawgyi) { return 'unicode'; } else if (match.unicode < match.zawgyi) { return 'zawgyi'; } else { return fallback_font_type; } } }
javascript
function fontDetect(content, fallback_font_type, options = {}){ if (!content) { if (!globalOptions.isSilentMode()) console.warn('Content must be specified on knayi.fontDetect.'); return fallback_font_type || 'en'; } if (content === '') return content; if (!mmCharacterRange.test(content)) return fallback_font_type || 'en'; content = content.trim().replace(/\u200B/g, ''); fallback_font_type = fallback_font_type || 'zawgyi'; options = globalOptions.detector(options); if (options.use_myanmartools) { var myanmartools_zg_probability = myanmartoolZawgyiDetector.getZawgyiProbability(content); if (myanmartools_zg_probability < options.myanmartools_zg_threshold[0]) { return 'unicode'; } else if (myanmartools_zg_probability > options.myanmartools_zg_threshold[1]) { return 'zawgyi'; } else { return fallback_font_type; } } else { var match = {}; for (var type in library.detect) { match[type] = 0; for (var i = 0; i < library.detect[type].length; i++) { var rule = library.detect[type][i] var m = content.match(rule); match[type] += (m && m.length) || 0; } } if (match.unicode > match.zawgyi) { return 'unicode'; } else if (match.unicode < match.zawgyi) { return 'zawgyi'; } else { return fallback_font_type; } } }
[ "function", "fontDetect", "(", "content", ",", "fallback_font_type", ",", "options", "=", "{", "}", ")", "{", "if", "(", "!", "content", ")", "{", "if", "(", "!", "globalOptions", ".", "isSilentMode", "(", ")", ")", "console", ".", "warn", "(", "'Content must be specified on knayi.fontDetect.'", ")", ";", "return", "fallback_font_type", "||", "'en'", ";", "}", "if", "(", "content", "===", "''", ")", "return", "content", ";", "if", "(", "!", "mmCharacterRange", ".", "test", "(", "content", ")", ")", "return", "fallback_font_type", "||", "'en'", ";", "content", "=", "content", ".", "trim", "(", ")", ".", "replace", "(", "/", "\\u200B", "/", "g", ",", "''", ")", ";", "fallback_font_type", "=", "fallback_font_type", "||", "'zawgyi'", ";", "options", "=", "globalOptions", ".", "detector", "(", "options", ")", ";", "if", "(", "options", ".", "use_myanmartools", ")", "{", "var", "myanmartools_zg_probability", "=", "myanmartoolZawgyiDetector", ".", "getZawgyiProbability", "(", "content", ")", ";", "if", "(", "myanmartools_zg_probability", "<", "options", ".", "myanmartools_zg_threshold", "[", "0", "]", ")", "{", "return", "'unicode'", ";", "}", "else", "if", "(", "myanmartools_zg_probability", ">", "options", ".", "myanmartools_zg_threshold", "[", "1", "]", ")", "{", "return", "'zawgyi'", ";", "}", "else", "{", "return", "fallback_font_type", ";", "}", "}", "else", "{", "var", "match", "=", "{", "}", ";", "for", "(", "var", "type", "in", "library", ".", "detect", ")", "{", "match", "[", "type", "]", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "library", ".", "detect", "[", "type", "]", ".", "length", ";", "i", "++", ")", "{", "var", "rule", "=", "library", ".", "detect", "[", "type", "]", "[", "i", "]", "var", "m", "=", "content", ".", "match", "(", "rule", ")", ";", "match", "[", "type", "]", "+=", "(", "m", "&&", "m", ".", "length", ")", "||", "0", ";", "}", "}", "if", "(", "match", ".", "unicode", ">", "match", ".", "zawgyi", ")", "{", "return", "'unicode'", ";", "}", "else", "if", "(", "match", ".", "unicode", "<", "match", ".", "zawgyi", ")", "{", "return", "'zawgyi'", ";", "}", "else", "{", "return", "fallback_font_type", ";", "}", "}", "}" ]
Font Type Detector agent @param content Text to make a detection @param def Default return format; @return unicode ? zawgyi
[ "Font", "Type", "Detector", "agent" ]
098dbc1cbeccfdda428e55aa37e04b413dc8619b
https://github.com/greenlikeorange/knayi-myscript/blob/098dbc1cbeccfdda428e55aa37e04b413dc8619b/library/detector.js#L37-L87
20,399
greenlikeorange/knayi-myscript
library/syllBreak.js
syllBreak
function syllBreak(content, fontType, breakpoint){ if (!content) { if (!globalOptions.isSilentMode()) console.warn('Content must be specified on knayi.syllBreak.'); return ''; } if (content === '' || !mmCharacterRange.test(content)) return content; content = content.trim().replace(/\u200B/g, ''); if (!fontType) fontType = fontDetect(content); var lib = library.syllable[fontType]; for (var i = 0; i < lib.length; i++) { content = content.replace(lib[i][0], lib[i][1]); }; content = content.replace(/^\u200B/, ''); if (breakpoint && breakpoint !== '\u200B') return content.replace(/\u200B/g, breakpoint); return content }
javascript
function syllBreak(content, fontType, breakpoint){ if (!content) { if (!globalOptions.isSilentMode()) console.warn('Content must be specified on knayi.syllBreak.'); return ''; } if (content === '' || !mmCharacterRange.test(content)) return content; content = content.trim().replace(/\u200B/g, ''); if (!fontType) fontType = fontDetect(content); var lib = library.syllable[fontType]; for (var i = 0; i < lib.length; i++) { content = content.replace(lib[i][0], lib[i][1]); }; content = content.replace(/^\u200B/, ''); if (breakpoint && breakpoint !== '\u200B') return content.replace(/\u200B/g, breakpoint); return content }
[ "function", "syllBreak", "(", "content", ",", "fontType", ",", "breakpoint", ")", "{", "if", "(", "!", "content", ")", "{", "if", "(", "!", "globalOptions", ".", "isSilentMode", "(", ")", ")", "console", ".", "warn", "(", "'Content must be specified on knayi.syllBreak.'", ")", ";", "return", "''", ";", "}", "if", "(", "content", "===", "''", "||", "!", "mmCharacterRange", ".", "test", "(", "content", ")", ")", "return", "content", ";", "content", "=", "content", ".", "trim", "(", ")", ".", "replace", "(", "/", "\\u200B", "/", "g", ",", "''", ")", ";", "if", "(", "!", "fontType", ")", "fontType", "=", "fontDetect", "(", "content", ")", ";", "var", "lib", "=", "library", ".", "syllable", "[", "fontType", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "lib", ".", "length", ";", "i", "++", ")", "{", "content", "=", "content", ".", "replace", "(", "lib", "[", "i", "]", "[", "0", "]", ",", "lib", "[", "i", "]", "[", "1", "]", ")", ";", "}", ";", "content", "=", "content", ".", "replace", "(", "/", "^\\u200B", "/", ",", "''", ")", ";", "if", "(", "breakpoint", "&&", "breakpoint", "!==", "'\\u200B'", ")", "return", "content", ".", "replace", "(", "/", "\\u200B", "/", "g", ",", "breakpoint", ")", ";", "return", "content", "}" ]
Syllable-Break agent @param content Text content @param language Language of content 'zawgyi' ? 'my' @param breakpoint Default is '\u200B' @return edited text
[ "Syllable", "-", "Break", "agent" ]
098dbc1cbeccfdda428e55aa37e04b413dc8619b
https://github.com/greenlikeorange/knayi-myscript/blob/098dbc1cbeccfdda428e55aa37e04b413dc8619b/library/syllBreak.js#L36-L62