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
15,400
ezolenko/rollup-plugin-typescript2
dist/rollup-plugin-typescript2.cjs.js
baseDelay
function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function() { func.apply(undefined$1, args); }, wait); }
javascript
function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function() { func.apply(undefined$1, args); }, wait); }
[ "function", "baseDelay", "(", "func", ",", "wait", ",", "args", ")", "{", "if", "(", "typeof", "func", "!=", "'function'", ")", "{", "throw", "new", "TypeError", "(", "FUNC_ERROR_TEXT", ")", ";", "}", "return", "setTimeout", "(", "function", "(", ")", "{", "func", ".", "apply", "(", "undefined$1", ",", "args", ")", ";", "}", ",", "wait", ")", ";", "}" ]
The base implementation of `_.delay` and `_.defer` which accepts `args` to provide to `func`. @private @param {Function} func The function to delay. @param {number} wait The number of milliseconds to delay invocation. @param {Array} args The arguments to provide to `func`. @returns {number|Object} Returns the timer id or timeout object.
[ "The", "base", "implementation", "of", "_", ".", "delay", "and", "_", ".", "defer", "which", "accepts", "args", "to", "provide", "to", "func", "." ]
1fa02cd89ec3664a810342c4e4072496436e8a1d
https://github.com/ezolenko/rollup-plugin-typescript2/blob/1fa02cd89ec3664a810342c4e4072496436e8a1d/dist/rollup-plugin-typescript2.cjs.js#L2768-L2773
15,401
ezolenko/rollup-plugin-typescript2
dist/rollup-plugin-typescript2.cjs.js
baseIntersection
function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined$1; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; }
javascript
function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined$1; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; }
[ "function", "baseIntersection", "(", "arrays", ",", "iteratee", ",", "comparator", ")", "{", "var", "includes", "=", "comparator", "?", "arrayIncludesWith", ":", "arrayIncludes", ",", "length", "=", "arrays", "[", "0", "]", ".", "length", ",", "othLength", "=", "arrays", ".", "length", ",", "othIndex", "=", "othLength", ",", "caches", "=", "Array", "(", "othLength", ")", ",", "maxLength", "=", "Infinity", ",", "result", "=", "[", "]", ";", "while", "(", "othIndex", "--", ")", "{", "var", "array", "=", "arrays", "[", "othIndex", "]", ";", "if", "(", "othIndex", "&&", "iteratee", ")", "{", "array", "=", "arrayMap", "(", "array", ",", "baseUnary", "(", "iteratee", ")", ")", ";", "}", "maxLength", "=", "nativeMin", "(", "array", ".", "length", ",", "maxLength", ")", ";", "caches", "[", "othIndex", "]", "=", "!", "comparator", "&&", "(", "iteratee", "||", "(", "length", ">=", "120", "&&", "array", ".", "length", ">=", "120", ")", ")", "?", "new", "SetCache", "(", "othIndex", "&&", "array", ")", ":", "undefined$1", ";", "}", "array", "=", "arrays", "[", "0", "]", ";", "var", "index", "=", "-", "1", ",", "seen", "=", "caches", "[", "0", "]", ";", "outer", ":", "while", "(", "++", "index", "<", "length", "&&", "result", ".", "length", "<", "maxLength", ")", "{", "var", "value", "=", "array", "[", "index", "]", ",", "computed", "=", "iteratee", "?", "iteratee", "(", "value", ")", ":", "value", ";", "value", "=", "(", "comparator", "||", "value", "!==", "0", ")", "?", "value", ":", "0", ";", "if", "(", "!", "(", "seen", "?", "cacheHas", "(", "seen", ",", "computed", ")", ":", "includes", "(", "result", ",", "computed", ",", "comparator", ")", ")", ")", "{", "othIndex", "=", "othLength", ";", "while", "(", "--", "othIndex", ")", "{", "var", "cache", "=", "caches", "[", "othIndex", "]", ";", "if", "(", "!", "(", "cache", "?", "cacheHas", "(", "cache", ",", "computed", ")", ":", "includes", "(", "arrays", "[", "othIndex", "]", ",", "computed", ",", "comparator", ")", ")", ")", "{", "continue", "outer", ";", "}", "}", "if", "(", "seen", ")", "{", "seen", ".", "push", "(", "computed", ")", ";", "}", "result", ".", "push", "(", "value", ")", ";", "}", "}", "return", "result", ";", "}" ]
The base implementation of methods like `_.intersection`, without support for iteratee shorthands, that accepts an array of arrays to inspect. @private @param {Array} arrays The arrays to inspect. @param {Function} [iteratee] The iteratee invoked per element. @param {Function} [comparator] The comparator invoked per element. @returns {Array} Returns the new array of shared values.
[ "The", "base", "implementation", "of", "methods", "like", "_", ".", "intersection", "without", "support", "for", "iteratee", "shorthands", "that", "accepts", "an", "array", "of", "arrays", "to", "inspect", "." ]
1fa02cd89ec3664a810342c4e4072496436e8a1d
https://github.com/ezolenko/rollup-plugin-typescript2/blob/1fa02cd89ec3664a810342c4e4072496436e8a1d/dist/rollup-plugin-typescript2.cjs.js#L3154-L3205
15,402
ezolenko/rollup-plugin-typescript2
dist/rollup-plugin-typescript2.cjs.js
castSlice
function castSlice(array, start, end) { var length = array.length; end = end === undefined$1 ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); }
javascript
function castSlice(array, start, end) { var length = array.length; end = end === undefined$1 ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); }
[ "function", "castSlice", "(", "array", ",", "start", ",", "end", ")", "{", "var", "length", "=", "array", ".", "length", ";", "end", "=", "end", "===", "undefined$1", "?", "length", ":", "end", ";", "return", "(", "!", "start", "&&", "end", ">=", "length", ")", "?", "array", ":", "baseSlice", "(", "array", ",", "start", ",", "end", ")", ";", "}" ]
Casts `array` to a slice if it's needed. @private @param {Array} array The array to inspect. @param {number} start The start position. @param {number} [end=array.length] The end position. @returns {Array} Returns the cast slice.
[ "Casts", "array", "to", "a", "slice", "if", "it", "s", "needed", "." ]
1fa02cd89ec3664a810342c4e4072496436e8a1d
https://github.com/ezolenko/rollup-plugin-typescript2/blob/1fa02cd89ec3664a810342c4e4072496436e8a1d/dist/rollup-plugin-typescript2.cjs.js#L4504-L4508
15,403
ezolenko/rollup-plugin-typescript2
dist/rollup-plugin-typescript2.cjs.js
createCurry
function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, undefined$1, args, holders, undefined$1, undefined$1, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; }
javascript
function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, undefined$1, args, holders, undefined$1, undefined$1, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; }
[ "function", "createCurry", "(", "func", ",", "bitmask", ",", "arity", ")", "{", "var", "Ctor", "=", "createCtor", "(", "func", ")", ";", "function", "wrapper", "(", ")", "{", "var", "length", "=", "arguments", ".", "length", ",", "args", "=", "Array", "(", "length", ")", ",", "index", "=", "length", ",", "placeholder", "=", "getHolder", "(", "wrapper", ")", ";", "while", "(", "index", "--", ")", "{", "args", "[", "index", "]", "=", "arguments", "[", "index", "]", ";", "}", "var", "holders", "=", "(", "length", "<", "3", "&&", "args", "[", "0", "]", "!==", "placeholder", "&&", "args", "[", "length", "-", "1", "]", "!==", "placeholder", ")", "?", "[", "]", ":", "replaceHolders", "(", "args", ",", "placeholder", ")", ";", "length", "-=", "holders", ".", "length", ";", "if", "(", "length", "<", "arity", ")", "{", "return", "createRecurry", "(", "func", ",", "bitmask", ",", "createHybrid", ",", "wrapper", ".", "placeholder", ",", "undefined$1", ",", "args", ",", "holders", ",", "undefined$1", ",", "undefined$1", ",", "arity", "-", "length", ")", ";", "}", "var", "fn", "=", "(", "this", "&&", "this", "!==", "root", "&&", "this", "instanceof", "wrapper", ")", "?", "Ctor", ":", "func", ";", "return", "apply", "(", "fn", ",", "this", ",", "args", ")", ";", "}", "return", "wrapper", ";", "}" ]
Creates a function that wraps `func` to enable currying. @private @param {Function} func The function to wrap. @param {number} bitmask The bitmask flags. See `createWrap` for more details. @param {number} arity The arity of `func`. @returns {Function} Returns the new wrapped function.
[ "Creates", "a", "function", "that", "wraps", "func", "to", "enable", "currying", "." ]
1fa02cd89ec3664a810342c4e4072496436e8a1d
https://github.com/ezolenko/rollup-plugin-typescript2/blob/1fa02cd89ec3664a810342c4e4072496436e8a1d/dist/rollup-plugin-typescript2.cjs.js#L5038-L5064
15,404
ezolenko/rollup-plugin-typescript2
dist/rollup-plugin-typescript2.cjs.js
createRecurry
function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined$1, newHoldersRight = isCurry ? undefined$1 : holders, newPartials = isCurry ? partials : undefined$1, newPartialsRight = isCurry ? undefined$1 : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined$1, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); }
javascript
function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined$1, newHoldersRight = isCurry ? undefined$1 : holders, newPartials = isCurry ? partials : undefined$1, newPartialsRight = isCurry ? undefined$1 : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined$1, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); }
[ "function", "createRecurry", "(", "func", ",", "bitmask", ",", "wrapFunc", ",", "placeholder", ",", "thisArg", ",", "partials", ",", "holders", ",", "argPos", ",", "ary", ",", "arity", ")", "{", "var", "isCurry", "=", "bitmask", "&", "WRAP_CURRY_FLAG", ",", "newHolders", "=", "isCurry", "?", "holders", ":", "undefined$1", ",", "newHoldersRight", "=", "isCurry", "?", "undefined$1", ":", "holders", ",", "newPartials", "=", "isCurry", "?", "partials", ":", "undefined$1", ",", "newPartialsRight", "=", "isCurry", "?", "undefined$1", ":", "partials", ";", "bitmask", "|=", "(", "isCurry", "?", "WRAP_PARTIAL_FLAG", ":", "WRAP_PARTIAL_RIGHT_FLAG", ")", ";", "bitmask", "&=", "~", "(", "isCurry", "?", "WRAP_PARTIAL_RIGHT_FLAG", ":", "WRAP_PARTIAL_FLAG", ")", ";", "if", "(", "!", "(", "bitmask", "&", "WRAP_CURRY_BOUND_FLAG", ")", ")", "{", "bitmask", "&=", "~", "(", "WRAP_BIND_FLAG", "|", "WRAP_BIND_KEY_FLAG", ")", ";", "}", "var", "newData", "=", "[", "func", ",", "bitmask", ",", "thisArg", ",", "newPartials", ",", "newHolders", ",", "newPartialsRight", ",", "newHoldersRight", ",", "argPos", ",", "ary", ",", "arity", "]", ";", "var", "result", "=", "wrapFunc", ".", "apply", "(", "undefined$1", ",", "newData", ")", ";", "if", "(", "isLaziable", "(", "func", ")", ")", "{", "setData", "(", "result", ",", "newData", ")", ";", "}", "result", ".", "placeholder", "=", "placeholder", ";", "return", "setWrapToString", "(", "result", ",", "func", ",", "bitmask", ")", ";", "}" ]
Creates a function that wraps `func` to continue currying. @private @param {Function} func The function to wrap. @param {number} bitmask The bitmask flags. See `createWrap` for more details. @param {Function} wrapFunc The function to create the `func` wrapper. @param {*} placeholder The placeholder value. @param {*} [thisArg] The `this` binding of `func`. @param {Array} [partials] The arguments to prepend to those provided to the new function. @param {Array} [holders] The `partials` placeholder indexes. @param {Array} [argPos] The argument positions of the new function. @param {number} [ary] The arity cap of `func`. @param {number} [arity] The arity of `func`. @returns {Function} Returns the new wrapped function.
[ "Creates", "a", "function", "that", "wraps", "func", "to", "continue", "currying", "." ]
1fa02cd89ec3664a810342c4e4072496436e8a1d
https://github.com/ezolenko/rollup-plugin-typescript2/blob/1fa02cd89ec3664a810342c4e4072496436e8a1d/dist/rollup-plugin-typescript2.cjs.js#L5403-L5427
15,405
ezolenko/rollup-plugin-typescript2
dist/rollup-plugin-typescript2.cjs.js
shuffleSelf
function shuffleSelf(array, size) { var index = -1, length = array.length, lastIndex = length - 1; size = size === undefined$1 ? length : size; while (++index < size) { var rand = baseRandom(index, lastIndex), value = array[rand]; array[rand] = array[index]; array[index] = value; } array.length = size; return array; }
javascript
function shuffleSelf(array, size) { var index = -1, length = array.length, lastIndex = length - 1; size = size === undefined$1 ? length : size; while (++index < size) { var rand = baseRandom(index, lastIndex), value = array[rand]; array[rand] = array[index]; array[index] = value; } array.length = size; return array; }
[ "function", "shuffleSelf", "(", "array", ",", "size", ")", "{", "var", "index", "=", "-", "1", ",", "length", "=", "array", ".", "length", ",", "lastIndex", "=", "length", "-", "1", ";", "size", "=", "size", "===", "undefined$1", "?", "length", ":", "size", ";", "while", "(", "++", "index", "<", "size", ")", "{", "var", "rand", "=", "baseRandom", "(", "index", ",", "lastIndex", ")", ",", "value", "=", "array", "[", "rand", "]", ";", "array", "[", "rand", "]", "=", "array", "[", "index", "]", ";", "array", "[", "index", "]", "=", "value", ";", "}", "array", ".", "length", "=", "size", ";", "return", "array", ";", "}" ]
A specialized version of `_.shuffle` which mutates and sets the size of `array`. @private @param {Array} array The array to shuffle. @param {number} [size=array.length] The size of `array`. @returns {Array} Returns `array`.
[ "A", "specialized", "version", "of", "_", ".", "shuffle", "which", "mutates", "and", "sets", "the", "size", "of", "array", "." ]
1fa02cd89ec3664a810342c4e4072496436e8a1d
https://github.com/ezolenko/rollup-plugin-typescript2/blob/1fa02cd89ec3664a810342c4e4072496436e8a1d/dist/rollup-plugin-typescript2.cjs.js#L6729-L6744
15,406
ezolenko/rollup-plugin-typescript2
dist/rollup-plugin-typescript2.cjs.js
last
function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined$1; }
javascript
function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined$1; }
[ "function", "last", "(", "array", ")", "{", "var", "length", "=", "array", "==", "null", "?", "0", ":", "array", ".", "length", ";", "return", "length", "?", "array", "[", "length", "-", "1", "]", ":", "undefined$1", ";", "}" ]
Gets the last element of `array`. @static @memberOf _ @since 0.1.0 @category Array @param {Array} array The array to query. @returns {*} Returns the last element of `array`. @example _.last([1, 2, 3]); // => 3
[ "Gets", "the", "last", "element", "of", "array", "." ]
1fa02cd89ec3664a810342c4e4072496436e8a1d
https://github.com/ezolenko/rollup-plugin-typescript2/blob/1fa02cd89ec3664a810342c4e4072496436e8a1d/dist/rollup-plugin-typescript2.cjs.js#L7627-L7630
15,407
ezolenko/rollup-plugin-typescript2
dist/rollup-plugin-typescript2.cjs.js
take
function take(array, n, guard) { if (!(array && array.length)) { return []; } n = (guard || n === undefined$1) ? 1 : toInteger(n); return baseSlice(array, 0, n < 0 ? 0 : n); }
javascript
function take(array, n, guard) { if (!(array && array.length)) { return []; } n = (guard || n === undefined$1) ? 1 : toInteger(n); return baseSlice(array, 0, n < 0 ? 0 : n); }
[ "function", "take", "(", "array", ",", "n", ",", "guard", ")", "{", "if", "(", "!", "(", "array", "&&", "array", ".", "length", ")", ")", "{", "return", "[", "]", ";", "}", "n", "=", "(", "guard", "||", "n", "===", "undefined$1", ")", "?", "1", ":", "toInteger", "(", "n", ")", ";", "return", "baseSlice", "(", "array", ",", "0", ",", "n", "<", "0", "?", "0", ":", "n", ")", ";", "}" ]
Creates a slice of `array` with `n` elements taken from the beginning. @static @memberOf _ @since 0.1.0 @category Array @param {Array} array The array to query. @param {number} [n=1] The number of elements to take. @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. @returns {Array} Returns the slice of `array`. @example _.take([1, 2, 3]); // => [1] _.take([1, 2, 3], 2); // => [1, 2] _.take([1, 2, 3], 5); // => [1, 2, 3] _.take([1, 2, 3], 0); // => []
[ "Creates", "a", "slice", "of", "array", "with", "n", "elements", "taken", "from", "the", "beginning", "." ]
1fa02cd89ec3664a810342c4e4072496436e8a1d
https://github.com/ezolenko/rollup-plugin-typescript2/blob/1fa02cd89ec3664a810342c4e4072496436e8a1d/dist/rollup-plugin-typescript2.cjs.js#L8187-L8193
15,408
ezolenko/rollup-plugin-typescript2
dist/rollup-plugin-typescript2.cjs.js
template
function template(string, options, guard) { // Based on John Resig's `tmpl` implementation // (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). var settings = lodash.templateSettings; if (guard && isIterateeCall(string, options, guard)) { options = undefined$1; } string = toString(string); options = assignInWith({}, options, settings, customDefaultsAssignIn); var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; // Compile the regexp to match each delimiter. var reDelimiters = RegExp( (options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$' , 'g'); // Use a sourceURL for easier debugging. var sourceURL = '//# sourceURL=' + ('sourceURL' in options ? options.sourceURL : ('lodash.templateSources[' + (++templateCounter) + ']') ) + '\n'; string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); // Escape characters that can't be included in string literals. source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source += "' +\n__e(" + escapeValue + ") +\n'"; } if (evaluateValue) { isEvaluating = true; source += "';\n" + evaluateValue + ";\n__p += '"; } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } index = offset + match.length; // The JS engine embedded in Adobe products needs `match` returned in // order to produce the correct `offset` value. return match; }); source += "';\n"; // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. var variable = options.variable; if (!variable) { source = 'with (obj) {\n' + source + '\n}\n'; } // Cleanup code by stripping empty strings. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) .replace(reEmptyStringMiddle, '$1') .replace(reEmptyStringTrailing, '$1;'); // Frame code as the function body. source = 'function(' + (variable || 'obj') + ') {\n' + (variable ? '' : 'obj || (obj = {});\n' ) + "var __t, __p = ''" + (isEscaping ? ', __e = _.escape' : '' ) + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n' ) + source + 'return __p\n}'; var result = attempt(function() { return Function(importsKeys, sourceURL + 'return ' + source) .apply(undefined$1, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; }
javascript
function template(string, options, guard) { // Based on John Resig's `tmpl` implementation // (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). var settings = lodash.templateSettings; if (guard && isIterateeCall(string, options, guard)) { options = undefined$1; } string = toString(string); options = assignInWith({}, options, settings, customDefaultsAssignIn); var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; // Compile the regexp to match each delimiter. var reDelimiters = RegExp( (options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$' , 'g'); // Use a sourceURL for easier debugging. var sourceURL = '//# sourceURL=' + ('sourceURL' in options ? options.sourceURL : ('lodash.templateSources[' + (++templateCounter) + ']') ) + '\n'; string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); // Escape characters that can't be included in string literals. source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source += "' +\n__e(" + escapeValue + ") +\n'"; } if (evaluateValue) { isEvaluating = true; source += "';\n" + evaluateValue + ";\n__p += '"; } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } index = offset + match.length; // The JS engine embedded in Adobe products needs `match` returned in // order to produce the correct `offset` value. return match; }); source += "';\n"; // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. var variable = options.variable; if (!variable) { source = 'with (obj) {\n' + source + '\n}\n'; } // Cleanup code by stripping empty strings. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) .replace(reEmptyStringMiddle, '$1') .replace(reEmptyStringTrailing, '$1;'); // Frame code as the function body. source = 'function(' + (variable || 'obj') + ') {\n' + (variable ? '' : 'obj || (obj = {});\n' ) + "var __t, __p = ''" + (isEscaping ? ', __e = _.escape' : '' ) + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n' ) + source + 'return __p\n}'; var result = attempt(function() { return Function(importsKeys, sourceURL + 'return ' + source) .apply(undefined$1, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; }
[ "function", "template", "(", "string", ",", "options", ",", "guard", ")", "{", "// Based on John Resig's `tmpl` implementation", "// (http://ejohn.org/blog/javascript-micro-templating/)", "// and Laura Doktorova's doT.js (https://github.com/olado/doT).", "var", "settings", "=", "lodash", ".", "templateSettings", ";", "if", "(", "guard", "&&", "isIterateeCall", "(", "string", ",", "options", ",", "guard", ")", ")", "{", "options", "=", "undefined$1", ";", "}", "string", "=", "toString", "(", "string", ")", ";", "options", "=", "assignInWith", "(", "{", "}", ",", "options", ",", "settings", ",", "customDefaultsAssignIn", ")", ";", "var", "imports", "=", "assignInWith", "(", "{", "}", ",", "options", ".", "imports", ",", "settings", ".", "imports", ",", "customDefaultsAssignIn", ")", ",", "importsKeys", "=", "keys", "(", "imports", ")", ",", "importsValues", "=", "baseValues", "(", "imports", ",", "importsKeys", ")", ";", "var", "isEscaping", ",", "isEvaluating", ",", "index", "=", "0", ",", "interpolate", "=", "options", ".", "interpolate", "||", "reNoMatch", ",", "source", "=", "\"__p += '\"", ";", "// Compile the regexp to match each delimiter.", "var", "reDelimiters", "=", "RegExp", "(", "(", "options", ".", "escape", "||", "reNoMatch", ")", ".", "source", "+", "'|'", "+", "interpolate", ".", "source", "+", "'|'", "+", "(", "interpolate", "===", "reInterpolate", "?", "reEsTemplate", ":", "reNoMatch", ")", ".", "source", "+", "'|'", "+", "(", "options", ".", "evaluate", "||", "reNoMatch", ")", ".", "source", "+", "'|$'", ",", "'g'", ")", ";", "// Use a sourceURL for easier debugging.", "var", "sourceURL", "=", "'//# sourceURL='", "+", "(", "'sourceURL'", "in", "options", "?", "options", ".", "sourceURL", ":", "(", "'lodash.templateSources['", "+", "(", "++", "templateCounter", ")", "+", "']'", ")", ")", "+", "'\\n'", ";", "string", ".", "replace", "(", "reDelimiters", ",", "function", "(", "match", ",", "escapeValue", ",", "interpolateValue", ",", "esTemplateValue", ",", "evaluateValue", ",", "offset", ")", "{", "interpolateValue", "||", "(", "interpolateValue", "=", "esTemplateValue", ")", ";", "// Escape characters that can't be included in string literals.", "source", "+=", "string", ".", "slice", "(", "index", ",", "offset", ")", ".", "replace", "(", "reUnescapedString", ",", "escapeStringChar", ")", ";", "// Replace delimiters with snippets.", "if", "(", "escapeValue", ")", "{", "isEscaping", "=", "true", ";", "source", "+=", "\"' +\\n__e(\"", "+", "escapeValue", "+", "\") +\\n'\"", ";", "}", "if", "(", "evaluateValue", ")", "{", "isEvaluating", "=", "true", ";", "source", "+=", "\"';\\n\"", "+", "evaluateValue", "+", "\";\\n__p += '\"", ";", "}", "if", "(", "interpolateValue", ")", "{", "source", "+=", "\"' +\\n((__t = (\"", "+", "interpolateValue", "+", "\")) == null ? '' : __t) +\\n'\"", ";", "}", "index", "=", "offset", "+", "match", ".", "length", ";", "// The JS engine embedded in Adobe products needs `match` returned in", "// order to produce the correct `offset` value.", "return", "match", ";", "}", ")", ";", "source", "+=", "\"';\\n\"", ";", "// If `variable` is not specified wrap a with-statement around the generated", "// code to add the data object to the top of the scope chain.", "var", "variable", "=", "options", ".", "variable", ";", "if", "(", "!", "variable", ")", "{", "source", "=", "'with (obj) {\\n'", "+", "source", "+", "'\\n}\\n'", ";", "}", "// Cleanup code by stripping empty strings.", "source", "=", "(", "isEvaluating", "?", "source", ".", "replace", "(", "reEmptyStringLeading", ",", "''", ")", ":", "source", ")", ".", "replace", "(", "reEmptyStringMiddle", ",", "'$1'", ")", ".", "replace", "(", "reEmptyStringTrailing", ",", "'$1;'", ")", ";", "// Frame code as the function body.", "source", "=", "'function('", "+", "(", "variable", "||", "'obj'", ")", "+", "') {\\n'", "+", "(", "variable", "?", "''", ":", "'obj || (obj = {});\\n'", ")", "+", "\"var __t, __p = ''\"", "+", "(", "isEscaping", "?", "', __e = _.escape'", ":", "''", ")", "+", "(", "isEvaluating", "?", "', __j = Array.prototype.join;\\n'", "+", "\"function print() { __p += __j.call(arguments, '') }\\n\"", ":", "';\\n'", ")", "+", "source", "+", "'return __p\\n}'", ";", "var", "result", "=", "attempt", "(", "function", "(", ")", "{", "return", "Function", "(", "importsKeys", ",", "sourceURL", "+", "'return '", "+", "source", ")", ".", "apply", "(", "undefined$1", ",", "importsValues", ")", ";", "}", ")", ";", "// Provide the compiled function's source by its `toString` method or", "// the `source` property as a convenience for inlining compiled templates.", "result", ".", "source", "=", "source", ";", "if", "(", "isError", "(", "result", ")", ")", "{", "throw", "result", ";", "}", "return", "result", ";", "}" ]
Creates a compiled template function that can interpolate data properties in "interpolate" delimiters, HTML-escape interpolated data properties in "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data properties may be accessed as free variables in the template. If a setting object is given, it takes precedence over `_.templateSettings` values. **Note:** In the development build `_.template` utilizes [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) for easier debugging. For more information on precompiling templates see [lodash's custom builds documentation](https://lodash.com/custom-builds). For more information on Chrome extension sandboxes see [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). @static @since 0.1.0 @memberOf _ @category String @param {string} [string=''] The template string. @param {Object} [options={}] The options object. @param {RegExp} [options.escape=_.templateSettings.escape] The HTML "escape" delimiter. @param {RegExp} [options.evaluate=_.templateSettings.evaluate] The "evaluate" delimiter. @param {Object} [options.imports=_.templateSettings.imports] An object to import into the template as free variables. @param {RegExp} [options.interpolate=_.templateSettings.interpolate] The "interpolate" delimiter. @param {string} [options.sourceURL='lodash.templateSources[n]'] The sourceURL of the compiled template. @param {string} [options.variable='obj'] The data object variable name. @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. @returns {Function} Returns the compiled template function. @example // Use the "interpolate" delimiter to create a compiled template. var compiled = _.template('hello <%= user %>!'); compiled({ 'user': 'fred' }); // => 'hello fred!' // Use the HTML "escape" delimiter to escape data property values. var compiled = _.template('<b><%- value %></b>'); compiled({ 'value': '<script>' }); // => '<b>&lt;script&gt;</b>' // Use the "evaluate" delimiter to execute JavaScript and generate HTML. var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>'); compiled({ 'users': ['fred', 'barney'] }); // => '<li>fred</li><li>barney</li>' // Use the internal `print` function in "evaluate" delimiters. var compiled = _.template('<% print("hello " + user); %>!'); compiled({ 'user': 'barney' }); // => 'hello barney!' // Use the ES template literal delimiter as an "interpolate" delimiter. // Disable support by replacing the "interpolate" delimiter. var compiled = _.template('hello ${ user }!'); compiled({ 'user': 'pebbles' }); // => 'hello pebbles!' // Use backslashes to treat delimiters as plain text. var compiled = _.template('<%= "\\<%- value %\\>" %>'); compiled({ 'value': 'ignored' }); // => '<%- value %>' // Use the `imports` option to import `jQuery` as `jq`. var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>'; var compiled = _.template(text, { 'imports': { 'jq': jQuery } }); compiled({ 'users': ['fred', 'barney'] }); // => '<li>fred</li><li>barney</li>' // Use the `sourceURL` option to specify a custom sourceURL for the template. var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' }); compiled(data); // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector. // Use the `variable` option to ensure a with-statement isn't used in the compiled template. var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' }); compiled.source; // => function(data) { // var __t, __p = ''; // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!'; // return __p; // } // Use custom template delimiters. _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; var compiled = _.template('hello {{ user }}!'); compiled({ 'user': 'mustache' }); // => 'hello mustache!' // Use the `source` property to inline compiled templates for meaningful // line numbers in error messages and stack traces. fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\ var JST = {\ "main": ' + _.template(mainText).source + '\ };\ ');
[ "Creates", "a", "compiled", "template", "function", "that", "can", "interpolate", "data", "properties", "in", "interpolate", "delimiters", "HTML", "-", "escape", "interpolated", "data", "properties", "in", "escape", "delimiters", "and", "execute", "JavaScript", "in", "evaluate", "delimiters", ".", "Data", "properties", "may", "be", "accessed", "as", "free", "variables", "in", "the", "template", ".", "If", "a", "setting", "object", "is", "given", "it", "takes", "precedence", "over", "_", ".", "templateSettings", "values", "." ]
1fa02cd89ec3664a810342c4e4072496436e8a1d
https://github.com/ezolenko/rollup-plugin-typescript2/blob/1fa02cd89ec3664a810342c4e4072496436e8a1d/dist/rollup-plugin-typescript2.cjs.js#L14787-L14893
15,409
ezolenko/rollup-plugin-typescript2
dist/rollup-plugin-typescript2.cjs.js
baseKeys
function baseKeys(object) { if (!_isPrototype(object)) { return _nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty$7.call(object, key) && key != 'constructor') { result.push(key); } } return result; }
javascript
function baseKeys(object) { if (!_isPrototype(object)) { return _nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty$7.call(object, key) && key != 'constructor') { result.push(key); } } return result; }
[ "function", "baseKeys", "(", "object", ")", "{", "if", "(", "!", "_isPrototype", "(", "object", ")", ")", "{", "return", "_nativeKeys", "(", "object", ")", ";", "}", "var", "result", "=", "[", "]", ";", "for", "(", "var", "key", "in", "Object", "(", "object", ")", ")", "{", "if", "(", "hasOwnProperty$7", ".", "call", "(", "object", ",", "key", ")", "&&", "key", "!=", "'constructor'", ")", "{", "result", ".", "push", "(", "key", ")", ";", "}", "}", "return", "result", ";", "}" ]
The base implementation of `_.keys` which doesn't treat sparse arrays as dense. @private @param {Object} object The object to query. @returns {Array} Returns the array of property names.
[ "The", "base", "implementation", "of", "_", ".", "keys", "which", "doesn", "t", "treat", "sparse", "arrays", "as", "dense", "." ]
1fa02cd89ec3664a810342c4e4072496436e8a1d
https://github.com/ezolenko/rollup-plugin-typescript2/blob/1fa02cd89ec3664a810342c4e4072496436e8a1d/dist/rollup-plugin-typescript2.cjs.js#L18793-L18804
15,410
ezolenko/rollup-plugin-typescript2
dist/rollup-plugin-typescript2.cjs.js
baseFilter
function baseFilter(collection, predicate) { var result = []; _baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; }
javascript
function baseFilter(collection, predicate) { var result = []; _baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; }
[ "function", "baseFilter", "(", "collection", ",", "predicate", ")", "{", "var", "result", "=", "[", "]", ";", "_baseEach", "(", "collection", ",", "function", "(", "value", ",", "index", ",", "collection", ")", "{", "if", "(", "predicate", "(", "value", ",", "index", ",", "collection", ")", ")", "{", "result", ".", "push", "(", "value", ")", ";", "}", "}", ")", ";", "return", "result", ";", "}" ]
The base implementation of `_.filter` without support for iteratee shorthands. @private @param {Array|Object} collection The collection to iterate over. @param {Function} predicate The function invoked per iteration. @returns {Array} Returns the new filtered array.
[ "The", "base", "implementation", "of", "_", ".", "filter", "without", "support", "for", "iteratee", "shorthands", "." ]
1fa02cd89ec3664a810342c4e4072496436e8a1d
https://github.com/ezolenko/rollup-plugin-typescript2/blob/1fa02cd89ec3664a810342c4e4072496436e8a1d/dist/rollup-plugin-typescript2.cjs.js#L20009-L20017
15,411
ezolenko/rollup-plugin-typescript2
dist/rollup-plugin-typescript2.cjs.js
baseIsEqual
function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) { return value !== value && other !== other; } return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); }
javascript
function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) { return value !== value && other !== other; } return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); }
[ "function", "baseIsEqual", "(", "value", ",", "other", ",", "bitmask", ",", "customizer", ",", "stack", ")", "{", "if", "(", "value", "===", "other", ")", "{", "return", "true", ";", "}", "if", "(", "value", "==", "null", "||", "other", "==", "null", "||", "(", "!", "isObjectLike_1", "(", "value", ")", "&&", "!", "isObjectLike_1", "(", "other", ")", ")", ")", "{", "return", "value", "!==", "value", "&&", "other", "!==", "other", ";", "}", "return", "_baseIsEqualDeep", "(", "value", ",", "other", ",", "bitmask", ",", "customizer", ",", "baseIsEqual", ",", "stack", ")", ";", "}" ]
The base implementation of `_.isEqual` which supports partial comparisons and tracks traversed objects. @private @param {*} value The value to compare. @param {*} other The other value to compare. @param {boolean} bitmask The bitmask flags. 1 - Unordered comparison 2 - Partial comparison @param {Function} [customizer] The function to customize comparisons. @param {Object} [stack] Tracks traversed `value` and `other` objects. @returns {boolean} Returns `true` if the values are equivalent, else `false`.
[ "The", "base", "implementation", "of", "_", ".", "isEqual", "which", "supports", "partial", "comparisons", "and", "tracks", "traversed", "objects", "." ]
1fa02cd89ec3664a810342c4e4072496436e8a1d
https://github.com/ezolenko/rollup-plugin-typescript2/blob/1fa02cd89ec3664a810342c4e4072496436e8a1d/dist/rollup-plugin-typescript2.cjs.js#L20519-L20527
15,412
ezolenko/rollup-plugin-typescript2
dist/rollup-plugin-typescript2.cjs.js
baseUniq
function baseUniq(array, iteratee, comparator) { var index = -1, includes = _arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = _arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE$1) { var set = iteratee ? null : _createSet(array); if (set) { return _setToArray(set); } isCommon = false; includes = _cacheHas; seen = new _SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; }
javascript
function baseUniq(array, iteratee, comparator) { var index = -1, includes = _arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = _arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE$1) { var set = iteratee ? null : _createSet(array); if (set) { return _setToArray(set); } isCommon = false; includes = _cacheHas; seen = new _SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; }
[ "function", "baseUniq", "(", "array", ",", "iteratee", ",", "comparator", ")", "{", "var", "index", "=", "-", "1", ",", "includes", "=", "_arrayIncludes", ",", "length", "=", "array", ".", "length", ",", "isCommon", "=", "true", ",", "result", "=", "[", "]", ",", "seen", "=", "result", ";", "if", "(", "comparator", ")", "{", "isCommon", "=", "false", ";", "includes", "=", "_arrayIncludesWith", ";", "}", "else", "if", "(", "length", ">=", "LARGE_ARRAY_SIZE$1", ")", "{", "var", "set", "=", "iteratee", "?", "null", ":", "_createSet", "(", "array", ")", ";", "if", "(", "set", ")", "{", "return", "_setToArray", "(", "set", ")", ";", "}", "isCommon", "=", "false", ";", "includes", "=", "_cacheHas", ";", "seen", "=", "new", "_SetCache", ";", "}", "else", "{", "seen", "=", "iteratee", "?", "[", "]", ":", "result", ";", "}", "outer", ":", "while", "(", "++", "index", "<", "length", ")", "{", "var", "value", "=", "array", "[", "index", "]", ",", "computed", "=", "iteratee", "?", "iteratee", "(", "value", ")", ":", "value", ";", "value", "=", "(", "comparator", "||", "value", "!==", "0", ")", "?", "value", ":", "0", ";", "if", "(", "isCommon", "&&", "computed", "===", "computed", ")", "{", "var", "seenIndex", "=", "seen", ".", "length", ";", "while", "(", "seenIndex", "--", ")", "{", "if", "(", "seen", "[", "seenIndex", "]", "===", "computed", ")", "{", "continue", "outer", ";", "}", "}", "if", "(", "iteratee", ")", "{", "seen", ".", "push", "(", "computed", ")", ";", "}", "result", ".", "push", "(", "value", ")", ";", "}", "else", "if", "(", "!", "includes", "(", "seen", ",", "computed", ",", "comparator", ")", ")", "{", "if", "(", "seen", "!==", "result", ")", "{", "seen", ".", "push", "(", "computed", ")", ";", "}", "result", ".", "push", "(", "value", ")", ";", "}", "}", "return", "result", ";", "}" ]
The base implementation of `_.uniqBy` without support for iteratee shorthands. @private @param {Array} array The array to inspect. @param {Function} [iteratee] The iteratee invoked per element. @param {Function} [comparator] The comparator invoked per element. @returns {Array} Returns the new duplicate free array.
[ "The", "base", "implementation", "of", "_", ".", "uniqBy", "without", "support", "for", "iteratee", "shorthands", "." ]
1fa02cd89ec3664a810342c4e4072496436e8a1d
https://github.com/ezolenko/rollup-plugin-typescript2/blob/1fa02cd89ec3664a810342c4e4072496436e8a1d/dist/rollup-plugin-typescript2.cjs.js#L22139-L22189
15,413
jansepar/node-jenkins-api
src/main.js
function (specificOptions, customParams, callback) { // Options - Default values const options = Object.assign({}, { urlPattern: ['/'], method: 'GET', successStatusCodes: [HTTP_CODE_200], failureStatusCodes: [], bodyProp: null, noparse: false, request: {} }, defaultOptions, specificOptions); // Create the url const url = buildUrl(options.urlPattern, customParams); // Build the actual request options const requestOptions = Object.assign({ method: options.method, url: url, headers: [], followAllRedirects: true, form: null, body: null }, options.request); // Do the request request(requestOptions, function (error, response, body) { if (error) { callback(error, response); return; } if ((Array.isArray(options.successStatusCodes) && !options.successStatusCodes.includes(response.statusCode)) || (Array.isArray(options.failureStatusCodes) && options.failureStatusCodes.includes(response.statusCode))) { callback(`Server returned unexpected status code: ${response.statusCode}`, response); return; } if (options.noparse) { // Wrap body in the response object if (typeof body === 'string') { body = { body: body }; } // Add location const location = response.headers.Location || response.headers.location; if (location) { body.location = location; } // Add status code body.statusCode = response.statusCode; callback(null, body); } else { tryParseJson(body, options.bodyProp, callback); } }); }
javascript
function (specificOptions, customParams, callback) { // Options - Default values const options = Object.assign({}, { urlPattern: ['/'], method: 'GET', successStatusCodes: [HTTP_CODE_200], failureStatusCodes: [], bodyProp: null, noparse: false, request: {} }, defaultOptions, specificOptions); // Create the url const url = buildUrl(options.urlPattern, customParams); // Build the actual request options const requestOptions = Object.assign({ method: options.method, url: url, headers: [], followAllRedirects: true, form: null, body: null }, options.request); // Do the request request(requestOptions, function (error, response, body) { if (error) { callback(error, response); return; } if ((Array.isArray(options.successStatusCodes) && !options.successStatusCodes.includes(response.statusCode)) || (Array.isArray(options.failureStatusCodes) && options.failureStatusCodes.includes(response.statusCode))) { callback(`Server returned unexpected status code: ${response.statusCode}`, response); return; } if (options.noparse) { // Wrap body in the response object if (typeof body === 'string') { body = { body: body }; } // Add location const location = response.headers.Location || response.headers.location; if (location) { body.location = location; } // Add status code body.statusCode = response.statusCode; callback(null, body); } else { tryParseJson(body, options.bodyProp, callback); } }); }
[ "function", "(", "specificOptions", ",", "customParams", ",", "callback", ")", "{", "// Options - Default values", "const", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "{", "urlPattern", ":", "[", "'/'", "]", ",", "method", ":", "'GET'", ",", "successStatusCodes", ":", "[", "HTTP_CODE_200", "]", ",", "failureStatusCodes", ":", "[", "]", ",", "bodyProp", ":", "null", ",", "noparse", ":", "false", ",", "request", ":", "{", "}", "}", ",", "defaultOptions", ",", "specificOptions", ")", ";", "// Create the url", "const", "url", "=", "buildUrl", "(", "options", ".", "urlPattern", ",", "customParams", ")", ";", "// Build the actual request options", "const", "requestOptions", "=", "Object", ".", "assign", "(", "{", "method", ":", "options", ".", "method", ",", "url", ":", "url", ",", "headers", ":", "[", "]", ",", "followAllRedirects", ":", "true", ",", "form", ":", "null", ",", "body", ":", "null", "}", ",", "options", ".", "request", ")", ";", "// Do the request", "request", "(", "requestOptions", ",", "function", "(", "error", ",", "response", ",", "body", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ",", "response", ")", ";", "return", ";", "}", "if", "(", "(", "Array", ".", "isArray", "(", "options", ".", "successStatusCodes", ")", "&&", "!", "options", ".", "successStatusCodes", ".", "includes", "(", "response", ".", "statusCode", ")", ")", "||", "(", "Array", ".", "isArray", "(", "options", ".", "failureStatusCodes", ")", "&&", "options", ".", "failureStatusCodes", ".", "includes", "(", "response", ".", "statusCode", ")", ")", ")", "{", "callback", "(", "`", "${", "response", ".", "statusCode", "}", "`", ",", "response", ")", ";", "return", ";", "}", "if", "(", "options", ".", "noparse", ")", "{", "// Wrap body in the response object", "if", "(", "typeof", "body", "===", "'string'", ")", "{", "body", "=", "{", "body", ":", "body", "}", ";", "}", "// Add location", "const", "location", "=", "response", ".", "headers", ".", "Location", "||", "response", ".", "headers", ".", "location", ";", "if", "(", "location", ")", "{", "body", ".", "location", "=", "location", ";", "}", "// Add status code", "body", ".", "statusCode", "=", "response", ".", "statusCode", ";", "callback", "(", "null", ",", "body", ")", ";", "}", "else", "{", "tryParseJson", "(", "body", ",", "options", ".", "bodyProp", ",", "callback", ")", ";", "}", "}", ")", ";", "}" ]
Run the actual HTTP request. @param {object} specificOptions - options object overriding the default options below. @param {object} customParams - custom url params to be added to url. @param {function} callback - the callback function to be called when request is finished.
[ "Run", "the", "actual", "HTTP", "request", "." ]
1f1ac16a6055bc162c7ecfdee286c2a458a1e19b
https://github.com/jansepar/node-jenkins-api/blob/1f1ac16a6055bc162c7ecfdee286c2a458a1e19b/src/main.js#L238-L298
15,414
jansepar/node-jenkins-api
src/main.js
function (jobName, jobConfig, customParams, callback) { [jobName, jobConfig, customParams, callback] = doArgs(arguments, ['string', 'string', ['object', {}], 'function']); // Set the created job name! customParams.name = jobName; const self = this; doRequest({ method: 'POST', urlPattern: [JOB_CREATE], request: { body: jobConfig, headers: { 'Content-Type': 'application/xml' } }, noparse: true }, customParams, function (error, data) { if (error) { callback(error, data); return; } self.job_info(jobName, customParams, callback); }); }
javascript
function (jobName, jobConfig, customParams, callback) { [jobName, jobConfig, customParams, callback] = doArgs(arguments, ['string', 'string', ['object', {}], 'function']); // Set the created job name! customParams.name = jobName; const self = this; doRequest({ method: 'POST', urlPattern: [JOB_CREATE], request: { body: jobConfig, headers: { 'Content-Type': 'application/xml' } }, noparse: true }, customParams, function (error, data) { if (error) { callback(error, data); return; } self.job_info(jobName, customParams, callback); }); }
[ "function", "(", "jobName", ",", "jobConfig", ",", "customParams", ",", "callback", ")", "{", "[", "jobName", ",", "jobConfig", ",", "customParams", ",", "callback", "]", "=", "doArgs", "(", "arguments", ",", "[", "'string'", ",", "'string'", ",", "[", "'object'", ",", "{", "}", "]", ",", "'function'", "]", ")", ";", "// Set the created job name!", "customParams", ".", "name", "=", "jobName", ";", "const", "self", "=", "this", ";", "doRequest", "(", "{", "method", ":", "'POST'", ",", "urlPattern", ":", "[", "JOB_CREATE", "]", ",", "request", ":", "{", "body", ":", "jobConfig", ",", "headers", ":", "{", "'Content-Type'", ":", "'application/xml'", "}", "}", ",", "noparse", ":", "true", "}", ",", "customParams", ",", "function", "(", "error", ",", "data", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ",", "data", ")", ";", "return", ";", "}", "self", ".", "job_info", "(", "jobName", ",", "customParams", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Create a new job based on a jobConfig string @param {string} jobName @param {string} jobConfig @param {object|undefined} customParams is optional @param {function} callback
[ "Create", "a", "new", "job", "based", "on", "a", "jobConfig", "string" ]
1f1ac16a6055bc162c7ecfdee286c2a458a1e19b
https://github.com/jansepar/node-jenkins-api/blob/1f1ac16a6055bc162c7ecfdee286c2a458a1e19b/src/main.js#L652-L675
15,415
jansepar/node-jenkins-api
src/main.js
function (viewName, viewConfig, customParams, callback) { [viewName, viewConfig, customParams, callback] = doArgs(arguments, ['string', 'object', ['object', {}], 'function']); viewConfig.json = JSON.stringify(viewConfig); const self = this; doRequest({ method: 'POST', urlPattern: [VIEW_CONFIG, viewName], request: { form: viewConfig // headers: {'content-type': 'application/x-www-form-urlencoded'}, }, noparse: true }, customParams, function (error, data) { if (error) { callback(error, data); return; } self.view_info(viewName, customParams, callback); }); }
javascript
function (viewName, viewConfig, customParams, callback) { [viewName, viewConfig, customParams, callback] = doArgs(arguments, ['string', 'object', ['object', {}], 'function']); viewConfig.json = JSON.stringify(viewConfig); const self = this; doRequest({ method: 'POST', urlPattern: [VIEW_CONFIG, viewName], request: { form: viewConfig // headers: {'content-type': 'application/x-www-form-urlencoded'}, }, noparse: true }, customParams, function (error, data) { if (error) { callback(error, data); return; } self.view_info(viewName, customParams, callback); }); }
[ "function", "(", "viewName", ",", "viewConfig", ",", "customParams", ",", "callback", ")", "{", "[", "viewName", ",", "viewConfig", ",", "customParams", ",", "callback", "]", "=", "doArgs", "(", "arguments", ",", "[", "'string'", ",", "'object'", ",", "[", "'object'", ",", "{", "}", "]", ",", "'function'", "]", ")", ";", "viewConfig", ".", "json", "=", "JSON", ".", "stringify", "(", "viewConfig", ")", ";", "const", "self", "=", "this", ";", "doRequest", "(", "{", "method", ":", "'POST'", ",", "urlPattern", ":", "[", "VIEW_CONFIG", ",", "viewName", "]", ",", "request", ":", "{", "form", ":", "viewConfig", "// headers: {'content-type': 'application/x-www-form-urlencoded'},", "}", ",", "noparse", ":", "true", "}", ",", "customParams", ",", "function", "(", "error", ",", "data", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ",", "data", ")", ";", "return", ";", "}", "self", ".", "view_info", "(", "viewName", ",", "customParams", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Update a view based on a viewConfig object @param {string} viewName @param {object} viewConfig @param {object|undefined} customParams is optional @param {function} callback
[ "Update", "a", "view", "based", "on", "a", "viewConfig", "object" ]
1f1ac16a6055bc162c7ecfdee286c2a458a1e19b
https://github.com/jansepar/node-jenkins-api/blob/1f1ac16a6055bc162c7ecfdee286c2a458a1e19b/src/main.js#L959-L981
15,416
jansepar/node-jenkins-api
src/main.js
function (viewName, customParams, callback) { [viewName, customParams, callback] = doArgs(arguments, ['string', ['object', {}], 'function']); doRequest({ urlPattern: [VIEW_INFO, viewName], bodyProp: 'jobs' }, customParams, callback); }
javascript
function (viewName, customParams, callback) { [viewName, customParams, callback] = doArgs(arguments, ['string', ['object', {}], 'function']); doRequest({ urlPattern: [VIEW_INFO, viewName], bodyProp: 'jobs' }, customParams, callback); }
[ "function", "(", "viewName", ",", "customParams", ",", "callback", ")", "{", "[", "viewName", ",", "customParams", ",", "callback", "]", "=", "doArgs", "(", "arguments", ",", "[", "'string'", ",", "[", "'object'", ",", "{", "}", "]", ",", "'function'", "]", ")", ";", "doRequest", "(", "{", "urlPattern", ":", "[", "VIEW_INFO", ",", "viewName", "]", ",", "bodyProp", ":", "'jobs'", "}", ",", "customParams", ",", "callback", ")", ";", "}" ]
Return a list of objet literals containing the name and color of all the jobs for a view on the Jenkins server @param {string} viewName @param {object|undefined} customParams is optional @param {function} callback
[ "Return", "a", "list", "of", "objet", "literals", "containing", "the", "name", "and", "color", "of", "all", "the", "jobs", "for", "a", "view", "on", "the", "Jenkins", "server" ]
1f1ac16a6055bc162c7ecfdee286c2a458a1e19b
https://github.com/jansepar/node-jenkins-api/blob/1f1ac16a6055bc162c7ecfdee286c2a458a1e19b/src/main.js#L1047-L1054
15,417
jansepar/node-jenkins-api
src/main.js
function (pluginName, customParams, callback) { [pluginName, customParams, callback] = doArgs(arguments, ['string', ['object', {}], 'function']); const body = `<jenkins><install plugin="${pluginName}" /></jenkins>`; doRequest({ method: 'POST', urlPattern: [INSTALL_PLUGIN], request: { body: body, headers: { 'Content-Type': 'text/xml' } }, noparse: true, bodyProp: 'plugins' }, customParams, callback); }
javascript
function (pluginName, customParams, callback) { [pluginName, customParams, callback] = doArgs(arguments, ['string', ['object', {}], 'function']); const body = `<jenkins><install plugin="${pluginName}" /></jenkins>`; doRequest({ method: 'POST', urlPattern: [INSTALL_PLUGIN], request: { body: body, headers: { 'Content-Type': 'text/xml' } }, noparse: true, bodyProp: 'plugins' }, customParams, callback); }
[ "function", "(", "pluginName", ",", "customParams", ",", "callback", ")", "{", "[", "pluginName", ",", "customParams", ",", "callback", "]", "=", "doArgs", "(", "arguments", ",", "[", "'string'", ",", "[", "'object'", ",", "{", "}", "]", ",", "'function'", "]", ")", ";", "const", "body", "=", "`", "${", "pluginName", "}", "`", ";", "doRequest", "(", "{", "method", ":", "'POST'", ",", "urlPattern", ":", "[", "INSTALL_PLUGIN", "]", ",", "request", ":", "{", "body", ":", "body", ",", "headers", ":", "{", "'Content-Type'", ":", "'text/xml'", "}", "}", ",", "noparse", ":", "true", ",", "bodyProp", ":", "'plugins'", "}", ",", "customParams", ",", "callback", ")", ";", "}" ]
Install a plugin @param {string} pluginName @param {object|undefined} customParams is optional @param {function} callback
[ "Install", "a", "plugin" ]
1f1ac16a6055bc162c7ecfdee286c2a458a1e19b
https://github.com/jansepar/node-jenkins-api/blob/1f1ac16a6055bc162c7ecfdee286c2a458a1e19b/src/main.js#L1086-L1101
15,418
jansepar/node-jenkins-api
src/main.js
function (folderName, customParams, callback) { [folderName, customParams, callback] = doArgs(arguments, ['string', ['object', {}], 'function']); const mode = 'com.cloudbees.hudson.plugins.folder.Folder'; customParams.name = folderName; customParams.mode = mode; customParams.Submit = 'OK'; doRequest({ method: 'POST', urlPattern: [NEWFOLDER] }, customParams, callback); }
javascript
function (folderName, customParams, callback) { [folderName, customParams, callback] = doArgs(arguments, ['string', ['object', {}], 'function']); const mode = 'com.cloudbees.hudson.plugins.folder.Folder'; customParams.name = folderName; customParams.mode = mode; customParams.Submit = 'OK'; doRequest({ method: 'POST', urlPattern: [NEWFOLDER] }, customParams, callback); }
[ "function", "(", "folderName", ",", "customParams", ",", "callback", ")", "{", "[", "folderName", ",", "customParams", ",", "callback", "]", "=", "doArgs", "(", "arguments", ",", "[", "'string'", ",", "[", "'object'", ",", "{", "}", "]", ",", "'function'", "]", ")", ";", "const", "mode", "=", "'com.cloudbees.hudson.plugins.folder.Folder'", ";", "customParams", ".", "name", "=", "folderName", ";", "customParams", ".", "mode", "=", "mode", ";", "customParams", ".", "Submit", "=", "'OK'", ";", "doRequest", "(", "{", "method", ":", "'POST'", ",", "urlPattern", ":", "[", "NEWFOLDER", "]", "}", ",", "customParams", ",", "callback", ")", ";", "}" ]
Create a new folder with given name Requires Folder plugin in Jenkins: @see https://wiki.jenkins-ci.org/display/JENKINS/CloudBees+Folders+Plugin @see https://gist.github.com/stuart-warren/7786892 @param {string} folderName @param {object|undefined} customParams is optional @param {function} callback
[ "Create", "a", "new", "folder", "with", "given", "name" ]
1f1ac16a6055bc162c7ecfdee286c2a458a1e19b
https://github.com/jansepar/node-jenkins-api/blob/1f1ac16a6055bc162c7ecfdee286c2a458a1e19b/src/main.js#L1114-L1127
15,419
jansepar/node-jenkins-api
lib/main.js
appendParams
function appendParams(url, specificParams) { // Assign default and specific parameters var params = Object.assign({}, defaultParams, specificParams); // Stringify the querystring params var paramsString = qs.stringify(params); // Empty params if (paramsString === '') { return url; } // Does url contain parameters already? var delim = url.includes('?') ? '&' : '?'; return url + delim + paramsString; }
javascript
function appendParams(url, specificParams) { // Assign default and specific parameters var params = Object.assign({}, defaultParams, specificParams); // Stringify the querystring params var paramsString = qs.stringify(params); // Empty params if (paramsString === '') { return url; } // Does url contain parameters already? var delim = url.includes('?') ? '&' : '?'; return url + delim + paramsString; }
[ "function", "appendParams", "(", "url", ",", "specificParams", ")", "{", "// Assign default and specific parameters", "var", "params", "=", "Object", ".", "assign", "(", "{", "}", ",", "defaultParams", ",", "specificParams", ")", ";", "// Stringify the querystring params", "var", "paramsString", "=", "qs", ".", "stringify", "(", "params", ")", ";", "// Empty params", "if", "(", "paramsString", "===", "''", ")", "{", "return", "url", ";", "}", "// Does url contain parameters already?", "var", "delim", "=", "url", ".", "includes", "(", "'?'", ")", "?", "'&'", ":", "'?'", ";", "return", "url", "+", "delim", "+", "paramsString", ";", "}" ]
Build REST params and correctly append them to URL. @param {string} url to be extended with params. @param {object} specificParams key/value pair of params. @returns {string} the extended url.
[ "Build", "REST", "params", "and", "correctly", "append", "them", "to", "URL", "." ]
1f1ac16a6055bc162c7ecfdee286c2a458a1e19b
https://github.com/jansepar/node-jenkins-api/blob/1f1ac16a6055bc162c7ecfdee286c2a458a1e19b/lib/main.js#L256-L272
15,420
jansepar/node-jenkins-api
lib/main.js
buildUrl
function buildUrl(urlPattern, customParams) { var url = formatUrl.apply(null, urlPattern); url = appendParams(url, customParams); return url; }
javascript
function buildUrl(urlPattern, customParams) { var url = formatUrl.apply(null, urlPattern); url = appendParams(url, customParams); return url; }
[ "function", "buildUrl", "(", "urlPattern", ",", "customParams", ")", "{", "var", "url", "=", "formatUrl", ".", "apply", "(", "null", ",", "urlPattern", ")", ";", "url", "=", "appendParams", "(", "url", ",", "customParams", ")", ";", "return", "url", ";", "}" ]
Just helper funckion to build the request URL. @param {array<string>} urlPattern array in format of [urlFormat, arg1, arg2] used to build the URL. @param {object} customParams key/value pair of params. @returns {string} the URL built.
[ "Just", "helper", "funckion", "to", "build", "the", "request", "URL", "." ]
1f1ac16a6055bc162c7ecfdee286c2a458a1e19b
https://github.com/jansepar/node-jenkins-api/blob/1f1ac16a6055bc162c7ecfdee286c2a458a1e19b/lib/main.js#L281-L286
15,421
jansepar/node-jenkins-api
lib/main.js
delete_build
function delete_build(jobName, buildNumber, customParams, callback) { var _doArgs21 = doArgs(arguments, ['string', 'string|number', ['object', {}], 'function']); var _doArgs22 = _slicedToArray(_doArgs21, 4); jobName = _doArgs22[0]; buildNumber = _doArgs22[1]; customParams = _doArgs22[2]; callback = _doArgs22[3]; doRequest({ method: 'POST', urlPattern: [BUILD_DELETE, jobName, buildNumber], noparse: true }, customParams, function (error, data) { if (error) { callback(error, data); } else { data.body = 'Build ' + buildNumber + ' deleted.'; callback(null, data); } }); }
javascript
function delete_build(jobName, buildNumber, customParams, callback) { var _doArgs21 = doArgs(arguments, ['string', 'string|number', ['object', {}], 'function']); var _doArgs22 = _slicedToArray(_doArgs21, 4); jobName = _doArgs22[0]; buildNumber = _doArgs22[1]; customParams = _doArgs22[2]; callback = _doArgs22[3]; doRequest({ method: 'POST', urlPattern: [BUILD_DELETE, jobName, buildNumber], noparse: true }, customParams, function (error, data) { if (error) { callback(error, data); } else { data.body = 'Build ' + buildNumber + ' deleted.'; callback(null, data); } }); }
[ "function", "delete_build", "(", "jobName", ",", "buildNumber", ",", "customParams", ",", "callback", ")", "{", "var", "_doArgs21", "=", "doArgs", "(", "arguments", ",", "[", "'string'", ",", "'string|number'", ",", "[", "'object'", ",", "{", "}", "]", ",", "'function'", "]", ")", ";", "var", "_doArgs22", "=", "_slicedToArray", "(", "_doArgs21", ",", "4", ")", ";", "jobName", "=", "_doArgs22", "[", "0", "]", ";", "buildNumber", "=", "_doArgs22", "[", "1", "]", ";", "customParams", "=", "_doArgs22", "[", "2", "]", ";", "callback", "=", "_doArgs22", "[", "3", "]", ";", "doRequest", "(", "{", "method", ":", "'POST'", ",", "urlPattern", ":", "[", "BUILD_DELETE", ",", "jobName", ",", "buildNumber", "]", ",", "noparse", ":", "true", "}", ",", "customParams", ",", "function", "(", "error", ",", "data", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ",", "data", ")", ";", "}", "else", "{", "data", ".", "body", "=", "'Build '", "+", "buildNumber", "+", "' deleted.'", ";", "callback", "(", "null", ",", "data", ")", ";", "}", "}", ")", ";", "}" ]
Deletes build data for certain job
[ "Deletes", "build", "data", "for", "certain", "job" ]
1f1ac16a6055bc162c7ecfdee286c2a458a1e19b
https://github.com/jansepar/node-jenkins-api/blob/1f1ac16a6055bc162c7ecfdee286c2a458a1e19b/lib/main.js#L569-L592
15,422
jansepar/node-jenkins-api
lib/main.js
update_job
function update_job(jobName, jobConfig, customParams, callback) { var _doArgs29 = doArgs(arguments, ['string', 'string', ['object', {}], 'function']); var _doArgs30 = _slicedToArray(_doArgs29, 4); jobName = _doArgs30[0]; jobConfig = _doArgs30[1]; customParams = _doArgs30[2]; callback = _doArgs30[3]; doRequest({ method: 'POST', urlPattern: [JOB_CONFIG, jobName], request: { body: jobConfig, headers: { 'Content-Type': 'application/xml' } }, noparse: true }, customParams, function (error, data) { if (error) { callback(error, data); return; } // TODO rather return job_info ??? // const data = {name: jobName, location: response.headers['Location'] || response.headers['location']}; callback(null, { name: jobName }); }); }
javascript
function update_job(jobName, jobConfig, customParams, callback) { var _doArgs29 = doArgs(arguments, ['string', 'string', ['object', {}], 'function']); var _doArgs30 = _slicedToArray(_doArgs29, 4); jobName = _doArgs30[0]; jobConfig = _doArgs30[1]; customParams = _doArgs30[2]; callback = _doArgs30[3]; doRequest({ method: 'POST', urlPattern: [JOB_CONFIG, jobName], request: { body: jobConfig, headers: { 'Content-Type': 'application/xml' } }, noparse: true }, customParams, function (error, data) { if (error) { callback(error, data); return; } // TODO rather return job_info ??? // const data = {name: jobName, location: response.headers['Location'] || response.headers['location']}; callback(null, { name: jobName }); }); }
[ "function", "update_job", "(", "jobName", ",", "jobConfig", ",", "customParams", ",", "callback", ")", "{", "var", "_doArgs29", "=", "doArgs", "(", "arguments", ",", "[", "'string'", ",", "'string'", ",", "[", "'object'", ",", "{", "}", "]", ",", "'function'", "]", ")", ";", "var", "_doArgs30", "=", "_slicedToArray", "(", "_doArgs29", ",", "4", ")", ";", "jobName", "=", "_doArgs30", "[", "0", "]", ";", "jobConfig", "=", "_doArgs30", "[", "1", "]", ";", "customParams", "=", "_doArgs30", "[", "2", "]", ";", "callback", "=", "_doArgs30", "[", "3", "]", ";", "doRequest", "(", "{", "method", ":", "'POST'", ",", "urlPattern", ":", "[", "JOB_CONFIG", ",", "jobName", "]", ",", "request", ":", "{", "body", ":", "jobConfig", ",", "headers", ":", "{", "'Content-Type'", ":", "'application/xml'", "}", "}", ",", "noparse", ":", "true", "}", ",", "customParams", ",", "function", "(", "error", ",", "data", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ",", "data", ")", ";", "return", ";", "}", "// TODO rather return job_info ???", "// const data = {name: jobName, location: response.headers['Location'] || response.headers['location']};", "callback", "(", "null", ",", "{", "name", ":", "jobName", "}", ")", ";", "}", ")", ";", "}" ]
Update a existing job based on a jobConfig xml string
[ "Update", "a", "existing", "job", "based", "on", "a", "jobConfig", "xml", "string" ]
1f1ac16a6055bc162c7ecfdee286c2a458a1e19b
https://github.com/jansepar/node-jenkins-api/blob/1f1ac16a6055bc162c7ecfdee286c2a458a1e19b/lib/main.js#L666-L694
15,423
jansepar/node-jenkins-api
lib/main.js
enable_job
function enable_job(jobName, customParams, callback) { var _doArgs41 = doArgs(arguments, ['string', ['object', {}], 'function']); var _doArgs42 = _slicedToArray(_doArgs41, 3); jobName = _doArgs42[0]; customParams = _doArgs42[1]; callback = _doArgs42[2]; var self = this; doRequest({ method: 'POST', urlPattern: [JOB_ENABLE, jobName], noparse: true }, customParams, function (error, data) { if (error) { callback(error, data); return; } self.job_info(jobName, customParams, callback); }); }
javascript
function enable_job(jobName, customParams, callback) { var _doArgs41 = doArgs(arguments, ['string', ['object', {}], 'function']); var _doArgs42 = _slicedToArray(_doArgs41, 3); jobName = _doArgs42[0]; customParams = _doArgs42[1]; callback = _doArgs42[2]; var self = this; doRequest({ method: 'POST', urlPattern: [JOB_ENABLE, jobName], noparse: true }, customParams, function (error, data) { if (error) { callback(error, data); return; } self.job_info(jobName, customParams, callback); }); }
[ "function", "enable_job", "(", "jobName", ",", "customParams", ",", "callback", ")", "{", "var", "_doArgs41", "=", "doArgs", "(", "arguments", ",", "[", "'string'", ",", "[", "'object'", ",", "{", "}", "]", ",", "'function'", "]", ")", ";", "var", "_doArgs42", "=", "_slicedToArray", "(", "_doArgs41", ",", "3", ")", ";", "jobName", "=", "_doArgs42", "[", "0", "]", ";", "customParams", "=", "_doArgs42", "[", "1", "]", ";", "callback", "=", "_doArgs42", "[", "2", "]", ";", "var", "self", "=", "this", ";", "doRequest", "(", "{", "method", ":", "'POST'", ",", "urlPattern", ":", "[", "JOB_ENABLE", ",", "jobName", "]", ",", "noparse", ":", "true", "}", ",", "customParams", ",", "function", "(", "error", ",", "data", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ",", "data", ")", ";", "return", ";", "}", "self", ".", "job_info", "(", "jobName", ",", "customParams", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Enables a job
[ "Enables", "a", "job" ]
1f1ac16a6055bc162c7ecfdee286c2a458a1e19b
https://github.com/jansepar/node-jenkins-api/blob/1f1ac16a6055bc162c7ecfdee286c2a458a1e19b/lib/main.js#L824-L847
15,424
mapbox/tilebelt
index.js
tileToBBOX
function tileToBBOX(tile) { var e = tile2lon(tile[0] + 1, tile[2]); var w = tile2lon(tile[0], tile[2]); var s = tile2lat(tile[1] + 1, tile[2]); var n = tile2lat(tile[1], tile[2]); return [w, s, e, n]; }
javascript
function tileToBBOX(tile) { var e = tile2lon(tile[0] + 1, tile[2]); var w = tile2lon(tile[0], tile[2]); var s = tile2lat(tile[1] + 1, tile[2]); var n = tile2lat(tile[1], tile[2]); return [w, s, e, n]; }
[ "function", "tileToBBOX", "(", "tile", ")", "{", "var", "e", "=", "tile2lon", "(", "tile", "[", "0", "]", "+", "1", ",", "tile", "[", "2", "]", ")", ";", "var", "w", "=", "tile2lon", "(", "tile", "[", "0", "]", ",", "tile", "[", "2", "]", ")", ";", "var", "s", "=", "tile2lat", "(", "tile", "[", "1", "]", "+", "1", ",", "tile", "[", "2", "]", ")", ";", "var", "n", "=", "tile2lat", "(", "tile", "[", "1", "]", ",", "tile", "[", "2", "]", ")", ";", "return", "[", "w", ",", "s", ",", "e", ",", "n", "]", ";", "}" ]
Get the bbox of a tile @name tileToBBOX @param {Array<number>} tile @returns {Array<number>} bbox @example var bbox = tileToBBOX([5, 10, 10]) //=bbox
[ "Get", "the", "bbox", "of", "a", "tile" ]
7df684f198837d9ea0385a0b0b8f71c8d0f3acac
https://github.com/mapbox/tilebelt/blob/7df684f198837d9ea0385a0b0b8f71c8d0f3acac/index.js#L16-L22
15,425
mapbox/tilebelt
index.js
tileToGeoJSON
function tileToGeoJSON(tile) { var bbox = tileToBBOX(tile); var poly = { type: 'Polygon', coordinates: [[ [bbox[0], bbox[1]], [bbox[0], bbox[3]], [bbox[2], bbox[3]], [bbox[2], bbox[1]], [bbox[0], bbox[1]] ]] }; return poly; }
javascript
function tileToGeoJSON(tile) { var bbox = tileToBBOX(tile); var poly = { type: 'Polygon', coordinates: [[ [bbox[0], bbox[1]], [bbox[0], bbox[3]], [bbox[2], bbox[3]], [bbox[2], bbox[1]], [bbox[0], bbox[1]] ]] }; return poly; }
[ "function", "tileToGeoJSON", "(", "tile", ")", "{", "var", "bbox", "=", "tileToBBOX", "(", "tile", ")", ";", "var", "poly", "=", "{", "type", ":", "'Polygon'", ",", "coordinates", ":", "[", "[", "[", "bbox", "[", "0", "]", ",", "bbox", "[", "1", "]", "]", ",", "[", "bbox", "[", "0", "]", ",", "bbox", "[", "3", "]", "]", ",", "[", "bbox", "[", "2", "]", ",", "bbox", "[", "3", "]", "]", ",", "[", "bbox", "[", "2", "]", ",", "bbox", "[", "1", "]", "]", ",", "[", "bbox", "[", "0", "]", ",", "bbox", "[", "1", "]", "]", "]", "]", "}", ";", "return", "poly", ";", "}" ]
Get a geojson representation of a tile @name tileToGeoJSON @param {Array<number>} tile @returns {Feature<Polygon>} @example var poly = tileToGeoJSON([5, 10, 10]) //=poly
[ "Get", "a", "geojson", "representation", "of", "a", "tile" ]
7df684f198837d9ea0385a0b0b8f71c8d0f3acac
https://github.com/mapbox/tilebelt/blob/7df684f198837d9ea0385a0b0b8f71c8d0f3acac/index.js#L34-L47
15,426
mapbox/tilebelt
index.js
pointToTile
function pointToTile(lon, lat, z) { var tile = pointToTileFraction(lon, lat, z); tile[0] = Math.floor(tile[0]); tile[1] = Math.floor(tile[1]); return tile; }
javascript
function pointToTile(lon, lat, z) { var tile = pointToTileFraction(lon, lat, z); tile[0] = Math.floor(tile[0]); tile[1] = Math.floor(tile[1]); return tile; }
[ "function", "pointToTile", "(", "lon", ",", "lat", ",", "z", ")", "{", "var", "tile", "=", "pointToTileFraction", "(", "lon", ",", "lat", ",", "z", ")", ";", "tile", "[", "0", "]", "=", "Math", ".", "floor", "(", "tile", "[", "0", "]", ")", ";", "tile", "[", "1", "]", "=", "Math", ".", "floor", "(", "tile", "[", "1", "]", ")", ";", "return", "tile", ";", "}" ]
Get the tile for a point at a specified zoom level @name pointToTile @param {number} lon @param {number} lat @param {number} z @returns {Array<number>} tile @example var tile = pointToTile(1, 1, 20) //=tile
[ "Get", "the", "tile", "for", "a", "point", "at", "a", "specified", "zoom", "level" ]
7df684f198837d9ea0385a0b0b8f71c8d0f3acac
https://github.com/mapbox/tilebelt/blob/7df684f198837d9ea0385a0b0b8f71c8d0f3acac/index.js#L70-L75
15,427
mapbox/tilebelt
index.js
getChildren
function getChildren(tile) { return [ [tile[0] * 2, tile[1] * 2, tile[2] + 1], [tile[0] * 2 + 1, tile[1] * 2, tile[2 ] + 1], [tile[0] * 2 + 1, tile[1] * 2 + 1, tile[2] + 1], [tile[0] * 2, tile[1] * 2 + 1, tile[2] + 1] ]; }
javascript
function getChildren(tile) { return [ [tile[0] * 2, tile[1] * 2, tile[2] + 1], [tile[0] * 2 + 1, tile[1] * 2, tile[2 ] + 1], [tile[0] * 2 + 1, tile[1] * 2 + 1, tile[2] + 1], [tile[0] * 2, tile[1] * 2 + 1, tile[2] + 1] ]; }
[ "function", "getChildren", "(", "tile", ")", "{", "return", "[", "[", "tile", "[", "0", "]", "*", "2", ",", "tile", "[", "1", "]", "*", "2", ",", "tile", "[", "2", "]", "+", "1", "]", ",", "[", "tile", "[", "0", "]", "*", "2", "+", "1", ",", "tile", "[", "1", "]", "*", "2", ",", "tile", "[", "2", "]", "+", "1", "]", ",", "[", "tile", "[", "0", "]", "*", "2", "+", "1", ",", "tile", "[", "1", "]", "*", "2", "+", "1", ",", "tile", "[", "2", "]", "+", "1", "]", ",", "[", "tile", "[", "0", "]", "*", "2", ",", "tile", "[", "1", "]", "*", "2", "+", "1", ",", "tile", "[", "2", "]", "+", "1", "]", "]", ";", "}" ]
Get the 4 tiles one zoom level higher @name getChildren @param {Array<number>} tile @returns {Array<Array<number>>} tiles @example var tiles = getChildren([5, 10, 10]) //=tiles
[ "Get", "the", "4", "tiles", "one", "zoom", "level", "higher" ]
7df684f198837d9ea0385a0b0b8f71c8d0f3acac
https://github.com/mapbox/tilebelt/blob/7df684f198837d9ea0385a0b0b8f71c8d0f3acac/index.js#L87-L94
15,428
mapbox/tilebelt
index.js
hasSiblings
function hasSiblings(tile, tiles) { var siblings = getSiblings(tile); for (var i = 0; i < siblings.length; i++) { if (!hasTile(tiles, siblings[i])) return false; } return true; }
javascript
function hasSiblings(tile, tiles) { var siblings = getSiblings(tile); for (var i = 0; i < siblings.length; i++) { if (!hasTile(tiles, siblings[i])) return false; } return true; }
[ "function", "hasSiblings", "(", "tile", ",", "tiles", ")", "{", "var", "siblings", "=", "getSiblings", "(", "tile", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "siblings", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "hasTile", "(", "tiles", ",", "siblings", "[", "i", "]", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}" ]
Get the 3 sibling tiles for a tile @name getSiblings @param {Array<number>} tile @returns {Array<Array<number>>} tiles @example var tiles = getSiblings([5, 10, 10]) //=tiles
[ "Get", "the", "3", "sibling", "tiles", "for", "a", "tile" ]
7df684f198837d9ea0385a0b0b8f71c8d0f3acac
https://github.com/mapbox/tilebelt/blob/7df684f198837d9ea0385a0b0b8f71c8d0f3acac/index.js#L124-L130
15,429
mapbox/tilebelt
index.js
hasTile
function hasTile(tiles, tile) { for (var i = 0; i < tiles.length; i++) { if (tilesEqual(tiles[i], tile)) return true; } return false; }
javascript
function hasTile(tiles, tile) { for (var i = 0; i < tiles.length; i++) { if (tilesEqual(tiles[i], tile)) return true; } return false; }
[ "function", "hasTile", "(", "tiles", ",", "tile", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "tiles", ".", "length", ";", "i", "++", ")", "{", "if", "(", "tilesEqual", "(", "tiles", "[", "i", "]", ",", "tile", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
Check to see if an array of tiles contains a particular tile @name hasTile @param {Array<Array<number>>} tiles @param {Array<number>} tile @returns {boolean} @example var tiles = [ [0, 0, 5], [0, 1, 5], [1, 1, 5], [1, 0, 5] ] hasTile(tiles, [0, 0, 5]) //=boolean
[ "Check", "to", "see", "if", "an", "array", "of", "tiles", "contains", "a", "particular", "tile" ]
7df684f198837d9ea0385a0b0b8f71c8d0f3acac
https://github.com/mapbox/tilebelt/blob/7df684f198837d9ea0385a0b0b8f71c8d0f3acac/index.js#L149-L154
15,430
mapbox/tilebelt
index.js
tileToQuadkey
function tileToQuadkey(tile) { var index = ''; for (var z = tile[2]; z > 0; z--) { var b = 0; var mask = 1 << (z - 1); if ((tile[0] & mask) !== 0) b++; if ((tile[1] & mask) !== 0) b += 2; index += b.toString(); } return index; }
javascript
function tileToQuadkey(tile) { var index = ''; for (var z = tile[2]; z > 0; z--) { var b = 0; var mask = 1 << (z - 1); if ((tile[0] & mask) !== 0) b++; if ((tile[1] & mask) !== 0) b += 2; index += b.toString(); } return index; }
[ "function", "tileToQuadkey", "(", "tile", ")", "{", "var", "index", "=", "''", ";", "for", "(", "var", "z", "=", "tile", "[", "2", "]", ";", "z", ">", "0", ";", "z", "--", ")", "{", "var", "b", "=", "0", ";", "var", "mask", "=", "1", "<<", "(", "z", "-", "1", ")", ";", "if", "(", "(", "tile", "[", "0", "]", "&", "mask", ")", "!==", "0", ")", "b", "++", ";", "if", "(", "(", "tile", "[", "1", "]", "&", "mask", ")", "!==", "0", ")", "b", "+=", "2", ";", "index", "+=", "b", ".", "toString", "(", ")", ";", "}", "return", "index", ";", "}" ]
Get the quadkey for a tile @name tileToQuadkey @param {Array<number>} tile @returns {string} quadkey @example var quadkey = tileToQuadkey([0, 1, 5]) //=quadkey
[ "Get", "the", "quadkey", "for", "a", "tile" ]
7df684f198837d9ea0385a0b0b8f71c8d0f3acac
https://github.com/mapbox/tilebelt/blob/7df684f198837d9ea0385a0b0b8f71c8d0f3acac/index.js#L185-L195
15,431
mapbox/tilebelt
index.js
quadkeyToTile
function quadkeyToTile(quadkey) { var x = 0; var y = 0; var z = quadkey.length; for (var i = z; i > 0; i--) { var mask = 1 << (i - 1); var q = +quadkey[z - i]; if (q === 1) x |= mask; if (q === 2) y |= mask; if (q === 3) { x |= mask; y |= mask; } } return [x, y, z]; }
javascript
function quadkeyToTile(quadkey) { var x = 0; var y = 0; var z = quadkey.length; for (var i = z; i > 0; i--) { var mask = 1 << (i - 1); var q = +quadkey[z - i]; if (q === 1) x |= mask; if (q === 2) y |= mask; if (q === 3) { x |= mask; y |= mask; } } return [x, y, z]; }
[ "function", "quadkeyToTile", "(", "quadkey", ")", "{", "var", "x", "=", "0", ";", "var", "y", "=", "0", ";", "var", "z", "=", "quadkey", ".", "length", ";", "for", "(", "var", "i", "=", "z", ";", "i", ">", "0", ";", "i", "--", ")", "{", "var", "mask", "=", "1", "<<", "(", "i", "-", "1", ")", ";", "var", "q", "=", "+", "quadkey", "[", "z", "-", "i", "]", ";", "if", "(", "q", "===", "1", ")", "x", "|=", "mask", ";", "if", "(", "q", "===", "2", ")", "y", "|=", "mask", ";", "if", "(", "q", "===", "3", ")", "{", "x", "|=", "mask", ";", "y", "|=", "mask", ";", "}", "}", "return", "[", "x", ",", "y", ",", "z", "]", ";", "}" ]
Get the tile for a quadkey @name quadkeyToTile @param {string} quadkey @returns {Array<number>} tile @example var tile = quadkeyToTile('00001033') //=tile
[ "Get", "the", "tile", "for", "a", "quadkey" ]
7df684f198837d9ea0385a0b0b8f71c8d0f3acac
https://github.com/mapbox/tilebelt/blob/7df684f198837d9ea0385a0b0b8f71c8d0f3acac/index.js#L207-L223
15,432
mapbox/tilebelt
index.js
bboxToTile
function bboxToTile(bboxCoords) { var min = pointToTile(bboxCoords[0], bboxCoords[1], 32); var max = pointToTile(bboxCoords[2], bboxCoords[3], 32); var bbox = [min[0], min[1], max[0], max[1]]; var z = getBboxZoom(bbox); if (z === 0) return [0, 0, 0]; var x = bbox[0] >>> (32 - z); var y = bbox[1] >>> (32 - z); return [x, y, z]; }
javascript
function bboxToTile(bboxCoords) { var min = pointToTile(bboxCoords[0], bboxCoords[1], 32); var max = pointToTile(bboxCoords[2], bboxCoords[3], 32); var bbox = [min[0], min[1], max[0], max[1]]; var z = getBboxZoom(bbox); if (z === 0) return [0, 0, 0]; var x = bbox[0] >>> (32 - z); var y = bbox[1] >>> (32 - z); return [x, y, z]; }
[ "function", "bboxToTile", "(", "bboxCoords", ")", "{", "var", "min", "=", "pointToTile", "(", "bboxCoords", "[", "0", "]", ",", "bboxCoords", "[", "1", "]", ",", "32", ")", ";", "var", "max", "=", "pointToTile", "(", "bboxCoords", "[", "2", "]", ",", "bboxCoords", "[", "3", "]", ",", "32", ")", ";", "var", "bbox", "=", "[", "min", "[", "0", "]", ",", "min", "[", "1", "]", ",", "max", "[", "0", "]", ",", "max", "[", "1", "]", "]", ";", "var", "z", "=", "getBboxZoom", "(", "bbox", ")", ";", "if", "(", "z", "===", "0", ")", "return", "[", "0", ",", "0", ",", "0", "]", ";", "var", "x", "=", "bbox", "[", "0", "]", ">>>", "(", "32", "-", "z", ")", ";", "var", "y", "=", "bbox", "[", "1", "]", ">>>", "(", "32", "-", "z", ")", ";", "return", "[", "x", ",", "y", ",", "z", "]", ";", "}" ]
Get the smallest tile to cover a bbox @name bboxToTile @param {Array<number>} bbox @returns {Array<number>} tile @example var tile = bboxToTile([ -178, 84, -177, 85 ]) //=tile
[ "Get", "the", "smallest", "tile", "to", "cover", "a", "bbox" ]
7df684f198837d9ea0385a0b0b8f71c8d0f3acac
https://github.com/mapbox/tilebelt/blob/7df684f198837d9ea0385a0b0b8f71c8d0f3acac/index.js#L235-L245
15,433
mapbox/tilebelt
index.js
pointToTileFraction
function pointToTileFraction(lon, lat, z) { var sin = Math.sin(lat * d2r), z2 = Math.pow(2, z), x = z2 * (lon / 360 + 0.5), y = z2 * (0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI); // Wrap Tile X x = x % z2 if (x < 0) x = x + z2 return [x, y, z]; }
javascript
function pointToTileFraction(lon, lat, z) { var sin = Math.sin(lat * d2r), z2 = Math.pow(2, z), x = z2 * (lon / 360 + 0.5), y = z2 * (0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI); // Wrap Tile X x = x % z2 if (x < 0) x = x + z2 return [x, y, z]; }
[ "function", "pointToTileFraction", "(", "lon", ",", "lat", ",", "z", ")", "{", "var", "sin", "=", "Math", ".", "sin", "(", "lat", "*", "d2r", ")", ",", "z2", "=", "Math", ".", "pow", "(", "2", ",", "z", ")", ",", "x", "=", "z2", "*", "(", "lon", "/", "360", "+", "0.5", ")", ",", "y", "=", "z2", "*", "(", "0.5", "-", "0.25", "*", "Math", ".", "log", "(", "(", "1", "+", "sin", ")", "/", "(", "1", "-", "sin", ")", ")", "/", "Math", ".", "PI", ")", ";", "// Wrap Tile X", "x", "=", "x", "%", "z2", "if", "(", "x", "<", "0", ")", "x", "=", "x", "+", "z2", "return", "[", "x", ",", "y", ",", "z", "]", ";", "}" ]
Get the precise fractional tile location for a point at a zoom level @name pointToTileFraction @param {number} lon @param {number} lat @param {number} z @returns {Array<number>} tile fraction var tile = pointToTileFraction(30.5, 50.5, 15) //=tile
[ "Get", "the", "precise", "fractional", "tile", "location", "for", "a", "point", "at", "a", "zoom", "level" ]
7df684f198837d9ea0385a0b0b8f71c8d0f3acac
https://github.com/mapbox/tilebelt/blob/7df684f198837d9ea0385a0b0b8f71c8d0f3acac/index.js#L271-L281
15,434
caseycesari/GeoJSON.js
geojson.js
addOptionals
function addOptionals(geojson, settings){ if(settings.crs && checkCRS(settings.crs)) { if(settings.isPostgres) geojson.geometry.crs = settings.crs; else geojson.crs = settings.crs; } if (settings.bbox) { geojson.bbox = settings.bbox; } if (settings.extraGlobal) { geojson.properties = {}; for (var key in settings.extraGlobal) { geojson.properties[key] = settings.extraGlobal[key]; } } }
javascript
function addOptionals(geojson, settings){ if(settings.crs && checkCRS(settings.crs)) { if(settings.isPostgres) geojson.geometry.crs = settings.crs; else geojson.crs = settings.crs; } if (settings.bbox) { geojson.bbox = settings.bbox; } if (settings.extraGlobal) { geojson.properties = {}; for (var key in settings.extraGlobal) { geojson.properties[key] = settings.extraGlobal[key]; } } }
[ "function", "addOptionals", "(", "geojson", ",", "settings", ")", "{", "if", "(", "settings", ".", "crs", "&&", "checkCRS", "(", "settings", ".", "crs", ")", ")", "{", "if", "(", "settings", ".", "isPostgres", ")", "geojson", ".", "geometry", ".", "crs", "=", "settings", ".", "crs", ";", "else", "geojson", ".", "crs", "=", "settings", ".", "crs", ";", "}", "if", "(", "settings", ".", "bbox", ")", "{", "geojson", ".", "bbox", "=", "settings", ".", "bbox", ";", "}", "if", "(", "settings", ".", "extraGlobal", ")", "{", "geojson", ".", "properties", "=", "{", "}", ";", "for", "(", "var", "key", "in", "settings", ".", "extraGlobal", ")", "{", "geojson", ".", "properties", "[", "key", "]", "=", "settings", ".", "extraGlobal", "[", "key", "]", ";", "}", "}", "}" ]
Adds the optional GeoJSON properties crs and bbox if they have been specified
[ "Adds", "the", "optional", "GeoJSON", "properties", "crs", "and", "bbox", "if", "they", "have", "been", "specified" ]
92c8cc50548b3c34716c5b82ef96de64ff4ff482
https://github.com/caseycesari/GeoJSON.js/blob/92c8cc50548b3c34716c5b82ef96de64ff4ff482/geojson.js#L85-L101
15,435
caseycesari/GeoJSON.js
geojson.js
checkCRS
function checkCRS(crs) { if (crs.type === 'name') { if (crs.properties && crs.properties.name) { return true; } else { throw new Error('Invalid CRS. Properties must contain "name" key'); } } else if (crs.type === 'link') { if (crs.properties && crs.properties.href && crs.properties.type) { return true; } else { throw new Error('Invalid CRS. Properties must contain "href" and "type" key'); } } else { throw new Error('Invald CRS. Type attribute must be "name" or "link"'); } }
javascript
function checkCRS(crs) { if (crs.type === 'name') { if (crs.properties && crs.properties.name) { return true; } else { throw new Error('Invalid CRS. Properties must contain "name" key'); } } else if (crs.type === 'link') { if (crs.properties && crs.properties.href && crs.properties.type) { return true; } else { throw new Error('Invalid CRS. Properties must contain "href" and "type" key'); } } else { throw new Error('Invald CRS. Type attribute must be "name" or "link"'); } }
[ "function", "checkCRS", "(", "crs", ")", "{", "if", "(", "crs", ".", "type", "===", "'name'", ")", "{", "if", "(", "crs", ".", "properties", "&&", "crs", ".", "properties", ".", "name", ")", "{", "return", "true", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid CRS. Properties must contain \"name\" key'", ")", ";", "}", "}", "else", "if", "(", "crs", ".", "type", "===", "'link'", ")", "{", "if", "(", "crs", ".", "properties", "&&", "crs", ".", "properties", ".", "href", "&&", "crs", ".", "properties", ".", "type", ")", "{", "return", "true", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid CRS. Properties must contain \"href\" and \"type\" key'", ")", ";", "}", "}", "else", "{", "throw", "new", "Error", "(", "'Invald CRS. Type attribute must be \"name\" or \"link\"'", ")", ";", "}", "}" ]
Verify that the structure of CRS object is valid
[ "Verify", "that", "the", "structure", "of", "CRS", "object", "is", "valid" ]
92c8cc50548b3c34716c5b82ef96de64ff4ff482
https://github.com/caseycesari/GeoJSON.js/blob/92c8cc50548b3c34716c5b82ef96de64ff4ff482/geojson.js#L104-L120
15,436
caseycesari/GeoJSON.js
geojson.js
setGeom
function setGeom(params) { params.geom = {}; for(var param in params) { if(params.hasOwnProperty(param) && geoms.indexOf(param) !== -1){ params.geom[param] = params[param]; delete params[param]; } } setGeomAttrList(params.geom); }
javascript
function setGeom(params) { params.geom = {}; for(var param in params) { if(params.hasOwnProperty(param) && geoms.indexOf(param) !== -1){ params.geom[param] = params[param]; delete params[param]; } } setGeomAttrList(params.geom); }
[ "function", "setGeom", "(", "params", ")", "{", "params", ".", "geom", "=", "{", "}", ";", "for", "(", "var", "param", "in", "params", ")", "{", "if", "(", "params", ".", "hasOwnProperty", "(", "param", ")", "&&", "geoms", ".", "indexOf", "(", "param", ")", "!==", "-", "1", ")", "{", "params", ".", "geom", "[", "param", "]", "=", "params", "[", "param", "]", ";", "delete", "params", "[", "param", "]", ";", "}", "}", "setGeomAttrList", "(", "params", ".", "geom", ")", ";", "}" ]
Moves the user-specified geometry parameters under the `geom` key in param for easier access
[ "Moves", "the", "user", "-", "specified", "geometry", "parameters", "under", "the", "geom", "key", "in", "param", "for", "easier", "access" ]
92c8cc50548b3c34716c5b82ef96de64ff4ff482
https://github.com/caseycesari/GeoJSON.js/blob/92c8cc50548b3c34716c5b82ef96de64ff4ff482/geojson.js#L124-L135
15,437
caseycesari/GeoJSON.js
geojson.js
setGeomAttrList
function setGeomAttrList(params) { for(var param in params) { if(params.hasOwnProperty(param)) { if(typeof params[param] === 'string') { geomAttrs.push(params[param]); } else if (typeof params[param] === 'object') { // Array of coordinates for Point geomAttrs.push(params[param][0]); geomAttrs.push(params[param][1]); } } } if(geomAttrs.length === 0) { throw new Error('No geometry attributes specified'); } }
javascript
function setGeomAttrList(params) { for(var param in params) { if(params.hasOwnProperty(param)) { if(typeof params[param] === 'string') { geomAttrs.push(params[param]); } else if (typeof params[param] === 'object') { // Array of coordinates for Point geomAttrs.push(params[param][0]); geomAttrs.push(params[param][1]); } } } if(geomAttrs.length === 0) { throw new Error('No geometry attributes specified'); } }
[ "function", "setGeomAttrList", "(", "params", ")", "{", "for", "(", "var", "param", "in", "params", ")", "{", "if", "(", "params", ".", "hasOwnProperty", "(", "param", ")", ")", "{", "if", "(", "typeof", "params", "[", "param", "]", "===", "'string'", ")", "{", "geomAttrs", ".", "push", "(", "params", "[", "param", "]", ")", ";", "}", "else", "if", "(", "typeof", "params", "[", "param", "]", "===", "'object'", ")", "{", "// Array of coordinates for Point", "geomAttrs", ".", "push", "(", "params", "[", "param", "]", "[", "0", "]", ")", ";", "geomAttrs", ".", "push", "(", "params", "[", "param", "]", "[", "1", "]", ")", ";", "}", "}", "}", "if", "(", "geomAttrs", ".", "length", "===", "0", ")", "{", "throw", "new", "Error", "(", "'No geometry attributes specified'", ")", ";", "}", "}" ]
Adds fields which contain geometry data to geomAttrs. This list is used when adding properties to the features so that no geometry fields are added the properties key
[ "Adds", "fields", "which", "contain", "geometry", "data", "to", "geomAttrs", ".", "This", "list", "is", "used", "when", "adding", "properties", "to", "the", "features", "so", "that", "no", "geometry", "fields", "are", "added", "the", "properties", "key" ]
92c8cc50548b3c34716c5b82ef96de64ff4ff482
https://github.com/caseycesari/GeoJSON.js/blob/92c8cc50548b3c34716c5b82ef96de64ff4ff482/geojson.js#L141-L154
15,438
caseycesari/GeoJSON.js
geojson.js
getFeature
function getFeature(args) { var item = args.item, params = args.params, propFunc = args.propFunc; var feature = { "type": "Feature" }; feature.geometry = buildGeom(item, params); feature.properties = propFunc.call(item); return feature; }
javascript
function getFeature(args) { var item = args.item, params = args.params, propFunc = args.propFunc; var feature = { "type": "Feature" }; feature.geometry = buildGeom(item, params); feature.properties = propFunc.call(item); return feature; }
[ "function", "getFeature", "(", "args", ")", "{", "var", "item", "=", "args", ".", "item", ",", "params", "=", "args", ".", "params", ",", "propFunc", "=", "args", ".", "propFunc", ";", "var", "feature", "=", "{", "\"type\"", ":", "\"Feature\"", "}", ";", "feature", ".", "geometry", "=", "buildGeom", "(", "item", ",", "params", ")", ";", "feature", ".", "properties", "=", "propFunc", ".", "call", "(", "item", ")", ";", "return", "feature", ";", "}" ]
Creates a feature object to be added to the GeoJSON features array
[ "Creates", "a", "feature", "object", "to", "be", "added", "to", "the", "GeoJSON", "features", "array" ]
92c8cc50548b3c34716c5b82ef96de64ff4ff482
https://github.com/caseycesari/GeoJSON.js/blob/92c8cc50548b3c34716c5b82ef96de64ff4ff482/geojson.js#L158-L169
15,439
caseycesari/GeoJSON.js
geojson.js
getPropFunction
function getPropFunction(params) { var func; if(!params.exclude && !params.include) { func = function(properties) { for(var attr in this) { if(this.hasOwnProperty(attr) && (geomAttrs.indexOf(attr) === -1)) { properties[attr] = this[attr]; } } }; } else if(params.include) { func = function(properties) { params.include.forEach(function(attr){ properties[attr] = this[attr]; }, this); }; } else if(params.exclude) { func = function(properties) { for(var attr in this) { if(this.hasOwnProperty(attr) && (geomAttrs.indexOf(attr) === -1) && (params.exclude.indexOf(attr) === -1)) { properties[attr] = this[attr]; } } }; } return function() { var properties = {}; func.call(this, properties); if(params.extra) { addExtra(properties, params.extra); } return properties; }; }
javascript
function getPropFunction(params) { var func; if(!params.exclude && !params.include) { func = function(properties) { for(var attr in this) { if(this.hasOwnProperty(attr) && (geomAttrs.indexOf(attr) === -1)) { properties[attr] = this[attr]; } } }; } else if(params.include) { func = function(properties) { params.include.forEach(function(attr){ properties[attr] = this[attr]; }, this); }; } else if(params.exclude) { func = function(properties) { for(var attr in this) { if(this.hasOwnProperty(attr) && (geomAttrs.indexOf(attr) === -1) && (params.exclude.indexOf(attr) === -1)) { properties[attr] = this[attr]; } } }; } return function() { var properties = {}; func.call(this, properties); if(params.extra) { addExtra(properties, params.extra); } return properties; }; }
[ "function", "getPropFunction", "(", "params", ")", "{", "var", "func", ";", "if", "(", "!", "params", ".", "exclude", "&&", "!", "params", ".", "include", ")", "{", "func", "=", "function", "(", "properties", ")", "{", "for", "(", "var", "attr", "in", "this", ")", "{", "if", "(", "this", ".", "hasOwnProperty", "(", "attr", ")", "&&", "(", "geomAttrs", ".", "indexOf", "(", "attr", ")", "===", "-", "1", ")", ")", "{", "properties", "[", "attr", "]", "=", "this", "[", "attr", "]", ";", "}", "}", "}", ";", "}", "else", "if", "(", "params", ".", "include", ")", "{", "func", "=", "function", "(", "properties", ")", "{", "params", ".", "include", ".", "forEach", "(", "function", "(", "attr", ")", "{", "properties", "[", "attr", "]", "=", "this", "[", "attr", "]", ";", "}", ",", "this", ")", ";", "}", ";", "}", "else", "if", "(", "params", ".", "exclude", ")", "{", "func", "=", "function", "(", "properties", ")", "{", "for", "(", "var", "attr", "in", "this", ")", "{", "if", "(", "this", ".", "hasOwnProperty", "(", "attr", ")", "&&", "(", "geomAttrs", ".", "indexOf", "(", "attr", ")", "===", "-", "1", ")", "&&", "(", "params", ".", "exclude", ".", "indexOf", "(", "attr", ")", "===", "-", "1", ")", ")", "{", "properties", "[", "attr", "]", "=", "this", "[", "attr", "]", ";", "}", "}", "}", ";", "}", "return", "function", "(", ")", "{", "var", "properties", "=", "{", "}", ";", "func", ".", "call", "(", "this", ",", "properties", ")", ";", "if", "(", "params", ".", "extra", ")", "{", "addExtra", "(", "properties", ",", "params", ".", "extra", ")", ";", "}", "return", "properties", ";", "}", ";", "}" ]
Returns the function to be used to build the properties object for each feature
[ "Returns", "the", "function", "to", "be", "used", "to", "build", "the", "properties", "object", "for", "each", "feature" ]
92c8cc50548b3c34716c5b82ef96de64ff4ff482
https://github.com/caseycesari/GeoJSON.js/blob/92c8cc50548b3c34716c5b82ef96de64ff4ff482/geojson.js#L278-L313
15,440
caseycesari/GeoJSON.js
geojson.js
addExtra
function addExtra(properties, extra) { for(var key in extra){ if(extra.hasOwnProperty(key)) { properties[key] = extra[key]; } } return properties; }
javascript
function addExtra(properties, extra) { for(var key in extra){ if(extra.hasOwnProperty(key)) { properties[key] = extra[key]; } } return properties; }
[ "function", "addExtra", "(", "properties", ",", "extra", ")", "{", "for", "(", "var", "key", "in", "extra", ")", "{", "if", "(", "extra", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "properties", "[", "key", "]", "=", "extra", "[", "key", "]", ";", "}", "}", "return", "properties", ";", "}" ]
Adds data contained in the `extra` parameter if it has been specified
[ "Adds", "data", "contained", "in", "the", "extra", "parameter", "if", "it", "has", "been", "specified" ]
92c8cc50548b3c34716c5b82ef96de64ff4ff482
https://github.com/caseycesari/GeoJSON.js/blob/92c8cc50548b3c34716c5b82ef96de64ff4ff482/geojson.js#L317-L325
15,441
jdxcode/npm-register
lib/packages.js
fetchAllDependents
async function fetchAllDependents (name) { let pkg = await npm.getLatest(name) let deps = Object.keys(pkg.dependencies || {}) if (!deps.length) return [] let promises = [] for (let dep of deps) { promises.push(fetchAllDependents(dep)) } for (let subdeps of await Promise.all(promises)) { deps = deps.concat(subdeps) } return _.uniq(deps.sort()) }
javascript
async function fetchAllDependents (name) { let pkg = await npm.getLatest(name) let deps = Object.keys(pkg.dependencies || {}) if (!deps.length) return [] let promises = [] for (let dep of deps) { promises.push(fetchAllDependents(dep)) } for (let subdeps of await Promise.all(promises)) { deps = deps.concat(subdeps) } return _.uniq(deps.sort()) }
[ "async", "function", "fetchAllDependents", "(", "name", ")", "{", "let", "pkg", "=", "await", "npm", ".", "getLatest", "(", "name", ")", "let", "deps", "=", "Object", ".", "keys", "(", "pkg", ".", "dependencies", "||", "{", "}", ")", "if", "(", "!", "deps", ".", "length", ")", "return", "[", "]", "let", "promises", "=", "[", "]", "for", "(", "let", "dep", "of", "deps", ")", "{", "promises", ".", "push", "(", "fetchAllDependents", "(", "dep", ")", ")", "}", "for", "(", "let", "subdeps", "of", "await", "Promise", ".", "all", "(", "promises", ")", ")", "{", "deps", "=", "deps", ".", "concat", "(", "subdeps", ")", "}", "return", "_", ".", "uniq", "(", "deps", ".", "sort", "(", ")", ")", "}" ]
traverses finding all dependents of a package
[ "traverses", "finding", "all", "dependents", "of", "a", "package" ]
43a5015af5f8b14110ce0faddb14504fc8bca20f
https://github.com/jdxcode/npm-register/blob/43a5015af5f8b14110ce0faddb14504fc8bca20f/lib/packages.js#L40-L52
15,442
infor-design/design-system
scripts/node/build-icons.js
createIconFiles
function createIconFiles(srcFile, dest) { const thisTaskName = swlog.logSubStart('create icon files'); return new Promise(resolve => { const exportArtboardsOptions = [ 'export', 'artboards', srcFile, `--formats=${options.iconFormats.join(',')}`, '--include-symbols=NO', '--save-for-web=YES', `--output=${dest}` ]; const outputStr = sketchtoolExec(exportArtboardsOptions.join(' ')); resolve(outputStr); }) .then(output => { options.iconFormats.forEach(format => { const regex = new RegExp(`\\.${format}`, 'g'); const count = (output.match(regex) || []).length; swlog.logTaskAction('Created', `${count} ${format.toUpperCase()} files`); }) swlog.logSubEnd(thisTaskName); if (options.iconFormats.indexOf('svg') !== -1) { return optimizeSVGs(dest); } }); }
javascript
function createIconFiles(srcFile, dest) { const thisTaskName = swlog.logSubStart('create icon files'); return new Promise(resolve => { const exportArtboardsOptions = [ 'export', 'artboards', srcFile, `--formats=${options.iconFormats.join(',')}`, '--include-symbols=NO', '--save-for-web=YES', `--output=${dest}` ]; const outputStr = sketchtoolExec(exportArtboardsOptions.join(' ')); resolve(outputStr); }) .then(output => { options.iconFormats.forEach(format => { const regex = new RegExp(`\\.${format}`, 'g'); const count = (output.match(regex) || []).length; swlog.logTaskAction('Created', `${count} ${format.toUpperCase()} files`); }) swlog.logSubEnd(thisTaskName); if (options.iconFormats.indexOf('svg') !== -1) { return optimizeSVGs(dest); } }); }
[ "function", "createIconFiles", "(", "srcFile", ",", "dest", ")", "{", "const", "thisTaskName", "=", "swlog", ".", "logSubStart", "(", "'create icon files'", ")", ";", "return", "new", "Promise", "(", "resolve", "=>", "{", "const", "exportArtboardsOptions", "=", "[", "'export'", ",", "'artboards'", ",", "srcFile", ",", "`", "${", "options", ".", "iconFormats", ".", "join", "(", "','", ")", "}", "`", ",", "'--include-symbols=NO'", ",", "'--save-for-web=YES'", ",", "`", "${", "dest", "}", "`", "]", ";", "const", "outputStr", "=", "sketchtoolExec", "(", "exportArtboardsOptions", ".", "join", "(", "' '", ")", ")", ";", "resolve", "(", "outputStr", ")", ";", "}", ")", ".", "then", "(", "output", "=>", "{", "options", ".", "iconFormats", ".", "forEach", "(", "format", "=>", "{", "const", "regex", "=", "new", "RegExp", "(", "`", "\\\\", "${", "format", "}", "`", ",", "'g'", ")", ";", "const", "count", "=", "(", "output", ".", "match", "(", "regex", ")", "||", "[", "]", ")", ".", "length", ";", "swlog", ".", "logTaskAction", "(", "'Created'", ",", "`", "${", "count", "}", "${", "format", ".", "toUpperCase", "(", ")", "}", "`", ")", ";", "}", ")", "swlog", ".", "logSubEnd", "(", "thisTaskName", ")", ";", "if", "(", "options", ".", "iconFormats", ".", "indexOf", "(", "'svg'", ")", "!==", "-", "1", ")", "{", "return", "optimizeSVGs", "(", "dest", ")", ";", "}", "}", ")", ";", "}" ]
Create the svg files form sketch layers @see {@link https://developer.sketchapp.com/reference/api/#export} @param {String} srcFile - The sketch file @param {String} dest - The destination @returns {Promise}
[ "Create", "the", "svg", "files", "form", "sketch", "layers" ]
94fb5321415bf2555808d4d56ba88b342fb6b3e4
https://github.com/infor-design/design-system/blob/94fb5321415bf2555808d4d56ba88b342fb6b3e4/scripts/node/build-icons.js#L105-L135
15,443
infor-design/design-system
scripts/node/build-icons.js
sortByFileFormat
function sortByFileFormat(srcDir, format) { const initialFiles = `${srcDir}/*.${format}` const files = glob.sync(initialFiles); const dest = `${srcDir}/${format}`; let count = 0; createDirs([dest]); // Loop through and move each file const promises = files.map(f => { return new Promise((resolve, reject) => { const filename = sanitize(path.basename(f)); const reg = /[\w-]+-(16|24|32)\.[\w]+/; const match = filename.match(reg); let thisDest = dest; if (match) { const size = match[1]; thisDest = `${thisDest}/${size}`; createDirs([thisDest]); } fs.rename(f, `${thisDest}/${filename}`, err => { if (err) { reject(err); } count++; resolve(`${dest}/${filename}`); }); }); }); return Promise.all(promises).then(() => { swlog.logTaskAction('Moved', `${count}/${files.length} ${format.toUpperCase()} files`); }); }
javascript
function sortByFileFormat(srcDir, format) { const initialFiles = `${srcDir}/*.${format}` const files = glob.sync(initialFiles); const dest = `${srcDir}/${format}`; let count = 0; createDirs([dest]); // Loop through and move each file const promises = files.map(f => { return new Promise((resolve, reject) => { const filename = sanitize(path.basename(f)); const reg = /[\w-]+-(16|24|32)\.[\w]+/; const match = filename.match(reg); let thisDest = dest; if (match) { const size = match[1]; thisDest = `${thisDest}/${size}`; createDirs([thisDest]); } fs.rename(f, `${thisDest}/${filename}`, err => { if (err) { reject(err); } count++; resolve(`${dest}/${filename}`); }); }); }); return Promise.all(promises).then(() => { swlog.logTaskAction('Moved', `${count}/${files.length} ${format.toUpperCase()} files`); }); }
[ "function", "sortByFileFormat", "(", "srcDir", ",", "format", ")", "{", "const", "initialFiles", "=", "`", "${", "srcDir", "}", "${", "format", "}", "`", "const", "files", "=", "glob", ".", "sync", "(", "initialFiles", ")", ";", "const", "dest", "=", "`", "${", "srcDir", "}", "${", "format", "}", "`", ";", "let", "count", "=", "0", ";", "createDirs", "(", "[", "dest", "]", ")", ";", "// Loop through and move each file", "const", "promises", "=", "files", ".", "map", "(", "f", "=>", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "filename", "=", "sanitize", "(", "path", ".", "basename", "(", "f", ")", ")", ";", "const", "reg", "=", "/", "[\\w-]+-(16|24|32)\\.[\\w]+", "/", ";", "const", "match", "=", "filename", ".", "match", "(", "reg", ")", ";", "let", "thisDest", "=", "dest", ";", "if", "(", "match", ")", "{", "const", "size", "=", "match", "[", "1", "]", ";", "thisDest", "=", "`", "${", "thisDest", "}", "${", "size", "}", "`", ";", "createDirs", "(", "[", "thisDest", "]", ")", ";", "}", "fs", ".", "rename", "(", "f", ",", "`", "${", "thisDest", "}", "${", "filename", "}", "`", ",", "err", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "count", "++", ";", "resolve", "(", "`", "${", "dest", "}", "${", "filename", "}", "`", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "return", "Promise", ".", "all", "(", "promises", ")", ".", "then", "(", "(", ")", "=>", "{", "swlog", ".", "logTaskAction", "(", "'Moved'", ",", "`", "${", "count", "}", "${", "files", ".", "length", "}", "${", "format", ".", "toUpperCase", "(", ")", "}", "`", ")", ";", "}", ")", ";", "}" ]
Move icon types into proper directory @param {String} srcDir - Directory of files @param {Array} formats - Array of file formats
[ "Move", "icon", "types", "into", "proper", "directory" ]
94fb5321415bf2555808d4d56ba88b342fb6b3e4
https://github.com/infor-design/design-system/blob/94fb5321415bf2555808d4d56ba88b342fb6b3e4/scripts/node/build-icons.js#L150-L185
15,444
infor-design/design-system
scripts/node/build-icons.js
createPagesMetadata
function createPagesMetadata(src, dest) { return new Promise((resolve, reject) => { const thisTaskName = swlog.logSubStart('create metadata file'); const outputStr = sketchtoolExec(`metadata ${src}`) const ignoredPages = ['Symbols', 'Icon Sheet', '------------'] let customObj = { categories: [] }; const dataObj = JSON.parse(outputStr); // Loop through pages, then arboards, to create a // simple mapping of names (ignoring certain pages) // and naming pages "categories" and artboards "icons" for (const pageId in dataObj.pagesAndArtboards) { if (dataObj.pagesAndArtboards.hasOwnProperty(pageId) && ! ignoredPages.includes(dataObj.pagesAndArtboards[pageId].name)) { const tempObj = { name: dataObj.pagesAndArtboards[pageId].name, icons: [] }; for (const ab in dataObj.pagesAndArtboards[pageId].artboards) { if (dataObj.pagesAndArtboards[pageId].artboards.hasOwnProperty(ab)) { tempObj.icons.push(dataObj.pagesAndArtboards[pageId].artboards[ab].name); } } tempObj.icons.sort(); customObj.categories.push(tempObj); } } fs.writeFileSync(`${dest}/metadata.json`, JSON.stringify(customObj, null, 4), 'utf-8'); swlog.logSubEnd(thisTaskName); resolve(); }); }
javascript
function createPagesMetadata(src, dest) { return new Promise((resolve, reject) => { const thisTaskName = swlog.logSubStart('create metadata file'); const outputStr = sketchtoolExec(`metadata ${src}`) const ignoredPages = ['Symbols', 'Icon Sheet', '------------'] let customObj = { categories: [] }; const dataObj = JSON.parse(outputStr); // Loop through pages, then arboards, to create a // simple mapping of names (ignoring certain pages) // and naming pages "categories" and artboards "icons" for (const pageId in dataObj.pagesAndArtboards) { if (dataObj.pagesAndArtboards.hasOwnProperty(pageId) && ! ignoredPages.includes(dataObj.pagesAndArtboards[pageId].name)) { const tempObj = { name: dataObj.pagesAndArtboards[pageId].name, icons: [] }; for (const ab in dataObj.pagesAndArtboards[pageId].artboards) { if (dataObj.pagesAndArtboards[pageId].artboards.hasOwnProperty(ab)) { tempObj.icons.push(dataObj.pagesAndArtboards[pageId].artboards[ab].name); } } tempObj.icons.sort(); customObj.categories.push(tempObj); } } fs.writeFileSync(`${dest}/metadata.json`, JSON.stringify(customObj, null, 4), 'utf-8'); swlog.logSubEnd(thisTaskName); resolve(); }); }
[ "function", "createPagesMetadata", "(", "src", ",", "dest", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "thisTaskName", "=", "swlog", ".", "logSubStart", "(", "'create metadata file'", ")", ";", "const", "outputStr", "=", "sketchtoolExec", "(", "`", "${", "src", "}", "`", ")", "const", "ignoredPages", "=", "[", "'Symbols'", ",", "'Icon Sheet'", ",", "'------------'", "]", "let", "customObj", "=", "{", "categories", ":", "[", "]", "}", ";", "const", "dataObj", "=", "JSON", ".", "parse", "(", "outputStr", ")", ";", "// Loop through pages, then arboards, to create a", "// simple mapping of names (ignoring certain pages)", "// and naming pages \"categories\" and artboards \"icons\"", "for", "(", "const", "pageId", "in", "dataObj", ".", "pagesAndArtboards", ")", "{", "if", "(", "dataObj", ".", "pagesAndArtboards", ".", "hasOwnProperty", "(", "pageId", ")", "&&", "!", "ignoredPages", ".", "includes", "(", "dataObj", ".", "pagesAndArtboards", "[", "pageId", "]", ".", "name", ")", ")", "{", "const", "tempObj", "=", "{", "name", ":", "dataObj", ".", "pagesAndArtboards", "[", "pageId", "]", ".", "name", ",", "icons", ":", "[", "]", "}", ";", "for", "(", "const", "ab", "in", "dataObj", ".", "pagesAndArtboards", "[", "pageId", "]", ".", "artboards", ")", "{", "if", "(", "dataObj", ".", "pagesAndArtboards", "[", "pageId", "]", ".", "artboards", ".", "hasOwnProperty", "(", "ab", ")", ")", "{", "tempObj", ".", "icons", ".", "push", "(", "dataObj", ".", "pagesAndArtboards", "[", "pageId", "]", ".", "artboards", "[", "ab", "]", ".", "name", ")", ";", "}", "}", "tempObj", ".", "icons", ".", "sort", "(", ")", ";", "customObj", ".", "categories", ".", "push", "(", "tempObj", ")", ";", "}", "}", "fs", ".", "writeFileSync", "(", "`", "${", "dest", "}", "`", ",", "JSON", ".", "stringify", "(", "customObj", ",", "null", ",", "4", ")", ",", "'utf-8'", ")", ";", "swlog", ".", "logSubEnd", "(", "thisTaskName", ")", ";", "resolve", "(", ")", ";", "}", ")", ";", "}" ]
Get the metadata from the sketch file to map icons names to page names @param {String} src - The source of the sketch file @param {String} dest - The destination @returns {Promise}
[ "Get", "the", "metadata", "from", "the", "sketch", "file", "to", "map", "icons", "names", "to", "page", "names" ]
94fb5321415bf2555808d4d56ba88b342fb6b3e4
https://github.com/infor-design/design-system/blob/94fb5321415bf2555808d4d56ba88b342fb6b3e4/scripts/node/build-icons.js#L194-L228
15,445
infor-design/design-system
scripts/node/build-icons.js
createDirs
function createDirs(arrPaths) { arrPaths.forEach(path => { if (!fs.existsSync(path)) { fs.mkdirSync(path); } }); }
javascript
function createDirs(arrPaths) { arrPaths.forEach(path => { if (!fs.existsSync(path)) { fs.mkdirSync(path); } }); }
[ "function", "createDirs", "(", "arrPaths", ")", "{", "arrPaths", ".", "forEach", "(", "path", "=>", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "path", ")", ")", "{", "fs", ".", "mkdirSync", "(", "path", ")", ";", "}", "}", ")", ";", "}" ]
Create directories if they don't exist @param {array} arrPaths - the directory path(s)
[ "Create", "directories", "if", "they", "don", "t", "exist" ]
94fb5321415bf2555808d4d56ba88b342fb6b3e4
https://github.com/infor-design/design-system/blob/94fb5321415bf2555808d4d56ba88b342fb6b3e4/scripts/node/build-icons.js#L234-L240
15,446
infor-design/design-system
scripts/node/build-icons.js
optimizeSVGs
function optimizeSVGs(src) { const startOptimizeTaskName = swlog.logSubStart('optimize SVGs'); // Optimize with svgo: const svgoOptimize = new svgo({ js2svg: { useShortTags: false }, plugins: [ { removeViewBox: false }, { convertColors: { currentColor: '#000000' }}, { removeDimensions: true }, { moveGroupAttrsToElems: true }, { removeUselessStrokeAndFill: true }, { customSvgoRemoveGroupFill }, { customSvgoNonScalingStroke }, { customSvgoFillStroke } ] }); const svgFiles = glob.sync(`${src}/*.svg`); // Divide each optimization into a promise const svgPromises = svgFiles.map(async filepath => { try { const data = await readFile(filepath, 'utf8'); const dataOptimized = await svgoOptimize.optimize(data); await writeFile(filepath, dataOptimized.data, 'utf-8'); } catch(err) { swlog.error(err); } }); return Promise.all(svgPromises).then(() => { swlog.logSubEnd(startOptimizeTaskName); }).catch(swlog.error); }
javascript
function optimizeSVGs(src) { const startOptimizeTaskName = swlog.logSubStart('optimize SVGs'); // Optimize with svgo: const svgoOptimize = new svgo({ js2svg: { useShortTags: false }, plugins: [ { removeViewBox: false }, { convertColors: { currentColor: '#000000' }}, { removeDimensions: true }, { moveGroupAttrsToElems: true }, { removeUselessStrokeAndFill: true }, { customSvgoRemoveGroupFill }, { customSvgoNonScalingStroke }, { customSvgoFillStroke } ] }); const svgFiles = glob.sync(`${src}/*.svg`); // Divide each optimization into a promise const svgPromises = svgFiles.map(async filepath => { try { const data = await readFile(filepath, 'utf8'); const dataOptimized = await svgoOptimize.optimize(data); await writeFile(filepath, dataOptimized.data, 'utf-8'); } catch(err) { swlog.error(err); } }); return Promise.all(svgPromises).then(() => { swlog.logSubEnd(startOptimizeTaskName); }).catch(swlog.error); }
[ "function", "optimizeSVGs", "(", "src", ")", "{", "const", "startOptimizeTaskName", "=", "swlog", ".", "logSubStart", "(", "'optimize SVGs'", ")", ";", "// Optimize with svgo:", "const", "svgoOptimize", "=", "new", "svgo", "(", "{", "js2svg", ":", "{", "useShortTags", ":", "false", "}", ",", "plugins", ":", "[", "{", "removeViewBox", ":", "false", "}", ",", "{", "convertColors", ":", "{", "currentColor", ":", "'#000000'", "}", "}", ",", "{", "removeDimensions", ":", "true", "}", ",", "{", "moveGroupAttrsToElems", ":", "true", "}", ",", "{", "removeUselessStrokeAndFill", ":", "true", "}", ",", "{", "customSvgoRemoveGroupFill", "}", ",", "{", "customSvgoNonScalingStroke", "}", ",", "{", "customSvgoFillStroke", "}", "]", "}", ")", ";", "const", "svgFiles", "=", "glob", ".", "sync", "(", "`", "${", "src", "}", "`", ")", ";", "// Divide each optimization into a promise", "const", "svgPromises", "=", "svgFiles", ".", "map", "(", "async", "filepath", "=>", "{", "try", "{", "const", "data", "=", "await", "readFile", "(", "filepath", ",", "'utf8'", ")", ";", "const", "dataOptimized", "=", "await", "svgoOptimize", ".", "optimize", "(", "data", ")", ";", "await", "writeFile", "(", "filepath", ",", "dataOptimized", ".", "data", ",", "'utf-8'", ")", ";", "}", "catch", "(", "err", ")", "{", "swlog", ".", "error", "(", "err", ")", ";", "}", "}", ")", ";", "return", "Promise", ".", "all", "(", "svgPromises", ")", ".", "then", "(", "(", ")", "=>", "{", "swlog", ".", "logSubEnd", "(", "startOptimizeTaskName", ")", ";", "}", ")", ".", "catch", "(", "swlog", ".", "error", ")", ";", "}" ]
Optimize the generated .svg icon files @param {String} src - The source directory for svgs
[ "Optimize", "the", "generated", ".", "svg", "icon", "files" ]
94fb5321415bf2555808d4d56ba88b342fb6b3e4
https://github.com/infor-design/design-system/blob/94fb5321415bf2555808d4d56ba88b342fb6b3e4/scripts/node/build-icons.js#L246-L281
15,447
JedWatson/react-hammerjs
gulpfile.js
getBumpTask
function getBumpTask(type) { return function () { return gulp.src(['./package.json', './bower.json']) .pipe(bump({ type: type })) .pipe(gulp.dest('./')); }; }
javascript
function getBumpTask(type) { return function () { return gulp.src(['./package.json', './bower.json']) .pipe(bump({ type: type })) .pipe(gulp.dest('./')); }; }
[ "function", "getBumpTask", "(", "type", ")", "{", "return", "function", "(", ")", "{", "return", "gulp", ".", "src", "(", "[", "'./package.json'", ",", "'./bower.json'", "]", ")", ".", "pipe", "(", "bump", "(", "{", "type", ":", "type", "}", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "'./'", ")", ")", ";", "}", ";", "}" ]
Version bump tasks
[ "Version", "bump", "tasks" ]
14500eb2583654fac843ee9bd40f48fd4a65e818
https://github.com/JedWatson/react-hammerjs/blob/14500eb2583654fac843ee9bd40f48fd4a65e818/gulpfile.js#L86-L92
15,448
pat310/google-trends-api
src/request.js
rereq
function rereq(options, done) { let req; req = https.request(options, (res) => { let chunk = ''; res.on('data', (data) => { chunk += data; }); res.on('end', () => { done(null, chunk.toString('utf8')); }); }); req.on('error', (e) => { done(e); }); req.end(); }
javascript
function rereq(options, done) { let req; req = https.request(options, (res) => { let chunk = ''; res.on('data', (data) => { chunk += data; }); res.on('end', () => { done(null, chunk.toString('utf8')); }); }); req.on('error', (e) => { done(e); }); req.end(); }
[ "function", "rereq", "(", "options", ",", "done", ")", "{", "let", "req", ";", "req", "=", "https", ".", "request", "(", "options", ",", "(", "res", ")", "=>", "{", "let", "chunk", "=", "''", ";", "res", ".", "on", "(", "'data'", ",", "(", "data", ")", "=>", "{", "chunk", "+=", "data", ";", "}", ")", ";", "res", ".", "on", "(", "'end'", ",", "(", ")", "=>", "{", "done", "(", "null", ",", "chunk", ".", "toString", "(", "'utf8'", ")", ")", ";", "}", ")", ";", "}", ")", ";", "req", ".", "on", "(", "'error'", ",", "(", "e", ")", "=>", "{", "done", "(", "e", ")", ";", "}", ")", ";", "req", ".", "end", "(", ")", ";", "}" ]
simpler request method for avoiding double-promise confusion
[ "simpler", "request", "method", "for", "avoiding", "double", "-", "promise", "confusion" ]
4ccdd273257a91aca27590d3a20e7814ed7cefa2
https://github.com/pat310/google-trends-api/blob/4ccdd273257a91aca27590d3a20e7814ed7cefa2/src/request.js#L9-L26
15,449
shouldjs/should.js
lib/assertion.js
LightAssertionError
function LightAssertionError(options) { merge(this, options); if (!options.message) { Object.defineProperty(this, "message", { get: function() { if (!this._message) { this._message = this.generateMessage(); this.generatedMessage = true; } return this._message; } }); } }
javascript
function LightAssertionError(options) { merge(this, options); if (!options.message) { Object.defineProperty(this, "message", { get: function() { if (!this._message) { this._message = this.generateMessage(); this.generatedMessage = true; } return this._message; } }); } }
[ "function", "LightAssertionError", "(", "options", ")", "{", "merge", "(", "this", ",", "options", ")", ";", "if", "(", "!", "options", ".", "message", ")", "{", "Object", ".", "defineProperty", "(", "this", ",", "\"message\"", ",", "{", "get", ":", "function", "(", ")", "{", "if", "(", "!", "this", ".", "_message", ")", "{", "this", ".", "_message", "=", "this", ".", "generateMessage", "(", ")", ";", "this", ".", "generatedMessage", "=", "true", ";", "}", "return", "this", ".", "_message", ";", "}", "}", ")", ";", "}", "}" ]
a bit hacky way how to get error to do not have stack
[ "a", "bit", "hacky", "way", "how", "to", "get", "error", "to", "do", "not", "have", "stack" ]
690405e879d2a46c3bac38fbfabe1dce3c7de44d
https://github.com/shouldjs/should.js/blob/690405e879d2a46c3bac38fbfabe1dce3c7de44d/lib/assertion.js#L12-L26
15,450
shouldjs/should.js
lib/assertion.js
function(expr) { if (expr) { return this; } var params = this.params; if ("obj" in params && !("actual" in params)) { params.actual = params.obj; } else if (!("obj" in params) && !("actual" in params)) { params.actual = this.obj; } params.stackStartFunction = params.stackStartFunction || this.assert; params.negate = this.negate; params.assertion = this; if (this.light) { throw new LightAssertionError(params); } else { throw new AssertionError(params); } }
javascript
function(expr) { if (expr) { return this; } var params = this.params; if ("obj" in params && !("actual" in params)) { params.actual = params.obj; } else if (!("obj" in params) && !("actual" in params)) { params.actual = this.obj; } params.stackStartFunction = params.stackStartFunction || this.assert; params.negate = this.negate; params.assertion = this; if (this.light) { throw new LightAssertionError(params); } else { throw new AssertionError(params); } }
[ "function", "(", "expr", ")", "{", "if", "(", "expr", ")", "{", "return", "this", ";", "}", "var", "params", "=", "this", ".", "params", ";", "if", "(", "\"obj\"", "in", "params", "&&", "!", "(", "\"actual\"", "in", "params", ")", ")", "{", "params", ".", "actual", "=", "params", ".", "obj", ";", "}", "else", "if", "(", "!", "(", "\"obj\"", "in", "params", ")", "&&", "!", "(", "\"actual\"", "in", "params", ")", ")", "{", "params", ".", "actual", "=", "this", ".", "obj", ";", "}", "params", ".", "stackStartFunction", "=", "params", ".", "stackStartFunction", "||", "this", ".", "assert", ";", "params", ".", "negate", "=", "this", ".", "negate", ";", "params", ".", "assertion", "=", "this", ";", "if", "(", "this", ".", "light", ")", "{", "throw", "new", "LightAssertionError", "(", "params", ")", ";", "}", "else", "{", "throw", "new", "AssertionError", "(", "params", ")", ";", "}", "}" ]
Base method for assertions. Before calling this method need to fill Assertion#params object. This method usually called from other assertion methods. `Assertion#params` can contain such properties: * `operator` - required string containing description of this assertion * `obj` - optional replacement for this.obj, it is useful if you prepare more clear object then given * `message` - if this property filled with string any others will be ignored and this one used as assertion message * `expected` - any object used when you need to assert relation between given object and expected. Like given == expected (== is a relation) * `details` - additional string with details to generated message @memberOf Assertion @category assertion @param {*} expr Any expression that will be used as a condition for asserting. @example var a = new should.Assertion(42); a.params = { operator: 'to be magic number', } a.assert(false); //throws AssertionError: expected 42 to be magic number
[ "Base", "method", "for", "assertions", "." ]
690405e879d2a46c3bac38fbfabe1dce3c7de44d
https://github.com/shouldjs/should.js/blob/690405e879d2a46c3bac38fbfabe1dce3c7de44d/lib/assertion.js#L76-L99
15,451
shouldjs/should.js
should.js
has
function has(obj, key) { var type = getGlobalType(obj); var func = defaultTypeAdaptorStorage.requireAdaptor(type, 'has'); return func(obj, key); }
javascript
function has(obj, key) { var type = getGlobalType(obj); var func = defaultTypeAdaptorStorage.requireAdaptor(type, 'has'); return func(obj, key); }
[ "function", "has", "(", "obj", ",", "key", ")", "{", "var", "type", "=", "getGlobalType", "(", "obj", ")", ";", "var", "func", "=", "defaultTypeAdaptorStorage", ".", "requireAdaptor", "(", "type", ",", "'has'", ")", ";", "return", "func", "(", "obj", ",", "key", ")", ";", "}" ]
return boolean if obj has such 'key'
[ "return", "boolean", "if", "obj", "has", "such", "key" ]
690405e879d2a46c3bac38fbfabe1dce3c7de44d
https://github.com/shouldjs/should.js/blob/690405e879d2a46c3bac38fbfabe1dce3c7de44d/should.js#L856-L860
15,452
shouldjs/should.js
should.js
get
function get(obj, key) { var type = getGlobalType(obj); var func = defaultTypeAdaptorStorage.requireAdaptor(type, 'get'); return func(obj, key); }
javascript
function get(obj, key) { var type = getGlobalType(obj); var func = defaultTypeAdaptorStorage.requireAdaptor(type, 'get'); return func(obj, key); }
[ "function", "get", "(", "obj", ",", "key", ")", "{", "var", "type", "=", "getGlobalType", "(", "obj", ")", ";", "var", "func", "=", "defaultTypeAdaptorStorage", ".", "requireAdaptor", "(", "type", ",", "'get'", ")", ";", "return", "func", "(", "obj", ",", "key", ")", ";", "}" ]
return value for given key
[ "return", "value", "for", "given", "key" ]
690405e879d2a46c3bac38fbfabe1dce3c7de44d
https://github.com/shouldjs/should.js/blob/690405e879d2a46c3bac38fbfabe1dce3c7de44d/should.js#L863-L867
15,453
reworkcss/css
lib/stringify/identity.js
Compiler
function Compiler(options) { options = options || {}; Base.call(this, options); this.indentation = options.indent; }
javascript
function Compiler(options) { options = options || {}; Base.call(this, options); this.indentation = options.indent; }
[ "function", "Compiler", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "Base", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "indentation", "=", "options", ".", "indent", ";", "}" ]
Initialize a new `Compiler`.
[ "Initialize", "a", "new", "Compiler", "." ]
64910e8474385e4fde8cfe5369a9b768f3e08ac5
https://github.com/reworkcss/css/blob/64910e8474385e4fde8cfe5369a9b768f3e08ac5/lib/stringify/identity.js#L19-L23
15,454
reworkcss/css
lib/stringify/source-map-support.js
mixin
function mixin(compiler) { compiler._comment = compiler.comment; compiler.map = new SourceMap(); compiler.position = { line: 1, column: 1 }; compiler.files = {}; for (var k in exports) compiler[k] = exports[k]; }
javascript
function mixin(compiler) { compiler._comment = compiler.comment; compiler.map = new SourceMap(); compiler.position = { line: 1, column: 1 }; compiler.files = {}; for (var k in exports) compiler[k] = exports[k]; }
[ "function", "mixin", "(", "compiler", ")", "{", "compiler", ".", "_comment", "=", "compiler", ".", "comment", ";", "compiler", ".", "map", "=", "new", "SourceMap", "(", ")", ";", "compiler", ".", "position", "=", "{", "line", ":", "1", ",", "column", ":", "1", "}", ";", "compiler", ".", "files", "=", "{", "}", ";", "for", "(", "var", "k", "in", "exports", ")", "compiler", "[", "k", "]", "=", "exports", "[", "k", "]", ";", "}" ]
Mixin source map support into `compiler`. @param {Compiler} compiler @api public
[ "Mixin", "source", "map", "support", "into", "compiler", "." ]
64910e8474385e4fde8cfe5369a9b768f3e08ac5
https://github.com/reworkcss/css/blob/64910e8474385e4fde8cfe5369a9b768f3e08ac5/lib/stringify/source-map-support.js#L26-L32
15,455
reworkcss/css
lib/parse/index.js
updatePosition
function updatePosition(str) { var lines = str.match(/\n/g); if (lines) lineno += lines.length; var i = str.lastIndexOf('\n'); column = ~i ? str.length - i : column + str.length; }
javascript
function updatePosition(str) { var lines = str.match(/\n/g); if (lines) lineno += lines.length; var i = str.lastIndexOf('\n'); column = ~i ? str.length - i : column + str.length; }
[ "function", "updatePosition", "(", "str", ")", "{", "var", "lines", "=", "str", ".", "match", "(", "/", "\\n", "/", "g", ")", ";", "if", "(", "lines", ")", "lineno", "+=", "lines", ".", "length", ";", "var", "i", "=", "str", ".", "lastIndexOf", "(", "'\\n'", ")", ";", "column", "=", "~", "i", "?", "str", ".", "length", "-", "i", ":", "column", "+", "str", ".", "length", ";", "}" ]
Update lineno and column based on `str`.
[ "Update", "lineno", "and", "column", "based", "on", "str", "." ]
64910e8474385e4fde8cfe5369a9b768f3e08ac5
https://github.com/reworkcss/css/blob/64910e8474385e4fde8cfe5369a9b768f3e08ac5/lib/parse/index.js#L19-L24
15,456
reworkcss/css
lib/parse/index.js
Position
function Position(start) { this.start = start; this.end = { line: lineno, column: column }; this.source = options.source; }
javascript
function Position(start) { this.start = start; this.end = { line: lineno, column: column }; this.source = options.source; }
[ "function", "Position", "(", "start", ")", "{", "this", ".", "start", "=", "start", ";", "this", ".", "end", "=", "{", "line", ":", "lineno", ",", "column", ":", "column", "}", ";", "this", ".", "source", "=", "options", ".", "source", ";", "}" ]
Store position information for a node
[ "Store", "position", "information", "for", "a", "node" ]
64910e8474385e4fde8cfe5369a9b768f3e08ac5
https://github.com/reworkcss/css/blob/64910e8474385e4fde8cfe5369a9b768f3e08ac5/lib/parse/index.js#L43-L47
15,457
reworkcss/css
lib/parse/index.js
stylesheet
function stylesheet() { var rulesList = rules(); return { type: 'stylesheet', stylesheet: { source: options.source, rules: rulesList, parsingErrors: errorsList } }; }
javascript
function stylesheet() { var rulesList = rules(); return { type: 'stylesheet', stylesheet: { source: options.source, rules: rulesList, parsingErrors: errorsList } }; }
[ "function", "stylesheet", "(", ")", "{", "var", "rulesList", "=", "rules", "(", ")", ";", "return", "{", "type", ":", "'stylesheet'", ",", "stylesheet", ":", "{", "source", ":", "options", ".", "source", ",", "rules", ":", "rulesList", ",", "parsingErrors", ":", "errorsList", "}", "}", ";", "}" ]
Parse stylesheet.
[ "Parse", "stylesheet", "." ]
64910e8474385e4fde8cfe5369a9b768f3e08ac5
https://github.com/reworkcss/css/blob/64910e8474385e4fde8cfe5369a9b768f3e08ac5/lib/parse/index.js#L80-L91
15,458
reworkcss/css
lib/parse/index.js
rules
function rules() { var node; var rules = []; whitespace(); comments(rules); while (css.length && css.charAt(0) != '}' && (node = atrule() || rule())) { if (node !== false) { rules.push(node); comments(rules); } } return rules; }
javascript
function rules() { var node; var rules = []; whitespace(); comments(rules); while (css.length && css.charAt(0) != '}' && (node = atrule() || rule())) { if (node !== false) { rules.push(node); comments(rules); } } return rules; }
[ "function", "rules", "(", ")", "{", "var", "node", ";", "var", "rules", "=", "[", "]", ";", "whitespace", "(", ")", ";", "comments", "(", "rules", ")", ";", "while", "(", "css", ".", "length", "&&", "css", ".", "charAt", "(", "0", ")", "!=", "'}'", "&&", "(", "node", "=", "atrule", "(", ")", "||", "rule", "(", ")", ")", ")", "{", "if", "(", "node", "!==", "false", ")", "{", "rules", ".", "push", "(", "node", ")", ";", "comments", "(", "rules", ")", ";", "}", "}", "return", "rules", ";", "}" ]
Parse ruleset.
[ "Parse", "ruleset", "." ]
64910e8474385e4fde8cfe5369a9b768f3e08ac5
https://github.com/reworkcss/css/blob/64910e8474385e4fde8cfe5369a9b768f3e08ac5/lib/parse/index.js#L113-L125
15,459
reworkcss/css
lib/parse/index.js
match
function match(re) { var m = re.exec(css); if (!m) return; var str = m[0]; updatePosition(str); css = css.slice(str.length); return m; }
javascript
function match(re) { var m = re.exec(css); if (!m) return; var str = m[0]; updatePosition(str); css = css.slice(str.length); return m; }
[ "function", "match", "(", "re", ")", "{", "var", "m", "=", "re", ".", "exec", "(", "css", ")", ";", "if", "(", "!", "m", ")", "return", ";", "var", "str", "=", "m", "[", "0", "]", ";", "updatePosition", "(", "str", ")", ";", "css", "=", "css", ".", "slice", "(", "str", ".", "length", ")", ";", "return", "m", ";", "}" ]
Match `re` and return captures.
[ "Match", "re", "and", "return", "captures", "." ]
64910e8474385e4fde8cfe5369a9b768f3e08ac5
https://github.com/reworkcss/css/blob/64910e8474385e4fde8cfe5369a9b768f3e08ac5/lib/parse/index.js#L131-L138
15,460
reworkcss/css
lib/parse/index.js
comments
function comments(rules) { var c; rules = rules || []; while (c = comment()) { if (c !== false) { rules.push(c); } } return rules; }
javascript
function comments(rules) { var c; rules = rules || []; while (c = comment()) { if (c !== false) { rules.push(c); } } return rules; }
[ "function", "comments", "(", "rules", ")", "{", "var", "c", ";", "rules", "=", "rules", "||", "[", "]", ";", "while", "(", "c", "=", "comment", "(", ")", ")", "{", "if", "(", "c", "!==", "false", ")", "{", "rules", ".", "push", "(", "c", ")", ";", "}", "}", "return", "rules", ";", "}" ]
Parse comments;
[ "Parse", "comments", ";" ]
64910e8474385e4fde8cfe5369a9b768f3e08ac5
https://github.com/reworkcss/css/blob/64910e8474385e4fde8cfe5369a9b768f3e08ac5/lib/parse/index.js#L152-L161
15,461
reworkcss/css
lib/parse/index.js
comment
function comment() { var pos = position(); if ('/' != css.charAt(0) || '*' != css.charAt(1)) return; var i = 2; while ("" != css.charAt(i) && ('*' != css.charAt(i) || '/' != css.charAt(i + 1))) ++i; i += 2; if ("" === css.charAt(i-1)) { return error('End of comment missing'); } var str = css.slice(2, i - 2); column += 2; updatePosition(str); css = css.slice(i); column += 2; return pos({ type: 'comment', comment: str }); }
javascript
function comment() { var pos = position(); if ('/' != css.charAt(0) || '*' != css.charAt(1)) return; var i = 2; while ("" != css.charAt(i) && ('*' != css.charAt(i) || '/' != css.charAt(i + 1))) ++i; i += 2; if ("" === css.charAt(i-1)) { return error('End of comment missing'); } var str = css.slice(2, i - 2); column += 2; updatePosition(str); css = css.slice(i); column += 2; return pos({ type: 'comment', comment: str }); }
[ "function", "comment", "(", ")", "{", "var", "pos", "=", "position", "(", ")", ";", "if", "(", "'/'", "!=", "css", ".", "charAt", "(", "0", ")", "||", "'*'", "!=", "css", ".", "charAt", "(", "1", ")", ")", "return", ";", "var", "i", "=", "2", ";", "while", "(", "\"\"", "!=", "css", ".", "charAt", "(", "i", ")", "&&", "(", "'*'", "!=", "css", ".", "charAt", "(", "i", ")", "||", "'/'", "!=", "css", ".", "charAt", "(", "i", "+", "1", ")", ")", ")", "++", "i", ";", "i", "+=", "2", ";", "if", "(", "\"\"", "===", "css", ".", "charAt", "(", "i", "-", "1", ")", ")", "{", "return", "error", "(", "'End of comment missing'", ")", ";", "}", "var", "str", "=", "css", ".", "slice", "(", "2", ",", "i", "-", "2", ")", ";", "column", "+=", "2", ";", "updatePosition", "(", "str", ")", ";", "css", "=", "css", ".", "slice", "(", "i", ")", ";", "column", "+=", "2", ";", "return", "pos", "(", "{", "type", ":", "'comment'", ",", "comment", ":", "str", "}", ")", ";", "}" ]
Parse comment.
[ "Parse", "comment", "." ]
64910e8474385e4fde8cfe5369a9b768f3e08ac5
https://github.com/reworkcss/css/blob/64910e8474385e4fde8cfe5369a9b768f3e08ac5/lib/parse/index.js#L167-L189
15,462
reworkcss/css
lib/parse/index.js
selector
function selector() { var m = match(/^([^{]+)/); if (!m) return; /* @fix Remove all comments from selectors * http://ostermiller.org/findcomment.html */ return trim(m[0]) .replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g, '') .replace(/"(?:\\"|[^"])*"|'(?:\\'|[^'])*'/g, function(m) { return m.replace(/,/g, '\u200C'); }) .split(/\s*(?![^(]*\)),\s*/) .map(function(s) { return s.replace(/\u200C/g, ','); }); }
javascript
function selector() { var m = match(/^([^{]+)/); if (!m) return; /* @fix Remove all comments from selectors * http://ostermiller.org/findcomment.html */ return trim(m[0]) .replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g, '') .replace(/"(?:\\"|[^"])*"|'(?:\\'|[^'])*'/g, function(m) { return m.replace(/,/g, '\u200C'); }) .split(/\s*(?![^(]*\)),\s*/) .map(function(s) { return s.replace(/\u200C/g, ','); }); }
[ "function", "selector", "(", ")", "{", "var", "m", "=", "match", "(", "/", "^([^{]+)", "/", ")", ";", "if", "(", "!", "m", ")", "return", ";", "/* @fix Remove all comments from selectors\n * http://ostermiller.org/findcomment.html */", "return", "trim", "(", "m", "[", "0", "]", ")", ".", "replace", "(", "/", "\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+", "/", "g", ",", "''", ")", ".", "replace", "(", "/", "\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'", "/", "g", ",", "function", "(", "m", ")", "{", "return", "m", ".", "replace", "(", "/", ",", "/", "g", ",", "'\\u200C'", ")", ";", "}", ")", ".", "split", "(", "/", "\\s*(?![^(]*\\)),\\s*", "/", ")", ".", "map", "(", "function", "(", "s", ")", "{", "return", "s", ".", "replace", "(", "/", "\\u200C", "/", "g", ",", "','", ")", ";", "}", ")", ";", "}" ]
Parse selector.
[ "Parse", "selector", "." ]
64910e8474385e4fde8cfe5369a9b768f3e08ac5
https://github.com/reworkcss/css/blob/64910e8474385e4fde8cfe5369a9b768f3e08ac5/lib/parse/index.js#L195-L209
15,463
reworkcss/css
lib/parse/index.js
declarations
function declarations() { var decls = []; if (!open()) return error("missing '{'"); comments(decls); // declarations var decl; while (decl = declaration()) { if (decl !== false) { decls.push(decl); comments(decls); } } if (!close()) return error("missing '}'"); return decls; }
javascript
function declarations() { var decls = []; if (!open()) return error("missing '{'"); comments(decls); // declarations var decl; while (decl = declaration()) { if (decl !== false) { decls.push(decl); comments(decls); } } if (!close()) return error("missing '}'"); return decls; }
[ "function", "declarations", "(", ")", "{", "var", "decls", "=", "[", "]", ";", "if", "(", "!", "open", "(", ")", ")", "return", "error", "(", "\"missing '{'\"", ")", ";", "comments", "(", "decls", ")", ";", "// declarations", "var", "decl", ";", "while", "(", "decl", "=", "declaration", "(", ")", ")", "{", "if", "(", "decl", "!==", "false", ")", "{", "decls", ".", "push", "(", "decl", ")", ";", "comments", "(", "decls", ")", ";", "}", "}", "if", "(", "!", "close", "(", ")", ")", "return", "error", "(", "\"missing '}'\"", ")", ";", "return", "decls", ";", "}" ]
Parse declarations.
[ "Parse", "declarations", "." ]
64910e8474385e4fde8cfe5369a9b768f3e08ac5
https://github.com/reworkcss/css/blob/64910e8474385e4fde8cfe5369a9b768f3e08ac5/lib/parse/index.js#L245-L262
15,464
reworkcss/css
lib/parse/index.js
keyframe
function keyframe() { var m; var vals = []; var pos = position(); while (m = match(/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/)) { vals.push(m[1]); match(/^,\s*/); } if (!vals.length) return; return pos({ type: 'keyframe', values: vals, declarations: declarations() }); }
javascript
function keyframe() { var m; var vals = []; var pos = position(); while (m = match(/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/)) { vals.push(m[1]); match(/^,\s*/); } if (!vals.length) return; return pos({ type: 'keyframe', values: vals, declarations: declarations() }); }
[ "function", "keyframe", "(", ")", "{", "var", "m", ";", "var", "vals", "=", "[", "]", ";", "var", "pos", "=", "position", "(", ")", ";", "while", "(", "m", "=", "match", "(", "/", "^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*", "/", ")", ")", "{", "vals", ".", "push", "(", "m", "[", "1", "]", ")", ";", "match", "(", "/", "^,\\s*", "/", ")", ";", "}", "if", "(", "!", "vals", ".", "length", ")", "return", ";", "return", "pos", "(", "{", "type", ":", "'keyframe'", ",", "values", ":", "vals", ",", "declarations", ":", "declarations", "(", ")", "}", ")", ";", "}" ]
Parse keyframe.
[ "Parse", "keyframe", "." ]
64910e8474385e4fde8cfe5369a9b768f3e08ac5
https://github.com/reworkcss/css/blob/64910e8474385e4fde8cfe5369a9b768f3e08ac5/lib/parse/index.js#L268-L285
15,465
reworkcss/css
lib/parse/index.js
atkeyframes
function atkeyframes() { var pos = position(); var m = match(/^@([-\w]+)?keyframes\s*/); if (!m) return; var vendor = m[1]; // identifier var m = match(/^([-\w]+)\s*/); if (!m) return error("@keyframes missing name"); var name = m[1]; if (!open()) return error("@keyframes missing '{'"); var frame; var frames = comments(); while (frame = keyframe()) { frames.push(frame); frames = frames.concat(comments()); } if (!close()) return error("@keyframes missing '}'"); return pos({ type: 'keyframes', name: name, vendor: vendor, keyframes: frames }); }
javascript
function atkeyframes() { var pos = position(); var m = match(/^@([-\w]+)?keyframes\s*/); if (!m) return; var vendor = m[1]; // identifier var m = match(/^([-\w]+)\s*/); if (!m) return error("@keyframes missing name"); var name = m[1]; if (!open()) return error("@keyframes missing '{'"); var frame; var frames = comments(); while (frame = keyframe()) { frames.push(frame); frames = frames.concat(comments()); } if (!close()) return error("@keyframes missing '}'"); return pos({ type: 'keyframes', name: name, vendor: vendor, keyframes: frames }); }
[ "function", "atkeyframes", "(", ")", "{", "var", "pos", "=", "position", "(", ")", ";", "var", "m", "=", "match", "(", "/", "^@([-\\w]+)?keyframes\\s*", "/", ")", ";", "if", "(", "!", "m", ")", "return", ";", "var", "vendor", "=", "m", "[", "1", "]", ";", "// identifier", "var", "m", "=", "match", "(", "/", "^([-\\w]+)\\s*", "/", ")", ";", "if", "(", "!", "m", ")", "return", "error", "(", "\"@keyframes missing name\"", ")", ";", "var", "name", "=", "m", "[", "1", "]", ";", "if", "(", "!", "open", "(", ")", ")", "return", "error", "(", "\"@keyframes missing '{'\"", ")", ";", "var", "frame", ";", "var", "frames", "=", "comments", "(", ")", ";", "while", "(", "frame", "=", "keyframe", "(", ")", ")", "{", "frames", ".", "push", "(", "frame", ")", ";", "frames", "=", "frames", ".", "concat", "(", "comments", "(", ")", ")", ";", "}", "if", "(", "!", "close", "(", ")", ")", "return", "error", "(", "\"@keyframes missing '}'\"", ")", ";", "return", "pos", "(", "{", "type", ":", "'keyframes'", ",", "name", ":", "name", ",", "vendor", ":", "vendor", ",", "keyframes", ":", "frames", "}", ")", ";", "}" ]
Parse keyframes.
[ "Parse", "keyframes", "." ]
64910e8474385e4fde8cfe5369a9b768f3e08ac5
https://github.com/reworkcss/css/blob/64910e8474385e4fde8cfe5369a9b768f3e08ac5/lib/parse/index.js#L291-L320
15,466
reworkcss/css
lib/parse/index.js
atsupports
function atsupports() { var pos = position(); var m = match(/^@supports *([^{]+)/); if (!m) return; var supports = trim(m[1]); if (!open()) return error("@supports missing '{'"); var style = comments().concat(rules()); if (!close()) return error("@supports missing '}'"); return pos({ type: 'supports', supports: supports, rules: style }); }
javascript
function atsupports() { var pos = position(); var m = match(/^@supports *([^{]+)/); if (!m) return; var supports = trim(m[1]); if (!open()) return error("@supports missing '{'"); var style = comments().concat(rules()); if (!close()) return error("@supports missing '}'"); return pos({ type: 'supports', supports: supports, rules: style }); }
[ "function", "atsupports", "(", ")", "{", "var", "pos", "=", "position", "(", ")", ";", "var", "m", "=", "match", "(", "/", "^@supports *([^{]+)", "/", ")", ";", "if", "(", "!", "m", ")", "return", ";", "var", "supports", "=", "trim", "(", "m", "[", "1", "]", ")", ";", "if", "(", "!", "open", "(", ")", ")", "return", "error", "(", "\"@supports missing '{'\"", ")", ";", "var", "style", "=", "comments", "(", ")", ".", "concat", "(", "rules", "(", ")", ")", ";", "if", "(", "!", "close", "(", ")", ")", "return", "error", "(", "\"@supports missing '}'\"", ")", ";", "return", "pos", "(", "{", "type", ":", "'supports'", ",", "supports", ":", "supports", ",", "rules", ":", "style", "}", ")", ";", "}" ]
Parse supports.
[ "Parse", "supports", "." ]
64910e8474385e4fde8cfe5369a9b768f3e08ac5
https://github.com/reworkcss/css/blob/64910e8474385e4fde8cfe5369a9b768f3e08ac5/lib/parse/index.js#L326-L344
15,467
reworkcss/css
lib/parse/index.js
atmedia
function atmedia() { var pos = position(); var m = match(/^@media *([^{]+)/); if (!m) return; var media = trim(m[1]); if (!open()) return error("@media missing '{'"); var style = comments().concat(rules()); if (!close()) return error("@media missing '}'"); return pos({ type: 'media', media: media, rules: style }); }
javascript
function atmedia() { var pos = position(); var m = match(/^@media *([^{]+)/); if (!m) return; var media = trim(m[1]); if (!open()) return error("@media missing '{'"); var style = comments().concat(rules()); if (!close()) return error("@media missing '}'"); return pos({ type: 'media', media: media, rules: style }); }
[ "function", "atmedia", "(", ")", "{", "var", "pos", "=", "position", "(", ")", ";", "var", "m", "=", "match", "(", "/", "^@media *([^{]+)", "/", ")", ";", "if", "(", "!", "m", ")", "return", ";", "var", "media", "=", "trim", "(", "m", "[", "1", "]", ")", ";", "if", "(", "!", "open", "(", ")", ")", "return", "error", "(", "\"@media missing '{'\"", ")", ";", "var", "style", "=", "comments", "(", ")", ".", "concat", "(", "rules", "(", ")", ")", ";", "if", "(", "!", "close", "(", ")", ")", "return", "error", "(", "\"@media missing '}'\"", ")", ";", "return", "pos", "(", "{", "type", ":", "'media'", ",", "media", ":", "media", ",", "rules", ":", "style", "}", ")", ";", "}" ]
Parse media.
[ "Parse", "media", "." ]
64910e8474385e4fde8cfe5369a9b768f3e08ac5
https://github.com/reworkcss/css/blob/64910e8474385e4fde8cfe5369a9b768f3e08ac5/lib/parse/index.js#L372-L390
15,468
reworkcss/css
lib/parse/index.js
atpage
function atpage() { var pos = position(); var m = match(/^@page */); if (!m) return; var sel = selector() || []; if (!open()) return error("@page missing '{'"); var decls = comments(); // declarations var decl; while (decl = declaration()) { decls.push(decl); decls = decls.concat(comments()); } if (!close()) return error("@page missing '}'"); return pos({ type: 'page', selectors: sel, declarations: decls }); }
javascript
function atpage() { var pos = position(); var m = match(/^@page */); if (!m) return; var sel = selector() || []; if (!open()) return error("@page missing '{'"); var decls = comments(); // declarations var decl; while (decl = declaration()) { decls.push(decl); decls = decls.concat(comments()); } if (!close()) return error("@page missing '}'"); return pos({ type: 'page', selectors: sel, declarations: decls }); }
[ "function", "atpage", "(", ")", "{", "var", "pos", "=", "position", "(", ")", ";", "var", "m", "=", "match", "(", "/", "^@page *", "/", ")", ";", "if", "(", "!", "m", ")", "return", ";", "var", "sel", "=", "selector", "(", ")", "||", "[", "]", ";", "if", "(", "!", "open", "(", ")", ")", "return", "error", "(", "\"@page missing '{'\"", ")", ";", "var", "decls", "=", "comments", "(", ")", ";", "// declarations", "var", "decl", ";", "while", "(", "decl", "=", "declaration", "(", ")", ")", "{", "decls", ".", "push", "(", "decl", ")", ";", "decls", "=", "decls", ".", "concat", "(", "comments", "(", ")", ")", ";", "}", "if", "(", "!", "close", "(", ")", ")", "return", "error", "(", "\"@page missing '}'\"", ")", ";", "return", "pos", "(", "{", "type", ":", "'page'", ",", "selectors", ":", "sel", ",", "declarations", ":", "decls", "}", ")", ";", "}" ]
Parse paged media.
[ "Parse", "paged", "media", "." ]
64910e8474385e4fde8cfe5369a9b768f3e08ac5
https://github.com/reworkcss/css/blob/64910e8474385e4fde8cfe5369a9b768f3e08ac5/lib/parse/index.js#L413-L437
15,469
reworkcss/css
lib/parse/index.js
atdocument
function atdocument() { var pos = position(); var m = match(/^@([-\w]+)?document *([^{]+)/); if (!m) return; var vendor = trim(m[1]); var doc = trim(m[2]); if (!open()) return error("@document missing '{'"); var style = comments().concat(rules()); if (!close()) return error("@document missing '}'"); return pos({ type: 'document', document: doc, vendor: vendor, rules: style }); }
javascript
function atdocument() { var pos = position(); var m = match(/^@([-\w]+)?document *([^{]+)/); if (!m) return; var vendor = trim(m[1]); var doc = trim(m[2]); if (!open()) return error("@document missing '{'"); var style = comments().concat(rules()); if (!close()) return error("@document missing '}'"); return pos({ type: 'document', document: doc, vendor: vendor, rules: style }); }
[ "function", "atdocument", "(", ")", "{", "var", "pos", "=", "position", "(", ")", ";", "var", "m", "=", "match", "(", "/", "^@([-\\w]+)?document *([^{]+)", "/", ")", ";", "if", "(", "!", "m", ")", "return", ";", "var", "vendor", "=", "trim", "(", "m", "[", "1", "]", ")", ";", "var", "doc", "=", "trim", "(", "m", "[", "2", "]", ")", ";", "if", "(", "!", "open", "(", ")", ")", "return", "error", "(", "\"@document missing '{'\"", ")", ";", "var", "style", "=", "comments", "(", ")", ".", "concat", "(", "rules", "(", ")", ")", ";", "if", "(", "!", "close", "(", ")", ")", "return", "error", "(", "\"@document missing '}'\"", ")", ";", "return", "pos", "(", "{", "type", ":", "'document'", ",", "document", ":", "doc", ",", "vendor", ":", "vendor", ",", "rules", ":", "style", "}", ")", ";", "}" ]
Parse document.
[ "Parse", "document", "." ]
64910e8474385e4fde8cfe5369a9b768f3e08ac5
https://github.com/reworkcss/css/blob/64910e8474385e4fde8cfe5369a9b768f3e08ac5/lib/parse/index.js#L443-L463
15,470
reworkcss/css
lib/parse/index.js
rule
function rule() { var pos = position(); var sel = selector(); if (!sel) return error('selector missing'); comments(); return pos({ type: 'rule', selectors: sel, declarations: declarations() }); }
javascript
function rule() { var pos = position(); var sel = selector(); if (!sel) return error('selector missing'); comments(); return pos({ type: 'rule', selectors: sel, declarations: declarations() }); }
[ "function", "rule", "(", ")", "{", "var", "pos", "=", "position", "(", ")", ";", "var", "sel", "=", "selector", "(", ")", ";", "if", "(", "!", "sel", ")", "return", "error", "(", "'selector missing'", ")", ";", "comments", "(", ")", ";", "return", "pos", "(", "{", "type", ":", "'rule'", ",", "selectors", ":", "sel", ",", "declarations", ":", "declarations", "(", ")", "}", ")", ";", "}" ]
Parse rule.
[ "Parse", "rule", "." ]
64910e8474385e4fde8cfe5369a9b768f3e08ac5
https://github.com/reworkcss/css/blob/64910e8474385e4fde8cfe5369a9b768f3e08ac5/lib/parse/index.js#L551-L563
15,471
reworkcss/css
lib/parse/index.js
addParent
function addParent(obj, parent) { var isNode = obj && typeof obj.type === 'string'; var childParent = isNode ? obj : parent; for (var k in obj) { var value = obj[k]; if (Array.isArray(value)) { value.forEach(function(v) { addParent(v, childParent); }); } else if (value && typeof value === 'object') { addParent(value, childParent); } } if (isNode) { Object.defineProperty(obj, 'parent', { configurable: true, writable: true, enumerable: false, value: parent || null }); } return obj; }
javascript
function addParent(obj, parent) { var isNode = obj && typeof obj.type === 'string'; var childParent = isNode ? obj : parent; for (var k in obj) { var value = obj[k]; if (Array.isArray(value)) { value.forEach(function(v) { addParent(v, childParent); }); } else if (value && typeof value === 'object') { addParent(value, childParent); } } if (isNode) { Object.defineProperty(obj, 'parent', { configurable: true, writable: true, enumerable: false, value: parent || null }); } return obj; }
[ "function", "addParent", "(", "obj", ",", "parent", ")", "{", "var", "isNode", "=", "obj", "&&", "typeof", "obj", ".", "type", "===", "'string'", ";", "var", "childParent", "=", "isNode", "?", "obj", ":", "parent", ";", "for", "(", "var", "k", "in", "obj", ")", "{", "var", "value", "=", "obj", "[", "k", "]", ";", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "value", ".", "forEach", "(", "function", "(", "v", ")", "{", "addParent", "(", "v", ",", "childParent", ")", ";", "}", ")", ";", "}", "else", "if", "(", "value", "&&", "typeof", "value", "===", "'object'", ")", "{", "addParent", "(", "value", ",", "childParent", ")", ";", "}", "}", "if", "(", "isNode", ")", "{", "Object", ".", "defineProperty", "(", "obj", ",", "'parent'", ",", "{", "configurable", ":", "true", ",", "writable", ":", "true", ",", "enumerable", ":", "false", ",", "value", ":", "parent", "||", "null", "}", ")", ";", "}", "return", "obj", ";", "}" ]
Adds non-enumerable parent node reference to each node.
[ "Adds", "non", "-", "enumerable", "parent", "node", "reference", "to", "each", "node", "." ]
64910e8474385e4fde8cfe5369a9b768f3e08ac5
https://github.com/reworkcss/css/blob/64910e8474385e4fde8cfe5369a9b768f3e08ac5/lib/parse/index.js#L580-L603
15,472
Stanko/react-plx
source/Plx.js
getElementTop
function getElementTop(el) { let top = 0; let element = el; do { top += element.offsetTop || 0; element = element.offsetParent; } while (element); return top; }
javascript
function getElementTop(el) { let top = 0; let element = el; do { top += element.offsetTop || 0; element = element.offsetParent; } while (element); return top; }
[ "function", "getElementTop", "(", "el", ")", "{", "let", "top", "=", "0", ";", "let", "element", "=", "el", ";", "do", "{", "top", "+=", "element", ".", "offsetTop", "||", "0", ";", "element", "=", "element", ".", "offsetParent", ";", "}", "while", "(", "element", ")", ";", "return", "top", ";", "}" ]
Get element's top offset
[ "Get", "element", "s", "top", "offset" ]
47a88bc8c02632e19681299413ee614c12a459f6
https://github.com/Stanko/react-plx/blob/47a88bc8c02632e19681299413ee614c12a459f6/source/Plx.js#L175-L185
15,473
Stanko/react-plx
source/Plx.js
getUnit
function getUnit(property, unit) { let propertyUnit = unit || DEFAULT_UNIT; if (ANGLE_PROPERTIES.indexOf(property) >= 0) { propertyUnit = unit || DEFAULT_ANGLE_UNIT; } return propertyUnit; }
javascript
function getUnit(property, unit) { let propertyUnit = unit || DEFAULT_UNIT; if (ANGLE_PROPERTIES.indexOf(property) >= 0) { propertyUnit = unit || DEFAULT_ANGLE_UNIT; } return propertyUnit; }
[ "function", "getUnit", "(", "property", ",", "unit", ")", "{", "let", "propertyUnit", "=", "unit", "||", "DEFAULT_UNIT", ";", "if", "(", "ANGLE_PROPERTIES", ".", "indexOf", "(", "property", ")", ">=", "0", ")", "{", "propertyUnit", "=", "unit", "||", "DEFAULT_ANGLE_UNIT", ";", "}", "return", "propertyUnit", ";", "}" ]
Returns CSS unit
[ "Returns", "CSS", "unit" ]
47a88bc8c02632e19681299413ee614c12a459f6
https://github.com/Stanko/react-plx/blob/47a88bc8c02632e19681299413ee614c12a459f6/source/Plx.js#L188-L196
15,474
Stanko/react-plx
source/Plx.js
parallax
function parallax(scrollPosition, start, duration, startValue, endValue, easing) { let min = startValue; let max = endValue; const invert = startValue > endValue; // Safety check, if "startValue" is in the wrong format if (typeof startValue !== 'number') { console.warn(`Plx, ERROR: startValue is not a number (type: "${ typeof endValue }", value: "${ endValue }")`); // eslint-disable-line return null; } // Safety check, if "endValue" is in the wrong format if (typeof endValue !== 'number') { console.warn(`Plx, ERROR: endValue is not a number (type: "${ typeof endValue }", value: "${ endValue }")`); // eslint-disable-line return null; } // Safety check, if "duration" is in the wrong format if (typeof duration !== 'number' || duration === 0) { console.warn(`Plx, ERROR: duration is zero or not a number (type: "${ typeof duration }", value: "${ duration }")`); // eslint-disable-line return null; } if (invert) { min = endValue; max = startValue; } let percentage = ((scrollPosition - start) / duration); if (percentage > 1) { percentage = 1; } else if (percentage < 0) { percentage = 0; } // Apply easing if (easing) { const easingPropType = typeof easing; if (easingPropType === 'object' && easing.length === 4) { percentage = BezierEasing( easing[0], easing[1], easing[2], easing[3] )(percentage); } else if (easingPropType === 'string' && EASINGS[easing]) { percentage = BezierEasing( EASINGS[easing][0], EASINGS[easing][1], EASINGS[easing][2], EASINGS[easing][3] )(percentage); } else if (easingPropType === 'function') { percentage = easing(percentage); } } let value = percentage * (max - min); if (invert) { value = max - value; } else { value += min; } return parseFloat(value.toFixed(3)); }
javascript
function parallax(scrollPosition, start, duration, startValue, endValue, easing) { let min = startValue; let max = endValue; const invert = startValue > endValue; // Safety check, if "startValue" is in the wrong format if (typeof startValue !== 'number') { console.warn(`Plx, ERROR: startValue is not a number (type: "${ typeof endValue }", value: "${ endValue }")`); // eslint-disable-line return null; } // Safety check, if "endValue" is in the wrong format if (typeof endValue !== 'number') { console.warn(`Plx, ERROR: endValue is not a number (type: "${ typeof endValue }", value: "${ endValue }")`); // eslint-disable-line return null; } // Safety check, if "duration" is in the wrong format if (typeof duration !== 'number' || duration === 0) { console.warn(`Plx, ERROR: duration is zero or not a number (type: "${ typeof duration }", value: "${ duration }")`); // eslint-disable-line return null; } if (invert) { min = endValue; max = startValue; } let percentage = ((scrollPosition - start) / duration); if (percentage > 1) { percentage = 1; } else if (percentage < 0) { percentage = 0; } // Apply easing if (easing) { const easingPropType = typeof easing; if (easingPropType === 'object' && easing.length === 4) { percentage = BezierEasing( easing[0], easing[1], easing[2], easing[3] )(percentage); } else if (easingPropType === 'string' && EASINGS[easing]) { percentage = BezierEasing( EASINGS[easing][0], EASINGS[easing][1], EASINGS[easing][2], EASINGS[easing][3] )(percentage); } else if (easingPropType === 'function') { percentage = easing(percentage); } } let value = percentage * (max - min); if (invert) { value = max - value; } else { value += min; } return parseFloat(value.toFixed(3)); }
[ "function", "parallax", "(", "scrollPosition", ",", "start", ",", "duration", ",", "startValue", ",", "endValue", ",", "easing", ")", "{", "let", "min", "=", "startValue", ";", "let", "max", "=", "endValue", ";", "const", "invert", "=", "startValue", ">", "endValue", ";", "// Safety check, if \"startValue\" is in the wrong format", "if", "(", "typeof", "startValue", "!==", "'number'", ")", "{", "console", ".", "warn", "(", "`", "${", "typeof", "endValue", "}", "${", "endValue", "}", "`", ")", ";", "// eslint-disable-line", "return", "null", ";", "}", "// Safety check, if \"endValue\" is in the wrong format", "if", "(", "typeof", "endValue", "!==", "'number'", ")", "{", "console", ".", "warn", "(", "`", "${", "typeof", "endValue", "}", "${", "endValue", "}", "`", ")", ";", "// eslint-disable-line", "return", "null", ";", "}", "// Safety check, if \"duration\" is in the wrong format", "if", "(", "typeof", "duration", "!==", "'number'", "||", "duration", "===", "0", ")", "{", "console", ".", "warn", "(", "`", "${", "typeof", "duration", "}", "${", "duration", "}", "`", ")", ";", "// eslint-disable-line", "return", "null", ";", "}", "if", "(", "invert", ")", "{", "min", "=", "endValue", ";", "max", "=", "startValue", ";", "}", "let", "percentage", "=", "(", "(", "scrollPosition", "-", "start", ")", "/", "duration", ")", ";", "if", "(", "percentage", ">", "1", ")", "{", "percentage", "=", "1", ";", "}", "else", "if", "(", "percentage", "<", "0", ")", "{", "percentage", "=", "0", ";", "}", "// Apply easing", "if", "(", "easing", ")", "{", "const", "easingPropType", "=", "typeof", "easing", ";", "if", "(", "easingPropType", "===", "'object'", "&&", "easing", ".", "length", "===", "4", ")", "{", "percentage", "=", "BezierEasing", "(", "easing", "[", "0", "]", ",", "easing", "[", "1", "]", ",", "easing", "[", "2", "]", ",", "easing", "[", "3", "]", ")", "(", "percentage", ")", ";", "}", "else", "if", "(", "easingPropType", "===", "'string'", "&&", "EASINGS", "[", "easing", "]", ")", "{", "percentage", "=", "BezierEasing", "(", "EASINGS", "[", "easing", "]", "[", "0", "]", ",", "EASINGS", "[", "easing", "]", "[", "1", "]", ",", "EASINGS", "[", "easing", "]", "[", "2", "]", ",", "EASINGS", "[", "easing", "]", "[", "3", "]", ")", "(", "percentage", ")", ";", "}", "else", "if", "(", "easingPropType", "===", "'function'", ")", "{", "percentage", "=", "easing", "(", "percentage", ")", ";", "}", "}", "let", "value", "=", "percentage", "*", "(", "max", "-", "min", ")", ";", "if", "(", "invert", ")", "{", "value", "=", "max", "-", "value", ";", "}", "else", "{", "value", "+=", "min", ";", "}", "return", "parseFloat", "(", "value", ".", "toFixed", "(", "3", ")", ")", ";", "}" ]
Calculates the current value for parallaxing property
[ "Calculates", "the", "current", "value", "for", "parallaxing", "property" ]
47a88bc8c02632e19681299413ee614c12a459f6
https://github.com/Stanko/react-plx/blob/47a88bc8c02632e19681299413ee614c12a459f6/source/Plx.js#L320-L388
15,475
Stanko/react-plx
source/Plx.js
colorParallax
function colorParallax(scrollPosition, start, duration, startValue, endValue, easing) { let startObject = null; let endObject = null; if (startValue[0].toLowerCase() === 'r') { startObject = rgbToObject(startValue); } else { startObject = hexToObject(startValue); } if (endValue[0].toLowerCase() === 'r') { endObject = rgbToObject(endValue); } else { endObject = hexToObject(endValue); } if (startObject && endObject) { const r = parallax(scrollPosition, start, duration, startObject.r, endObject.r, easing); const g = parallax(scrollPosition, start, duration, startObject.g, endObject.g, easing); const b = parallax(scrollPosition, start, duration, startObject.b, endObject.b, easing); const a = parallax(scrollPosition, start, duration, startObject.a, endObject.a, easing); return `rgba(${ parseInt(r, 10) }, ${ parseInt(g, 10) }, ${ parseInt(b, 10) }, ${ a })`; } return null; }
javascript
function colorParallax(scrollPosition, start, duration, startValue, endValue, easing) { let startObject = null; let endObject = null; if (startValue[0].toLowerCase() === 'r') { startObject = rgbToObject(startValue); } else { startObject = hexToObject(startValue); } if (endValue[0].toLowerCase() === 'r') { endObject = rgbToObject(endValue); } else { endObject = hexToObject(endValue); } if (startObject && endObject) { const r = parallax(scrollPosition, start, duration, startObject.r, endObject.r, easing); const g = parallax(scrollPosition, start, duration, startObject.g, endObject.g, easing); const b = parallax(scrollPosition, start, duration, startObject.b, endObject.b, easing); const a = parallax(scrollPosition, start, duration, startObject.a, endObject.a, easing); return `rgba(${ parseInt(r, 10) }, ${ parseInt(g, 10) }, ${ parseInt(b, 10) }, ${ a })`; } return null; }
[ "function", "colorParallax", "(", "scrollPosition", ",", "start", ",", "duration", ",", "startValue", ",", "endValue", ",", "easing", ")", "{", "let", "startObject", "=", "null", ";", "let", "endObject", "=", "null", ";", "if", "(", "startValue", "[", "0", "]", ".", "toLowerCase", "(", ")", "===", "'r'", ")", "{", "startObject", "=", "rgbToObject", "(", "startValue", ")", ";", "}", "else", "{", "startObject", "=", "hexToObject", "(", "startValue", ")", ";", "}", "if", "(", "endValue", "[", "0", "]", ".", "toLowerCase", "(", ")", "===", "'r'", ")", "{", "endObject", "=", "rgbToObject", "(", "endValue", ")", ";", "}", "else", "{", "endObject", "=", "hexToObject", "(", "endValue", ")", ";", "}", "if", "(", "startObject", "&&", "endObject", ")", "{", "const", "r", "=", "parallax", "(", "scrollPosition", ",", "start", ",", "duration", ",", "startObject", ".", "r", ",", "endObject", ".", "r", ",", "easing", ")", ";", "const", "g", "=", "parallax", "(", "scrollPosition", ",", "start", ",", "duration", ",", "startObject", ".", "g", ",", "endObject", ".", "g", ",", "easing", ")", ";", "const", "b", "=", "parallax", "(", "scrollPosition", ",", "start", ",", "duration", ",", "startObject", ".", "b", ",", "endObject", ".", "b", ",", "easing", ")", ";", "const", "a", "=", "parallax", "(", "scrollPosition", ",", "start", ",", "duration", ",", "startObject", ".", "a", ",", "endObject", ".", "a", ",", "easing", ")", ";", "return", "`", "${", "parseInt", "(", "r", ",", "10", ")", "}", "${", "parseInt", "(", "g", ",", "10", ")", "}", "${", "parseInt", "(", "b", ",", "10", ")", "}", "${", "a", "}", "`", ";", "}", "return", "null", ";", "}" ]
Calculates current value for color parallax
[ "Calculates", "current", "value", "for", "color", "parallax" ]
47a88bc8c02632e19681299413ee614c12a459f6
https://github.com/Stanko/react-plx/blob/47a88bc8c02632e19681299413ee614c12a459f6/source/Plx.js#L391-L417
15,476
Stanko/react-plx
source/Plx.js
applyProperty
function applyProperty(scrollPosition, propertyData, startPosition, duration, style, easing) { const { startValue, endValue, property, unit, } = propertyData; // If property is one of the color properties // Use it's parallax method const isColor = COLOR_PROPERTIES.indexOf(property) > -1; const parallaxMethod = isColor ? colorParallax : parallax; // Get new CSS value const value = parallaxMethod( scrollPosition, startPosition, duration, startValue, endValue, easing ); // Get transform function const transformMethod = TRANSFORM_MAP[property]; const filterMethod = FILTER_MAP[property]; const newStyle = style; if (transformMethod) { // Get CSS unit const propertyUnit = getUnit(property, unit); // Transforms, apply value to transform function newStyle.transform[property] = transformMethod(value, propertyUnit); } else if (filterMethod) { // Get CSS unit const propertyUnit = getUnit(property, unit); // Filters, apply value to filter function newStyle.filter[property] = filterMethod(value, propertyUnit); } else { // All other properties newStyle[property] = value; // Add unit if it is passed if (unit) { newStyle[property] += unit; } } return newStyle; }
javascript
function applyProperty(scrollPosition, propertyData, startPosition, duration, style, easing) { const { startValue, endValue, property, unit, } = propertyData; // If property is one of the color properties // Use it's parallax method const isColor = COLOR_PROPERTIES.indexOf(property) > -1; const parallaxMethod = isColor ? colorParallax : parallax; // Get new CSS value const value = parallaxMethod( scrollPosition, startPosition, duration, startValue, endValue, easing ); // Get transform function const transformMethod = TRANSFORM_MAP[property]; const filterMethod = FILTER_MAP[property]; const newStyle = style; if (transformMethod) { // Get CSS unit const propertyUnit = getUnit(property, unit); // Transforms, apply value to transform function newStyle.transform[property] = transformMethod(value, propertyUnit); } else if (filterMethod) { // Get CSS unit const propertyUnit = getUnit(property, unit); // Filters, apply value to filter function newStyle.filter[property] = filterMethod(value, propertyUnit); } else { // All other properties newStyle[property] = value; // Add unit if it is passed if (unit) { newStyle[property] += unit; } } return newStyle; }
[ "function", "applyProperty", "(", "scrollPosition", ",", "propertyData", ",", "startPosition", ",", "duration", ",", "style", ",", "easing", ")", "{", "const", "{", "startValue", ",", "endValue", ",", "property", ",", "unit", ",", "}", "=", "propertyData", ";", "// If property is one of the color properties", "// Use it's parallax method", "const", "isColor", "=", "COLOR_PROPERTIES", ".", "indexOf", "(", "property", ")", ">", "-", "1", ";", "const", "parallaxMethod", "=", "isColor", "?", "colorParallax", ":", "parallax", ";", "// Get new CSS value", "const", "value", "=", "parallaxMethod", "(", "scrollPosition", ",", "startPosition", ",", "duration", ",", "startValue", ",", "endValue", ",", "easing", ")", ";", "// Get transform function", "const", "transformMethod", "=", "TRANSFORM_MAP", "[", "property", "]", ";", "const", "filterMethod", "=", "FILTER_MAP", "[", "property", "]", ";", "const", "newStyle", "=", "style", ";", "if", "(", "transformMethod", ")", "{", "// Get CSS unit", "const", "propertyUnit", "=", "getUnit", "(", "property", ",", "unit", ")", ";", "// Transforms, apply value to transform function", "newStyle", ".", "transform", "[", "property", "]", "=", "transformMethod", "(", "value", ",", "propertyUnit", ")", ";", "}", "else", "if", "(", "filterMethod", ")", "{", "// Get CSS unit", "const", "propertyUnit", "=", "getUnit", "(", "property", ",", "unit", ")", ";", "// Filters, apply value to filter function", "newStyle", ".", "filter", "[", "property", "]", "=", "filterMethod", "(", "value", ",", "propertyUnit", ")", ";", "}", "else", "{", "// All other properties", "newStyle", "[", "property", "]", "=", "value", ";", "// Add unit if it is passed", "if", "(", "unit", ")", "{", "newStyle", "[", "property", "]", "+=", "unit", ";", "}", "}", "return", "newStyle", ";", "}" ]
Applies property parallax to the style object
[ "Applies", "property", "parallax", "to", "the", "style", "object" ]
47a88bc8c02632e19681299413ee614c12a459f6
https://github.com/Stanko/react-plx/blob/47a88bc8c02632e19681299413ee614c12a459f6/source/Plx.js#L420-L469
15,477
Stanko/react-plx
source/Plx.js
getClasses
function getClasses(lastSegmentScrolledBy, isInSegment, parallaxData) { let cssClasses = null; if (lastSegmentScrolledBy === null) { cssClasses = 'Plx--above'; } else if (lastSegmentScrolledBy === parallaxData.length - 1 && !isInSegment) { cssClasses = 'Plx--below'; } else if (lastSegmentScrolledBy !== null && isInSegment) { const segmentName = parallaxData[lastSegmentScrolledBy].name || lastSegmentScrolledBy; cssClasses = `Plx--active Plx--in Plx--in-${ segmentName }`; } else if (lastSegmentScrolledBy !== null && !isInSegment) { const segmentName = parallaxData[lastSegmentScrolledBy].name || lastSegmentScrolledBy; const nextSegmentName = parallaxData[lastSegmentScrolledBy + 1].name || lastSegmentScrolledBy + 1; cssClasses = `Plx--active Plx--between Plx--between-${ segmentName }-and-${ nextSegmentName }`; } return cssClasses; }
javascript
function getClasses(lastSegmentScrolledBy, isInSegment, parallaxData) { let cssClasses = null; if (lastSegmentScrolledBy === null) { cssClasses = 'Plx--above'; } else if (lastSegmentScrolledBy === parallaxData.length - 1 && !isInSegment) { cssClasses = 'Plx--below'; } else if (lastSegmentScrolledBy !== null && isInSegment) { const segmentName = parallaxData[lastSegmentScrolledBy].name || lastSegmentScrolledBy; cssClasses = `Plx--active Plx--in Plx--in-${ segmentName }`; } else if (lastSegmentScrolledBy !== null && !isInSegment) { const segmentName = parallaxData[lastSegmentScrolledBy].name || lastSegmentScrolledBy; const nextSegmentName = parallaxData[lastSegmentScrolledBy + 1].name || lastSegmentScrolledBy + 1; cssClasses = `Plx--active Plx--between Plx--between-${ segmentName }-and-${ nextSegmentName }`; } return cssClasses; }
[ "function", "getClasses", "(", "lastSegmentScrolledBy", ",", "isInSegment", ",", "parallaxData", ")", "{", "let", "cssClasses", "=", "null", ";", "if", "(", "lastSegmentScrolledBy", "===", "null", ")", "{", "cssClasses", "=", "'Plx--above'", ";", "}", "else", "if", "(", "lastSegmentScrolledBy", "===", "parallaxData", ".", "length", "-", "1", "&&", "!", "isInSegment", ")", "{", "cssClasses", "=", "'Plx--below'", ";", "}", "else", "if", "(", "lastSegmentScrolledBy", "!==", "null", "&&", "isInSegment", ")", "{", "const", "segmentName", "=", "parallaxData", "[", "lastSegmentScrolledBy", "]", ".", "name", "||", "lastSegmentScrolledBy", ";", "cssClasses", "=", "`", "${", "segmentName", "}", "`", ";", "}", "else", "if", "(", "lastSegmentScrolledBy", "!==", "null", "&&", "!", "isInSegment", ")", "{", "const", "segmentName", "=", "parallaxData", "[", "lastSegmentScrolledBy", "]", ".", "name", "||", "lastSegmentScrolledBy", ";", "const", "nextSegmentName", "=", "parallaxData", "[", "lastSegmentScrolledBy", "+", "1", "]", ".", "name", "||", "lastSegmentScrolledBy", "+", "1", ";", "cssClasses", "=", "`", "${", "segmentName", "}", "${", "nextSegmentName", "}", "`", ";", "}", "return", "cssClasses", ";", "}" ]
Returns CSS classes based on animation state
[ "Returns", "CSS", "classes", "based", "on", "animation", "state" ]
47a88bc8c02632e19681299413ee614c12a459f6
https://github.com/Stanko/react-plx/blob/47a88bc8c02632e19681299413ee614c12a459f6/source/Plx.js#L472-L491
15,478
Stanko/react-plx
source/Plx.js
omit
function omit(object, keysToOmit) { const result = {}; Object.keys(object).forEach(key => { if (keysToOmit.indexOf(key) === -1) { result[key] = object[key]; } }); return result; }
javascript
function omit(object, keysToOmit) { const result = {}; Object.keys(object).forEach(key => { if (keysToOmit.indexOf(key) === -1) { result[key] = object[key]; } }); return result; }
[ "function", "omit", "(", "object", ",", "keysToOmit", ")", "{", "const", "result", "=", "{", "}", ";", "Object", ".", "keys", "(", "object", ")", ".", "forEach", "(", "key", "=>", "{", "if", "(", "keysToOmit", ".", "indexOf", "(", "key", ")", "===", "-", "1", ")", "{", "result", "[", "key", "]", "=", "object", "[", "key", "]", ";", "}", "}", ")", ";", "return", "result", ";", "}" ]
Omits "keysToOmit" from "object"
[ "Omits", "keysToOmit", "from", "object" ]
47a88bc8c02632e19681299413ee614c12a459f6
https://github.com/Stanko/react-plx/blob/47a88bc8c02632e19681299413ee614c12a459f6/source/Plx.js#L500-L510
15,479
hokaccha/node-jwt-simple
lib/jwt.js
assignProperties
function assignProperties(dest, source) { for (var attr in source) { if (source.hasOwnProperty(attr)) { dest[attr] = source[attr]; } } }
javascript
function assignProperties(dest, source) { for (var attr in source) { if (source.hasOwnProperty(attr)) { dest[attr] = source[attr]; } } }
[ "function", "assignProperties", "(", "dest", ",", "source", ")", "{", "for", "(", "var", "attr", "in", "source", ")", "{", "if", "(", "source", ".", "hasOwnProperty", "(", "attr", ")", ")", "{", "dest", "[", "attr", "]", "=", "source", "[", "attr", "]", ";", "}", "}", "}" ]
private util functions
[ "private", "util", "functions" ]
c58bfe5e5bb049015fcd55be5fc1b2d5c652dbcd
https://github.com/hokaccha/node-jwt-simple/blob/c58bfe5e5bb049015fcd55be5fc1b2d5c652dbcd/lib/jwt.js#L156-L162
15,480
CartoDB/carto-vl
src/renderer/decoder/polygonDecoder.js
resizeBuffers
function resizeBuffers (additionalSize) { const minimumNeededSize = index + additionalSize; if (minimumNeededSize > geomBuffer.vertices.length) { const newSize = 2 * minimumNeededSize; geomBuffer.vertices = resizeBuffer(geomBuffer.vertices, newSize); geomBuffer.normals = resizeBuffer(geomBuffer.normals, newSize); } }
javascript
function resizeBuffers (additionalSize) { const minimumNeededSize = index + additionalSize; if (minimumNeededSize > geomBuffer.vertices.length) { const newSize = 2 * minimumNeededSize; geomBuffer.vertices = resizeBuffer(geomBuffer.vertices, newSize); geomBuffer.normals = resizeBuffer(geomBuffer.normals, newSize); } }
[ "function", "resizeBuffers", "(", "additionalSize", ")", "{", "const", "minimumNeededSize", "=", "index", "+", "additionalSize", ";", "if", "(", "minimumNeededSize", ">", "geomBuffer", ".", "vertices", ".", "length", ")", "{", "const", "newSize", "=", "2", "*", "minimumNeededSize", ";", "geomBuffer", ".", "vertices", "=", "resizeBuffer", "(", "geomBuffer", ".", "vertices", ",", "newSize", ")", ";", "geomBuffer", ".", "normals", "=", "resizeBuffer", "(", "geomBuffer", ".", "normals", ",", "newSize", ")", ";", "}", "}" ]
Resize buffers as needed if `additionalSize` floats overflow the current buffers
[ "Resize", "buffers", "as", "needed", "if", "additionalSize", "floats", "overflow", "the", "current", "buffers" ]
2cc704a0f3fda0943b3d3f84dac9466defb18f2c
https://github.com/CartoDB/carto-vl/blob/2cc704a0f3fda0943b3d3f84dac9466defb18f2c/src/renderer/decoder/polygonDecoder.js#L79-L86
15,481
CartoDB/carto-vl
src/renderer/decoder/polygonDecoder.js
addVertex
function addVertex (array, vertexIndex) { geomBuffer.vertices[index] = array[vertexIndex]; geomBuffer.normals[index++] = 0; geomBuffer.vertices[index] = array[vertexIndex + 1]; geomBuffer.normals[index++] = 0; }
javascript
function addVertex (array, vertexIndex) { geomBuffer.vertices[index] = array[vertexIndex]; geomBuffer.normals[index++] = 0; geomBuffer.vertices[index] = array[vertexIndex + 1]; geomBuffer.normals[index++] = 0; }
[ "function", "addVertex", "(", "array", ",", "vertexIndex", ")", "{", "geomBuffer", ".", "vertices", "[", "index", "]", "=", "array", "[", "vertexIndex", "]", ";", "geomBuffer", ".", "normals", "[", "index", "++", "]", "=", "0", ";", "geomBuffer", ".", "vertices", "[", "index", "]", "=", "array", "[", "vertexIndex", "+", "1", "]", ";", "geomBuffer", ".", "normals", "[", "index", "++", "]", "=", "0", ";", "}" ]
Add vertex in triangles.
[ "Add", "vertex", "in", "triangles", "." ]
2cc704a0f3fda0943b3d3f84dac9466defb18f2c
https://github.com/CartoDB/carto-vl/blob/2cc704a0f3fda0943b3d3f84dac9466defb18f2c/src/renderer/decoder/polygonDecoder.js#L89-L94
15,482
CartoDB/carto-vl
src/utils/time/periodISO.js
yearWeek
function yearWeek (y, yd) { const dow = isoDow(y, 1, 1); const start = dow > 4 ? 9 - dow : 2 - dow; if ((Math.abs(yd - start) % 7) !== 0) { // y yd is not the start of any week return []; } if (yd < start) { // The week starts before the first week of the year => go back one year yd += Math.round((Date.UTC(y, 0, 1) - Date.UTC(y - 1, 0, 1)) / MS_PER_DAY); return yearWeek(y - 1, yd); } else if (Date.UTC(y, 0, 1) + (yd - 1 + 3) * MS_PER_DAY >= Date.UTC(y + 1, 0, 1)) { // The Wednesday (start of week + 3) lies in the next year => advance one year yd -= Math.round((Date.UTC(y + 1, 0, 1) - Date.UTC(y, 0, 1)) / MS_PER_DAY); return yearWeek(y + 1, yd); } return [y, 1 + Math.round((yd - start) / 7)]; }
javascript
function yearWeek (y, yd) { const dow = isoDow(y, 1, 1); const start = dow > 4 ? 9 - dow : 2 - dow; if ((Math.abs(yd - start) % 7) !== 0) { // y yd is not the start of any week return []; } if (yd < start) { // The week starts before the first week of the year => go back one year yd += Math.round((Date.UTC(y, 0, 1) - Date.UTC(y - 1, 0, 1)) / MS_PER_DAY); return yearWeek(y - 1, yd); } else if (Date.UTC(y, 0, 1) + (yd - 1 + 3) * MS_PER_DAY >= Date.UTC(y + 1, 0, 1)) { // The Wednesday (start of week + 3) lies in the next year => advance one year yd -= Math.round((Date.UTC(y + 1, 0, 1) - Date.UTC(y, 0, 1)) / MS_PER_DAY); return yearWeek(y + 1, yd); } return [y, 1 + Math.round((yd - start) / 7)]; }
[ "function", "yearWeek", "(", "y", ",", "yd", ")", "{", "const", "dow", "=", "isoDow", "(", "y", ",", "1", ",", "1", ")", ";", "const", "start", "=", "dow", ">", "4", "?", "9", "-", "dow", ":", "2", "-", "dow", ";", "if", "(", "(", "Math", ".", "abs", "(", "yd", "-", "start", ")", "%", "7", ")", "!==", "0", ")", "{", "// y yd is not the start of any week", "return", "[", "]", ";", "}", "if", "(", "yd", "<", "start", ")", "{", "// The week starts before the first week of the year => go back one year", "yd", "+=", "Math", ".", "round", "(", "(", "Date", ".", "UTC", "(", "y", ",", "0", ",", "1", ")", "-", "Date", ".", "UTC", "(", "y", "-", "1", ",", "0", ",", "1", ")", ")", "/", "MS_PER_DAY", ")", ";", "return", "yearWeek", "(", "y", "-", "1", ",", "yd", ")", ";", "}", "else", "if", "(", "Date", ".", "UTC", "(", "y", ",", "0", ",", "1", ")", "+", "(", "yd", "-", "1", "+", "3", ")", "*", "MS_PER_DAY", ">=", "Date", ".", "UTC", "(", "y", "+", "1", ",", "0", ",", "1", ")", ")", "{", "// The Wednesday (start of week + 3) lies in the next year => advance one year", "yd", "-=", "Math", ".", "round", "(", "(", "Date", ".", "UTC", "(", "y", "+", "1", ",", "0", ",", "1", ")", "-", "Date", ".", "UTC", "(", "y", ",", "0", ",", "1", ")", ")", "/", "MS_PER_DAY", ")", ";", "return", "yearWeek", "(", "y", "+", "1", ",", "yd", ")", ";", "}", "return", "[", "y", ",", "1", "+", "Math", ".", "round", "(", "(", "yd", "-", "start", ")", "/", "7", ")", "]", ";", "}" ]
Return year and week number given year and day number
[ "Return", "year", "and", "week", "number", "given", "year", "and", "day", "number" ]
2cc704a0f3fda0943b3d3f84dac9466defb18f2c
https://github.com/CartoDB/carto-vl/blob/2cc704a0f3fda0943b3d3f84dac9466defb18f2c/src/utils/time/periodISO.js#L51-L68
15,483
CartoDB/carto-vl
src/renderer/viz/colorspaces.js
XYZToSRGB
function XYZToSRGB ({ x, y, z, a }) { // Poynton, "Frequently Asked Questions About Color," page 10 // Wikipedia: http://en.wikipedia.org/wiki/SRGB // Wikipedia: http://en.wikipedia.org/wiki/CIE_1931_color_space // Convert XYZ to linear RGB const r = clamp(3.2406 * x - 1.5372 * y - 0.4986 * z, 0, 1); const g = clamp(-0.9689 * x + 1.8758 * y + 0.0415 * z, 0, 1); const b = clamp(0.0557 * x - 0.2040 * y + 1.0570 * z, 0, 1); return linearRGBToSRGB({ r, g, b, a }); }
javascript
function XYZToSRGB ({ x, y, z, a }) { // Poynton, "Frequently Asked Questions About Color," page 10 // Wikipedia: http://en.wikipedia.org/wiki/SRGB // Wikipedia: http://en.wikipedia.org/wiki/CIE_1931_color_space // Convert XYZ to linear RGB const r = clamp(3.2406 * x - 1.5372 * y - 0.4986 * z, 0, 1); const g = clamp(-0.9689 * x + 1.8758 * y + 0.0415 * z, 0, 1); const b = clamp(0.0557 * x - 0.2040 * y + 1.0570 * z, 0, 1); return linearRGBToSRGB({ r, g, b, a }); }
[ "function", "XYZToSRGB", "(", "{", "x", ",", "y", ",", "z", ",", "a", "}", ")", "{", "// Poynton, \"Frequently Asked Questions About Color,\" page 10", "// Wikipedia: http://en.wikipedia.org/wiki/SRGB", "// Wikipedia: http://en.wikipedia.org/wiki/CIE_1931_color_space", "// Convert XYZ to linear RGB", "const", "r", "=", "clamp", "(", "3.2406", "*", "x", "-", "1.5372", "*", "y", "-", "0.4986", "*", "z", ",", "0", ",", "1", ")", ";", "const", "g", "=", "clamp", "(", "-", "0.9689", "*", "x", "+", "1.8758", "*", "y", "+", "0.0415", "*", "z", ",", "0", ",", "1", ")", ";", "const", "b", "=", "clamp", "(", "0.0557", "*", "x", "-", "0.2040", "*", "y", "+", "1.0570", "*", "z", ",", "0", ",", "1", ")", ";", "return", "linearRGBToSRGB", "(", "{", "r", ",", "g", ",", "b", ",", "a", "}", ")", ";", "}" ]
Convert CIE XYZ to sRGB with the D65 white point
[ "Convert", "CIE", "XYZ", "to", "sRGB", "with", "the", "D65", "white", "point" ]
2cc704a0f3fda0943b3d3f84dac9466defb18f2c
https://github.com/CartoDB/carto-vl/blob/2cc704a0f3fda0943b3d3f84dac9466defb18f2c/src/renderer/viz/colorspaces.js#L118-L129
15,484
CartoDB/carto-vl
src/setup/config-service.js
checkConfig
function checkConfig (config) { if (config) { if (!util.isObject(config)) { throw new CartoValidationError('\'config\' property must be an object.', CartoValidationErrorTypes.INCORRECT_TYPE); } _checkServerURL(config.serverURL); } }
javascript
function checkConfig (config) { if (config) { if (!util.isObject(config)) { throw new CartoValidationError('\'config\' property must be an object.', CartoValidationErrorTypes.INCORRECT_TYPE); } _checkServerURL(config.serverURL); } }
[ "function", "checkConfig", "(", "config", ")", "{", "if", "(", "config", ")", "{", "if", "(", "!", "util", ".", "isObject", "(", "config", ")", ")", "{", "throw", "new", "CartoValidationError", "(", "'\\'config\\' property must be an object.'", ",", "CartoValidationErrorTypes", ".", "INCORRECT_TYPE", ")", ";", "}", "_checkServerURL", "(", "config", ".", "serverURL", ")", ";", "}", "}" ]
Check a valid config parameter. @param {Object} config
[ "Check", "a", "valid", "config", "parameter", "." ]
2cc704a0f3fda0943b3d3f84dac9466defb18f2c
https://github.com/CartoDB/carto-vl/blob/2cc704a0f3fda0943b3d3f84dac9466defb18f2c/src/setup/config-service.js#L40-L47
15,485
CartoDB/carto-vl
src/utils/geometry.js
normalize
function normalize (x, y) { const s = Math.hypot(x, y); return [x / s, y / s]; }
javascript
function normalize (x, y) { const s = Math.hypot(x, y); return [x / s, y / s]; }
[ "function", "normalize", "(", "x", ",", "y", ")", "{", "const", "s", "=", "Math", ".", "hypot", "(", "x", ",", "y", ")", ";", "return", "[", "x", "/", "s", ",", "y", "/", "s", "]", ";", "}" ]
Return the vector scaled to length 1
[ "Return", "the", "vector", "scaled", "to", "length", "1" ]
2cc704a0f3fda0943b3d3f84dac9466defb18f2c
https://github.com/CartoDB/carto-vl/blob/2cc704a0f3fda0943b3d3f84dac9466defb18f2c/src/utils/geometry.js#L84-L87
15,486
CartoDB/carto-vl
examples/editor/index.js
generateSnippet
function generateSnippet (config) { const apiKey = config.b || 'default_public'; const username = config.c; const serverURL = config.d || 'https://{user}.carto.com'; const vizSpec = config.e || ''; const center = config.f || { lat: 0, lng: 0 }; const zoom = config.g || 10; const basemap = BASEMAPS[config.h] || 'https://basemaps.cartocdn.com/gl/voyager-gl-style/style.json'; const source = config.i === sourceTypes.DATASET ? `new carto.source.Dataset("${config.a}")` : `new carto.source.SQL(\`${config.a}\`)`; return `<!DOCTYPE html> <html> <head> <title>Exported map | CARTO VL</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta charset="UTF-8"> <script src="http://libs.cartocdn.com/carto-vl/v${carto.version}/carto-vl.js"></script> <script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.js"></script> <link href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.css" rel="stylesheet" /> <style> html, body { margin: 0; } #map { position: absolute; width: 100%; height: 100%; } </style> </head> <body> <div id="map"></div> <script> const map = new mapboxgl.Map({ container: 'map', style: '${basemap}', center: [${center.lng}, ${center.lat}], zoom: ${zoom} }); carto.setDefaultConfig({ serverURL: '${serverURL}' }); carto.setDefaultAuth({ username: '${username}', apiKey: '${apiKey}' }); const source = ${source}; const viz = new carto.Viz(\` ${vizSpec} \`); const layer = new carto.Layer('layer', source, viz); layer.addTo(map, 'watername_ocean'); </script> </body> </html> `; }
javascript
function generateSnippet (config) { const apiKey = config.b || 'default_public'; const username = config.c; const serverURL = config.d || 'https://{user}.carto.com'; const vizSpec = config.e || ''; const center = config.f || { lat: 0, lng: 0 }; const zoom = config.g || 10; const basemap = BASEMAPS[config.h] || 'https://basemaps.cartocdn.com/gl/voyager-gl-style/style.json'; const source = config.i === sourceTypes.DATASET ? `new carto.source.Dataset("${config.a}")` : `new carto.source.SQL(\`${config.a}\`)`; return `<!DOCTYPE html> <html> <head> <title>Exported map | CARTO VL</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta charset="UTF-8"> <script src="http://libs.cartocdn.com/carto-vl/v${carto.version}/carto-vl.js"></script> <script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.js"></script> <link href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.css" rel="stylesheet" /> <style> html, body { margin: 0; } #map { position: absolute; width: 100%; height: 100%; } </style> </head> <body> <div id="map"></div> <script> const map = new mapboxgl.Map({ container: 'map', style: '${basemap}', center: [${center.lng}, ${center.lat}], zoom: ${zoom} }); carto.setDefaultConfig({ serverURL: '${serverURL}' }); carto.setDefaultAuth({ username: '${username}', apiKey: '${apiKey}' }); const source = ${source}; const viz = new carto.Viz(\` ${vizSpec} \`); const layer = new carto.Layer('layer', source, viz); layer.addTo(map, 'watername_ocean'); </script> </body> </html> `; }
[ "function", "generateSnippet", "(", "config", ")", "{", "const", "apiKey", "=", "config", ".", "b", "||", "'default_public'", ";", "const", "username", "=", "config", ".", "c", ";", "const", "serverURL", "=", "config", ".", "d", "||", "'https://{user}.carto.com'", ";", "const", "vizSpec", "=", "config", ".", "e", "||", "''", ";", "const", "center", "=", "config", ".", "f", "||", "{", "lat", ":", "0", ",", "lng", ":", "0", "}", ";", "const", "zoom", "=", "config", ".", "g", "||", "10", ";", "const", "basemap", "=", "BASEMAPS", "[", "config", ".", "h", "]", "||", "'https://basemaps.cartocdn.com/gl/voyager-gl-style/style.json'", ";", "const", "source", "=", "config", ".", "i", "===", "sourceTypes", ".", "DATASET", "?", "`", "${", "config", ".", "a", "}", "`", ":", "`", "\\`", "${", "config", ".", "a", "}", "\\`", "`", ";", "return", "`", "${", "carto", ".", "version", "}", "${", "basemap", "}", "${", "center", ".", "lng", "}", "${", "center", ".", "lat", "}", "${", "zoom", "}", "${", "serverURL", "}", "${", "username", "}", "${", "apiKey", "}", "${", "source", "}", "\\`", "${", "vizSpec", "}", "\\`", "`", ";", "}" ]
Generates an HTML template for the given map configuration
[ "Generates", "an", "HTML", "template", "for", "the", "given", "map", "configuration" ]
2cc704a0f3fda0943b3d3f84dac9466defb18f2c
https://github.com/CartoDB/carto-vl/blob/2cc704a0f3fda0943b3d3f84dac9466defb18f2c/examples/editor/index.js#L390-L454
15,487
CartoDB/carto-vl
src/utils/time/parseISO.js
startOfIsoWeek
function startOfIsoWeek (y, w) { const dow = isoDow(y, 1, 1); const startDay = dow > 4 ? 9 - dow : 2 - dow; const startDate = new Date(y, 0, startDay); return addDays(startDate, (w - 1) * 7); }
javascript
function startOfIsoWeek (y, w) { const dow = isoDow(y, 1, 1); const startDay = dow > 4 ? 9 - dow : 2 - dow; const startDate = new Date(y, 0, startDay); return addDays(startDate, (w - 1) * 7); }
[ "function", "startOfIsoWeek", "(", "y", ",", "w", ")", "{", "const", "dow", "=", "isoDow", "(", "y", ",", "1", ",", "1", ")", ";", "const", "startDay", "=", "dow", ">", "4", "?", "9", "-", "dow", ":", "2", "-", "dow", ";", "const", "startDate", "=", "new", "Date", "(", "y", ",", "0", ",", "startDay", ")", ";", "return", "addDays", "(", "startDate", ",", "(", "w", "-", "1", ")", "*", "7", ")", ";", "}" ]
compute start date of yWw
[ "compute", "start", "date", "of", "yWw" ]
2cc704a0f3fda0943b3d3f84dac9466defb18f2c
https://github.com/CartoDB/carto-vl/blob/2cc704a0f3fda0943b3d3f84dac9466defb18f2c/src/utils/time/parseISO.js#L160-L165
15,488
CartoDB/carto-vl
src/client/rsys.js
wRectangleTiles
function wRectangleTiles (z, wr) { const [wMinx, wMiny, wMaxx, wMaxy] = wr; const n = (1 << z); // for 0 <= z <= 30 equals Math.pow(2, z) const clamp = x => Math.min(Math.max(x, 0), n - 1); // compute tile coordinate ranges const tMinx = clamp(Math.floor(n * (wMinx + 1) * 0.5)); const tMaxx = clamp(Math.ceil(n * (wMaxx + 1) * 0.5) - 1); const tMiny = clamp(Math.floor(n * (1 - wMaxy) * 0.5)); const tMaxy = clamp(Math.ceil(n * (1 - wMiny) * 0.5) - 1); let tiles = []; for (let x = tMinx; x <= tMaxx; ++x) { for (let y = tMiny; y <= tMaxy; ++y) { tiles.push({ x: x, y: y, z: z }); } } return tiles; }
javascript
function wRectangleTiles (z, wr) { const [wMinx, wMiny, wMaxx, wMaxy] = wr; const n = (1 << z); // for 0 <= z <= 30 equals Math.pow(2, z) const clamp = x => Math.min(Math.max(x, 0), n - 1); // compute tile coordinate ranges const tMinx = clamp(Math.floor(n * (wMinx + 1) * 0.5)); const tMaxx = clamp(Math.ceil(n * (wMaxx + 1) * 0.5) - 1); const tMiny = clamp(Math.floor(n * (1 - wMaxy) * 0.5)); const tMaxy = clamp(Math.ceil(n * (1 - wMiny) * 0.5) - 1); let tiles = []; for (let x = tMinx; x <= tMaxx; ++x) { for (let y = tMiny; y <= tMaxy; ++y) { tiles.push({ x: x, y: y, z: z }); } } return tiles; }
[ "function", "wRectangleTiles", "(", "z", ",", "wr", ")", "{", "const", "[", "wMinx", ",", "wMiny", ",", "wMaxx", ",", "wMaxy", "]", "=", "wr", ";", "const", "n", "=", "(", "1", "<<", "z", ")", ";", "// for 0 <= z <= 30 equals Math.pow(2, z)", "const", "clamp", "=", "x", "=>", "Math", ".", "min", "(", "Math", ".", "max", "(", "x", ",", "0", ")", ",", "n", "-", "1", ")", ";", "// compute tile coordinate ranges", "const", "tMinx", "=", "clamp", "(", "Math", ".", "floor", "(", "n", "*", "(", "wMinx", "+", "1", ")", "*", "0.5", ")", ")", ";", "const", "tMaxx", "=", "clamp", "(", "Math", ".", "ceil", "(", "n", "*", "(", "wMaxx", "+", "1", ")", "*", "0.5", ")", "-", "1", ")", ";", "const", "tMiny", "=", "clamp", "(", "Math", ".", "floor", "(", "n", "*", "(", "1", "-", "wMaxy", ")", "*", "0.5", ")", ")", ";", "const", "tMaxy", "=", "clamp", "(", "Math", ".", "ceil", "(", "n", "*", "(", "1", "-", "wMiny", ")", "*", "0.5", ")", "-", "1", ")", ";", "let", "tiles", "=", "[", "]", ";", "for", "(", "let", "x", "=", "tMinx", ";", "x", "<=", "tMaxx", ";", "++", "x", ")", "{", "for", "(", "let", "y", "=", "tMiny", ";", "y", "<=", "tMaxy", ";", "++", "y", ")", "{", "tiles", ".", "push", "(", "{", "x", ":", "x", ",", "y", ":", "y", ",", "z", ":", "z", "}", ")", ";", "}", "}", "return", "tiles", ";", "}" ]
TC tiles of a given zoom level that intersect a W rectangle @param {number} z @param {Array} - rectangle extents [minx, miny, maxx, maxy] @return {Array} - array of TC tiles {x, y, z}
[ "TC", "tiles", "of", "a", "given", "zoom", "level", "that", "intersect", "a", "W", "rectangle" ]
2cc704a0f3fda0943b3d3f84dac9466defb18f2c
https://github.com/CartoDB/carto-vl/blob/2cc704a0f3fda0943b3d3f84dac9466defb18f2c/src/client/rsys.js#L95-L112
15,489
CartoDB/carto-vl
src/renderer/viz/expressions/aggregation/viewport/ViewportAggCalculator.js
_reset
function _reset (viewportExpressions, renderLayer) { const metadata = renderLayer.viz.metadata; viewportExpressions.forEach(expr => expr._resetViewportAgg(metadata, renderLayer)); }
javascript
function _reset (viewportExpressions, renderLayer) { const metadata = renderLayer.viz.metadata; viewportExpressions.forEach(expr => expr._resetViewportAgg(metadata, renderLayer)); }
[ "function", "_reset", "(", "viewportExpressions", ",", "renderLayer", ")", "{", "const", "metadata", "=", "renderLayer", ".", "viz", ".", "metadata", ";", "viewportExpressions", ".", "forEach", "(", "expr", "=>", "expr", ".", "_resetViewportAgg", "(", "metadata", ",", "renderLayer", ")", ")", ";", "}" ]
Reset previous viewport aggregation function values. It assumes that all dataframes of the renderLayer share the same metadata
[ "Reset", "previous", "viewport", "aggregation", "function", "values", ".", "It", "assumes", "that", "all", "dataframes", "of", "the", "renderLayer", "share", "the", "same", "metadata" ]
2cc704a0f3fda0943b3d3f84dac9466defb18f2c
https://github.com/CartoDB/carto-vl/blob/2cc704a0f3fda0943b3d3f84dac9466defb18f2c/src/renderer/viz/expressions/aggregation/viewport/ViewportAggCalculator.js#L43-L46
15,490
CartoDB/carto-vl
src/renderer/viz/expressions/aggregation/viewport/ViewportAggCalculator.js
_runInActiveDataframes
function _runInActiveDataframes (viewportExpressions, renderLayer) { const dataframes = renderLayer.getActiveDataframes(); const inViewportFeaturesIDs = _runInDataframes(viewportExpressions, renderLayer, dataframes); _runImprovedForPartialFeatures(viewportExpressions, renderLayer, inViewportFeaturesIDs); }
javascript
function _runInActiveDataframes (viewportExpressions, renderLayer) { const dataframes = renderLayer.getActiveDataframes(); const inViewportFeaturesIDs = _runInDataframes(viewportExpressions, renderLayer, dataframes); _runImprovedForPartialFeatures(viewportExpressions, renderLayer, inViewportFeaturesIDs); }
[ "function", "_runInActiveDataframes", "(", "viewportExpressions", ",", "renderLayer", ")", "{", "const", "dataframes", "=", "renderLayer", ".", "getActiveDataframes", "(", ")", ";", "const", "inViewportFeaturesIDs", "=", "_runInDataframes", "(", "viewportExpressions", ",", "renderLayer", ",", "dataframes", ")", ";", "_runImprovedForPartialFeatures", "(", "viewportExpressions", ",", "renderLayer", ",", "inViewportFeaturesIDs", ")", ";", "}" ]
Run all viewport aggregations in the active dataframes
[ "Run", "all", "viewport", "aggregations", "in", "the", "active", "dataframes" ]
2cc704a0f3fda0943b3d3f84dac9466defb18f2c
https://github.com/CartoDB/carto-vl/blob/2cc704a0f3fda0943b3d3f84dac9466defb18f2c/src/renderer/viz/expressions/aggregation/viewport/ViewportAggCalculator.js#L51-L56
15,491
CartoDB/carto-vl
src/renderer/viz/expressions/aggregation/viewport/ViewportAggCalculator.js
_runInDataframes
function _runInDataframes (viewportExpressions, renderLayer, dataframes) { const processedFeaturesIDs = new Set(); // same feature can belong to multiple dataframes const viz = renderLayer.viz; const inViewportFeaturesIDs = new Set(); dataframes.forEach(dataframe => { _runInDataframe(viz, viewportExpressions, dataframe, processedFeaturesIDs, inViewportFeaturesIDs); }); return inViewportFeaturesIDs; }
javascript
function _runInDataframes (viewportExpressions, renderLayer, dataframes) { const processedFeaturesIDs = new Set(); // same feature can belong to multiple dataframes const viz = renderLayer.viz; const inViewportFeaturesIDs = new Set(); dataframes.forEach(dataframe => { _runInDataframe(viz, viewportExpressions, dataframe, processedFeaturesIDs, inViewportFeaturesIDs); }); return inViewportFeaturesIDs; }
[ "function", "_runInDataframes", "(", "viewportExpressions", ",", "renderLayer", ",", "dataframes", ")", "{", "const", "processedFeaturesIDs", "=", "new", "Set", "(", ")", ";", "// same feature can belong to multiple dataframes", "const", "viz", "=", "renderLayer", ".", "viz", ";", "const", "inViewportFeaturesIDs", "=", "new", "Set", "(", ")", ";", "dataframes", ".", "forEach", "(", "dataframe", "=>", "{", "_runInDataframe", "(", "viz", ",", "viewportExpressions", ",", "dataframe", ",", "processedFeaturesIDs", ",", "inViewportFeaturesIDs", ")", ";", "}", ")", ";", "return", "inViewportFeaturesIDs", ";", "}" ]
Run all viewport aggregations in the dataframes, and returns a list of featureIDs inside the viewport & not filtered out. That's a list of the features effectively included in the viewportExpressions run
[ "Run", "all", "viewport", "aggregations", "in", "the", "dataframes", "and", "returns", "a", "list", "of", "featureIDs", "inside", "the", "viewport", "&", "not", "filtered", "out", ".", "That", "s", "a", "list", "of", "the", "features", "effectively", "included", "in", "the", "viewportExpressions", "run" ]
2cc704a0f3fda0943b3d3f84dac9466defb18f2c
https://github.com/CartoDB/carto-vl/blob/2cc704a0f3fda0943b3d3f84dac9466defb18f2c/src/renderer/viz/expressions/aggregation/viewport/ViewportAggCalculator.js#L62-L71
15,492
CartoDB/carto-vl
src/renderer/viz/expressions/aggregation/viewport/ViewportAggCalculator.js
_runForPartialViewportFeatures
function _runForPartialViewportFeatures (viewportFeaturesExpressions, renderLayer, featuresIDs) { // Reset previous expressions with (possibly 1 partial) features viewportFeaturesExpressions.forEach(expr => expr._resetViewportAgg(null, renderLayer)); // Gather all pieces per feature const piecesPerFeature = renderLayer.getAllPiecesPerFeature(featuresIDs); // Run viewportFeatures with the whole set of feature pieces viewportFeaturesExpressions.forEach(expr => { for (const featureId in piecesPerFeature) { expr.accumViewportAgg(piecesPerFeature[featureId]); } }); }
javascript
function _runForPartialViewportFeatures (viewportFeaturesExpressions, renderLayer, featuresIDs) { // Reset previous expressions with (possibly 1 partial) features viewportFeaturesExpressions.forEach(expr => expr._resetViewportAgg(null, renderLayer)); // Gather all pieces per feature const piecesPerFeature = renderLayer.getAllPiecesPerFeature(featuresIDs); // Run viewportFeatures with the whole set of feature pieces viewportFeaturesExpressions.forEach(expr => { for (const featureId in piecesPerFeature) { expr.accumViewportAgg(piecesPerFeature[featureId]); } }); }
[ "function", "_runForPartialViewportFeatures", "(", "viewportFeaturesExpressions", ",", "renderLayer", ",", "featuresIDs", ")", "{", "// Reset previous expressions with (possibly 1 partial) features", "viewportFeaturesExpressions", ".", "forEach", "(", "expr", "=>", "expr", ".", "_resetViewportAgg", "(", "null", ",", "renderLayer", ")", ")", ";", "// Gather all pieces per feature", "const", "piecesPerFeature", "=", "renderLayer", ".", "getAllPiecesPerFeature", "(", "featuresIDs", ")", ";", "// Run viewportFeatures with the whole set of feature pieces", "viewportFeaturesExpressions", ".", "forEach", "(", "expr", "=>", "{", "for", "(", "const", "featureId", "in", "piecesPerFeature", ")", "{", "expr", ".", "accumViewportAgg", "(", "piecesPerFeature", "[", "featureId", "]", ")", ";", "}", "}", ")", ";", "}" ]
Rerun viewportFeatures to improve its results, including all feature pieces in dataframes
[ "Rerun", "viewportFeatures", "to", "improve", "its", "results", "including", "all", "feature", "pieces", "in", "dataframes" ]
2cc704a0f3fda0943b3d3f84dac9466defb18f2c
https://github.com/CartoDB/carto-vl/blob/2cc704a0f3fda0943b3d3f84dac9466defb18f2c/src/renderer/viz/expressions/aggregation/viewport/ViewportAggCalculator.js#L133-L146
15,493
CartoDB/carto-vl
src/setup/auth-service.js
checkAuth
function checkAuth (auth) { if (util.isUndefined(auth)) { throw new CartoValidationError('\'auth\'', CartoValidationErrorTypes.MISSING_REQUIRED); } if (!util.isObject(auth)) { throw new CartoValidationError('\'auth\' property must be an object.', CartoValidationErrorTypes.INCORRECT_TYPE); } auth.username = util.isUndefined(auth.username) ? auth.user : auth.username; // backwards compatibility checkApiKey(auth.apiKey); checkUsername(auth.username); }
javascript
function checkAuth (auth) { if (util.isUndefined(auth)) { throw new CartoValidationError('\'auth\'', CartoValidationErrorTypes.MISSING_REQUIRED); } if (!util.isObject(auth)) { throw new CartoValidationError('\'auth\' property must be an object.', CartoValidationErrorTypes.INCORRECT_TYPE); } auth.username = util.isUndefined(auth.username) ? auth.user : auth.username; // backwards compatibility checkApiKey(auth.apiKey); checkUsername(auth.username); }
[ "function", "checkAuth", "(", "auth", ")", "{", "if", "(", "util", ".", "isUndefined", "(", "auth", ")", ")", "{", "throw", "new", "CartoValidationError", "(", "'\\'auth\\''", ",", "CartoValidationErrorTypes", ".", "MISSING_REQUIRED", ")", ";", "}", "if", "(", "!", "util", ".", "isObject", "(", "auth", ")", ")", "{", "throw", "new", "CartoValidationError", "(", "'\\'auth\\' property must be an object.'", ",", "CartoValidationErrorTypes", ".", "INCORRECT_TYPE", ")", ";", "}", "auth", ".", "username", "=", "util", ".", "isUndefined", "(", "auth", ".", "username", ")", "?", "auth", ".", "user", ":", "auth", ".", "username", ";", "// backwards compatibility", "checkApiKey", "(", "auth", ".", "apiKey", ")", ";", "checkUsername", "(", "auth", ".", "username", ")", ";", "}" ]
Check a valid auth parameter. @param {Object} auth
[ "Check", "a", "valid", "auth", "parameter", "." ]
2cc704a0f3fda0943b3d3f84dac9466defb18f2c
https://github.com/CartoDB/carto-vl/blob/2cc704a0f3fda0943b3d3f84dac9466defb18f2c/src/setup/auth-service.js#L41-L51
15,494
pa11y/pa11y-ci
bin/pa11y-ci.js
resolveConfigPath
function resolveConfigPath(configPath) { // Specify a default configPath = configPath || '.pa11yci'; if (configPath[0] !== '/') { configPath = path.join(process.cwd(), configPath); } if (/\.js(on)?$/.test(configPath)) { configPath = configPath.replace(/\.js(on)?$/, ''); } return configPath; }
javascript
function resolveConfigPath(configPath) { // Specify a default configPath = configPath || '.pa11yci'; if (configPath[0] !== '/') { configPath = path.join(process.cwd(), configPath); } if (/\.js(on)?$/.test(configPath)) { configPath = configPath.replace(/\.js(on)?$/, ''); } return configPath; }
[ "function", "resolveConfigPath", "(", "configPath", ")", "{", "// Specify a default", "configPath", "=", "configPath", "||", "'.pa11yci'", ";", "if", "(", "configPath", "[", "0", "]", "!==", "'/'", ")", "{", "configPath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "configPath", ")", ";", "}", "if", "(", "/", "\\.js(on)?$", "/", ".", "test", "(", "configPath", ")", ")", "{", "configPath", "=", "configPath", ".", "replace", "(", "/", "\\.js(on)?$", "/", ",", "''", ")", ";", "}", "return", "configPath", ";", "}" ]
Resolve the config path, and make sure it's relative to the current working directory
[ "Resolve", "the", "config", "path", "and", "make", "sure", "it", "s", "relative", "to", "the", "current", "working", "directory" ]
5b9991c1b016f8be1be272162bb724a9f51554ff
https://github.com/pa11y/pa11y-ci/blob/5b9991c1b016f8be1be272162bb724a9f51554ff/bin/pa11y-ci.js#L142-L152
15,495
pa11y/pa11y-ci
bin/pa11y-ci.js
loadLocalConfigUnmodified
function loadLocalConfigUnmodified(configPath) { try { return JSON.parse(fs.readFileSync(configPath, 'utf-8')); } catch (error) { if (error.code !== 'ENOENT') { throw error; } } }
javascript
function loadLocalConfigUnmodified(configPath) { try { return JSON.parse(fs.readFileSync(configPath, 'utf-8')); } catch (error) { if (error.code !== 'ENOENT') { throw error; } } }
[ "function", "loadLocalConfigUnmodified", "(", "configPath", ")", "{", "try", "{", "return", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "configPath", ",", "'utf-8'", ")", ")", ";", "}", "catch", "(", "error", ")", "{", "if", "(", "error", ".", "code", "!==", "'ENOENT'", ")", "{", "throw", "error", ";", "}", "}", "}" ]
Load the config file using the exact path that was passed in
[ "Load", "the", "config", "file", "using", "the", "exact", "path", "that", "was", "passed", "in" ]
5b9991c1b016f8be1be272162bb724a9f51554ff
https://github.com/pa11y/pa11y-ci/blob/5b9991c1b016f8be1be272162bb724a9f51554ff/bin/pa11y-ci.js#L156-L164
15,496
pa11y/pa11y-ci
bin/pa11y-ci.js
defaultConfig
function defaultConfig(config) { config.urls = config.urls || []; config.defaults = config.defaults || {}; config.defaults.log = config.defaults.log || console; // Setting to undefined rather than 0 allows for a fallback to the default config.defaults.wrapWidth = process.stdout.columns || undefined; if (program.json) { delete config.defaults.log; } return config; }
javascript
function defaultConfig(config) { config.urls = config.urls || []; config.defaults = config.defaults || {}; config.defaults.log = config.defaults.log || console; // Setting to undefined rather than 0 allows for a fallback to the default config.defaults.wrapWidth = process.stdout.columns || undefined; if (program.json) { delete config.defaults.log; } return config; }
[ "function", "defaultConfig", "(", "config", ")", "{", "config", ".", "urls", "=", "config", ".", "urls", "||", "[", "]", ";", "config", ".", "defaults", "=", "config", ".", "defaults", "||", "{", "}", ";", "config", ".", "defaults", ".", "log", "=", "config", ".", "defaults", ".", "log", "||", "console", ";", "// \tSetting to undefined rather than 0 allows for a fallback to the default", "config", ".", "defaults", ".", "wrapWidth", "=", "process", ".", "stdout", ".", "columns", "||", "undefined", ";", "if", "(", "program", ".", "json", ")", "{", "delete", "config", ".", "defaults", ".", "log", ";", "}", "return", "config", ";", "}" ]
Tidy up and default the configurations found in the file the user specified.
[ "Tidy", "up", "and", "default", "the", "configurations", "found", "in", "the", "file", "the", "user", "specified", "." ]
5b9991c1b016f8be1be272162bb724a9f51554ff
https://github.com/pa11y/pa11y-ci/blob/5b9991c1b016f8be1be272162bb724a9f51554ff/bin/pa11y-ci.js#L190-L200
15,497
pa11y/pa11y-ci
bin/pa11y-ci.js
loadSitemapIntoConfig
function loadSitemapIntoConfig(program, config) { const sitemapUrl = program.sitemap; const sitemapFind = ( program.sitemapFind ? new RegExp(program.sitemapFind, 'gi') : null ); const sitemapReplace = program.sitemapReplace || ''; const sitemapExclude = ( program.sitemapExclude ? new RegExp(program.sitemapExclude, 'gi') : null ); return Promise.resolve() .then(() => { return fetch(sitemapUrl); }) .then(response => { return response.text(); }) .then(body => { const $ = cheerio.load(body, { xmlMode: true }); $('url > loc').toArray().forEach(element => { let url = $(element).text(); if (sitemapExclude && url.match(sitemapExclude)) { return; } if (sitemapFind) { url = url.replace(sitemapFind, sitemapReplace); } config.urls.push(url); }); return config; }) .catch(error => { if (error.stack && error.stack.includes('node-fetch')) { throw new Error(`The sitemap "${sitemapUrl}" could not be loaded`); } throw new Error(`The sitemap "${sitemapUrl}" could not be parsed`); }); }
javascript
function loadSitemapIntoConfig(program, config) { const sitemapUrl = program.sitemap; const sitemapFind = ( program.sitemapFind ? new RegExp(program.sitemapFind, 'gi') : null ); const sitemapReplace = program.sitemapReplace || ''; const sitemapExclude = ( program.sitemapExclude ? new RegExp(program.sitemapExclude, 'gi') : null ); return Promise.resolve() .then(() => { return fetch(sitemapUrl); }) .then(response => { return response.text(); }) .then(body => { const $ = cheerio.load(body, { xmlMode: true }); $('url > loc').toArray().forEach(element => { let url = $(element).text(); if (sitemapExclude && url.match(sitemapExclude)) { return; } if (sitemapFind) { url = url.replace(sitemapFind, sitemapReplace); } config.urls.push(url); }); return config; }) .catch(error => { if (error.stack && error.stack.includes('node-fetch')) { throw new Error(`The sitemap "${sitemapUrl}" could not be loaded`); } throw new Error(`The sitemap "${sitemapUrl}" could not be parsed`); }); }
[ "function", "loadSitemapIntoConfig", "(", "program", ",", "config", ")", "{", "const", "sitemapUrl", "=", "program", ".", "sitemap", ";", "const", "sitemapFind", "=", "(", "program", ".", "sitemapFind", "?", "new", "RegExp", "(", "program", ".", "sitemapFind", ",", "'gi'", ")", ":", "null", ")", ";", "const", "sitemapReplace", "=", "program", ".", "sitemapReplace", "||", "''", ";", "const", "sitemapExclude", "=", "(", "program", ".", "sitemapExclude", "?", "new", "RegExp", "(", "program", ".", "sitemapExclude", ",", "'gi'", ")", ":", "null", ")", ";", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "return", "fetch", "(", "sitemapUrl", ")", ";", "}", ")", ".", "then", "(", "response", "=>", "{", "return", "response", ".", "text", "(", ")", ";", "}", ")", ".", "then", "(", "body", "=>", "{", "const", "$", "=", "cheerio", ".", "load", "(", "body", ",", "{", "xmlMode", ":", "true", "}", ")", ";", "$", "(", "'url > loc'", ")", ".", "toArray", "(", ")", ".", "forEach", "(", "element", "=>", "{", "let", "url", "=", "$", "(", "element", ")", ".", "text", "(", ")", ";", "if", "(", "sitemapExclude", "&&", "url", ".", "match", "(", "sitemapExclude", ")", ")", "{", "return", ";", "}", "if", "(", "sitemapFind", ")", "{", "url", "=", "url", ".", "replace", "(", "sitemapFind", ",", "sitemapReplace", ")", ";", "}", "config", ".", "urls", ".", "push", "(", "url", ")", ";", "}", ")", ";", "return", "config", ";", "}", ")", ".", "catch", "(", "error", "=>", "{", "if", "(", "error", ".", "stack", "&&", "error", ".", "stack", ".", "includes", "(", "'node-fetch'", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "sitemapUrl", "}", "`", ")", ";", "}", "throw", "new", "Error", "(", "`", "${", "sitemapUrl", "}", "`", ")", ";", "}", ")", ";", "}" ]
Load a sitemap from a remote URL, parse out the URLs, and add them to an existing config object
[ "Load", "a", "sitemap", "from", "a", "remote", "URL", "parse", "out", "the", "URLs", "and", "add", "them", "to", "an", "existing", "config", "object" ]
5b9991c1b016f8be1be272162bb724a9f51554ff
https://github.com/pa11y/pa11y-ci/blob/5b9991c1b016f8be1be272162bb724a9f51554ff/bin/pa11y-ci.js#L204-L249
15,498
bbc/waveform-data.js
lib/segment.js
WaveformDataSegment
function WaveformDataSegment(context, start, end) { this.context = context; /** * Start index. * * ```javascript * var waveform = new WaveformData({ ... }, WaveformData.adapters.object); * waveform.set_segment(10, 50, "example"); * * console.log(waveform.segments.example.start); // -> 10 * * waveform.offset(20, 50); * console.log(waveform.segments.example.start); // -> 10 * * waveform.offset(70, 100); * console.log(waveform.segments.example.start); // -> 10 * ``` * @type {Integer} Initial starting point of the segment. */ this.start = start; /** * End index. * * ```javascript * var waveform = new WaveformData({ ... }, WaveformData.adapters.object); * waveform.set_segment(10, 50, "example"); * * console.log(waveform.segments.example.end); // -> 50 * * waveform.offset(20, 50); * console.log(waveform.segments.example.end); // -> 50 * * waveform.offset(70, 100); * console.log(waveform.segments.example.end); // -> 50 * ``` * @type {Integer} Initial ending point of the segment. */ this.end = end; }
javascript
function WaveformDataSegment(context, start, end) { this.context = context; /** * Start index. * * ```javascript * var waveform = new WaveformData({ ... }, WaveformData.adapters.object); * waveform.set_segment(10, 50, "example"); * * console.log(waveform.segments.example.start); // -> 10 * * waveform.offset(20, 50); * console.log(waveform.segments.example.start); // -> 10 * * waveform.offset(70, 100); * console.log(waveform.segments.example.start); // -> 10 * ``` * @type {Integer} Initial starting point of the segment. */ this.start = start; /** * End index. * * ```javascript * var waveform = new WaveformData({ ... }, WaveformData.adapters.object); * waveform.set_segment(10, 50, "example"); * * console.log(waveform.segments.example.end); // -> 50 * * waveform.offset(20, 50); * console.log(waveform.segments.example.end); // -> 50 * * waveform.offset(70, 100); * console.log(waveform.segments.example.end); // -> 50 * ``` * @type {Integer} Initial ending point of the segment. */ this.end = end; }
[ "function", "WaveformDataSegment", "(", "context", ",", "start", ",", "end", ")", "{", "this", ".", "context", "=", "context", ";", "/**\n * Start index.\n *\n * ```javascript\n * var waveform = new WaveformData({ ... }, WaveformData.adapters.object);\n * waveform.set_segment(10, 50, \"example\");\n *\n * console.log(waveform.segments.example.start); // -> 10\n *\n * waveform.offset(20, 50);\n * console.log(waveform.segments.example.start); // -> 10\n *\n * waveform.offset(70, 100);\n * console.log(waveform.segments.example.start); // -> 10\n * ```\n * @type {Integer} Initial starting point of the segment.\n */", "this", ".", "start", "=", "start", ";", "/**\n * End index.\n *\n * ```javascript\n * var waveform = new WaveformData({ ... }, WaveformData.adapters.object);\n * waveform.set_segment(10, 50, \"example\");\n *\n * console.log(waveform.segments.example.end); // -> 50\n *\n * waveform.offset(20, 50);\n * console.log(waveform.segments.example.end); // -> 50\n *\n * waveform.offset(70, 100);\n * console.log(waveform.segments.example.end); // -> 50\n * ```\n * @type {Integer} Initial ending point of the segment.\n */", "this", ".", "end", "=", "end", ";", "}" ]
Segments are an easy way to keep track of portions of the described audio file. They return values based on the actual offset. Which means if you change your offset and: * a segment becomes **out of scope**, no data will be returned; * a segment is only **partially included in the offset**, only the visible parts will be returned; * a segment is **fully included in the offset**, its whole content will be returned. Segments are created with the `WaveformData.set_segment(from, to, name?)` method. @see WaveformData.prototype.set_segment @param {WaveformData} context WaveformData instance @param {Integer} start Initial start index @param {Integer} end Initial end index @constructor
[ "Segments", "are", "an", "easy", "way", "to", "keep", "track", "of", "portions", "of", "the", "described", "audio", "file", "." ]
64967ad58aac527642be193eee916698df521efa
https://github.com/bbc/waveform-data.js/blob/64967ad58aac527642be193eee916698df521efa/lib/segment.js#L26-L68
15,499
bbc/waveform-data.js
lib/core.js
WaveformData
function WaveformData(response_data, adapter) { /** * Backend adapter used to manage access to the data. * * @type {Object} */ this.adapter = adapter.fromResponseData(response_data); /** * Defined segments. * * ```javascript * var waveform = new WaveformData({ ... }, WaveformData.adapters.object); * * console.log(waveform.segments.speakerA); // -> undefined * * waveform.set_segment(30, 90, "speakerA"); * * console.log(waveform.segments.speakerA.start); // -> 30 * ``` * * @type {Object} A hash of `WaveformDataSegment` objects. */ this.segments = {}; /** * Defined points. * * ```javascript * var waveform = new WaveformData({ ... }, WaveformData.adapters.object); * * console.log(waveform.points.speakerA); // -> undefined * * waveform.set_point(30, "speakerA"); * * console.log(waveform.points.speakerA.timeStamp); // -> 30 * ``` * * @type {Object} A hash of `WaveformDataPoint` objects. */ this.points = {}; this.offset(0, this.adapter.length); }
javascript
function WaveformData(response_data, adapter) { /** * Backend adapter used to manage access to the data. * * @type {Object} */ this.adapter = adapter.fromResponseData(response_data); /** * Defined segments. * * ```javascript * var waveform = new WaveformData({ ... }, WaveformData.adapters.object); * * console.log(waveform.segments.speakerA); // -> undefined * * waveform.set_segment(30, 90, "speakerA"); * * console.log(waveform.segments.speakerA.start); // -> 30 * ``` * * @type {Object} A hash of `WaveformDataSegment` objects. */ this.segments = {}; /** * Defined points. * * ```javascript * var waveform = new WaveformData({ ... }, WaveformData.adapters.object); * * console.log(waveform.points.speakerA); // -> undefined * * waveform.set_point(30, "speakerA"); * * console.log(waveform.points.speakerA.timeStamp); // -> 30 * ``` * * @type {Object} A hash of `WaveformDataPoint` objects. */ this.points = {}; this.offset(0, this.adapter.length); }
[ "function", "WaveformData", "(", "response_data", ",", "adapter", ")", "{", "/**\n * Backend adapter used to manage access to the data.\n *\n * @type {Object}\n */", "this", ".", "adapter", "=", "adapter", ".", "fromResponseData", "(", "response_data", ")", ";", "/**\n * Defined segments.\n *\n * ```javascript\n * var waveform = new WaveformData({ ... }, WaveformData.adapters.object);\n *\n * console.log(waveform.segments.speakerA); // -> undefined\n *\n * waveform.set_segment(30, 90, \"speakerA\");\n *\n * console.log(waveform.segments.speakerA.start); // -> 30\n * ```\n *\n * @type {Object} A hash of `WaveformDataSegment` objects.\n */", "this", ".", "segments", "=", "{", "}", ";", "/**\n * Defined points.\n *\n * ```javascript\n * var waveform = new WaveformData({ ... }, WaveformData.adapters.object);\n *\n * console.log(waveform.points.speakerA); // -> undefined\n *\n * waveform.set_point(30, \"speakerA\");\n *\n * console.log(waveform.points.speakerA.timeStamp); // -> 30\n * ```\n *\n * @type {Object} A hash of `WaveformDataPoint` objects.\n */", "this", ".", "points", "=", "{", "}", ";", "this", ".", "offset", "(", "0", ",", "this", ".", "adapter", ".", "length", ")", ";", "}" ]
Facade to iterate on audio waveform response. ```javascript var waveform = new WaveformData({ ... }, WaveformData.adapters.object); var json_waveform = new WaveformData(xhr.responseText, WaveformData.adapters.object); var arraybuff_waveform = new WaveformData( getArrayBufferData(), WaveformData.adapters.arraybuffer ); ``` ## Offsets An **offset** is a non-destructive way to iterate on a subset of data. It is the easiest way to **navigate** through data without having to deal with complex calculations. Simply iterate over the data to display them. *Notice*: the default offset is the entire set of data. @param {String|ArrayBuffer|Mixed} response_data Waveform data, to be consumed by the related adapter. @param {WaveformData.adapter|Function} adapter Backend adapter used to manage access to the data. @constructor
[ "Facade", "to", "iterate", "on", "audio", "waveform", "response", "." ]
64967ad58aac527642be193eee916698df521efa
https://github.com/bbc/waveform-data.js/blob/64967ad58aac527642be193eee916698df521efa/lib/core.js#L36-L82