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
37,200
mikolalysenko/clean-pslg
clean-pslg.js
boundEdges
function boundEdges (points, edges) { var bounds = new Array(edges.length) for (var i = 0; i < edges.length; ++i) { var e = edges[i] var a = points[e[0]] var b = points[e[1]] bounds[i] = [ nextafter(Math.min(a[0], b[0]), -Infinity), nextafter(Math.min(a[1], b[1]), -Infinity), nextafter(Math.max(a[0], b[0]), Infinity), nextafter(Math.max(a[1], b[1]), Infinity) ] } return bounds }
javascript
function boundEdges (points, edges) { var bounds = new Array(edges.length) for (var i = 0; i < edges.length; ++i) { var e = edges[i] var a = points[e[0]] var b = points[e[1]] bounds[i] = [ nextafter(Math.min(a[0], b[0]), -Infinity), nextafter(Math.min(a[1], b[1]), -Infinity), nextafter(Math.max(a[0], b[0]), Infinity), nextafter(Math.max(a[1], b[1]), Infinity) ] } return bounds }
[ "function", "boundEdges", "(", "points", ",", "edges", ")", "{", "var", "bounds", "=", "new", "Array", "(", "edges", ".", "length", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "edges", ".", "length", ";", "++", "i", ")", "{", "var", "e", "=", "edges", "[", "i", "]", "var", "a", "=", "points", "[", "e", "[", "0", "]", "]", "var", "b", "=", "points", "[", "e", "[", "1", "]", "]", "bounds", "[", "i", "]", "=", "[", "nextafter", "(", "Math", ".", "min", "(", "a", "[", "0", "]", ",", "b", "[", "0", "]", ")", ",", "-", "Infinity", ")", ",", "nextafter", "(", "Math", ".", "min", "(", "a", "[", "1", "]", ",", "b", "[", "1", "]", ")", ",", "-", "Infinity", ")", ",", "nextafter", "(", "Math", ".", "max", "(", "a", "[", "0", "]", ",", "b", "[", "0", "]", ")", ",", "Infinity", ")", ",", "nextafter", "(", "Math", ".", "max", "(", "a", "[", "1", "]", ",", "b", "[", "1", "]", ")", ",", "Infinity", ")", "]", "}", "return", "bounds", "}" ]
Convert a list of edges in a pslg to bounding boxes
[ "Convert", "a", "list", "of", "edges", "in", "a", "pslg", "to", "bounding", "boxes" ]
c20e801e036bf2c8ebca6ea6c6631aa64fc334c7
https://github.com/mikolalysenko/clean-pslg/blob/c20e801e036bf2c8ebca6ea6c6631aa64fc334c7/clean-pslg.js#L26-L40
37,201
mikolalysenko/clean-pslg
clean-pslg.js
boundPoints
function boundPoints (points) { var bounds = new Array(points.length) for (var i = 0; i < points.length; ++i) { var p = points[i] bounds[i] = [ nextafter(p[0], -Infinity), nextafter(p[1], -Infinity), nextafter(p[0], Infinity), nextafter(p[1], Infinity) ] } return bounds }
javascript
function boundPoints (points) { var bounds = new Array(points.length) for (var i = 0; i < points.length; ++i) { var p = points[i] bounds[i] = [ nextafter(p[0], -Infinity), nextafter(p[1], -Infinity), nextafter(p[0], Infinity), nextafter(p[1], Infinity) ] } return bounds }
[ "function", "boundPoints", "(", "points", ")", "{", "var", "bounds", "=", "new", "Array", "(", "points", ".", "length", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "points", ".", "length", ";", "++", "i", ")", "{", "var", "p", "=", "points", "[", "i", "]", "bounds", "[", "i", "]", "=", "[", "nextafter", "(", "p", "[", "0", "]", ",", "-", "Infinity", ")", ",", "nextafter", "(", "p", "[", "1", "]", ",", "-", "Infinity", ")", ",", "nextafter", "(", "p", "[", "0", "]", ",", "Infinity", ")", ",", "nextafter", "(", "p", "[", "1", "]", ",", "Infinity", ")", "]", "}", "return", "bounds", "}" ]
Convert a list of points into bounding boxes by duplicating coords
[ "Convert", "a", "list", "of", "points", "into", "bounding", "boxes", "by", "duplicating", "coords" ]
c20e801e036bf2c8ebca6ea6c6631aa64fc334c7
https://github.com/mikolalysenko/clean-pslg/blob/c20e801e036bf2c8ebca6ea6c6631aa64fc334c7/clean-pslg.js#L43-L55
37,202
mikolalysenko/clean-pslg
clean-pslg.js
dedupPoints
function dedupPoints (floatPoints, ratPoints, floatBounds) { var numPoints = ratPoints.length var uf = new UnionFind(numPoints) // Compute rational bounds var bounds = [] for (var i = 0; i < ratPoints.length; ++i) { var p = ratPoints[i] var xb = boundRat(p[0]) var yb = boundRat(p[1]) bounds.push([ nextafter(xb[0], -Infinity), nextafter(yb[0], -Infinity), nextafter(xb[1], Infinity), nextafter(yb[1], Infinity) ]) } // Link all points with over lapping boxes boxIntersect(bounds, function (i, j) { uf.link(i, j) }) // Do 1 pass over points to combine points in label sets var noDupes = true var labels = new Array(numPoints) for (var i = 0; i < numPoints; ++i) { var j = uf.find(i) if (j !== i) { // Clear no-dupes flag, zero out label noDupes = false // Make each point the top-left point from its cell floatPoints[j] = [ Math.min(floatPoints[i][0], floatPoints[j][0]), Math.min(floatPoints[i][1], floatPoints[j][1]) ] } } // If no duplicates, return null to signal termination if (noDupes) { return null } var ptr = 0 for (var i = 0; i < numPoints; ++i) { var j = uf.find(i) if (j === i) { labels[i] = ptr floatPoints[ptr++] = floatPoints[i] } else { labels[i] = -1 } } floatPoints.length = ptr // Do a second pass to fix up missing labels for (var i = 0; i < numPoints; ++i) { if (labels[i] < 0) { labels[i] = labels[uf.find(i)] } } // Return resulting union-find data structure return labels }
javascript
function dedupPoints (floatPoints, ratPoints, floatBounds) { var numPoints = ratPoints.length var uf = new UnionFind(numPoints) // Compute rational bounds var bounds = [] for (var i = 0; i < ratPoints.length; ++i) { var p = ratPoints[i] var xb = boundRat(p[0]) var yb = boundRat(p[1]) bounds.push([ nextafter(xb[0], -Infinity), nextafter(yb[0], -Infinity), nextafter(xb[1], Infinity), nextafter(yb[1], Infinity) ]) } // Link all points with over lapping boxes boxIntersect(bounds, function (i, j) { uf.link(i, j) }) // Do 1 pass over points to combine points in label sets var noDupes = true var labels = new Array(numPoints) for (var i = 0; i < numPoints; ++i) { var j = uf.find(i) if (j !== i) { // Clear no-dupes flag, zero out label noDupes = false // Make each point the top-left point from its cell floatPoints[j] = [ Math.min(floatPoints[i][0], floatPoints[j][0]), Math.min(floatPoints[i][1], floatPoints[j][1]) ] } } // If no duplicates, return null to signal termination if (noDupes) { return null } var ptr = 0 for (var i = 0; i < numPoints; ++i) { var j = uf.find(i) if (j === i) { labels[i] = ptr floatPoints[ptr++] = floatPoints[i] } else { labels[i] = -1 } } floatPoints.length = ptr // Do a second pass to fix up missing labels for (var i = 0; i < numPoints; ++i) { if (labels[i] < 0) { labels[i] = labels[uf.find(i)] } } // Return resulting union-find data structure return labels }
[ "function", "dedupPoints", "(", "floatPoints", ",", "ratPoints", ",", "floatBounds", ")", "{", "var", "numPoints", "=", "ratPoints", ".", "length", "var", "uf", "=", "new", "UnionFind", "(", "numPoints", ")", "// Compute rational bounds", "var", "bounds", "=", "[", "]", "for", "(", "var", "i", "=", "0", ";", "i", "<", "ratPoints", ".", "length", ";", "++", "i", ")", "{", "var", "p", "=", "ratPoints", "[", "i", "]", "var", "xb", "=", "boundRat", "(", "p", "[", "0", "]", ")", "var", "yb", "=", "boundRat", "(", "p", "[", "1", "]", ")", "bounds", ".", "push", "(", "[", "nextafter", "(", "xb", "[", "0", "]", ",", "-", "Infinity", ")", ",", "nextafter", "(", "yb", "[", "0", "]", ",", "-", "Infinity", ")", ",", "nextafter", "(", "xb", "[", "1", "]", ",", "Infinity", ")", ",", "nextafter", "(", "yb", "[", "1", "]", ",", "Infinity", ")", "]", ")", "}", "// Link all points with over lapping boxes", "boxIntersect", "(", "bounds", ",", "function", "(", "i", ",", "j", ")", "{", "uf", ".", "link", "(", "i", ",", "j", ")", "}", ")", "// Do 1 pass over points to combine points in label sets", "var", "noDupes", "=", "true", "var", "labels", "=", "new", "Array", "(", "numPoints", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numPoints", ";", "++", "i", ")", "{", "var", "j", "=", "uf", ".", "find", "(", "i", ")", "if", "(", "j", "!==", "i", ")", "{", "// Clear no-dupes flag, zero out label", "noDupes", "=", "false", "// Make each point the top-left point from its cell", "floatPoints", "[", "j", "]", "=", "[", "Math", ".", "min", "(", "floatPoints", "[", "i", "]", "[", "0", "]", ",", "floatPoints", "[", "j", "]", "[", "0", "]", ")", ",", "Math", ".", "min", "(", "floatPoints", "[", "i", "]", "[", "1", "]", ",", "floatPoints", "[", "j", "]", "[", "1", "]", ")", "]", "}", "}", "// If no duplicates, return null to signal termination", "if", "(", "noDupes", ")", "{", "return", "null", "}", "var", "ptr", "=", "0", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numPoints", ";", "++", "i", ")", "{", "var", "j", "=", "uf", ".", "find", "(", "i", ")", "if", "(", "j", "===", "i", ")", "{", "labels", "[", "i", "]", "=", "ptr", "floatPoints", "[", "ptr", "++", "]", "=", "floatPoints", "[", "i", "]", "}", "else", "{", "labels", "[", "i", "]", "=", "-", "1", "}", "}", "floatPoints", ".", "length", "=", "ptr", "// Do a second pass to fix up missing labels", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numPoints", ";", "++", "i", ")", "{", "if", "(", "labels", "[", "i", "]", "<", "0", ")", "{", "labels", "[", "i", "]", "=", "labels", "[", "uf", ".", "find", "(", "i", ")", "]", "}", "}", "// Return resulting union-find data structure", "return", "labels", "}" ]
Merge overlapping points
[ "Merge", "overlapping", "points" ]
c20e801e036bf2c8ebca6ea6c6631aa64fc334c7
https://github.com/mikolalysenko/clean-pslg/blob/c20e801e036bf2c8ebca6ea6c6631aa64fc334c7/clean-pslg.js#L191-L257
37,203
mikolalysenko/clean-pslg
clean-pslg.js
dedupEdges
function dedupEdges (edges, labels, useColor) { if (edges.length === 0) { return } if (labels) { for (var i = 0; i < edges.length; ++i) { var e = edges[i] var a = labels[e[0]] var b = labels[e[1]] e[0] = Math.min(a, b) e[1] = Math.max(a, b) } } else { for (var i = 0; i < edges.length; ++i) { var e = edges[i] var a = e[0] var b = e[1] e[0] = Math.min(a, b) e[1] = Math.max(a, b) } } if (useColor) { edges.sort(compareLex3) } else { edges.sort(compareLex2) } var ptr = 1 for (var i = 1; i < edges.length; ++i) { var prev = edges[i - 1] var next = edges[i] if (next[0] === prev[0] && next[1] === prev[1] && (!useColor || next[2] === prev[2])) { continue } edges[ptr++] = next } edges.length = ptr }
javascript
function dedupEdges (edges, labels, useColor) { if (edges.length === 0) { return } if (labels) { for (var i = 0; i < edges.length; ++i) { var e = edges[i] var a = labels[e[0]] var b = labels[e[1]] e[0] = Math.min(a, b) e[1] = Math.max(a, b) } } else { for (var i = 0; i < edges.length; ++i) { var e = edges[i] var a = e[0] var b = e[1] e[0] = Math.min(a, b) e[1] = Math.max(a, b) } } if (useColor) { edges.sort(compareLex3) } else { edges.sort(compareLex2) } var ptr = 1 for (var i = 1; i < edges.length; ++i) { var prev = edges[i - 1] var next = edges[i] if (next[0] === prev[0] && next[1] === prev[1] && (!useColor || next[2] === prev[2])) { continue } edges[ptr++] = next } edges.length = ptr }
[ "function", "dedupEdges", "(", "edges", ",", "labels", ",", "useColor", ")", "{", "if", "(", "edges", ".", "length", "===", "0", ")", "{", "return", "}", "if", "(", "labels", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "edges", ".", "length", ";", "++", "i", ")", "{", "var", "e", "=", "edges", "[", "i", "]", "var", "a", "=", "labels", "[", "e", "[", "0", "]", "]", "var", "b", "=", "labels", "[", "e", "[", "1", "]", "]", "e", "[", "0", "]", "=", "Math", ".", "min", "(", "a", ",", "b", ")", "e", "[", "1", "]", "=", "Math", ".", "max", "(", "a", ",", "b", ")", "}", "}", "else", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "edges", ".", "length", ";", "++", "i", ")", "{", "var", "e", "=", "edges", "[", "i", "]", "var", "a", "=", "e", "[", "0", "]", "var", "b", "=", "e", "[", "1", "]", "e", "[", "0", "]", "=", "Math", ".", "min", "(", "a", ",", "b", ")", "e", "[", "1", "]", "=", "Math", ".", "max", "(", "a", ",", "b", ")", "}", "}", "if", "(", "useColor", ")", "{", "edges", ".", "sort", "(", "compareLex3", ")", "}", "else", "{", "edges", ".", "sort", "(", "compareLex2", ")", "}", "var", "ptr", "=", "1", "for", "(", "var", "i", "=", "1", ";", "i", "<", "edges", ".", "length", ";", "++", "i", ")", "{", "var", "prev", "=", "edges", "[", "i", "-", "1", "]", "var", "next", "=", "edges", "[", "i", "]", "if", "(", "next", "[", "0", "]", "===", "prev", "[", "0", "]", "&&", "next", "[", "1", "]", "===", "prev", "[", "1", "]", "&&", "(", "!", "useColor", "||", "next", "[", "2", "]", "===", "prev", "[", "2", "]", ")", ")", "{", "continue", "}", "edges", "[", "ptr", "++", "]", "=", "next", "}", "edges", ".", "length", "=", "ptr", "}" ]
Remove duplicate edge labels
[ "Remove", "duplicate", "edge", "labels" ]
c20e801e036bf2c8ebca6ea6c6631aa64fc334c7
https://github.com/mikolalysenko/clean-pslg/blob/c20e801e036bf2c8ebca6ea6c6631aa64fc334c7/clean-pslg.js#L274-L311
37,204
mikolalysenko/clean-pslg
clean-pslg.js
snapRound
function snapRound (points, edges, useColor) { // 1. find edge crossings var edgeBounds = boundEdges(points, edges) var crossings = getCrossings(points, edges, edgeBounds) // 2. find t-junctions var vertBounds = boundPoints(points) var tjunctions = getTJunctions(points, edges, edgeBounds, vertBounds) // 3. cut edges, construct rational points var ratPoints = cutEdges(points, edges, crossings, tjunctions, useColor) // 4. dedupe verts var labels = dedupPoints(points, ratPoints, vertBounds) // 5. dedupe edges dedupEdges(edges, labels, useColor) // 6. check termination if (!labels) { return (crossings.length > 0 || tjunctions.length > 0) } // More iterations necessary return true }
javascript
function snapRound (points, edges, useColor) { // 1. find edge crossings var edgeBounds = boundEdges(points, edges) var crossings = getCrossings(points, edges, edgeBounds) // 2. find t-junctions var vertBounds = boundPoints(points) var tjunctions = getTJunctions(points, edges, edgeBounds, vertBounds) // 3. cut edges, construct rational points var ratPoints = cutEdges(points, edges, crossings, tjunctions, useColor) // 4. dedupe verts var labels = dedupPoints(points, ratPoints, vertBounds) // 5. dedupe edges dedupEdges(edges, labels, useColor) // 6. check termination if (!labels) { return (crossings.length > 0 || tjunctions.length > 0) } // More iterations necessary return true }
[ "function", "snapRound", "(", "points", ",", "edges", ",", "useColor", ")", "{", "// 1. find edge crossings", "var", "edgeBounds", "=", "boundEdges", "(", "points", ",", "edges", ")", "var", "crossings", "=", "getCrossings", "(", "points", ",", "edges", ",", "edgeBounds", ")", "// 2. find t-junctions", "var", "vertBounds", "=", "boundPoints", "(", "points", ")", "var", "tjunctions", "=", "getTJunctions", "(", "points", ",", "edges", ",", "edgeBounds", ",", "vertBounds", ")", "// 3. cut edges, construct rational points", "var", "ratPoints", "=", "cutEdges", "(", "points", ",", "edges", ",", "crossings", ",", "tjunctions", ",", "useColor", ")", "// 4. dedupe verts", "var", "labels", "=", "dedupPoints", "(", "points", ",", "ratPoints", ",", "vertBounds", ")", "// 5. dedupe edges", "dedupEdges", "(", "edges", ",", "labels", ",", "useColor", ")", "// 6. check termination", "if", "(", "!", "labels", ")", "{", "return", "(", "crossings", ".", "length", ">", "0", "||", "tjunctions", ".", "length", ">", "0", ")", "}", "// More iterations necessary", "return", "true", "}" ]
Repeat until convergence
[ "Repeat", "until", "convergence" ]
c20e801e036bf2c8ebca6ea6c6631aa64fc334c7
https://github.com/mikolalysenko/clean-pslg/blob/c20e801e036bf2c8ebca6ea6c6631aa64fc334c7/clean-pslg.js#L320-L345
37,205
mikolalysenko/clean-pslg
clean-pslg.js
cleanPSLG
function cleanPSLG (points, edges, colors) { // If using colors, augment edges with color data var prevEdges if (colors) { prevEdges = edges var augEdges = new Array(edges.length) for (var i = 0; i < edges.length; ++i) { var e = edges[i] augEdges[i] = [e[0], e[1], colors[i]] } edges = augEdges } // First round: remove duplicate edges and points var modified = preRound(points, edges, !!colors) // Run snap rounding until convergence while (snapRound(points, edges, !!colors)) { modified = true } // Strip color tags if (!!colors && modified) { prevEdges.length = 0 colors.length = 0 for (var i = 0; i < edges.length; ++i) { var e = edges[i] prevEdges.push([e[0], e[1]]) colors.push(e[2]) } } return modified }
javascript
function cleanPSLG (points, edges, colors) { // If using colors, augment edges with color data var prevEdges if (colors) { prevEdges = edges var augEdges = new Array(edges.length) for (var i = 0; i < edges.length; ++i) { var e = edges[i] augEdges[i] = [e[0], e[1], colors[i]] } edges = augEdges } // First round: remove duplicate edges and points var modified = preRound(points, edges, !!colors) // Run snap rounding until convergence while (snapRound(points, edges, !!colors)) { modified = true } // Strip color tags if (!!colors && modified) { prevEdges.length = 0 colors.length = 0 for (var i = 0; i < edges.length; ++i) { var e = edges[i] prevEdges.push([e[0], e[1]]) colors.push(e[2]) } } return modified }
[ "function", "cleanPSLG", "(", "points", ",", "edges", ",", "colors", ")", "{", "// If using colors, augment edges with color data", "var", "prevEdges", "if", "(", "colors", ")", "{", "prevEdges", "=", "edges", "var", "augEdges", "=", "new", "Array", "(", "edges", ".", "length", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "edges", ".", "length", ";", "++", "i", ")", "{", "var", "e", "=", "edges", "[", "i", "]", "augEdges", "[", "i", "]", "=", "[", "e", "[", "0", "]", ",", "e", "[", "1", "]", ",", "colors", "[", "i", "]", "]", "}", "edges", "=", "augEdges", "}", "// First round: remove duplicate edges and points", "var", "modified", "=", "preRound", "(", "points", ",", "edges", ",", "!", "!", "colors", ")", "// Run snap rounding until convergence", "while", "(", "snapRound", "(", "points", ",", "edges", ",", "!", "!", "colors", ")", ")", "{", "modified", "=", "true", "}", "// Strip color tags", "if", "(", "!", "!", "colors", "&&", "modified", ")", "{", "prevEdges", ".", "length", "=", "0", "colors", ".", "length", "=", "0", "for", "(", "var", "i", "=", "0", ";", "i", "<", "edges", ".", "length", ";", "++", "i", ")", "{", "var", "e", "=", "edges", "[", "i", "]", "prevEdges", ".", "push", "(", "[", "e", "[", "0", "]", ",", "e", "[", "1", "]", "]", ")", "colors", ".", "push", "(", "e", "[", "2", "]", ")", "}", "}", "return", "modified", "}" ]
Main loop, runs PSLG clean up until completion
[ "Main", "loop", "runs", "PSLG", "clean", "up", "until", "completion" ]
c20e801e036bf2c8ebca6ea6c6631aa64fc334c7
https://github.com/mikolalysenko/clean-pslg/blob/c20e801e036bf2c8ebca6ea6c6631aa64fc334c7/clean-pslg.js#L348-L381
37,206
reapp/reapp-kit
src/lib/theme.js
convertRawTheme
function convertRawTheme(theme) { if (!Array.isArray(theme.constants)) { return { constants: Object.keys(theme.constants).map(key => theme.constants[key]), styles: [].concat(theme.styles), animations: [].concat(theme.animations) } } else return theme; }
javascript
function convertRawTheme(theme) { if (!Array.isArray(theme.constants)) { return { constants: Object.keys(theme.constants).map(key => theme.constants[key]), styles: [].concat(theme.styles), animations: [].concat(theme.animations) } } else return theme; }
[ "function", "convertRawTheme", "(", "theme", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "theme", ".", "constants", ")", ")", "{", "return", "{", "constants", ":", "Object", ".", "keys", "(", "theme", ".", "constants", ")", ".", "map", "(", "key", "=>", "theme", ".", "constants", "[", "key", "]", ")", ",", "styles", ":", "[", "]", ".", "concat", "(", "theme", ".", "styles", ")", ",", "animations", ":", "[", "]", ".", "concat", "(", "theme", ".", "animations", ")", "}", "}", "else", "return", "theme", ";", "}" ]
user may not want to configure a whole theme and just pass in the theme we give them wholesale, lets convert it
[ "user", "may", "not", "want", "to", "configure", "a", "whole", "theme", "and", "just", "pass", "in", "the", "theme", "we", "give", "them", "wholesale", "lets", "convert", "it" ]
10557c6b808542f52bb421e23efb2b58dff567ed
https://github.com/reapp/reapp-kit/blob/10557c6b808542f52bb421e23efb2b58dff567ed/src/lib/theme.js#L20-L30
37,207
jonschlinkert/expand-object
index.js
expand
function expand(str, opts) { opts = opts || {}; if (typeof str !== 'string') { throw new TypeError('expand-object expects a string.'); } if (!/[.|:=]/.test(str) && /,/.test(str)) { return toArray(str); } var m; if ((m = /(\w+[:=]\w+\.)+/.exec(str)) && !/[|,+]/.test(str)) { var val = m[0].split(':').join('.'); str = val + str.slice(m[0].length); } var arr = splitString(str, '|'); var len = arr.length, i = -1; var res = {}; if (isArrayLike(str) && arr.length === 1) { return expandArrayObj(str, opts); } while (++i < len) { var val = arr[i]; // test for `https://foo` if (/\w:\/\/\w/.test(val)) { res[val] = ''; continue; } var re = /^((?:\w+)\.(?:\w+))[:.]((?:\w+,)+)+((?:\w+):(?:\w+))/; var m = re.exec(val); if (m && m[1] && m[2] && m[3]) { var arrVal = m[2]; arrVal = arrVal.replace(/,$/, ''); var prop = arrVal.split(','); prop = prop.concat(toObject(m[3])); res = set(res, m[1], prop); } else if (!/[.,\|:=]/.test(val)) { res[val] = opts.toBoolean ? true : ''; } else { res = expandObject(res, val, opts); } } return res; }
javascript
function expand(str, opts) { opts = opts || {}; if (typeof str !== 'string') { throw new TypeError('expand-object expects a string.'); } if (!/[.|:=]/.test(str) && /,/.test(str)) { return toArray(str); } var m; if ((m = /(\w+[:=]\w+\.)+/.exec(str)) && !/[|,+]/.test(str)) { var val = m[0].split(':').join('.'); str = val + str.slice(m[0].length); } var arr = splitString(str, '|'); var len = arr.length, i = -1; var res = {}; if (isArrayLike(str) && arr.length === 1) { return expandArrayObj(str, opts); } while (++i < len) { var val = arr[i]; // test for `https://foo` if (/\w:\/\/\w/.test(val)) { res[val] = ''; continue; } var re = /^((?:\w+)\.(?:\w+))[:.]((?:\w+,)+)+((?:\w+):(?:\w+))/; var m = re.exec(val); if (m && m[1] && m[2] && m[3]) { var arrVal = m[2]; arrVal = arrVal.replace(/,$/, ''); var prop = arrVal.split(','); prop = prop.concat(toObject(m[3])); res = set(res, m[1], prop); } else if (!/[.,\|:=]/.test(val)) { res[val] = opts.toBoolean ? true : ''; } else { res = expandObject(res, val, opts); } } return res; }
[ "function", "expand", "(", "str", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "if", "(", "typeof", "str", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'expand-object expects a string.'", ")", ";", "}", "if", "(", "!", "/", "[.|:=]", "/", ".", "test", "(", "str", ")", "&&", "/", ",", "/", ".", "test", "(", "str", ")", ")", "{", "return", "toArray", "(", "str", ")", ";", "}", "var", "m", ";", "if", "(", "(", "m", "=", "/", "(\\w+[:=]\\w+\\.)+", "/", ".", "exec", "(", "str", ")", ")", "&&", "!", "/", "[|,+]", "/", ".", "test", "(", "str", ")", ")", "{", "var", "val", "=", "m", "[", "0", "]", ".", "split", "(", "':'", ")", ".", "join", "(", "'.'", ")", ";", "str", "=", "val", "+", "str", ".", "slice", "(", "m", "[", "0", "]", ".", "length", ")", ";", "}", "var", "arr", "=", "splitString", "(", "str", ",", "'|'", ")", ";", "var", "len", "=", "arr", ".", "length", ",", "i", "=", "-", "1", ";", "var", "res", "=", "{", "}", ";", "if", "(", "isArrayLike", "(", "str", ")", "&&", "arr", ".", "length", "===", "1", ")", "{", "return", "expandArrayObj", "(", "str", ",", "opts", ")", ";", "}", "while", "(", "++", "i", "<", "len", ")", "{", "var", "val", "=", "arr", "[", "i", "]", ";", "// test for `https://foo`", "if", "(", "/", "\\w:\\/\\/\\w", "/", ".", "test", "(", "val", ")", ")", "{", "res", "[", "val", "]", "=", "''", ";", "continue", ";", "}", "var", "re", "=", "/", "^((?:\\w+)\\.(?:\\w+))[:.]((?:\\w+,)+)+((?:\\w+):(?:\\w+))", "/", ";", "var", "m", "=", "re", ".", "exec", "(", "val", ")", ";", "if", "(", "m", "&&", "m", "[", "1", "]", "&&", "m", "[", "2", "]", "&&", "m", "[", "3", "]", ")", "{", "var", "arrVal", "=", "m", "[", "2", "]", ";", "arrVal", "=", "arrVal", ".", "replace", "(", "/", ",$", "/", ",", "''", ")", ";", "var", "prop", "=", "arrVal", ".", "split", "(", "','", ")", ";", "prop", "=", "prop", ".", "concat", "(", "toObject", "(", "m", "[", "3", "]", ")", ")", ";", "res", "=", "set", "(", "res", ",", "m", "[", "1", "]", ",", "prop", ")", ";", "}", "else", "if", "(", "!", "/", "[.,\\|:=]", "/", ".", "test", "(", "val", ")", ")", "{", "res", "[", "val", "]", "=", "opts", ".", "toBoolean", "?", "true", ":", "''", ";", "}", "else", "{", "res", "=", "expandObject", "(", "res", ",", "val", ",", "opts", ")", ";", "}", "}", "return", "res", ";", "}" ]
Expand the given string into an object. @param {String} `str` @return {Object}
[ "Expand", "the", "given", "string", "into", "an", "object", "." ]
98abd15d44d167d8c40f77bfcf01022b1d631c93
https://github.com/jonschlinkert/expand-object/blob/98abd15d44d167d8c40f77bfcf01022b1d631c93/index.js#L13-L61
37,208
socialshares/buttons
src/socialshares.js
getService
function getService (classList) { let service Object.keys(services).forEach(key => { if (classList.contains('socialshares-' + key)) { service = services[key] service.name = key } }) return service }
javascript
function getService (classList) { let service Object.keys(services).forEach(key => { if (classList.contains('socialshares-' + key)) { service = services[key] service.name = key } }) return service }
[ "function", "getService", "(", "classList", ")", "{", "let", "service", "Object", ".", "keys", "(", "services", ")", ".", "forEach", "(", "key", "=>", "{", "if", "(", "classList", ".", "contains", "(", "'socialshares-'", "+", "key", ")", ")", "{", "service", "=", "services", "[", "key", "]", "service", ".", "name", "=", "key", "}", "}", ")", "return", "service", "}" ]
Identifies the service based on the button's class and returns the metadata for that service.
[ "Identifies", "the", "service", "based", "on", "the", "button", "s", "class", "and", "returns", "the", "metadata", "for", "that", "service", "." ]
f0d47c7b8dfb6d9e994d266f199a936ced7c0f28
https://github.com/socialshares/buttons/blob/f0d47c7b8dfb6d9e994d266f199a936ced7c0f28/src/socialshares.js#L37-L48
37,209
socialshares/buttons
src/socialshares.js
openDialog
function openDialog (url) { const width = socialshares.config.dialog.width const height = socialshares.config.dialog.height // Center the popup const top = (window.screen.height / 2 - height / 2) const left = (window.screen.width / 2 - width / 2) window.open(url, 'Share', `width=${width},height=${height},top=${top},left=${left},menubar=no,toolbar=no,resizable=yes,scrollbars=yes`) }
javascript
function openDialog (url) { const width = socialshares.config.dialog.width const height = socialshares.config.dialog.height // Center the popup const top = (window.screen.height / 2 - height / 2) const left = (window.screen.width / 2 - width / 2) window.open(url, 'Share', `width=${width},height=${height},top=${top},left=${left},menubar=no,toolbar=no,resizable=yes,scrollbars=yes`) }
[ "function", "openDialog", "(", "url", ")", "{", "const", "width", "=", "socialshares", ".", "config", ".", "dialog", ".", "width", "const", "height", "=", "socialshares", ".", "config", ".", "dialog", ".", "height", "// Center the popup", "const", "top", "=", "(", "window", ".", "screen", ".", "height", "/", "2", "-", "height", "/", "2", ")", "const", "left", "=", "(", "window", ".", "screen", ".", "width", "/", "2", "-", "width", "/", "2", ")", "window", ".", "open", "(", "url", ",", "'Share'", ",", "`", "${", "width", "}", "${", "height", "}", "${", "top", "}", "${", "left", "}", "`", ")", "}" ]
Popup window helper
[ "Popup", "window", "helper" ]
f0d47c7b8dfb6d9e994d266f199a936ced7c0f28
https://github.com/socialshares/buttons/blob/f0d47c7b8dfb6d9e994d266f199a936ced7c0f28/src/socialshares.js#L57-L66
37,210
tadam313/sheet-db
src/rest_client.js
fetchData
async function fetchData(key, transformation, cacheMiss) { // TODO: needs better caching logic var data = cache.get(key); if (data) { return data; } try { data = transformation(await cacheMiss()); } catch (err) { throw new Error('The response contains invalid data'); } cache.put(key, data); return data; }
javascript
async function fetchData(key, transformation, cacheMiss) { // TODO: needs better caching logic var data = cache.get(key); if (data) { return data; } try { data = transformation(await cacheMiss()); } catch (err) { throw new Error('The response contains invalid data'); } cache.put(key, data); return data; }
[ "async", "function", "fetchData", "(", "key", ",", "transformation", ",", "cacheMiss", ")", "{", "// TODO: needs better caching logic", "var", "data", "=", "cache", ".", "get", "(", "key", ")", ";", "if", "(", "data", ")", "{", "return", "data", ";", "}", "try", "{", "data", "=", "transformation", "(", "await", "cacheMiss", "(", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "throw", "new", "Error", "(", "'The response contains invalid data'", ")", ";", "}", "cache", ".", "put", "(", "key", ",", "data", ")", ";", "return", "data", ";", "}" ]
Tries to fetch the response from the cache and provides fallback if not found @param {string} key - Key of the data in the cache @param {function} transformation - Transformation of the data @param {function} cacheMiss - Handler in case of the data is not found in the cache @returns {*}
[ "Tries", "to", "fetch", "the", "response", "from", "the", "cache", "and", "provides", "fallback", "if", "not", "found" ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/rest_client.js#L46-L63
37,211
tadam313/sheet-db
src/rest_client.js
querySheetInfo
async function querySheetInfo(sheetId) { var key = util.createIdentifier('sheet_info', sheetId); return await fetchData(key, api.converter.sheetInfoResponse, () => executeRequest('sheet_info', {sheetId: sheetId}) ); }
javascript
async function querySheetInfo(sheetId) { var key = util.createIdentifier('sheet_info', sheetId); return await fetchData(key, api.converter.sheetInfoResponse, () => executeRequest('sheet_info', {sheetId: sheetId}) ); }
[ "async", "function", "querySheetInfo", "(", "sheetId", ")", "{", "var", "key", "=", "util", ".", "createIdentifier", "(", "'sheet_info'", ",", "sheetId", ")", ";", "return", "await", "fetchData", "(", "key", ",", "api", ".", "converter", ".", "sheetInfoResponse", ",", "(", ")", "=>", "executeRequest", "(", "'sheet_info'", ",", "{", "sheetId", ":", "sheetId", "}", ")", ")", ";", "}" ]
Queries the specific sheet info. @param {string} sheetId
[ "Queries", "the", "specific", "sheet", "info", "." ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/rest_client.js#L79-L85
37,212
tadam313/sheet-db
src/rest_client.js
createWorksheet
async function createWorksheet(sheetId, worksheetTitle, options) { options = Object.assign({ title: worksheetTitle }, options); let payload = api.converter.createWorksheetRequest(options); let response = await executeRequest('create_worksheet', { body: payload, sheetId: sheetId }); cache.clear(); // converts worksheetData to model return api.converter.workSheetInfoResponse(response); }
javascript
async function createWorksheet(sheetId, worksheetTitle, options) { options = Object.assign({ title: worksheetTitle }, options); let payload = api.converter.createWorksheetRequest(options); let response = await executeRequest('create_worksheet', { body: payload, sheetId: sheetId }); cache.clear(); // converts worksheetData to model return api.converter.workSheetInfoResponse(response); }
[ "async", "function", "createWorksheet", "(", "sheetId", ",", "worksheetTitle", ",", "options", ")", "{", "options", "=", "Object", ".", "assign", "(", "{", "title", ":", "worksheetTitle", "}", ",", "options", ")", ";", "let", "payload", "=", "api", ".", "converter", ".", "createWorksheetRequest", "(", "options", ")", ";", "let", "response", "=", "await", "executeRequest", "(", "'create_worksheet'", ",", "{", "body", ":", "payload", ",", "sheetId", ":", "sheetId", "}", ")", ";", "cache", ".", "clear", "(", ")", ";", "// converts worksheetData to model", "return", "api", ".", "converter", ".", "workSheetInfoResponse", "(", "response", ")", ";", "}" ]
Creates the specific worksheet @param {string} sheetId ID of the sheet @param {string} worksheetTitle name of the worksheet to be created @param {object} options
[ "Creates", "the", "specific", "worksheet" ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/rest_client.js#L94-L107
37,213
tadam313/sheet-db
src/rest_client.js
dropWorksheet
async function dropWorksheet(sheetId, worksheetId) { let response = await executeRequest('drop_worksheet', { sheetId: sheetId, worksheetId: worksheetId }); cache.clear(); return response; }
javascript
async function dropWorksheet(sheetId, worksheetId) { let response = await executeRequest('drop_worksheet', { sheetId: sheetId, worksheetId: worksheetId }); cache.clear(); return response; }
[ "async", "function", "dropWorksheet", "(", "sheetId", ",", "worksheetId", ")", "{", "let", "response", "=", "await", "executeRequest", "(", "'drop_worksheet'", ",", "{", "sheetId", ":", "sheetId", ",", "worksheetId", ":", "worksheetId", "}", ")", ";", "cache", ".", "clear", "(", ")", ";", "return", "response", ";", "}" ]
Drops the specific worksheet @param {string} sheetId @param {string} worksheetId
[ "Drops", "the", "specific", "worksheet" ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/rest_client.js#L115-L123
37,214
tadam313/sheet-db
src/rest_client.js
insertEntries
async function insertEntries(worksheetInfo, entries, options) { let response; let insertEntry = (entry) => { var payload = Object.assign({ body: api.converter.createEntryRequest(entry) }, worksheetInfo ); return executeRequest('create_entry', payload); }; if (options.ordered) { for (let entry of entries) { response = await insertEntry(entry); } } else { response = await Promise.all(entries.map(entry => insertEntry(entry))); } cache.clear(); return response; }
javascript
async function insertEntries(worksheetInfo, entries, options) { let response; let insertEntry = (entry) => { var payload = Object.assign({ body: api.converter.createEntryRequest(entry) }, worksheetInfo ); return executeRequest('create_entry', payload); }; if (options.ordered) { for (let entry of entries) { response = await insertEntry(entry); } } else { response = await Promise.all(entries.map(entry => insertEntry(entry))); } cache.clear(); return response; }
[ "async", "function", "insertEntries", "(", "worksheetInfo", ",", "entries", ",", "options", ")", "{", "let", "response", ";", "let", "insertEntry", "=", "(", "entry", ")", "=>", "{", "var", "payload", "=", "Object", ".", "assign", "(", "{", "body", ":", "api", ".", "converter", ".", "createEntryRequest", "(", "entry", ")", "}", ",", "worksheetInfo", ")", ";", "return", "executeRequest", "(", "'create_entry'", ",", "payload", ")", ";", "}", ";", "if", "(", "options", ".", "ordered", ")", "{", "for", "(", "let", "entry", "of", "entries", ")", "{", "response", "=", "await", "insertEntry", "(", "entry", ")", ";", "}", "}", "else", "{", "response", "=", "await", "Promise", ".", "all", "(", "entries", ".", "map", "(", "entry", "=>", "insertEntry", "(", "entry", ")", ")", ")", ";", "}", "cache", ".", "clear", "(", ")", ";", "return", "response", ";", "}" ]
Creates the specific entry @param {string} worksheetInfo @param {array} entries @param {object} options
[ "Creates", "the", "specific", "entry" ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/rest_client.js#L132-L154
37,215
tadam313/sheet-db
src/rest_client.js
updateEntries
async function updateEntries(worksheetInfo, entries) { let requests = entries.map(entry => { var payload = Object.assign({ body: api.converter.updateEntryRequest(entry), entityId: entry._id }, worksheetInfo ); return executeRequest('update_entry', payload); }); let response = Promise.all(requests); cache.clear(); return response; }
javascript
async function updateEntries(worksheetInfo, entries) { let requests = entries.map(entry => { var payload = Object.assign({ body: api.converter.updateEntryRequest(entry), entityId: entry._id }, worksheetInfo ); return executeRequest('update_entry', payload); }); let response = Promise.all(requests); cache.clear(); return response; }
[ "async", "function", "updateEntries", "(", "worksheetInfo", ",", "entries", ")", "{", "let", "requests", "=", "entries", ".", "map", "(", "entry", "=>", "{", "var", "payload", "=", "Object", ".", "assign", "(", "{", "body", ":", "api", ".", "converter", ".", "updateEntryRequest", "(", "entry", ")", ",", "entityId", ":", "entry", ".", "_id", "}", ",", "worksheetInfo", ")", ";", "return", "executeRequest", "(", "'update_entry'", ",", "payload", ")", ";", "}", ")", ";", "let", "response", "=", "Promise", ".", "all", "(", "requests", ")", ";", "cache", ".", "clear", "(", ")", ";", "return", "response", ";", "}" ]
Update the specified entries @param {object} worksheetInfo SheetID and worksheetID @param {array} entries
[ "Update", "the", "specified", "entries" ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/rest_client.js#L162-L178
37,216
tadam313/sheet-db
src/rest_client.js
queryWorksheet
async function queryWorksheet(workSheetInfo, query, options) { var key = util.createIdentifier( workSheetInfo.worksheetId, JSON.stringify(query) ); options = options || {}; options.query = query; return await fetchData( key, api.converter.queryResponse, () => { let payload = util._extend( workSheetInfo, api.converter.queryRequest(options) ); return executeRequest('query_worksheet', payload); }); }
javascript
async function queryWorksheet(workSheetInfo, query, options) { var key = util.createIdentifier( workSheetInfo.worksheetId, JSON.stringify(query) ); options = options || {}; options.query = query; return await fetchData( key, api.converter.queryResponse, () => { let payload = util._extend( workSheetInfo, api.converter.queryRequest(options) ); return executeRequest('query_worksheet', payload); }); }
[ "async", "function", "queryWorksheet", "(", "workSheetInfo", ",", "query", ",", "options", ")", "{", "var", "key", "=", "util", ".", "createIdentifier", "(", "workSheetInfo", ".", "worksheetId", ",", "JSON", ".", "stringify", "(", "query", ")", ")", ";", "options", "=", "options", "||", "{", "}", ";", "options", ".", "query", "=", "query", ";", "return", "await", "fetchData", "(", "key", ",", "api", ".", "converter", ".", "queryResponse", ",", "(", ")", "=>", "{", "let", "payload", "=", "util", ".", "_extend", "(", "workSheetInfo", ",", "api", ".", "converter", ".", "queryRequest", "(", "options", ")", ")", ";", "return", "executeRequest", "(", "'query_worksheet'", ",", "payload", ")", ";", "}", ")", ";", "}" ]
Queries the specific worksheet @param {object} workSheetInfo worksheetInfo SheetID and worksheetID @param {object} query Query descriptor @param {object} options query options
[ "Queries", "the", "specific", "worksheet" ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/rest_client.js#L187-L207
37,217
tadam313/sheet-db
src/rest_client.js
deleteEntries
async function deleteEntries(worksheetInfo, entityIds) { entityIds.reverse(); // since google pushes up the removed row, the ID will change to the previous // avoiding this iterate through the collection in reverse order // TODO: needs performance improvement var response; for (let id of entityIds) { let payload = util._extend({entityId: id}, worksheetInfo); response = await executeRequest('delete_entry', payload); } cache.clear(); return response; }
javascript
async function deleteEntries(worksheetInfo, entityIds) { entityIds.reverse(); // since google pushes up the removed row, the ID will change to the previous // avoiding this iterate through the collection in reverse order // TODO: needs performance improvement var response; for (let id of entityIds) { let payload = util._extend({entityId: id}, worksheetInfo); response = await executeRequest('delete_entry', payload); } cache.clear(); return response; }
[ "async", "function", "deleteEntries", "(", "worksheetInfo", ",", "entityIds", ")", "{", "entityIds", ".", "reverse", "(", ")", ";", "// since google pushes up the removed row, the ID will change to the previous", "// avoiding this iterate through the collection in reverse order", "// TODO: needs performance improvement", "var", "response", ";", "for", "(", "let", "id", "of", "entityIds", ")", "{", "let", "payload", "=", "util", ".", "_extend", "(", "{", "entityId", ":", "id", "}", ",", "worksheetInfo", ")", ";", "response", "=", "await", "executeRequest", "(", "'delete_entry'", ",", "payload", ")", ";", "}", "cache", ".", "clear", "(", ")", ";", "return", "response", ";", "}" ]
Deletes specified entries @param {object} worksheetInfo worksheetInfo SheetID and worksheetID @param {array} entityIds IDs of the entities
[ "Deletes", "specified", "entries" ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/rest_client.js#L215-L231
37,218
tadam313/sheet-db
src/rest_client.js
queryFields
async function queryFields(workSheetInfo) { var key = util.createIdentifier( 'queryFields', workSheetInfo.worksheetId ); return await fetchData( key, api.converter.queryFieldNames, () => executeRequest('query_fields', workSheetInfo) ); }
javascript
async function queryFields(workSheetInfo) { var key = util.createIdentifier( 'queryFields', workSheetInfo.worksheetId ); return await fetchData( key, api.converter.queryFieldNames, () => executeRequest('query_fields', workSheetInfo) ); }
[ "async", "function", "queryFields", "(", "workSheetInfo", ")", "{", "var", "key", "=", "util", ".", "createIdentifier", "(", "'queryFields'", ",", "workSheetInfo", ".", "worksheetId", ")", ";", "return", "await", "fetchData", "(", "key", ",", "api", ".", "converter", ".", "queryFieldNames", ",", "(", ")", "=>", "executeRequest", "(", "'query_fields'", ",", "workSheetInfo", ")", ")", ";", "}" ]
Queries the fields from the spreadsheet @param {object} workSheetInfo SheetID and worksheetID
[ "Queries", "the", "fields", "from", "the", "spreadsheet" ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/rest_client.js#L238-L249
37,219
tadam313/sheet-db
src/api/v3/converter.js
createXMLWriter
function createXMLWriter(extended) { extended = extended || false; var xw = new XmlWriter().startElement('entry') .writeAttribute('xmlns', 'http://www.w3.org/2005/Atom'); return extended ? xw.writeAttribute( 'xmlns:gsx', 'http://schemas.google.com/spreadsheets/2006/extended' ) : xw.writeAttribute( 'xmlns:gs', 'http://schemas.google.com/spreadsheets/2006' ); }
javascript
function createXMLWriter(extended) { extended = extended || false; var xw = new XmlWriter().startElement('entry') .writeAttribute('xmlns', 'http://www.w3.org/2005/Atom'); return extended ? xw.writeAttribute( 'xmlns:gsx', 'http://schemas.google.com/spreadsheets/2006/extended' ) : xw.writeAttribute( 'xmlns:gs', 'http://schemas.google.com/spreadsheets/2006' ); }
[ "function", "createXMLWriter", "(", "extended", ")", "{", "extended", "=", "extended", "||", "false", ";", "var", "xw", "=", "new", "XmlWriter", "(", ")", ".", "startElement", "(", "'entry'", ")", ".", "writeAttribute", "(", "'xmlns'", ",", "'http://www.w3.org/2005/Atom'", ")", ";", "return", "extended", "?", "xw", ".", "writeAttribute", "(", "'xmlns:gsx'", ",", "'http://schemas.google.com/spreadsheets/2006/extended'", ")", ":", "xw", ".", "writeAttribute", "(", "'xmlns:gs'", ",", "'http://schemas.google.com/spreadsheets/2006'", ")", ";", "}" ]
Creates XML writer for the data. @param extended @returns {*}
[ "Creates", "XML", "writer", "for", "the", "data", "." ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L28-L43
37,220
tadam313/sheet-db
src/api/v3/converter.js
queryRequest
function queryRequest(queryOptions) { if (!queryOptions) { return; } var options = util._extend({}, queryOptions); if (options.query && options.query.length) { options.query = '&sq=' + encodeURIComponent(options.query); } if (options.sort) { options.orderBy = '&orderby=column:' + options.sort; delete options.sort; } if (options.descending) { options.reverse = '&reverse=true'; delete options.descending; } return options; }
javascript
function queryRequest(queryOptions) { if (!queryOptions) { return; } var options = util._extend({}, queryOptions); if (options.query && options.query.length) { options.query = '&sq=' + encodeURIComponent(options.query); } if (options.sort) { options.orderBy = '&orderby=column:' + options.sort; delete options.sort; } if (options.descending) { options.reverse = '&reverse=true'; delete options.descending; } return options; }
[ "function", "queryRequest", "(", "queryOptions", ")", "{", "if", "(", "!", "queryOptions", ")", "{", "return", ";", "}", "var", "options", "=", "util", ".", "_extend", "(", "{", "}", ",", "queryOptions", ")", ";", "if", "(", "options", ".", "query", "&&", "options", ".", "query", ".", "length", ")", "{", "options", ".", "query", "=", "'&sq='", "+", "encodeURIComponent", "(", "options", ".", "query", ")", ";", "}", "if", "(", "options", ".", "sort", ")", "{", "options", ".", "orderBy", "=", "'&orderby=column:'", "+", "options", ".", "sort", ";", "delete", "options", ".", "sort", ";", "}", "if", "(", "options", ".", "descending", ")", "{", "options", ".", "reverse", "=", "'&reverse=true'", ";", "delete", "options", ".", "descending", ";", "}", "return", "options", ";", "}" ]
Transforms query request object @param queryOptions @returns {*}
[ "Transforms", "query", "request", "object" ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L61-L84
37,221
tadam313/sheet-db
src/api/v3/converter.js
worksheetData
function worksheetData(worksheet) { return { worksheetId: getItemIdFromUrl(g(worksheet.id)), title: g(worksheet.title), updated: g(worksheet.updated), colCount: g(worksheet['gs$colCount']), rowCount: g(worksheet['gs$rowCount']) }; }
javascript
function worksheetData(worksheet) { return { worksheetId: getItemIdFromUrl(g(worksheet.id)), title: g(worksheet.title), updated: g(worksheet.updated), colCount: g(worksheet['gs$colCount']), rowCount: g(worksheet['gs$rowCount']) }; }
[ "function", "worksheetData", "(", "worksheet", ")", "{", "return", "{", "worksheetId", ":", "getItemIdFromUrl", "(", "g", "(", "worksheet", ".", "id", ")", ")", ",", "title", ":", "g", "(", "worksheet", ".", "title", ")", ",", "updated", ":", "g", "(", "worksheet", ".", "updated", ")", ",", "colCount", ":", "g", "(", "worksheet", "[", "'gs$colCount'", "]", ")", ",", "rowCount", ":", "g", "(", "worksheet", "[", "'gs$rowCount'", "]", ")", "}", ";", "}" ]
Converts 'worksheet info' response to domain specific data. @param worksheet @returns {{id: *, title, updated: Date, colCount, rowCount}}
[ "Converts", "worksheet", "info", "response", "to", "domain", "specific", "data", "." ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L92-L100
37,222
tadam313/sheet-db
src/api/v3/converter.js
worksheetEntry
function worksheetEntry(entry, fieldPrefix) { fieldPrefix = fieldPrefix || 'gsx$'; var data = { '_id': getItemIdFromUrl(g(entry.id)), '_updated': g(entry.updated) }; Object.keys(entry) .filter(function(key) { return ~key.indexOf(fieldPrefix) && g(entry[key], true); }) .forEach(function(key) { var normalizedKey = key.substr(fieldPrefix.length); data[normalizedKey] = g(entry[key]); }); return data; }
javascript
function worksheetEntry(entry, fieldPrefix) { fieldPrefix = fieldPrefix || 'gsx$'; var data = { '_id': getItemIdFromUrl(g(entry.id)), '_updated': g(entry.updated) }; Object.keys(entry) .filter(function(key) { return ~key.indexOf(fieldPrefix) && g(entry[key], true); }) .forEach(function(key) { var normalizedKey = key.substr(fieldPrefix.length); data[normalizedKey] = g(entry[key]); }); return data; }
[ "function", "worksheetEntry", "(", "entry", ",", "fieldPrefix", ")", "{", "fieldPrefix", "=", "fieldPrefix", "||", "'gsx$'", ";", "var", "data", "=", "{", "'_id'", ":", "getItemIdFromUrl", "(", "g", "(", "entry", ".", "id", ")", ")", ",", "'_updated'", ":", "g", "(", "entry", ".", "updated", ")", "}", ";", "Object", ".", "keys", "(", "entry", ")", ".", "filter", "(", "function", "(", "key", ")", "{", "return", "~", "key", ".", "indexOf", "(", "fieldPrefix", ")", "&&", "g", "(", "entry", "[", "key", "]", ",", "true", ")", ";", "}", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "var", "normalizedKey", "=", "key", ".", "substr", "(", "fieldPrefix", ".", "length", ")", ";", "data", "[", "normalizedKey", "]", "=", "g", "(", "entry", "[", "key", "]", ")", ";", "}", ")", ";", "return", "data", ";", "}" ]
Converts 'get worksheet entry' response to domain specific data. @param entry @param fieldPrefix @returns {*}
[ "Converts", "get", "worksheet", "entry", "response", "to", "domain", "specific", "data", "." ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L109-L127
37,223
tadam313/sheet-db
src/api/v3/converter.js
sheetInfoResponse
function sheetInfoResponse(rawData) { var feed = rawData.feed; return { title: g(feed.title), updated: g(feed.updated), workSheets: feed.entry.map(worksheetData), authors: feed.author.map(item => ({ name: g(item.name), email: g(item.email) })) }; }
javascript
function sheetInfoResponse(rawData) { var feed = rawData.feed; return { title: g(feed.title), updated: g(feed.updated), workSheets: feed.entry.map(worksheetData), authors: feed.author.map(item => ({ name: g(item.name), email: g(item.email) })) }; }
[ "function", "sheetInfoResponse", "(", "rawData", ")", "{", "var", "feed", "=", "rawData", ".", "feed", ";", "return", "{", "title", ":", "g", "(", "feed", ".", "title", ")", ",", "updated", ":", "g", "(", "feed", ".", "updated", ")", ",", "workSheets", ":", "feed", ".", "entry", ".", "map", "(", "worksheetData", ")", ",", "authors", ":", "feed", ".", "author", ".", "map", "(", "item", "=>", "(", "{", "name", ":", "g", "(", "item", ".", "name", ")", ",", "email", ":", "g", "(", "item", ".", "email", ")", "}", ")", ")", "}", ";", "}" ]
Converts 'sheet info' response to domain specific data. @param rawData @returns {*}
[ "Converts", "sheet", "info", "response", "to", "domain", "specific", "data", "." ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L135-L144
37,224
tadam313/sheet-db
src/api/v3/converter.js
workSheetInfoResponse
function workSheetInfoResponse(rawData) { if (typeof rawData === 'string') { rawData = JSON.parse(rawData); } return worksheetData(rawData.entry); }
javascript
function workSheetInfoResponse(rawData) { if (typeof rawData === 'string') { rawData = JSON.parse(rawData); } return worksheetData(rawData.entry); }
[ "function", "workSheetInfoResponse", "(", "rawData", ")", "{", "if", "(", "typeof", "rawData", "===", "'string'", ")", "{", "rawData", "=", "JSON", ".", "parse", "(", "rawData", ")", ";", "}", "return", "worksheetData", "(", "rawData", ".", "entry", ")", ";", "}" ]
Converts create worksheet result to domain specific data. @param rawData @returns {*}
[ "Converts", "create", "worksheet", "result", "to", "domain", "specific", "data", "." ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L152-L159
37,225
tadam313/sheet-db
src/api/v3/converter.js
queryResponse
function queryResponse(rawData) { var entry = rawData.feed.entry || []; return entry.map(function(item) { return worksheetEntry(item); }); }
javascript
function queryResponse(rawData) { var entry = rawData.feed.entry || []; return entry.map(function(item) { return worksheetEntry(item); }); }
[ "function", "queryResponse", "(", "rawData", ")", "{", "var", "entry", "=", "rawData", ".", "feed", ".", "entry", "||", "[", "]", ";", "return", "entry", ".", "map", "(", "function", "(", "item", ")", "{", "return", "worksheetEntry", "(", "item", ")", ";", "}", ")", ";", "}" ]
Converts the query results to domain specific data. @param rawData @returns {*}
[ "Converts", "the", "query", "results", "to", "domain", "specific", "data", "." ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L167-L172
37,226
tadam313/sheet-db
src/api/v3/converter.js
queryFieldNames
function queryFieldNames(rawData) { var entry = rawData.feed.entry || []; return entry.map(function(item) { var field = worksheetEntry(item, 'gs$'); field.cell = field.cell.replace(/_/g, ''); return field; }); }
javascript
function queryFieldNames(rawData) { var entry = rawData.feed.entry || []; return entry.map(function(item) { var field = worksheetEntry(item, 'gs$'); field.cell = field.cell.replace(/_/g, ''); return field; }); }
[ "function", "queryFieldNames", "(", "rawData", ")", "{", "var", "entry", "=", "rawData", ".", "feed", ".", "entry", "||", "[", "]", ";", "return", "entry", ".", "map", "(", "function", "(", "item", ")", "{", "var", "field", "=", "worksheetEntry", "(", "item", ",", "'gs$'", ")", ";", "field", ".", "cell", "=", "field", ".", "cell", ".", "replace", "(", "/", "_", "/", "g", ",", "''", ")", ";", "return", "field", ";", "}", ")", ";", "}" ]
Converts field names query response, used by schema operations @param rawData
[ "Converts", "field", "names", "query", "response", "used", "by", "schema", "operations" ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L179-L186
37,227
tadam313/sheet-db
src/api/v3/converter.js
createWorksheetRequest
function createWorksheetRequest(options) { options = options || {}; // TODO: needs to handle overflow cases and create ore dynamically var rowCount = util.coerceNumber(options.rowCount || 5000); var colCount = util.coerceNumber(options.colCount || 50); options.rowCount = Math.max(rowCount, 10); options.colCount = Math.max(colCount, 10); var xw = createXMLWriter() .startElement('title') .text(options.title) .endElement() .startElement('gs:rowCount') .text(options.rowCount) .endElement() .startElement('gs:colCount') .text(options.colCount) .endElement() .endElement(); return xw.toString(); }
javascript
function createWorksheetRequest(options) { options = options || {}; // TODO: needs to handle overflow cases and create ore dynamically var rowCount = util.coerceNumber(options.rowCount || 5000); var colCount = util.coerceNumber(options.colCount || 50); options.rowCount = Math.max(rowCount, 10); options.colCount = Math.max(colCount, 10); var xw = createXMLWriter() .startElement('title') .text(options.title) .endElement() .startElement('gs:rowCount') .text(options.rowCount) .endElement() .startElement('gs:colCount') .text(options.colCount) .endElement() .endElement(); return xw.toString(); }
[ "function", "createWorksheetRequest", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "// TODO: needs to handle overflow cases and create ore dynamically", "var", "rowCount", "=", "util", ".", "coerceNumber", "(", "options", ".", "rowCount", "||", "5000", ")", ";", "var", "colCount", "=", "util", ".", "coerceNumber", "(", "options", ".", "colCount", "||", "50", ")", ";", "options", ".", "rowCount", "=", "Math", ".", "max", "(", "rowCount", ",", "10", ")", ";", "options", ".", "colCount", "=", "Math", ".", "max", "(", "colCount", ",", "10", ")", ";", "var", "xw", "=", "createXMLWriter", "(", ")", ".", "startElement", "(", "'title'", ")", ".", "text", "(", "options", ".", "title", ")", ".", "endElement", "(", ")", ".", "startElement", "(", "'gs:rowCount'", ")", ".", "text", "(", "options", ".", "rowCount", ")", ".", "endElement", "(", ")", ".", "startElement", "(", "'gs:colCount'", ")", ".", "text", "(", "options", ".", "colCount", ")", ".", "endElement", "(", ")", ".", "endElement", "(", ")", ";", "return", "xw", ".", "toString", "(", ")", ";", "}" ]
Creates worksheet request payload. @param options @returns {*}
[ "Creates", "worksheet", "request", "payload", "." ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L194-L217
37,228
tadam313/sheet-db
src/api/v3/converter.js
createEntryRequest
function createEntryRequest(entry) { var xw = createXMLWriter(true); Object.keys(entry).forEach(function(key) { xw = xw.startElement('gsx:' + key) .text(util.coerceNumber(entry[key]).toString()) .endElement(); }); return xw.endElement().toString(); }
javascript
function createEntryRequest(entry) { var xw = createXMLWriter(true); Object.keys(entry).forEach(function(key) { xw = xw.startElement('gsx:' + key) .text(util.coerceNumber(entry[key]).toString()) .endElement(); }); return xw.endElement().toString(); }
[ "function", "createEntryRequest", "(", "entry", ")", "{", "var", "xw", "=", "createXMLWriter", "(", "true", ")", ";", "Object", ".", "keys", "(", "entry", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "xw", "=", "xw", ".", "startElement", "(", "'gsx:'", "+", "key", ")", ".", "text", "(", "util", ".", "coerceNumber", "(", "entry", "[", "key", "]", ")", ".", "toString", "(", ")", ")", ".", "endElement", "(", ")", ";", "}", ")", ";", "return", "xw", ".", "endElement", "(", ")", ".", "toString", "(", ")", ";", "}" ]
Creates 'create entry' request payload. @param entry @returns {*}
[ "Creates", "create", "entry", "request", "payload", "." ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L225-L235
37,229
tadam313/sheet-db
src/api/v3/converter.js
updateEntryRequest
function updateEntryRequest(entry) { var xw = createXMLWriter(true); Object.keys(entry) .filter(function(key) { // filter out internal properties return key.indexOf('_') !== 0; }) .forEach(function(key) { xw = xw.startElement('gsx:' + key) .text(util.coerceNumber(entry[key]).toString()) .endElement(); }); return xw.endElement().toString(); }
javascript
function updateEntryRequest(entry) { var xw = createXMLWriter(true); Object.keys(entry) .filter(function(key) { // filter out internal properties return key.indexOf('_') !== 0; }) .forEach(function(key) { xw = xw.startElement('gsx:' + key) .text(util.coerceNumber(entry[key]).toString()) .endElement(); }); return xw.endElement().toString(); }
[ "function", "updateEntryRequest", "(", "entry", ")", "{", "var", "xw", "=", "createXMLWriter", "(", "true", ")", ";", "Object", ".", "keys", "(", "entry", ")", ".", "filter", "(", "function", "(", "key", ")", "{", "// filter out internal properties", "return", "key", ".", "indexOf", "(", "'_'", ")", "!==", "0", ";", "}", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "xw", "=", "xw", ".", "startElement", "(", "'gsx:'", "+", "key", ")", ".", "text", "(", "util", ".", "coerceNumber", "(", "entry", "[", "key", "]", ")", ".", "toString", "(", ")", ")", ".", "endElement", "(", ")", ";", "}", ")", ";", "return", "xw", ".", "endElement", "(", ")", ".", "toString", "(", ")", ";", "}" ]
Creates an 'update entry' request payload @param entry @returns {*}
[ "Creates", "an", "update", "entry", "request", "payload" ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L243-L258
37,230
tadam313/sheet-db
src/api/v3/converter.js
createFieldRequest
function createFieldRequest(columnName, position) { if (util.isNaN(position) || position <= 0) { throw new TypeError('Position should be a number which is higher than one!'); } var xw = createXMLWriter(); xw = xw.startElement('gs:cell') .writeAttribute('row', 1) .writeAttribute('col', position) .writeAttribute('inputValue', columnName) .endElement(); return xw.endElement().toString(); }
javascript
function createFieldRequest(columnName, position) { if (util.isNaN(position) || position <= 0) { throw new TypeError('Position should be a number which is higher than one!'); } var xw = createXMLWriter(); xw = xw.startElement('gs:cell') .writeAttribute('row', 1) .writeAttribute('col', position) .writeAttribute('inputValue', columnName) .endElement(); return xw.endElement().toString(); }
[ "function", "createFieldRequest", "(", "columnName", ",", "position", ")", "{", "if", "(", "util", ".", "isNaN", "(", "position", ")", "||", "position", "<=", "0", ")", "{", "throw", "new", "TypeError", "(", "'Position should be a number which is higher than one!'", ")", ";", "}", "var", "xw", "=", "createXMLWriter", "(", ")", ";", "xw", "=", "xw", ".", "startElement", "(", "'gs:cell'", ")", ".", "writeAttribute", "(", "'row'", ",", "1", ")", ".", "writeAttribute", "(", "'col'", ",", "position", ")", ".", "writeAttribute", "(", "'inputValue'", ",", "columnName", ")", ".", "endElement", "(", ")", ";", "return", "xw", ".", "endElement", "(", ")", ".", "toString", "(", ")", ";", "}" ]
Creates the 'create column' request payload @param columnName @param position @returns {*}
[ "Creates", "the", "create", "column", "request", "payload" ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L268-L283
37,231
doda/immutable-lodash
src/immutable-lodash.js
chunk
function chunk(iterable, size=1) { let current = 0 if (_.isEmpty(iterable)) { return iterable } let result = List() while (current < iterable.size) { result = result.push(iterable.slice(current, current + size)) current += size } return result }
javascript
function chunk(iterable, size=1) { let current = 0 if (_.isEmpty(iterable)) { return iterable } let result = List() while (current < iterable.size) { result = result.push(iterable.slice(current, current + size)) current += size } return result }
[ "function", "chunk", "(", "iterable", ",", "size", "=", "1", ")", "{", "let", "current", "=", "0", "if", "(", "_", ".", "isEmpty", "(", "iterable", ")", ")", "{", "return", "iterable", "}", "let", "result", "=", "List", "(", ")", "while", "(", "current", "<", "iterable", ".", "size", ")", "{", "result", "=", "result", ".", "push", "(", "iterable", ".", "slice", "(", "current", ",", "current", "+", "size", ")", ")", "current", "+=", "size", "}", "return", "result", "}" ]
Creates an iterable of elements split into groups the length of `size`. If `iterable` can't be split evenly, the final chunk will be the remaining elements. @static @memberOf _ @category Iterable @param {Iterable} iterable The iterable to process. @param {number} [size=1] The length of each chunk @returns {Iterable} Returns the new iterable of chunks. @example let list = ['a', 'b', 'c', 'd'] _.chunk(list, 2) // => [['a', 'b'], ['c', 'd']] _.chunk(list, 3) // => [['a', 'b', 'c'], ['d']]
[ "Creates", "an", "iterable", "of", "elements", "split", "into", "groups", "the", "length", "of", "size", ".", "If", "iterable", "can", "t", "be", "split", "evenly", "the", "final", "chunk", "will", "be", "the", "remaining", "elements", "." ]
f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09
https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L46-L57
37,232
doda/immutable-lodash
src/immutable-lodash.js
difference
function difference(iterable, values) { const valueSet = Set(values) return iterable.filterNot((x) => valueSet.has(x)) }
javascript
function difference(iterable, values) { const valueSet = Set(values) return iterable.filterNot((x) => valueSet.has(x)) }
[ "function", "difference", "(", "iterable", ",", "values", ")", "{", "const", "valueSet", "=", "Set", "(", "values", ")", "return", "iterable", ".", "filterNot", "(", "(", "x", ")", "=>", "valueSet", ".", "has", "(", "x", ")", ")", "}" ]
Creates an Iterable of `iterable` values not included in the other given iterables The order of result values is determined by the order they occur in the first iterable. @static @memberOf _ @category Iterable @param {Iterable} iterable The iterable to inspect. @param {...Iterable} [values] The values to exclude. @returns {Iterable} Returns the iterable of filtered values. @see _.without, _.xor @example _.difference([2, 1], [2, 3]) // => [1]
[ "Creates", "an", "Iterable", "of", "iterable", "values", "not", "included", "in", "the", "other", "given", "iterables", "The", "order", "of", "result", "values", "is", "determined", "by", "the", "order", "they", "occur", "in", "the", "first", "iterable", "." ]
f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09
https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L117-L120
37,233
doda/immutable-lodash
src/immutable-lodash.js
fill
function fill(iterable, value, start=0, end=iterable.size) { let num = end - start return iterable.splice(start, num, ...Repeat(value, num)) }
javascript
function fill(iterable, value, start=0, end=iterable.size) { let num = end - start return iterable.splice(start, num, ...Repeat(value, num)) }
[ "function", "fill", "(", "iterable", ",", "value", ",", "start", "=", "0", ",", "end", "=", "iterable", ".", "size", ")", "{", "let", "num", "=", "end", "-", "start", "return", "iterable", ".", "splice", "(", "start", ",", "num", ",", "...", "Repeat", "(", "value", ",", "num", ")", ")", "}" ]
Fills elements of `iterable` with `value` from `start` up to, but not including, `end`. @static @memberOf _ @category Iterable @param {Iterable} iterable The iterable to fill. @param {*} value The value to fill `iterable` with. @param {number} [start=0] The start position. @param {number} [end=iterable.size] The end position. @returns {Iterable} Returns `iterable`. @example let list = [1, 2, 3] _.fill(list, 'a') // => ['a', 'a', 'a'] _.fill([4, 6, 8, 10], '*', 1, 3) // => [4, '*', '*', 10]
[ "Fills", "elements", "of", "iterable", "with", "value", "from", "start", "up", "to", "but", "not", "including", "end", "." ]
f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09
https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L170-L173
37,234
doda/immutable-lodash
src/immutable-lodash.js
intersection
function intersection(...iterables) { if (_.isEmpty(iterables)) return OrderedSet() let result = OrderedSet(iterables[0]) for (let iterable of iterables.slice(1)) { result = result.intersect(iterable) } return result.toSeq() }
javascript
function intersection(...iterables) { if (_.isEmpty(iterables)) return OrderedSet() let result = OrderedSet(iterables[0]) for (let iterable of iterables.slice(1)) { result = result.intersect(iterable) } return result.toSeq() }
[ "function", "intersection", "(", "...", "iterables", ")", "{", "if", "(", "_", ".", "isEmpty", "(", "iterables", ")", ")", "return", "OrderedSet", "(", ")", "let", "result", "=", "OrderedSet", "(", "iterables", "[", "0", "]", ")", "for", "(", "let", "iterable", "of", "iterables", ".", "slice", "(", "1", ")", ")", "{", "result", "=", "result", ".", "intersect", "(", "iterable", ")", "}", "return", "result", ".", "toSeq", "(", ")", "}" ]
Returns a sequence of unique values that are included in all given iterables The order of result values is determined by the order they occur in the first iterable. @static @memberOf _ @category Iterable @param {...Iterable} [iterables] The iterables to inspect. @returns {Iterable} Returns the new iterable of intersecting values. @example _.intersection([2, 1], [2, 3]) // => Seq [2]
[ "Returns", "a", "sequence", "of", "unique", "values", "that", "are", "included", "in", "all", "given", "iterables", "The", "order", "of", "result", "values", "is", "determined", "by", "the", "order", "they", "occur", "in", "the", "first", "iterable", "." ]
f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09
https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L190-L198
37,235
doda/immutable-lodash
src/immutable-lodash.js
sample
function sample(iterable) { let index = lodash.random(0, iterable.size - 1) return iterable.get(index) }
javascript
function sample(iterable) { let index = lodash.random(0, iterable.size - 1) return iterable.get(index) }
[ "function", "sample", "(", "iterable", ")", "{", "let", "index", "=", "lodash", ".", "random", "(", "0", ",", "iterable", ".", "size", "-", "1", ")", "return", "iterable", ".", "get", "(", "index", ")", "}" ]
Gets a random element from `iterable`. @static @memberOf _ @category iterable @param {Iterable} iterable The iterable to sample. @returns {*} Returns the random element. @example _.sample([1, 2, 3, 4]) // => 2
[ "Gets", "a", "random", "element", "from", "iterable", "." ]
f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09
https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L515-L518
37,236
doda/immutable-lodash
src/immutable-lodash.js
sampleSize
function sampleSize(iterable, n=1) { let index = -1 let result = List(iterable) const length = result.size const lastIndex = length - 1 while (++index < n) { const rand = lodash.random(index, lastIndex) const value = result.get(rand) result = result.set(rand, result.get(index)) result = result.set(index, value) } return result.slice(0, Math.min(length, n)) }
javascript
function sampleSize(iterable, n=1) { let index = -1 let result = List(iterable) const length = result.size const lastIndex = length - 1 while (++index < n) { const rand = lodash.random(index, lastIndex) const value = result.get(rand) result = result.set(rand, result.get(index)) result = result.set(index, value) } return result.slice(0, Math.min(length, n)) }
[ "function", "sampleSize", "(", "iterable", ",", "n", "=", "1", ")", "{", "let", "index", "=", "-", "1", "let", "result", "=", "List", "(", "iterable", ")", "const", "length", "=", "result", ".", "size", "const", "lastIndex", "=", "length", "-", "1", "while", "(", "++", "index", "<", "n", ")", "{", "const", "rand", "=", "lodash", ".", "random", "(", "index", ",", "lastIndex", ")", "const", "value", "=", "result", ".", "get", "(", "rand", ")", "result", "=", "result", ".", "set", "(", "rand", ",", "result", ".", "get", "(", "index", ")", ")", "result", "=", "result", ".", "set", "(", "index", ",", "value", ")", "}", "return", "result", ".", "slice", "(", "0", ",", "Math", ".", "min", "(", "length", ",", "n", ")", ")", "}" ]
Gets `n` random elements at unique keys from `iterable` up to the size of `iterable`. @static @memberOf _ @category iterable @param {Iterable} iterable The iterable to sample. @param {number} [n=1] The number of elements to sample. @returns {List} Returns the random elements. @example _.sampleSize([1, 2, 3], 2) // => List [3, 1] _.sampleSize([1, 2, 3], 4) // => List [2, 3, 1]
[ "Gets", "n", "random", "elements", "at", "unique", "keys", "from", "iterable", "up", "to", "the", "size", "of", "iterable", "." ]
f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09
https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L538-L553
37,237
doda/immutable-lodash
src/immutable-lodash.js
at
function at(map, paths) { return paths.map((path) => { return map.getIn(splitPath(path)) }) }
javascript
function at(map, paths) { return paths.map((path) => { return map.getIn(splitPath(path)) }) }
[ "function", "at", "(", "map", ",", "paths", ")", "{", "return", "paths", ".", "map", "(", "(", "path", ")", "=>", "{", "return", "map", ".", "getIn", "(", "splitPath", "(", "path", ")", ")", "}", ")", "}" ]
Creates an array of values corresponding to `paths` of `iterable`. @static @memberOf _ @category Iterable @param {Iterable} iterable The iterable to iterate over. @param {...(string|string[])} [paths] The property paths of elements to pick. @returns {Iterable} Returns the picked values. @example let iterable = { 'a': [{ 'b': { 'c': 3 } }, 4] } _.at(iterable, ['a[0].b.c', 'a[1]']) // => [3, 4]
[ "Creates", "an", "array", "of", "values", "corresponding", "to", "paths", "of", "iterable", "." ]
f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09
https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L596-L600
37,238
doda/immutable-lodash
src/immutable-lodash.js
defaults
function defaults(map, ...sources) { return map.mergeWith((prev, next) => { return prev === undefined ? next : prev }, ...sources) }
javascript
function defaults(map, ...sources) { return map.mergeWith((prev, next) => { return prev === undefined ? next : prev }, ...sources) }
[ "function", "defaults", "(", "map", ",", "...", "sources", ")", "{", "return", "map", ".", "mergeWith", "(", "(", "prev", ",", "next", ")", "=>", "{", "return", "prev", "===", "undefined", "?", "next", ":", "prev", "}", ",", "...", "sources", ")", "}" ]
Creates new iterable with all properties of source iterables that resolve to `undefined`. Source iterables are applied from left to right. Once a key is set, additional values of the same key are ignored. @static @memberOf _ @category Iterable @param {Iterable} iterable The destination iterable. @param {...Iterable} [sources] The source iterables. @returns {Iterable} Returns `iterable`. @see _.defaultsDeep @example _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }) // => { 'a': 1, 'b': 2 }
[ "Creates", "new", "iterable", "with", "all", "properties", "of", "source", "iterables", "that", "resolve", "to", "undefined", ".", "Source", "iterables", "are", "applied", "from", "left", "to", "right", ".", "Once", "a", "key", "is", "set", "additional", "values", "of", "the", "same", "key", "are", "ignored", "." ]
f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09
https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L620-L624
37,239
doda/immutable-lodash
src/immutable-lodash.js
defaultsDeep
function defaultsDeep(map, ...sources) { return map.mergeDeepWith((prev, next) => { return prev === undefined ? next : prev }, ...sources) }
javascript
function defaultsDeep(map, ...sources) { return map.mergeDeepWith((prev, next) => { return prev === undefined ? next : prev }, ...sources) }
[ "function", "defaultsDeep", "(", "map", ",", "...", "sources", ")", "{", "return", "map", ".", "mergeDeepWith", "(", "(", "prev", ",", "next", ")", "=>", "{", "return", "prev", "===", "undefined", "?", "next", ":", "prev", "}", ",", "...", "sources", ")", "}" ]
This method is like `_.defaults` except that it recursively assigns default properties. @static @memberOf _ @category Iterable @param {Iterable} iterable The destination iterable. @param {...Iterable} [sources] The source iterables. @returns {Iterable} Returns `iterable`. @see _.defaults @example _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }) // => { 'a': { 'b': 2, 'c': 3 } }
[ "This", "method", "is", "like", "_", ".", "defaults", "except", "that", "it", "recursively", "assigns", "default", "properties", "." ]
f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09
https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L643-L647
37,240
doda/immutable-lodash
src/immutable-lodash.js
pick
function pick(map, props) { props = Set(props) return _.pickBy(map, (key) => { return props.has(key) }) }
javascript
function pick(map, props) { props = Set(props) return _.pickBy(map, (key) => { return props.has(key) }) }
[ "function", "pick", "(", "map", ",", "props", ")", "{", "props", "=", "Set", "(", "props", ")", "return", "_", ".", "pickBy", "(", "map", ",", "(", "key", ")", "=>", "{", "return", "props", ".", "has", "(", "key", ")", "}", ")", "}" ]
Creates an iterable composed of the picked `iterable` properties. @static @memberOf _ @category Iterable @param {Iterable} iterable The source iterable. @param {...(string|string[])} [props] The property identifiers to pick. @returns {Iterable} Returns the new iterable. @example let iterable = { 'a': 1, 'b': '2', 'c': 3 } _.pick(iterable, ['a', 'c']) // => { 'a': 1, 'c': 3 }
[ "Creates", "an", "iterable", "composed", "of", "the", "picked", "iterable", "properties", "." ]
f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09
https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L743-L748
37,241
tadam313/sheet-db
src/util.js
coerceNumber
function coerceNumber(value) { if (typeof value === 'number') { return value; } let isfloat = /^\d*(\.|,)\d*$/; if (isfloat.test(value)) { value = value.replace(',', '.'); } let numberValue = Number(value); return numberValue == value || !value ? numberValue : value }
javascript
function coerceNumber(value) { if (typeof value === 'number') { return value; } let isfloat = /^\d*(\.|,)\d*$/; if (isfloat.test(value)) { value = value.replace(',', '.'); } let numberValue = Number(value); return numberValue == value || !value ? numberValue : value }
[ "function", "coerceNumber", "(", "value", ")", "{", "if", "(", "typeof", "value", "===", "'number'", ")", "{", "return", "value", ";", "}", "let", "isfloat", "=", "/", "^\\d*(\\.|,)\\d*$", "/", ";", "if", "(", "isfloat", ".", "test", "(", "value", ")", ")", "{", "value", "=", "value", ".", "replace", "(", "','", ",", "'.'", ")", ";", "}", "let", "numberValue", "=", "Number", "(", "value", ")", ";", "return", "numberValue", "==", "value", "||", "!", "value", "?", "numberValue", ":", "value", "}" ]
Tries to convert the value to number. Since we can not decide the type of the data coming back from the spreadsheet, we try to coerce it to number. Finally we check the coerced value whether is equals to the original value. This check assure that the coercion won't break anything. Note the 'weak equality' operator here is really important. @param {*} value @returns {*}
[ "Tries", "to", "convert", "the", "value", "to", "number", ".", "Since", "we", "can", "not", "decide", "the", "type", "of", "the", "data", "coming", "back", "from", "the", "spreadsheet", "we", "try", "to", "coerce", "it", "to", "number", ".", "Finally", "we", "check", "the", "coerced", "value", "whether", "is", "equals", "to", "the", "original", "value", ".", "This", "check", "assure", "that", "the", "coercion", "won", "t", "break", "anything", ".", "Note", "the", "weak", "equality", "operator", "here", "is", "really", "important", "." ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/util.js#L25-L38
37,242
tadam313/sheet-db
src/util.js
coerceDate
function coerceDate(value) { if (value instanceof Date) { return value; } let timestamp = Date.parse(value); if (!isNaN(timestamp)) { return new Date(timestamp); } return value; }
javascript
function coerceDate(value) { if (value instanceof Date) { return value; } let timestamp = Date.parse(value); if (!isNaN(timestamp)) { return new Date(timestamp); } return value; }
[ "function", "coerceDate", "(", "value", ")", "{", "if", "(", "value", "instanceof", "Date", ")", "{", "return", "value", ";", "}", "let", "timestamp", "=", "Date", ".", "parse", "(", "value", ")", ";", "if", "(", "!", "isNaN", "(", "timestamp", ")", ")", "{", "return", "new", "Date", "(", "timestamp", ")", ";", "}", "return", "value", ";", "}" ]
Tries to convert the value to Date. First it try to parse it and if it gets a number, the Date constructor will be fed with that. @param {*} value @returns {*}
[ "Tries", "to", "convert", "the", "value", "to", "Date", ".", "First", "it", "try", "to", "parse", "it", "and", "if", "it", "gets", "a", "number", "the", "Date", "constructor", "will", "be", "fed", "with", "that", "." ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/util.js#L47-L59
37,243
tadam313/sheet-db
src/util.js
coerceValue
function coerceValue(value) { let numValue = coerceNumber(value); if (numValue === value) { return coerceDate(value); } return numValue; }
javascript
function coerceValue(value) { let numValue = coerceNumber(value); if (numValue === value) { return coerceDate(value); } return numValue; }
[ "function", "coerceValue", "(", "value", ")", "{", "let", "numValue", "=", "coerceNumber", "(", "value", ")", ";", "if", "(", "numValue", "===", "value", ")", "{", "return", "coerceDate", "(", "value", ")", ";", "}", "return", "numValue", ";", "}" ]
We can not decide the type of the data coming back from the spreadsheet, we try to coerce it to Date or Number. If both "failes" it will leave the value unchanged. @param {*} value @returns {*}
[ "We", "can", "not", "decide", "the", "type", "of", "the", "data", "coming", "back", "from", "the", "spreadsheet", "we", "try", "to", "coerce", "it", "to", "Date", "or", "Number", ".", "If", "both", "failes", "it", "will", "leave", "the", "value", "unchanged", "." ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/util.js#L68-L77
37,244
tadam313/sheet-db
src/util.js
getArrayFields
function getArrayFields(array) { return (array || []).reduce((old, current) => { arrayDiff(Object.keys(current), old) .forEach(key => old.push(key)); return old; }, []); }
javascript
function getArrayFields(array) { return (array || []).reduce((old, current) => { arrayDiff(Object.keys(current), old) .forEach(key => old.push(key)); return old; }, []); }
[ "function", "getArrayFields", "(", "array", ")", "{", "return", "(", "array", "||", "[", "]", ")", ".", "reduce", "(", "(", "old", ",", "current", ")", "=>", "{", "arrayDiff", "(", "Object", ".", "keys", "(", "current", ")", ",", "old", ")", ".", "forEach", "(", "key", "=>", "old", ".", "push", "(", "key", ")", ")", ";", "return", "old", ";", "}", ",", "[", "]", ")", ";", "}" ]
Retrieves every field in the array of objects. These are collected in a Hash-map which means they are unique. @param {array} array Subject of the operation @returns {array}
[ "Retrieves", "every", "field", "in", "the", "array", "of", "objects", ".", "These", "are", "collected", "in", "a", "Hash", "-", "map", "which", "means", "they", "are", "unique", "." ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/util.js#L85-L92
37,245
tadam313/sheet-db
src/util.js
arrayDiff
function arrayDiff(arrayTarget, arrayCheck) { if (!(arrayTarget instanceof Array) || !(arrayCheck instanceof Array)) { throw new Error('Both objects have to be an array'); } return arrayTarget.filter(item => !~arrayCheck.indexOf(item)); }
javascript
function arrayDiff(arrayTarget, arrayCheck) { if (!(arrayTarget instanceof Array) || !(arrayCheck instanceof Array)) { throw new Error('Both objects have to be an array'); } return arrayTarget.filter(item => !~arrayCheck.indexOf(item)); }
[ "function", "arrayDiff", "(", "arrayTarget", ",", "arrayCheck", ")", "{", "if", "(", "!", "(", "arrayTarget", "instanceof", "Array", ")", "||", "!", "(", "arrayCheck", "instanceof", "Array", ")", ")", "{", "throw", "new", "Error", "(", "'Both objects have to be an array'", ")", ";", "}", "return", "arrayTarget", ".", "filter", "(", "item", "=>", "!", "~", "arrayCheck", ".", "indexOf", "(", "item", ")", ")", ";", "}" ]
Determines which elements from arrayTarget are not present in arrayCheck. @param {array} arrayTarget Target of the check @param {array} arrayCheck Subject of the check @returns {array}
[ "Determines", "which", "elements", "from", "arrayTarget", "are", "not", "present", "in", "arrayCheck", "." ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/util.js#L101-L107
37,246
tadam313/sheet-db
src/util.js
copyMetaProperties
function copyMetaProperties(dest, source) { if (!dest || !source) { return dest; } let fields = ['_id', '_updated']; for (let field of fields) { dest[field] = source[field]; } return dest; }
javascript
function copyMetaProperties(dest, source) { if (!dest || !source) { return dest; } let fields = ['_id', '_updated']; for (let field of fields) { dest[field] = source[field]; } return dest; }
[ "function", "copyMetaProperties", "(", "dest", ",", "source", ")", "{", "if", "(", "!", "dest", "||", "!", "source", ")", "{", "return", "dest", ";", "}", "let", "fields", "=", "[", "'_id'", ",", "'_updated'", "]", ";", "for", "(", "let", "field", "of", "fields", ")", "{", "dest", "[", "field", "]", "=", "source", "[", "field", "]", ";", "}", "return", "dest", ";", "}" ]
Grab meta google drive meta properties from source and add those to dest. @param dest @param source
[ "Grab", "meta", "google", "drive", "meta", "properties", "from", "source", "and", "add", "those", "to", "dest", "." ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/util.js#L124-L136
37,247
GitbookIO/plugin-styles-sass
index.js
renderSASS
function renderSASS(input, output) { var d = Q.defer(); sass.render({ file: input }, function (e, out) { if (e) return d.reject(e); fs.writeFileSync(output, out.css); d.resolve(); }); return d.promise; }
javascript
function renderSASS(input, output) { var d = Q.defer(); sass.render({ file: input }, function (e, out) { if (e) return d.reject(e); fs.writeFileSync(output, out.css); d.resolve(); }); return d.promise; }
[ "function", "renderSASS", "(", "input", ",", "output", ")", "{", "var", "d", "=", "Q", ".", "defer", "(", ")", ";", "sass", ".", "render", "(", "{", "file", ":", "input", "}", ",", "function", "(", "e", ",", "out", ")", "{", "if", "(", "e", ")", "return", "d", ".", "reject", "(", "e", ")", ";", "fs", ".", "writeFileSync", "(", "output", ",", "out", ".", "css", ")", ";", "d", ".", "resolve", "(", ")", ";", "}", ")", ";", "return", "d", ".", "promise", ";", "}" ]
Compile a SASS file into a css
[ "Compile", "a", "SASS", "file", "into", "a", "css" ]
d073d9db46e6c669992b9ed98dc1a48f1483e6ce
https://github.com/GitbookIO/plugin-styles-sass/blob/d073d9db46e6c669992b9ed98dc1a48f1483e6ce/index.js#L8-L21
37,248
GitbookIO/plugin-styles-sass
index.js
function() { var book = this; var styles = book.config.get('styles'); return _.reduce(styles, function(prev, filename, type) { return prev.then(function() { var extension = path.extname(filename).toLowerCase(); if (extension != '.sass' && extension != '.scss') return; book.log.info.ln('compile sass file: ', filename); // Temporary CSS file var tmpfile = type+'-'+Date.now()+'.css'; // Replace config book.config.set('styles.'+type, tmpfile); return renderSASS( book.resolve(filename), path.resolve(book.options.output, tmpfile) ); }); }, Q()); }
javascript
function() { var book = this; var styles = book.config.get('styles'); return _.reduce(styles, function(prev, filename, type) { return prev.then(function() { var extension = path.extname(filename).toLowerCase(); if (extension != '.sass' && extension != '.scss') return; book.log.info.ln('compile sass file: ', filename); // Temporary CSS file var tmpfile = type+'-'+Date.now()+'.css'; // Replace config book.config.set('styles.'+type, tmpfile); return renderSASS( book.resolve(filename), path.resolve(book.options.output, tmpfile) ); }); }, Q()); }
[ "function", "(", ")", "{", "var", "book", "=", "this", ";", "var", "styles", "=", "book", ".", "config", ".", "get", "(", "'styles'", ")", ";", "return", "_", ".", "reduce", "(", "styles", ",", "function", "(", "prev", ",", "filename", ",", "type", ")", "{", "return", "prev", ".", "then", "(", "function", "(", ")", "{", "var", "extension", "=", "path", ".", "extname", "(", "filename", ")", ".", "toLowerCase", "(", ")", ";", "if", "(", "extension", "!=", "'.sass'", "&&", "extension", "!=", "'.scss'", ")", "return", ";", "book", ".", "log", ".", "info", ".", "ln", "(", "'compile sass file: '", ",", "filename", ")", ";", "// Temporary CSS file", "var", "tmpfile", "=", "type", "+", "'-'", "+", "Date", ".", "now", "(", ")", "+", "'.css'", ";", "// Replace config", "book", ".", "config", ".", "set", "(", "'styles.'", "+", "type", ",", "tmpfile", ")", ";", "return", "renderSASS", "(", "book", ".", "resolve", "(", "filename", ")", ",", "path", ".", "resolve", "(", "book", ".", "options", ".", "output", ",", "tmpfile", ")", ")", ";", "}", ")", ";", "}", ",", "Q", "(", ")", ")", ";", "}" ]
Compile sass as CSS
[ "Compile", "sass", "as", "CSS" ]
d073d9db46e6c669992b9ed98dc1a48f1483e6ce
https://github.com/GitbookIO/plugin-styles-sass/blob/d073d9db46e6c669992b9ed98dc1a48f1483e6ce/index.js#L26-L50
37,249
switer/muxjs
lib/keypath.js
_keyPathNormalize
function _keyPathNormalize(kp) { return new String(kp).replace(/\[([^\[\]]+)\]/g, function(m, k) { return '.' + k.replace(/^["']|["']$/g, '') }) }
javascript
function _keyPathNormalize(kp) { return new String(kp).replace(/\[([^\[\]]+)\]/g, function(m, k) { return '.' + k.replace(/^["']|["']$/g, '') }) }
[ "function", "_keyPathNormalize", "(", "kp", ")", "{", "return", "new", "String", "(", "kp", ")", ".", "replace", "(", "/", "\\[([^\\[\\]]+)\\]", "/", "g", ",", "function", "(", "m", ",", "k", ")", "{", "return", "'.'", "+", "k", ".", "replace", "(", "/", "^[\"']|[\"']$", "/", "g", ",", "''", ")", "}", ")", "}" ]
normalize all access ways into dot access @example "person.books[1].title" --> "person.books.1.title"
[ "normalize", "all", "access", "ways", "into", "dot", "access" ]
bc272efa32572c63be813bb7ce083879c6dc7266
https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/keypath.js#L7-L11
37,250
switer/muxjs
lib/keypath.js
_set
function _set(obj, keypath, value, hook) { var parts = _keyPathNormalize(keypath).split('.') var last = parts.pop() var dest = obj parts.forEach(function(key) { // Still set to non-object, just throw that error dest = dest[key] }) if (hook) { // hook proxy set value hook(dest, last, value) } else { dest[last] = value } return obj }
javascript
function _set(obj, keypath, value, hook) { var parts = _keyPathNormalize(keypath).split('.') var last = parts.pop() var dest = obj parts.forEach(function(key) { // Still set to non-object, just throw that error dest = dest[key] }) if (hook) { // hook proxy set value hook(dest, last, value) } else { dest[last] = value } return obj }
[ "function", "_set", "(", "obj", ",", "keypath", ",", "value", ",", "hook", ")", "{", "var", "parts", "=", "_keyPathNormalize", "(", "keypath", ")", ".", "split", "(", "'.'", ")", "var", "last", "=", "parts", ".", "pop", "(", ")", "var", "dest", "=", "obj", "parts", ".", "forEach", "(", "function", "(", "key", ")", "{", "// Still set to non-object, just throw that error", "dest", "=", "dest", "[", "key", "]", "}", ")", "if", "(", "hook", ")", "{", "// hook proxy set value", "hook", "(", "dest", ",", "last", ",", "value", ")", "}", "else", "{", "dest", "[", "last", "]", "=", "value", "}", "return", "obj", "}" ]
set value to object by keypath
[ "set", "value", "to", "object", "by", "keypath" ]
bc272efa32572c63be813bb7ce083879c6dc7266
https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/keypath.js#L15-L30
37,251
switer/muxjs
lib/keypath.js
_get
function _get(obj, keypath) { var parts = _keyPathNormalize(keypath).split('.') var dest = obj parts.forEach(function(key) { if (isNon(dest)) return !(dest = undf()) dest = dest[key] }) return dest }
javascript
function _get(obj, keypath) { var parts = _keyPathNormalize(keypath).split('.') var dest = obj parts.forEach(function(key) { if (isNon(dest)) return !(dest = undf()) dest = dest[key] }) return dest }
[ "function", "_get", "(", "obj", ",", "keypath", ")", "{", "var", "parts", "=", "_keyPathNormalize", "(", "keypath", ")", ".", "split", "(", "'.'", ")", "var", "dest", "=", "obj", "parts", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "isNon", "(", "dest", ")", ")", "return", "!", "(", "dest", "=", "undf", "(", ")", ")", "dest", "=", "dest", "[", "key", "]", "}", ")", "return", "dest", "}" ]
get value of object by keypath
[ "get", "value", "of", "object", "by", "keypath" ]
bc272efa32572c63be813bb7ce083879c6dc7266
https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/keypath.js#L43-L51
37,252
switer/muxjs
lib/keypath.js
_join
function _join(pre, tail) { var _hasBegin = !!pre if(!_hasBegin) pre = '' if (/^\[.*\]$/.exec(tail)) return pre + tail else if (typeof(tail) == 'number') return pre + '[' + tail + ']' else if (_hasBegin) return pre + '.' + tail else return tail }
javascript
function _join(pre, tail) { var _hasBegin = !!pre if(!_hasBegin) pre = '' if (/^\[.*\]$/.exec(tail)) return pre + tail else if (typeof(tail) == 'number') return pre + '[' + tail + ']' else if (_hasBegin) return pre + '.' + tail else return tail }
[ "function", "_join", "(", "pre", ",", "tail", ")", "{", "var", "_hasBegin", "=", "!", "!", "pre", "if", "(", "!", "_hasBegin", ")", "pre", "=", "''", "if", "(", "/", "^\\[.*\\]$", "/", ".", "exec", "(", "tail", ")", ")", "return", "pre", "+", "tail", "else", "if", "(", "typeof", "(", "tail", ")", "==", "'number'", ")", "return", "pre", "+", "'['", "+", "tail", "+", "']'", "else", "if", "(", "_hasBegin", ")", "return", "pre", "+", "'.'", "+", "tail", "else", "return", "tail", "}" ]
append path to a base path
[ "append", "path", "to", "a", "base", "path" ]
bc272efa32572c63be813bb7ce083879c6dc7266
https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/keypath.js#L56-L63
37,253
chip-js/fragments-js
src/util/toFragment.js
listToFragment
function listToFragment(list) { var fragment = document.createDocumentFragment(); for (var i = 0, l = list.length; i < l; i++) { // Use toFragment since this may be an array of text, a jQuery object of `<template>`s, etc. fragment.appendChild(toFragment(list[i])); if (l === list.length + 1) { // adjust for NodeLists which are live, they shrink as we pull nodes out of the DOM i--; l--; } } return fragment; }
javascript
function listToFragment(list) { var fragment = document.createDocumentFragment(); for (var i = 0, l = list.length; i < l; i++) { // Use toFragment since this may be an array of text, a jQuery object of `<template>`s, etc. fragment.appendChild(toFragment(list[i])); if (l === list.length + 1) { // adjust for NodeLists which are live, they shrink as we pull nodes out of the DOM i--; l--; } } return fragment; }
[ "function", "listToFragment", "(", "list", ")", "{", "var", "fragment", "=", "document", ".", "createDocumentFragment", "(", ")", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "list", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "// Use toFragment since this may be an array of text, a jQuery object of `<template>`s, etc.", "fragment", ".", "appendChild", "(", "toFragment", "(", "list", "[", "i", "]", ")", ")", ";", "if", "(", "l", "===", "list", ".", "length", "+", "1", ")", "{", "// adjust for NodeLists which are live, they shrink as we pull nodes out of the DOM", "i", "--", ";", "l", "--", ";", "}", "}", "return", "fragment", ";", "}" ]
Converts an HTMLCollection, NodeList, jQuery object, or array into a document fragment.
[ "Converts", "an", "HTMLCollection", "NodeList", "jQuery", "object", "or", "array", "into", "a", "document", "fragment", "." ]
5d613ea42c3823423efb01fce4ffef80c7f5ce0f
https://github.com/chip-js/fragments-js/blob/5d613ea42c3823423efb01fce4ffef80c7f5ce0f/src/util/toFragment.js#L50-L62
37,254
chip-js/fragments-js
src/util/toFragment.js
function(string) { if (!string) { var fragment = document.createDocumentFragment(); fragment.appendChild(document.createTextNode('')); return fragment; } var templateElement; templateElement = document.createElement('template'); templateElement.innerHTML = string; return templateElement.content; }
javascript
function(string) { if (!string) { var fragment = document.createDocumentFragment(); fragment.appendChild(document.createTextNode('')); return fragment; } var templateElement; templateElement = document.createElement('template'); templateElement.innerHTML = string; return templateElement.content; }
[ "function", "(", "string", ")", "{", "if", "(", "!", "string", ")", "{", "var", "fragment", "=", "document", ".", "createDocumentFragment", "(", ")", ";", "fragment", ".", "appendChild", "(", "document", ".", "createTextNode", "(", "''", ")", ")", ";", "return", "fragment", ";", "}", "var", "templateElement", ";", "templateElement", "=", "document", ".", "createElement", "(", "'template'", ")", ";", "templateElement", ".", "innerHTML", "=", "string", ";", "return", "templateElement", ".", "content", ";", "}" ]
Converts a string of HTML text into a document fragment.
[ "Converts", "a", "string", "of", "HTML", "text", "into", "a", "document", "fragment", "." ]
5d613ea42c3823423efb01fce4ffef80c7f5ce0f
https://github.com/chip-js/fragments-js/blob/5d613ea42c3823423efb01fce4ffef80c7f5ce0f/src/util/toFragment.js#L65-L75
37,255
nahody/postcss-export-vars
index.js
createFile
function createFile() { let fileContent = ''; /* * Customize data by type */ switch (options.type) { case 'js': fileContent += `'use strict';` + '\n'; for (let collectionKey in _variableCollection) { fileContent += `const ${collectionKey} = '${_variableCollection[collectionKey]}';` + '\n'; } if (_.endsWith(options.file, 'js') === false) options.file += '.js'; break; default: /* json */ fileContent = JSON.stringify(_variableCollection); if (_.endsWith(options.file, 'json') === false) options.file += '.json'; } /* * Write file */ return fs.writeFileSync(options.file, fileContent, 'utf8'); }
javascript
function createFile() { let fileContent = ''; /* * Customize data by type */ switch (options.type) { case 'js': fileContent += `'use strict';` + '\n'; for (let collectionKey in _variableCollection) { fileContent += `const ${collectionKey} = '${_variableCollection[collectionKey]}';` + '\n'; } if (_.endsWith(options.file, 'js') === false) options.file += '.js'; break; default: /* json */ fileContent = JSON.stringify(_variableCollection); if (_.endsWith(options.file, 'json') === false) options.file += '.json'; } /* * Write file */ return fs.writeFileSync(options.file, fileContent, 'utf8'); }
[ "function", "createFile", "(", ")", "{", "let", "fileContent", "=", "''", ";", "/*\n * Customize data by type\n */", "switch", "(", "options", ".", "type", ")", "{", "case", "'js'", ":", "fileContent", "+=", "`", "`", "+", "'\\n'", ";", "for", "(", "let", "collectionKey", "in", "_variableCollection", ")", "{", "fileContent", "+=", "`", "${", "collectionKey", "}", "${", "_variableCollection", "[", "collectionKey", "]", "}", "`", "+", "'\\n'", ";", "}", "if", "(", "_", ".", "endsWith", "(", "options", ".", "file", ",", "'js'", ")", "===", "false", ")", "options", ".", "file", "+=", "'.js'", ";", "break", ";", "default", ":", "/* json */", "fileContent", "=", "JSON", ".", "stringify", "(", "_variableCollection", ")", ";", "if", "(", "_", ".", "endsWith", "(", "options", ".", "file", ",", "'json'", ")", "===", "false", ")", "options", ".", "file", "+=", "'.json'", ";", "}", "/*\n * Write file\n */", "return", "fs", ".", "writeFileSync", "(", "options", ".", "file", ",", "fileContent", ",", "'utf8'", ")", ";", "}" ]
Create file.
[ "Create", "file", "." ]
ee6afbe1c6ec5091912e636b42a661a25e447d7d
https://github.com/nahody/postcss-export-vars/blob/ee6afbe1c6ec5091912e636b42a661a25e447d7d/index.js#L29-L56
37,256
nahody/postcss-export-vars
index.js
propertyMatch
function propertyMatch(property) { for (let count = 0; count < options.match.length; count++) { if (property.indexOf(options.match[count]) > -1) { return true; } } return false; }
javascript
function propertyMatch(property) { for (let count = 0; count < options.match.length; count++) { if (property.indexOf(options.match[count]) > -1) { return true; } } return false; }
[ "function", "propertyMatch", "(", "property", ")", "{", "for", "(", "let", "count", "=", "0", ";", "count", "<", "options", ".", "match", ".", "length", ";", "count", "++", ")", "{", "if", "(", "property", ".", "indexOf", "(", "options", ".", "match", "[", "count", "]", ")", ">", "-", "1", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Detect if property fulfill one matching value. @param property @returns {boolean}
[ "Detect", "if", "property", "fulfill", "one", "matching", "value", "." ]
ee6afbe1c6ec5091912e636b42a661a25e447d7d
https://github.com/nahody/postcss-export-vars/blob/ee6afbe1c6ec5091912e636b42a661a25e447d7d/index.js#L64-L72
37,257
nahody/postcss-export-vars
index.js
extractVariables
function extractVariables(value) { let regex = [/var\((.*?)\)/g, /\$([a-zA-Z0-9_\-]*)/g ], result = [], matchResult; regex.forEach(expression => { while (matchResult = expression.exec(value)) { result.push({ origin: matchResult[0], variable: matchResult[1] }); } }); return result; }
javascript
function extractVariables(value) { let regex = [/var\((.*?)\)/g, /\$([a-zA-Z0-9_\-]*)/g ], result = [], matchResult; regex.forEach(expression => { while (matchResult = expression.exec(value)) { result.push({ origin: matchResult[0], variable: matchResult[1] }); } }); return result; }
[ "function", "extractVariables", "(", "value", ")", "{", "let", "regex", "=", "[", "/", "var\\((.*?)\\)", "/", "g", ",", "/", "\\$([a-zA-Z0-9_\\-]*)", "/", "g", "]", ",", "result", "=", "[", "]", ",", "matchResult", ";", "regex", ".", "forEach", "(", "expression", "=>", "{", "while", "(", "matchResult", "=", "expression", ".", "exec", "(", "value", ")", ")", "{", "result", ".", "push", "(", "{", "origin", ":", "matchResult", "[", "0", "]", ",", "variable", ":", "matchResult", "[", "1", "]", "}", ")", ";", "}", "}", ")", ";", "return", "result", ";", "}" ]
Extract custom properties and sass like variables from value. Return each found variable as array with objects. @example 'test vars(--var1) + $width' result in array with objects: [{origin:'vars(--var1)', variable: '--var1'},{origin:'$width', variable: 'width'}] @param value @returns {Array}
[ "Extract", "custom", "properties", "and", "sass", "like", "variables", "from", "value", ".", "Return", "each", "found", "variable", "as", "array", "with", "objects", "." ]
ee6afbe1c6ec5091912e636b42a661a25e447d7d
https://github.com/nahody/postcss-export-vars/blob/ee6afbe1c6ec5091912e636b42a661a25e447d7d/index.js#L84-L96
37,258
nahody/postcss-export-vars
index.js
resolveReferences
function resolveReferences() { for (let key in _variableCollection) { let referenceVariables = extractVariables(_variableCollection[key]); for (let current = 0; current < referenceVariables.length; current++) { if (_.isEmpty(_variableCollection[_.camelCase(referenceVariables[current].variable)]) === false) { _variableCollection[key] = _variableCollection[key].replace(referenceVariables[current].origin, _variableCollection[_.camelCase(referenceVariables[current].variable)]); } } } }
javascript
function resolveReferences() { for (let key in _variableCollection) { let referenceVariables = extractVariables(_variableCollection[key]); for (let current = 0; current < referenceVariables.length; current++) { if (_.isEmpty(_variableCollection[_.camelCase(referenceVariables[current].variable)]) === false) { _variableCollection[key] = _variableCollection[key].replace(referenceVariables[current].origin, _variableCollection[_.camelCase(referenceVariables[current].variable)]); } } } }
[ "function", "resolveReferences", "(", ")", "{", "for", "(", "let", "key", "in", "_variableCollection", ")", "{", "let", "referenceVariables", "=", "extractVariables", "(", "_variableCollection", "[", "key", "]", ")", ";", "for", "(", "let", "current", "=", "0", ";", "current", "<", "referenceVariables", ".", "length", ";", "current", "++", ")", "{", "if", "(", "_", ".", "isEmpty", "(", "_variableCollection", "[", "_", ".", "camelCase", "(", "referenceVariables", "[", "current", "]", ".", "variable", ")", "]", ")", "===", "false", ")", "{", "_variableCollection", "[", "key", "]", "=", "_variableCollection", "[", "key", "]", ".", "replace", "(", "referenceVariables", "[", "current", "]", ".", "origin", ",", "_variableCollection", "[", "_", ".", "camelCase", "(", "referenceVariables", "[", "current", "]", ".", "variable", ")", "]", ")", ";", "}", "}", "}", "}" ]
Resolve references on variable values to other variables.
[ "Resolve", "references", "on", "variable", "values", "to", "other", "variables", "." ]
ee6afbe1c6ec5091912e636b42a661a25e447d7d
https://github.com/nahody/postcss-export-vars/blob/ee6afbe1c6ec5091912e636b42a661a25e447d7d/index.js#L101-L113
37,259
nahody/postcss-export-vars
index.js
escapeValue
function escapeValue(value) { switch (options.type) { case 'js': return value.replace(/'/g, '\\\''); case 'json': return value.replace(/"/g, '\\"'); default: return value; } }
javascript
function escapeValue(value) { switch (options.type) { case 'js': return value.replace(/'/g, '\\\''); case 'json': return value.replace(/"/g, '\\"'); default: return value; } }
[ "function", "escapeValue", "(", "value", ")", "{", "switch", "(", "options", ".", "type", ")", "{", "case", "'js'", ":", "return", "value", ".", "replace", "(", "/", "'", "/", "g", ",", "'\\\\\\''", ")", ";", "case", "'json'", ":", "return", "value", ".", "replace", "(", "/", "\"", "/", "g", ",", "'\\\\\"'", ")", ";", "default", ":", "return", "value", ";", "}", "}" ]
Escape values depends on type. For JS escape single quote, for json double quotes. For everything else return origin value. @param value {string} @returns {string}
[ "Escape", "values", "depends", "on", "type", "." ]
ee6afbe1c6ec5091912e636b42a661a25e447d7d
https://github.com/nahody/postcss-export-vars/blob/ee6afbe1c6ec5091912e636b42a661a25e447d7d/index.js#L124-L133
37,260
kadamwhite/tokenize-markdown
tokenize-markdown.js
convertToTokens
function convertToTokens( contents, filterParams ) { var tokens = marked.lexer( contents ); // Simple case: no filtering needs to happen if ( ! filterParams ) { // Return the array of tokens from this content return tokens; } /** * Filter method to check whether a token is valid, based on the provided * object of filter parameters * * If the filter object defines a RegExp for a key, test the token's property * against that RegExp; otherwise, do a strict equality check between the * provided value and the token's value for a given key. * * @param {Object} token A token object * @return {Boolean} Whether the provided token object is valid */ function isTokenValid( token ) { /** * Reducer function to check token validity: start the token out as valid, * then reduce through the provided filter parameters, updating the validity * of the token after checking each value. * * @param {Boolean} valid Reducer function memo value * @param {String|RegExp} targetValue The expected value of the specified property * on this token, or else a RegExp against which * to test that property * @param {String} key The key within the token to test * @return {Boolean} Whether the token is still valid, after * validating the provided key */ function checkTokenParam( valid, targetValue, key ) { // Once invalid, always invalid: fast-fail in this case if ( ! valid ) { return false; } // Without a target value, filtering doesn't mean much: move along if ( typeof targetValue === 'undefined' ) { return true; } var tokenPropToTest = token[ key ]; if ( isRegExp( targetValue ) ) { // Special-case if the target value is a RegExp return targetValue.test( tokenPropToTest ); } return tokenPropToTest === targetValue; } // Check each property on this token against the provided params return reduce( filterParams, checkTokenParam, true ); } // Return a filtered array of tokens from the provided content return tokens.filter( isTokenValid ); }
javascript
function convertToTokens( contents, filterParams ) { var tokens = marked.lexer( contents ); // Simple case: no filtering needs to happen if ( ! filterParams ) { // Return the array of tokens from this content return tokens; } /** * Filter method to check whether a token is valid, based on the provided * object of filter parameters * * If the filter object defines a RegExp for a key, test the token's property * against that RegExp; otherwise, do a strict equality check between the * provided value and the token's value for a given key. * * @param {Object} token A token object * @return {Boolean} Whether the provided token object is valid */ function isTokenValid( token ) { /** * Reducer function to check token validity: start the token out as valid, * then reduce through the provided filter parameters, updating the validity * of the token after checking each value. * * @param {Boolean} valid Reducer function memo value * @param {String|RegExp} targetValue The expected value of the specified property * on this token, or else a RegExp against which * to test that property * @param {String} key The key within the token to test * @return {Boolean} Whether the token is still valid, after * validating the provided key */ function checkTokenParam( valid, targetValue, key ) { // Once invalid, always invalid: fast-fail in this case if ( ! valid ) { return false; } // Without a target value, filtering doesn't mean much: move along if ( typeof targetValue === 'undefined' ) { return true; } var tokenPropToTest = token[ key ]; if ( isRegExp( targetValue ) ) { // Special-case if the target value is a RegExp return targetValue.test( tokenPropToTest ); } return tokenPropToTest === targetValue; } // Check each property on this token against the provided params return reduce( filterParams, checkTokenParam, true ); } // Return a filtered array of tokens from the provided content return tokens.filter( isTokenValid ); }
[ "function", "convertToTokens", "(", "contents", ",", "filterParams", ")", "{", "var", "tokens", "=", "marked", ".", "lexer", "(", "contents", ")", ";", "// Simple case: no filtering needs to happen", "if", "(", "!", "filterParams", ")", "{", "// Return the array of tokens from this content", "return", "tokens", ";", "}", "/**\n * Filter method to check whether a token is valid, based on the provided\n * object of filter parameters\n *\n * If the filter object defines a RegExp for a key, test the token's property\n * against that RegExp; otherwise, do a strict equality check between the\n * provided value and the token's value for a given key.\n *\n * @param {Object} token A token object\n * @return {Boolean} Whether the provided token object is valid\n */", "function", "isTokenValid", "(", "token", ")", "{", "/**\n * Reducer function to check token validity: start the token out as valid,\n * then reduce through the provided filter parameters, updating the validity\n * of the token after checking each value.\n *\n * @param {Boolean} valid Reducer function memo value\n * @param {String|RegExp} targetValue The expected value of the specified property\n * on this token, or else a RegExp against which\n * to test that property\n * @param {String} key The key within the token to test\n * @return {Boolean} Whether the token is still valid, after\n * validating the provided key\n */", "function", "checkTokenParam", "(", "valid", ",", "targetValue", ",", "key", ")", "{", "// Once invalid, always invalid: fast-fail in this case", "if", "(", "!", "valid", ")", "{", "return", "false", ";", "}", "// Without a target value, filtering doesn't mean much: move along", "if", "(", "typeof", "targetValue", "===", "'undefined'", ")", "{", "return", "true", ";", "}", "var", "tokenPropToTest", "=", "token", "[", "key", "]", ";", "if", "(", "isRegExp", "(", "targetValue", ")", ")", "{", "// Special-case if the target value is a RegExp", "return", "targetValue", ".", "test", "(", "tokenPropToTest", ")", ";", "}", "return", "tokenPropToTest", "===", "targetValue", ";", "}", "// Check each property on this token against the provided params", "return", "reduce", "(", "filterParams", ",", "checkTokenParam", ",", "true", ")", ";", "}", "// Return a filtered array of tokens from the provided content", "return", "tokens", ".", "filter", "(", "isTokenValid", ")", ";", "}" ]
Convert provided content into a token list with marked @param {String} contents A markdown string or file's contents @param {Object} [filterParams] An optional array of properties to use to filter the returned tokens for this file @return {Object}
[ "Convert", "provided", "content", "into", "a", "token", "list", "with", "marked" ]
ecc08f4d71edb6c834ca223e0f25761f6e1ef4c0
https://github.com/kadamwhite/tokenize-markdown/blob/ecc08f4d71edb6c834ca223e0f25761f6e1ef4c0/tokenize-markdown.js#L16-L77
37,261
kadamwhite/tokenize-markdown
tokenize-markdown.js
isTokenValid
function isTokenValid( token ) { /** * Reducer function to check token validity: start the token out as valid, * then reduce through the provided filter parameters, updating the validity * of the token after checking each value. * * @param {Boolean} valid Reducer function memo value * @param {String|RegExp} targetValue The expected value of the specified property * on this token, or else a RegExp against which * to test that property * @param {String} key The key within the token to test * @return {Boolean} Whether the token is still valid, after * validating the provided key */ function checkTokenParam( valid, targetValue, key ) { // Once invalid, always invalid: fast-fail in this case if ( ! valid ) { return false; } // Without a target value, filtering doesn't mean much: move along if ( typeof targetValue === 'undefined' ) { return true; } var tokenPropToTest = token[ key ]; if ( isRegExp( targetValue ) ) { // Special-case if the target value is a RegExp return targetValue.test( tokenPropToTest ); } return tokenPropToTest === targetValue; } // Check each property on this token against the provided params return reduce( filterParams, checkTokenParam, true ); }
javascript
function isTokenValid( token ) { /** * Reducer function to check token validity: start the token out as valid, * then reduce through the provided filter parameters, updating the validity * of the token after checking each value. * * @param {Boolean} valid Reducer function memo value * @param {String|RegExp} targetValue The expected value of the specified property * on this token, or else a RegExp against which * to test that property * @param {String} key The key within the token to test * @return {Boolean} Whether the token is still valid, after * validating the provided key */ function checkTokenParam( valid, targetValue, key ) { // Once invalid, always invalid: fast-fail in this case if ( ! valid ) { return false; } // Without a target value, filtering doesn't mean much: move along if ( typeof targetValue === 'undefined' ) { return true; } var tokenPropToTest = token[ key ]; if ( isRegExp( targetValue ) ) { // Special-case if the target value is a RegExp return targetValue.test( tokenPropToTest ); } return tokenPropToTest === targetValue; } // Check each property on this token against the provided params return reduce( filterParams, checkTokenParam, true ); }
[ "function", "isTokenValid", "(", "token", ")", "{", "/**\n * Reducer function to check token validity: start the token out as valid,\n * then reduce through the provided filter parameters, updating the validity\n * of the token after checking each value.\n *\n * @param {Boolean} valid Reducer function memo value\n * @param {String|RegExp} targetValue The expected value of the specified property\n * on this token, or else a RegExp against which\n * to test that property\n * @param {String} key The key within the token to test\n * @return {Boolean} Whether the token is still valid, after\n * validating the provided key\n */", "function", "checkTokenParam", "(", "valid", ",", "targetValue", ",", "key", ")", "{", "// Once invalid, always invalid: fast-fail in this case", "if", "(", "!", "valid", ")", "{", "return", "false", ";", "}", "// Without a target value, filtering doesn't mean much: move along", "if", "(", "typeof", "targetValue", "===", "'undefined'", ")", "{", "return", "true", ";", "}", "var", "tokenPropToTest", "=", "token", "[", "key", "]", ";", "if", "(", "isRegExp", "(", "targetValue", ")", ")", "{", "// Special-case if the target value is a RegExp", "return", "targetValue", ".", "test", "(", "tokenPropToTest", ")", ";", "}", "return", "tokenPropToTest", "===", "targetValue", ";", "}", "// Check each property on this token against the provided params", "return", "reduce", "(", "filterParams", ",", "checkTokenParam", ",", "true", ")", ";", "}" ]
Filter method to check whether a token is valid, based on the provided object of filter parameters If the filter object defines a RegExp for a key, test the token's property against that RegExp; otherwise, do a strict equality check between the provided value and the token's value for a given key. @param {Object} token A token object @return {Boolean} Whether the provided token object is valid
[ "Filter", "method", "to", "check", "whether", "a", "token", "is", "valid", "based", "on", "the", "provided", "object", "of", "filter", "parameters" ]
ecc08f4d71edb6c834ca223e0f25761f6e1ef4c0
https://github.com/kadamwhite/tokenize-markdown/blob/ecc08f4d71edb6c834ca223e0f25761f6e1ef4c0/tokenize-markdown.js#L36-L73
37,262
kadamwhite/tokenize-markdown
tokenize-markdown.js
tokenizeMarkdownFromFiles
function tokenizeMarkdownFromFiles( files, filterParams ) { /** * Read in the provided file and return its contents as markdown tokens * * @param {String} file A file path to read in * @return {Array} An array of the individual markdown tokens found * within the provided list of files */ function readAndTokenize( file ) { // Read the file var fileContents = grunt.file.read( file ); // Map file into an object defining the tokens for this file return { file: file, tokens: convertToTokens( fileContents, filterParams ) }; } // Expand the provided file globs into a list of files, and process each // one into an object containing that file's markdown tokens return grunt.file.expand( files ).map( readAndTokenize ); }
javascript
function tokenizeMarkdownFromFiles( files, filterParams ) { /** * Read in the provided file and return its contents as markdown tokens * * @param {String} file A file path to read in * @return {Array} An array of the individual markdown tokens found * within the provided list of files */ function readAndTokenize( file ) { // Read the file var fileContents = grunt.file.read( file ); // Map file into an object defining the tokens for this file return { file: file, tokens: convertToTokens( fileContents, filterParams ) }; } // Expand the provided file globs into a list of files, and process each // one into an object containing that file's markdown tokens return grunt.file.expand( files ).map( readAndTokenize ); }
[ "function", "tokenizeMarkdownFromFiles", "(", "files", ",", "filterParams", ")", "{", "/**\n * Read in the provided file and return its contents as markdown tokens\n *\n * @param {String} file A file path to read in\n * @return {Array} An array of the individual markdown tokens found\n * within the provided list of files\n */", "function", "readAndTokenize", "(", "file", ")", "{", "// Read the file", "var", "fileContents", "=", "grunt", ".", "file", ".", "read", "(", "file", ")", ";", "// Map file into an object defining the tokens for this file", "return", "{", "file", ":", "file", ",", "tokens", ":", "convertToTokens", "(", "fileContents", ",", "filterParams", ")", "}", ";", "}", "// Expand the provided file globs into a list of files, and process each", "// one into an object containing that file's markdown tokens", "return", "grunt", ".", "file", ".", "expand", "(", "files", ")", ".", "map", "(", "readAndTokenize", ")", ";", "}" ]
Get an array of markdown tokens per file from an array of files, optionally filtered to only those tokens matching a particular set of attributes @example var tokenizeMarkdown = require( 'tokenize-markdown' ); // Get all tokens var tokens = tokenizeMarkdown.fromFiles( [ 'slides/*.md' ] ); // Get only tokens of type "code" and lang "javascript" var jsTokens = tokenizeMarkdown.fromFiles( [ 'slides/*.md' ], { type: 'code', lang: 'javascript' }); // Get tokens of lang "javascript" or "html", using a regex var jsOrHtmlTokens = tokenizeMarkdown.fromFiles( [ 'slides/*.md' ], { lang: /(javascript|html)/ }); @method fromFiles @param {Array} files Array of file sources to expand and process @param {Object} [filterParams] Optional hash of properties to use to filter the returned tokens @return {Array} Array of token objects
[ "Get", "an", "array", "of", "markdown", "tokens", "per", "file", "from", "an", "array", "of", "files", "optionally", "filtered", "to", "only", "those", "tokens", "matching", "a", "particular", "set", "of", "attributes" ]
ecc08f4d71edb6c834ca223e0f25761f6e1ef4c0
https://github.com/kadamwhite/tokenize-markdown/blob/ecc08f4d71edb6c834ca223e0f25761f6e1ef4c0/tokenize-markdown.js#L107-L129
37,263
kadamwhite/tokenize-markdown
tokenize-markdown.js
readAndTokenize
function readAndTokenize( file ) { // Read the file var fileContents = grunt.file.read( file ); // Map file into an object defining the tokens for this file return { file: file, tokens: convertToTokens( fileContents, filterParams ) }; }
javascript
function readAndTokenize( file ) { // Read the file var fileContents = grunt.file.read( file ); // Map file into an object defining the tokens for this file return { file: file, tokens: convertToTokens( fileContents, filterParams ) }; }
[ "function", "readAndTokenize", "(", "file", ")", "{", "// Read the file", "var", "fileContents", "=", "grunt", ".", "file", ".", "read", "(", "file", ")", ";", "// Map file into an object defining the tokens for this file", "return", "{", "file", ":", "file", ",", "tokens", ":", "convertToTokens", "(", "fileContents", ",", "filterParams", ")", "}", ";", "}" ]
Read in the provided file and return its contents as markdown tokens @param {String} file A file path to read in @return {Array} An array of the individual markdown tokens found within the provided list of files
[ "Read", "in", "the", "provided", "file", "and", "return", "its", "contents", "as", "markdown", "tokens" ]
ecc08f4d71edb6c834ca223e0f25761f6e1ef4c0
https://github.com/kadamwhite/tokenize-markdown/blob/ecc08f4d71edb6c834ca223e0f25761f6e1ef4c0/tokenize-markdown.js#L115-L124
37,264
switer/muxjs
lib/mux.js
MuxFactory
function MuxFactory(options) { function Class (receiveProps) { Ctor.call(this, options, receiveProps) } Class.prototype = Object.create(Mux.prototype) return Class }
javascript
function MuxFactory(options) { function Class (receiveProps) { Ctor.call(this, options, receiveProps) } Class.prototype = Object.create(Mux.prototype) return Class }
[ "function", "MuxFactory", "(", "options", ")", "{", "function", "Class", "(", "receiveProps", ")", "{", "Ctor", ".", "call", "(", "this", ",", "options", ",", "receiveProps", ")", "}", "Class", ".", "prototype", "=", "Object", ".", "create", "(", "Mux", ".", "prototype", ")", "return", "Class", "}" ]
Mux model factory @private
[ "Mux", "model", "factory" ]
bc272efa32572c63be813bb7ce083879c6dc7266
https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L77-L84
37,265
switer/muxjs
lib/mux.js
_defPrivateProperty
function _defPrivateProperty(name, value) { if (instanceOf(value, Function)) value = value.bind(model) _privateProperties[name] = value $util.def(model, name, { enumerable: false, value: value }) }
javascript
function _defPrivateProperty(name, value) { if (instanceOf(value, Function)) value = value.bind(model) _privateProperties[name] = value $util.def(model, name, { enumerable: false, value: value }) }
[ "function", "_defPrivateProperty", "(", "name", ",", "value", ")", "{", "if", "(", "instanceOf", "(", "value", ",", "Function", ")", ")", "value", "=", "value", ".", "bind", "(", "model", ")", "_privateProperties", "[", "name", "]", "=", "value", "$util", ".", "def", "(", "model", ",", "name", ",", "{", "enumerable", ":", "false", ",", "value", ":", "value", "}", ")", "}" ]
define priavate property of the instance object
[ "define", "priavate", "property", "of", "the", "instance", "object" ]
bc272efa32572c63be813bb7ce083879c6dc7266
https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L113-L120
37,266
switer/muxjs
lib/mux.js
_emitChange
function _emitChange(propname/*, arg1, ..., argX*/) { var args = arguments var kp = $normalize($join(_rootPath(), propname)) args[0] = CHANGE_EVENT + ':' + kp _emitter.emit(CHANGE_EVENT, kp) emitter.emit.apply(emitter, args) args = $util.copyArray(args) args[0] = kp args.unshift('*') emitter.emit.apply(emitter, args) }
javascript
function _emitChange(propname/*, arg1, ..., argX*/) { var args = arguments var kp = $normalize($join(_rootPath(), propname)) args[0] = CHANGE_EVENT + ':' + kp _emitter.emit(CHANGE_EVENT, kp) emitter.emit.apply(emitter, args) args = $util.copyArray(args) args[0] = kp args.unshift('*') emitter.emit.apply(emitter, args) }
[ "function", "_emitChange", "(", "propname", "/*, arg1, ..., argX*/", ")", "{", "var", "args", "=", "arguments", "var", "kp", "=", "$normalize", "(", "$join", "(", "_rootPath", "(", ")", ",", "propname", ")", ")", "args", "[", "0", "]", "=", "CHANGE_EVENT", "+", "':'", "+", "kp", "_emitter", ".", "emit", "(", "CHANGE_EVENT", ",", "kp", ")", "emitter", ".", "emit", ".", "apply", "(", "emitter", ",", "args", ")", "args", "=", "$util", ".", "copyArray", "(", "args", ")", "args", "[", "0", "]", "=", "kp", "args", ".", "unshift", "(", "'*'", ")", "emitter", ".", "emit", ".", "apply", "(", "emitter", ",", "args", ")", "}" ]
local proxy for EventEmitter
[ "local", "proxy", "for", "EventEmitter" ]
bc272efa32572c63be813bb7ce083879c6dc7266
https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L204-L215
37,267
switer/muxjs
lib/mux.js
_prop2CptDepsMapping
function _prop2CptDepsMapping (propname, dep) { // if ($indexOf(_computedKeys, dep)) // return $warn('Dependency should not computed property') $util.patch(_cptDepsMapping, dep, []) var dest = _cptDepsMapping[dep] if ($indexOf(dest, propname)) return dest.push(propname) }
javascript
function _prop2CptDepsMapping (propname, dep) { // if ($indexOf(_computedKeys, dep)) // return $warn('Dependency should not computed property') $util.patch(_cptDepsMapping, dep, []) var dest = _cptDepsMapping[dep] if ($indexOf(dest, propname)) return dest.push(propname) }
[ "function", "_prop2CptDepsMapping", "(", "propname", ",", "dep", ")", "{", "// if ($indexOf(_computedKeys, dep))", "// return $warn('Dependency should not computed property')", "$util", ".", "patch", "(", "_cptDepsMapping", ",", "dep", ",", "[", "]", ")", "var", "dest", "=", "_cptDepsMapping", "[", "dep", "]", "if", "(", "$indexOf", "(", "dest", ",", "propname", ")", ")", "return", "dest", ".", "push", "(", "propname", ")", "}" ]
Add dependence to "_cptDepsMapping" @param propname <String> property name @param dep <String> dependency name
[ "Add", "dependence", "to", "_cptDepsMapping" ]
bc272efa32572c63be813bb7ce083879c6dc7266
https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L221-L229
37,268
switer/muxjs
lib/mux.js
_subInstance
function _subInstance (target, props, kp) { var ins var _mux = target.__mux__ if (_mux && _mux.__kp__ === kp && _mux.__root__ === __muxid__) { // reuse ins = target // emitter proxy ins._$emitter(emitter) // a private emitter for communication between instances ins._$_emitter(_emitter) } else { ins = new Mux({ props: props, emitter: emitter, _emitter: _emitter, __kp__: kp }) } if (!ins.__root__) { $util.def(ins, '__root__', { enumerable: false, value: __muxid__ }) } return ins }
javascript
function _subInstance (target, props, kp) { var ins var _mux = target.__mux__ if (_mux && _mux.__kp__ === kp && _mux.__root__ === __muxid__) { // reuse ins = target // emitter proxy ins._$emitter(emitter) // a private emitter for communication between instances ins._$_emitter(_emitter) } else { ins = new Mux({ props: props, emitter: emitter, _emitter: _emitter, __kp__: kp }) } if (!ins.__root__) { $util.def(ins, '__root__', { enumerable: false, value: __muxid__ }) } return ins }
[ "function", "_subInstance", "(", "target", ",", "props", ",", "kp", ")", "{", "var", "ins", "var", "_mux", "=", "target", ".", "__mux__", "if", "(", "_mux", "&&", "_mux", ".", "__kp__", "===", "kp", "&&", "_mux", ".", "__root__", "===", "__muxid__", ")", "{", "// reuse", "ins", "=", "target", "// emitter proxy", "ins", ".", "_$emitter", "(", "emitter", ")", "// a private emitter for communication between instances", "ins", ".", "_$_emitter", "(", "_emitter", ")", "}", "else", "{", "ins", "=", "new", "Mux", "(", "{", "props", ":", "props", ",", "emitter", ":", "emitter", ",", "_emitter", ":", "_emitter", ",", "__kp__", ":", "kp", "}", ")", "}", "if", "(", "!", "ins", ".", "__root__", ")", "{", "$util", ".", "def", "(", "ins", ",", "'__root__'", ",", "{", "enumerable", ":", "false", ",", "value", ":", "__muxid__", "}", ")", "}", "return", "ins", "}" ]
Instance or reuse a sub-mux-instance with specified keyPath and emitter @param target <Object> instance target, it could be a Mux instance @param props <Object> property value that has been walked @param kp <String> keyPath of target, use to diff instance keyPath changes or instance with the keyPath
[ "Instance", "or", "reuse", "a", "sub", "-", "mux", "-", "instance", "with", "specified", "keyPath", "and", "emitter" ]
bc272efa32572c63be813bb7ce083879c6dc7266
https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L236-L262
37,269
switer/muxjs
lib/mux.js
_walk
function _walk (name, value, mountedPath) { var tov = $type(value) // type of value // initial path prefix is root path var kp = mountedPath ? mountedPath : $join(_rootPath(), name) /** * Array methods hook */ if (tov == ARRAY) { $arrayHook(value, function (self, methodName, nativeMethod, args) { var pv = $util.copyArray(self) var result = nativeMethod.apply(self, args) // set value directly after walk _props[name] = _walk(name, self, kp) if (methodName == 'splice') { _emitChange(kp, self, pv, methodName, args) } else { _emitChange(kp, self, pv, methodName) } return result }) } // deep observe into each property value switch(tov) { case OBJECT: // walk deep into object items var props = {} var obj = value if (instanceOf(value, Mux)) obj = value.$props() $util.objEach(obj, function (k, v) { props[k] = _walk(k, v, $join(kp, k)) }) return _subInstance(value, props, kp) case ARRAY: // walk deep into array items value.forEach(function (item, index) { value[index] = _walk(index, item, $join(kp, index)) }) return value default: return value } }
javascript
function _walk (name, value, mountedPath) { var tov = $type(value) // type of value // initial path prefix is root path var kp = mountedPath ? mountedPath : $join(_rootPath(), name) /** * Array methods hook */ if (tov == ARRAY) { $arrayHook(value, function (self, methodName, nativeMethod, args) { var pv = $util.copyArray(self) var result = nativeMethod.apply(self, args) // set value directly after walk _props[name] = _walk(name, self, kp) if (methodName == 'splice') { _emitChange(kp, self, pv, methodName, args) } else { _emitChange(kp, self, pv, methodName) } return result }) } // deep observe into each property value switch(tov) { case OBJECT: // walk deep into object items var props = {} var obj = value if (instanceOf(value, Mux)) obj = value.$props() $util.objEach(obj, function (k, v) { props[k] = _walk(k, v, $join(kp, k)) }) return _subInstance(value, props, kp) case ARRAY: // walk deep into array items value.forEach(function (item, index) { value[index] = _walk(index, item, $join(kp, index)) }) return value default: return value } }
[ "function", "_walk", "(", "name", ",", "value", ",", "mountedPath", ")", "{", "var", "tov", "=", "$type", "(", "value", ")", "// type of value", "// initial path prefix is root path", "var", "kp", "=", "mountedPath", "?", "mountedPath", ":", "$join", "(", "_rootPath", "(", ")", ",", "name", ")", "/**\n * Array methods hook\n */", "if", "(", "tov", "==", "ARRAY", ")", "{", "$arrayHook", "(", "value", ",", "function", "(", "self", ",", "methodName", ",", "nativeMethod", ",", "args", ")", "{", "var", "pv", "=", "$util", ".", "copyArray", "(", "self", ")", "var", "result", "=", "nativeMethod", ".", "apply", "(", "self", ",", "args", ")", "// set value directly after walk", "_props", "[", "name", "]", "=", "_walk", "(", "name", ",", "self", ",", "kp", ")", "if", "(", "methodName", "==", "'splice'", ")", "{", "_emitChange", "(", "kp", ",", "self", ",", "pv", ",", "methodName", ",", "args", ")", "}", "else", "{", "_emitChange", "(", "kp", ",", "self", ",", "pv", ",", "methodName", ")", "}", "return", "result", "}", ")", "}", "// deep observe into each property value", "switch", "(", "tov", ")", "{", "case", "OBJECT", ":", "// walk deep into object items", "var", "props", "=", "{", "}", "var", "obj", "=", "value", "if", "(", "instanceOf", "(", "value", ",", "Mux", ")", ")", "obj", "=", "value", ".", "$props", "(", ")", "$util", ".", "objEach", "(", "obj", ",", "function", "(", "k", ",", "v", ")", "{", "props", "[", "k", "]", "=", "_walk", "(", "k", ",", "v", ",", "$join", "(", "kp", ",", "k", ")", ")", "}", ")", "return", "_subInstance", "(", "value", ",", "props", ",", "kp", ")", "case", "ARRAY", ":", "// walk deep into array items", "value", ".", "forEach", "(", "function", "(", "item", ",", "index", ")", "{", "value", "[", "index", "]", "=", "_walk", "(", "index", ",", "item", ",", "$join", "(", "kp", ",", "index", ")", ")", "}", ")", "return", "value", "default", ":", "return", "value", "}", "}" ]
A hook method for setting value to "_props" @param name <String> property name @param value @param mountedPath <String> property's value mouted path
[ "A", "hook", "method", "for", "setting", "value", "to", "_props" ]
bc272efa32572c63be813bb7ce083879c6dc7266
https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L270-L312
37,270
switer/muxjs
lib/mux.js
_$set
function _$set(kp, value, lazyEmit) { if (_destroy) return _destroyNotice() return _$sync(kp, value, lazyEmit) // if (!diff) return /** * Base type change of object type will be trigger change event * next and pre value are not keypath value but property value */ // if ( kp == diff.mounted && $util.diff(diff.next, diff.pre) ) { // var propname = diff.mounted // // emit change immediately // _emitChange(propname, diff.next, diff.pre) // } }
javascript
function _$set(kp, value, lazyEmit) { if (_destroy) return _destroyNotice() return _$sync(kp, value, lazyEmit) // if (!diff) return /** * Base type change of object type will be trigger change event * next and pre value are not keypath value but property value */ // if ( kp == diff.mounted && $util.diff(diff.next, diff.pre) ) { // var propname = diff.mounted // // emit change immediately // _emitChange(propname, diff.next, diff.pre) // } }
[ "function", "_$set", "(", "kp", ",", "value", ",", "lazyEmit", ")", "{", "if", "(", "_destroy", ")", "return", "_destroyNotice", "(", ")", "return", "_$sync", "(", "kp", ",", "value", ",", "lazyEmit", ")", "// if (!diff) return", "/**\n * Base type change of object type will be trigger change event\n * next and pre value are not keypath value but property value\n */", "// if ( kp == diff.mounted && $util.diff(diff.next, diff.pre) ) {", "// var propname = diff.mounted", "// // emit change immediately", "// _emitChange(propname, diff.next, diff.pre)", "// }", "}" ]
sync props value and trigger change event @param kp <String> keyPath
[ "sync", "props", "value", "and", "trigger", "change", "event" ]
bc272efa32572c63be813bb7ce083879c6dc7266
https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L374-L388
37,271
switer/muxjs
lib/mux.js
_$setMulti
function _$setMulti(keyMap) { if (_destroy) return _destroyNotice() if (!keyMap || $type(keyMap) != OBJECT) return var changes = [] $util.objEach(keyMap, function (key, item) { var cg = _$set(key, item, true) if (cg) changes.push(cg) }) changes.forEach(function (args) { _emitChange.apply(null, args) }) }
javascript
function _$setMulti(keyMap) { if (_destroy) return _destroyNotice() if (!keyMap || $type(keyMap) != OBJECT) return var changes = [] $util.objEach(keyMap, function (key, item) { var cg = _$set(key, item, true) if (cg) changes.push(cg) }) changes.forEach(function (args) { _emitChange.apply(null, args) }) }
[ "function", "_$setMulti", "(", "keyMap", ")", "{", "if", "(", "_destroy", ")", "return", "_destroyNotice", "(", ")", "if", "(", "!", "keyMap", "||", "$type", "(", "keyMap", ")", "!=", "OBJECT", ")", "return", "var", "changes", "=", "[", "]", "$util", ".", "objEach", "(", "keyMap", ",", "function", "(", "key", ",", "item", ")", "{", "var", "cg", "=", "_$set", "(", "key", ",", "item", ",", "true", ")", "if", "(", "cg", ")", "changes", ".", "push", "(", "cg", ")", "}", ")", "changes", ".", "forEach", "(", "function", "(", "args", ")", "{", "_emitChange", ".", "apply", "(", "null", ",", "args", ")", "}", ")", "}" ]
sync props's value in batch and trigger change event @param keyMap <Object> properties object
[ "sync", "props", "s", "value", "in", "batch", "and", "trigger", "change", "event" ]
bc272efa32572c63be813bb7ce083879c6dc7266
https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L394-L407
37,272
switer/muxjs
lib/mux.js
_$add
function _$add(prop, value, lazyEmit) { if (prop.match(/[\.\[\]]/)) { throw new Error('Propname shoudn\'t contains "." or "[" or "]"') } if ($indexOf(_observableKeys, prop)) { // If value is specified, reset value return arguments.length > 1 ? true : false } _props[prop] = _walk(prop, $util.copyValue(value)) _observableKeys.push(prop) $util.def(model, prop, { enumerable: true, get: function() { return _props[prop] }, set: function (v) { _$set(prop, v) } }) // add peroperty will trigger change event if (!lazyEmit) { _emitChange(prop, value) } else { return { kp: prop, vl: value } } }
javascript
function _$add(prop, value, lazyEmit) { if (prop.match(/[\.\[\]]/)) { throw new Error('Propname shoudn\'t contains "." or "[" or "]"') } if ($indexOf(_observableKeys, prop)) { // If value is specified, reset value return arguments.length > 1 ? true : false } _props[prop] = _walk(prop, $util.copyValue(value)) _observableKeys.push(prop) $util.def(model, prop, { enumerable: true, get: function() { return _props[prop] }, set: function (v) { _$set(prop, v) } }) // add peroperty will trigger change event if (!lazyEmit) { _emitChange(prop, value) } else { return { kp: prop, vl: value } } }
[ "function", "_$add", "(", "prop", ",", "value", ",", "lazyEmit", ")", "{", "if", "(", "prop", ".", "match", "(", "/", "[\\.\\[\\]]", "/", ")", ")", "{", "throw", "new", "Error", "(", "'Propname shoudn\\'t contains \".\" or \"[\" or \"]\"'", ")", "}", "if", "(", "$indexOf", "(", "_observableKeys", ",", "prop", ")", ")", "{", "// If value is specified, reset value", "return", "arguments", ".", "length", ">", "1", "?", "true", ":", "false", "}", "_props", "[", "prop", "]", "=", "_walk", "(", "prop", ",", "$util", ".", "copyValue", "(", "value", ")", ")", "_observableKeys", ".", "push", "(", "prop", ")", "$util", ".", "def", "(", "model", ",", "prop", ",", "{", "enumerable", ":", "true", ",", "get", ":", "function", "(", ")", "{", "return", "_props", "[", "prop", "]", "}", ",", "set", ":", "function", "(", "v", ")", "{", "_$set", "(", "prop", ",", "v", ")", "}", "}", ")", "// add peroperty will trigger change event", "if", "(", "!", "lazyEmit", ")", "{", "_emitChange", "(", "prop", ",", "value", ")", "}", "else", "{", "return", "{", "kp", ":", "prop", ",", "vl", ":", "value", "}", "}", "}" ]
create a prop observer if not in observer, return true if no value setting. @param prop <String> property name @param value property value
[ "create", "a", "prop", "observer", "if", "not", "in", "observer", "return", "true", "if", "no", "value", "setting", "." ]
bc272efa32572c63be813bb7ce083879c6dc7266
https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L415-L444
37,273
switer/muxjs
lib/mux.js
_walkResetEmiter
function _walkResetEmiter (ins, em, _pem) { if ($type(ins) == OBJECT) { var items = ins if (instanceOf(ins, Mux)) { ins._$emitter(em, _pem) items = ins.$props() } $util.objEach(items, function (k, v) { _walkResetEmiter(v, em, _pem) }) } else if ($type(ins) == ARRAY) { ins.forEach(function (v) { _walkResetEmiter(v, em, _pem) }) } }
javascript
function _walkResetEmiter (ins, em, _pem) { if ($type(ins) == OBJECT) { var items = ins if (instanceOf(ins, Mux)) { ins._$emitter(em, _pem) items = ins.$props() } $util.objEach(items, function (k, v) { _walkResetEmiter(v, em, _pem) }) } else if ($type(ins) == ARRAY) { ins.forEach(function (v) { _walkResetEmiter(v, em, _pem) }) } }
[ "function", "_walkResetEmiter", "(", "ins", ",", "em", ",", "_pem", ")", "{", "if", "(", "$type", "(", "ins", ")", "==", "OBJECT", ")", "{", "var", "items", "=", "ins", "if", "(", "instanceOf", "(", "ins", ",", "Mux", ")", ")", "{", "ins", ".", "_$emitter", "(", "em", ",", "_pem", ")", "items", "=", "ins", ".", "$props", "(", ")", "}", "$util", ".", "objEach", "(", "items", ",", "function", "(", "k", ",", "v", ")", "{", "_walkResetEmiter", "(", "v", ",", "em", ",", "_pem", ")", "}", ")", "}", "else", "if", "(", "$type", "(", "ins", ")", "==", "ARRAY", ")", "{", "ins", ".", "forEach", "(", "function", "(", "v", ")", "{", "_walkResetEmiter", "(", "v", ",", "em", ",", "_pem", ")", "}", ")", "}", "}" ]
Reset emitter of the instance recursively @param ins <Mux>
[ "Reset", "emitter", "of", "the", "instance", "recursively" ]
bc272efa32572c63be813bb7ce083879c6dc7266
https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L758-L773
37,274
hightail/smartling-sdk
smartling.js
function (apiBaseUrl, apiKey, projectId) { this.config = { apiBaseUrl: apiBaseUrl, apiKey: apiKey, projectId: projectId }; }
javascript
function (apiBaseUrl, apiKey, projectId) { this.config = { apiBaseUrl: apiBaseUrl, apiKey: apiKey, projectId: projectId }; }
[ "function", "(", "apiBaseUrl", ",", "apiKey", ",", "projectId", ")", "{", "this", ".", "config", "=", "{", "apiBaseUrl", ":", "apiBaseUrl", ",", "apiKey", ":", "apiKey", ",", "projectId", ":", "projectId", "}", ";", "}" ]
Initializes Smartling with the given params @param baseUrl @param apiKey @param projectId
[ "Initializes", "Smartling", "with", "the", "given", "params" ]
08a15c4eed1ee842bf00c82f80ade4cada91b9a5
https://github.com/hightail/smartling-sdk/blob/08a15c4eed1ee842bf00c82f80ade4cada91b9a5/smartling.js#L107-L113
37,275
tadam313/sheet-db
index.js
connect
function connect(sheetId, options) { options = options || {}; // TODO: needs better access token handling let api = apiFactory.getApi(options.version); let restClient = clientFactory({ token: options.token, gApi: api, gCache: cache }); return new Spreadsheet(sheetId, restClient, options); }
javascript
function connect(sheetId, options) { options = options || {}; // TODO: needs better access token handling let api = apiFactory.getApi(options.version); let restClient = clientFactory({ token: options.token, gApi: api, gCache: cache }); return new Spreadsheet(sheetId, restClient, options); }
[ "function", "connect", "(", "sheetId", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "// TODO: needs better access token handling", "let", "api", "=", "apiFactory", ".", "getApi", "(", "options", ".", "version", ")", ";", "let", "restClient", "=", "clientFactory", "(", "{", "token", ":", "options", ".", "token", ",", "gApi", ":", "api", ",", "gCache", ":", "cache", "}", ")", ";", "return", "new", "Spreadsheet", "(", "sheetId", ",", "restClient", ",", "options", ")", ";", "}" ]
Connects and initializes the sheet db. @param {string} sheetId - ID of the specific spreadsheet @param {object} options - Optional options.
[ "Connects", "and", "initializes", "the", "sheet", "db", "." ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/index.js#L15-L28
37,276
chip-js/fragments-js
src/animated-binding.js
function(node, callback) { if (node.firstViewNode) node = node.firstViewNode; this.animateNode('out', node, callback); }
javascript
function(node, callback) { if (node.firstViewNode) node = node.firstViewNode; this.animateNode('out', node, callback); }
[ "function", "(", "node", ",", "callback", ")", "{", "if", "(", "node", ".", "firstViewNode", ")", "node", "=", "node", ".", "firstViewNode", ";", "this", ".", "animateNode", "(", "'out'", ",", "node", ",", "callback", ")", ";", "}" ]
Helper method to remove a node from the DOM, allowing for animations to occur. `callback` will be called when finished.
[ "Helper", "method", "to", "remove", "a", "node", "from", "the", "DOM", "allowing", "for", "animations", "to", "occur", ".", "callback", "will", "be", "called", "when", "finished", "." ]
5d613ea42c3823423efb01fce4ffef80c7f5ce0f
https://github.com/chip-js/fragments-js/blob/5d613ea42c3823423efb01fce4ffef80c7f5ce0f/src/animated-binding.js#L88-L92
37,277
elcontraption/polylinear-scale
src/index.js
polylinearScale
function polylinearScale (domain, range, clamp) { const domains = domain || [0, 1] const ranges = range || [0, 1] clamp = clamp || false if (domains.length !== ranges.length) { throw new Error('polylinearScale requires domain and range to have an equivalent number of values') } /** * The compiled scale to return * * @param {Number} value The number to scale * @return {Number} The result */ return function (value) { var rangeMin var rangeMax var domain var range var ratio var result var i = 0 /* eslint-disable no-sequences */ while (i < domains.length - 1) { if (value >= domains[i] && value <= domains[i + 1]) { domain = [domains[i], domains[i + 1]], range = [ranges[i], ranges[i + 1]] break } i++ } // Value is outside given domain if (domain === undefined) { if (value < domains[0]) { domain = [domains[0], domains[1]] range = [ranges[0], ranges[1]] } else { domain = [domains[domains.length - 2], domains[domains.length - 1]] range = [ranges[ranges.length - 2], ranges[ranges.length - 1]] } } ratio = (range[1] - range[0]) / (domain[1] - domain[0]) result = range[0] + ratio * (value - domain[0]) if (clamp) { rangeMin = Math.min(range[0], range[1]) rangeMax = Math.max(range[0], range[1]) result = Math.min(rangeMax, Math.max(rangeMin, result)) } return result } }
javascript
function polylinearScale (domain, range, clamp) { const domains = domain || [0, 1] const ranges = range || [0, 1] clamp = clamp || false if (domains.length !== ranges.length) { throw new Error('polylinearScale requires domain and range to have an equivalent number of values') } /** * The compiled scale to return * * @param {Number} value The number to scale * @return {Number} The result */ return function (value) { var rangeMin var rangeMax var domain var range var ratio var result var i = 0 /* eslint-disable no-sequences */ while (i < domains.length - 1) { if (value >= domains[i] && value <= domains[i + 1]) { domain = [domains[i], domains[i + 1]], range = [ranges[i], ranges[i + 1]] break } i++ } // Value is outside given domain if (domain === undefined) { if (value < domains[0]) { domain = [domains[0], domains[1]] range = [ranges[0], ranges[1]] } else { domain = [domains[domains.length - 2], domains[domains.length - 1]] range = [ranges[ranges.length - 2], ranges[ranges.length - 1]] } } ratio = (range[1] - range[0]) / (domain[1] - domain[0]) result = range[0] + ratio * (value - domain[0]) if (clamp) { rangeMin = Math.min(range[0], range[1]) rangeMax = Math.max(range[0], range[1]) result = Math.min(rangeMax, Math.max(rangeMin, result)) } return result } }
[ "function", "polylinearScale", "(", "domain", ",", "range", ",", "clamp", ")", "{", "const", "domains", "=", "domain", "||", "[", "0", ",", "1", "]", "const", "ranges", "=", "range", "||", "[", "0", ",", "1", "]", "clamp", "=", "clamp", "||", "false", "if", "(", "domains", ".", "length", "!==", "ranges", ".", "length", ")", "{", "throw", "new", "Error", "(", "'polylinearScale requires domain and range to have an equivalent number of values'", ")", "}", "/**\n * The compiled scale to return\n *\n * @param {Number} value The number to scale\n * @return {Number} The result\n */", "return", "function", "(", "value", ")", "{", "var", "rangeMin", "var", "rangeMax", "var", "domain", "var", "range", "var", "ratio", "var", "result", "var", "i", "=", "0", "/* eslint-disable no-sequences */", "while", "(", "i", "<", "domains", ".", "length", "-", "1", ")", "{", "if", "(", "value", ">=", "domains", "[", "i", "]", "&&", "value", "<=", "domains", "[", "i", "+", "1", "]", ")", "{", "domain", "=", "[", "domains", "[", "i", "]", ",", "domains", "[", "i", "+", "1", "]", "]", ",", "range", "=", "[", "ranges", "[", "i", "]", ",", "ranges", "[", "i", "+", "1", "]", "]", "break", "}", "i", "++", "}", "// Value is outside given domain", "if", "(", "domain", "===", "undefined", ")", "{", "if", "(", "value", "<", "domains", "[", "0", "]", ")", "{", "domain", "=", "[", "domains", "[", "0", "]", ",", "domains", "[", "1", "]", "]", "range", "=", "[", "ranges", "[", "0", "]", ",", "ranges", "[", "1", "]", "]", "}", "else", "{", "domain", "=", "[", "domains", "[", "domains", ".", "length", "-", "2", "]", ",", "domains", "[", "domains", ".", "length", "-", "1", "]", "]", "range", "=", "[", "ranges", "[", "ranges", ".", "length", "-", "2", "]", ",", "ranges", "[", "ranges", ".", "length", "-", "1", "]", "]", "}", "}", "ratio", "=", "(", "range", "[", "1", "]", "-", "range", "[", "0", "]", ")", "/", "(", "domain", "[", "1", "]", "-", "domain", "[", "0", "]", ")", "result", "=", "range", "[", "0", "]", "+", "ratio", "*", "(", "value", "-", "domain", "[", "0", "]", ")", "if", "(", "clamp", ")", "{", "rangeMin", "=", "Math", ".", "min", "(", "range", "[", "0", "]", ",", "range", "[", "1", "]", ")", "rangeMax", "=", "Math", ".", "max", "(", "range", "[", "0", "]", ",", "range", "[", "1", "]", ")", "result", "=", "Math", ".", "min", "(", "rangeMax", ",", "Math", ".", "max", "(", "rangeMin", ",", "result", ")", ")", "}", "return", "result", "}", "}" ]
A polylinear scale Supports multiple piecewise linear scales that divide a continuous domain and range. @param {Array} domain Two or more numbers @param {Array} range Numbers equivalent to number in `domain` @param {Boolean} clamp Enables or disables clamping @return {Function} Scale function
[ "A", "polylinear", "scale" ]
1cf6b0e710932eba7bf97f334ce0dc24c001b872
https://github.com/elcontraption/polylinear-scale/blob/1cf6b0e710932eba7bf97f334ce0dc24c001b872/src/index.js#L11-L67
37,278
lddubeau/bluejax
index.js
inherit
function inherit(inheritor, inherited) { inheritor.prototype = Object.create(inherited.prototype); inheritor.prototype.constructor = inheritor; }
javascript
function inherit(inheritor, inherited) { inheritor.prototype = Object.create(inherited.prototype); inheritor.prototype.constructor = inheritor; }
[ "function", "inherit", "(", "inheritor", ",", "inherited", ")", "{", "inheritor", ".", "prototype", "=", "Object", ".", "create", "(", "inherited", ".", "prototype", ")", ";", "inheritor", ".", "prototype", ".", "constructor", "=", "inheritor", ";", "}" ]
Utility function for class inheritance.
[ "Utility", "function", "for", "class", "inheritance", "." ]
106359491ba707b5bb22b3b5b84cedca08555ff8
https://github.com/lddubeau/bluejax/blob/106359491ba707b5bb22b3b5b84cedca08555ff8/index.js#L26-L29
37,279
lddubeau/bluejax
index.js
rename
function rename(cls, name) { try { Object.defineProperty(cls, "name", { value: name }); } catch (ex) { // Trying to defineProperty on `name` fails on Safari with a TypeError. if (!(ex instanceof TypeError)) { throw ex; } } cls.prototype.name = name; }
javascript
function rename(cls, name) { try { Object.defineProperty(cls, "name", { value: name }); } catch (ex) { // Trying to defineProperty on `name` fails on Safari with a TypeError. if (!(ex instanceof TypeError)) { throw ex; } } cls.prototype.name = name; }
[ "function", "rename", "(", "cls", ",", "name", ")", "{", "try", "{", "Object", ".", "defineProperty", "(", "cls", ",", "\"name\"", ",", "{", "value", ":", "name", "}", ")", ";", "}", "catch", "(", "ex", ")", "{", "// Trying to defineProperty on `name` fails on Safari with a TypeError.", "if", "(", "!", "(", "ex", "instanceof", "TypeError", ")", ")", "{", "throw", "ex", ";", "}", "}", "cls", ".", "prototype", ".", "name", "=", "name", ";", "}" ]
Utility function for classes that are derived from Error. The prototype name is initially set to some generic value which is not particularly useful. This fixes the problem. We have to pass an explicit string through `name` because on some platforms we cannot count on `cls.name`.
[ "Utility", "function", "for", "classes", "that", "are", "derived", "from", "Error", ".", "The", "prototype", "name", "is", "initially", "set", "to", "some", "generic", "value", "which", "is", "not", "particularly", "useful", ".", "This", "fixes", "the", "problem", ".", "We", "have", "to", "pass", "an", "explicit", "string", "through", "name", "because", "on", "some", "platforms", "we", "cannot", "count", "on", "cls", ".", "name", "." ]
106359491ba707b5bb22b3b5b84cedca08555ff8
https://github.com/lddubeau/bluejax/blob/106359491ba707b5bb22b3b5b84cedca08555ff8/index.js#L35-L46
37,280
lddubeau/bluejax
index.js
makeError
function makeError(jqXHR, textStatus, errorThrown, options) { var Constructor = statusToError[textStatus]; // We did not find anything in the map, which would happen if the textStatus // was "error". Determine whether an ``HttpError`` or an ``AjaxError`` must // be thrown. if (!Constructor) { Constructor = statusToError[(jqXHR.status !== 0) ? "http" : "ajax"]; } return new Constructor(jqXHR, textStatus, errorThrown, options); }
javascript
function makeError(jqXHR, textStatus, errorThrown, options) { var Constructor = statusToError[textStatus]; // We did not find anything in the map, which would happen if the textStatus // was "error". Determine whether an ``HttpError`` or an ``AjaxError`` must // be thrown. if (!Constructor) { Constructor = statusToError[(jqXHR.status !== 0) ? "http" : "ajax"]; } return new Constructor(jqXHR, textStatus, errorThrown, options); }
[ "function", "makeError", "(", "jqXHR", ",", "textStatus", ",", "errorThrown", ",", "options", ")", "{", "var", "Constructor", "=", "statusToError", "[", "textStatus", "]", ";", "// We did not find anything in the map, which would happen if the textStatus", "// was \"error\". Determine whether an ``HttpError`` or an ``AjaxError`` must", "// be thrown.", "if", "(", "!", "Constructor", ")", "{", "Constructor", "=", "statusToError", "[", "(", "jqXHR", ".", "status", "!==", "0", ")", "?", "\"http\"", ":", "\"ajax\"", "]", ";", "}", "return", "new", "Constructor", "(", "jqXHR", ",", "textStatus", ",", "errorThrown", ",", "options", ")", ";", "}" ]
Given a ``jqXHR`` that failed, create an error object.
[ "Given", "a", "jqXHR", "that", "failed", "create", "an", "error", "object", "." ]
106359491ba707b5bb22b3b5b84cedca08555ff8
https://github.com/lddubeau/bluejax/blob/106359491ba707b5bb22b3b5b84cedca08555ff8/index.js#L150-L161
37,281
lddubeau/bluejax
index.js
connectionCheck
function connectionCheck(error, diagnose) { var servers = diagnose.knownServers; // Nothing to check so we fail immediately. if (!servers || servers.length === 0) { throw new ServerDownError(error); } // We check all the servers that the user asked to check. If none respond, // we blame the network. Otherwise, we blame the server. return Promise.all(servers.map(function urlToAjax(url) { // eslint-disable-next-line no-use-before-define return ajax({ url: dedupURL(normalizeURL(url)), timeout: 1000 }) .reflect(); })).filter(function filterSuccessfulServers(result) { return result.isFulfilled(); }).then(function checkAnyFullfilled(fulfilled) { if (fulfilled.length === 0) { throw new NetworkDownError(error); } throw new ServerDownError(error); }); }
javascript
function connectionCheck(error, diagnose) { var servers = diagnose.knownServers; // Nothing to check so we fail immediately. if (!servers || servers.length === 0) { throw new ServerDownError(error); } // We check all the servers that the user asked to check. If none respond, // we blame the network. Otherwise, we blame the server. return Promise.all(servers.map(function urlToAjax(url) { // eslint-disable-next-line no-use-before-define return ajax({ url: dedupURL(normalizeURL(url)), timeout: 1000 }) .reflect(); })).filter(function filterSuccessfulServers(result) { return result.isFulfilled(); }).then(function checkAnyFullfilled(fulfilled) { if (fulfilled.length === 0) { throw new NetworkDownError(error); } throw new ServerDownError(error); }); }
[ "function", "connectionCheck", "(", "error", ",", "diagnose", ")", "{", "var", "servers", "=", "diagnose", ".", "knownServers", ";", "// Nothing to check so we fail immediately.", "if", "(", "!", "servers", "||", "servers", ".", "length", "===", "0", ")", "{", "throw", "new", "ServerDownError", "(", "error", ")", ";", "}", "// We check all the servers that the user asked to check. If none respond,", "// we blame the network. Otherwise, we blame the server.", "return", "Promise", ".", "all", "(", "servers", ".", "map", "(", "function", "urlToAjax", "(", "url", ")", "{", "// eslint-disable-next-line no-use-before-define", "return", "ajax", "(", "{", "url", ":", "dedupURL", "(", "normalizeURL", "(", "url", ")", ")", ",", "timeout", ":", "1000", "}", ")", ".", "reflect", "(", ")", ";", "}", ")", ")", ".", "filter", "(", "function", "filterSuccessfulServers", "(", "result", ")", "{", "return", "result", ".", "isFulfilled", "(", ")", ";", "}", ")", ".", "then", "(", "function", "checkAnyFullfilled", "(", "fulfilled", ")", "{", "if", "(", "fulfilled", ".", "length", "===", "0", ")", "{", "throw", "new", "NetworkDownError", "(", "error", ")", ";", "}", "throw", "new", "ServerDownError", "(", "error", ")", ";", "}", ")", ";", "}" ]
This is called once we know a) the browser is not offline but b) we cannot reach the server that should serve our request.
[ "This", "is", "called", "once", "we", "know", "a", ")", "the", "browser", "is", "not", "offline", "but", "b", ")", "we", "cannot", "reach", "the", "server", "that", "should", "serve", "our", "request", "." ]
106359491ba707b5bb22b3b5b84cedca08555ff8
https://github.com/lddubeau/bluejax/blob/106359491ba707b5bb22b3b5b84cedca08555ff8/index.js#L250-L273
37,282
lddubeau/bluejax
index.js
diagnoseIt
function diagnoseIt(error, diagnose) { // The browser reports being offline, blame the problem on this. if (("onLine" in navigator) && !navigator.onLine) { throw new BrowserOfflineError(error); } var serverURL = diagnose.serverURL; var check; // If the user gave us a server URL to check whether the server is up at // all, use it. If that failed, then we need to check the connection. If we // do not have a server URL, then we need to check the connection right // away. if (serverURL) { // eslint-disable-next-line no-use-before-define check = ajax({ url: dedupURL(normalizeURL(serverURL)) }) .catch(function failed() { return connectionCheck(error, diagnose); }); } else { check = connectionCheck(error, diagnose); } return check.then(function success() { // All of our checks passed... and we have no tries left, so just rethrow // what we would have thrown in the first place. throw error; }); }
javascript
function diagnoseIt(error, diagnose) { // The browser reports being offline, blame the problem on this. if (("onLine" in navigator) && !navigator.onLine) { throw new BrowserOfflineError(error); } var serverURL = diagnose.serverURL; var check; // If the user gave us a server URL to check whether the server is up at // all, use it. If that failed, then we need to check the connection. If we // do not have a server URL, then we need to check the connection right // away. if (serverURL) { // eslint-disable-next-line no-use-before-define check = ajax({ url: dedupURL(normalizeURL(serverURL)) }) .catch(function failed() { return connectionCheck(error, diagnose); }); } else { check = connectionCheck(error, diagnose); } return check.then(function success() { // All of our checks passed... and we have no tries left, so just rethrow // what we would have thrown in the first place. throw error; }); }
[ "function", "diagnoseIt", "(", "error", ",", "diagnose", ")", "{", "// The browser reports being offline, blame the problem on this.", "if", "(", "(", "\"onLine\"", "in", "navigator", ")", "&&", "!", "navigator", ".", "onLine", ")", "{", "throw", "new", "BrowserOfflineError", "(", "error", ")", ";", "}", "var", "serverURL", "=", "diagnose", ".", "serverURL", ";", "var", "check", ";", "// If the user gave us a server URL to check whether the server is up at", "// all, use it. If that failed, then we need to check the connection. If we", "// do not have a server URL, then we need to check the connection right", "// away.", "if", "(", "serverURL", ")", "{", "// eslint-disable-next-line no-use-before-define", "check", "=", "ajax", "(", "{", "url", ":", "dedupURL", "(", "normalizeURL", "(", "serverURL", ")", ")", "}", ")", ".", "catch", "(", "function", "failed", "(", ")", "{", "return", "connectionCheck", "(", "error", ",", "diagnose", ")", ";", "}", ")", ";", "}", "else", "{", "check", "=", "connectionCheck", "(", "error", ",", "diagnose", ")", ";", "}", "return", "check", ".", "then", "(", "function", "success", "(", ")", "{", "// All of our checks passed... and we have no tries left, so just rethrow", "// what we would have thrown in the first place.", "throw", "error", ";", "}", ")", ";", "}" ]
This is called when our tries all failed. This function attempts to figure out where the issue is.
[ "This", "is", "called", "when", "our", "tries", "all", "failed", ".", "This", "function", "attempts", "to", "figure", "out", "where", "the", "issue", "is", "." ]
106359491ba707b5bb22b3b5b84cedca08555ff8
https://github.com/lddubeau/bluejax/blob/106359491ba707b5bb22b3b5b84cedca08555ff8/index.js#L277-L305
37,283
lddubeau/bluejax
index.js
isNetworkIssue
function isNetworkIssue(error) { // We don't want to retry when a HTTP error occurred. return !(error instanceof errors.HttpError) && !(error instanceof errors.ParserError) && !(error instanceof errors.AbortError); }
javascript
function isNetworkIssue(error) { // We don't want to retry when a HTTP error occurred. return !(error instanceof errors.HttpError) && !(error instanceof errors.ParserError) && !(error instanceof errors.AbortError); }
[ "function", "isNetworkIssue", "(", "error", ")", "{", "// We don't want to retry when a HTTP error occurred.", "return", "!", "(", "error", "instanceof", "errors", ".", "HttpError", ")", "&&", "!", "(", "error", "instanceof", "errors", ".", "ParserError", ")", "&&", "!", "(", "error", "instanceof", "errors", ".", "AbortError", ")", ";", "}" ]
Determine whether the error is due to a network problem. We do not perform diagnosis on errors like an HTTP status code of 400 because errors like these are an indication that the application was not queried properly rather than a problem with the server being inaccessible or a network issue. So we need to distinguish network issues from the rest.
[ "Determine", "whether", "the", "error", "is", "due", "to", "a", "network", "problem", ".", "We", "do", "not", "perform", "diagnosis", "on", "errors", "like", "an", "HTTP", "status", "code", "of", "400", "because", "errors", "like", "these", "are", "an", "indication", "that", "the", "application", "was", "not", "queried", "properly", "rather", "than", "a", "problem", "with", "the", "server", "being", "inaccessible", "or", "a", "network", "issue", ".", "So", "we", "need", "to", "distinguish", "network", "issues", "from", "the", "rest", "." ]
106359491ba707b5bb22b3b5b84cedca08555ff8
https://github.com/lddubeau/bluejax/blob/106359491ba707b5bb22b3b5b84cedca08555ff8/index.js#L312-L317
37,284
lddubeau/bluejax
index.js
doit
function doit(originalArgs, originalSettings, jqOptions, bjOptions) { var xhr; var p = new Promise(function resolver(resolve, reject) { xhr = bluetry.perform.call(this, originalSettings, jqOptions, bjOptions); function succeded(data, textStatus, jqXHR) { resolve(bjOptions.verboseResults ? [data, textStatus, jqXHR] : data); } function failed(jqXHR, textStatus, errorThrown) { var error = makeError( jqXHR, textStatus, errorThrown, bjOptions.verboseExceptions ? originalArgs : null); if (!isNetworkIssue(error)) { // As mentioned earlier, errors that are not due to the network cause // an immediate rejection: no diagnosis. reject(error); } else { // Move to perhaps diagnosing what could be the problem. var diagnose = bjOptions.diagnose; if (!diagnose || !diagnose.on) { // The user did not request diagnosis: fail now. reject(error); } else { // Otherwise, we perform the requested diagnosis. We cannot just // call ``reject`` with the return value of ``diagnoseIt``, as the // rejection value would be a promise and not an error. (``resolve`` // assimilates promises, ``reject`` does not). resolve(diagnoseIt(error, diagnose)); } } } xhr.fail(failed).done(succeded); }); return { xhr: xhr, promise: p }; }
javascript
function doit(originalArgs, originalSettings, jqOptions, bjOptions) { var xhr; var p = new Promise(function resolver(resolve, reject) { xhr = bluetry.perform.call(this, originalSettings, jqOptions, bjOptions); function succeded(data, textStatus, jqXHR) { resolve(bjOptions.verboseResults ? [data, textStatus, jqXHR] : data); } function failed(jqXHR, textStatus, errorThrown) { var error = makeError( jqXHR, textStatus, errorThrown, bjOptions.verboseExceptions ? originalArgs : null); if (!isNetworkIssue(error)) { // As mentioned earlier, errors that are not due to the network cause // an immediate rejection: no diagnosis. reject(error); } else { // Move to perhaps diagnosing what could be the problem. var diagnose = bjOptions.diagnose; if (!diagnose || !diagnose.on) { // The user did not request diagnosis: fail now. reject(error); } else { // Otherwise, we perform the requested diagnosis. We cannot just // call ``reject`` with the return value of ``diagnoseIt``, as the // rejection value would be a promise and not an error. (``resolve`` // assimilates promises, ``reject`` does not). resolve(diagnoseIt(error, diagnose)); } } } xhr.fail(failed).done(succeded); }); return { xhr: xhr, promise: p }; }
[ "function", "doit", "(", "originalArgs", ",", "originalSettings", ",", "jqOptions", ",", "bjOptions", ")", "{", "var", "xhr", ";", "var", "p", "=", "new", "Promise", "(", "function", "resolver", "(", "resolve", ",", "reject", ")", "{", "xhr", "=", "bluetry", ".", "perform", ".", "call", "(", "this", ",", "originalSettings", ",", "jqOptions", ",", "bjOptions", ")", ";", "function", "succeded", "(", "data", ",", "textStatus", ",", "jqXHR", ")", "{", "resolve", "(", "bjOptions", ".", "verboseResults", "?", "[", "data", ",", "textStatus", ",", "jqXHR", "]", ":", "data", ")", ";", "}", "function", "failed", "(", "jqXHR", ",", "textStatus", ",", "errorThrown", ")", "{", "var", "error", "=", "makeError", "(", "jqXHR", ",", "textStatus", ",", "errorThrown", ",", "bjOptions", ".", "verboseExceptions", "?", "originalArgs", ":", "null", ")", ";", "if", "(", "!", "isNetworkIssue", "(", "error", ")", ")", "{", "// As mentioned earlier, errors that are not due to the network cause", "// an immediate rejection: no diagnosis.", "reject", "(", "error", ")", ";", "}", "else", "{", "// Move to perhaps diagnosing what could be the problem.", "var", "diagnose", "=", "bjOptions", ".", "diagnose", ";", "if", "(", "!", "diagnose", "||", "!", "diagnose", ".", "on", ")", "{", "// The user did not request diagnosis: fail now.", "reject", "(", "error", ")", ";", "}", "else", "{", "// Otherwise, we perform the requested diagnosis. We cannot just", "// call ``reject`` with the return value of ``diagnoseIt``, as the", "// rejection value would be a promise and not an error. (``resolve``", "// assimilates promises, ``reject`` does not).", "resolve", "(", "diagnoseIt", "(", "error", ",", "diagnose", ")", ")", ";", "}", "}", "}", "xhr", ".", "fail", "(", "failed", ")", ".", "done", "(", "succeded", ")", ";", "}", ")", ";", "return", "{", "xhr", ":", "xhr", ",", "promise", ":", "p", "}", ";", "}" ]
This is the core of the functionality provided by Bluejax.
[ "This", "is", "the", "core", "of", "the", "functionality", "provided", "by", "Bluejax", "." ]
106359491ba707b5bb22b3b5b84cedca08555ff8
https://github.com/lddubeau/bluejax/blob/106359491ba707b5bb22b3b5b84cedca08555ff8/index.js#L320-L359
37,285
lddubeau/bluejax
index.js
_ajax$
function _ajax$(url, settings, override) { // We just need to split up the arguments and pass them to ``doit``. var originalArgs = settings ? [url, settings] : [url]; var originalSettings = settings || url; var extracted = bluetry.extractBluejaxOptions(originalArgs); // We need a copy here so that we do not mess up what the user passes to us. var bluejaxOptions = $.extend({}, override, extracted[0]); var cleanedOptions = extracted[1]; return doit(originalArgs, originalSettings, cleanedOptions, bluejaxOptions); }
javascript
function _ajax$(url, settings, override) { // We just need to split up the arguments and pass them to ``doit``. var originalArgs = settings ? [url, settings] : [url]; var originalSettings = settings || url; var extracted = bluetry.extractBluejaxOptions(originalArgs); // We need a copy here so that we do not mess up what the user passes to us. var bluejaxOptions = $.extend({}, override, extracted[0]); var cleanedOptions = extracted[1]; return doit(originalArgs, originalSettings, cleanedOptions, bluejaxOptions); }
[ "function", "_ajax$", "(", "url", ",", "settings", ",", "override", ")", "{", "// We just need to split up the arguments and pass them to ``doit``.", "var", "originalArgs", "=", "settings", "?", "[", "url", ",", "settings", "]", ":", "[", "url", "]", ";", "var", "originalSettings", "=", "settings", "||", "url", ";", "var", "extracted", "=", "bluetry", ".", "extractBluejaxOptions", "(", "originalArgs", ")", ";", "// We need a copy here so that we do not mess up what the user passes to us.", "var", "bluejaxOptions", "=", "$", ".", "extend", "(", "{", "}", ",", "override", ",", "extracted", "[", "0", "]", ")", ";", "var", "cleanedOptions", "=", "extracted", "[", "1", "]", ";", "return", "doit", "(", "originalArgs", ",", "originalSettings", ",", "cleanedOptions", ",", "bluejaxOptions", ")", ";", "}" ]
We need this so that we can use ``make``. The ``override`` parameter is used solely by ``make`` to pass the options that the user specified on ``make``.
[ "We", "need", "this", "so", "that", "we", "can", "use", "make", ".", "The", "override", "parameter", "is", "used", "solely", "by", "make", "to", "pass", "the", "options", "that", "the", "user", "specified", "on", "make", "." ]
106359491ba707b5bb22b3b5b84cedca08555ff8
https://github.com/lddubeau/bluejax/blob/106359491ba707b5bb22b3b5b84cedca08555ff8/index.js#L364-L373
37,286
mwittig/logger-winston
logger-winston.js
init
function init(config) { // the given config is only applied if no config has been set already (stored as localConfig) if (Object.keys(localConfig).length === 0) { if (config.hasOwnProperty("logging") && (config.logging.constructor === {}.constructor)) { // config has "logging" key with an {} object value //console.log("LOGGER: Setting config"); localConfig = _merge({}, config.logging); } else { // no valid config - use default localConfig = { default: { console: {}}}; } } }
javascript
function init(config) { // the given config is only applied if no config has been set already (stored as localConfig) if (Object.keys(localConfig).length === 0) { if (config.hasOwnProperty("logging") && (config.logging.constructor === {}.constructor)) { // config has "logging" key with an {} object value //console.log("LOGGER: Setting config"); localConfig = _merge({}, config.logging); } else { // no valid config - use default localConfig = { default: { console: {}}}; } } }
[ "function", "init", "(", "config", ")", "{", "// the given config is only applied if no config has been set already (stored as localConfig)", "if", "(", "Object", ".", "keys", "(", "localConfig", ")", ".", "length", "===", "0", ")", "{", "if", "(", "config", ".", "hasOwnProperty", "(", "\"logging\"", ")", "&&", "(", "config", ".", "logging", ".", "constructor", "===", "{", "}", ".", "constructor", ")", ")", "{", "// config has \"logging\" key with an {} object value", "//console.log(\"LOGGER: Setting config\");", "localConfig", "=", "_merge", "(", "{", "}", ",", "config", ".", "logging", ")", ";", "}", "else", "{", "// no valid config - use default", "localConfig", "=", "{", "default", ":", "{", "console", ":", "{", "}", "}", "}", ";", "}", "}", "}" ]
Initialize logging with the given configuration. As the given configuration will be cached internally the first invocation will take effect, only. Make sure to invoke this function at the very beginning of the program before other topics using logging get loaded. @param {Object} config - The logging configuration. @param {Object} config.logging - Contains the logging configuration for at least one winston container. A specific container configuration can be provided by defining a configuration for a category matching the topicName. A default configuration can provided by defining a container for the category "default". A container configuration contains at least one transport configuration. Note, you may run into an issue in strict mode, if you need to setup multiple transports of the same type, e.g., two file transports, as the strict mode inhibits duplicate object keys. In this case the transport name can be augmented with a "#name" postfix, e.g. "file#debug". @param {Object} [config.logging.[topicName]=default] - A specific container for a given topicName can be setup by providing a container configuration where the property name is equal to given topicName. The container configuration must contain at least one winston transport configuration. If the container configuration contains the key "inheritDefault" set to true, the default configuration will be mixed in. This way, it possible to solely define transport properties which shall differ from the default configuration. @param {Object} [config.logging.default=builtin] - Contains the default configuration applicable to loggers without a specific container configuration. The container configuration must contain at least one winston transport configuration. If no default configuration is provided a console transport configuration with winston builtin defaults will be used.
[ "Initialize", "logging", "with", "the", "given", "configuration", ".", "As", "the", "given", "configuration", "will", "be", "cached", "internally", "the", "first", "invocation", "will", "take", "effect", "only", ".", "Make", "sure", "to", "invoke", "this", "function", "at", "the", "very", "beginning", "of", "the", "program", "before", "other", "topics", "using", "logging", "get", "loaded", "." ]
0893c8714d78bdf33294b300f6c9cddf4ccef9f5
https://github.com/mwittig/logger-winston/blob/0893c8714d78bdf33294b300f6c9cddf4ccef9f5/logger-winston.js#L31-L44
37,287
mallocator/gulp-international
index.js
trueOrMatch
function trueOrMatch(needle, haystack) { if (needle === true) { return true; } if (_.isRegExp(needle) && needle.test(haystack)) { return true; } if (_.isString(needle) && haystack.indexOf(needle) !== -1) { return true; } if (needle instanceof Array) { for (var i in needle) { if (trueOrMatch(needle[i], haystack)) { return true; } } } return false; }
javascript
function trueOrMatch(needle, haystack) { if (needle === true) { return true; } if (_.isRegExp(needle) && needle.test(haystack)) { return true; } if (_.isString(needle) && haystack.indexOf(needle) !== -1) { return true; } if (needle instanceof Array) { for (var i in needle) { if (trueOrMatch(needle[i], haystack)) { return true; } } } return false; }
[ "function", "trueOrMatch", "(", "needle", ",", "haystack", ")", "{", "if", "(", "needle", "===", "true", ")", "{", "return", "true", ";", "}", "if", "(", "_", ".", "isRegExp", "(", "needle", ")", "&&", "needle", ".", "test", "(", "haystack", ")", ")", "{", "return", "true", ";", "}", "if", "(", "_", ".", "isString", "(", "needle", ")", "&&", "haystack", ".", "indexOf", "(", "needle", ")", "!==", "-", "1", ")", "{", "return", "true", ";", "}", "if", "(", "needle", "instanceof", "Array", ")", "{", "for", "(", "var", "i", "in", "needle", ")", "{", "if", "(", "trueOrMatch", "(", "needle", "[", "i", "]", ",", "haystack", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
A helper function to test whether an option was set to true or the value matches the options regular expression. @param {boolean|string|RegExp} needle @param {String} haystack @returns {boolean}
[ "A", "helper", "function", "to", "test", "whether", "an", "option", "was", "set", "to", "true", "or", "the", "value", "matches", "the", "options", "regular", "expression", "." ]
0b235341acd1d72937e900f13fd4a6de855ff1e4
https://github.com/mallocator/gulp-international/blob/0b235341acd1d72937e900f13fd4a6de855ff1e4/index.js#L54-L72
37,288
mallocator/gulp-international
index.js
splitIniLine
function splitIniLine(line) { var separator = line.indexOf('='); if (separator === -1) { return [line]; } return [ line.substr(0, separator), line.substr(separator + 1) ]; }
javascript
function splitIniLine(line) { var separator = line.indexOf('='); if (separator === -1) { return [line]; } return [ line.substr(0, separator), line.substr(separator + 1) ]; }
[ "function", "splitIniLine", "(", "line", ")", "{", "var", "separator", "=", "line", ".", "indexOf", "(", "'='", ")", ";", "if", "(", "separator", "===", "-", "1", ")", "{", "return", "[", "line", "]", ";", "}", "return", "[", "line", ".", "substr", "(", "0", ",", "separator", ")", ",", "line", ".", "substr", "(", "separator", "+", "1", ")", "]", ";", "}" ]
Splits a line from an ini file into 2. Any subsequent '=' are ignored. @param {String} line @returns {String[]}
[ "Splits", "a", "line", "from", "an", "ini", "file", "into", "2", ".", "Any", "subsequent", "=", "are", "ignored", "." ]
0b235341acd1d72937e900f13fd4a6de855ff1e4
https://github.com/mallocator/gulp-international/blob/0b235341acd1d72937e900f13fd4a6de855ff1e4/index.js#L79-L88
37,289
mallocator/gulp-international
index.js
ini2json
function ini2json(iniData) { var result = {}; var iniLines = iniData.toString().split('\n'); var context = null; for (var i in iniLines) { var fields = splitIniLine(iniLines[i]); for (var j in fields) { fields[j] = fields[j].trim(); } if (fields[0].length) { if (fields[0].indexOf('[')===0) { context = fields[0].substring(1, fields[0].length - 1); } else { if (context) { if (!result[context]) { result[context] = {}; } result[context][fields[0]] = fields[1]; } else { result[fields[0]] = fields[1]; } } } } return result; }
javascript
function ini2json(iniData) { var result = {}; var iniLines = iniData.toString().split('\n'); var context = null; for (var i in iniLines) { var fields = splitIniLine(iniLines[i]); for (var j in fields) { fields[j] = fields[j].trim(); } if (fields[0].length) { if (fields[0].indexOf('[')===0) { context = fields[0].substring(1, fields[0].length - 1); } else { if (context) { if (!result[context]) { result[context] = {}; } result[context][fields[0]] = fields[1]; } else { result[fields[0]] = fields[1]; } } } } return result; }
[ "function", "ini2json", "(", "iniData", ")", "{", "var", "result", "=", "{", "}", ";", "var", "iniLines", "=", "iniData", ".", "toString", "(", ")", ".", "split", "(", "'\\n'", ")", ";", "var", "context", "=", "null", ";", "for", "(", "var", "i", "in", "iniLines", ")", "{", "var", "fields", "=", "splitIniLine", "(", "iniLines", "[", "i", "]", ")", ";", "for", "(", "var", "j", "in", "fields", ")", "{", "fields", "[", "j", "]", "=", "fields", "[", "j", "]", ".", "trim", "(", ")", ";", "}", "if", "(", "fields", "[", "0", "]", ".", "length", ")", "{", "if", "(", "fields", "[", "0", "]", ".", "indexOf", "(", "'['", ")", "===", "0", ")", "{", "context", "=", "fields", "[", "0", "]", ".", "substring", "(", "1", ",", "fields", "[", "0", "]", ".", "length", "-", "1", ")", ";", "}", "else", "{", "if", "(", "context", ")", "{", "if", "(", "!", "result", "[", "context", "]", ")", "{", "result", "[", "context", "]", "=", "{", "}", ";", "}", "result", "[", "context", "]", "[", "fields", "[", "0", "]", "]", "=", "fields", "[", "1", "]", ";", "}", "else", "{", "result", "[", "fields", "[", "0", "]", "]", "=", "fields", "[", "1", "]", ";", "}", "}", "}", "}", "return", "result", ";", "}" ]
Simple conversion helper to get a json file from an ini file. @param {String} iniData @returns {{}}
[ "Simple", "conversion", "helper", "to", "get", "a", "json", "file", "from", "an", "ini", "file", "." ]
0b235341acd1d72937e900f13fd4a6de855ff1e4
https://github.com/mallocator/gulp-international/blob/0b235341acd1d72937e900f13fd4a6de855ff1e4/index.js#L95-L120
37,290
mallocator/gulp-international
index.js
splitCsvLine
function splitCsvLine(line) { if (!line.trim().length) { return []; } var fields = []; var inQuotes = false; var separator = 0; for (var i = 0; i < line.length; i++) { switch(line[i]) { case "\"": if (i>0 && line[i-1] != "\\") { inQuotes = !inQuotes; } break; case ",": if (!inQuotes) { if (separator < i) { var field = line.substring(separator, i).trim(); if (field.length) { fields.push(field); } } separator = i + 1; } break; } } fields.push(line.substring(separator).trim()); return fields; }
javascript
function splitCsvLine(line) { if (!line.trim().length) { return []; } var fields = []; var inQuotes = false; var separator = 0; for (var i = 0; i < line.length; i++) { switch(line[i]) { case "\"": if (i>0 && line[i-1] != "\\") { inQuotes = !inQuotes; } break; case ",": if (!inQuotes) { if (separator < i) { var field = line.substring(separator, i).trim(); if (field.length) { fields.push(field); } } separator = i + 1; } break; } } fields.push(line.substring(separator).trim()); return fields; }
[ "function", "splitCsvLine", "(", "line", ")", "{", "if", "(", "!", "line", ".", "trim", "(", ")", ".", "length", ")", "{", "return", "[", "]", ";", "}", "var", "fields", "=", "[", "]", ";", "var", "inQuotes", "=", "false", ";", "var", "separator", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "line", ".", "length", ";", "i", "++", ")", "{", "switch", "(", "line", "[", "i", "]", ")", "{", "case", "\"\\\"\"", ":", "if", "(", "i", ">", "0", "&&", "line", "[", "i", "-", "1", "]", "!=", "\"\\\\\"", ")", "{", "inQuotes", "=", "!", "inQuotes", ";", "}", "break", ";", "case", "\",\"", ":", "if", "(", "!", "inQuotes", ")", "{", "if", "(", "separator", "<", "i", ")", "{", "var", "field", "=", "line", ".", "substring", "(", "separator", ",", "i", ")", ".", "trim", "(", ")", ";", "if", "(", "field", ".", "length", ")", "{", "fields", ".", "push", "(", "field", ")", ";", "}", "}", "separator", "=", "i", "+", "1", ";", "}", "break", ";", "}", "}", "fields", ".", "push", "(", "line", ".", "substring", "(", "separator", ")", ".", "trim", "(", ")", ")", ";", "return", "fields", ";", "}" ]
Converts a line of a CSV file to an array of strings, omitting empty fields. @param {String} line @returns {String[]}
[ "Converts", "a", "line", "of", "a", "CSV", "file", "to", "an", "array", "of", "strings", "omitting", "empty", "fields", "." ]
0b235341acd1d72937e900f13fd4a6de855ff1e4
https://github.com/mallocator/gulp-international/blob/0b235341acd1d72937e900f13fd4a6de855ff1e4/index.js#L127-L156
37,291
mallocator/gulp-international
index.js
csv2json
function csv2json(csvData) { var result = {}; var csvLines = csvData.toString().split('\n'); for (var i in csvLines) { var fields = splitCsvLine(csvLines[i]); if (fields.length) { var key = ''; for (var k = 0; k < fields.length - 1; k++) { if (fields[k].length) { key += '.' + fields[k]; } } result[key.substr(1)] = fields[fields.length - 1]; } } return result; }
javascript
function csv2json(csvData) { var result = {}; var csvLines = csvData.toString().split('\n'); for (var i in csvLines) { var fields = splitCsvLine(csvLines[i]); if (fields.length) { var key = ''; for (var k = 0; k < fields.length - 1; k++) { if (fields[k].length) { key += '.' + fields[k]; } } result[key.substr(1)] = fields[fields.length - 1]; } } return result; }
[ "function", "csv2json", "(", "csvData", ")", "{", "var", "result", "=", "{", "}", ";", "var", "csvLines", "=", "csvData", ".", "toString", "(", ")", ".", "split", "(", "'\\n'", ")", ";", "for", "(", "var", "i", "in", "csvLines", ")", "{", "var", "fields", "=", "splitCsvLine", "(", "csvLines", "[", "i", "]", ")", ";", "if", "(", "fields", ".", "length", ")", "{", "var", "key", "=", "''", ";", "for", "(", "var", "k", "=", "0", ";", "k", "<", "fields", ".", "length", "-", "1", ";", "k", "++", ")", "{", "if", "(", "fields", "[", "k", "]", ".", "length", ")", "{", "key", "+=", "'.'", "+", "fields", "[", "k", "]", ";", "}", "}", "result", "[", "key", ".", "substr", "(", "1", ")", "]", "=", "fields", "[", "fields", ".", "length", "-", "1", "]", ";", "}", "}", "return", "result", ";", "}" ]
Simple conversion helper to get a json file from a csv file. @param {String} csvData @returns {Object}
[ "Simple", "conversion", "helper", "to", "get", "a", "json", "file", "from", "a", "csv", "file", "." ]
0b235341acd1d72937e900f13fd4a6de855ff1e4
https://github.com/mallocator/gulp-international/blob/0b235341acd1d72937e900f13fd4a6de855ff1e4/index.js#L163-L179
37,292
mallocator/gulp-international
index.js
load
function load(options) { if (cache[options.locales]) { options.verbose && gutil.log('Skip loading cached translations from', options.locales); return dictionaries = cache[options.locales]; } try { options.verbose && gutil.log('Loading translations from', options.locales); var files = fs.readdirSync(options.locales); var count = 0; for (var i in files) { var file = files[i]; switch (path.extname(file)) { case '.json': case '.js': dictionaries[path.basename(file, path.extname(file))] = flat(require(path.join(process.cwd(), options.locales, file))); options.verbose && gutil.log('Added translations from', file); count++; break; case '.ini': var iniData = fs.readFileSync(path.join(process.cwd(), options.locales, file)); dictionaries[path.basename(file, path.extname(file))] = flat(ini2json(iniData)); options.verbose && gutil.log('Added translations from', file); count++; break; case '.csv': var csvData = fs.readFileSync(path.join(process.cwd(), options.locales, file)); dictionaries[path.basename(file, path.extname(file))] = csv2json(csvData); options.verbose && gutil.log('Added translations from', file); count++; break; default: options.verbose && gutil.log('Ignored file', file); } } options.verbose && gutil.log('Loaded', count, 'translations from', options.locales); if (options.cache) { options.verbose && gutil.log('Cashing translations from', options.locales); cache[options.locales] = dictionaries; } } catch (e) { e.message = 'No translation dictionaries have been found!'; throw e; } }
javascript
function load(options) { if (cache[options.locales]) { options.verbose && gutil.log('Skip loading cached translations from', options.locales); return dictionaries = cache[options.locales]; } try { options.verbose && gutil.log('Loading translations from', options.locales); var files = fs.readdirSync(options.locales); var count = 0; for (var i in files) { var file = files[i]; switch (path.extname(file)) { case '.json': case '.js': dictionaries[path.basename(file, path.extname(file))] = flat(require(path.join(process.cwd(), options.locales, file))); options.verbose && gutil.log('Added translations from', file); count++; break; case '.ini': var iniData = fs.readFileSync(path.join(process.cwd(), options.locales, file)); dictionaries[path.basename(file, path.extname(file))] = flat(ini2json(iniData)); options.verbose && gutil.log('Added translations from', file); count++; break; case '.csv': var csvData = fs.readFileSync(path.join(process.cwd(), options.locales, file)); dictionaries[path.basename(file, path.extname(file))] = csv2json(csvData); options.verbose && gutil.log('Added translations from', file); count++; break; default: options.verbose && gutil.log('Ignored file', file); } } options.verbose && gutil.log('Loaded', count, 'translations from', options.locales); if (options.cache) { options.verbose && gutil.log('Cashing translations from', options.locales); cache[options.locales] = dictionaries; } } catch (e) { e.message = 'No translation dictionaries have been found!'; throw e; } }
[ "function", "load", "(", "options", ")", "{", "if", "(", "cache", "[", "options", ".", "locales", "]", ")", "{", "options", ".", "verbose", "&&", "gutil", ".", "log", "(", "'Skip loading cached translations from'", ",", "options", ".", "locales", ")", ";", "return", "dictionaries", "=", "cache", "[", "options", ".", "locales", "]", ";", "}", "try", "{", "options", ".", "verbose", "&&", "gutil", ".", "log", "(", "'Loading translations from'", ",", "options", ".", "locales", ")", ";", "var", "files", "=", "fs", ".", "readdirSync", "(", "options", ".", "locales", ")", ";", "var", "count", "=", "0", ";", "for", "(", "var", "i", "in", "files", ")", "{", "var", "file", "=", "files", "[", "i", "]", ";", "switch", "(", "path", ".", "extname", "(", "file", ")", ")", "{", "case", "'.json'", ":", "case", "'.js'", ":", "dictionaries", "[", "path", ".", "basename", "(", "file", ",", "path", ".", "extname", "(", "file", ")", ")", "]", "=", "flat", "(", "require", "(", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "options", ".", "locales", ",", "file", ")", ")", ")", ";", "options", ".", "verbose", "&&", "gutil", ".", "log", "(", "'Added translations from'", ",", "file", ")", ";", "count", "++", ";", "break", ";", "case", "'.ini'", ":", "var", "iniData", "=", "fs", ".", "readFileSync", "(", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "options", ".", "locales", ",", "file", ")", ")", ";", "dictionaries", "[", "path", ".", "basename", "(", "file", ",", "path", ".", "extname", "(", "file", ")", ")", "]", "=", "flat", "(", "ini2json", "(", "iniData", ")", ")", ";", "options", ".", "verbose", "&&", "gutil", ".", "log", "(", "'Added translations from'", ",", "file", ")", ";", "count", "++", ";", "break", ";", "case", "'.csv'", ":", "var", "csvData", "=", "fs", ".", "readFileSync", "(", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "options", ".", "locales", ",", "file", ")", ")", ";", "dictionaries", "[", "path", ".", "basename", "(", "file", ",", "path", ".", "extname", "(", "file", ")", ")", "]", "=", "csv2json", "(", "csvData", ")", ";", "options", ".", "verbose", "&&", "gutil", ".", "log", "(", "'Added translations from'", ",", "file", ")", ";", "count", "++", ";", "break", ";", "default", ":", "options", ".", "verbose", "&&", "gutil", ".", "log", "(", "'Ignored file'", ",", "file", ")", ";", "}", "}", "options", ".", "verbose", "&&", "gutil", ".", "log", "(", "'Loaded'", ",", "count", ",", "'translations from'", ",", "options", ".", "locales", ")", ";", "if", "(", "options", ".", "cache", ")", "{", "options", ".", "verbose", "&&", "gutil", ".", "log", "(", "'Cashing translations from'", ",", "options", ".", "locales", ")", ";", "cache", "[", "options", ".", "locales", "]", "=", "dictionaries", ";", "}", "}", "catch", "(", "e", ")", "{", "e", ".", "message", "=", "'No translation dictionaries have been found!'", ";", "throw", "e", ";", "}", "}" ]
Loads the dictionaries from the locale directory. @param {Object} options
[ "Loads", "the", "dictionaries", "from", "the", "locale", "directory", "." ]
0b235341acd1d72937e900f13fd4a6de855ff1e4
https://github.com/mallocator/gulp-international/blob/0b235341acd1d72937e900f13fd4a6de855ff1e4/index.js#L185-L228
37,293
mallocator/gulp-international
index.js
isBinary
function isBinary(buffer) { var chunk = buffer.toString('utf8', 0, Math.min(buffer.length, 24)); for (var i in chunk) { var charCode = chunk.charCodeAt(i); if (charCode == 65533 || charCode <= 8) { return true; } } return false; }
javascript
function isBinary(buffer) { var chunk = buffer.toString('utf8', 0, Math.min(buffer.length, 24)); for (var i in chunk) { var charCode = chunk.charCodeAt(i); if (charCode == 65533 || charCode <= 8) { return true; } } return false; }
[ "function", "isBinary", "(", "buffer", ")", "{", "var", "chunk", "=", "buffer", ".", "toString", "(", "'utf8'", ",", "0", ",", "Math", ".", "min", "(", "buffer", ".", "length", ",", "24", ")", ")", ";", "for", "(", "var", "i", "in", "chunk", ")", "{", "var", "charCode", "=", "chunk", ".", "charCodeAt", "(", "i", ")", ";", "if", "(", "charCode", "==", "65533", "||", "charCode", "<=", "8", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Helper function that detects whether a buffer is binary or utf8. @param {Buffer} buffer @returns {boolean}
[ "Helper", "function", "that", "detects", "whether", "a", "buffer", "is", "binary", "or", "utf8", "." ]
0b235341acd1d72937e900f13fd4a6de855ff1e4
https://github.com/mallocator/gulp-international/blob/0b235341acd1d72937e900f13fd4a6de855ff1e4/index.js#L235-L244
37,294
mallocator/gulp-international
index.js
replace
function replace(file, options) { var contents = file.contents; var copied = 0; var processed = translate(options, contents, copied, file.path); var files = []; for (var lang in processed) { var params = {}; params.ext = path.extname(file.path).substr(1); params.name = path.basename(file.path, path.extname(file.path)); params.path = file.path.substring(file.base.length, file.path.lastIndexOf(path.sep)); params.lang = lang; var filePath = options.filename; for (var param in params) { filePath = filePath.replace('${' + param + '}', params[param]); } filePath = path.join(file.base,filePath); var newFile = new gutil.File({ base: file.base, cwd: file.cwd, path: filePath, contents: new Buffer(processed[lang], 'utf8') }); files.push(newFile); } return files; }
javascript
function replace(file, options) { var contents = file.contents; var copied = 0; var processed = translate(options, contents, copied, file.path); var files = []; for (var lang in processed) { var params = {}; params.ext = path.extname(file.path).substr(1); params.name = path.basename(file.path, path.extname(file.path)); params.path = file.path.substring(file.base.length, file.path.lastIndexOf(path.sep)); params.lang = lang; var filePath = options.filename; for (var param in params) { filePath = filePath.replace('${' + param + '}', params[param]); } filePath = path.join(file.base,filePath); var newFile = new gutil.File({ base: file.base, cwd: file.cwd, path: filePath, contents: new Buffer(processed[lang], 'utf8') }); files.push(newFile); } return files; }
[ "function", "replace", "(", "file", ",", "options", ")", "{", "var", "contents", "=", "file", ".", "contents", ";", "var", "copied", "=", "0", ";", "var", "processed", "=", "translate", "(", "options", ",", "contents", ",", "copied", ",", "file", ".", "path", ")", ";", "var", "files", "=", "[", "]", ";", "for", "(", "var", "lang", "in", "processed", ")", "{", "var", "params", "=", "{", "}", ";", "params", ".", "ext", "=", "path", ".", "extname", "(", "file", ".", "path", ")", ".", "substr", "(", "1", ")", ";", "params", ".", "name", "=", "path", ".", "basename", "(", "file", ".", "path", ",", "path", ".", "extname", "(", "file", ".", "path", ")", ")", ";", "params", ".", "path", "=", "file", ".", "path", ".", "substring", "(", "file", ".", "base", ".", "length", ",", "file", ".", "path", ".", "lastIndexOf", "(", "path", ".", "sep", ")", ")", ";", "params", ".", "lang", "=", "lang", ";", "var", "filePath", "=", "options", ".", "filename", ";", "for", "(", "var", "param", "in", "params", ")", "{", "filePath", "=", "filePath", ".", "replace", "(", "'${'", "+", "param", "+", "'}'", ",", "params", "[", "param", "]", ")", ";", "}", "filePath", "=", "path", ".", "join", "(", "file", ".", "base", ",", "filePath", ")", ";", "var", "newFile", "=", "new", "gutil", ".", "File", "(", "{", "base", ":", "file", ".", "base", ",", "cwd", ":", "file", ".", "cwd", ",", "path", ":", "filePath", ",", "contents", ":", "new", "Buffer", "(", "processed", "[", "lang", "]", ",", "'utf8'", ")", "}", ")", ";", "files", ".", "push", "(", "newFile", ")", ";", "}", "return", "files", ";", "}" ]
Performs the actual replacing of tokens with translations. @param {File} file @param {Object} options @returns {File[]}
[ "Performs", "the", "actual", "replacing", "of", "tokens", "with", "translations", "." ]
0b235341acd1d72937e900f13fd4a6de855ff1e4
https://github.com/mallocator/gulp-international/blob/0b235341acd1d72937e900f13fd4a6de855ff1e4/index.js#L321-L351
37,295
mesqueeb/find-and-replace-anything
dist/index.esm.js
findAndReplace
function findAndReplace(target, find, replaceWith, config) { if (config === void 0) { config = { onlyPlainObjects: false }; } if ((config.onlyPlainObjects === false && !isAnyObject(target)) || (config.onlyPlainObjects === true && !isPlainObject(target))) { if (target === find) return replaceWith; return target; } return Object.keys(target) .reduce(function (carry, key) { var val = target[key]; carry[key] = findAndReplace(val, find, replaceWith, config); return carry; }, {}); }
javascript
function findAndReplace(target, find, replaceWith, config) { if (config === void 0) { config = { onlyPlainObjects: false }; } if ((config.onlyPlainObjects === false && !isAnyObject(target)) || (config.onlyPlainObjects === true && !isPlainObject(target))) { if (target === find) return replaceWith; return target; } return Object.keys(target) .reduce(function (carry, key) { var val = target[key]; carry[key] = findAndReplace(val, find, replaceWith, config); return carry; }, {}); }
[ "function", "findAndReplace", "(", "target", ",", "find", ",", "replaceWith", ",", "config", ")", "{", "if", "(", "config", "===", "void", "0", ")", "{", "config", "=", "{", "onlyPlainObjects", ":", "false", "}", ";", "}", "if", "(", "(", "config", ".", "onlyPlainObjects", "===", "false", "&&", "!", "isAnyObject", "(", "target", ")", ")", "||", "(", "config", ".", "onlyPlainObjects", "===", "true", "&&", "!", "isPlainObject", "(", "target", ")", ")", ")", "{", "if", "(", "target", "===", "find", ")", "return", "replaceWith", ";", "return", "target", ";", "}", "return", "Object", ".", "keys", "(", "target", ")", ".", "reduce", "(", "function", "(", "carry", ",", "key", ")", "{", "var", "val", "=", "target", "[", "key", "]", ";", "carry", "[", "key", "]", "=", "findAndReplace", "(", "val", ",", "find", ",", "replaceWith", ",", "config", ")", ";", "return", "carry", ";", "}", ",", "{", "}", ")", ";", "}" ]
Goes through an object recursively and replaces all occurences of the `find` value with `replaceWith`. Also works no non-objects. @export @param {*} target Target can be anything @param {*} find val to find @param {*} replaceWith val to replace @param {IConfig} [config={onlyPlainObjects: false}] @returns {*} the target with replaced values
[ "Goes", "through", "an", "object", "recursively", "and", "replaces", "all", "occurences", "of", "the", "find", "value", "with", "replaceWith", ".", "Also", "works", "no", "non", "-", "objects", "." ]
67ea731c5d39a222a804abc637d26061a3076001
https://github.com/mesqueeb/find-and-replace-anything/blob/67ea731c5d39a222a804abc637d26061a3076001/dist/index.esm.js#L13-L27
37,296
mesqueeb/find-and-replace-anything
dist/index.esm.js
findAndReplaceIf
function findAndReplaceIf(target, checkFn) { if (!isPlainObject(target)) return checkFn(target); return Object.keys(target) .reduce(function (carry, key) { var val = target[key]; carry[key] = findAndReplaceIf(val, checkFn); return carry; }, {}); }
javascript
function findAndReplaceIf(target, checkFn) { if (!isPlainObject(target)) return checkFn(target); return Object.keys(target) .reduce(function (carry, key) { var val = target[key]; carry[key] = findAndReplaceIf(val, checkFn); return carry; }, {}); }
[ "function", "findAndReplaceIf", "(", "target", ",", "checkFn", ")", "{", "if", "(", "!", "isPlainObject", "(", "target", ")", ")", "return", "checkFn", "(", "target", ")", ";", "return", "Object", ".", "keys", "(", "target", ")", ".", "reduce", "(", "function", "(", "carry", ",", "key", ")", "{", "var", "val", "=", "target", "[", "key", "]", ";", "carry", "[", "key", "]", "=", "findAndReplaceIf", "(", "val", ",", "checkFn", ")", ";", "return", "carry", ";", "}", ",", "{", "}", ")", ";", "}" ]
Goes through an object recursively and replaces all props with what's is returned in the `checkFn`. Also works no non-objects. @export @param {*} target Target can be anything @param {*} checkFn a function that will receive the `foundVal` @returns {*} the target with replaced values
[ "Goes", "through", "an", "object", "recursively", "and", "replaces", "all", "props", "with", "what", "s", "is", "returned", "in", "the", "checkFn", ".", "Also", "works", "no", "non", "-", "objects", "." ]
67ea731c5d39a222a804abc637d26061a3076001
https://github.com/mesqueeb/find-and-replace-anything/blob/67ea731c5d39a222a804abc637d26061a3076001/dist/index.esm.js#L36-L45
37,297
ProperJS/hobo
lib/core/on.js
function ( e ) { // Default context is `this` element var context = (selector ? matchElement( e.target, selector, true ) : this); // Handle `mouseenter` and `mouseleave` if ( event === "mouseenter" || event === "mouseleave" ) { var relatedElement = (event === "mouseenter" ? e.fromElement : e.toElement); if ( context && ( relatedElement !== context && !context.contains( relatedElement ) ) ) { callback.call( context, e ); } // Fire callback if context element } else if ( context ) { callback.call( context, e ); } }
javascript
function ( e ) { // Default context is `this` element var context = (selector ? matchElement( e.target, selector, true ) : this); // Handle `mouseenter` and `mouseleave` if ( event === "mouseenter" || event === "mouseleave" ) { var relatedElement = (event === "mouseenter" ? e.fromElement : e.toElement); if ( context && ( relatedElement !== context && !context.contains( relatedElement ) ) ) { callback.call( context, e ); } // Fire callback if context element } else if ( context ) { callback.call( context, e ); } }
[ "function", "(", "e", ")", "{", "// Default context is `this` element", "var", "context", "=", "(", "selector", "?", "matchElement", "(", "e", ".", "target", ",", "selector", ",", "true", ")", ":", "this", ")", ";", "// Handle `mouseenter` and `mouseleave`", "if", "(", "event", "===", "\"mouseenter\"", "||", "event", "===", "\"mouseleave\"", ")", "{", "var", "relatedElement", "=", "(", "event", "===", "\"mouseenter\"", "?", "e", ".", "fromElement", ":", "e", ".", "toElement", ")", ";", "if", "(", "context", "&&", "(", "relatedElement", "!==", "context", "&&", "!", "context", ".", "contains", "(", "relatedElement", ")", ")", ")", "{", "callback", ".", "call", "(", "context", ",", "e", ")", ";", "}", "// Fire callback if context element", "}", "else", "if", "(", "context", ")", "{", "callback", ".", "call", "(", "context", ",", "e", ")", ";", "}", "}" ]
Unique ID for each node event
[ "Unique", "ID", "for", "each", "node", "event" ]
505caadb3d66ba8257c188acb77645b335f66760
https://github.com/ProperJS/hobo/blob/505caadb3d66ba8257c188acb77645b335f66760/lib/core/on.js#L25-L41
37,298
tadam313/sheet-db
src/query.js
binaryOperator
function binaryOperator(queryObject, actualField, key) { return actualField + OPS[key] + stringify(queryObject, actualField); }
javascript
function binaryOperator(queryObject, actualField, key) { return actualField + OPS[key] + stringify(queryObject, actualField); }
[ "function", "binaryOperator", "(", "queryObject", ",", "actualField", ",", "key", ")", "{", "return", "actualField", "+", "OPS", "[", "key", "]", "+", "stringify", "(", "queryObject", ",", "actualField", ")", ";", "}" ]
Converts binary operator queries into string by applying operator and recursively invokes parsing process for rvalue. @param {object} queryObject Which contains the operator. @param {string} actualField Current field of the object which the filter is operating on. @param {string} key The current operation key. @returns {string}
[ "Converts", "binary", "operator", "queries", "into", "string", "by", "applying", "operator", "and", "recursively", "invokes", "parsing", "process", "for", "rvalue", "." ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/query.js#L84-L86
37,299
tadam313/sheet-db
src/query.js
logicalOperator
function logicalOperator(queryObject, actualField, key) { let textQuery = '('; for (let i = 0; i < queryObject.length; i++) { textQuery += (i > 0 ? OPS[key] : '') + stringify(queryObject[i], actualField); } return textQuery + ')'; }
javascript
function logicalOperator(queryObject, actualField, key) { let textQuery = '('; for (let i = 0; i < queryObject.length; i++) { textQuery += (i > 0 ? OPS[key] : '') + stringify(queryObject[i], actualField); } return textQuery + ')'; }
[ "function", "logicalOperator", "(", "queryObject", ",", "actualField", ",", "key", ")", "{", "let", "textQuery", "=", "'('", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "queryObject", ".", "length", ";", "i", "++", ")", "{", "textQuery", "+=", "(", "i", ">", "0", "?", "OPS", "[", "key", "]", ":", "''", ")", "+", "stringify", "(", "queryObject", "[", "i", "]", ",", "actualField", ")", ";", "}", "return", "textQuery", "+", "')'", ";", "}" ]
Converts logical operator queries into string by applying operator and recursively invokes parsing process for rvalue. @param {object} queryObject Which contains the operator. @param {string} actualField Current field of the object which the filter is operating on. @param {string} key Should be '$and' or '$or'. The current operation key. @returns {string}
[ "Converts", "logical", "operator", "queries", "into", "string", "by", "applying", "operator", "and", "recursively", "invokes", "parsing", "process", "for", "rvalue", "." ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/query.js#L97-L105