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
18,100
archilogic-com/3dio-js
src/utils/data3d/buffer/triangulate-2d.js
equals
function equals (data, p1, p2) { return data[p1] === data[p2] && data[p1 + 1] === data[p2 + 1] }
javascript
function equals (data, p1, p2) { return data[p1] === data[p2] && data[p1 + 1] === data[p2 + 1] }
[ "function", "equals", "(", "data", ",", "p1", ",", "p2", ")", "{", "return", "data", "[", "p1", "]", "===", "data", "[", "p2", "]", "&&", "data", "[", "p1", "+", "1", "]", "===", "data", "[", "p2", "+", "1", "]", "}" ]
check if two points are equal
[ "check", "if", "two", "points", "are", "equal" ]
23b777b0466095fe53bfb64de6ff1588da51f483
https://github.com/archilogic-com/3dio-js/blob/23b777b0466095fe53bfb64de6ff1588da51f483/src/utils/data3d/buffer/triangulate-2d.js#L626-L628
18,101
archilogic-com/3dio-js
src/staging/get-furniture-alternatives.js
getOffset
function getOffset(a, b) { // for elements that are aligned at the wall we want to compute the offset accordingly var edgeAligned = config.edgeAligned var tags = a.tags a = a.boundingPoints b = b.boundingPoints if (!a || !b) return { x: 0, y: 0, z: 0 } // check if the furniture's virtual origin should be center or edge var isEdgeAligned = edgeAligned.some(function(t) { return tags.includes(t) }) var zOffset // compute offset between edges or centers if (isEdgeAligned) zOffset = a.min[2] - b.min[2] else zOffset = (a.max[2] + a.min[2]) / 2 - (b.max[2] + b.min[2]) / 2 var offset = { // compute offset between centers x: (a.max[0] + a.min[0]) / 2 - (b.max[0] + b.min[0]) / 2, y: 0, z: zOffset } return offset }
javascript
function getOffset(a, b) { // for elements that are aligned at the wall we want to compute the offset accordingly var edgeAligned = config.edgeAligned var tags = a.tags a = a.boundingPoints b = b.boundingPoints if (!a || !b) return { x: 0, y: 0, z: 0 } // check if the furniture's virtual origin should be center or edge var isEdgeAligned = edgeAligned.some(function(t) { return tags.includes(t) }) var zOffset // compute offset between edges or centers if (isEdgeAligned) zOffset = a.min[2] - b.min[2] else zOffset = (a.max[2] + a.min[2]) / 2 - (b.max[2] + b.min[2]) / 2 var offset = { // compute offset between centers x: (a.max[0] + a.min[0]) / 2 - (b.max[0] + b.min[0]) / 2, y: 0, z: zOffset } return offset }
[ "function", "getOffset", "(", "a", ",", "b", ")", "{", "// for elements that are aligned at the wall we want to compute the offset accordingly", "var", "edgeAligned", "=", "config", ".", "edgeAligned", "var", "tags", "=", "a", ".", "tags", "a", "=", "a", ".", "boundingPoints", "b", "=", "b", ".", "boundingPoints", "if", "(", "!", "a", "||", "!", "b", ")", "return", "{", "x", ":", "0", ",", "y", ":", "0", ",", "z", ":", "0", "}", "// check if the furniture's virtual origin should be center or edge", "var", "isEdgeAligned", "=", "edgeAligned", ".", "some", "(", "function", "(", "t", ")", "{", "return", "tags", ".", "includes", "(", "t", ")", "}", ")", "var", "zOffset", "// compute offset between edges or centers", "if", "(", "isEdgeAligned", ")", "zOffset", "=", "a", ".", "min", "[", "2", "]", "-", "b", ".", "min", "[", "2", "]", "else", "zOffset", "=", "(", "a", ".", "max", "[", "2", "]", "+", "a", ".", "min", "[", "2", "]", ")", "/", "2", "-", "(", "b", ".", "max", "[", "2", "]", "+", "b", ".", "min", "[", "2", "]", ")", "/", "2", "var", "offset", "=", "{", "// compute offset between centers", "x", ":", "(", "a", ".", "max", "[", "0", "]", "+", "a", ".", "min", "[", "0", "]", ")", "/", "2", "-", "(", "b", ".", "max", "[", "0", "]", "+", "b", ".", "min", "[", "0", "]", ")", "/", "2", ",", "y", ":", "0", ",", "z", ":", "zOffset", "}", "return", "offset", "}" ]
get offset based on bounding boxes
[ "get", "offset", "based", "on", "bounding", "boxes" ]
23b777b0466095fe53bfb64de6ff1588da51f483
https://github.com/archilogic-com/3dio-js/blob/23b777b0466095fe53bfb64de6ff1588da51f483/src/staging/get-furniture-alternatives.js#L161-L187
18,102
archilogic-com/3dio-js
src/staging/replace-furniture.js
updateElementsById
function updateElementsById(sceneStructure, id, replacement) { var isArray = Array.isArray(sceneStructure) sceneStructure = isArray ? sceneStructure : [sceneStructure] sceneStructure = sceneStructure.map(function(element3d) { // furniture id is stored in src param if (element3d.type === 'interior' && element3d.src.substring(1) === id && replacement.furniture) { // apply new id element3d.src = '!' + replacement.furniture.id // compute new position for items that differ in size and mesh origin var newPosition = getNewPosition(element3d, replacement.offset) // apply new position element3d.x = newPosition.x element3d.y = newPosition.y element3d.z = newPosition.z } // recursivley search tree if (element3d.children && element3d.children.length) { element3d.children = updateElementsById(element3d.children, id, replacement) } return element3d }) return isArray ? sceneStructure : sceneStructure[0] }
javascript
function updateElementsById(sceneStructure, id, replacement) { var isArray = Array.isArray(sceneStructure) sceneStructure = isArray ? sceneStructure : [sceneStructure] sceneStructure = sceneStructure.map(function(element3d) { // furniture id is stored in src param if (element3d.type === 'interior' && element3d.src.substring(1) === id && replacement.furniture) { // apply new id element3d.src = '!' + replacement.furniture.id // compute new position for items that differ in size and mesh origin var newPosition = getNewPosition(element3d, replacement.offset) // apply new position element3d.x = newPosition.x element3d.y = newPosition.y element3d.z = newPosition.z } // recursivley search tree if (element3d.children && element3d.children.length) { element3d.children = updateElementsById(element3d.children, id, replacement) } return element3d }) return isArray ? sceneStructure : sceneStructure[0] }
[ "function", "updateElementsById", "(", "sceneStructure", ",", "id", ",", "replacement", ")", "{", "var", "isArray", "=", "Array", ".", "isArray", "(", "sceneStructure", ")", "sceneStructure", "=", "isArray", "?", "sceneStructure", ":", "[", "sceneStructure", "]", "sceneStructure", "=", "sceneStructure", ".", "map", "(", "function", "(", "element3d", ")", "{", "// furniture id is stored in src param", "if", "(", "element3d", ".", "type", "===", "'interior'", "&&", "element3d", ".", "src", ".", "substring", "(", "1", ")", "===", "id", "&&", "replacement", ".", "furniture", ")", "{", "// apply new id", "element3d", ".", "src", "=", "'!'", "+", "replacement", ".", "furniture", ".", "id", "// compute new position for items that differ in size and mesh origin", "var", "newPosition", "=", "getNewPosition", "(", "element3d", ",", "replacement", ".", "offset", ")", "// apply new position", "element3d", ".", "x", "=", "newPosition", ".", "x", "element3d", ".", "y", "=", "newPosition", ".", "y", "element3d", ".", "z", "=", "newPosition", ".", "z", "}", "// recursivley search tree", "if", "(", "element3d", ".", "children", "&&", "element3d", ".", "children", ".", "length", ")", "{", "element3d", ".", "children", "=", "updateElementsById", "(", "element3d", ".", "children", ",", "id", ",", "replacement", ")", "}", "return", "element3d", "}", ")", "return", "isArray", "?", "sceneStructure", ":", "sceneStructure", "[", "0", "]", "}" ]
search by furniture id and replace params
[ "search", "by", "furniture", "id", "and", "replace", "params" ]
23b777b0466095fe53bfb64de6ff1588da51f483
https://github.com/archilogic-com/3dio-js/blob/23b777b0466095fe53bfb64de6ff1588da51f483/src/staging/replace-furniture.js#L102-L126
18,103
archilogic-com/3dio-js
src/staging/replace-furniture.js
getNewPosition
function getNewPosition(element3d, offset) { var s = Math.sin(element3d.ry / 180 * Math.PI) var c = Math.cos(element3d.ry / 180 * Math.PI) var newPosition = { x: element3d.x + offset.x * c + offset.z * s, y: element3d.y + offset.y, z: element3d.z - offset.x * s + offset.z * c } return newPosition }
javascript
function getNewPosition(element3d, offset) { var s = Math.sin(element3d.ry / 180 * Math.PI) var c = Math.cos(element3d.ry / 180 * Math.PI) var newPosition = { x: element3d.x + offset.x * c + offset.z * s, y: element3d.y + offset.y, z: element3d.z - offset.x * s + offset.z * c } return newPosition }
[ "function", "getNewPosition", "(", "element3d", ",", "offset", ")", "{", "var", "s", "=", "Math", ".", "sin", "(", "element3d", ".", "ry", "/", "180", "*", "Math", ".", "PI", ")", "var", "c", "=", "Math", ".", "cos", "(", "element3d", ".", "ry", "/", "180", "*", "Math", ".", "PI", ")", "var", "newPosition", "=", "{", "x", ":", "element3d", ".", "x", "+", "offset", ".", "x", "*", "c", "+", "offset", ".", "z", "*", "s", ",", "y", ":", "element3d", ".", "y", "+", "offset", ".", "y", ",", "z", ":", "element3d", ".", "z", "-", "offset", ".", "x", "*", "s", "+", "offset", ".", "z", "*", "c", "}", "return", "newPosition", "}" ]
compute new position based on bounding boxes
[ "compute", "new", "position", "based", "on", "bounding", "boxes" ]
23b777b0466095fe53bfb64de6ff1588da51f483
https://github.com/archilogic-com/3dio-js/blob/23b777b0466095fe53bfb64de6ff1588da51f483/src/staging/replace-furniture.js#L129-L139
18,104
archilogic-com/3dio-js
src/utils/processing/when-hi-res-textures-ready.js
pollTexture
function pollTexture(storageId) { var url = getNoCdnUrlFromStorageId(storageId) return poll(function (resolve, reject, next) { checkIfFileExists(url).then(function(exists){ exists ? resolve() : next() }) }) }
javascript
function pollTexture(storageId) { var url = getNoCdnUrlFromStorageId(storageId) return poll(function (resolve, reject, next) { checkIfFileExists(url).then(function(exists){ exists ? resolve() : next() }) }) }
[ "function", "pollTexture", "(", "storageId", ")", "{", "var", "url", "=", "getNoCdnUrlFromStorageId", "(", "storageId", ")", "return", "poll", "(", "function", "(", "resolve", ",", "reject", ",", "next", ")", "{", "checkIfFileExists", "(", "url", ")", ".", "then", "(", "function", "(", "exists", ")", "{", "exists", "?", "resolve", "(", ")", ":", "next", "(", ")", "}", ")", "}", ")", "}" ]
poll for DDS storageIds
[ "poll", "for", "DDS", "storageIds" ]
23b777b0466095fe53bfb64de6ff1588da51f483
https://github.com/archilogic-com/3dio-js/blob/23b777b0466095fe53bfb64de6ff1588da51f483/src/utils/processing/when-hi-res-textures-ready.js#L56-L68
18,105
jshttp/statuses
index.js
populateStatusesMap
function populateStatusesMap (statuses, codes) { var arr = [] Object.keys(codes).forEach(function forEachCode (code) { var message = codes[code] var status = Number(code) // Populate properties statuses[status] = message statuses[message] = status statuses[message.toLowerCase()] = status // Add to array arr.push(status) }) return arr }
javascript
function populateStatusesMap (statuses, codes) { var arr = [] Object.keys(codes).forEach(function forEachCode (code) { var message = codes[code] var status = Number(code) // Populate properties statuses[status] = message statuses[message] = status statuses[message.toLowerCase()] = status // Add to array arr.push(status) }) return arr }
[ "function", "populateStatusesMap", "(", "statuses", ",", "codes", ")", "{", "var", "arr", "=", "[", "]", "Object", ".", "keys", "(", "codes", ")", ".", "forEach", "(", "function", "forEachCode", "(", "code", ")", "{", "var", "message", "=", "codes", "[", "code", "]", "var", "status", "=", "Number", "(", "code", ")", "// Populate properties", "statuses", "[", "status", "]", "=", "message", "statuses", "[", "message", "]", "=", "status", "statuses", "[", "message", ".", "toLowerCase", "(", ")", "]", "=", "status", "// Add to array", "arr", ".", "push", "(", "status", ")", "}", ")", "return", "arr", "}" ]
Populate the statuses map for given codes. @private
[ "Populate", "the", "statuses", "map", "for", "given", "codes", "." ]
5b319c2bca7034943a43a5b4b3268866221661e1
https://github.com/jshttp/statuses/blob/5b319c2bca7034943a43a5b4b3268866221661e1/index.js#L60-L77
18,106
jshttp/statuses
index.js
status
function status (code) { if (typeof code === 'number') { if (!status[code]) throw new Error('invalid status code: ' + code) return code } if (typeof code !== 'string') { throw new TypeError('code must be a number or string') } // '403' var n = parseInt(code, 10) if (!isNaN(n)) { if (!status[n]) throw new Error('invalid status code: ' + n) return n } n = status[code.toLowerCase()] if (!n) throw new Error('invalid status message: "' + code + '"') return n }
javascript
function status (code) { if (typeof code === 'number') { if (!status[code]) throw new Error('invalid status code: ' + code) return code } if (typeof code !== 'string') { throw new TypeError('code must be a number or string') } // '403' var n = parseInt(code, 10) if (!isNaN(n)) { if (!status[n]) throw new Error('invalid status code: ' + n) return n } n = status[code.toLowerCase()] if (!n) throw new Error('invalid status message: "' + code + '"') return n }
[ "function", "status", "(", "code", ")", "{", "if", "(", "typeof", "code", "===", "'number'", ")", "{", "if", "(", "!", "status", "[", "code", "]", ")", "throw", "new", "Error", "(", "'invalid status code: '", "+", "code", ")", "return", "code", "}", "if", "(", "typeof", "code", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'code must be a number or string'", ")", "}", "// '403'", "var", "n", "=", "parseInt", "(", "code", ",", "10", ")", "if", "(", "!", "isNaN", "(", "n", ")", ")", "{", "if", "(", "!", "status", "[", "n", "]", ")", "throw", "new", "Error", "(", "'invalid status code: '", "+", "n", ")", "return", "n", "}", "n", "=", "status", "[", "code", ".", "toLowerCase", "(", ")", "]", "if", "(", "!", "n", ")", "throw", "new", "Error", "(", "'invalid status message: \"'", "+", "code", "+", "'\"'", ")", "return", "n", "}" ]
Get the status code. Given a number, this will throw if it is not a known status code, otherwise the code will be returned. Given a string, the string will be parsed for a number and return the code if valid, otherwise will lookup the code assuming this is the status message. @param {string|number} code @returns {number} @public
[ "Get", "the", "status", "code", "." ]
5b319c2bca7034943a43a5b4b3268866221661e1
https://github.com/jshttp/statuses/blob/5b319c2bca7034943a43a5b4b3268866221661e1/index.js#L93-L113
18,107
heroku/heroku-kafka-jsplugin
lib/clusters.js
fetchProvisionedInfo
function fetchProvisionedInfo (heroku, addon) { return heroku.request({ host: host(addon), method: 'get', path: `/data/kafka/v0/clusters/${addon.id}` }).catch(err => { if (err.statusCode !== 404) throw err cli.exit(1, `${cli.color.addon(addon.name)} is not yet provisioned.\nRun ${cli.color.cmd('heroku kafka:wait')} to wait until the cluster is provisioned.`) }) }
javascript
function fetchProvisionedInfo (heroku, addon) { return heroku.request({ host: host(addon), method: 'get', path: `/data/kafka/v0/clusters/${addon.id}` }).catch(err => { if (err.statusCode !== 404) throw err cli.exit(1, `${cli.color.addon(addon.name)} is not yet provisioned.\nRun ${cli.color.cmd('heroku kafka:wait')} to wait until the cluster is provisioned.`) }) }
[ "function", "fetchProvisionedInfo", "(", "heroku", ",", "addon", ")", "{", "return", "heroku", ".", "request", "(", "{", "host", ":", "host", "(", "addon", ")", ",", "method", ":", "'get'", ",", "path", ":", "`", "${", "addon", ".", "id", "}", "`", "}", ")", ".", "catch", "(", "err", "=>", "{", "if", "(", "err", ".", "statusCode", "!==", "404", ")", "throw", "err", "cli", ".", "exit", "(", "1", ",", "`", "${", "cli", ".", "color", ".", "addon", "(", "addon", ".", "name", ")", "}", "\\n", "${", "cli", ".", "color", ".", "cmd", "(", "'heroku kafka:wait'", ")", "}", "`", ")", "}", ")", "}" ]
Fetch kafka info about a provisioned cluster or exit with failure
[ "Fetch", "kafka", "info", "about", "a", "provisioned", "cluster", "or", "exit", "with", "failure" ]
2f259293e2c4dfd06129055f96b6765d71e390ee
https://github.com/heroku/heroku-kafka-jsplugin/blob/2f259293e2c4dfd06129055f96b6765d71e390ee/lib/clusters.js#L82-L91
18,108
apache/cordova-plugin-test-framework
www/assets/jasmine-2.4.1/jasmine.js
jenkinsHash
function jenkinsHash(key) { var hash, i; for(hash = i = 0; i < key.length; ++i) { hash += key.charCodeAt(i); hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return hash; }
javascript
function jenkinsHash(key) { var hash, i; for(hash = i = 0; i < key.length; ++i) { hash += key.charCodeAt(i); hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return hash; }
[ "function", "jenkinsHash", "(", "key", ")", "{", "var", "hash", ",", "i", ";", "for", "(", "hash", "=", "i", "=", "0", ";", "i", "<", "key", ".", "length", ";", "++", "i", ")", "{", "hash", "+=", "key", ".", "charCodeAt", "(", "i", ")", ";", "hash", "+=", "(", "hash", "<<", "10", ")", ";", "hash", "^=", "(", "hash", ">>", "6", ")", ";", "}", "hash", "+=", "(", "hash", "<<", "3", ")", ";", "hash", "^=", "(", "hash", ">>", "11", ")", ";", "hash", "+=", "(", "hash", "<<", "15", ")", ";", "return", "hash", ";", "}" ]
Bob Jenkins One-at-a-Time Hash algorithm is a non-cryptographic hash function used to get a different output when the key changes slighly. We use your return to sort the children randomly in a consistent way when used in conjunction with a seed
[ "Bob", "Jenkins", "One", "-", "at", "-", "a", "-", "Time", "Hash", "algorithm", "is", "a", "non", "-", "cryptographic", "hash", "function", "used", "to", "get", "a", "different", "output", "when", "the", "key", "changes", "slighly", ".", "We", "use", "your", "return", "to", "sort", "the", "children", "randomly", "in", "a", "consistent", "way", "when", "used", "in", "conjunction", "with", "a", "seed" ]
e09315bc8a5fa16c8a8e712df58d1451e259b4fe
https://github.com/apache/cordova-plugin-test-framework/blob/e09315bc8a5fa16c8a8e712df58d1451e259b4fe/www/assets/jasmine-2.4.1/jasmine.js#L485-L496
18,109
spritejs/sprite-core
lib/modules/animation/patheffect/index.js
match
function match(pathA, pathB) { var minCurves = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 100; var shapesA = pathToShapes(pathA.path); var shapesB = pathToShapes(pathB.path); var lenA = shapesA.length, lenB = shapesB.length; if (lenA > lenB) { _subShapes(shapesB, lenA - lenB); } else if (lenA < lenB) { _upShapes(shapesA, lenB - lenA); } shapesA = (0, _sort.sort)(shapesA, shapesB); shapesA.forEach(function (curves, index) { var lenA = curves.length, lenB = shapesB[index].length; if (lenA > lenB) { if (lenA < minCurves) { _splitCurves(curves, minCurves - lenA); _splitCurves(shapesB[index], minCurves - lenB); } else { _splitCurves(shapesB[index], lenA - lenB); } } else if (lenA < lenB) { if (lenB < minCurves) { _splitCurves(curves, minCurves - lenA); _splitCurves(shapesB[index], minCurves - lenB); } else { _splitCurves(curves, lenB - lenA); } } }); shapesA.forEach(function (curves, index) { shapesA[index] = (0, _sort.sortCurves)(curves, shapesB[index]); }); return [shapesA, shapesB]; }
javascript
function match(pathA, pathB) { var minCurves = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 100; var shapesA = pathToShapes(pathA.path); var shapesB = pathToShapes(pathB.path); var lenA = shapesA.length, lenB = shapesB.length; if (lenA > lenB) { _subShapes(shapesB, lenA - lenB); } else if (lenA < lenB) { _upShapes(shapesA, lenB - lenA); } shapesA = (0, _sort.sort)(shapesA, shapesB); shapesA.forEach(function (curves, index) { var lenA = curves.length, lenB = shapesB[index].length; if (lenA > lenB) { if (lenA < minCurves) { _splitCurves(curves, minCurves - lenA); _splitCurves(shapesB[index], minCurves - lenB); } else { _splitCurves(shapesB[index], lenA - lenB); } } else if (lenA < lenB) { if (lenB < minCurves) { _splitCurves(curves, minCurves - lenA); _splitCurves(shapesB[index], minCurves - lenB); } else { _splitCurves(curves, lenB - lenA); } } }); shapesA.forEach(function (curves, index) { shapesA[index] = (0, _sort.sortCurves)(curves, shapesB[index]); }); return [shapesA, shapesB]; }
[ "function", "match", "(", "pathA", ",", "pathB", ")", "{", "var", "minCurves", "=", "arguments", ".", "length", ">", "2", "&&", "arguments", "[", "2", "]", "!==", "undefined", "?", "arguments", "[", "2", "]", ":", "100", ";", "var", "shapesA", "=", "pathToShapes", "(", "pathA", ".", "path", ")", ";", "var", "shapesB", "=", "pathToShapes", "(", "pathB", ".", "path", ")", ";", "var", "lenA", "=", "shapesA", ".", "length", ",", "lenB", "=", "shapesB", ".", "length", ";", "if", "(", "lenA", ">", "lenB", ")", "{", "_subShapes", "(", "shapesB", ",", "lenA", "-", "lenB", ")", ";", "}", "else", "if", "(", "lenA", "<", "lenB", ")", "{", "_upShapes", "(", "shapesA", ",", "lenB", "-", "lenA", ")", ";", "}", "shapesA", "=", "(", "0", ",", "_sort", ".", "sort", ")", "(", "shapesA", ",", "shapesB", ")", ";", "shapesA", ".", "forEach", "(", "function", "(", "curves", ",", "index", ")", "{", "var", "lenA", "=", "curves", ".", "length", ",", "lenB", "=", "shapesB", "[", "index", "]", ".", "length", ";", "if", "(", "lenA", ">", "lenB", ")", "{", "if", "(", "lenA", "<", "minCurves", ")", "{", "_splitCurves", "(", "curves", ",", "minCurves", "-", "lenA", ")", ";", "_splitCurves", "(", "shapesB", "[", "index", "]", ",", "minCurves", "-", "lenB", ")", ";", "}", "else", "{", "_splitCurves", "(", "shapesB", "[", "index", "]", ",", "lenA", "-", "lenB", ")", ";", "}", "}", "else", "if", "(", "lenA", "<", "lenB", ")", "{", "if", "(", "lenB", "<", "minCurves", ")", "{", "_splitCurves", "(", "curves", ",", "minCurves", "-", "lenA", ")", ";", "_splitCurves", "(", "shapesB", "[", "index", "]", ",", "minCurves", "-", "lenB", ")", ";", "}", "else", "{", "_splitCurves", "(", "curves", ",", "lenB", "-", "lenA", ")", ";", "}", "}", "}", ")", ";", "shapesA", ".", "forEach", "(", "function", "(", "curves", ",", "index", ")", "{", "shapesA", "[", "index", "]", "=", "(", "0", ",", "_sort", ".", "sortCurves", ")", "(", "curves", ",", "shapesB", "[", "index", "]", ")", ";", "}", ")", ";", "return", "[", "shapesA", ",", "shapesB", "]", ";", "}" ]
match two path
[ "match", "two", "path" ]
902bf4650e95daeaad584d3255996304435cc125
https://github.com/spritejs/sprite-core/blob/902bf4650e95daeaad584d3255996304435cc125/lib/modules/animation/patheffect/index.js#L120-L160
18,110
spritejs/sprite-core
lib/utils/decorators.js
absolute
function absolute(elementDescriptor) { if (arguments.length === 3) { elementDescriptor = polyfillLegacy.apply(this, arguments); } var _elementDescriptor7 = elementDescriptor, descriptor = _elementDescriptor7.descriptor; if (descriptor.get) { var _getter = descriptor.get; descriptor.get = function () { this[_attrAbsolute] = true; var ret = _getter.call(this); this[_attrAbsolute] = false; return ret; }; } if (arguments.length === 3) return elementDescriptor.descriptor; return elementDescriptor; }
javascript
function absolute(elementDescriptor) { if (arguments.length === 3) { elementDescriptor = polyfillLegacy.apply(this, arguments); } var _elementDescriptor7 = elementDescriptor, descriptor = _elementDescriptor7.descriptor; if (descriptor.get) { var _getter = descriptor.get; descriptor.get = function () { this[_attrAbsolute] = true; var ret = _getter.call(this); this[_attrAbsolute] = false; return ret; }; } if (arguments.length === 3) return elementDescriptor.descriptor; return elementDescriptor; }
[ "function", "absolute", "(", "elementDescriptor", ")", "{", "if", "(", "arguments", ".", "length", "===", "3", ")", "{", "elementDescriptor", "=", "polyfillLegacy", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "var", "_elementDescriptor7", "=", "elementDescriptor", ",", "descriptor", "=", "_elementDescriptor7", ".", "descriptor", ";", "if", "(", "descriptor", ".", "get", ")", "{", "var", "_getter", "=", "descriptor", ".", "get", ";", "descriptor", ".", "get", "=", "function", "(", ")", "{", "this", "[", "_attrAbsolute", "]", "=", "true", ";", "var", "ret", "=", "_getter", ".", "call", "(", "this", ")", ";", "this", "[", "_attrAbsolute", "]", "=", "false", ";", "return", "ret", ";", "}", ";", "}", "if", "(", "arguments", ".", "length", "===", "3", ")", "return", "elementDescriptor", ".", "descriptor", ";", "return", "elementDescriptor", ";", "}" ]
set tag force to get absolute value from relative attributes
[ "set", "tag", "force", "to", "get", "absolute", "value", "from", "relative", "attributes" ]
902bf4650e95daeaad584d3255996304435cc125
https://github.com/spritejs/sprite-core/blob/902bf4650e95daeaad584d3255996304435cc125/lib/utils/decorators.js#L551-L574
18,111
spritejs/sprite-core
lib/utils/decorators.js
decorators
function decorators() { for (var _len3 = arguments.length, funcs = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { funcs[_key3] = arguments[_key3]; } return function (key, value, descriptor) { var elementDescriptor; if (!descriptor) { elementDescriptor = key; } else { elementDescriptor = { key: key, descriptor: descriptor, value: value }; } var ret = funcs.reduceRight(function (a, b) { return b.call(this, a); }, elementDescriptor); return ret && ret.descriptor; }; }
javascript
function decorators() { for (var _len3 = arguments.length, funcs = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { funcs[_key3] = arguments[_key3]; } return function (key, value, descriptor) { var elementDescriptor; if (!descriptor) { elementDescriptor = key; } else { elementDescriptor = { key: key, descriptor: descriptor, value: value }; } var ret = funcs.reduceRight(function (a, b) { return b.call(this, a); }, elementDescriptor); return ret && ret.descriptor; }; }
[ "function", "decorators", "(", ")", "{", "for", "(", "var", "_len3", "=", "arguments", ".", "length", ",", "funcs", "=", "new", "Array", "(", "_len3", ")", ",", "_key3", "=", "0", ";", "_key3", "<", "_len3", ";", "_key3", "++", ")", "{", "funcs", "[", "_key3", "]", "=", "arguments", "[", "_key3", "]", ";", "}", "return", "function", "(", "key", ",", "value", ",", "descriptor", ")", "{", "var", "elementDescriptor", ";", "if", "(", "!", "descriptor", ")", "{", "elementDescriptor", "=", "key", ";", "}", "else", "{", "elementDescriptor", "=", "{", "key", ":", "key", ",", "descriptor", ":", "descriptor", ",", "value", ":", "value", "}", ";", "}", "var", "ret", "=", "funcs", ".", "reduceRight", "(", "function", "(", "a", ",", "b", ")", "{", "return", "b", ".", "call", "(", "this", ",", "a", ")", ";", "}", ",", "elementDescriptor", ")", ";", "return", "ret", "&&", "ret", ".", "descriptor", ";", "}", ";", "}" ]
return a function to apply any decorators to a descriptor
[ "return", "a", "function", "to", "apply", "any", "decorators", "to", "a", "descriptor" ]
902bf4650e95daeaad584d3255996304435cc125
https://github.com/spritejs/sprite-core/blob/902bf4650e95daeaad584d3255996304435cc125/lib/utils/decorators.js#L673-L696
18,112
CVarisco/create-component-app
src/defaultTemplates/js/common.template.js
generateComponentMethods
function generateComponentMethods(componentMethods) { if (componentMethods.length === 0) { return '' } return componentMethods.reduce((acc, method) => { const methods = `${acc}\n\xa0\xa0\xa0\xa0${method}(){}\n` return methods }, '') }
javascript
function generateComponentMethods(componentMethods) { if (componentMethods.length === 0) { return '' } return componentMethods.reduce((acc, method) => { const methods = `${acc}\n\xa0\xa0\xa0\xa0${method}(){}\n` return methods }, '') }
[ "function", "generateComponentMethods", "(", "componentMethods", ")", "{", "if", "(", "componentMethods", ".", "length", "===", "0", ")", "{", "return", "''", "}", "return", "componentMethods", ".", "reduce", "(", "(", "acc", ",", "method", ")", "=>", "{", "const", "methods", "=", "`", "${", "acc", "}", "\\n", "\\xa0", "\\xa0", "\\xa0", "\\xa0", "${", "method", "}", "\\n", "`", "return", "methods", "}", ",", "''", ")", "}" ]
Create the concatenation of methods string that will be injected into class and pure components @param {Array} componentMethods @return {String} methods
[ "Create", "the", "concatenation", "of", "methods", "string", "that", "will", "be", "injected", "into", "class", "and", "pure", "components" ]
67ae259f8e20153f0ac39fb61831c2473367f2e4
https://github.com/CVarisco/create-component-app/blob/67ae259f8e20153f0ac39fb61831c2473367f2e4/src/defaultTemplates/js/common.template.js#L19-L29
18,113
CVarisco/create-component-app
src/utils.js
generateQuestionsCustom
function generateQuestionsCustom(config, questions) { const mandatoryQuestions = [questions.name, questions.path] return mandatoryQuestions.filter((question) => { if (config[question.name]) { return false } return true }) }
javascript
function generateQuestionsCustom(config, questions) { const mandatoryQuestions = [questions.name, questions.path] return mandatoryQuestions.filter((question) => { if (config[question.name]) { return false } return true }) }
[ "function", "generateQuestionsCustom", "(", "config", ",", "questions", ")", "{", "const", "mandatoryQuestions", "=", "[", "questions", ".", "name", ",", "questions", ".", "path", "]", "return", "mandatoryQuestions", ".", "filter", "(", "(", "question", ")", "=>", "{", "if", "(", "config", "[", "question", ".", "name", "]", ")", "{", "return", "false", "}", "return", "true", "}", ")", "}" ]
If the user want to use custom templates, return filtered questions for only custom configuration @param {object} config @param {object} questions
[ "If", "the", "user", "want", "to", "use", "custom", "templates", "return", "filtered", "questions", "for", "only", "custom", "configuration" ]
67ae259f8e20153f0ac39fb61831c2473367f2e4
https://github.com/CVarisco/create-component-app/blob/67ae259f8e20153f0ac39fb61831c2473367f2e4/src/utils.js#L40-L49
18,114
CVarisco/create-component-app
src/utils.js
generateQuestions
function generateQuestions(config = {}, questions = {}) { const questionKeys = Object.keys(questions) if (!config) { return questionKeys.map(question => questions[question]) } // If type is custom, filter question mandatory to work if (config.type === 'custom') { return generateQuestionsCustom(config, questions) } // filter questions from config object const filteredQuestions = [] questionKeys.forEach((question) => { if (!(question in config)) { filteredQuestions.push(questions[question]) } }) return filteredQuestions }
javascript
function generateQuestions(config = {}, questions = {}) { const questionKeys = Object.keys(questions) if (!config) { return questionKeys.map(question => questions[question]) } // If type is custom, filter question mandatory to work if (config.type === 'custom') { return generateQuestionsCustom(config, questions) } // filter questions from config object const filteredQuestions = [] questionKeys.forEach((question) => { if (!(question in config)) { filteredQuestions.push(questions[question]) } }) return filteredQuestions }
[ "function", "generateQuestions", "(", "config", "=", "{", "}", ",", "questions", "=", "{", "}", ")", "{", "const", "questionKeys", "=", "Object", ".", "keys", "(", "questions", ")", "if", "(", "!", "config", ")", "{", "return", "questionKeys", ".", "map", "(", "question", "=>", "questions", "[", "question", "]", ")", "}", "// If type is custom, filter question mandatory to work", "if", "(", "config", ".", "type", "===", "'custom'", ")", "{", "return", "generateQuestionsCustom", "(", "config", ",", "questions", ")", "}", "// filter questions from config object", "const", "filteredQuestions", "=", "[", "]", "questionKeys", ".", "forEach", "(", "(", "question", ")", "=>", "{", "if", "(", "!", "(", "question", "in", "config", ")", ")", "{", "filteredQuestions", ".", "push", "(", "questions", "[", "question", "]", ")", "}", "}", ")", "return", "filteredQuestions", "}" ]
Generate questions filtered by the config file if exist @param {object} config @param {object} questions @returns {array}
[ "Generate", "questions", "filtered", "by", "the", "config", "file", "if", "exist" ]
67ae259f8e20153f0ac39fb61831c2473367f2e4
https://github.com/CVarisco/create-component-app/blob/67ae259f8e20153f0ac39fb61831c2473367f2e4/src/utils.js#L58-L79
18,115
CVarisco/create-component-app
src/utils.js
createListOfDirectories
function createListOfDirectories(prev, dir) { return { ...prev, [dir.split(path.sep).pop()]: dir, } }
javascript
function createListOfDirectories(prev, dir) { return { ...prev, [dir.split(path.sep).pop()]: dir, } }
[ "function", "createListOfDirectories", "(", "prev", ",", "dir", ")", "{", "return", "{", "...", "prev", ",", "[", "dir", ".", "split", "(", "path", ".", "sep", ")", ".", "pop", "(", ")", "]", ":", "dir", ",", "}", "}" ]
Reduce callback to reduce the list of directories @param {object} prev @param {array} dir
[ "Reduce", "callback", "to", "reduce", "the", "list", "of", "directories" ]
67ae259f8e20153f0ac39fb61831c2473367f2e4
https://github.com/CVarisco/create-component-app/blob/67ae259f8e20153f0ac39fb61831c2473367f2e4/src/utils.js#L86-L91
18,116
CVarisco/create-component-app
src/utils.js
getTemplatesList
function getTemplatesList(customPath = null) { const predefined = getDirectories(DEFAULT_PATH_TEMPLATES).reduce(createListOfDirectories, {}) try { const custom = customPath ? getDirectories(customPath).reduce(createListOfDirectories, {}) : [] return { ...predefined, ...custom } } catch (error) { Logger.warn('The custom templates path that you supply is unreachable') Logger.warn('falling back to defaults templates') return predefined } }
javascript
function getTemplatesList(customPath = null) { const predefined = getDirectories(DEFAULT_PATH_TEMPLATES).reduce(createListOfDirectories, {}) try { const custom = customPath ? getDirectories(customPath).reduce(createListOfDirectories, {}) : [] return { ...predefined, ...custom } } catch (error) { Logger.warn('The custom templates path that you supply is unreachable') Logger.warn('falling back to defaults templates') return predefined } }
[ "function", "getTemplatesList", "(", "customPath", "=", "null", ")", "{", "const", "predefined", "=", "getDirectories", "(", "DEFAULT_PATH_TEMPLATES", ")", ".", "reduce", "(", "createListOfDirectories", ",", "{", "}", ")", "try", "{", "const", "custom", "=", "customPath", "?", "getDirectories", "(", "customPath", ")", ".", "reduce", "(", "createListOfDirectories", ",", "{", "}", ")", ":", "[", "]", "return", "{", "...", "predefined", ",", "...", "custom", "}", "}", "catch", "(", "error", ")", "{", "Logger", ".", "warn", "(", "'The custom templates path that you supply is unreachable'", ")", "Logger", ".", "warn", "(", "'falling back to defaults templates'", ")", "return", "predefined", "}", "}" ]
Returns the list of templates available @param {any} customPath
[ "Returns", "the", "list", "of", "templates", "available" ]
67ae259f8e20153f0ac39fb61831c2473367f2e4
https://github.com/CVarisco/create-component-app/blob/67ae259f8e20153f0ac39fb61831c2473367f2e4/src/utils.js#L97-L108
18,117
CVarisco/create-component-app
src/utils.js
getConfig
function getConfig(configPath, searchPath = process.cwd(), stopDir = homedir()) { const useCustomPath = !!configPath const explorer = cosmiconfig('cca', { sync: true, stopDir }) try { const searchPathAbsolute = !useCustomPath && searchPath const configPathAbsolute = useCustomPath && path.join(process.cwd(), configPath) // search from the root of the process if the user didnt specify a config file, // or use the custom path if a file is passed. const result = explorer.load(searchPathAbsolute, configPathAbsolute) // dont throw if the explorer didnt find a configfile, // instead use default config const config = result ? result.config : {} const filepath = result ? result.filepath : {} if (!result) Logger.log('No config file detected, using defaults.') return { ...config, filepath } } catch (error) { Logger.error('An error occured while parsing your config file. Using defaults...\n\n', error.message) } return {} }
javascript
function getConfig(configPath, searchPath = process.cwd(), stopDir = homedir()) { const useCustomPath = !!configPath const explorer = cosmiconfig('cca', { sync: true, stopDir }) try { const searchPathAbsolute = !useCustomPath && searchPath const configPathAbsolute = useCustomPath && path.join(process.cwd(), configPath) // search from the root of the process if the user didnt specify a config file, // or use the custom path if a file is passed. const result = explorer.load(searchPathAbsolute, configPathAbsolute) // dont throw if the explorer didnt find a configfile, // instead use default config const config = result ? result.config : {} const filepath = result ? result.filepath : {} if (!result) Logger.log('No config file detected, using defaults.') return { ...config, filepath } } catch (error) { Logger.error('An error occured while parsing your config file. Using defaults...\n\n', error.message) } return {} }
[ "function", "getConfig", "(", "configPath", ",", "searchPath", "=", "process", ".", "cwd", "(", ")", ",", "stopDir", "=", "homedir", "(", ")", ")", "{", "const", "useCustomPath", "=", "!", "!", "configPath", "const", "explorer", "=", "cosmiconfig", "(", "'cca'", ",", "{", "sync", ":", "true", ",", "stopDir", "}", ")", "try", "{", "const", "searchPathAbsolute", "=", "!", "useCustomPath", "&&", "searchPath", "const", "configPathAbsolute", "=", "useCustomPath", "&&", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "configPath", ")", "// search from the root of the process if the user didnt specify a config file,", "// or use the custom path if a file is passed.", "const", "result", "=", "explorer", ".", "load", "(", "searchPathAbsolute", ",", "configPathAbsolute", ")", "// dont throw if the explorer didnt find a configfile,", "// instead use default config", "const", "config", "=", "result", "?", "result", ".", "config", ":", "{", "}", "const", "filepath", "=", "result", "?", "result", ".", "filepath", ":", "{", "}", "if", "(", "!", "result", ")", "Logger", ".", "log", "(", "'No config file detected, using defaults.'", ")", "return", "{", "...", "config", ",", "filepath", "}", "}", "catch", "(", "error", ")", "{", "Logger", ".", "error", "(", "'An error occured while parsing your config file. Using defaults...\\n\\n'", ",", "error", ".", "message", ")", "}", "return", "{", "}", "}" ]
Dynamically import a config file if exist @param {any} configPath @param {any} [searchPath=process.cwd()] @param {any} [stopDir=homedir()] @returns {Object} config
[ "Dynamically", "import", "a", "config", "file", "if", "exist" ]
67ae259f8e20153f0ac39fb61831c2473367f2e4
https://github.com/CVarisco/create-component-app/blob/67ae259f8e20153f0ac39fb61831c2473367f2e4/src/utils.js#L118-L140
18,118
CVarisco/create-component-app
src/files.js
getDirectories
function getDirectories(source) { const isDirectory = sourcePath => lstatSync(sourcePath).isDirectory() return readdirSync(source) .map(name => join(source, name)) .filter(isDirectory) }
javascript
function getDirectories(source) { const isDirectory = sourcePath => lstatSync(sourcePath).isDirectory() return readdirSync(source) .map(name => join(source, name)) .filter(isDirectory) }
[ "function", "getDirectories", "(", "source", ")", "{", "const", "isDirectory", "=", "sourcePath", "=>", "lstatSync", "(", "sourcePath", ")", ".", "isDirectory", "(", ")", "return", "readdirSync", "(", "source", ")", ".", "map", "(", "name", "=>", "join", "(", "source", ",", "name", ")", ")", ".", "filter", "(", "isDirectory", ")", "}" ]
fetch a list of dirs inside a dir @param {any} source path of a dir @returns {array} list of the dirs inside
[ "fetch", "a", "list", "of", "dirs", "inside", "a", "dir" ]
67ae259f8e20153f0ac39fb61831c2473367f2e4
https://github.com/CVarisco/create-component-app/blob/67ae259f8e20153f0ac39fb61831c2473367f2e4/src/files.js#L20-L25
18,119
CVarisco/create-component-app
src/files.js
readFile
function readFile(path, fileName) { return new Promise((resolve, reject) => { fs.readFile(`${path}/${fileName}`, 'utf8', (err, content) => { if (err) { return reject(err) } return resolve(content) }) }) }
javascript
function readFile(path, fileName) { return new Promise((resolve, reject) => { fs.readFile(`${path}/${fileName}`, 'utf8', (err, content) => { if (err) { return reject(err) } return resolve(content) }) }) }
[ "function", "readFile", "(", "path", ",", "fileName", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fs", ".", "readFile", "(", "`", "${", "path", "}", "${", "fileName", "}", "`", ",", "'utf8'", ",", "(", "err", ",", "content", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "reject", "(", "err", ")", "}", "return", "resolve", "(", "content", ")", "}", ")", "}", ")", "}" ]
readFile fs promise wrapped @param {string} path @param {string} fileName
[ "readFile", "fs", "promise", "wrapped" ]
67ae259f8e20153f0ac39fb61831c2473367f2e4
https://github.com/CVarisco/create-component-app/blob/67ae259f8e20153f0ac39fb61831c2473367f2e4/src/files.js#L32-L42
18,120
CVarisco/create-component-app
src/files.js
replaceKeys
function replaceKeys(searchString, replacement) { const replacementKeys = { COMPONENT_NAME: replacement, component_name: replacement.toLowerCase(), COMPONENT_CAP_NAME: replacement.toUpperCase(), cOMPONENT_NAME: replacement[0].toLowerCase() + replacement.substr(1), } return Object.keys(replacementKeys).reduce( (acc, curr) => { if (acc.includes(curr)) { const regEx = new RegExp(curr, 'g') return acc.replace(regEx, replacementKeys[curr]) } return acc }, searchString ) }
javascript
function replaceKeys(searchString, replacement) { const replacementKeys = { COMPONENT_NAME: replacement, component_name: replacement.toLowerCase(), COMPONENT_CAP_NAME: replacement.toUpperCase(), cOMPONENT_NAME: replacement[0].toLowerCase() + replacement.substr(1), } return Object.keys(replacementKeys).reduce( (acc, curr) => { if (acc.includes(curr)) { const regEx = new RegExp(curr, 'g') return acc.replace(regEx, replacementKeys[curr]) } return acc }, searchString ) }
[ "function", "replaceKeys", "(", "searchString", ",", "replacement", ")", "{", "const", "replacementKeys", "=", "{", "COMPONENT_NAME", ":", "replacement", ",", "component_name", ":", "replacement", ".", "toLowerCase", "(", ")", ",", "COMPONENT_CAP_NAME", ":", "replacement", ".", "toUpperCase", "(", ")", ",", "cOMPONENT_NAME", ":", "replacement", "[", "0", "]", ".", "toLowerCase", "(", ")", "+", "replacement", ".", "substr", "(", "1", ")", ",", "}", "return", "Object", ".", "keys", "(", "replacementKeys", ")", ".", "reduce", "(", "(", "acc", ",", "curr", ")", "=>", "{", "if", "(", "acc", ".", "includes", "(", "curr", ")", ")", "{", "const", "regEx", "=", "new", "RegExp", "(", "curr", ",", "'g'", ")", "return", "acc", ".", "replace", "(", "regEx", ",", "replacementKeys", "[", "curr", "]", ")", "}", "return", "acc", "}", ",", "searchString", ")", "}" ]
generate the file name @param {string} searchString @param {string} replacement
[ "generate", "the", "file", "name" ]
67ae259f8e20153f0ac39fb61831c2473367f2e4
https://github.com/CVarisco/create-component-app/blob/67ae259f8e20153f0ac39fb61831c2473367f2e4/src/files.js#L49-L67
18,121
CVarisco/create-component-app
src/files.js
generateFilesFromTemplate
async function generateFilesFromTemplate({ name, path, templatesPath }) { try { const files = glob.sync('**/*', { cwd: templatesPath, nodir: true }) const config = getConfig(null, templatesPath, templatesPath) const outputPath = config.noMkdir ? `${path}` : `${path}/${name}` files.map(async (templateFileName) => { // Get the template content const content = await readFile(templatesPath, templateFileName) const replaced = replaceKeys(content, name) // Exist ? const newFileName = replaceKeys(templateFileName, name) // Write the new file with the new content fs.outputFile(`${outputPath}/${newFileName}`, replaced) }) } catch (e) { Logger.error(e.message) } }
javascript
async function generateFilesFromTemplate({ name, path, templatesPath }) { try { const files = glob.sync('**/*', { cwd: templatesPath, nodir: true }) const config = getConfig(null, templatesPath, templatesPath) const outputPath = config.noMkdir ? `${path}` : `${path}/${name}` files.map(async (templateFileName) => { // Get the template content const content = await readFile(templatesPath, templateFileName) const replaced = replaceKeys(content, name) // Exist ? const newFileName = replaceKeys(templateFileName, name) // Write the new file with the new content fs.outputFile(`${outputPath}/${newFileName}`, replaced) }) } catch (e) { Logger.error(e.message) } }
[ "async", "function", "generateFilesFromTemplate", "(", "{", "name", ",", "path", ",", "templatesPath", "}", ")", "{", "try", "{", "const", "files", "=", "glob", ".", "sync", "(", "'**/*'", ",", "{", "cwd", ":", "templatesPath", ",", "nodir", ":", "true", "}", ")", "const", "config", "=", "getConfig", "(", "null", ",", "templatesPath", ",", "templatesPath", ")", "const", "outputPath", "=", "config", ".", "noMkdir", "?", "`", "${", "path", "}", "`", ":", "`", "${", "path", "}", "${", "name", "}", "`", "files", ".", "map", "(", "async", "(", "templateFileName", ")", "=>", "{", "// Get the template content", "const", "content", "=", "await", "readFile", "(", "templatesPath", ",", "templateFileName", ")", "const", "replaced", "=", "replaceKeys", "(", "content", ",", "name", ")", "// Exist ?", "const", "newFileName", "=", "replaceKeys", "(", "templateFileName", ",", "name", ")", "// Write the new file with the new content", "fs", ".", "outputFile", "(", "`", "${", "outputPath", "}", "${", "newFileName", "}", "`", ",", "replaced", ")", "}", ")", "}", "catch", "(", "e", ")", "{", "Logger", ".", "error", "(", "e", ".", "message", ")", "}", "}" ]
Generate component files from custom templates folder Get every single file in the folder @param {string} the name of the component used to create folder and file @param {string} where the component folder is created @param {string} where the custom templates are
[ "Generate", "component", "files", "from", "custom", "templates", "folder", "Get", "every", "single", "file", "in", "the", "folder" ]
67ae259f8e20153f0ac39fb61831c2473367f2e4
https://github.com/CVarisco/create-component-app/blob/67ae259f8e20153f0ac39fb61831c2473367f2e4/src/files.js#L76-L94
18,122
CVarisco/create-component-app
src/files.js
getFileNames
function getFileNames(fileNames = [], componentName) { const defaultFileNames = { testFileName: `${defaultOptions.testFileName}.${componentName}`, componentFileName: componentName, styleFileName: componentName, } const formattedFileNames = Object.keys(fileNames).reduce( (acc, curr) => { acc[curr] = replaceKeys(fileNames[curr], componentName) return acc }, { ...defaultFileNames } ) return formattedFileNames }
javascript
function getFileNames(fileNames = [], componentName) { const defaultFileNames = { testFileName: `${defaultOptions.testFileName}.${componentName}`, componentFileName: componentName, styleFileName: componentName, } const formattedFileNames = Object.keys(fileNames).reduce( (acc, curr) => { acc[curr] = replaceKeys(fileNames[curr], componentName) return acc }, { ...defaultFileNames } ) return formattedFileNames }
[ "function", "getFileNames", "(", "fileNames", "=", "[", "]", ",", "componentName", ")", "{", "const", "defaultFileNames", "=", "{", "testFileName", ":", "`", "${", "defaultOptions", ".", "testFileName", "}", "${", "componentName", "}", "`", ",", "componentFileName", ":", "componentName", ",", "styleFileName", ":", "componentName", ",", "}", "const", "formattedFileNames", "=", "Object", ".", "keys", "(", "fileNames", ")", ".", "reduce", "(", "(", "acc", ",", "curr", ")", "=>", "{", "acc", "[", "curr", "]", "=", "replaceKeys", "(", "fileNames", "[", "curr", "]", ",", "componentName", ")", "return", "acc", "}", ",", "{", "...", "defaultFileNames", "}", ")", "return", "formattedFileNames", "}" ]
Return the default names replace from user filenames @param {object} fileNames object with the user selected filenames @param {string} componentName @return {object} with the correct filenames
[ "Return", "the", "default", "names", "replace", "from", "user", "filenames" ]
67ae259f8e20153f0ac39fb61831c2473367f2e4
https://github.com/CVarisco/create-component-app/blob/67ae259f8e20153f0ac39fb61831c2473367f2e4/src/files.js#L102-L118
18,123
CVarisco/create-component-app
src/files.js
generateFiles
function generateFiles(params) { const { type, name, fileNames, path, indexFile, cssExtension, componentMethods, jsExtension, connected, includeStories, includeTests, } = params const destination = `${path}/${name}` const { testFileName, componentFileName, styleFileName } = getFileNames(fileNames, name) if (indexFile || connected) { fs.outputFile(`${destination}/index.js`, generateIndexFile(componentFileName, connected)) } if (includeStories) { fs.outputFile(`${destination}/${name}.stories.${jsExtension}`, generateStorybookTemplate(name)) } if (includeTests) { fs.outputFile(`${destination}/${testFileName}.${jsExtension}`, generateTestTemplate(name)) } // Create js file fs.outputFile( `${destination}/${componentFileName}.${jsExtension}`, generateComponentTemplate(type, componentFileName, { cssExtension, componentMethods, styleFileName, }) ) // Create css file if (cssExtension) { fs.outputFile( `${destination}/${styleFileName}.${cssExtension}`, generateStyleFile(styleFileName) ) } }
javascript
function generateFiles(params) { const { type, name, fileNames, path, indexFile, cssExtension, componentMethods, jsExtension, connected, includeStories, includeTests, } = params const destination = `${path}/${name}` const { testFileName, componentFileName, styleFileName } = getFileNames(fileNames, name) if (indexFile || connected) { fs.outputFile(`${destination}/index.js`, generateIndexFile(componentFileName, connected)) } if (includeStories) { fs.outputFile(`${destination}/${name}.stories.${jsExtension}`, generateStorybookTemplate(name)) } if (includeTests) { fs.outputFile(`${destination}/${testFileName}.${jsExtension}`, generateTestTemplate(name)) } // Create js file fs.outputFile( `${destination}/${componentFileName}.${jsExtension}`, generateComponentTemplate(type, componentFileName, { cssExtension, componentMethods, styleFileName, }) ) // Create css file if (cssExtension) { fs.outputFile( `${destination}/${styleFileName}.${cssExtension}`, generateStyleFile(styleFileName) ) } }
[ "function", "generateFiles", "(", "params", ")", "{", "const", "{", "type", ",", "name", ",", "fileNames", ",", "path", ",", "indexFile", ",", "cssExtension", ",", "componentMethods", ",", "jsExtension", ",", "connected", ",", "includeStories", ",", "includeTests", ",", "}", "=", "params", "const", "destination", "=", "`", "${", "path", "}", "${", "name", "}", "`", "const", "{", "testFileName", ",", "componentFileName", ",", "styleFileName", "}", "=", "getFileNames", "(", "fileNames", ",", "name", ")", "if", "(", "indexFile", "||", "connected", ")", "{", "fs", ".", "outputFile", "(", "`", "${", "destination", "}", "`", ",", "generateIndexFile", "(", "componentFileName", ",", "connected", ")", ")", "}", "if", "(", "includeStories", ")", "{", "fs", ".", "outputFile", "(", "`", "${", "destination", "}", "${", "name", "}", "${", "jsExtension", "}", "`", ",", "generateStorybookTemplate", "(", "name", ")", ")", "}", "if", "(", "includeTests", ")", "{", "fs", ".", "outputFile", "(", "`", "${", "destination", "}", "${", "testFileName", "}", "${", "jsExtension", "}", "`", ",", "generateTestTemplate", "(", "name", ")", ")", "}", "// Create js file", "fs", ".", "outputFile", "(", "`", "${", "destination", "}", "${", "componentFileName", "}", "${", "jsExtension", "}", "`", ",", "generateComponentTemplate", "(", "type", ",", "componentFileName", ",", "{", "cssExtension", ",", "componentMethods", ",", "styleFileName", ",", "}", ")", ")", "// Create css file", "if", "(", "cssExtension", ")", "{", "fs", ".", "outputFile", "(", "`", "${", "destination", "}", "${", "styleFileName", "}", "${", "cssExtension", "}", "`", ",", "generateStyleFile", "(", "styleFileName", ")", ")", "}", "}" ]
Generate component files @param {object} params object with: @param {string} type: the type of component template @param {object} fileNames: object that contains the filenames to replace @param {string} name: the name of the component used to create folder and file @param {string} path: where the component folder is created @param {string} cssExtension: the extension of the css file @param {string} jsExtension: the extension of the component file @param {array} componentMethods: Array of strings of methods to include in a class component @param {boolean} indexFile: include or not an index file @param {boolean} connected: include or not the connect function of redux @param {boolean} includeStories: include or not the storybook file @param {boolean} includeTests: include or not the test file
[ "Generate", "component", "files" ]
67ae259f8e20153f0ac39fb61831c2473367f2e4
https://github.com/CVarisco/create-component-app/blob/67ae259f8e20153f0ac39fb61831c2473367f2e4/src/files.js#L136-L183
18,124
thibauts/node-castv2-client
lib/controllers/heartbeat.js
HeartbeatController
function HeartbeatController(client, sourceId, destinationId) { JsonController.call(this, client, sourceId, destinationId, 'urn:x-cast:com.google.cast.tp.heartbeat'); this.pingTimer = null; this.timeout = null; this.intervalValue = DEFAULT_INTERVAL; this.on('message', onmessage); this.once('close', onclose); var self = this; function onmessage(data, broadcast) { if(data.type === 'PONG') { self.emit('pong'); } } function onclose() { self.removeListener('message', onmessage); self.stop(); } }
javascript
function HeartbeatController(client, sourceId, destinationId) { JsonController.call(this, client, sourceId, destinationId, 'urn:x-cast:com.google.cast.tp.heartbeat'); this.pingTimer = null; this.timeout = null; this.intervalValue = DEFAULT_INTERVAL; this.on('message', onmessage); this.once('close', onclose); var self = this; function onmessage(data, broadcast) { if(data.type === 'PONG') { self.emit('pong'); } } function onclose() { self.removeListener('message', onmessage); self.stop(); } }
[ "function", "HeartbeatController", "(", "client", ",", "sourceId", ",", "destinationId", ")", "{", "JsonController", ".", "call", "(", "this", ",", "client", ",", "sourceId", ",", "destinationId", ",", "'urn:x-cast:com.google.cast.tp.heartbeat'", ")", ";", "this", ".", "pingTimer", "=", "null", ";", "this", ".", "timeout", "=", "null", ";", "this", ".", "intervalValue", "=", "DEFAULT_INTERVAL", ";", "this", ".", "on", "(", "'message'", ",", "onmessage", ")", ";", "this", ".", "once", "(", "'close'", ",", "onclose", ")", ";", "var", "self", "=", "this", ";", "function", "onmessage", "(", "data", ",", "broadcast", ")", "{", "if", "(", "data", ".", "type", "===", "'PONG'", ")", "{", "self", ".", "emit", "(", "'pong'", ")", ";", "}", "}", "function", "onclose", "(", ")", "{", "self", ".", "removeListener", "(", "'message'", ",", "onmessage", ")", ";", "self", ".", "stop", "(", ")", ";", "}", "}" ]
timeouts after 3 intervals
[ "timeouts", "after", "3", "intervals" ]
a083b71f747557c1f3d5411abe7142e186ed9732
https://github.com/thibauts/node-castv2-client/blob/a083b71f747557c1f3d5411abe7142e186ed9732/lib/controllers/heartbeat.js#L8-L31
18,125
holidaypirates/nucleus
src/messages/errors.js
function(key, type, validKeys, raw) { return { title: 'Annotation ' + chalk.underline('@' + key) + ' not allowed for type ' + type + ' of ' + chalk.underline(raw.descriptor) + ' in ' + raw.file, text: 'Valid annotations are @' + validKeys.join(', @') + '. This element will not appear in the final StyleGuide until you fix this error.' }; }
javascript
function(key, type, validKeys, raw) { return { title: 'Annotation ' + chalk.underline('@' + key) + ' not allowed for type ' + type + ' of ' + chalk.underline(raw.descriptor) + ' in ' + raw.file, text: 'Valid annotations are @' + validKeys.join(', @') + '. This element will not appear in the final StyleGuide until you fix this error.' }; }
[ "function", "(", "key", ",", "type", ",", "validKeys", ",", "raw", ")", "{", "return", "{", "title", ":", "'Annotation '", "+", "chalk", ".", "underline", "(", "'@'", "+", "key", ")", "+", "' not allowed for type '", "+", "type", "+", "' of '", "+", "chalk", ".", "underline", "(", "raw", ".", "descriptor", ")", "+", "' in '", "+", "raw", ".", "file", ",", "text", ":", "'Valid annotations are @'", "+", "validKeys", ".", "join", "(", "', @'", ")", "+", "'. This element will not appear in the final StyleGuide until you fix this error.'", "}", ";", "}" ]
Whenever there are annotations that are not allowed for certain entity types.
[ "Whenever", "there", "are", "annotations", "that", "are", "not", "allowed", "for", "certain", "entity", "types", "." ]
4baca8555350655a062d9201c6266528d885f3e8
https://github.com/holidaypirates/nucleus/blob/4baca8555350655a062d9201c6266528d885f3e8/src/messages/errors.js#L21-L27
18,126
verbose/verb
lib/plugins/format.js
fixList
function fixList(str) { str = str.replace(/([ ]{1,4}[+-] \[?[^)]+\)?)\n\n\* /gm, '$1\n* '); str = str.split('__{_}_*').join('**{*}**'); return str; }
javascript
function fixList(str) { str = str.replace(/([ ]{1,4}[+-] \[?[^)]+\)?)\n\n\* /gm, '$1\n* '); str = str.split('__{_}_*').join('**{*}**'); return str; }
[ "function", "fixList", "(", "str", ")", "{", "str", "=", "str", ".", "replace", "(", "/", "([ ]{1,4}[+-] \\[?[^)]+\\)?)\\n\\n\\* ", "/", "gm", ",", "'$1\\n* '", ")", ";", "str", "=", "str", ".", "split", "(", "'__{_}_*'", ")", ".", "join", "(", "'**{*}**'", ")", ";", "return", "str", ";", "}" ]
Fix list formatting
[ "Fix", "list", "formatting" ]
ec545b12d76a2c64996a7d9c078641341122ae18
https://github.com/verbose/verb/blob/ec545b12d76a2c64996a7d9c078641341122ae18/lib/plugins/format.js#L54-L58
18,127
verbose/verb
lib/plugins/format.js
noformat
function noformat(app, file, locals, argv) { return app.isTrue('noformat') || app.isFalse('format') || file.noformat === true || file.format === false || locals.noformat === true || locals.format === false || argv.noformat === true || argv.format === false; }
javascript
function noformat(app, file, locals, argv) { return app.isTrue('noformat') || app.isFalse('format') || file.noformat === true || file.format === false || locals.noformat === true || locals.format === false || argv.noformat === true || argv.format === false; }
[ "function", "noformat", "(", "app", ",", "file", ",", "locals", ",", "argv", ")", "{", "return", "app", ".", "isTrue", "(", "'noformat'", ")", "||", "app", ".", "isFalse", "(", "'format'", ")", "||", "file", ".", "noformat", "===", "true", "||", "file", ".", "format", "===", "false", "||", "locals", ".", "noformat", "===", "true", "||", "locals", ".", "format", "===", "false", "||", "argv", ".", "noformat", "===", "true", "||", "argv", ".", "format", "===", "false", ";", "}" ]
Push the `file` through if the user has specfied not to format it.
[ "Push", "the", "file", "through", "if", "the", "user", "has", "specfied", "not", "to", "format", "it", "." ]
ec545b12d76a2c64996a7d9c078641341122ae18
https://github.com/verbose/verb/blob/ec545b12d76a2c64996a7d9c078641341122ae18/lib/plugins/format.js#L80-L85
18,128
verbose/verb
lib/transforms/env/ignore.js
gitignore
function gitignore(cwd, fp, arr) { fp = path.resolve(cwd, fp); if (!fs.existsSync(fp)) { return utils.defaultIgnores; } var str = fs.readFileSync(fp, 'utf8'); return parse(str, arr); }
javascript
function gitignore(cwd, fp, arr) { fp = path.resolve(cwd, fp); if (!fs.existsSync(fp)) { return utils.defaultIgnores; } var str = fs.readFileSync(fp, 'utf8'); return parse(str, arr); }
[ "function", "gitignore", "(", "cwd", ",", "fp", ",", "arr", ")", "{", "fp", "=", "path", ".", "resolve", "(", "cwd", ",", "fp", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "fp", ")", ")", "{", "return", "utils", ".", "defaultIgnores", ";", "}", "var", "str", "=", "fs", ".", "readFileSync", "(", "fp", ",", "'utf8'", ")", ";", "return", "parse", "(", "str", ",", "arr", ")", ";", "}" ]
Parse the local `.gitignore` file and add the resulting ignore patterns.
[ "Parse", "the", "local", ".", "gitignore", "file", "and", "add", "the", "resulting", "ignore", "patterns", "." ]
ec545b12d76a2c64996a7d9c078641341122ae18
https://github.com/verbose/verb/blob/ec545b12d76a2c64996a7d9c078641341122ae18/lib/transforms/env/ignore.js#L26-L33
18,129
verbose/verb
lib/stack.js
createStack
function createStack(app, plugins) { if (app.enabled('minimal config')) { return es.pipe.apply(es, []); } function enabled(acc, plugin, name) { if (plugin == null) { acc.push(through.obj()); } if (app.enabled(name + ' plugin')) { acc.push(plugin); } return acc; } var arr = _.reduce(plugins, enabled, []); return es.pipe.apply(es, arr); }
javascript
function createStack(app, plugins) { if (app.enabled('minimal config')) { return es.pipe.apply(es, []); } function enabled(acc, plugin, name) { if (plugin == null) { acc.push(through.obj()); } if (app.enabled(name + ' plugin')) { acc.push(plugin); } return acc; } var arr = _.reduce(plugins, enabled, []); return es.pipe.apply(es, arr); }
[ "function", "createStack", "(", "app", ",", "plugins", ")", "{", "if", "(", "app", ".", "enabled", "(", "'minimal config'", ")", ")", "{", "return", "es", ".", "pipe", ".", "apply", "(", "es", ",", "[", "]", ")", ";", "}", "function", "enabled", "(", "acc", ",", "plugin", ",", "name", ")", "{", "if", "(", "plugin", "==", "null", ")", "{", "acc", ".", "push", "(", "through", ".", "obj", "(", ")", ")", ";", "}", "if", "(", "app", ".", "enabled", "(", "name", "+", "' plugin'", ")", ")", "{", "acc", ".", "push", "(", "plugin", ")", ";", "}", "return", "acc", ";", "}", "var", "arr", "=", "_", ".", "reduce", "(", "plugins", ",", "enabled", ",", "[", "]", ")", ";", "return", "es", ".", "pipe", ".", "apply", "(", "es", ",", "arr", ")", ";", "}" ]
Create the default plugin stack based on user settings. Disable a plugin by passing the name of the plugin + ` plugin` to `app.disable()`, **Example:** ```js app.disable('src:foo plugin'); app.disable('src:bar plugin'); ```
[ "Create", "the", "default", "plugin", "stack", "based", "on", "user", "settings", "." ]
ec545b12d76a2c64996a7d9c078641341122ae18
https://github.com/verbose/verb/blob/ec545b12d76a2c64996a7d9c078641341122ae18/lib/stack.js#L81-L96
18,130
verbose/verb
lib/plugins/reflinks.js
enabled
function enabled(app, file, options, argv) { var template = extend({}, file.locals, file.options, file.data); return isTrue(argv, 'reflinks') || isTrue(template, 'reflinks') || isTrue(options, 'reflinks') || isTrue(app.options, 'reflinks'); }
javascript
function enabled(app, file, options, argv) { var template = extend({}, file.locals, file.options, file.data); return isTrue(argv, 'reflinks') || isTrue(template, 'reflinks') || isTrue(options, 'reflinks') || isTrue(app.options, 'reflinks'); }
[ "function", "enabled", "(", "app", ",", "file", ",", "options", ",", "argv", ")", "{", "var", "template", "=", "extend", "(", "{", "}", ",", "file", ".", "locals", ",", "file", ".", "options", ",", "file", ".", "data", ")", ";", "return", "isTrue", "(", "argv", ",", "'reflinks'", ")", "||", "isTrue", "(", "template", ",", "'reflinks'", ")", "||", "isTrue", "(", "options", ",", "'reflinks'", ")", "||", "isTrue", "(", "app", ".", "options", ",", "'reflinks'", ")", ";", "}" ]
Push the `file` through if the user has specfied not to generate reflinks.
[ "Push", "the", "file", "through", "if", "the", "user", "has", "specfied", "not", "to", "generate", "reflinks", "." ]
ec545b12d76a2c64996a7d9c078641341122ae18
https://github.com/verbose/verb/blob/ec545b12d76a2c64996a7d9c078641341122ae18/lib/plugins/reflinks.js#L66-L72
18,131
danielstjules/buddy.js
lib/reporters/json.js
JSONReporter
function JSONReporter(detector) { BaseReporter.call(this, detector); detector.on('start', function() { process.stdout.write('['); }); detector.on('end', function() { process.stdout.write("]\n"); }); }
javascript
function JSONReporter(detector) { BaseReporter.call(this, detector); detector.on('start', function() { process.stdout.write('['); }); detector.on('end', function() { process.stdout.write("]\n"); }); }
[ "function", "JSONReporter", "(", "detector", ")", "{", "BaseReporter", ".", "call", "(", "this", ",", "detector", ")", ";", "detector", ".", "on", "(", "'start'", ",", "function", "(", ")", "{", "process", ".", "stdout", ".", "write", "(", "'['", ")", ";", "}", ")", ";", "detector", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "process", ".", "stdout", ".", "write", "(", "\"]\\n\"", ")", ";", "}", ")", ";", "}" ]
A JSON reporter that displays the file, line number, value, associated line, and context of any found magic number. @constructor @param {Detector} detector The instance on which to register its listeners
[ "A", "JSON", "reporter", "that", "displays", "the", "file", "line", "number", "value", "associated", "line", "and", "context", "of", "any", "found", "magic", "number", "." ]
57d8cf14f3550cb0a49dd44f48e216f3aa4ee800
https://github.com/danielstjules/buddy.js/blob/57d8cf14f3550cb0a49dd44f48e216f3aa4ee800/lib/reporters/json.js#L12-L22
18,132
yathit/ydn-db
src/ydn/db/conn/indexed_db.js
function(db, opt_err) { if (df.hasFired()) { goog.log.warning(me.logger, 'database already set.'); } else if (goog.isDef(opt_err)) { goog.log.warning(me.logger, opt_err ? opt_err.message : 'Error received.'); me.idx_db_ = null; df.errback(opt_err); } else { goog.asserts.assertObject(db, 'db'); me.idx_db_ = db; me.idx_db_.onabort = function(e) { goog.log.finest(me.logger, me + ': abort'); var request = /** @type {IDBRequest} */ (e.target); me.onError(request.error); }; me.idx_db_.onerror = function(e) { if (ydn.db.con.IndexedDb.DEBUG) { goog.global.console.log(e); } goog.log.finest(me.logger, me + ': error'); var request = /** @type {IDBRequest} */ (e.target); me.onError(request.error); }; /** * @this {null} * @param {IDBVersionChangeEvent} event event. */ me.idx_db_.onversionchange = function(event) { // Handle version changes while a web app is open in another tab // https://developer.mozilla.org/en-US/docs/IndexedDB/Using_IndexedDB# // Version_changes_while_a_web_app_is_open_in_another_tab // if (ydn.db.con.IndexedDb.DEBUG) { goog.global.console.log([this, event]); } goog.log.finest(me.logger, me + ' closing connection for onversionchange to: ' + event.version); if (me.idx_db_) { me.idx_db_.onabort = null; me.idx_db_.onblocked = null; me.idx_db_.onerror = null; me.idx_db_.onversionchange = null; me.onVersionChange(event); if (!event.defaultPrevented) { me.idx_db_.close(); me.idx_db_ = null; var e = new Error(); e.name = event.type; me.onFail(e); } } }; df.callback(parseFloat(old_version)); } }
javascript
function(db, opt_err) { if (df.hasFired()) { goog.log.warning(me.logger, 'database already set.'); } else if (goog.isDef(opt_err)) { goog.log.warning(me.logger, opt_err ? opt_err.message : 'Error received.'); me.idx_db_ = null; df.errback(opt_err); } else { goog.asserts.assertObject(db, 'db'); me.idx_db_ = db; me.idx_db_.onabort = function(e) { goog.log.finest(me.logger, me + ': abort'); var request = /** @type {IDBRequest} */ (e.target); me.onError(request.error); }; me.idx_db_.onerror = function(e) { if (ydn.db.con.IndexedDb.DEBUG) { goog.global.console.log(e); } goog.log.finest(me.logger, me + ': error'); var request = /** @type {IDBRequest} */ (e.target); me.onError(request.error); }; /** * @this {null} * @param {IDBVersionChangeEvent} event event. */ me.idx_db_.onversionchange = function(event) { // Handle version changes while a web app is open in another tab // https://developer.mozilla.org/en-US/docs/IndexedDB/Using_IndexedDB# // Version_changes_while_a_web_app_is_open_in_another_tab // if (ydn.db.con.IndexedDb.DEBUG) { goog.global.console.log([this, event]); } goog.log.finest(me.logger, me + ' closing connection for onversionchange to: ' + event.version); if (me.idx_db_) { me.idx_db_.onabort = null; me.idx_db_.onblocked = null; me.idx_db_.onerror = null; me.idx_db_.onversionchange = null; me.onVersionChange(event); if (!event.defaultPrevented) { me.idx_db_.close(); me.idx_db_ = null; var e = new Error(); e.name = event.type; me.onFail(e); } } }; df.callback(parseFloat(old_version)); } }
[ "function", "(", "db", ",", "opt_err", ")", "{", "if", "(", "df", ".", "hasFired", "(", ")", ")", "{", "goog", ".", "log", ".", "warning", "(", "me", ".", "logger", ",", "'database already set.'", ")", ";", "}", "else", "if", "(", "goog", ".", "isDef", "(", "opt_err", ")", ")", "{", "goog", ".", "log", ".", "warning", "(", "me", ".", "logger", ",", "opt_err", "?", "opt_err", ".", "message", ":", "'Error received.'", ")", ";", "me", ".", "idx_db_", "=", "null", ";", "df", ".", "errback", "(", "opt_err", ")", ";", "}", "else", "{", "goog", ".", "asserts", ".", "assertObject", "(", "db", ",", "'db'", ")", ";", "me", ".", "idx_db_", "=", "db", ";", "me", ".", "idx_db_", ".", "onabort", "=", "function", "(", "e", ")", "{", "goog", ".", "log", ".", "finest", "(", "me", ".", "logger", ",", "me", "+", "': abort'", ")", ";", "var", "request", "=", "/** @type {IDBRequest} */", "(", "e", ".", "target", ")", ";", "me", ".", "onError", "(", "request", ".", "error", ")", ";", "}", ";", "me", ".", "idx_db_", ".", "onerror", "=", "function", "(", "e", ")", "{", "if", "(", "ydn", ".", "db", ".", "con", ".", "IndexedDb", ".", "DEBUG", ")", "{", "goog", ".", "global", ".", "console", ".", "log", "(", "e", ")", ";", "}", "goog", ".", "log", ".", "finest", "(", "me", ".", "logger", ",", "me", "+", "': error'", ")", ";", "var", "request", "=", "/** @type {IDBRequest} */", "(", "e", ".", "target", ")", ";", "me", ".", "onError", "(", "request", ".", "error", ")", ";", "}", ";", "/**\n * @this {null}\n * @param {IDBVersionChangeEvent} event event.\n */", "me", ".", "idx_db_", ".", "onversionchange", "=", "function", "(", "event", ")", "{", "// Handle version changes while a web app is open in another tab", "// https://developer.mozilla.org/en-US/docs/IndexedDB/Using_IndexedDB#", "// Version_changes_while_a_web_app_is_open_in_another_tab", "//", "if", "(", "ydn", ".", "db", ".", "con", ".", "IndexedDb", ".", "DEBUG", ")", "{", "goog", ".", "global", ".", "console", ".", "log", "(", "[", "this", ",", "event", "]", ")", ";", "}", "goog", ".", "log", ".", "finest", "(", "me", ".", "logger", ",", "me", "+", "' closing connection for onversionchange to: '", "+", "event", ".", "version", ")", ";", "if", "(", "me", ".", "idx_db_", ")", "{", "me", ".", "idx_db_", ".", "onabort", "=", "null", ";", "me", ".", "idx_db_", ".", "onblocked", "=", "null", ";", "me", ".", "idx_db_", ".", "onerror", "=", "null", ";", "me", ".", "idx_db_", ".", "onversionchange", "=", "null", ";", "me", ".", "onVersionChange", "(", "event", ")", ";", "if", "(", "!", "event", ".", "defaultPrevented", ")", "{", "me", ".", "idx_db_", ".", "close", "(", ")", ";", "me", ".", "idx_db_", "=", "null", ";", "var", "e", "=", "new", "Error", "(", ")", ";", "e", ".", "name", "=", "event", ".", "type", ";", "me", ".", "onFail", "(", "e", ")", ";", "}", "}", "}", ";", "df", ".", "callback", "(", "parseFloat", "(", "old_version", ")", ")", ";", "}", "}" ]
This is final result of connection. It is either fail or connected and only once. @param {IDBDatabase} db database instance. @param {Error=} opt_err error.
[ "This", "is", "final", "result", "of", "connection", ".", "It", "is", "either", "fail", "or", "connected", "and", "only", "once", "." ]
fe128f0680cc5492c5d479c43c1a9d56f673b5d1
https://github.com/yathit/ydn-db/blob/fe128f0680cc5492c5d479c43c1a9d56f673b5d1/src/ydn/db/conn/indexed_db.js#L86-L143
18,133
yathit/ydn-db
src/ydn/db/conn/indexed_db.js
function(db, trans, is_caller_setversion) { var action = is_caller_setversion ? 'changing' : 'upgrading'; goog.log.finer(me.logger, action + ' version to ' + db.version + ' from ' + old_version); // create store that we don't have previously for (var i = 0; i < schema.stores.length; i++) { // this is sync process. me.update_store_(db, trans, schema.stores[i]); } // delete stores var storeNames = /** @type {DOMStringList} */ (db.objectStoreNames); for (var n = storeNames.length, i = 0; i < n; i++) { if (!schema.hasStore(storeNames[i])) { db.deleteObjectStore(storeNames[i]); goog.log.finer(me.logger, 'store: ' + storeNames[i] + ' deleted.'); } } }
javascript
function(db, trans, is_caller_setversion) { var action = is_caller_setversion ? 'changing' : 'upgrading'; goog.log.finer(me.logger, action + ' version to ' + db.version + ' from ' + old_version); // create store that we don't have previously for (var i = 0; i < schema.stores.length; i++) { // this is sync process. me.update_store_(db, trans, schema.stores[i]); } // delete stores var storeNames = /** @type {DOMStringList} */ (db.objectStoreNames); for (var n = storeNames.length, i = 0; i < n; i++) { if (!schema.hasStore(storeNames[i])) { db.deleteObjectStore(storeNames[i]); goog.log.finer(me.logger, 'store: ' + storeNames[i] + ' deleted.'); } } }
[ "function", "(", "db", ",", "trans", ",", "is_caller_setversion", ")", "{", "var", "action", "=", "is_caller_setversion", "?", "'changing'", ":", "'upgrading'", ";", "goog", ".", "log", ".", "finer", "(", "me", ".", "logger", ",", "action", "+", "' version to '", "+", "db", ".", "version", "+", "' from '", "+", "old_version", ")", ";", "// create store that we don't have previously", "for", "(", "var", "i", "=", "0", ";", "i", "<", "schema", ".", "stores", ".", "length", ";", "i", "++", ")", "{", "// this is sync process.", "me", ".", "update_store_", "(", "db", ",", "trans", ",", "schema", ".", "stores", "[", "i", "]", ")", ";", "}", "// delete stores", "var", "storeNames", "=", "/** @type {DOMStringList} */", "(", "db", ".", "objectStoreNames", ")", ";", "for", "(", "var", "n", "=", "storeNames", ".", "length", ",", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "if", "(", "!", "schema", ".", "hasStore", "(", "storeNames", "[", "i", "]", ")", ")", "{", "db", ".", "deleteObjectStore", "(", "storeNames", "[", "i", "]", ")", ";", "goog", ".", "log", ".", "finer", "(", "me", ".", "logger", ",", "'store: '", "+", "storeNames", "[", "i", "]", "+", "' deleted.'", ")", ";", "}", "}", "}" ]
Migrate from current version to the given version. @protected @param {IDBDatabase} db database instance. @param {IDBTransaction} trans transaction. @param {boolean} is_caller_setversion call from set version.
[ "Migrate", "from", "current", "version", "to", "the", "given", "version", "." ]
fe128f0680cc5492c5d479c43c1a9d56f673b5d1
https://github.com/yathit/ydn-db/blob/fe128f0680cc5492c5d479c43c1a9d56f673b5d1/src/ydn/db/conn/indexed_db.js#L153-L173
18,134
yathit/ydn-db
src/ydn/db/conn/indexed_db.js
function(db_schema) { var diff_msg = schema.difference(db_schema, false, true); if (diff_msg.length > 0) { goog.log.log(me.logger, goog.log.Level.FINER, diff_msg); setDb(null, new ydn.error.ConstraintError('different schema: ' + diff_msg)); } else { setDb(db); } }
javascript
function(db_schema) { var diff_msg = schema.difference(db_schema, false, true); if (diff_msg.length > 0) { goog.log.log(me.logger, goog.log.Level.FINER, diff_msg); setDb(null, new ydn.error.ConstraintError('different schema: ' + diff_msg)); } else { setDb(db); } }
[ "function", "(", "db_schema", ")", "{", "var", "diff_msg", "=", "schema", ".", "difference", "(", "db_schema", ",", "false", ",", "true", ")", ";", "if", "(", "diff_msg", ".", "length", ">", "0", ")", "{", "goog", ".", "log", ".", "log", "(", "me", ".", "logger", ",", "goog", ".", "log", ".", "Level", ".", "FINER", ",", "diff_msg", ")", ";", "setDb", "(", "null", ",", "new", "ydn", ".", "error", ".", "ConstraintError", "(", "'different schema: '", "+", "diff_msg", ")", ")", ";", "}", "else", "{", "setDb", "(", "db", ")", ";", "}", "}" ]
Validate given schema and schema of opened database. @param {ydn.db.schema.Database} db_schema schema.
[ "Validate", "given", "schema", "and", "schema", "of", "opened", "database", "." ]
fe128f0680cc5492c5d479c43c1a9d56f673b5d1
https://github.com/yathit/ydn-db/blob/fe128f0680cc5492c5d479c43c1a9d56f673b5d1/src/ydn/db/conn/indexed_db.js#L343-L352
18,135
yathit/ydn-db
src/ydn/db/core/operator.js
function(i, opt_key) { if (done) { if (ydn.db.core.DbOperator.DEBUG) { goog.global.console.log('iterator ' + i + ' done'); } // calling next to a terminated iterator throw new ydn.error.InternalError(); } result_count++; var is_result_ready = result_count === total; var idx = idx2iterator[i]; /** * @type {!ydn.db.Iterator} */ var iterator = iterators[idx]; /** * @type {!ydn.db.core.req.ICursor} */ var cursor = cursors[idx]; var primary_key = cursor.getPrimaryKey(); var value = cursor.getValue(); if (ydn.db.core.DbOperator.DEBUG) { var key_str = opt_key + (goog.isDefAndNotNull(primary_key) ? ', ' + primary_key : ''); var ready_str = is_result_ready ? ' (all result done)' : ''; goog.global.console.log(cursor + ' new position ' + key_str + ready_str); } keys[i] = opt_key; if (iterator.isIndexIterator()) { if (iterator.isKeyIterator()) { values[i] = primary_key; } else { values[i] = value; } } else { if (iterator.isKeyIterator()) { values[i] = opt_key; } else { values[i] = value; } } if (is_result_ready) { // receive all results on_result_ready(); } }
javascript
function(i, opt_key) { if (done) { if (ydn.db.core.DbOperator.DEBUG) { goog.global.console.log('iterator ' + i + ' done'); } // calling next to a terminated iterator throw new ydn.error.InternalError(); } result_count++; var is_result_ready = result_count === total; var idx = idx2iterator[i]; /** * @type {!ydn.db.Iterator} */ var iterator = iterators[idx]; /** * @type {!ydn.db.core.req.ICursor} */ var cursor = cursors[idx]; var primary_key = cursor.getPrimaryKey(); var value = cursor.getValue(); if (ydn.db.core.DbOperator.DEBUG) { var key_str = opt_key + (goog.isDefAndNotNull(primary_key) ? ', ' + primary_key : ''); var ready_str = is_result_ready ? ' (all result done)' : ''; goog.global.console.log(cursor + ' new position ' + key_str + ready_str); } keys[i] = opt_key; if (iterator.isIndexIterator()) { if (iterator.isKeyIterator()) { values[i] = primary_key; } else { values[i] = value; } } else { if (iterator.isKeyIterator()) { values[i] = opt_key; } else { values[i] = value; } } if (is_result_ready) { // receive all results on_result_ready(); } }
[ "function", "(", "i", ",", "opt_key", ")", "{", "if", "(", "done", ")", "{", "if", "(", "ydn", ".", "db", ".", "core", ".", "DbOperator", ".", "DEBUG", ")", "{", "goog", ".", "global", ".", "console", ".", "log", "(", "'iterator '", "+", "i", "+", "' done'", ")", ";", "}", "// calling next to a terminated iterator", "throw", "new", "ydn", ".", "error", ".", "InternalError", "(", ")", ";", "}", "result_count", "++", ";", "var", "is_result_ready", "=", "result_count", "===", "total", ";", "var", "idx", "=", "idx2iterator", "[", "i", "]", ";", "/**\n * @type {!ydn.db.Iterator}\n */", "var", "iterator", "=", "iterators", "[", "idx", "]", ";", "/**\n * @type {!ydn.db.core.req.ICursor}\n */", "var", "cursor", "=", "cursors", "[", "idx", "]", ";", "var", "primary_key", "=", "cursor", ".", "getPrimaryKey", "(", ")", ";", "var", "value", "=", "cursor", ".", "getValue", "(", ")", ";", "if", "(", "ydn", ".", "db", ".", "core", ".", "DbOperator", ".", "DEBUG", ")", "{", "var", "key_str", "=", "opt_key", "+", "(", "goog", ".", "isDefAndNotNull", "(", "primary_key", ")", "?", "', '", "+", "primary_key", ":", "''", ")", ";", "var", "ready_str", "=", "is_result_ready", "?", "' (all result done)'", ":", "''", ";", "goog", ".", "global", ".", "console", ".", "log", "(", "cursor", "+", "' new position '", "+", "key_str", "+", "ready_str", ")", ";", "}", "keys", "[", "i", "]", "=", "opt_key", ";", "if", "(", "iterator", ".", "isIndexIterator", "(", ")", ")", "{", "if", "(", "iterator", ".", "isKeyIterator", "(", ")", ")", "{", "values", "[", "i", "]", "=", "primary_key", ";", "}", "else", "{", "values", "[", "i", "]", "=", "value", ";", "}", "}", "else", "{", "if", "(", "iterator", ".", "isKeyIterator", "(", ")", ")", "{", "values", "[", "i", "]", "=", "opt_key", ";", "}", "else", "{", "values", "[", "i", "]", "=", "value", ";", "}", "}", "if", "(", "is_result_ready", ")", "{", "// receive all results", "on_result_ready", "(", ")", ";", "}", "}" ]
Received iterator result. When all iterators result are collected, begin to send request to collect streamers results. @param {number} i index. @param {IDBKey=} opt_key effective key.
[ "Received", "iterator", "result", ".", "When", "all", "iterators", "result", "are", "collected", "begin", "to", "send", "request", "to", "collect", "streamers", "results", "." ]
fe128f0680cc5492c5d479c43c1a9d56f673b5d1
https://github.com/yathit/ydn-db/blob/fe128f0680cc5492c5d479c43c1a9d56f673b5d1/src/ydn/db/core/operator.js#L481-L528
18,136
yathit/ydn-db
src/ydn/db/crud/req/websql.js
function(index, value) { var idx_name = ydn.db.base.PREFIX_MULTIENTRY + table.getName() + ':' + index.getName(); var idx_sql = insert_statement + goog.string.quote(idx_name) + ' (' + table.getSQLKeyColumnNameQuoted() + ', ' + index.getSQLIndexColumnNameQuoted() + ') VALUES (?, ?)'; var idx_params = [ydn.db.schema.Index.js2sql(key, table.getType()), ydn.db.schema.Index.js2sql(value, index.getType())]; /** * @param {SQLTransaction} tx transaction. * @param {SQLResultSet} rs results. */ var idx_success = function(tx, rs) { }; /** * @param {SQLTransaction} tr transaction. * @param {SQLError} error error. * @return {boolean} true to roll back. */ var idx_error = function(tr, error) { goog.log.warning(me.logger, 'multiEntry index insert error: ' + error.message); return false; }; goog.log.finest(me.logger, req.getLabel() + ' multiEntry ' + idx_sql + ' ' + idx_params); tx.executeSql(idx_sql, idx_params, idx_success, idx_error); }
javascript
function(index, value) { var idx_name = ydn.db.base.PREFIX_MULTIENTRY + table.getName() + ':' + index.getName(); var idx_sql = insert_statement + goog.string.quote(idx_name) + ' (' + table.getSQLKeyColumnNameQuoted() + ', ' + index.getSQLIndexColumnNameQuoted() + ') VALUES (?, ?)'; var idx_params = [ydn.db.schema.Index.js2sql(key, table.getType()), ydn.db.schema.Index.js2sql(value, index.getType())]; /** * @param {SQLTransaction} tx transaction. * @param {SQLResultSet} rs results. */ var idx_success = function(tx, rs) { }; /** * @param {SQLTransaction} tr transaction. * @param {SQLError} error error. * @return {boolean} true to roll back. */ var idx_error = function(tr, error) { goog.log.warning(me.logger, 'multiEntry index insert error: ' + error.message); return false; }; goog.log.finest(me.logger, req.getLabel() + ' multiEntry ' + idx_sql + ' ' + idx_params); tx.executeSql(idx_sql, idx_params, idx_success, idx_error); }
[ "function", "(", "index", ",", "value", ")", "{", "var", "idx_name", "=", "ydn", ".", "db", ".", "base", ".", "PREFIX_MULTIENTRY", "+", "table", ".", "getName", "(", ")", "+", "':'", "+", "index", ".", "getName", "(", ")", ";", "var", "idx_sql", "=", "insert_statement", "+", "goog", ".", "string", ".", "quote", "(", "idx_name", ")", "+", "' ('", "+", "table", ".", "getSQLKeyColumnNameQuoted", "(", ")", "+", "', '", "+", "index", ".", "getSQLIndexColumnNameQuoted", "(", ")", "+", "') VALUES (?, ?)'", ";", "var", "idx_params", "=", "[", "ydn", ".", "db", ".", "schema", ".", "Index", ".", "js2sql", "(", "key", ",", "table", ".", "getType", "(", ")", ")", ",", "ydn", ".", "db", ".", "schema", ".", "Index", ".", "js2sql", "(", "value", ",", "index", ".", "getType", "(", ")", ")", "]", ";", "/**\n * @param {SQLTransaction} tx transaction.\n * @param {SQLResultSet} rs results.\n */", "var", "idx_success", "=", "function", "(", "tx", ",", "rs", ")", "{", "}", ";", "/**\n * @param {SQLTransaction} tr transaction.\n * @param {SQLError} error error.\n * @return {boolean} true to roll back.\n */", "var", "idx_error", "=", "function", "(", "tr", ",", "error", ")", "{", "goog", ".", "log", ".", "warning", "(", "me", ".", "logger", ",", "'multiEntry index insert error: '", "+", "error", ".", "message", ")", ";", "return", "false", ";", "}", ";", "goog", ".", "log", ".", "finest", "(", "me", ".", "logger", ",", "req", ".", "getLabel", "(", ")", "+", "' multiEntry '", "+", "idx_sql", "+", "' '", "+", "idx_params", ")", ";", "tx", ".", "executeSql", "(", "idx_sql", ",", "idx_params", ",", "idx_success", ",", "idx_error", ")", ";", "}" ]
Insert a row for each multi entry index. @param {ydn.db.schema.Index} index multi entry index. @param {number} value index at.
[ "Insert", "a", "row", "for", "each", "multi", "entry", "index", "." ]
fe128f0680cc5492c5d479c43c1a9d56f673b5d1
https://github.com/yathit/ydn-db/blob/fe128f0680cc5492c5d479c43c1a9d56f673b5d1/src/ydn/db/crud/req/websql.js#L266-L295
18,137
yuanyan/boron
gulpfile.js
buildExampleScripts
function buildExampleScripts(dev) { var dest = EXAMPLE_DIST_PATH; var opts = dev ? watchify.args : {}; opts.debug = dev ? true : false; opts.hasExports = true; return function() { var common = browserify(opts), bundle = browserify(opts).require('./' + SRC_PATH + '/' + PACKAGE_FILE, { expose: PACKAGE_NAME }), example = browserify(opts).exclude(PACKAGE_NAME).add('./' + EXAMPLE_SRC_PATH + '/' + EXAMPLE_APP); DEPENDENCIES.forEach(function(pkg) { common.require(pkg); bundle.exclude(pkg); example.exclude(pkg); }); if (dev) { watchBundle(common, 'common.js', dest); watchBundle(bundle, 'bundle.js', dest); watchBundle(example, 'app.js', dest); } return merge( doBundle(common, 'common.js', dest), doBundle(bundle, 'bundle.js', dest), doBundle(example, 'app.js', dest) ); } }
javascript
function buildExampleScripts(dev) { var dest = EXAMPLE_DIST_PATH; var opts = dev ? watchify.args : {}; opts.debug = dev ? true : false; opts.hasExports = true; return function() { var common = browserify(opts), bundle = browserify(opts).require('./' + SRC_PATH + '/' + PACKAGE_FILE, { expose: PACKAGE_NAME }), example = browserify(opts).exclude(PACKAGE_NAME).add('./' + EXAMPLE_SRC_PATH + '/' + EXAMPLE_APP); DEPENDENCIES.forEach(function(pkg) { common.require(pkg); bundle.exclude(pkg); example.exclude(pkg); }); if (dev) { watchBundle(common, 'common.js', dest); watchBundle(bundle, 'bundle.js', dest); watchBundle(example, 'app.js', dest); } return merge( doBundle(common, 'common.js', dest), doBundle(bundle, 'bundle.js', dest), doBundle(example, 'app.js', dest) ); } }
[ "function", "buildExampleScripts", "(", "dev", ")", "{", "var", "dest", "=", "EXAMPLE_DIST_PATH", ";", "var", "opts", "=", "dev", "?", "watchify", ".", "args", ":", "{", "}", ";", "opts", ".", "debug", "=", "dev", "?", "true", ":", "false", ";", "opts", ".", "hasExports", "=", "true", ";", "return", "function", "(", ")", "{", "var", "common", "=", "browserify", "(", "opts", ")", ",", "bundle", "=", "browserify", "(", "opts", ")", ".", "require", "(", "'./'", "+", "SRC_PATH", "+", "'/'", "+", "PACKAGE_FILE", ",", "{", "expose", ":", "PACKAGE_NAME", "}", ")", ",", "example", "=", "browserify", "(", "opts", ")", ".", "exclude", "(", "PACKAGE_NAME", ")", ".", "add", "(", "'./'", "+", "EXAMPLE_SRC_PATH", "+", "'/'", "+", "EXAMPLE_APP", ")", ";", "DEPENDENCIES", ".", "forEach", "(", "function", "(", "pkg", ")", "{", "common", ".", "require", "(", "pkg", ")", ";", "bundle", ".", "exclude", "(", "pkg", ")", ";", "example", ".", "exclude", "(", "pkg", ")", ";", "}", ")", ";", "if", "(", "dev", ")", "{", "watchBundle", "(", "common", ",", "'common.js'", ",", "dest", ")", ";", "watchBundle", "(", "bundle", ",", "'bundle.js'", ",", "dest", ")", ";", "watchBundle", "(", "example", ",", "'app.js'", ",", "dest", ")", ";", "}", "return", "merge", "(", "doBundle", "(", "common", ",", "'common.js'", ",", "dest", ")", ",", "doBundle", "(", "bundle", ",", "'bundle.js'", ",", "dest", ")", ",", "doBundle", "(", "example", ",", "'app.js'", ",", "dest", ")", ")", ";", "}", "}" ]
Build example scripts Returns a gulp task with watchify when in development mode
[ "Build", "example", "scripts" ]
9b5008948cae38398f7ab83b11f106d2bbd3603a
https://github.com/yuanyan/boron/blob/9b5008948cae38398f7ab83b11f106d2bbd3603a/gulpfile.js#L121-L155
18,138
jsantell/poet
lib/poet/methods.js
addTemplate
function addTemplate (poet, data) { if (!data.ext || !data.fn) throw new Error('Template must have both an extension and formatter function'); [].concat(data.ext).map(function (ext) { poet.templates[ext] = data.fn; }); return poet; }
javascript
function addTemplate (poet, data) { if (!data.ext || !data.fn) throw new Error('Template must have both an extension and formatter function'); [].concat(data.ext).map(function (ext) { poet.templates[ext] = data.fn; }); return poet; }
[ "function", "addTemplate", "(", "poet", ",", "data", ")", "{", "if", "(", "!", "data", ".", "ext", "||", "!", "data", ".", "fn", ")", "throw", "new", "Error", "(", "'Template must have both an extension and formatter function'", ")", ";", "[", "]", ".", "concat", "(", "data", ".", "ext", ")", ".", "map", "(", "function", "(", "ext", ")", "{", "poet", ".", "templates", "[", "ext", "]", "=", "data", ".", "fn", ";", "}", ")", ";", "return", "poet", ";", "}" ]
Adds `data.fn` as a template formatter for all files with extension `data.ext`, which may be a string or an array of strings. Adds to `poet` instance templates. @params {Poet} poet @params {Object} data @returns {Poet}
[ "Adds", "data", ".", "fn", "as", "a", "template", "formatter", "for", "all", "files", "with", "extension", "data", ".", "ext", "which", "may", "be", "a", "string", "or", "an", "array", "of", "strings", ".", "Adds", "to", "poet", "instance", "templates", "." ]
509eec54d7420fa95a1ed92823f6614cfde76da2
https://github.com/jsantell/poet/blob/509eec54d7420fa95a1ed92823f6614cfde76da2/lib/poet/methods.js#L23-L32
18,139
jsantell/poet
lib/poet/methods.js
watch
function watch (poet, callback) { var watcher = fs.watch(poet.options.posts, function (event, filename) { poet.init().then(callback); }); poet.watchers.push({ 'watcher': watcher, 'callback': callback }); return poet; }
javascript
function watch (poet, callback) { var watcher = fs.watch(poet.options.posts, function (event, filename) { poet.init().then(callback); }); poet.watchers.push({ 'watcher': watcher, 'callback': callback }); return poet; }
[ "function", "watch", "(", "poet", ",", "callback", ")", "{", "var", "watcher", "=", "fs", ".", "watch", "(", "poet", ".", "options", ".", "posts", ",", "function", "(", "event", ",", "filename", ")", "{", "poet", ".", "init", "(", ")", ".", "then", "(", "callback", ")", ";", "}", ")", ";", "poet", ".", "watchers", ".", "push", "(", "{", "'watcher'", ":", "watcher", ",", "'callback'", ":", "callback", "}", ")", ";", "return", "poet", ";", "}" ]
Sets up the `poet` instance to watch the posts directory for any changes and calls the callback whenever a change is made @params {Object} poet @params {function} [callback] @returns {Poet}
[ "Sets", "up", "the", "poet", "instance", "to", "watch", "the", "posts", "directory", "for", "any", "changes", "and", "calls", "the", "callback", "whenever", "a", "change", "is", "made" ]
509eec54d7420fa95a1ed92823f6614cfde76da2
https://github.com/jsantell/poet/blob/509eec54d7420fa95a1ed92823f6614cfde76da2/lib/poet/methods.js#L140-L149
18,140
jsantell/poet
lib/poet/methods.js
unwatch
function unwatch (poet) { poet.watchers.forEach(function (watcher) { watcher.watcher.close(); }); poet.futures.forEach(function (future) { clearTimeout(future); }); poet.watchers = []; poet.futures = []; return poet; }
javascript
function unwatch (poet) { poet.watchers.forEach(function (watcher) { watcher.watcher.close(); }); poet.futures.forEach(function (future) { clearTimeout(future); }); poet.watchers = []; poet.futures = []; return poet; }
[ "function", "unwatch", "(", "poet", ")", "{", "poet", ".", "watchers", ".", "forEach", "(", "function", "(", "watcher", ")", "{", "watcher", ".", "watcher", ".", "close", "(", ")", ";", "}", ")", ";", "poet", ".", "futures", ".", "forEach", "(", "function", "(", "future", ")", "{", "clearTimeout", "(", "future", ")", ";", "}", ")", ";", "poet", ".", "watchers", "=", "[", "]", ";", "poet", ".", "futures", "=", "[", "]", ";", "return", "poet", ";", "}" ]
Removes all watchers from the `poet` instance so previously registered callbacks are not called again
[ "Removes", "all", "watchers", "from", "the", "poet", "instance", "so", "previously", "registered", "callbacks", "are", "not", "called", "again" ]
509eec54d7420fa95a1ed92823f6614cfde76da2
https://github.com/jsantell/poet/blob/509eec54d7420fa95a1ed92823f6614cfde76da2/lib/poet/methods.js#L156-L166
18,141
jsantell/poet
lib/poet/methods.js
scheduleFutures
function scheduleFutures (poet, allPosts) { var now = Date.now(); var extraTime = 5 * 1000; // 10 seconds buffer var min = now - extraTime; allPosts.forEach(function (post, i) { if (!post) return; var postTime = post.date.getTime(); // if post is in the future if (postTime - min > 0) { // Prevent setTimeout overflow when scheduling more than 24 days out. See https://github.com/jsantell/poet/issues/119 var delay = Math.min(postTime - min, Math.pow(2, 31) - 1); var future = setTimeout(function () { poet.watchers.forEach(function (watcher) { poet.init().then(watcher.callback); }); }, delay); poet.futures.push(future); } }); }
javascript
function scheduleFutures (poet, allPosts) { var now = Date.now(); var extraTime = 5 * 1000; // 10 seconds buffer var min = now - extraTime; allPosts.forEach(function (post, i) { if (!post) return; var postTime = post.date.getTime(); // if post is in the future if (postTime - min > 0) { // Prevent setTimeout overflow when scheduling more than 24 days out. See https://github.com/jsantell/poet/issues/119 var delay = Math.min(postTime - min, Math.pow(2, 31) - 1); var future = setTimeout(function () { poet.watchers.forEach(function (watcher) { poet.init().then(watcher.callback); }); }, delay); poet.futures.push(future); } }); }
[ "function", "scheduleFutures", "(", "poet", ",", "allPosts", ")", "{", "var", "now", "=", "Date", ".", "now", "(", ")", ";", "var", "extraTime", "=", "5", "*", "1000", ";", "// 10 seconds buffer", "var", "min", "=", "now", "-", "extraTime", ";", "allPosts", ".", "forEach", "(", "function", "(", "post", ",", "i", ")", "{", "if", "(", "!", "post", ")", "return", ";", "var", "postTime", "=", "post", ".", "date", ".", "getTime", "(", ")", ";", "// if post is in the future", "if", "(", "postTime", "-", "min", ">", "0", ")", "{", "// Prevent setTimeout overflow when scheduling more than 24 days out. See https://github.com/jsantell/poet/issues/119", "var", "delay", "=", "Math", ".", "min", "(", "postTime", "-", "min", ",", "Math", ".", "pow", "(", "2", ",", "31", ")", "-", "1", ")", ";", "var", "future", "=", "setTimeout", "(", "function", "(", ")", "{", "poet", ".", "watchers", ".", "forEach", "(", "function", "(", "watcher", ")", "{", "poet", ".", "init", "(", ")", ".", "then", "(", "watcher", ".", "callback", ")", ";", "}", ")", ";", "}", ",", "delay", ")", ";", "poet", ".", "futures", ".", "push", "(", "future", ")", ";", "}", "}", ")", ";", "}" ]
Schedules a watch event for all posts that are posted in a future date.
[ "Schedules", "a", "watch", "event", "for", "all", "posts", "that", "are", "posted", "in", "a", "future", "date", "." ]
509eec54d7420fa95a1ed92823f6614cfde76da2
https://github.com/jsantell/poet/blob/509eec54d7420fa95a1ed92823f6614cfde76da2/lib/poet/methods.js#L172-L194
18,142
jsantell/poet
lib/poet/utils.js
getPostPaths
function getPostPaths (dir) { return fs.readdir(dir).then(function (files) { return all(files.map(function (file) { var path = pathify(dir, file); return fs.stat(path).then(function (stats) { return stats.isDirectory() ? getPostPaths(path) : path; }); })); }).then(function (files) { return _.flatten(files); }); }
javascript
function getPostPaths (dir) { return fs.readdir(dir).then(function (files) { return all(files.map(function (file) { var path = pathify(dir, file); return fs.stat(path).then(function (stats) { return stats.isDirectory() ? getPostPaths(path) : path; }); })); }).then(function (files) { return _.flatten(files); }); }
[ "function", "getPostPaths", "(", "dir", ")", "{", "return", "fs", ".", "readdir", "(", "dir", ")", ".", "then", "(", "function", "(", "files", ")", "{", "return", "all", "(", "files", ".", "map", "(", "function", "(", "file", ")", "{", "var", "path", "=", "pathify", "(", "dir", ",", "file", ")", ";", "return", "fs", ".", "stat", "(", "path", ")", ".", "then", "(", "function", "(", "stats", ")", "{", "return", "stats", ".", "isDirectory", "(", ")", "?", "getPostPaths", "(", "path", ")", ":", "path", ";", "}", ")", ";", "}", ")", ")", ";", "}", ")", ".", "then", "(", "function", "(", "files", ")", "{", "return", "_", ".", "flatten", "(", "files", ")", ";", "}", ")", ";", "}" ]
Recursively search `dir` and return all file paths as strings in an array @params {String} dir @returns {Array}
[ "Recursively", "search", "dir", "and", "return", "all", "file", "paths", "as", "strings", "in", "an", "array" ]
509eec54d7420fa95a1ed92823f6614cfde76da2
https://github.com/jsantell/poet/blob/509eec54d7420fa95a1ed92823f6614cfde76da2/lib/poet/utils.js#L48-L61
18,143
jsantell/poet
lib/poet/utils.js
getPreview
function getPreview (post, body, options) { var readMoreTag = options.readMoreTag || post.readMoreTag; var preview; if (post.preview) { preview = post.preview; } else if (post.previewLength) { preview = body.trim().substr(0, post.previewLength); } else if (~body.indexOf(readMoreTag)) { preview = body.split(readMoreTag)[0]; } else { preview = body.trim().replace(/\n.*/g, ''); } return preview; }
javascript
function getPreview (post, body, options) { var readMoreTag = options.readMoreTag || post.readMoreTag; var preview; if (post.preview) { preview = post.preview; } else if (post.previewLength) { preview = body.trim().substr(0, post.previewLength); } else if (~body.indexOf(readMoreTag)) { preview = body.split(readMoreTag)[0]; } else { preview = body.trim().replace(/\n.*/g, ''); } return preview; }
[ "function", "getPreview", "(", "post", ",", "body", ",", "options", ")", "{", "var", "readMoreTag", "=", "options", ".", "readMoreTag", "||", "post", ".", "readMoreTag", ";", "var", "preview", ";", "if", "(", "post", ".", "preview", ")", "{", "preview", "=", "post", ".", "preview", ";", "}", "else", "if", "(", "post", ".", "previewLength", ")", "{", "preview", "=", "body", ".", "trim", "(", ")", ".", "substr", "(", "0", ",", "post", ".", "previewLength", ")", ";", "}", "else", "if", "(", "~", "body", ".", "indexOf", "(", "readMoreTag", ")", ")", "{", "preview", "=", "body", ".", "split", "(", "readMoreTag", ")", "[", "0", "]", ";", "}", "else", "{", "preview", "=", "body", ".", "trim", "(", ")", ".", "replace", "(", "/", "\\n.*", "/", "g", ",", "''", ")", ";", "}", "return", "preview", ";", "}" ]
Takes a `post` object, `body` text and an `options` object and generates preview text in order of priority of a `preview` property on the post, then `previewLength`, followed by finding a `readMoreTag` in the body. Otherwise, use the first paragraph in `body`. @params {Object} post @params {String} body @params {Object} options @return {String}
[ "Takes", "a", "post", "object", "body", "text", "and", "an", "options", "object", "and", "generates", "preview", "text", "in", "order", "of", "priority", "of", "a", "preview", "property", "on", "the", "post", "then", "previewLength", "followed", "by", "finding", "a", "readMoreTag", "in", "the", "body", "." ]
509eec54d7420fa95a1ed92823f6614cfde76da2
https://github.com/jsantell/poet/blob/509eec54d7420fa95a1ed92823f6614cfde76da2/lib/poet/utils.js#L92-L106
18,144
jsantell/poet
lib/poet/utils.js
method
function method (lambda) { return function () { return lambda.apply(null, [this].concat(Array.prototype.slice.call(arguments, 0))); }; }
javascript
function method (lambda) { return function () { return lambda.apply(null, [this].concat(Array.prototype.slice.call(arguments, 0))); }; }
[ "function", "method", "(", "lambda", ")", "{", "return", "function", "(", ")", "{", "return", "lambda", ".", "apply", "(", "null", ",", "[", "this", "]", ".", "concat", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ")", ")", ";", "}", ";", "}" ]
Takes `lambda` function and returns a method. When returned method is invoked, it calls the wrapped `lambda` and passes `this` as a first argument and given arguments as the rest. @params {Function} lambda @returns {Function}
[ "Takes", "lambda", "function", "and", "returns", "a", "method", ".", "When", "returned", "method", "is", "invoked", "it", "calls", "the", "wrapped", "lambda", "and", "passes", "this", "as", "a", "first", "argument", "and", "given", "arguments", "as", "the", "rest", "." ]
509eec54d7420fa95a1ed92823f6614cfde76da2
https://github.com/jsantell/poet/blob/509eec54d7420fa95a1ed92823f6614cfde76da2/lib/poet/utils.js#L118-L122
18,145
jsantell/poet
lib/poet/utils.js
getTemplate
function getTemplate (templates, fileName) { var extMatch = fileName.match(/\.([^\.]*)$/); if (extMatch && extMatch.length > 1) return templates[extMatch[1]]; return null; }
javascript
function getTemplate (templates, fileName) { var extMatch = fileName.match(/\.([^\.]*)$/); if (extMatch && extMatch.length > 1) return templates[extMatch[1]]; return null; }
[ "function", "getTemplate", "(", "templates", ",", "fileName", ")", "{", "var", "extMatch", "=", "fileName", ".", "match", "(", "/", "\\.([^\\.]*)$", "/", ")", ";", "if", "(", "extMatch", "&&", "extMatch", ".", "length", ">", "1", ")", "return", "templates", "[", "extMatch", "[", "1", "]", "]", ";", "return", "null", ";", "}" ]
Takes a templates hash `templates` and a fileName and returns a templating function if found @params {Object} templates @params {String} fileName @returns {Function|null}
[ "Takes", "a", "templates", "hash", "templates", "and", "a", "fileName", "and", "returns", "a", "templating", "function", "if", "found" ]
509eec54d7420fa95a1ed92823f6614cfde76da2
https://github.com/jsantell/poet/blob/509eec54d7420fa95a1ed92823f6614cfde76da2/lib/poet/utils.js#L134-L139
18,146
jsantell/poet
lib/poet/utils.js
createPost
function createPost (filePath, options) { var fileName = path.basename(filePath); return fs.readFile(filePath, 'utf-8').then(function (data) { var parsed = (options.metaFormat === 'yaml' ? yamlFm : jsonFm)(data); var body = parsed.body; var post = parsed.attributes; // If no date defined, create one for current date post.date = new Date(post.date); post.content = body; // url slug for post post.slug = convertStringToSlug(post.slug || post.title); post.url = createURL(getRoute(options.routes, 'post'), post.slug); post.preview = getPreview(post, body, options); return post; }); }
javascript
function createPost (filePath, options) { var fileName = path.basename(filePath); return fs.readFile(filePath, 'utf-8').then(function (data) { var parsed = (options.metaFormat === 'yaml' ? yamlFm : jsonFm)(data); var body = parsed.body; var post = parsed.attributes; // If no date defined, create one for current date post.date = new Date(post.date); post.content = body; // url slug for post post.slug = convertStringToSlug(post.slug || post.title); post.url = createURL(getRoute(options.routes, 'post'), post.slug); post.preview = getPreview(post, body, options); return post; }); }
[ "function", "createPost", "(", "filePath", ",", "options", ")", "{", "var", "fileName", "=", "path", ".", "basename", "(", "filePath", ")", ";", "return", "fs", ".", "readFile", "(", "filePath", ",", "'utf-8'", ")", ".", "then", "(", "function", "(", "data", ")", "{", "var", "parsed", "=", "(", "options", ".", "metaFormat", "===", "'yaml'", "?", "yamlFm", ":", "jsonFm", ")", "(", "data", ")", ";", "var", "body", "=", "parsed", ".", "body", ";", "var", "post", "=", "parsed", ".", "attributes", ";", "// If no date defined, create one for current date", "post", ".", "date", "=", "new", "Date", "(", "post", ".", "date", ")", ";", "post", ".", "content", "=", "body", ";", "// url slug for post", "post", ".", "slug", "=", "convertStringToSlug", "(", "post", ".", "slug", "||", "post", ".", "title", ")", ";", "post", ".", "url", "=", "createURL", "(", "getRoute", "(", "options", ".", "routes", ",", "'post'", ")", ",", "post", ".", "slug", ")", ";", "post", ".", "preview", "=", "getPreview", "(", "post", ",", "body", ",", "options", ")", ";", "return", "post", ";", "}", ")", ";", "}" ]
Accepts a name of a file and an options hash and returns an object representing a post object @params {String} data @params {String} fileName @params {Object} options @returns {Object}
[ "Accepts", "a", "name", "of", "a", "file", "and", "an", "options", "hash", "and", "returns", "an", "object", "representing", "a", "post", "object" ]
509eec54d7420fa95a1ed92823f6614cfde76da2
https://github.com/jsantell/poet/blob/509eec54d7420fa95a1ed92823f6614cfde76da2/lib/poet/utils.js#L159-L174
18,147
jsantell/poet
lib/poet/utils.js
sortPosts
function sortPosts (posts) { return Object.keys(posts).map(function (post) { return posts[post]; }) .sort(function (a,b) { if ( a.date < b.date ) return 1; if ( a.date > b.date ) return -1; return 0; }); }
javascript
function sortPosts (posts) { return Object.keys(posts).map(function (post) { return posts[post]; }) .sort(function (a,b) { if ( a.date < b.date ) return 1; if ( a.date > b.date ) return -1; return 0; }); }
[ "function", "sortPosts", "(", "posts", ")", "{", "return", "Object", ".", "keys", "(", "posts", ")", ".", "map", "(", "function", "(", "post", ")", "{", "return", "posts", "[", "post", "]", ";", "}", ")", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "if", "(", "a", ".", "date", "<", "b", ".", "date", ")", "return", "1", ";", "if", "(", "a", ".", "date", ">", "b", ".", "date", ")", "return", "-", "1", ";", "return", "0", ";", "}", ")", ";", "}" ]
Takes an array `posts` of post objects and returns a new, sorted version based off of date @params {Array} posts @returns {Array}
[ "Takes", "an", "array", "posts", "of", "post", "objects", "and", "returns", "a", "new", "sorted", "version", "based", "off", "of", "date" ]
509eec54d7420fa95a1ed92823f6614cfde76da2
https://github.com/jsantell/poet/blob/509eec54d7420fa95a1ed92823f6614cfde76da2/lib/poet/utils.js#L185-L192
18,148
jsantell/poet
lib/poet/utils.js
getTags
function getTags (posts) { var tags = posts.reduce(function (tags, post) { if (!post.tags || !Array.isArray(post.tags)) return tags; return tags.concat(post.tags); }, []); return _.unique(tags).sort(); }
javascript
function getTags (posts) { var tags = posts.reduce(function (tags, post) { if (!post.tags || !Array.isArray(post.tags)) return tags; return tags.concat(post.tags); }, []); return _.unique(tags).sort(); }
[ "function", "getTags", "(", "posts", ")", "{", "var", "tags", "=", "posts", ".", "reduce", "(", "function", "(", "tags", ",", "post", ")", "{", "if", "(", "!", "post", ".", "tags", "||", "!", "Array", ".", "isArray", "(", "post", ".", "tags", ")", ")", "return", "tags", ";", "return", "tags", ".", "concat", "(", "post", ".", "tags", ")", ";", "}", ",", "[", "]", ")", ";", "return", "_", ".", "unique", "(", "tags", ")", ".", "sort", "(", ")", ";", "}" ]
Takes an array `posts` of sorted posts and returns a sorted array with all tags @params {Array} posts @returns {Array}
[ "Takes", "an", "array", "posts", "of", "sorted", "posts", "and", "returns", "a", "sorted", "array", "with", "all", "tags" ]
509eec54d7420fa95a1ed92823f6614cfde76da2
https://github.com/jsantell/poet/blob/509eec54d7420fa95a1ed92823f6614cfde76da2/lib/poet/utils.js#L203-L210
18,149
jsantell/poet
lib/poet/utils.js
getCategories
function getCategories (posts) { var categories = posts.reduce(function (categories, post) { if (!post.category) return categories; return categories.concat(post.category); }, []); return _.unique(categories).sort(); }
javascript
function getCategories (posts) { var categories = posts.reduce(function (categories, post) { if (!post.category) return categories; return categories.concat(post.category); }, []); return _.unique(categories).sort(); }
[ "function", "getCategories", "(", "posts", ")", "{", "var", "categories", "=", "posts", ".", "reduce", "(", "function", "(", "categories", ",", "post", ")", "{", "if", "(", "!", "post", ".", "category", ")", "return", "categories", ";", "return", "categories", ".", "concat", "(", "post", ".", "category", ")", ";", "}", ",", "[", "]", ")", ";", "return", "_", ".", "unique", "(", "categories", ")", ".", "sort", "(", ")", ";", "}" ]
Takes an array `posts` of sorted posts and returns a sorted array with all categories @params {Array} posts @returns {Array}
[ "Takes", "an", "array", "posts", "of", "sorted", "posts", "and", "returns", "a", "sorted", "array", "with", "all", "categories" ]
509eec54d7420fa95a1ed92823f6614cfde76da2
https://github.com/jsantell/poet/blob/509eec54d7420fa95a1ed92823f6614cfde76da2/lib/poet/utils.js#L221-L228
18,150
jsantell/poet
lib/poet/utils.js
pathify
function pathify (dir, file) { if (file) return path.normalize(path.join(dir, file)); else return path.normalize(dir); }
javascript
function pathify (dir, file) { if (file) return path.normalize(path.join(dir, file)); else return path.normalize(dir); }
[ "function", "pathify", "(", "dir", ",", "file", ")", "{", "if", "(", "file", ")", "return", "path", ".", "normalize", "(", "path", ".", "join", "(", "dir", ",", "file", ")", ")", ";", "else", "return", "path", ".", "normalize", "(", "dir", ")", ";", "}" ]
Normalizes and joins a path of `dir` and optionally `file` @params {String} dir @params {String} file @returns {String}
[ "Normalizes", "and", "joins", "a", "path", "of", "dir", "and", "optionally", "file" ]
509eec54d7420fa95a1ed92823f6614cfde76da2
https://github.com/jsantell/poet/blob/509eec54d7420fa95a1ed92823f6614cfde76da2/lib/poet/utils.js#L272-L277
18,151
jsantell/poet
lib/poet/routes.js
bindRoutes
function bindRoutes (poet) { var app = poet.app; var routes = poet.options.routes; // If no routes specified, abort if (!routes) return; Object.keys(routes).map(function (route) { var type = utils.getRouteType(route); if (!type) return; app.get(route, routeMap[type](poet, routes[route])); }); }
javascript
function bindRoutes (poet) { var app = poet.app; var routes = poet.options.routes; // If no routes specified, abort if (!routes) return; Object.keys(routes).map(function (route) { var type = utils.getRouteType(route); if (!type) return; app.get(route, routeMap[type](poet, routes[route])); }); }
[ "function", "bindRoutes", "(", "poet", ")", "{", "var", "app", "=", "poet", ".", "app", ";", "var", "routes", "=", "poet", ".", "options", ".", "routes", ";", "// If no routes specified, abort", "if", "(", "!", "routes", ")", "return", ";", "Object", ".", "keys", "(", "routes", ")", ".", "map", "(", "function", "(", "route", ")", "{", "var", "type", "=", "utils", ".", "getRouteType", "(", "route", ")", ";", "if", "(", "!", "type", ")", "return", ";", "app", ".", "get", "(", "route", ",", "routeMap", "[", "type", "]", "(", "poet", ",", "routes", "[", "route", "]", ")", ")", ";", "}", ")", ";", "}" ]
Takes a `poet` instance and generates routes based off of `poet.options.routes` mappings. @params {Object} poet
[ "Takes", "a", "poet", "instance", "and", "generates", "routes", "based", "off", "of", "poet", ".", "options", ".", "routes", "mappings", "." ]
509eec54d7420fa95a1ed92823f6614cfde76da2
https://github.com/jsantell/poet/blob/509eec54d7420fa95a1ed92823f6614cfde76da2/lib/poet/routes.js#L16-L29
18,152
jsantell/poet
lib/poet/helpers.js
getPosts
function getPosts (poet) { if (poet.cache.posts) return poet.cache.posts; var posts = utils.sortPosts(poet.posts).filter(function (post) { // Filter out draft posts if showDrafts is false return (poet.options.showDrafts || !post.draft) && // Filter out posts in the future if showFuture is false (poet.options.showFuture || post.date < Date.now()); }); return poet.cache.posts = posts; }
javascript
function getPosts (poet) { if (poet.cache.posts) return poet.cache.posts; var posts = utils.sortPosts(poet.posts).filter(function (post) { // Filter out draft posts if showDrafts is false return (poet.options.showDrafts || !post.draft) && // Filter out posts in the future if showFuture is false (poet.options.showFuture || post.date < Date.now()); }); return poet.cache.posts = posts; }
[ "function", "getPosts", "(", "poet", ")", "{", "if", "(", "poet", ".", "cache", ".", "posts", ")", "return", "poet", ".", "cache", ".", "posts", ";", "var", "posts", "=", "utils", ".", "sortPosts", "(", "poet", ".", "posts", ")", ".", "filter", "(", "function", "(", "post", ")", "{", "// Filter out draft posts if showDrafts is false", "return", "(", "poet", ".", "options", ".", "showDrafts", "||", "!", "post", ".", "draft", ")", "&&", "// Filter out posts in the future if showFuture is false", "(", "poet", ".", "options", ".", "showFuture", "||", "post", ".", "date", "<", "Date", ".", "now", "(", ")", ")", ";", "}", ")", ";", "return", "poet", ".", "cache", ".", "posts", "=", "posts", ";", "}" ]
Takes a `poet` instance and returns the posts in sorted, array form @params {Object} poet @returns {Array}
[ "Takes", "a", "poet", "instance", "and", "returns", "the", "posts", "in", "sorted", "array", "form" ]
509eec54d7420fa95a1ed92823f6614cfde76da2
https://github.com/jsantell/poet/blob/509eec54d7420fa95a1ed92823f6614cfde76da2/lib/poet/helpers.js#L70-L82
18,153
jsantell/poet
lib/poet/helpers.js
getTags
function getTags (poet) { return poet.cache.tags || (poet.cache.tags = utils.getTags(getPosts(poet))); }
javascript
function getTags (poet) { return poet.cache.tags || (poet.cache.tags = utils.getTags(getPosts(poet))); }
[ "function", "getTags", "(", "poet", ")", "{", "return", "poet", ".", "cache", ".", "tags", "||", "(", "poet", ".", "cache", ".", "tags", "=", "utils", ".", "getTags", "(", "getPosts", "(", "poet", ")", ")", ")", ";", "}" ]
Takes a `poet` instance and returns the tags in sorted, array form @params {Object} poet @returns {Array}
[ "Takes", "a", "poet", "instance", "and", "returns", "the", "tags", "in", "sorted", "array", "form" ]
509eec54d7420fa95a1ed92823f6614cfde76da2
https://github.com/jsantell/poet/blob/509eec54d7420fa95a1ed92823f6614cfde76da2/lib/poet/helpers.js#L91-L93
18,154
jsantell/poet
lib/poet/helpers.js
getCategories
function getCategories (poet) { return poet.cache.categories || (poet.cache.categories = utils.getCategories(getPosts(poet))); }
javascript
function getCategories (poet) { return poet.cache.categories || (poet.cache.categories = utils.getCategories(getPosts(poet))); }
[ "function", "getCategories", "(", "poet", ")", "{", "return", "poet", ".", "cache", ".", "categories", "||", "(", "poet", ".", "cache", ".", "categories", "=", "utils", ".", "getCategories", "(", "getPosts", "(", "poet", ")", ")", ")", ";", "}" ]
Takes a `poet` instance and returns the categories in sorted, array form @params {Object} poet @returns {Array}
[ "Takes", "a", "poet", "instance", "and", "returns", "the", "categories", "in", "sorted", "array", "form" ]
509eec54d7420fa95a1ed92823f6614cfde76da2
https://github.com/jsantell/poet/blob/509eec54d7420fa95a1ed92823f6614cfde76da2/lib/poet/helpers.js#L102-L105
18,155
jsantell/poet
lib/poet/defaults.js
createDefaults
function createDefaults () { return { postsPerPage: 5, posts: './_posts/', showDrafts: process.env.NODE_ENV !== 'production', showFuture: process.env.NODE_ENV !== 'production', metaFormat: 'json', readMoreLink: readMoreLink, readMoreTag: '<!--more-->', routes: { '/post/:post': 'post', '/page/:page': 'page', '/tag/:tag': 'tag', '/category/:category': 'category' } }; }
javascript
function createDefaults () { return { postsPerPage: 5, posts: './_posts/', showDrafts: process.env.NODE_ENV !== 'production', showFuture: process.env.NODE_ENV !== 'production', metaFormat: 'json', readMoreLink: readMoreLink, readMoreTag: '<!--more-->', routes: { '/post/:post': 'post', '/page/:page': 'page', '/tag/:tag': 'tag', '/category/:category': 'category' } }; }
[ "function", "createDefaults", "(", ")", "{", "return", "{", "postsPerPage", ":", "5", ",", "posts", ":", "'./_posts/'", ",", "showDrafts", ":", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", ",", "showFuture", ":", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", ",", "metaFormat", ":", "'json'", ",", "readMoreLink", ":", "readMoreLink", ",", "readMoreTag", ":", "'<!--more-->'", ",", "routes", ":", "{", "'/post/:post'", ":", "'post'", ",", "'/page/:page'", ":", "'page'", ",", "'/tag/:tag'", ":", "'tag'", ",", "'/category/:category'", ":", "'category'", "}", "}", ";", "}" ]
Returns a fresh copy of default options @returns {Object}
[ "Returns", "a", "fresh", "copy", "of", "default", "options" ]
509eec54d7420fa95a1ed92823f6614cfde76da2
https://github.com/jsantell/poet/blob/509eec54d7420fa95a1ed92823f6614cfde76da2/lib/poet/defaults.js#L16-L32
18,156
mjohnston/react-native-webpack-server
bin/rnws.js
createServer
function createServer(opts) { opts.webpackConfigPath = path.resolve(process.cwd(), opts.webpackConfigPath); if (fs.existsSync(opts.webpackConfigPath)) { opts.webpackConfig = require(path.resolve(process.cwd(), opts.webpackConfigPath)); } else { throw new Error('Must specify webpackConfigPath or create ./webpack.config.js'); } delete opts.webpackConfigPath; const server = new Server(opts); return server; }
javascript
function createServer(opts) { opts.webpackConfigPath = path.resolve(process.cwd(), opts.webpackConfigPath); if (fs.existsSync(opts.webpackConfigPath)) { opts.webpackConfig = require(path.resolve(process.cwd(), opts.webpackConfigPath)); } else { throw new Error('Must specify webpackConfigPath or create ./webpack.config.js'); } delete opts.webpackConfigPath; const server = new Server(opts); return server; }
[ "function", "createServer", "(", "opts", ")", "{", "opts", ".", "webpackConfigPath", "=", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "opts", ".", "webpackConfigPath", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "opts", ".", "webpackConfigPath", ")", ")", "{", "opts", ".", "webpackConfig", "=", "require", "(", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "opts", ".", "webpackConfigPath", ")", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Must specify webpackConfigPath or create ./webpack.config.js'", ")", ";", "}", "delete", "opts", ".", "webpackConfigPath", ";", "const", "server", "=", "new", "Server", "(", "opts", ")", ";", "return", "server", ";", "}" ]
Create a server instance using the provided options. @param {Object} opts react-native-webpack-server options @return {Server} react-native-webpack-server server
[ "Create", "a", "server", "instance", "using", "the", "provided", "options", "." ]
98c5c4c2a809da90bc076c9de73e3acc586ea8df
https://github.com/mjohnston/react-native-webpack-server/blob/98c5c4c2a809da90bc076c9de73e3acc586ea8df/bin/rnws.js#L40-L51
18,157
mjohnston/react-native-webpack-server
bin/rnws.js
commonOptions
function commonOptions(program) { return program .option( '-H, --hostname [hostname]', 'Hostname on which the server will listen. [localhost]', 'localhost' ) .option( '-P, --port [port]', 'Port on which the server will listen. [8080]', 8080 ) .option( '-p, --packagerPort [port]', 'Port on which the react-native packager will listen. [8081]', 8081 ) .option( '-w, --webpackPort [port]', 'Port on which the webpack dev server will listen. [8082]', 8082 ) .option( '-c, --webpackConfigPath [path]', 'Path to the webpack configuration file. [webpack.config.js]', 'webpack.config.js' ) .option( '--no-android', 'Disable support for Android. [false]', false ) .option( '--no-ios', 'Disable support for iOS. [false]', false ) .option( '-A, --androidEntry [name]', 'Android entry module name. Has no effect if \'--no-android\' is passed. [index.android]', 'index.android' ) .option( '-I, --iosEntry [name]', 'iOS entry module name. Has no effect if \'--no-ios\' is passed. [index.ios]', 'index.ios' ) .option( '--projectRoots [projectRoots]', 'List of comma-separated paths for the react-native packager to consider as project root directories', null ) .option( '--root [root]', 'List of comma-separated paths for the react-native packager to consider as additional directories. If provided, these paths must include react-native and its dependencies.', null ) .option( '--assetRoots [assetRoots]', 'List of comma-separated paths for the react-native packager to consider as asset root directories', null ) .option( '-r, --resetCache', 'Remove cached react-native packager files [false]', false ) .option( '--hasteExternals', // React Native 0.23 rewrites `require('HasteModule')` calls to // `require(42)` where 42 is an internal module id. That breaks // treating Haste modules simply as commonjs modules and leaving // the `require()` call in the source. So for now this feature // only works with React Native <0.23. 'Allow direct import of React Native\'s (<0.23) internal Haste modules [false]', false ); }
javascript
function commonOptions(program) { return program .option( '-H, --hostname [hostname]', 'Hostname on which the server will listen. [localhost]', 'localhost' ) .option( '-P, --port [port]', 'Port on which the server will listen. [8080]', 8080 ) .option( '-p, --packagerPort [port]', 'Port on which the react-native packager will listen. [8081]', 8081 ) .option( '-w, --webpackPort [port]', 'Port on which the webpack dev server will listen. [8082]', 8082 ) .option( '-c, --webpackConfigPath [path]', 'Path to the webpack configuration file. [webpack.config.js]', 'webpack.config.js' ) .option( '--no-android', 'Disable support for Android. [false]', false ) .option( '--no-ios', 'Disable support for iOS. [false]', false ) .option( '-A, --androidEntry [name]', 'Android entry module name. Has no effect if \'--no-android\' is passed. [index.android]', 'index.android' ) .option( '-I, --iosEntry [name]', 'iOS entry module name. Has no effect if \'--no-ios\' is passed. [index.ios]', 'index.ios' ) .option( '--projectRoots [projectRoots]', 'List of comma-separated paths for the react-native packager to consider as project root directories', null ) .option( '--root [root]', 'List of comma-separated paths for the react-native packager to consider as additional directories. If provided, these paths must include react-native and its dependencies.', null ) .option( '--assetRoots [assetRoots]', 'List of comma-separated paths for the react-native packager to consider as asset root directories', null ) .option( '-r, --resetCache', 'Remove cached react-native packager files [false]', false ) .option( '--hasteExternals', // React Native 0.23 rewrites `require('HasteModule')` calls to // `require(42)` where 42 is an internal module id. That breaks // treating Haste modules simply as commonjs modules and leaving // the `require()` call in the source. So for now this feature // only works with React Native <0.23. 'Allow direct import of React Native\'s (<0.23) internal Haste modules [false]', false ); }
[ "function", "commonOptions", "(", "program", ")", "{", "return", "program", ".", "option", "(", "'-H, --hostname [hostname]'", ",", "'Hostname on which the server will listen. [localhost]'", ",", "'localhost'", ")", ".", "option", "(", "'-P, --port [port]'", ",", "'Port on which the server will listen. [8080]'", ",", "8080", ")", ".", "option", "(", "'-p, --packagerPort [port]'", ",", "'Port on which the react-native packager will listen. [8081]'", ",", "8081", ")", ".", "option", "(", "'-w, --webpackPort [port]'", ",", "'Port on which the webpack dev server will listen. [8082]'", ",", "8082", ")", ".", "option", "(", "'-c, --webpackConfigPath [path]'", ",", "'Path to the webpack configuration file. [webpack.config.js]'", ",", "'webpack.config.js'", ")", ".", "option", "(", "'--no-android'", ",", "'Disable support for Android. [false]'", ",", "false", ")", ".", "option", "(", "'--no-ios'", ",", "'Disable support for iOS. [false]'", ",", "false", ")", ".", "option", "(", "'-A, --androidEntry [name]'", ",", "'Android entry module name. Has no effect if \\'--no-android\\' is passed. [index.android]'", ",", "'index.android'", ")", ".", "option", "(", "'-I, --iosEntry [name]'", ",", "'iOS entry module name. Has no effect if \\'--no-ios\\' is passed. [index.ios]'", ",", "'index.ios'", ")", ".", "option", "(", "'--projectRoots [projectRoots]'", ",", "'List of comma-separated paths for the react-native packager to consider as project root directories'", ",", "null", ")", ".", "option", "(", "'--root [root]'", ",", "'List of comma-separated paths for the react-native packager to consider as additional directories. If provided, these paths must include react-native and its dependencies.'", ",", "null", ")", ".", "option", "(", "'--assetRoots [assetRoots]'", ",", "'List of comma-separated paths for the react-native packager to consider as asset root directories'", ",", "null", ")", ".", "option", "(", "'-r, --resetCache'", ",", "'Remove cached react-native packager files [false]'", ",", "false", ")", ".", "option", "(", "'--hasteExternals'", ",", "// React Native 0.23 rewrites `require('HasteModule')` calls to", "// `require(42)` where 42 is an internal module id. That breaks", "// treating Haste modules simply as commonjs modules and leaving", "// the `require()` call in the source. So for now this feature", "// only works with React Native <0.23.", "'Allow direct import of React Native\\'s (<0.23) internal Haste modules [false]'", ",", "false", ")", ";", "}" ]
Apply a set of common options to the commander.js program. @param {Object} program The commander.js program @return {Object} The program with options applied
[ "Apply", "a", "set", "of", "common", "options", "to", "the", "commander", ".", "js", "program", "." ]
98c5c4c2a809da90bc076c9de73e3acc586ea8df
https://github.com/mjohnston/react-native-webpack-server/blob/98c5c4c2a809da90bc076c9de73e3acc586ea8df/bin/rnws.js#L58-L135
18,158
mjohnston/react-native-webpack-server
lib/getReactNativeExternals.js
getReactNativeExternals
function getReactNativeExternals(options) { return Promise.all(options.platforms.map( (platform) => getReactNativeDependencyNames({ projectRoots: options.projectRoots || [process.cwd()], assetRoots: options.assetRoots || [process.cwd()], platform: platform, }) )).then((moduleNamesGroupedByPlatform) => { const allReactNativeModules = Array.prototype.concat.apply([], moduleNamesGroupedByPlatform); return makeWebpackExternalsConfig(allReactNativeModules); }); }
javascript
function getReactNativeExternals(options) { return Promise.all(options.platforms.map( (platform) => getReactNativeDependencyNames({ projectRoots: options.projectRoots || [process.cwd()], assetRoots: options.assetRoots || [process.cwd()], platform: platform, }) )).then((moduleNamesGroupedByPlatform) => { const allReactNativeModules = Array.prototype.concat.apply([], moduleNamesGroupedByPlatform); return makeWebpackExternalsConfig(allReactNativeModules); }); }
[ "function", "getReactNativeExternals", "(", "options", ")", "{", "return", "Promise", ".", "all", "(", "options", ".", "platforms", ".", "map", "(", "(", "platform", ")", "=>", "getReactNativeDependencyNames", "(", "{", "projectRoots", ":", "options", ".", "projectRoots", "||", "[", "process", ".", "cwd", "(", ")", "]", ",", "assetRoots", ":", "options", ".", "assetRoots", "||", "[", "process", ".", "cwd", "(", ")", "]", ",", "platform", ":", "platform", ",", "}", ")", ")", ")", ".", "then", "(", "(", "moduleNamesGroupedByPlatform", ")", "=>", "{", "const", "allReactNativeModules", "=", "Array", ".", "prototype", ".", "concat", ".", "apply", "(", "[", "]", ",", "moduleNamesGroupedByPlatform", ")", ";", "return", "makeWebpackExternalsConfig", "(", "allReactNativeModules", ")", ";", "}", ")", ";", "}" ]
Get a webpack 'externals' config for all React Native internal modules. @param {Object} options Options @param {String} options.projectRoot The project root path, where `node_modules/` is found @return {Object} A webpack 'externals' config object
[ "Get", "a", "webpack", "externals", "config", "for", "all", "React", "Native", "internal", "modules", "." ]
98c5c4c2a809da90bc076c9de73e3acc586ea8df
https://github.com/mjohnston/react-native-webpack-server/blob/98c5c4c2a809da90bc076c9de73e3acc586ea8df/lib/getReactNativeExternals.js#L11-L22
18,159
mjohnston/react-native-webpack-server
lib/getReactNativeExternals.js
makeWebpackExternalsConfig
function makeWebpackExternalsConfig(moduleNames) { return moduleNames.reduce((externals, moduleName) => Object.assign(externals, { [moduleName]: `commonjs ${moduleName}`, }), {}); }
javascript
function makeWebpackExternalsConfig(moduleNames) { return moduleNames.reduce((externals, moduleName) => Object.assign(externals, { [moduleName]: `commonjs ${moduleName}`, }), {}); }
[ "function", "makeWebpackExternalsConfig", "(", "moduleNames", ")", "{", "return", "moduleNames", ".", "reduce", "(", "(", "externals", ",", "moduleName", ")", "=>", "Object", ".", "assign", "(", "externals", ",", "{", "[", "moduleName", "]", ":", "`", "${", "moduleName", "}", "`", ",", "}", ")", ",", "{", "}", ")", ";", "}" ]
Make a webpack 'externals' object from the provided CommonJS module names. @param {Array<String>} moduleNames The list of module names @return {Object} A webpack 'externals' config object
[ "Make", "a", "webpack", "externals", "object", "from", "the", "provided", "CommonJS", "module", "names", "." ]
98c5c4c2a809da90bc076c9de73e3acc586ea8df
https://github.com/mjohnston/react-native-webpack-server/blob/98c5c4c2a809da90bc076c9de73e3acc586ea8df/lib/getReactNativeExternals.js#L29-L33
18,160
mjohnston/react-native-webpack-server
lib/getReactNativeExternals.js
getReactNativeDependencyNames
function getReactNativeDependencyNames(options) { const blacklist = require('react-native/packager/blacklist'); const ReactPackager = require('react-native/packager/react-packager'); const rnEntryPoint = require.resolve('react-native'); return ReactPackager.getDependencies({ blacklistRE: blacklist(false /* don't blacklist any platform */), projectRoots: options.projectRoots, assetRoots: options.assetRoots, transformModulePath: require.resolve('react-native/packager/transformer'), }, { entryFile: rnEntryPoint, dev: true, platform: options.platform, }).then(dependencies => dependencies.filter(dependency => !dependency.isPolyfill()) ).then(dependencies => Promise.all(dependencies.map(dependency => dependency.getName())) ); }
javascript
function getReactNativeDependencyNames(options) { const blacklist = require('react-native/packager/blacklist'); const ReactPackager = require('react-native/packager/react-packager'); const rnEntryPoint = require.resolve('react-native'); return ReactPackager.getDependencies({ blacklistRE: blacklist(false /* don't blacklist any platform */), projectRoots: options.projectRoots, assetRoots: options.assetRoots, transformModulePath: require.resolve('react-native/packager/transformer'), }, { entryFile: rnEntryPoint, dev: true, platform: options.platform, }).then(dependencies => dependencies.filter(dependency => !dependency.isPolyfill()) ).then(dependencies => Promise.all(dependencies.map(dependency => dependency.getName())) ); }
[ "function", "getReactNativeDependencyNames", "(", "options", ")", "{", "const", "blacklist", "=", "require", "(", "'react-native/packager/blacklist'", ")", ";", "const", "ReactPackager", "=", "require", "(", "'react-native/packager/react-packager'", ")", ";", "const", "rnEntryPoint", "=", "require", ".", "resolve", "(", "'react-native'", ")", ";", "return", "ReactPackager", ".", "getDependencies", "(", "{", "blacklistRE", ":", "blacklist", "(", "false", "/* don't blacklist any platform */", ")", ",", "projectRoots", ":", "options", ".", "projectRoots", ",", "assetRoots", ":", "options", ".", "assetRoots", ",", "transformModulePath", ":", "require", ".", "resolve", "(", "'react-native/packager/transformer'", ")", ",", "}", ",", "{", "entryFile", ":", "rnEntryPoint", ",", "dev", ":", "true", ",", "platform", ":", "options", ".", "platform", ",", "}", ")", ".", "then", "(", "dependencies", "=>", "dependencies", ".", "filter", "(", "dependency", "=>", "!", "dependency", ".", "isPolyfill", "(", ")", ")", ")", ".", "then", "(", "dependencies", "=>", "Promise", ".", "all", "(", "dependencies", ".", "map", "(", "dependency", "=>", "dependency", ".", "getName", "(", ")", ")", ")", ")", ";", "}" ]
Extract all non-polyfill dependency names from the React Native packager. @param {Object} options Options @param {String} options.projectRoot The project root path, where `node_modules/` is found @param {String} options.platform The platform for which to get dependencies @return {Promise<Object>} Resolves with a webpack 'externals' configuration object
[ "Extract", "all", "non", "-", "polyfill", "dependency", "names", "from", "the", "React", "Native", "packager", "." ]
98c5c4c2a809da90bc076c9de73e3acc586ea8df
https://github.com/mjohnston/react-native-webpack-server/blob/98c5c4c2a809da90bc076c9de73e3acc586ea8df/lib/getReactNativeExternals.js#L43-L62
18,161
nhn/tui.code-snippet
src/js/type.js
_hasOwnProperty
function _hasOwnProperty(obj) { var key; for (key in obj) { if (obj.hasOwnProperty(key)) { return true; } } return false; }
javascript
function _hasOwnProperty(obj) { var key; for (key in obj) { if (obj.hasOwnProperty(key)) { return true; } } return false; }
[ "function", "_hasOwnProperty", "(", "obj", ")", "{", "var", "key", ";", "for", "(", "key", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check whether given argument has own property @param {Object} obj - Target for checking @returns {boolean} - whether given argument has own property @memberof tui.util @private
[ "Check", "whether", "given", "argument", "has", "own", "property" ]
7973b0d635d7e6dbd408a214fd5dac859237d1a8
https://github.com/nhn/tui.code-snippet/blob/7973b0d635d7e6dbd408a214fd5dac859237d1a8/src/js/type.js#L290-L299
18,162
nhn/tui.code-snippet
src/js/request.js
sendHostname
function sendHostname(appName, trackingId) { var url = 'https://www.google-analytics.com/collect'; var hostname = location.hostname; var hitType = 'event'; var eventCategory = 'use'; var applicationKeyForStorage = 'TOAST UI ' + appName + ' for ' + hostname + ': Statistics'; var date = window.localStorage.getItem(applicationKeyForStorage); // skip if the flag is defined and is set to false explicitly if (!type.isUndefined(window.tui) && window.tui.usageStatistics === false) { return; } // skip if not pass seven days old if (date && !isExpired(date)) { return; } window.localStorage.setItem(applicationKeyForStorage, new Date().getTime()); setTimeout(function() { if (document.readyState === 'interactive' || document.readyState === 'complete') { imagePing(url, { v: 1, t: hitType, tid: trackingId, cid: hostname, dp: hostname, dh: appName, el: appName, ec: eventCategory }); } }, 1000); }
javascript
function sendHostname(appName, trackingId) { var url = 'https://www.google-analytics.com/collect'; var hostname = location.hostname; var hitType = 'event'; var eventCategory = 'use'; var applicationKeyForStorage = 'TOAST UI ' + appName + ' for ' + hostname + ': Statistics'; var date = window.localStorage.getItem(applicationKeyForStorage); // skip if the flag is defined and is set to false explicitly if (!type.isUndefined(window.tui) && window.tui.usageStatistics === false) { return; } // skip if not pass seven days old if (date && !isExpired(date)) { return; } window.localStorage.setItem(applicationKeyForStorage, new Date().getTime()); setTimeout(function() { if (document.readyState === 'interactive' || document.readyState === 'complete') { imagePing(url, { v: 1, t: hitType, tid: trackingId, cid: hostname, dp: hostname, dh: appName, el: appName, ec: eventCategory }); } }, 1000); }
[ "function", "sendHostname", "(", "appName", ",", "trackingId", ")", "{", "var", "url", "=", "'https://www.google-analytics.com/collect'", ";", "var", "hostname", "=", "location", ".", "hostname", ";", "var", "hitType", "=", "'event'", ";", "var", "eventCategory", "=", "'use'", ";", "var", "applicationKeyForStorage", "=", "'TOAST UI '", "+", "appName", "+", "' for '", "+", "hostname", "+", "': Statistics'", ";", "var", "date", "=", "window", ".", "localStorage", ".", "getItem", "(", "applicationKeyForStorage", ")", ";", "// skip if the flag is defined and is set to false explicitly", "if", "(", "!", "type", ".", "isUndefined", "(", "window", ".", "tui", ")", "&&", "window", ".", "tui", ".", "usageStatistics", "===", "false", ")", "{", "return", ";", "}", "// skip if not pass seven days old", "if", "(", "date", "&&", "!", "isExpired", "(", "date", ")", ")", "{", "return", ";", "}", "window", ".", "localStorage", ".", "setItem", "(", "applicationKeyForStorage", ",", "new", "Date", "(", ")", ".", "getTime", "(", ")", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "if", "(", "document", ".", "readyState", "===", "'interactive'", "||", "document", ".", "readyState", "===", "'complete'", ")", "{", "imagePing", "(", "url", ",", "{", "v", ":", "1", ",", "t", ":", "hitType", ",", "tid", ":", "trackingId", ",", "cid", ":", "hostname", ",", "dp", ":", "hostname", ",", "dh", ":", "appName", ",", "el", ":", "appName", ",", "ec", ":", "eventCategory", "}", ")", ";", "}", "}", ",", "1000", ")", ";", "}" ]
Send hostname on DOMContentLoaded. To prevent hostname set tui.usageStatistics to false. @param {string} appName - application name @param {string} trackingId - GA tracking ID @ignore
[ "Send", "hostname", "on", "DOMContentLoaded", ".", "To", "prevent", "hostname", "set", "tui", ".", "usageStatistics", "to", "false", "." ]
7973b0d635d7e6dbd408a214fd5dac859237d1a8
https://github.com/nhn/tui.code-snippet/blob/7973b0d635d7e6dbd408a214fd5dac859237d1a8/src/js/request.js#L32-L66
18,163
nhn/tui.code-snippet
karma.conf.js
setConfig
function setConfig(defaultConfig, server) { if (server === 'ne') { defaultConfig.customLaunchers = { 'IE8': { base: 'WebDriver', config: webdriverConfig, browserName: 'internet explorer', version: '8' }, 'IE9': { base: 'WebDriver', config: webdriverConfig, browserName: 'internet explorer', version: '9' }, 'IE10': { base: 'WebDriver', browserName: 'internet explorer', config: webdriverConfig, version: '10' }, 'IE11': { base: 'WebDriver', config: webdriverConfig, browserName: 'internet explorer', version: '11' }, 'Edge': { base: 'WebDriver', config: webdriverConfig, browserName: 'MicrosoftEdge' }, 'Chrome-WebDriver': { base: 'WebDriver', config: webdriverConfig, browserName: 'chrome' }, 'Firefox-WebDriver': { base: 'WebDriver', config: webdriverConfig, browserName: 'firefox' } // 'Safari-WebDriver': { // base: 'WebDriver', // config: webdriverConfig, // browserName: 'safari' // } }; defaultConfig.browsers = [ // @FIXME: localStorage mocking 버그. 이후 수정 필요 // 'IE8', 'IE9', 'IE10', // 'IE11', // 'Edge', 'Chrome-WebDriver', 'Firefox-WebDriver' // 'Safari-WebDriver' ]; defaultConfig.reporters.push('coverage'); defaultConfig.reporters.push('junit'); defaultConfig.coverageReporter = { dir: 'report/coverage/', reporters: [{ type: 'html', subdir: function(browser) { return 'report-html/' + browser; } }, { type: 'cobertura', subdir: function(browser) { return 'report-cobertura/' + browser; }, file: 'cobertura.txt' } ] }; defaultConfig.junitReporter = { outputDir: 'report/junit', suite: '' }; } else { defaultConfig.browsers = [ 'ChromeHeadless' ]; } }
javascript
function setConfig(defaultConfig, server) { if (server === 'ne') { defaultConfig.customLaunchers = { 'IE8': { base: 'WebDriver', config: webdriverConfig, browserName: 'internet explorer', version: '8' }, 'IE9': { base: 'WebDriver', config: webdriverConfig, browserName: 'internet explorer', version: '9' }, 'IE10': { base: 'WebDriver', browserName: 'internet explorer', config: webdriverConfig, version: '10' }, 'IE11': { base: 'WebDriver', config: webdriverConfig, browserName: 'internet explorer', version: '11' }, 'Edge': { base: 'WebDriver', config: webdriverConfig, browserName: 'MicrosoftEdge' }, 'Chrome-WebDriver': { base: 'WebDriver', config: webdriverConfig, browserName: 'chrome' }, 'Firefox-WebDriver': { base: 'WebDriver', config: webdriverConfig, browserName: 'firefox' } // 'Safari-WebDriver': { // base: 'WebDriver', // config: webdriverConfig, // browserName: 'safari' // } }; defaultConfig.browsers = [ // @FIXME: localStorage mocking 버그. 이후 수정 필요 // 'IE8', 'IE9', 'IE10', // 'IE11', // 'Edge', 'Chrome-WebDriver', 'Firefox-WebDriver' // 'Safari-WebDriver' ]; defaultConfig.reporters.push('coverage'); defaultConfig.reporters.push('junit'); defaultConfig.coverageReporter = { dir: 'report/coverage/', reporters: [{ type: 'html', subdir: function(browser) { return 'report-html/' + browser; } }, { type: 'cobertura', subdir: function(browser) { return 'report-cobertura/' + browser; }, file: 'cobertura.txt' } ] }; defaultConfig.junitReporter = { outputDir: 'report/junit', suite: '' }; } else { defaultConfig.browsers = [ 'ChromeHeadless' ]; } }
[ "function", "setConfig", "(", "defaultConfig", ",", "server", ")", "{", "if", "(", "server", "===", "'ne'", ")", "{", "defaultConfig", ".", "customLaunchers", "=", "{", "'IE8'", ":", "{", "base", ":", "'WebDriver'", ",", "config", ":", "webdriverConfig", ",", "browserName", ":", "'internet explorer'", ",", "version", ":", "'8'", "}", ",", "'IE9'", ":", "{", "base", ":", "'WebDriver'", ",", "config", ":", "webdriverConfig", ",", "browserName", ":", "'internet explorer'", ",", "version", ":", "'9'", "}", ",", "'IE10'", ":", "{", "base", ":", "'WebDriver'", ",", "browserName", ":", "'internet explorer'", ",", "config", ":", "webdriverConfig", ",", "version", ":", "'10'", "}", ",", "'IE11'", ":", "{", "base", ":", "'WebDriver'", ",", "config", ":", "webdriverConfig", ",", "browserName", ":", "'internet explorer'", ",", "version", ":", "'11'", "}", ",", "'Edge'", ":", "{", "base", ":", "'WebDriver'", ",", "config", ":", "webdriverConfig", ",", "browserName", ":", "'MicrosoftEdge'", "}", ",", "'Chrome-WebDriver'", ":", "{", "base", ":", "'WebDriver'", ",", "config", ":", "webdriverConfig", ",", "browserName", ":", "'chrome'", "}", ",", "'Firefox-WebDriver'", ":", "{", "base", ":", "'WebDriver'", ",", "config", ":", "webdriverConfig", ",", "browserName", ":", "'firefox'", "}", "// 'Safari-WebDriver': {", "// base: 'WebDriver',", "// config: webdriverConfig,", "// browserName: 'safari'", "// }", "}", ";", "defaultConfig", ".", "browsers", "=", "[", "// @FIXME: localStorage mocking 버그. 이후 수정 필요", "// 'IE8',", "'IE9'", ",", "'IE10'", ",", "// 'IE11',", "// 'Edge',", "'Chrome-WebDriver'", ",", "'Firefox-WebDriver'", "// 'Safari-WebDriver'", "]", ";", "defaultConfig", ".", "reporters", ".", "push", "(", "'coverage'", ")", ";", "defaultConfig", ".", "reporters", ".", "push", "(", "'junit'", ")", ";", "defaultConfig", ".", "coverageReporter", "=", "{", "dir", ":", "'report/coverage/'", ",", "reporters", ":", "[", "{", "type", ":", "'html'", ",", "subdir", ":", "function", "(", "browser", ")", "{", "return", "'report-html/'", "+", "browser", ";", "}", "}", ",", "{", "type", ":", "'cobertura'", ",", "subdir", ":", "function", "(", "browser", ")", "{", "return", "'report-cobertura/'", "+", "browser", ";", "}", ",", "file", ":", "'cobertura.txt'", "}", "]", "}", ";", "defaultConfig", ".", "junitReporter", "=", "{", "outputDir", ":", "'report/junit'", ",", "suite", ":", "''", "}", ";", "}", "else", "{", "defaultConfig", ".", "browsers", "=", "[", "'ChromeHeadless'", "]", ";", "}", "}" ]
manipulate config by server @param {Object} defaultConfig - base configuration @param {'ne'|null|undefined} server - ne: team selenium grid, null or undefined: local machine
[ "manipulate", "config", "by", "server" ]
7973b0d635d7e6dbd408a214fd5dac859237d1a8
https://github.com/nhn/tui.code-snippet/blob/7973b0d635d7e6dbd408a214fd5dac859237d1a8/karma.conf.js#L14-L101
18,164
nhn/tui.code-snippet
src/js/formatDate.js
isValidDate
function isValidDate(year, month, date) { // eslint-disable-line complexity var isValidYear, isValidMonth, isValid, lastDayInMonth; year = Number(year); month = Number(month); date = Number(date); isValidYear = (year > -1 && year < 100) || ((year > 1969) && (year < 2070)); isValidMonth = (month > 0) && (month < 13); if (!isValidYear || !isValidMonth) { return false; } lastDayInMonth = MONTH_DAYS[month]; if (month === 2 && year % 4 === 0) { if (year % 100 !== 0 || year % 400 === 0) { lastDayInMonth = 29; } } isValid = (date > 0) && (date <= lastDayInMonth); return isValid; }
javascript
function isValidDate(year, month, date) { // eslint-disable-line complexity var isValidYear, isValidMonth, isValid, lastDayInMonth; year = Number(year); month = Number(month); date = Number(date); isValidYear = (year > -1 && year < 100) || ((year > 1969) && (year < 2070)); isValidMonth = (month > 0) && (month < 13); if (!isValidYear || !isValidMonth) { return false; } lastDayInMonth = MONTH_DAYS[month]; if (month === 2 && year % 4 === 0) { if (year % 100 !== 0 || year % 400 === 0) { lastDayInMonth = 29; } } isValid = (date > 0) && (date <= lastDayInMonth); return isValid; }
[ "function", "isValidDate", "(", "year", ",", "month", ",", "date", ")", "{", "// eslint-disable-line complexity", "var", "isValidYear", ",", "isValidMonth", ",", "isValid", ",", "lastDayInMonth", ";", "year", "=", "Number", "(", "year", ")", ";", "month", "=", "Number", "(", "month", ")", ";", "date", "=", "Number", "(", "date", ")", ";", "isValidYear", "=", "(", "year", ">", "-", "1", "&&", "year", "<", "100", ")", "||", "(", "(", "year", ">", "1969", ")", "&&", "(", "year", "<", "2070", ")", ")", ";", "isValidMonth", "=", "(", "month", ">", "0", ")", "&&", "(", "month", "<", "13", ")", ";", "if", "(", "!", "isValidYear", "||", "!", "isValidMonth", ")", "{", "return", "false", ";", "}", "lastDayInMonth", "=", "MONTH_DAYS", "[", "month", "]", ";", "if", "(", "month", "===", "2", "&&", "year", "%", "4", "===", "0", ")", "{", "if", "(", "year", "%", "100", "!==", "0", "||", "year", "%", "400", "===", "0", ")", "{", "lastDayInMonth", "=", "29", ";", "}", "}", "isValid", "=", "(", "date", ">", "0", ")", "&&", "(", "date", "<=", "lastDayInMonth", ")", ";", "return", "isValid", ";", "}" ]
Check whether the given variables are valid date or not. @param {number} year - Year @param {number} month - Month @param {number} date - Day in month. @returns {boolean} Is valid? @private
[ "Check", "whether", "the", "given", "variables", "are", "valid", "date", "or", "not", "." ]
7973b0d635d7e6dbd408a214fd5dac859237d1a8
https://github.com/nhn/tui.code-snippet/blob/7973b0d635d7e6dbd408a214fd5dac859237d1a8/src/js/formatDate.js#L103-L127
18,165
nhn/tui.code-snippet
src/js/tricks.js
throttle
function throttle(fn, interval) { var base; var isLeading = true; var tick = function(_args) { fn.apply(null, _args); base = null; }; var debounced, stamp, args; /* istanbul ignore next */ interval = interval || 0; debounced = tricks.debounce(tick, interval); function throttled() { // eslint-disable-line require-jsdoc args = aps.call(arguments); if (isLeading) { tick(args); isLeading = false; return; } stamp = tricks.timestamp(); base = base || stamp; // pass array directly because `debounce()`, `tick()` are already use // `apply()` method to invoke developer's `fn` handler. // // also, this `debounced` line invoked every time for implements // `trailing` features. debounced(args); if ((stamp - base) >= interval) { tick(args); } } function reset() { // eslint-disable-line require-jsdoc isLeading = true; base = null; } throttled.reset = reset; return throttled; }
javascript
function throttle(fn, interval) { var base; var isLeading = true; var tick = function(_args) { fn.apply(null, _args); base = null; }; var debounced, stamp, args; /* istanbul ignore next */ interval = interval || 0; debounced = tricks.debounce(tick, interval); function throttled() { // eslint-disable-line require-jsdoc args = aps.call(arguments); if (isLeading) { tick(args); isLeading = false; return; } stamp = tricks.timestamp(); base = base || stamp; // pass array directly because `debounce()`, `tick()` are already use // `apply()` method to invoke developer's `fn` handler. // // also, this `debounced` line invoked every time for implements // `trailing` features. debounced(args); if ((stamp - base) >= interval) { tick(args); } } function reset() { // eslint-disable-line require-jsdoc isLeading = true; base = null; } throttled.reset = reset; return throttled; }
[ "function", "throttle", "(", "fn", ",", "interval", ")", "{", "var", "base", ";", "var", "isLeading", "=", "true", ";", "var", "tick", "=", "function", "(", "_args", ")", "{", "fn", ".", "apply", "(", "null", ",", "_args", ")", ";", "base", "=", "null", ";", "}", ";", "var", "debounced", ",", "stamp", ",", "args", ";", "/* istanbul ignore next */", "interval", "=", "interval", "||", "0", ";", "debounced", "=", "tricks", ".", "debounce", "(", "tick", ",", "interval", ")", ";", "function", "throttled", "(", ")", "{", "// eslint-disable-line require-jsdoc", "args", "=", "aps", ".", "call", "(", "arguments", ")", ";", "if", "(", "isLeading", ")", "{", "tick", "(", "args", ")", ";", "isLeading", "=", "false", ";", "return", ";", "}", "stamp", "=", "tricks", ".", "timestamp", "(", ")", ";", "base", "=", "base", "||", "stamp", ";", "// pass array directly because `debounce()`, `tick()` are already use", "// `apply()` method to invoke developer's `fn` handler.", "//", "// also, this `debounced` line invoked every time for implements", "// `trailing` features.", "debounced", "(", "args", ")", ";", "if", "(", "(", "stamp", "-", "base", ")", ">=", "interval", ")", "{", "tick", "(", "args", ")", ";", "}", "}", "function", "reset", "(", ")", "{", "// eslint-disable-line require-jsdoc", "isLeading", "=", "true", ";", "base", "=", "null", ";", "}", "throttled", ".", "reset", "=", "reset", ";", "return", "throttled", ";", "}" ]
Creates a throttled function that only invokes fn at most once per every interval milliseconds. You can use this throttle short time repeatedly invoking functions. (e.g MouseMove, Resize ...) if you need reuse throttled method. you must remove slugs (e.g. flag variable) related with throttling. @param {function} fn function to throttle @param {number} [interval=0] the number of milliseconds to throttle invocations to. @memberof tui.util @returns {function} throttled function @example //-- #1. Get Module --// var util = require('tui-code-snippet'); // node, commonjs var util = tui.util; // distribution file //-- #2. Use property --// function someMethodToInvokeThrottled() {} var throttled = util.throttle(someMethodToInvokeThrottled, 300); // invoke repeatedly throttled(); // invoke (leading) throttled(); throttled(); // invoke (near 300 milliseconds) throttled(); throttled(); throttled(); // invoke (near 600 milliseconds) // ... // invoke (trailing) // if you need reuse throttled method. then invoke reset() throttled.reset();
[ "Creates", "a", "throttled", "function", "that", "only", "invokes", "fn", "at", "most", "once", "per", "every", "interval", "milliseconds", "." ]
7973b0d635d7e6dbd408a214fd5dac859237d1a8
https://github.com/nhn/tui.code-snippet/blob/7973b0d635d7e6dbd408a214fd5dac859237d1a8/src/js/tricks.js#L99-L147
18,166
nhn/tui.code-snippet
src/js/object.js
extend
function extend(target, objects) { // eslint-disable-line no-unused-vars var hasOwnProp = Object.prototype.hasOwnProperty; var source, prop, i, len; for (i = 1, len = arguments.length; i < len; i += 1) { source = arguments[i]; for (prop in source) { if (hasOwnProp.call(source, prop)) { target[prop] = source[prop]; } } } return target; }
javascript
function extend(target, objects) { // eslint-disable-line no-unused-vars var hasOwnProp = Object.prototype.hasOwnProperty; var source, prop, i, len; for (i = 1, len = arguments.length; i < len; i += 1) { source = arguments[i]; for (prop in source) { if (hasOwnProp.call(source, prop)) { target[prop] = source[prop]; } } } return target; }
[ "function", "extend", "(", "target", ",", "objects", ")", "{", "// eslint-disable-line no-unused-vars", "var", "hasOwnProp", "=", "Object", ".", "prototype", ".", "hasOwnProperty", ";", "var", "source", ",", "prop", ",", "i", ",", "len", ";", "for", "(", "i", "=", "1", ",", "len", "=", "arguments", ".", "length", ";", "i", "<", "len", ";", "i", "+=", "1", ")", "{", "source", "=", "arguments", "[", "i", "]", ";", "for", "(", "prop", "in", "source", ")", "{", "if", "(", "hasOwnProp", ".", "call", "(", "source", ",", "prop", ")", ")", "{", "target", "[", "prop", "]", "=", "source", "[", "prop", "]", ";", "}", "}", "}", "return", "target", ";", "}" ]
Extend the target object from other objects. @param {object} target - Object that will be extended @param {...object} objects - Objects as sources @returns {object} Extended object @memberof tui.util
[ "Extend", "the", "target", "object", "from", "other", "objects", "." ]
7973b0d635d7e6dbd408a214fd5dac859237d1a8
https://github.com/nhn/tui.code-snippet/blob/7973b0d635d7e6dbd408a214fd5dac859237d1a8/src/js/object.js#L26-L40
18,167
nhn/tui.code-snippet
src/js/object.js
stamp
function stamp(obj) { if (!obj.__fe_id) { lastId += 1; obj.__fe_id = lastId; // eslint-disable-line camelcase } return obj.__fe_id; }
javascript
function stamp(obj) { if (!obj.__fe_id) { lastId += 1; obj.__fe_id = lastId; // eslint-disable-line camelcase } return obj.__fe_id; }
[ "function", "stamp", "(", "obj", ")", "{", "if", "(", "!", "obj", ".", "__fe_id", ")", "{", "lastId", "+=", "1", ";", "obj", ".", "__fe_id", "=", "lastId", ";", "// eslint-disable-line camelcase", "}", "return", "obj", ".", "__fe_id", ";", "}" ]
Assign a unique id to an object @param {object} obj - Object that will be assigned id. @returns {number} Stamped id @memberof tui.util
[ "Assign", "a", "unique", "id", "to", "an", "object" ]
7973b0d635d7e6dbd408a214fd5dac859237d1a8
https://github.com/nhn/tui.code-snippet/blob/7973b0d635d7e6dbd408a214fd5dac859237d1a8/src/js/object.js#L48-L55
18,168
suguru03/aigle
lib/aigle.js
mixin
function mixin(sources, opts = {}) { const { override, promisify = true } = opts; Object.getOwnPropertyNames(sources).forEach(key => { const func = sources[key]; if (typeof func !== 'function' || (Aigle[key] && !override)) { return; } // check lodash chain if (key === 'chain') { const obj = func(); if (obj && obj.__chain__) { Aigle.chain = _resolve; Aigle.prototype.value = function() { return this; }; return; } } const Proxy = createProxy(func, promisify); Aigle[key] = function(value, arg1, arg2, arg3) { return new Proxy(value, arg1, arg2, arg3)._execute(); }; Aigle.prototype[key] = function(arg1, arg2, arg3) { return addProxy(this, Proxy, arg1, arg2, arg3); }; }); return Aigle; }
javascript
function mixin(sources, opts = {}) { const { override, promisify = true } = opts; Object.getOwnPropertyNames(sources).forEach(key => { const func = sources[key]; if (typeof func !== 'function' || (Aigle[key] && !override)) { return; } // check lodash chain if (key === 'chain') { const obj = func(); if (obj && obj.__chain__) { Aigle.chain = _resolve; Aigle.prototype.value = function() { return this; }; return; } } const Proxy = createProxy(func, promisify); Aigle[key] = function(value, arg1, arg2, arg3) { return new Proxy(value, arg1, arg2, arg3)._execute(); }; Aigle.prototype[key] = function(arg1, arg2, arg3) { return addProxy(this, Proxy, arg1, arg2, arg3); }; }); return Aigle; }
[ "function", "mixin", "(", "sources", ",", "opts", "=", "{", "}", ")", "{", "const", "{", "override", ",", "promisify", "=", "true", "}", "=", "opts", ";", "Object", ".", "getOwnPropertyNames", "(", "sources", ")", ".", "forEach", "(", "key", "=>", "{", "const", "func", "=", "sources", "[", "key", "]", ";", "if", "(", "typeof", "func", "!==", "'function'", "||", "(", "Aigle", "[", "key", "]", "&&", "!", "override", ")", ")", "{", "return", ";", "}", "// check lodash chain", "if", "(", "key", "===", "'chain'", ")", "{", "const", "obj", "=", "func", "(", ")", ";", "if", "(", "obj", "&&", "obj", ".", "__chain__", ")", "{", "Aigle", ".", "chain", "=", "_resolve", ";", "Aigle", ".", "prototype", ".", "value", "=", "function", "(", ")", "{", "return", "this", ";", "}", ";", "return", ";", "}", "}", "const", "Proxy", "=", "createProxy", "(", "func", ",", "promisify", ")", ";", "Aigle", "[", "key", "]", "=", "function", "(", "value", ",", "arg1", ",", "arg2", ",", "arg3", ")", "{", "return", "new", "Proxy", "(", "value", ",", "arg1", ",", "arg2", ",", "arg3", ")", ".", "_execute", "(", ")", ";", "}", ";", "Aigle", ".", "prototype", "[", "key", "]", "=", "function", "(", "arg1", ",", "arg2", ",", "arg3", ")", "{", "return", "addProxy", "(", "this", ",", "Proxy", ",", "arg1", ",", "arg2", ",", "arg3", ")", ";", "}", ";", "}", ")", ";", "return", "Aigle", ";", "}" ]
Add functions which sources has to the Aigle class functions and static functions. The functions will be converted asynchronous functions. If an extended function returns a promise instance, the function will wait until the promise is resolved. @param {Object} sources @param {Object} [opts] @param {boolean} [opts.promisify=true] @param {boolean} [opts.override=false] @example Aigle.mixin(require('lodash')); const array = [1, 2, 3]; return Aigle.map(array, n => Aigle.delay(10, n * 2)) .sum() .then(value => { console.log(value; // 12 }); @example Aigle.mixin(require('lodash')); const array = [1.1, 1.4, 2.2]; return Aigle.map(array, n => Aigle.delay(10, n * 2)) .uniqBy(n => Aigle.delay(10, Math.floor(n)) .then(array => { console.log(array; // [2.2, 4.4] });
[ "Add", "functions", "which", "sources", "has", "to", "the", "Aigle", "class", "functions", "and", "static", "functions", ".", "The", "functions", "will", "be", "converted", "asynchronous", "functions", ".", "If", "an", "extended", "function", "returns", "a", "promise", "instance", "the", "function", "will", "wait", "until", "the", "promise", "is", "resolved", "." ]
c48f3ad200955d410ca078ccdd22f0bc738f7322
https://github.com/suguru03/aigle/blob/c48f3ad200955d410ca078ccdd22f0bc738f7322/lib/aigle.js#L3971-L3998
18,169
aearly/icepick
icepick.js
baseGet
function baseGet (coll, path) { return (path || []).reduce((curr, key) => { if (!curr) { return } return curr[key] }, coll) }
javascript
function baseGet (coll, path) { return (path || []).reduce((curr, key) => { if (!curr) { return } return curr[key] }, coll) }
[ "function", "baseGet", "(", "coll", ",", "path", ")", "{", "return", "(", "path", "||", "[", "]", ")", ".", "reduce", "(", "(", "curr", ",", "key", ")", "=>", "{", "if", "(", "!", "curr", ")", "{", "return", "}", "return", "curr", "[", "key", "]", "}", ",", "coll", ")", "}" ]
get an object from a hierachy based on an array of keys @param {Object|Array} coll @param {Array} path list of keys @return {Object} value, or undefined
[ "get", "an", "object", "from", "a", "hierachy", "based", "on", "an", "array", "of", "keys" ]
132a2111eb85d913c815d35c1b44aad919b6b0c1
https://github.com/aearly/icepick/blob/132a2111eb85d913c815d35c1b44aad919b6b0c1/icepick.js#L214-L219
18,170
cloudflarearchive/backgrid
src/formatter.js
function (number, model) { if (_.isNull(number) || _.isUndefined(number)) return ''; number = parseFloat(number).toFixed(~~this.decimals); var parts = number.split('.'); var integerPart = parts[0]; var decimalPart = parts[1] ? (this.decimalSeparator || '.') + parts[1] : ''; return integerPart.replace(this.HUMANIZED_NUM_RE, '$1' + this.orderSeparator) + decimalPart; }
javascript
function (number, model) { if (_.isNull(number) || _.isUndefined(number)) return ''; number = parseFloat(number).toFixed(~~this.decimals); var parts = number.split('.'); var integerPart = parts[0]; var decimalPart = parts[1] ? (this.decimalSeparator || '.') + parts[1] : ''; return integerPart.replace(this.HUMANIZED_NUM_RE, '$1' + this.orderSeparator) + decimalPart; }
[ "function", "(", "number", ",", "model", ")", "{", "if", "(", "_", ".", "isNull", "(", "number", ")", "||", "_", ".", "isUndefined", "(", "number", ")", ")", "return", "''", ";", "number", "=", "parseFloat", "(", "number", ")", ".", "toFixed", "(", "~", "~", "this", ".", "decimals", ")", ";", "var", "parts", "=", "number", ".", "split", "(", "'.'", ")", ";", "var", "integerPart", "=", "parts", "[", "0", "]", ";", "var", "decimalPart", "=", "parts", "[", "1", "]", "?", "(", "this", ".", "decimalSeparator", "||", "'.'", ")", "+", "parts", "[", "1", "]", ":", "''", ";", "return", "integerPart", ".", "replace", "(", "this", ".", "HUMANIZED_NUM_RE", ",", "'$1'", "+", "this", ".", "orderSeparator", ")", "+", "decimalPart", ";", "}" ]
Takes a floating point number and convert it to a formatted string where every thousand is separated by `orderSeparator`, with a `decimal` number of decimals separated by `decimalSeparator`. The number returned is rounded the usual way. @member Backgrid.NumberFormatter @param {number} number @param {Backbone.Model} model Used for more complicated formatting @return {string}
[ "Takes", "a", "floating", "point", "number", "and", "convert", "it", "to", "a", "formatted", "string", "where", "every", "thousand", "is", "separated", "by", "orderSeparator", "with", "a", "decimal", "number", "of", "decimals", "separated", "by", "decimalSeparator", ".", "The", "number", "returned", "is", "rounded", "the", "usual", "way", "." ]
646d68790fef504542a120fa36c07c717ca7ddc3
https://github.com/cloudflarearchive/backgrid/blob/646d68790fef504542a120fa36c07c717ca7ddc3/src/formatter.js#L105-L115
18,171
cloudflarearchive/backgrid
src/formatter.js
function (rawData, model) { if (_.isNull(rawData) || _.isUndefined(rawData)) return ''; return this._convert(rawData); }
javascript
function (rawData, model) { if (_.isNull(rawData) || _.isUndefined(rawData)) return ''; return this._convert(rawData); }
[ "function", "(", "rawData", ",", "model", ")", "{", "if", "(", "_", ".", "isNull", "(", "rawData", ")", "||", "_", ".", "isUndefined", "(", "rawData", ")", ")", "return", "''", ";", "return", "this", ".", "_convert", "(", "rawData", ")", ";", "}" ]
Converts an ISO-8601 formatted datetime string to a datetime string, date string or a time string. The timezone is ignored if supplied. @member Backgrid.DatetimeFormatter @param {string} rawData @param {Backbone.Model} model Used for more complicated formatting @return {string|null|undefined} ISO-8601 string in UTC. Null and undefined values are returned as is.
[ "Converts", "an", "ISO", "-", "8601", "formatted", "datetime", "string", "to", "a", "datetime", "string", "date", "string", "or", "a", "time", "string", ".", "The", "timezone", "is", "ignored", "if", "supplied", "." ]
646d68790fef504542a120fa36c07c717ca7ddc3
https://github.com/cloudflarearchive/backgrid/blob/646d68790fef504542a120fa36c07c717ca7ddc3/src/formatter.js#L337-L340
18,172
cloudflarearchive/backgrid
src/column.js
function () { if (!this.has("label")) { this.set({ label: this.get("name") }, { silent: true }); } var headerCell = Backgrid.resolveNameToClass(this.get("headerCell"), "HeaderCell"); var cell = Backgrid.resolveNameToClass(this.get("cell"), "Cell"); this.set({cell: cell, headerCell: headerCell}, { silent: true }); }
javascript
function () { if (!this.has("label")) { this.set({ label: this.get("name") }, { silent: true }); } var headerCell = Backgrid.resolveNameToClass(this.get("headerCell"), "HeaderCell"); var cell = Backgrid.resolveNameToClass(this.get("cell"), "Cell"); this.set({cell: cell, headerCell: headerCell}, { silent: true }); }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "has", "(", "\"label\"", ")", ")", "{", "this", ".", "set", "(", "{", "label", ":", "this", ".", "get", "(", "\"name\"", ")", "}", ",", "{", "silent", ":", "true", "}", ")", ";", "}", "var", "headerCell", "=", "Backgrid", ".", "resolveNameToClass", "(", "this", ".", "get", "(", "\"headerCell\"", ")", ",", "\"HeaderCell\"", ")", ";", "var", "cell", "=", "Backgrid", ".", "resolveNameToClass", "(", "this", ".", "get", "(", "\"cell\"", ")", ",", "\"Cell\"", ")", ";", "this", ".", "set", "(", "{", "cell", ":", "cell", ",", "headerCell", ":", "headerCell", "}", ",", "{", "silent", ":", "true", "}", ")", ";", "}" ]
Initializes this Column instance. @param {Object} attrs @param {string} attrs.name The model attribute this column is responsible for. @param {string|Backgrid.Cell} attrs.cell The cell type to use to render this column. @param {string} [attrs.label] @param {string|Backgrid.HeaderCell} [attrs.headerCell] @param {boolean|string|function(): boolean} [attrs.sortable=true] @param {boolean|string|function(): boolean} [attrs.editable=true] @param {boolean|string|function(): boolean} [attrs.renderable=true] @param {Backgrid.CellFormatter | Object | string} [attrs.formatter] @param {"toggle"|"cycle"} [attrs.sortType="cycle"] @param {(function(Backbone.Model, string): *) | string} [attrs.sortValue] @throws {TypeError} If attrs.cell or attrs.options are not supplied. @throws {ReferenceError} If formatter is a string but a formatter class of said name cannot be found in the Backgrid module. See: - Backgrid.Column.defaults - Backgrid.Cell - Backgrid.CellFormatter
[ "Initializes", "this", "Column", "instance", "." ]
646d68790fef504542a120fa36c07c717ca7ddc3
https://github.com/cloudflarearchive/backgrid/blob/646d68790fef504542a120fa36c07c717ca7ddc3/src/column.js#L142-L152
18,173
cloudflarearchive/backgrid
src/column.js
function () { var sortValue = this.get("sortValue"); if (_.isString(sortValue)) return this[sortValue]; else if (_.isFunction(sortValue)) return sortValue; return function (model, colName) { return model.get(colName); }; }
javascript
function () { var sortValue = this.get("sortValue"); if (_.isString(sortValue)) return this[sortValue]; else if (_.isFunction(sortValue)) return sortValue; return function (model, colName) { return model.get(colName); }; }
[ "function", "(", ")", "{", "var", "sortValue", "=", "this", ".", "get", "(", "\"sortValue\"", ")", ";", "if", "(", "_", ".", "isString", "(", "sortValue", ")", ")", "return", "this", "[", "sortValue", "]", ";", "else", "if", "(", "_", ".", "isFunction", "(", "sortValue", ")", ")", "return", "sortValue", ";", "return", "function", "(", "model", ",", "colName", ")", "{", "return", "model", ".", "get", "(", "colName", ")", ";", "}", ";", "}" ]
Returns an appropriate value extraction function from a model for sorting. If the column model contains an attribute `sortValue`, if it is a string, a method from the column instance identifified by the `sortValue` string is returned. If it is a function, it it returned as is. If `sortValue` isn't found from the column model's attributes, a default value extraction function is returned which will compare according to the natural order of the value's type. @return {function(Backbone.Model, string): *}
[ "Returns", "an", "appropriate", "value", "extraction", "function", "from", "a", "model", "for", "sorting", "." ]
646d68790fef504542a120fa36c07c717ca7ddc3
https://github.com/cloudflarearchive/backgrid/blob/646d68790fef504542a120fa36c07c717ca7ddc3/src/column.js#L166-L174
18,174
nearform/node-clinic-bubbleprof
visualizer/data/index.js
loadData
function loadData (settings = {}, json = data) { const dataSet = new DataSet(json, settings) dataSet.processData() return dataSet }
javascript
function loadData (settings = {}, json = data) { const dataSet = new DataSet(json, settings) dataSet.processData() return dataSet }
[ "function", "loadData", "(", "settings", "=", "{", "}", ",", "json", "=", "data", ")", "{", "const", "dataSet", "=", "new", "DataSet", "(", "json", ",", "settings", ")", "dataSet", ".", "processData", "(", ")", "return", "dataSet", "}" ]
'json = data' optional arg allows json to be passed in for browserless tests
[ "json", "=", "data", "optional", "arg", "allows", "json", "to", "be", "passed", "in", "for", "browserless", "tests" ]
684e873232997a1eab8a6318b288309b7ad825c1
https://github.com/nearform/node-clinic-bubbleprof/blob/684e873232997a1eab8a6318b288309b7ad825c1/visualizer/data/index.js#L8-L12
18,175
driverdan/node-XMLHttpRequest
lib/XMLHttpRequest.js
responseHandler
function responseHandler(resp) { // Set response var to the response we got back // This is so it remains accessable outside this scope response = resp; // Check for redirect // @TODO Prevent looped redirects if (response.statusCode === 301 || response.statusCode === 302 || response.statusCode === 303 || response.statusCode === 307) { // Change URL to the redirect location settings.url = response.headers.location; var url = Url.parse(settings.url); // Set host var in case it's used later host = url.hostname; // Options for the new request var newOptions = { hostname: url.hostname, port: url.port, path: url.path, method: response.statusCode === 303 ? "GET" : settings.method, headers: headers, withCredentials: self.withCredentials }; // Issue the new request request = doRequest(newOptions, responseHandler).on("error", errorHandler); request.end(); // @TODO Check if an XHR event needs to be fired here return; } response.setEncoding("utf8"); setState(self.HEADERS_RECEIVED); self.status = response.statusCode; response.on("data", function(chunk) { // Make sure there's some data if (chunk) { self.responseText += chunk; } // Don't emit state changes if the connection has been aborted. if (sendFlag) { setState(self.LOADING); } }); response.on("end", function() { if (sendFlag) { // Discard the end event if the connection has been aborted setState(self.DONE); sendFlag = false; } }); response.on("error", function(error) { self.handleError(error); }); }
javascript
function responseHandler(resp) { // Set response var to the response we got back // This is so it remains accessable outside this scope response = resp; // Check for redirect // @TODO Prevent looped redirects if (response.statusCode === 301 || response.statusCode === 302 || response.statusCode === 303 || response.statusCode === 307) { // Change URL to the redirect location settings.url = response.headers.location; var url = Url.parse(settings.url); // Set host var in case it's used later host = url.hostname; // Options for the new request var newOptions = { hostname: url.hostname, port: url.port, path: url.path, method: response.statusCode === 303 ? "GET" : settings.method, headers: headers, withCredentials: self.withCredentials }; // Issue the new request request = doRequest(newOptions, responseHandler).on("error", errorHandler); request.end(); // @TODO Check if an XHR event needs to be fired here return; } response.setEncoding("utf8"); setState(self.HEADERS_RECEIVED); self.status = response.statusCode; response.on("data", function(chunk) { // Make sure there's some data if (chunk) { self.responseText += chunk; } // Don't emit state changes if the connection has been aborted. if (sendFlag) { setState(self.LOADING); } }); response.on("end", function() { if (sendFlag) { // Discard the end event if the connection has been aborted setState(self.DONE); sendFlag = false; } }); response.on("error", function(error) { self.handleError(error); }); }
[ "function", "responseHandler", "(", "resp", ")", "{", "// Set response var to the response we got back", "// This is so it remains accessable outside this scope", "response", "=", "resp", ";", "// Check for redirect", "// @TODO Prevent looped redirects", "if", "(", "response", ".", "statusCode", "===", "301", "||", "response", ".", "statusCode", "===", "302", "||", "response", ".", "statusCode", "===", "303", "||", "response", ".", "statusCode", "===", "307", ")", "{", "// Change URL to the redirect location", "settings", ".", "url", "=", "response", ".", "headers", ".", "location", ";", "var", "url", "=", "Url", ".", "parse", "(", "settings", ".", "url", ")", ";", "// Set host var in case it's used later", "host", "=", "url", ".", "hostname", ";", "// Options for the new request", "var", "newOptions", "=", "{", "hostname", ":", "url", ".", "hostname", ",", "port", ":", "url", ".", "port", ",", "path", ":", "url", ".", "path", ",", "method", ":", "response", ".", "statusCode", "===", "303", "?", "\"GET\"", ":", "settings", ".", "method", ",", "headers", ":", "headers", ",", "withCredentials", ":", "self", ".", "withCredentials", "}", ";", "// Issue the new request", "request", "=", "doRequest", "(", "newOptions", ",", "responseHandler", ")", ".", "on", "(", "\"error\"", ",", "errorHandler", ")", ";", "request", ".", "end", "(", ")", ";", "// @TODO Check if an XHR event needs to be fired here", "return", ";", "}", "response", ".", "setEncoding", "(", "\"utf8\"", ")", ";", "setState", "(", "self", ".", "HEADERS_RECEIVED", ")", ";", "self", ".", "status", "=", "response", ".", "statusCode", ";", "response", ".", "on", "(", "\"data\"", ",", "function", "(", "chunk", ")", "{", "// Make sure there's some data", "if", "(", "chunk", ")", "{", "self", ".", "responseText", "+=", "chunk", ";", "}", "// Don't emit state changes if the connection has been aborted.", "if", "(", "sendFlag", ")", "{", "setState", "(", "self", ".", "LOADING", ")", ";", "}", "}", ")", ";", "response", ".", "on", "(", "\"end\"", ",", "function", "(", ")", "{", "if", "(", "sendFlag", ")", "{", "// Discard the end event if the connection has been aborted", "setState", "(", "self", ".", "DONE", ")", ";", "sendFlag", "=", "false", ";", "}", "}", ")", ";", "response", ".", "on", "(", "\"error\"", ",", "function", "(", "error", ")", "{", "self", ".", "handleError", "(", "error", ")", ";", "}", ")", ";", "}" ]
Handler for the response
[ "Handler", "for", "the", "response" ]
97966e4ca1c9f2cc5574d8775cbdacebfec75455
https://github.com/driverdan/node-XMLHttpRequest/blob/97966e4ca1c9f2cc5574d8775cbdacebfec75455/lib/XMLHttpRequest.js#L403-L459
18,176
ritz078/embed-js
packages/embed-plugin-noembed/src/index.js
_process
async function _process(args, { fetch }) { const url = args[0] try { const res = await fetch(`https://noembed.com/embed?url=${url}`) return await res.json() } catch (e) { return { html: url } } }
javascript
async function _process(args, { fetch }) { const url = args[0] try { const res = await fetch(`https://noembed.com/embed?url=${url}`) return await res.json() } catch (e) { return { html: url } } }
[ "async", "function", "_process", "(", "args", ",", "{", "fetch", "}", ")", "{", "const", "url", "=", "args", "[", "0", "]", "try", "{", "const", "res", "=", "await", "fetch", "(", "`", "${", "url", "}", "`", ")", "return", "await", "res", ".", "json", "(", ")", "}", "catch", "(", "e", ")", "{", "return", "{", "html", ":", "url", "}", "}", "}" ]
Fetches the data from the noembed API @param args @returns {Promise.<*>}
[ "Fetches", "the", "data", "from", "the", "noembed", "API" ]
539e51a09ad891cdc496b594d9ea7cd678e1cf30
https://github.com/ritz078/embed-js/blob/539e51a09ad891cdc496b594d9ea7cd678e1cf30/packages/embed-plugin-noembed/src/index.js#L14-L24
18,177
ritz078/embed-js
packages/embed-js/src/index.js
combineEmbedsText
function combineEmbedsText(embeds) { return embeds .sort((a, b) => a.index - b.index) .map(({ content }) => content) .join(" ") }
javascript
function combineEmbedsText(embeds) { return embeds .sort((a, b) => a.index - b.index) .map(({ content }) => content) .join(" ") }
[ "function", "combineEmbedsText", "(", "embeds", ")", "{", "return", "embeds", ".", "sort", "(", "(", "a", ",", "b", ")", "=>", "a", ".", "index", "-", "b", ".", "index", ")", ".", "map", "(", "(", "{", "content", "}", ")", "=>", "content", ")", ".", "join", "(", "\" \"", ")", "}" ]
Returns the embed code to be added at the end of original string. @param embeds @returns {string}
[ "Returns", "the", "embed", "code", "to", "be", "added", "at", "the", "end", "of", "original", "string", "." ]
539e51a09ad891cdc496b594d9ea7cd678e1cf30
https://github.com/ritz078/embed-js/blob/539e51a09ad891cdc496b594d9ea7cd678e1cf30/packages/embed-js/src/index.js#L11-L16
18,178
ritz078/embed-js
packages/embed-plugin-youtube/src/index.js
formatData
function formatData({ snippet, id }) { return { title: snippet.title, thumbnail: snippet.thumbnails.medium.url, description: snippet.description, url: `${baseUrl}watch?v=${id}`, embedUrl: `${baseUrl}embed/${id}` } }
javascript
function formatData({ snippet, id }) { return { title: snippet.title, thumbnail: snippet.thumbnails.medium.url, description: snippet.description, url: `${baseUrl}watch?v=${id}`, embedUrl: `${baseUrl}embed/${id}` } }
[ "function", "formatData", "(", "{", "snippet", ",", "id", "}", ")", "{", "return", "{", "title", ":", "snippet", ".", "title", ",", "thumbnail", ":", "snippet", ".", "thumbnails", ".", "medium", ".", "url", ",", "description", ":", "snippet", ".", "description", ",", "url", ":", "`", "${", "baseUrl", "}", "${", "id", "}", "`", ",", "embedUrl", ":", "`", "${", "baseUrl", "}", "${", "id", "}", "`", "}", "}" ]
Decorate data into a simpler structure @param data @returns {{title, thumbnail, rawDescription, views: *, likes: *, description: *, url: string, id, host: string}}
[ "Decorate", "data", "into", "a", "simpler", "structure" ]
539e51a09ad891cdc496b594d9ea7cd678e1cf30
https://github.com/ritz078/embed-js/blob/539e51a09ad891cdc496b594d9ea7cd678e1cf30/packages/embed-plugin-youtube/src/index.js#L18-L26
18,179
ritz078/embed-js
packages/embed-plugin-youtube/src/index.js
fetchDetails
async function fetchDetails(id, fetch, gAuthKey) { try { const res = await fetch( `https://www.googleapis.com/youtube/v3/videos?id=${id}&key=${gAuthKey}&part=snippet,statistics` ) const data = await res.json() return data.items[0] } catch (e) { console.log(e) return {} } }
javascript
async function fetchDetails(id, fetch, gAuthKey) { try { const res = await fetch( `https://www.googleapis.com/youtube/v3/videos?id=${id}&key=${gAuthKey}&part=snippet,statistics` ) const data = await res.json() return data.items[0] } catch (e) { console.log(e) return {} } }
[ "async", "function", "fetchDetails", "(", "id", ",", "fetch", ",", "gAuthKey", ")", "{", "try", "{", "const", "res", "=", "await", "fetch", "(", "`", "${", "id", "}", "${", "gAuthKey", "}", "`", ")", "const", "data", "=", "await", "res", ".", "json", "(", ")", "return", "data", ".", "items", "[", "0", "]", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "e", ")", "return", "{", "}", "}", "}" ]
Fetch details of a particular youtube video @param id @param gAuthKey @returns {Promise.<*>}
[ "Fetch", "details", "of", "a", "particular", "youtube", "video" ]
539e51a09ad891cdc496b594d9ea7cd678e1cf30
https://github.com/ritz078/embed-js/blob/539e51a09ad891cdc496b594d9ea7cd678e1cf30/packages/embed-plugin-youtube/src/index.js#L34-L45
18,180
ritz078/embed-js
packages/embed-plugin-youtube/src/index.js
onLoad
function onLoad({ input }, { clickClass, onVideoShow, height }) { if (!isDom(input)) { throw new Error("input should be a DOM Element.") } let classes = document.getElementsByClassName(clickClass) for (let i = 0; i < classes.length; i++) { classes[i].onclick = function() { let url = this.getAttribute("data-url") onVideoShow(url) url += "?autoplay=1" this.parentNode.innerHTML = withoutDetailsTemplate(url, height, id) } } }
javascript
function onLoad({ input }, { clickClass, onVideoShow, height }) { if (!isDom(input)) { throw new Error("input should be a DOM Element.") } let classes = document.getElementsByClassName(clickClass) for (let i = 0; i < classes.length; i++) { classes[i].onclick = function() { let url = this.getAttribute("data-url") onVideoShow(url) url += "?autoplay=1" this.parentNode.innerHTML = withoutDetailsTemplate(url, height, id) } } }
[ "function", "onLoad", "(", "{", "input", "}", ",", "{", "clickClass", ",", "onVideoShow", ",", "height", "}", ")", "{", "if", "(", "!", "isDom", "(", "input", ")", ")", "{", "throw", "new", "Error", "(", "\"input should be a DOM Element.\"", ")", "}", "let", "classes", "=", "document", ".", "getElementsByClassName", "(", "clickClass", ")", "for", "(", "let", "i", "=", "0", ";", "i", "<", "classes", ".", "length", ";", "i", "++", ")", "{", "classes", "[", "i", "]", ".", "onclick", "=", "function", "(", ")", "{", "let", "url", "=", "this", ".", "getAttribute", "(", "\"data-url\"", ")", "onVideoShow", "(", "url", ")", "url", "+=", "\"?autoplay=1\"", "this", ".", "parentNode", ".", "innerHTML", "=", "withoutDetailsTemplate", "(", "url", ",", "height", ",", "id", ")", "}", "}", "}" ]
Function executed when a content is rendered on the client site. @param input @param clickClass @param onVideoShow @param height
[ "Function", "executed", "when", "a", "content", "is", "rendered", "on", "the", "client", "site", "." ]
539e51a09ad891cdc496b594d9ea7cd678e1cf30
https://github.com/ritz078/embed-js/blob/539e51a09ad891cdc496b594d9ea7cd678e1cf30/packages/embed-plugin-youtube/src/index.js#L54-L67
18,181
ritz078/embed-js
packages/embed-plugin-twitter/src/index.js
_process
async function _process( args, { fetch }, { _omitScript, maxWidth, hideMedia, hideThread, align, lang, theme, linkColor, widgetType } ) { const params = { url: args[0], omitScript: _omitScript, maxWidth, hideMedia, hideThread, align, lang, theme, linkColor, widgetType } try { const apiUrl = `https://api.twitter.com/1/statuses/oembed.json?${getQuery( params )}` const res = await (isBrowser ? jsonp : fetch)(apiUrl) return await res.json() } catch (e) { return { html: "" } } }
javascript
async function _process( args, { fetch }, { _omitScript, maxWidth, hideMedia, hideThread, align, lang, theme, linkColor, widgetType } ) { const params = { url: args[0], omitScript: _omitScript, maxWidth, hideMedia, hideThread, align, lang, theme, linkColor, widgetType } try { const apiUrl = `https://api.twitter.com/1/statuses/oembed.json?${getQuery( params )}` const res = await (isBrowser ? jsonp : fetch)(apiUrl) return await res.json() } catch (e) { return { html: "" } } }
[ "async", "function", "_process", "(", "args", ",", "{", "fetch", "}", ",", "{", "_omitScript", ",", "maxWidth", ",", "hideMedia", ",", "hideThread", ",", "align", ",", "lang", ",", "theme", ",", "linkColor", ",", "widgetType", "}", ")", "{", "const", "params", "=", "{", "url", ":", "args", "[", "0", "]", ",", "omitScript", ":", "_omitScript", ",", "maxWidth", ",", "hideMedia", ",", "hideThread", ",", "align", ",", "lang", ",", "theme", ",", "linkColor", ",", "widgetType", "}", "try", "{", "const", "apiUrl", "=", "`", "${", "getQuery", "(", "params", ")", "}", "`", "const", "res", "=", "await", "(", "isBrowser", "?", "jsonp", ":", "fetch", ")", "(", "apiUrl", ")", "return", "await", "res", ".", "json", "(", ")", "}", "catch", "(", "e", ")", "{", "return", "{", "html", ":", "\"\"", "}", "}", "}" ]
Fetch the html content from the API @param url @param args @param omitScript @param maxWidth @param hideMedia @param hideThread @param align @param lang @param theme @param linkColor @param widgetType @returns {Promise.<*>}
[ "Fetch", "the", "html", "content", "from", "the", "API" ]
539e51a09ad891cdc496b594d9ea7cd678e1cf30
https://github.com/ritz078/embed-js/blob/539e51a09ad891cdc496b594d9ea7cd678e1cf30/packages/embed-plugin-twitter/src/index.js#L25-L63
18,182
ritz078/embed-js
packages/embed-plugin-utilities/src/insert.js
isMatchPresent
function isMatchPresent(regex, text, test = false) { return test ? regex.test(text) : text.match(regex) }
javascript
function isMatchPresent(regex, text, test = false) { return test ? regex.test(text) : text.match(regex) }
[ "function", "isMatchPresent", "(", "regex", ",", "text", ",", "test", "=", "false", ")", "{", "return", "test", "?", "regex", ".", "test", "(", "text", ")", ":", "text", ".", "match", "(", "regex", ")", "}" ]
Returns the matched regex data or whether the text has any matching string @param regex Regex of the matching pattern @param text String which has to be searched @param test Return boolean or matching array @returns {*} Boolean|Array
[ "Returns", "the", "matched", "regex", "data", "or", "whether", "the", "text", "has", "any", "matching", "string" ]
539e51a09ad891cdc496b594d9ea7cd678e1cf30
https://github.com/ritz078/embed-js/blob/539e51a09ad891cdc496b594d9ea7cd678e1cf30/packages/embed-plugin-utilities/src/insert.js#L17-L19
18,183
ritz078/embed-js
packages/embed-plugin-utilities/src/insert.js
isAnchorTagApplied
function isAnchorTagApplied({ result, plugins = [] }, { regex }) { return ( getAnchorRegex(regex).test(result) || plugins.filter(plugin => plugin.id === "url").length ) }
javascript
function isAnchorTagApplied({ result, plugins = [] }, { regex }) { return ( getAnchorRegex(regex).test(result) || plugins.filter(plugin => plugin.id === "url").length ) }
[ "function", "isAnchorTagApplied", "(", "{", "result", ",", "plugins", "=", "[", "]", "}", ",", "{", "regex", "}", ")", "{", "return", "(", "getAnchorRegex", "(", "regex", ")", ".", "test", "(", "result", ")", "||", "plugins", ".", "filter", "(", "plugin", "=>", "plugin", ".", "id", "===", "\"url\"", ")", ".", "length", ")", "}" ]
Tells wheteher the matching string is present inside an anchor tag @param text @returns {*} Boolean @param regex
[ "Tells", "wheteher", "the", "matching", "string", "is", "present", "inside", "an", "anchor", "tag" ]
539e51a09ad891cdc496b594d9ea7cd678e1cf30
https://github.com/ritz078/embed-js/blob/539e51a09ad891cdc496b594d9ea7cd678e1cf30/packages/embed-plugin-utilities/src/insert.js#L27-L32
18,184
ritz078/embed-js
packages/embed-plugin-utilities/src/insert.js
saveEmbedData
async function saveEmbedData(opts, pluginOptions) { const { regex } = pluginOptions let options = extend({}, opts) if (isAnchorTagApplied(options, { regex })) { await stringReplaceAsync( options.result, anchorRegex, async (match, url, index) => { if (!isMatchPresent(regex, match, true)) return match saveServiceName(options, pluginOptions, match) options = await pushEmbedContent(url, options, pluginOptions, index) return match } ) } else { options = pushEmbedContent(options.result, options, pluginOptions) } return options }
javascript
async function saveEmbedData(opts, pluginOptions) { const { regex } = pluginOptions let options = extend({}, opts) if (isAnchorTagApplied(options, { regex })) { await stringReplaceAsync( options.result, anchorRegex, async (match, url, index) => { if (!isMatchPresent(regex, match, true)) return match saveServiceName(options, pluginOptions, match) options = await pushEmbedContent(url, options, pluginOptions, index) return match } ) } else { options = pushEmbedContent(options.result, options, pluginOptions) } return options }
[ "async", "function", "saveEmbedData", "(", "opts", ",", "pluginOptions", ")", "{", "const", "{", "regex", "}", "=", "pluginOptions", "let", "options", "=", "extend", "(", "{", "}", ",", "opts", ")", "if", "(", "isAnchorTagApplied", "(", "options", ",", "{", "regex", "}", ")", ")", "{", "await", "stringReplaceAsync", "(", "options", ".", "result", ",", "anchorRegex", ",", "async", "(", "match", ",", "url", ",", "index", ")", "=>", "{", "if", "(", "!", "isMatchPresent", "(", "regex", ",", "match", ",", "true", ")", ")", "return", "match", "saveServiceName", "(", "options", ",", "pluginOptions", ",", "match", ")", "options", "=", "await", "pushEmbedContent", "(", "url", ",", "options", ",", "pluginOptions", ",", "index", ")", "return", "match", "}", ")", "}", "else", "{", "options", "=", "pushEmbedContent", "(", "options", ".", "result", ",", "options", ",", "pluginOptions", ")", "}", "return", "options", "}" ]
Save the embed code into an array that can be added later to the end of original string @param opts @param pluginOptions
[ "Save", "the", "embed", "code", "into", "an", "array", "that", "can", "be", "added", "later", "to", "the", "end", "of", "original", "string" ]
539e51a09ad891cdc496b594d9ea7cd678e1cf30
https://github.com/ritz078/embed-js/blob/539e51a09ad891cdc496b594d9ea7cd678e1cf30/packages/embed-plugin-utilities/src/insert.js#L57-L77
18,185
jsantell/dancer.js
dancer.js
function ( freq, endFreq ) { var sum = 0; if ( endFreq !== undefined ) { for ( var i = freq; i <= endFreq; i++ ) { sum += this.getSpectrum()[ i ]; } return sum / ( endFreq - freq + 1 ); } else { return this.getSpectrum()[ freq ]; } }
javascript
function ( freq, endFreq ) { var sum = 0; if ( endFreq !== undefined ) { for ( var i = freq; i <= endFreq; i++ ) { sum += this.getSpectrum()[ i ]; } return sum / ( endFreq - freq + 1 ); } else { return this.getSpectrum()[ freq ]; } }
[ "function", "(", "freq", ",", "endFreq", ")", "{", "var", "sum", "=", "0", ";", "if", "(", "endFreq", "!==", "undefined", ")", "{", "for", "(", "var", "i", "=", "freq", ";", "i", "<=", "endFreq", ";", "i", "++", ")", "{", "sum", "+=", "this", ".", "getSpectrum", "(", ")", "[", "i", "]", ";", "}", "return", "sum", "/", "(", "endFreq", "-", "freq", "+", "1", ")", ";", "}", "else", "{", "return", "this", ".", "getSpectrum", "(", ")", "[", "freq", "]", ";", "}", "}" ]
Returns the magnitude of a frequency or average over a range of frequencies
[ "Returns", "the", "magnitude", "of", "a", "frequency", "or", "average", "over", "a", "range", "of", "frequencies" ]
df0e7c0f53605be6a806a61d3a0454a752068138
https://github.com/jsantell/dancer.js/blob/df0e7c0f53605be6a806a61d3a0454a752068138/dancer.js#L106-L116
18,186
jsantell/dancer.js
dancer.js
function ( source ) { var _this = this; this.path = source ? source.src : this.path; this.isLoaded = false; this.progress = 0; !window.soundManager && !smLoading && loadSM.call( this ); if ( window.soundManager ) { this.audio = soundManager.createSound({ id : 'dancer' + Math.random() + '', url : this.path, stream : true, autoPlay : false, autoLoad : true, whileplaying : function () { _this.update(); }, whileloading : function () { _this.progress = this.bytesLoaded / this.bytesTotal; }, onload : function () { _this.fft = new FFT( SAMPLE_SIZE, SAMPLE_RATE ); _this.signal = new Float32Array( SAMPLE_SIZE ); _this.waveform = new Float32Array( SAMPLE_SIZE ); _this.isLoaded = true; _this.progress = 1; _this.dancer.trigger( 'loaded' ); } }); this.dancer.audio = this.audio; } // Returns audio if SM already loaded -- otherwise, // sets dancer instance's audio property after load return this.audio; }
javascript
function ( source ) { var _this = this; this.path = source ? source.src : this.path; this.isLoaded = false; this.progress = 0; !window.soundManager && !smLoading && loadSM.call( this ); if ( window.soundManager ) { this.audio = soundManager.createSound({ id : 'dancer' + Math.random() + '', url : this.path, stream : true, autoPlay : false, autoLoad : true, whileplaying : function () { _this.update(); }, whileloading : function () { _this.progress = this.bytesLoaded / this.bytesTotal; }, onload : function () { _this.fft = new FFT( SAMPLE_SIZE, SAMPLE_RATE ); _this.signal = new Float32Array( SAMPLE_SIZE ); _this.waveform = new Float32Array( SAMPLE_SIZE ); _this.isLoaded = true; _this.progress = 1; _this.dancer.trigger( 'loaded' ); } }); this.dancer.audio = this.audio; } // Returns audio if SM already loaded -- otherwise, // sets dancer instance's audio property after load return this.audio; }
[ "function", "(", "source", ")", "{", "var", "_this", "=", "this", ";", "this", ".", "path", "=", "source", "?", "source", ".", "src", ":", "this", ".", "path", ";", "this", ".", "isLoaded", "=", "false", ";", "this", ".", "progress", "=", "0", ";", "!", "window", ".", "soundManager", "&&", "!", "smLoading", "&&", "loadSM", ".", "call", "(", "this", ")", ";", "if", "(", "window", ".", "soundManager", ")", "{", "this", ".", "audio", "=", "soundManager", ".", "createSound", "(", "{", "id", ":", "'dancer'", "+", "Math", ".", "random", "(", ")", "+", "''", ",", "url", ":", "this", ".", "path", ",", "stream", ":", "true", ",", "autoPlay", ":", "false", ",", "autoLoad", ":", "true", ",", "whileplaying", ":", "function", "(", ")", "{", "_this", ".", "update", "(", ")", ";", "}", ",", "whileloading", ":", "function", "(", ")", "{", "_this", ".", "progress", "=", "this", ".", "bytesLoaded", "/", "this", ".", "bytesTotal", ";", "}", ",", "onload", ":", "function", "(", ")", "{", "_this", ".", "fft", "=", "new", "FFT", "(", "SAMPLE_SIZE", ",", "SAMPLE_RATE", ")", ";", "_this", ".", "signal", "=", "new", "Float32Array", "(", "SAMPLE_SIZE", ")", ";", "_this", ".", "waveform", "=", "new", "Float32Array", "(", "SAMPLE_SIZE", ")", ";", "_this", ".", "isLoaded", "=", "true", ";", "_this", ".", "progress", "=", "1", ";", "_this", ".", "dancer", ".", "trigger", "(", "'loaded'", ")", ";", "}", "}", ")", ";", "this", ".", "dancer", ".", "audio", "=", "this", ".", "audio", ";", "}", "// Returns audio if SM already loaded -- otherwise,", "// sets dancer instance's audio property after load", "return", "this", ".", "audio", ";", "}" ]
`source` can be either an Audio element, if supported, or an object either way, the path is stored in the `src` property
[ "source", "can", "be", "either", "an", "Audio", "element", "if", "supported", "or", "an", "object", "either", "way", "the", "path", "is", "stored", "in", "the", "src", "property" ]
df0e7c0f53605be6a806a61d3a0454a752068138
https://github.com/jsantell/dancer.js/blob/df0e7c0f53605be6a806a61d3a0454a752068138/dancer.js#L615-L652
18,187
jsantell/dancer.js
dancer.js
FFT
function FFT(bufferSize, sampleRate) { FourierTransform.call(this, bufferSize, sampleRate); this.reverseTable = new Uint32Array(bufferSize); var limit = 1; var bit = bufferSize >> 1; var i; while (limit < bufferSize) { for (i = 0; i < limit; i++) { this.reverseTable[i + limit] = this.reverseTable[i] + bit; } limit = limit << 1; bit = bit >> 1; } this.sinTable = new Float32Array(bufferSize); this.cosTable = new Float32Array(bufferSize); for (i = 0; i < bufferSize; i++) { this.sinTable[i] = Math.sin(-Math.PI/i); this.cosTable[i] = Math.cos(-Math.PI/i); } }
javascript
function FFT(bufferSize, sampleRate) { FourierTransform.call(this, bufferSize, sampleRate); this.reverseTable = new Uint32Array(bufferSize); var limit = 1; var bit = bufferSize >> 1; var i; while (limit < bufferSize) { for (i = 0; i < limit; i++) { this.reverseTable[i + limit] = this.reverseTable[i] + bit; } limit = limit << 1; bit = bit >> 1; } this.sinTable = new Float32Array(bufferSize); this.cosTable = new Float32Array(bufferSize); for (i = 0; i < bufferSize; i++) { this.sinTable[i] = Math.sin(-Math.PI/i); this.cosTable[i] = Math.cos(-Math.PI/i); } }
[ "function", "FFT", "(", "bufferSize", ",", "sampleRate", ")", "{", "FourierTransform", ".", "call", "(", "this", ",", "bufferSize", ",", "sampleRate", ")", ";", "this", ".", "reverseTable", "=", "new", "Uint32Array", "(", "bufferSize", ")", ";", "var", "limit", "=", "1", ";", "var", "bit", "=", "bufferSize", ">>", "1", ";", "var", "i", ";", "while", "(", "limit", "<", "bufferSize", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "limit", ";", "i", "++", ")", "{", "this", ".", "reverseTable", "[", "i", "+", "limit", "]", "=", "this", ".", "reverseTable", "[", "i", "]", "+", "bit", ";", "}", "limit", "=", "limit", "<<", "1", ";", "bit", "=", "bit", ">>", "1", ";", "}", "this", ".", "sinTable", "=", "new", "Float32Array", "(", "bufferSize", ")", ";", "this", ".", "cosTable", "=", "new", "Float32Array", "(", "bufferSize", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "bufferSize", ";", "i", "++", ")", "{", "this", ".", "sinTable", "[", "i", "]", "=", "Math", ".", "sin", "(", "-", "Math", ".", "PI", "/", "i", ")", ";", "this", ".", "cosTable", "[", "i", "]", "=", "Math", ".", "cos", "(", "-", "Math", ".", "PI", "/", "i", ")", ";", "}", "}" ]
FFT is a class for calculating the Discrete Fourier Transform of a signal with the Fast Fourier Transform algorithm. @param {Number} bufferSize The size of the sample buffer to be computed. Must be power of 2 @param {Number} sampleRate The sampleRate of the buffer (eg. 44100) @constructor
[ "FFT", "is", "a", "class", "for", "calculating", "the", "Discrete", "Fourier", "Transform", "of", "a", "signal", "with", "the", "Fast", "Fourier", "Transform", "algorithm", "." ]
df0e7c0f53605be6a806a61d3a0454a752068138
https://github.com/jsantell/dancer.js/blob/df0e7c0f53605be6a806a61d3a0454a752068138/dancer.js#L811-L837
18,188
jsantell/dancer.js
dancer.js
function(name){ var obj = -1; try{ obj = new ActiveXObject(name); }catch(err){ obj = {activeXError:true}; } return obj; }
javascript
function(name){ var obj = -1; try{ obj = new ActiveXObject(name); }catch(err){ obj = {activeXError:true}; } return obj; }
[ "function", "(", "name", ")", "{", "var", "obj", "=", "-", "1", ";", "try", "{", "obj", "=", "new", "ActiveXObject", "(", "name", ")", ";", "}", "catch", "(", "err", ")", "{", "obj", "=", "{", "activeXError", ":", "true", "}", ";", "}", "return", "obj", ";", "}" ]
Try and retrieve an ActiveX object having a specified name. @param {String} name The ActiveX object name lookup. @return One of ActiveX object or a simple object having an attribute of activeXError with a value of true. @type Object
[ "Try", "and", "retrieve", "an", "ActiveX", "object", "having", "a", "specified", "name", "." ]
df0e7c0f53605be6a806a61d3a0454a752068138
https://github.com/jsantell/dancer.js/blob/df0e7c0f53605be6a806a61d3a0454a752068138/dancer.js#L972-L980
18,189
jsantell/dancer.js
dancer.js
function(str){ var descParts = str.split(/ +/); var majorMinor = descParts[2].split(/\./); var revisionStr = descParts[3]; return { "raw":str, "major":parseInt(majorMinor[0], 10), "minor":parseInt(majorMinor[1], 10), "revisionStr":revisionStr, "revision":parseRevisionStrToInt(revisionStr) }; }
javascript
function(str){ var descParts = str.split(/ +/); var majorMinor = descParts[2].split(/\./); var revisionStr = descParts[3]; return { "raw":str, "major":parseInt(majorMinor[0], 10), "minor":parseInt(majorMinor[1], 10), "revisionStr":revisionStr, "revision":parseRevisionStrToInt(revisionStr) }; }
[ "function", "(", "str", ")", "{", "var", "descParts", "=", "str", ".", "split", "(", "/", " +", "/", ")", ";", "var", "majorMinor", "=", "descParts", "[", "2", "]", ".", "split", "(", "/", "\\.", "/", ")", ";", "var", "revisionStr", "=", "descParts", "[", "3", "]", ";", "return", "{", "\"raw\"", ":", "str", ",", "\"major\"", ":", "parseInt", "(", "majorMinor", "[", "0", "]", ",", "10", ")", ",", "\"minor\"", ":", "parseInt", "(", "majorMinor", "[", "1", "]", ",", "10", ")", ",", "\"revisionStr\"", ":", "revisionStr", ",", "\"revision\"", ":", "parseRevisionStrToInt", "(", "revisionStr", ")", "}", ";", "}" ]
Parse a standard enabledPlugin.description into an object. @param {String} str The enabledPlugin.description value. @return An object having raw, major, minor, revision and revisionStr attributes. @type Object
[ "Parse", "a", "standard", "enabledPlugin", ".", "description", "into", "an", "object", "." ]
df0e7c0f53605be6a806a61d3a0454a752068138
https://github.com/jsantell/dancer.js/blob/df0e7c0f53605be6a806a61d3a0454a752068138/dancer.js#L1005-L1016
18,190
jsantell/dancer.js
examples/lib/Three.debug.js
createParticleBuffers
function createParticleBuffers ( geometry ) { geometry.__webglVertexBuffer = _gl.createBuffer(); geometry.__webglColorBuffer = _gl.createBuffer(); _this.info.geometries ++; }
javascript
function createParticleBuffers ( geometry ) { geometry.__webglVertexBuffer = _gl.createBuffer(); geometry.__webglColorBuffer = _gl.createBuffer(); _this.info.geometries ++; }
[ "function", "createParticleBuffers", "(", "geometry", ")", "{", "geometry", ".", "__webglVertexBuffer", "=", "_gl", ".", "createBuffer", "(", ")", ";", "geometry", ".", "__webglColorBuffer", "=", "_gl", ".", "createBuffer", "(", ")", ";", "_this", ".", "info", ".", "geometries", "++", ";", "}" ]
Internal functions Buffer allocation
[ "Internal", "functions", "Buffer", "allocation" ]
df0e7c0f53605be6a806a61d3a0454a752068138
https://github.com/jsantell/dancer.js/blob/df0e7c0f53605be6a806a61d3a0454a752068138/examples/lib/Three.debug.js#L13048-L13055
18,191
jsantell/dancer.js
examples/lib/Three.debug.js
function ( geometry, n ) { var face, i, faces = geometry.faces, vertices = geometry.vertices, il = faces.length, totalArea = 0, cumulativeAreas = [], vA, vB, vC, vD; // precompute face areas for ( i = 0; i < il; i ++ ) { face = faces[ i ]; if ( face instanceof THREE.Face3 ) { vA = vertices[ face.a ]; vB = vertices[ face.b ]; vC = vertices[ face.c ]; face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC ); } else if ( face instanceof THREE.Face4 ) { vA = vertices[ face.a ]; vB = vertices[ face.b ]; vC = vertices[ face.c ]; vD = vertices[ face.d ]; face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ); face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD ); face._area = face._area1 + face._area2; } totalArea += face._area; cumulativeAreas[ i ] = totalArea; } // binary search cumulative areas array function binarySearchIndices( value ) { function binarySearch( start, end ) { // return closest larger index // if exact number is not found if ( end < start ) return start; var mid = start + Math.floor( ( end - start ) / 2 ); if ( cumulativeAreas[ mid ] > value ) { return binarySearch( start, mid - 1 ); } else if ( cumulativeAreas[ mid ] < value ) { return binarySearch( mid + 1, end ); } else { return mid; } } var result = binarySearch( 0, cumulativeAreas.length - 1 ) return result; } // pick random face weighted by face area var r, index, result = []; var stats = {}; for ( i = 0; i < n; i ++ ) { r = THREE.GeometryUtils.random() * totalArea; index = binarySearchIndices( r ); result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true ); if ( ! stats[ index ] ) { stats[ index ] = 1; } else { stats[ index ] += 1; } } return result; }
javascript
function ( geometry, n ) { var face, i, faces = geometry.faces, vertices = geometry.vertices, il = faces.length, totalArea = 0, cumulativeAreas = [], vA, vB, vC, vD; // precompute face areas for ( i = 0; i < il; i ++ ) { face = faces[ i ]; if ( face instanceof THREE.Face3 ) { vA = vertices[ face.a ]; vB = vertices[ face.b ]; vC = vertices[ face.c ]; face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC ); } else if ( face instanceof THREE.Face4 ) { vA = vertices[ face.a ]; vB = vertices[ face.b ]; vC = vertices[ face.c ]; vD = vertices[ face.d ]; face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ); face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD ); face._area = face._area1 + face._area2; } totalArea += face._area; cumulativeAreas[ i ] = totalArea; } // binary search cumulative areas array function binarySearchIndices( value ) { function binarySearch( start, end ) { // return closest larger index // if exact number is not found if ( end < start ) return start; var mid = start + Math.floor( ( end - start ) / 2 ); if ( cumulativeAreas[ mid ] > value ) { return binarySearch( start, mid - 1 ); } else if ( cumulativeAreas[ mid ] < value ) { return binarySearch( mid + 1, end ); } else { return mid; } } var result = binarySearch( 0, cumulativeAreas.length - 1 ) return result; } // pick random face weighted by face area var r, index, result = []; var stats = {}; for ( i = 0; i < n; i ++ ) { r = THREE.GeometryUtils.random() * totalArea; index = binarySearchIndices( r ); result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true ); if ( ! stats[ index ] ) { stats[ index ] = 1; } else { stats[ index ] += 1; } } return result; }
[ "function", "(", "geometry", ",", "n", ")", "{", "var", "face", ",", "i", ",", "faces", "=", "geometry", ".", "faces", ",", "vertices", "=", "geometry", ".", "vertices", ",", "il", "=", "faces", ".", "length", ",", "totalArea", "=", "0", ",", "cumulativeAreas", "=", "[", "]", ",", "vA", ",", "vB", ",", "vC", ",", "vD", ";", "// precompute face areas", "for", "(", "i", "=", "0", ";", "i", "<", "il", ";", "i", "++", ")", "{", "face", "=", "faces", "[", "i", "]", ";", "if", "(", "face", "instanceof", "THREE", ".", "Face3", ")", "{", "vA", "=", "vertices", "[", "face", ".", "a", "]", ";", "vB", "=", "vertices", "[", "face", ".", "b", "]", ";", "vC", "=", "vertices", "[", "face", ".", "c", "]", ";", "face", ".", "_area", "=", "THREE", ".", "GeometryUtils", ".", "triangleArea", "(", "vA", ",", "vB", ",", "vC", ")", ";", "}", "else", "if", "(", "face", "instanceof", "THREE", ".", "Face4", ")", "{", "vA", "=", "vertices", "[", "face", ".", "a", "]", ";", "vB", "=", "vertices", "[", "face", ".", "b", "]", ";", "vC", "=", "vertices", "[", "face", ".", "c", "]", ";", "vD", "=", "vertices", "[", "face", ".", "d", "]", ";", "face", ".", "_area1", "=", "THREE", ".", "GeometryUtils", ".", "triangleArea", "(", "vA", ",", "vB", ",", "vD", ")", ";", "face", ".", "_area2", "=", "THREE", ".", "GeometryUtils", ".", "triangleArea", "(", "vB", ",", "vC", ",", "vD", ")", ";", "face", ".", "_area", "=", "face", ".", "_area1", "+", "face", ".", "_area2", ";", "}", "totalArea", "+=", "face", ".", "_area", ";", "cumulativeAreas", "[", "i", "]", "=", "totalArea", ";", "}", "// binary search cumulative areas array", "function", "binarySearchIndices", "(", "value", ")", "{", "function", "binarySearch", "(", "start", ",", "end", ")", "{", "// return closest larger index", "// if exact number is not found", "if", "(", "end", "<", "start", ")", "return", "start", ";", "var", "mid", "=", "start", "+", "Math", ".", "floor", "(", "(", "end", "-", "start", ")", "/", "2", ")", ";", "if", "(", "cumulativeAreas", "[", "mid", "]", ">", "value", ")", "{", "return", "binarySearch", "(", "start", ",", "mid", "-", "1", ")", ";", "}", "else", "if", "(", "cumulativeAreas", "[", "mid", "]", "<", "value", ")", "{", "return", "binarySearch", "(", "mid", "+", "1", ",", "end", ")", ";", "}", "else", "{", "return", "mid", ";", "}", "}", "var", "result", "=", "binarySearch", "(", "0", ",", "cumulativeAreas", ".", "length", "-", "1", ")", "return", "result", ";", "}", "// pick random face weighted by face area", "var", "r", ",", "index", ",", "result", "=", "[", "]", ";", "var", "stats", "=", "{", "}", ";", "for", "(", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "r", "=", "THREE", ".", "GeometryUtils", ".", "random", "(", ")", "*", "totalArea", ";", "index", "=", "binarySearchIndices", "(", "r", ")", ";", "result", "[", "i", "]", "=", "THREE", ".", "GeometryUtils", ".", "randomPointInFace", "(", "faces", "[", "index", "]", ",", "geometry", ",", "true", ")", ";", "if", "(", "!", "stats", "[", "index", "]", ")", "{", "stats", "[", "index", "]", "=", "1", ";", "}", "else", "{", "stats", "[", "index", "]", "+=", "1", ";", "}", "}", "return", "result", ";", "}" ]
Get uniformly distributed random points in mesh - create array with cumulative sums of face areas - pick random number from 0 to total area - find corresponding place in area array by binary search - get random point in face
[ "Get", "uniformly", "distributed", "random", "points", "in", "mesh", "-", "create", "array", "with", "cumulative", "sums", "of", "face", "areas", "-", "pick", "random", "number", "from", "0", "to", "total", "area", "-", "find", "corresponding", "place", "in", "area", "array", "by", "binary", "search", "-", "get", "random", "point", "in", "face" ]
df0e7c0f53605be6a806a61d3a0454a752068138
https://github.com/jsantell/dancer.js/blob/df0e7c0f53605be6a806a61d3a0454a752068138/examples/lib/Three.debug.js#L19501-L19609
18,192
jsantell/dancer.js
examples/lib/Three.debug.js
function( geometry ) { var vertices = []; for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) { var n = vertices.length; var face = geometry.faces[ i ]; if ( face instanceof THREE.Face4 ) { var a = face.a; var b = face.b; var c = face.c; var d = face.d; var va = geometry.vertices[ a ]; var vb = geometry.vertices[ b ]; var vc = geometry.vertices[ c ]; var vd = geometry.vertices[ d ]; vertices.push( va.clone() ); vertices.push( vb.clone() ); vertices.push( vc.clone() ); vertices.push( vd.clone() ); face.a = n; face.b = n + 1; face.c = n + 2; face.d = n + 3; } else { var a = face.a; var b = face.b; var c = face.c; var va = geometry.vertices[ a ]; var vb = geometry.vertices[ b ]; var vc = geometry.vertices[ c ]; vertices.push( va.clone() ); vertices.push( vb.clone() ); vertices.push( vc.clone() ); face.a = n; face.b = n + 1; face.c = n + 2; } } geometry.vertices = vertices; delete geometry.__tmpVertices; }
javascript
function( geometry ) { var vertices = []; for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) { var n = vertices.length; var face = geometry.faces[ i ]; if ( face instanceof THREE.Face4 ) { var a = face.a; var b = face.b; var c = face.c; var d = face.d; var va = geometry.vertices[ a ]; var vb = geometry.vertices[ b ]; var vc = geometry.vertices[ c ]; var vd = geometry.vertices[ d ]; vertices.push( va.clone() ); vertices.push( vb.clone() ); vertices.push( vc.clone() ); vertices.push( vd.clone() ); face.a = n; face.b = n + 1; face.c = n + 2; face.d = n + 3; } else { var a = face.a; var b = face.b; var c = face.c; var va = geometry.vertices[ a ]; var vb = geometry.vertices[ b ]; var vc = geometry.vertices[ c ]; vertices.push( va.clone() ); vertices.push( vb.clone() ); vertices.push( vc.clone() ); face.a = n; face.b = n + 1; face.c = n + 2; } } geometry.vertices = vertices; delete geometry.__tmpVertices; }
[ "function", "(", "geometry", ")", "{", "var", "vertices", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "il", "=", "geometry", ".", "faces", ".", "length", ";", "i", "<", "il", ";", "i", "++", ")", "{", "var", "n", "=", "vertices", ".", "length", ";", "var", "face", "=", "geometry", ".", "faces", "[", "i", "]", ";", "if", "(", "face", "instanceof", "THREE", ".", "Face4", ")", "{", "var", "a", "=", "face", ".", "a", ";", "var", "b", "=", "face", ".", "b", ";", "var", "c", "=", "face", ".", "c", ";", "var", "d", "=", "face", ".", "d", ";", "var", "va", "=", "geometry", ".", "vertices", "[", "a", "]", ";", "var", "vb", "=", "geometry", ".", "vertices", "[", "b", "]", ";", "var", "vc", "=", "geometry", ".", "vertices", "[", "c", "]", ";", "var", "vd", "=", "geometry", ".", "vertices", "[", "d", "]", ";", "vertices", ".", "push", "(", "va", ".", "clone", "(", ")", ")", ";", "vertices", ".", "push", "(", "vb", ".", "clone", "(", ")", ")", ";", "vertices", ".", "push", "(", "vc", ".", "clone", "(", ")", ")", ";", "vertices", ".", "push", "(", "vd", ".", "clone", "(", ")", ")", ";", "face", ".", "a", "=", "n", ";", "face", ".", "b", "=", "n", "+", "1", ";", "face", ".", "c", "=", "n", "+", "2", ";", "face", ".", "d", "=", "n", "+", "3", ";", "}", "else", "{", "var", "a", "=", "face", ".", "a", ";", "var", "b", "=", "face", ".", "b", ";", "var", "c", "=", "face", ".", "c", ";", "var", "va", "=", "geometry", ".", "vertices", "[", "a", "]", ";", "var", "vb", "=", "geometry", ".", "vertices", "[", "b", "]", ";", "var", "vc", "=", "geometry", ".", "vertices", "[", "c", "]", ";", "vertices", ".", "push", "(", "va", ".", "clone", "(", ")", ")", ";", "vertices", ".", "push", "(", "vb", ".", "clone", "(", ")", ")", ";", "vertices", ".", "push", "(", "vc", ".", "clone", "(", ")", ")", ";", "face", ".", "a", "=", "n", ";", "face", ".", "b", "=", "n", "+", "1", ";", "face", ".", "c", "=", "n", "+", "2", ";", "}", "}", "geometry", ".", "vertices", "=", "vertices", ";", "delete", "geometry", ".", "__tmpVertices", ";", "}" ]
Make all faces use unique vertices so that each face can be separated from others
[ "Make", "all", "faces", "use", "unique", "vertices", "so", "that", "each", "face", "can", "be", "separated", "from", "others" ]
df0e7c0f53605be6a806a61d3a0454a752068138
https://github.com/jsantell/dancer.js/blob/df0e7c0f53605be6a806a61d3a0454a752068138/examples/lib/Three.debug.js#L19807-L19864
18,193
jsantell/dancer.js
examples/lib/Three.debug.js
function( ax, ay, bx, by, cx, cy, px, py ) { var aX, aY, bX, bY; var cX, cY, apx, apy; var bpx, bpy, cpx, cpy; var cCROSSap, bCROSScp, aCROSSbp; aX = cx - bx; aY = cy - by; bX = ax - cx; bY = ay - cy; cX = bx - ax; cY = by - ay; apx= px -ax; apy= py - ay; bpx= px - bx; bpy= py - by; cpx= px - cx; cpy= py - cy; aCROSSbp = aX*bpy - aY*bpx; cCROSSap = cX*apy - cY*apx; bCROSScp = bX*cpy - bY*cpx; return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ); }
javascript
function( ax, ay, bx, by, cx, cy, px, py ) { var aX, aY, bX, bY; var cX, cY, apx, apy; var bpx, bpy, cpx, cpy; var cCROSSap, bCROSScp, aCROSSbp; aX = cx - bx; aY = cy - by; bX = ax - cx; bY = ay - cy; cX = bx - ax; cY = by - ay; apx= px -ax; apy= py - ay; bpx= px - bx; bpy= py - by; cpx= px - cx; cpy= py - cy; aCROSSbp = aX*bpy - aY*bpx; cCROSSap = cX*apy - cY*apx; bCROSScp = bX*cpy - bY*cpx; return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ); }
[ "function", "(", "ax", ",", "ay", ",", "bx", ",", "by", ",", "cx", ",", "cy", ",", "px", ",", "py", ")", "{", "var", "aX", ",", "aY", ",", "bX", ",", "bY", ";", "var", "cX", ",", "cY", ",", "apx", ",", "apy", ";", "var", "bpx", ",", "bpy", ",", "cpx", ",", "cpy", ";", "var", "cCROSSap", ",", "bCROSScp", ",", "aCROSSbp", ";", "aX", "=", "cx", "-", "bx", ";", "aY", "=", "cy", "-", "by", ";", "bX", "=", "ax", "-", "cx", ";", "bY", "=", "ay", "-", "cy", ";", "cX", "=", "bx", "-", "ax", ";", "cY", "=", "by", "-", "ay", ";", "apx", "=", "px", "-", "ax", ";", "apy", "=", "py", "-", "ay", ";", "bpx", "=", "px", "-", "bx", ";", "bpy", "=", "py", "-", "by", ";", "cpx", "=", "px", "-", "cx", ";", "cpy", "=", "py", "-", "cy", ";", "aCROSSbp", "=", "aX", "*", "bpy", "-", "aY", "*", "bpx", ";", "cCROSSap", "=", "cX", "*", "apy", "-", "cY", "*", "apx", ";", "bCROSScp", "=", "bX", "*", "cpy", "-", "bY", "*", "cpx", ";", "return", "(", "(", "aCROSSbp", ">=", "0.0", ")", "&&", "(", "bCROSScp", ">=", "0.0", ")", "&&", "(", "cCROSSap", ">=", "0.0", ")", ")", ";", "}" ]
see if p is inside triangle abc
[ "see", "if", "p", "is", "inside", "triangle", "abc" ]
df0e7c0f53605be6a806a61d3a0454a752068138
https://github.com/jsantell/dancer.js/blob/df0e7c0f53605be6a806a61d3a0454a752068138/examples/lib/Three.debug.js#L28369-L28392
18,194
jsantell/dancer.js
examples/lib/Three.debug.js
addVertexEdgeMap
function addVertexEdgeMap(vertex, edge) { if (vertexEdgeMap[vertex]===undefined) { vertexEdgeMap[vertex] = []; } vertexEdgeMap[vertex].push(edge); }
javascript
function addVertexEdgeMap(vertex, edge) { if (vertexEdgeMap[vertex]===undefined) { vertexEdgeMap[vertex] = []; } vertexEdgeMap[vertex].push(edge); }
[ "function", "addVertexEdgeMap", "(", "vertex", ",", "edge", ")", "{", "if", "(", "vertexEdgeMap", "[", "vertex", "]", "===", "undefined", ")", "{", "vertexEdgeMap", "[", "vertex", "]", "=", "[", "]", ";", "}", "vertexEdgeMap", "[", "vertex", "]", ".", "push", "(", "edge", ")", ";", "}" ]
Gives faces connecting from each vertex
[ "Gives", "faces", "connecting", "from", "each", "vertex" ]
df0e7c0f53605be6a806a61d3a0454a752068138
https://github.com/jsantell/dancer.js/blob/df0e7c0f53605be6a806a61d3a0454a752068138/examples/lib/Three.debug.js#L29839-L29845
18,195
Yomguithereal/talisman
src/metrics/distance/levenshtein.js
levenshteinForStrings
function levenshteinForStrings(a, b) { if (a === b) return 0; const tmp = a; // Swapping the strings so that the shorter string is the first one. if (a.length > b.length) { a = b; b = tmp; } let la = a.length, lb = b.length; if (!la) return lb; if (!lb) return la; // Ignoring common suffix // NOTE: ~- is a fast - 1 operation, it does not work on big number though while (la > 0 && (a.charCodeAt(~-la) === b.charCodeAt(~-lb))) { la--; lb--; } if (!la) return lb; let start = 0; // Ignoring common prefix while (start < la && (a.charCodeAt(start) === b.charCodeAt(start))) start++; la -= start; lb -= start; if (!la) return lb; const v0 = VECTOR; let i = 0; while (i < lb) { CODES[i] = b.charCodeAt(start + i); v0[i] = ++i; } let current = 0, left, above, charA, j; // Starting the nested loops for (i = 0; i < la; i++) { left = i; current = i + 1; charA = a.charCodeAt(start + i); for (j = 0; j < lb; j++) { above = current; current = left; left = v0[j]; if (charA !== CODES[j]) { // Insertion if (left < current) current = left; // Deletion if (above < current) current = above; current++; } v0[j] = current; } } return current; }
javascript
function levenshteinForStrings(a, b) { if (a === b) return 0; const tmp = a; // Swapping the strings so that the shorter string is the first one. if (a.length > b.length) { a = b; b = tmp; } let la = a.length, lb = b.length; if (!la) return lb; if (!lb) return la; // Ignoring common suffix // NOTE: ~- is a fast - 1 operation, it does not work on big number though while (la > 0 && (a.charCodeAt(~-la) === b.charCodeAt(~-lb))) { la--; lb--; } if (!la) return lb; let start = 0; // Ignoring common prefix while (start < la && (a.charCodeAt(start) === b.charCodeAt(start))) start++; la -= start; lb -= start; if (!la) return lb; const v0 = VECTOR; let i = 0; while (i < lb) { CODES[i] = b.charCodeAt(start + i); v0[i] = ++i; } let current = 0, left, above, charA, j; // Starting the nested loops for (i = 0; i < la; i++) { left = i; current = i + 1; charA = a.charCodeAt(start + i); for (j = 0; j < lb; j++) { above = current; current = left; left = v0[j]; if (charA !== CODES[j]) { // Insertion if (left < current) current = left; // Deletion if (above < current) current = above; current++; } v0[j] = current; } } return current; }
[ "function", "levenshteinForStrings", "(", "a", ",", "b", ")", "{", "if", "(", "a", "===", "b", ")", "return", "0", ";", "const", "tmp", "=", "a", ";", "// Swapping the strings so that the shorter string is the first one.", "if", "(", "a", ".", "length", ">", "b", ".", "length", ")", "{", "a", "=", "b", ";", "b", "=", "tmp", ";", "}", "let", "la", "=", "a", ".", "length", ",", "lb", "=", "b", ".", "length", ";", "if", "(", "!", "la", ")", "return", "lb", ";", "if", "(", "!", "lb", ")", "return", "la", ";", "// Ignoring common suffix", "// NOTE: ~- is a fast - 1 operation, it does not work on big number though", "while", "(", "la", ">", "0", "&&", "(", "a", ".", "charCodeAt", "(", "~", "-", "la", ")", "===", "b", ".", "charCodeAt", "(", "~", "-", "lb", ")", ")", ")", "{", "la", "--", ";", "lb", "--", ";", "}", "if", "(", "!", "la", ")", "return", "lb", ";", "let", "start", "=", "0", ";", "// Ignoring common prefix", "while", "(", "start", "<", "la", "&&", "(", "a", ".", "charCodeAt", "(", "start", ")", "===", "b", ".", "charCodeAt", "(", "start", ")", ")", ")", "start", "++", ";", "la", "-=", "start", ";", "lb", "-=", "start", ";", "if", "(", "!", "la", ")", "return", "lb", ";", "const", "v0", "=", "VECTOR", ";", "let", "i", "=", "0", ";", "while", "(", "i", "<", "lb", ")", "{", "CODES", "[", "i", "]", "=", "b", ".", "charCodeAt", "(", "start", "+", "i", ")", ";", "v0", "[", "i", "]", "=", "++", "i", ";", "}", "let", "current", "=", "0", ",", "left", ",", "above", ",", "charA", ",", "j", ";", "// Starting the nested loops", "for", "(", "i", "=", "0", ";", "i", "<", "la", ";", "i", "++", ")", "{", "left", "=", "i", ";", "current", "=", "i", "+", "1", ";", "charA", "=", "a", ".", "charCodeAt", "(", "start", "+", "i", ")", ";", "for", "(", "j", "=", "0", ";", "j", "<", "lb", ";", "j", "++", ")", "{", "above", "=", "current", ";", "current", "=", "left", ";", "left", "=", "v0", "[", "j", "]", ";", "if", "(", "charA", "!==", "CODES", "[", "j", "]", ")", "{", "// Insertion", "if", "(", "left", "<", "current", ")", "current", "=", "left", ";", "// Deletion", "if", "(", "above", "<", "current", ")", "current", "=", "above", ";", "current", "++", ";", "}", "v0", "[", "j", "]", "=", "current", ";", "}", "}", "return", "current", ";", "}" ]
Function returning the Levenshtein distance between two sequences. This version only works on strings and leverage the `.charCodeAt` method to perform fast comparisons between 16 bits integers. @param {string} a - The first string to process. @param {string} b - The second string to process. @return {number} - The Levenshtein distance between a & b.
[ "Function", "returning", "the", "Levenshtein", "distance", "between", "two", "sequences", ".", "This", "version", "only", "works", "on", "strings", "and", "leverage", "the", ".", "charCodeAt", "method", "to", "perform", "fast", "comparisons", "between", "16", "bits", "integers", "." ]
51756b23cfd7e32c61f11c2f5a31f6396d15812a
https://github.com/Yomguithereal/talisman/blob/51756b23cfd7e32c61f11c2f5a31f6396d15812a/src/metrics/distance/levenshtein.js#L28-L116
18,196
Yomguithereal/talisman
src/phonetics/caverphone.js
caverphone
function caverphone(rules, name) { if (typeof name !== 'string') throw Error('talisman/phonetics/caverphone: the given name is not a string.'); // Preparing the name name = deburr(name) .toLowerCase() .replace(/[^a-z]/g, ''); // Applying the rules for (let i = 0, l = rules.length; i < l; i++) { const [match, replacement] = rules[i]; name = name.replace(match, replacement); } // Returning the padded code return pad(name); }
javascript
function caverphone(rules, name) { if (typeof name !== 'string') throw Error('talisman/phonetics/caverphone: the given name is not a string.'); // Preparing the name name = deburr(name) .toLowerCase() .replace(/[^a-z]/g, ''); // Applying the rules for (let i = 0, l = rules.length; i < l; i++) { const [match, replacement] = rules[i]; name = name.replace(match, replacement); } // Returning the padded code return pad(name); }
[ "function", "caverphone", "(", "rules", ",", "name", ")", "{", "if", "(", "typeof", "name", "!==", "'string'", ")", "throw", "Error", "(", "'talisman/phonetics/caverphone: the given name is not a string.'", ")", ";", "// Preparing the name", "name", "=", "deburr", "(", "name", ")", ".", "toLowerCase", "(", ")", ".", "replace", "(", "/", "[^a-z]", "/", "g", ",", "''", ")", ";", "// Applying the rules", "for", "(", "let", "i", "=", "0", ",", "l", "=", "rules", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "const", "[", "match", ",", "replacement", "]", "=", "rules", "[", "i", "]", ";", "name", "=", "name", ".", "replace", "(", "match", ",", "replacement", ")", ";", "}", "// Returning the padded code", "return", "pad", "(", "name", ")", ";", "}" ]
Function taking a single name and computing its caverphone code. @param {array} rules - The rules to use. @param {string} name - The name to process. @return {string} - The caverphone code. @throws {Error} The function expects the name to be a string.
[ "Function", "taking", "a", "single", "name", "and", "computing", "its", "caverphone", "code", "." ]
51756b23cfd7e32c61f11c2f5a31f6396d15812a
https://github.com/Yomguithereal/talisman/blob/51756b23cfd7e32c61f11c2f5a31f6396d15812a/src/phonetics/caverphone.js#L148-L166
18,197
Yomguithereal/talisman
src/metrics/distance/ratcliff-obershelp.js
indexOf
function indexOf(haystack, needle) { if (typeof haystack === 'string') return haystack.indexOf(needle); for (let i = 0, j = 0, l = haystack.length, n = needle.length; i < l; i++) { if (haystack[i] === needle[j]) { j++; if (j === n) return i - j + 1; } else { j = 0; } } return -1; }
javascript
function indexOf(haystack, needle) { if (typeof haystack === 'string') return haystack.indexOf(needle); for (let i = 0, j = 0, l = haystack.length, n = needle.length; i < l; i++) { if (haystack[i] === needle[j]) { j++; if (j === n) return i - j + 1; } else { j = 0; } } return -1; }
[ "function", "indexOf", "(", "haystack", ",", "needle", ")", "{", "if", "(", "typeof", "haystack", "===", "'string'", ")", "return", "haystack", ".", "indexOf", "(", "needle", ")", ";", "for", "(", "let", "i", "=", "0", ",", "j", "=", "0", ",", "l", "=", "haystack", ".", "length", ",", "n", "=", "needle", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "haystack", "[", "i", "]", "===", "needle", "[", "j", "]", ")", "{", "j", "++", ";", "if", "(", "j", "===", "n", ")", "return", "i", "-", "j", "+", "1", ";", "}", "else", "{", "j", "=", "0", ";", "}", "}", "return", "-", "1", ";", "}" ]
Abstract indexOf helper needed to find the given subsequence's starting index in the given sequence. Note that this function may seem naive because it misses cases when, for instance, the subsequence is not found but this is of no concern because we use the function in cases when it's not possible that the subsequence is not found. @param {mixed} haystack - Target sequence. @param {mixed} needle - Subsequence to find. @return {number} - The starting index.
[ "Abstract", "indexOf", "helper", "needed", "to", "find", "the", "given", "subsequence", "s", "starting", "index", "in", "the", "given", "sequence", ".", "Note", "that", "this", "function", "may", "seem", "naive", "because", "it", "misses", "cases", "when", "for", "instance", "the", "subsequence", "is", "not", "found", "but", "this", "is", "of", "no", "concern", "because", "we", "use", "the", "function", "in", "cases", "when", "it", "s", "not", "possible", "that", "the", "subsequence", "is", "not", "found", "." ]
51756b23cfd7e32c61f11c2f5a31f6396d15812a
https://github.com/Yomguithereal/talisman/blob/51756b23cfd7e32c61f11c2f5a31f6396d15812a/src/metrics/distance/ratcliff-obershelp.js#L34-L51
18,198
Yomguithereal/talisman
src/metrics/distance/ratcliff-obershelp.js
matches
function matches(a, b) { const stack = [a, b]; let m = 0; while (stack.length) { a = stack.pop(); b = stack.pop(); if (!a.length || !b.length) continue; const lcs = (new GeneralizedSuffixArray([a, b]).longestCommonSubsequence()), length = lcs.length; if (!length) continue; // Increasing matches m += length; // Add to the stack const aStart = indexOf(a, lcs), bStart = indexOf(b, lcs); stack.push(a.slice(0, aStart), b.slice(0, bStart)); stack.push(a.slice(aStart + length), b.slice(bStart + length)); } return m; }
javascript
function matches(a, b) { const stack = [a, b]; let m = 0; while (stack.length) { a = stack.pop(); b = stack.pop(); if (!a.length || !b.length) continue; const lcs = (new GeneralizedSuffixArray([a, b]).longestCommonSubsequence()), length = lcs.length; if (!length) continue; // Increasing matches m += length; // Add to the stack const aStart = indexOf(a, lcs), bStart = indexOf(b, lcs); stack.push(a.slice(0, aStart), b.slice(0, bStart)); stack.push(a.slice(aStart + length), b.slice(bStart + length)); } return m; }
[ "function", "matches", "(", "a", ",", "b", ")", "{", "const", "stack", "=", "[", "a", ",", "b", "]", ";", "let", "m", "=", "0", ";", "while", "(", "stack", ".", "length", ")", "{", "a", "=", "stack", ".", "pop", "(", ")", ";", "b", "=", "stack", ".", "pop", "(", ")", ";", "if", "(", "!", "a", ".", "length", "||", "!", "b", ".", "length", ")", "continue", ";", "const", "lcs", "=", "(", "new", "GeneralizedSuffixArray", "(", "[", "a", ",", "b", "]", ")", ".", "longestCommonSubsequence", "(", ")", ")", ",", "length", "=", "lcs", ".", "length", ";", "if", "(", "!", "length", ")", "continue", ";", "// Increasing matches", "m", "+=", "length", ";", "// Add to the stack", "const", "aStart", "=", "indexOf", "(", "a", ",", "lcs", ")", ",", "bStart", "=", "indexOf", "(", "b", ",", "lcs", ")", ";", "stack", ".", "push", "(", "a", ".", "slice", "(", "0", ",", "aStart", ")", ",", "b", ".", "slice", "(", "0", ",", "bStart", ")", ")", ";", "stack", ".", "push", "(", "a", ".", "slice", "(", "aStart", "+", "length", ")", ",", "b", ".", "slice", "(", "bStart", "+", "length", ")", ")", ";", "}", "return", "m", ";", "}" ]
Function returning the number of Ratcliff-Obershelp matches. This works by finding the LCS of both strings before recursively finding the LCS of the substrings both before and after the LCS in the initial strings and so on... @param {mixed} a - The first sequence to process. @param {mixed} b - The second sequence to process. @return {number} - The number of matches.
[ "Function", "returning", "the", "number", "of", "Ratcliff", "-", "Obershelp", "matches", ".", "This", "works", "by", "finding", "the", "LCS", "of", "both", "strings", "before", "recursively", "finding", "the", "LCS", "of", "the", "substrings", "both", "before", "and", "after", "the", "LCS", "in", "the", "initial", "strings", "and", "so", "on", "..." ]
51756b23cfd7e32c61f11c2f5a31f6396d15812a
https://github.com/Yomguithereal/talisman/blob/51756b23cfd7e32c61f11c2f5a31f6396d15812a/src/metrics/distance/ratcliff-obershelp.js#L63-L93
18,199
Yomguithereal/talisman
src/metrics/distance/jaro-winkler.js
customJaroWinkler
function customJaroWinkler(options, a, b) { options = options || {}; const { boostThreshold = 0.7, scalingFactor = 0.1 } = options; if (scalingFactor > 0.25) throw Error('talisman/metrics/distance/jaro-winkler: the scaling factor should not exceed 0.25.'); if (boostThreshold < 0 || boostThreshold > 1) throw Error('talisman/metrics/distance/jaro-winkler: the boost threshold should be comprised between 0 and 1.'); // Fast break if (a === b) return 1; // Computing Jaro-Winkler score const dj = jaro(a, b); if (dj < boostThreshold) return dj; const p = scalingFactor; let l = 0; const prefixLimit = Math.min(a.length, b.length, 4); // Common prefix (up to 4 characters) for (let i = 0; i < prefixLimit; i++) { if (a[i] === b[i]) l++; else break; } return dj + (l * p * (1 - dj)); }
javascript
function customJaroWinkler(options, a, b) { options = options || {}; const { boostThreshold = 0.7, scalingFactor = 0.1 } = options; if (scalingFactor > 0.25) throw Error('talisman/metrics/distance/jaro-winkler: the scaling factor should not exceed 0.25.'); if (boostThreshold < 0 || boostThreshold > 1) throw Error('talisman/metrics/distance/jaro-winkler: the boost threshold should be comprised between 0 and 1.'); // Fast break if (a === b) return 1; // Computing Jaro-Winkler score const dj = jaro(a, b); if (dj < boostThreshold) return dj; const p = scalingFactor; let l = 0; const prefixLimit = Math.min(a.length, b.length, 4); // Common prefix (up to 4 characters) for (let i = 0; i < prefixLimit; i++) { if (a[i] === b[i]) l++; else break; } return dj + (l * p * (1 - dj)); }
[ "function", "customJaroWinkler", "(", "options", ",", "a", ",", "b", ")", "{", "options", "=", "options", "||", "{", "}", ";", "const", "{", "boostThreshold", "=", "0.7", ",", "scalingFactor", "=", "0.1", "}", "=", "options", ";", "if", "(", "scalingFactor", ">", "0.25", ")", "throw", "Error", "(", "'talisman/metrics/distance/jaro-winkler: the scaling factor should not exceed 0.25.'", ")", ";", "if", "(", "boostThreshold", "<", "0", "||", "boostThreshold", ">", "1", ")", "throw", "Error", "(", "'talisman/metrics/distance/jaro-winkler: the boost threshold should be comprised between 0 and 1.'", ")", ";", "// Fast break", "if", "(", "a", "===", "b", ")", "return", "1", ";", "// Computing Jaro-Winkler score", "const", "dj", "=", "jaro", "(", "a", ",", "b", ")", ";", "if", "(", "dj", "<", "boostThreshold", ")", "return", "dj", ";", "const", "p", "=", "scalingFactor", ";", "let", "l", "=", "0", ";", "const", "prefixLimit", "=", "Math", ".", "min", "(", "a", ".", "length", ",", "b", ".", "length", ",", "4", ")", ";", "// Common prefix (up to 4 characters)", "for", "(", "let", "i", "=", "0", ";", "i", "<", "prefixLimit", ";", "i", "++", ")", "{", "if", "(", "a", "[", "i", "]", "===", "b", "[", "i", "]", ")", "l", "++", ";", "else", "break", ";", "}", "return", "dj", "+", "(", "l", "*", "p", "*", "(", "1", "-", "dj", ")", ")", ";", "}" ]
Function returning the Jaro-Winkler score between two sequences. @param {object} options - Custom options. @param {mixed} a - The first sequence. @param {mixed} b - The second sequence. @return {number} - The Jaro-Winkler score between a & b.
[ "Function", "returning", "the", "Jaro", "-", "Winkler", "score", "between", "two", "sequences", "." ]
51756b23cfd7e32c61f11c2f5a31f6396d15812a
https://github.com/Yomguithereal/talisman/blob/51756b23cfd7e32c61f11c2f5a31f6396d15812a/src/metrics/distance/jaro-winkler.js#L28-L67