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
46,000
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/multi-object-manager.js
function(x, y, settings){ settings = settings || {}; if(settings.filter){ var filter = settings.filter; settings.filter = function(objects){ return objects.filter(filter); }; } var results = this.map.getAdjacent(x, y, settings); var out = []; // merge all arrays return out.concat.apply(out, results); }
javascript
function(x, y, settings){ settings = settings || {}; if(settings.filter){ var filter = settings.filter; settings.filter = function(objects){ return objects.filter(filter); }; } var results = this.map.getAdjacent(x, y, settings); var out = []; // merge all arrays return out.concat.apply(out, results); }
[ "function", "(", "x", ",", "y", ",", "settings", ")", "{", "settings", "=", "settings", "||", "{", "}", ";", "if", "(", "settings", ".", "filter", ")", "{", "var", "filter", "=", "settings", ".", "filter", ";", "settings", ".", "filter", "=", "function", "(", "objects", ")", "{", "return", "objects", ".", "filter", "(", "filter", ")", ";", "}", ";", "}", "var", "results", "=", "this", ".", "map", ".", "getAdjacent", "(", "x", ",", "y", ",", "settings", ")", ";", "var", "out", "=", "[", "]", ";", "// merge all arrays", "return", "out", ".", "concat", ".", "apply", "(", "out", ",", "results", ")", ";", "}" ]
Same as `this.map.getAdjacent`, but merges all results into on flat array. @method getAdjacent @param {Number} x - Map tile x coord. @param {Number} y - Map tile y coord; @param {Object} [settings] @return {Array}
[ "Same", "as", "this", ".", "map", ".", "getAdjacent", "but", "merges", "all", "results", "into", "on", "flat", "array", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/multi-object-manager.js#L224-L236
46,001
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/player.js
Player
function Player(game) { this.game = game; this.fov = new RL.FovROT(game); // modify fov to set tiles as explored this.fov.setMapTileVisible = function(x, y, range, visibility){ RL.FovROT.prototype.setMapTileVisible.call(this, x, y, range, visibility); if(visibility){ var tile = this.game.map.get(x, y); if(tile){ tile.explored = true; } } }; if(this.init){ this.init(game); } }
javascript
function Player(game) { this.game = game; this.fov = new RL.FovROT(game); // modify fov to set tiles as explored this.fov.setMapTileVisible = function(x, y, range, visibility){ RL.FovROT.prototype.setMapTileVisible.call(this, x, y, range, visibility); if(visibility){ var tile = this.game.map.get(x, y); if(tile){ tile.explored = true; } } }; if(this.init){ this.init(game); } }
[ "function", "Player", "(", "game", ")", "{", "this", ".", "game", "=", "game", ";", "this", ".", "fov", "=", "new", "RL", ".", "FovROT", "(", "game", ")", ";", "// modify fov to set tiles as explored", "this", ".", "fov", ".", "setMapTileVisible", "=", "function", "(", "x", ",", "y", ",", "range", ",", "visibility", ")", "{", "RL", ".", "FovROT", ".", "prototype", ".", "setMapTileVisible", ".", "call", "(", "this", ",", "x", ",", "y", ",", "range", ",", "visibility", ")", ";", "if", "(", "visibility", ")", "{", "var", "tile", "=", "this", ".", "game", ".", "map", ".", "get", "(", "x", ",", "y", ")", ";", "if", "(", "tile", ")", "{", "tile", ".", "explored", "=", "true", ";", "}", "}", "}", ";", "if", "(", "this", ".", "init", ")", "{", "this", ".", "init", "(", "game", ")", ";", "}", "}" ]
Represents the player. Very similar to Entity Handles functionality triggered by keyboard and mouse Input @class Player @constructor @uses TileDraw @param {Game} game - game instance this obj is attached to
[ "Represents", "the", "player", ".", "Very", "similar", "to", "Entity", "Handles", "functionality", "triggered", "by", "keyboard", "and", "mouse", "Input" ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/player.js#L13-L31
46,002
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/player.js
function(){ var x = this.x, y = this.y, fieldRange = this.fovFieldRange, direction = this.fovDirection, maxViewDistance = this.fovMaxViewDistance; this.fov.update(x, y, fieldRange, direction, maxViewDistance, this); }
javascript
function(){ var x = this.x, y = this.y, fieldRange = this.fovFieldRange, direction = this.fovDirection, maxViewDistance = this.fovMaxViewDistance; this.fov.update(x, y, fieldRange, direction, maxViewDistance, this); }
[ "function", "(", ")", "{", "var", "x", "=", "this", ".", "x", ",", "y", "=", "this", ".", "y", ",", "fieldRange", "=", "this", ".", "fovFieldRange", ",", "direction", "=", "this", ".", "fovDirection", ",", "maxViewDistance", "=", "this", ".", "fovMaxViewDistance", ";", "this", ".", "fov", ".", "update", "(", "x", ",", "y", ",", "fieldRange", ",", "direction", ",", "maxViewDistance", ",", "this", ")", ";", "}" ]
Updates this.fov @method updateFov
[ "Updates", "this", ".", "fov" ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/player.js#L144-L151
46,003
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/player.js
function(action) { // if the action is a direction if(RL.Util.DIRECTIONS_4.indexOf(action) !== -1){ var offsetCoord = RL.Util.getOffsetCoordsFromDirection(action), moveToX = this.x + offsetCoord.x, moveToY = this.y + offsetCoord.y; return this.move(moveToX, moveToY); } if(action === 'wait'){ this.wait(); return true; } return false; }
javascript
function(action) { // if the action is a direction if(RL.Util.DIRECTIONS_4.indexOf(action) !== -1){ var offsetCoord = RL.Util.getOffsetCoordsFromDirection(action), moveToX = this.x + offsetCoord.x, moveToY = this.y + offsetCoord.y; return this.move(moveToX, moveToY); } if(action === 'wait'){ this.wait(); return true; } return false; }
[ "function", "(", "action", ")", "{", "// if the action is a direction", "if", "(", "RL", ".", "Util", ".", "DIRECTIONS_4", ".", "indexOf", "(", "action", ")", "!==", "-", "1", ")", "{", "var", "offsetCoord", "=", "RL", ".", "Util", ".", "getOffsetCoordsFromDirection", "(", "action", ")", ",", "moveToX", "=", "this", ".", "x", "+", "offsetCoord", ".", "x", ",", "moveToY", "=", "this", ".", "y", "+", "offsetCoord", ".", "y", ";", "return", "this", ".", "move", "(", "moveToX", ",", "moveToY", ")", ";", "}", "if", "(", "action", "===", "'wait'", ")", "{", "this", ".", "wait", "(", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Called when user key is pressed with action of key pressed as an arg. @method update @param {String} action - action bound to key pressed by user @return {Bool} true if action was taken.
[ "Called", "when", "user", "key", "is", "pressed", "with", "action", "of", "key", "pressed", "as", "an", "arg", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/player.js#L181-L196
46,004
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/player.js
function(x, y){ if(this.canMoveTo(x, y)){ this.moveTo(x, y); return true; } else { // entity occupying target tile (if any) var targetTileEnt = this.game.entityManager.get(x, y); // if already occupied if(targetTileEnt){ this.game.console.log('Excuse me <strong>Mr.' + targetTileEnt.name + '</strong>, you appear to be in the way.'); return targetTileEnt.bump(this); } else { // targeted tile (attempting to move into) var targetTile = this.game.map.get(x, y); return targetTile.bump(this); } } return false; }
javascript
function(x, y){ if(this.canMoveTo(x, y)){ this.moveTo(x, y); return true; } else { // entity occupying target tile (if any) var targetTileEnt = this.game.entityManager.get(x, y); // if already occupied if(targetTileEnt){ this.game.console.log('Excuse me <strong>Mr.' + targetTileEnt.name + '</strong>, you appear to be in the way.'); return targetTileEnt.bump(this); } else { // targeted tile (attempting to move into) var targetTile = this.game.map.get(x, y); return targetTile.bump(this); } } return false; }
[ "function", "(", "x", ",", "y", ")", "{", "if", "(", "this", ".", "canMoveTo", "(", "x", ",", "y", ")", ")", "{", "this", ".", "moveTo", "(", "x", ",", "y", ")", ";", "return", "true", ";", "}", "else", "{", "// entity occupying target tile (if any)", "var", "targetTileEnt", "=", "this", ".", "game", ".", "entityManager", ".", "get", "(", "x", ",", "y", ")", ";", "// if already occupied", "if", "(", "targetTileEnt", ")", "{", "this", ".", "game", ".", "console", ".", "log", "(", "'Excuse me <strong>Mr.'", "+", "targetTileEnt", ".", "name", "+", "'</strong>, you appear to be in the way.'", ")", ";", "return", "targetTileEnt", ".", "bump", "(", "this", ")", ";", "}", "else", "{", "// targeted tile (attempting to move into)", "var", "targetTile", "=", "this", ".", "game", ".", "map", ".", "get", "(", "x", ",", "y", ")", ";", "return", "targetTile", ".", "bump", "(", "this", ")", ";", "}", "}", "return", "false", ";", "}" ]
Move action. @method move @param {Number} x - Map tile cood to move to. @param {Number} y - Map tile cood to move to. @return {Bool} true if action was taken.
[ "Move", "action", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/player.js#L205-L223
46,005
jonjomckay/jjgraph
javascript/examples/grapheditor/www/js/EditorUi.js
function(cells, asText) { graph.getModel().beginUpdate(); try { // Applies only basic text styles if (asText) { var edge = graph.getModel().isEdge(cell); var current = (edge) ? graph.currentEdgeStyle : graph.currentVertexStyle; var textStyles = ['fontSize', 'fontFamily', 'fontColor']; for (var j = 0; j < textStyles.length; j++) { var value = current[textStyles[j]]; if (value != null) { graph.setCellStyles(textStyles[j], value, cells); } } } else { for (var i = 0; i < cells.length; i++) { var cell = cells[i]; // Removes styles defined in the cell style from the styles to be applied var cellStyle = graph.getModel().getStyle(cell); var tokens = (cellStyle != null) ? cellStyle.split(';') : []; var appliedStyles = styles.slice(); for (var j = 0; j < tokens.length; j++) { var tmp = tokens[j]; var pos = tmp.indexOf('='); if (pos >= 0) { var key = tmp.substring(0, pos); var index = mxUtils.indexOf(appliedStyles, key); if (index >= 0) { appliedStyles.splice(index, 1); } // Handles special cases where one defined style ignores other styles for (var k = 0; k < keyGroups.length; k++) { var group = keyGroups[k]; if (mxUtils.indexOf(group, key) >= 0) { for (var l = 0; l < group.length; l++) { var index2 = mxUtils.indexOf(appliedStyles, group[l]); if (index2 >= 0) { appliedStyles.splice(index2, 1); } } } } } } // Applies the current style to the cell var edge = graph.getModel().isEdge(cell); var current = (edge) ? graph.currentEdgeStyle : graph.currentVertexStyle; for (var j = 0; j < appliedStyles.length; j++) { var key = appliedStyles[j]; var styleValue = current[key]; if (styleValue != null && (key != 'shape' || edge)) { // Special case: Connect styles are not applied here but in the connection handler if (!edge || mxUtils.indexOf(connectStyles, key) < 0) { graph.setCellStyles(key, styleValue, [cell]); } } } } } } finally { graph.getModel().endUpdate(); } }
javascript
function(cells, asText) { graph.getModel().beginUpdate(); try { // Applies only basic text styles if (asText) { var edge = graph.getModel().isEdge(cell); var current = (edge) ? graph.currentEdgeStyle : graph.currentVertexStyle; var textStyles = ['fontSize', 'fontFamily', 'fontColor']; for (var j = 0; j < textStyles.length; j++) { var value = current[textStyles[j]]; if (value != null) { graph.setCellStyles(textStyles[j], value, cells); } } } else { for (var i = 0; i < cells.length; i++) { var cell = cells[i]; // Removes styles defined in the cell style from the styles to be applied var cellStyle = graph.getModel().getStyle(cell); var tokens = (cellStyle != null) ? cellStyle.split(';') : []; var appliedStyles = styles.slice(); for (var j = 0; j < tokens.length; j++) { var tmp = tokens[j]; var pos = tmp.indexOf('='); if (pos >= 0) { var key = tmp.substring(0, pos); var index = mxUtils.indexOf(appliedStyles, key); if (index >= 0) { appliedStyles.splice(index, 1); } // Handles special cases where one defined style ignores other styles for (var k = 0; k < keyGroups.length; k++) { var group = keyGroups[k]; if (mxUtils.indexOf(group, key) >= 0) { for (var l = 0; l < group.length; l++) { var index2 = mxUtils.indexOf(appliedStyles, group[l]); if (index2 >= 0) { appliedStyles.splice(index2, 1); } } } } } } // Applies the current style to the cell var edge = graph.getModel().isEdge(cell); var current = (edge) ? graph.currentEdgeStyle : graph.currentVertexStyle; for (var j = 0; j < appliedStyles.length; j++) { var key = appliedStyles[j]; var styleValue = current[key]; if (styleValue != null && (key != 'shape' || edge)) { // Special case: Connect styles are not applied here but in the connection handler if (!edge || mxUtils.indexOf(connectStyles, key) < 0) { graph.setCellStyles(key, styleValue, [cell]); } } } } } } finally { graph.getModel().endUpdate(); } }
[ "function", "(", "cells", ",", "asText", ")", "{", "graph", ".", "getModel", "(", ")", ".", "beginUpdate", "(", ")", ";", "try", "{", "// Applies only basic text styles", "if", "(", "asText", ")", "{", "var", "edge", "=", "graph", ".", "getModel", "(", ")", ".", "isEdge", "(", "cell", ")", ";", "var", "current", "=", "(", "edge", ")", "?", "graph", ".", "currentEdgeStyle", ":", "graph", ".", "currentVertexStyle", ";", "var", "textStyles", "=", "[", "'fontSize'", ",", "'fontFamily'", ",", "'fontColor'", "]", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "textStyles", ".", "length", ";", "j", "++", ")", "{", "var", "value", "=", "current", "[", "textStyles", "[", "j", "]", "]", ";", "if", "(", "value", "!=", "null", ")", "{", "graph", ".", "setCellStyles", "(", "textStyles", "[", "j", "]", ",", "value", ",", "cells", ")", ";", "}", "}", "}", "else", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "cells", ".", "length", ";", "i", "++", ")", "{", "var", "cell", "=", "cells", "[", "i", "]", ";", "// Removes styles defined in the cell style from the styles to be applied", "var", "cellStyle", "=", "graph", ".", "getModel", "(", ")", ".", "getStyle", "(", "cell", ")", ";", "var", "tokens", "=", "(", "cellStyle", "!=", "null", ")", "?", "cellStyle", ".", "split", "(", "';'", ")", ":", "[", "]", ";", "var", "appliedStyles", "=", "styles", ".", "slice", "(", ")", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "tokens", ".", "length", ";", "j", "++", ")", "{", "var", "tmp", "=", "tokens", "[", "j", "]", ";", "var", "pos", "=", "tmp", ".", "indexOf", "(", "'='", ")", ";", "if", "(", "pos", ">=", "0", ")", "{", "var", "key", "=", "tmp", ".", "substring", "(", "0", ",", "pos", ")", ";", "var", "index", "=", "mxUtils", ".", "indexOf", "(", "appliedStyles", ",", "key", ")", ";", "if", "(", "index", ">=", "0", ")", "{", "appliedStyles", ".", "splice", "(", "index", ",", "1", ")", ";", "}", "// Handles special cases where one defined style ignores other styles", "for", "(", "var", "k", "=", "0", ";", "k", "<", "keyGroups", ".", "length", ";", "k", "++", ")", "{", "var", "group", "=", "keyGroups", "[", "k", "]", ";", "if", "(", "mxUtils", ".", "indexOf", "(", "group", ",", "key", ")", ">=", "0", ")", "{", "for", "(", "var", "l", "=", "0", ";", "l", "<", "group", ".", "length", ";", "l", "++", ")", "{", "var", "index2", "=", "mxUtils", ".", "indexOf", "(", "appliedStyles", ",", "group", "[", "l", "]", ")", ";", "if", "(", "index2", ">=", "0", ")", "{", "appliedStyles", ".", "splice", "(", "index2", ",", "1", ")", ";", "}", "}", "}", "}", "}", "}", "// Applies the current style to the cell", "var", "edge", "=", "graph", ".", "getModel", "(", ")", ".", "isEdge", "(", "cell", ")", ";", "var", "current", "=", "(", "edge", ")", "?", "graph", ".", "currentEdgeStyle", ":", "graph", ".", "currentVertexStyle", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "appliedStyles", ".", "length", ";", "j", "++", ")", "{", "var", "key", "=", "appliedStyles", "[", "j", "]", ";", "var", "styleValue", "=", "current", "[", "key", "]", ";", "if", "(", "styleValue", "!=", "null", "&&", "(", "key", "!=", "'shape'", "||", "edge", ")", ")", "{", "// Special case: Connect styles are not applied here but in the connection handler", "if", "(", "!", "edge", "||", "mxUtils", ".", "indexOf", "(", "connectStyles", ",", "key", ")", "<", "0", ")", "{", "graph", ".", "setCellStyles", "(", "key", ",", "styleValue", ",", "[", "cell", "]", ")", ";", "}", "}", "}", "}", "}", "}", "finally", "{", "graph", ".", "getModel", "(", ")", ".", "endUpdate", "(", ")", ";", "}", "}" ]
Implements a global current style for edges and vertices that is applied to new cells
[ "Implements", "a", "global", "current", "style", "for", "edges", "and", "vertices", "that", "is", "applied", "to", "new", "cells" ]
f041596ea8cb33e7a47e8c029008f13b31a92469
https://github.com/jonjomckay/jjgraph/blob/f041596ea8cb33e7a47e8c029008f13b31a92469/javascript/examples/grapheditor/www/js/EditorUi.js#L500-L594
46,006
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/fov-rot.js
function(direction){ var coord = RL.Util.getOffsetCoordsFromDirection(direction); return [coord.x, coord.y]; }
javascript
function(direction){ var coord = RL.Util.getOffsetCoordsFromDirection(direction); return [coord.x, coord.y]; }
[ "function", "(", "direction", ")", "{", "var", "coord", "=", "RL", ".", "Util", ".", "getOffsetCoordsFromDirection", "(", "direction", ")", ";", "return", "[", "coord", ".", "x", ",", "coord", ".", "y", "]", ";", "}" ]
Converts a string direction to an rot direction @method directionStringToArray @param {String} direction - Direction of fov (used as default) (not used for fieldRange 360) valid directions: ['up', 'down', 'left', 'right', 'up_left', 'up_right', 'down_left', 'down_right']. @return {Array} [x, y]
[ "Converts", "a", "string", "direction", "to", "an", "rot", "direction" ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/fov-rot.js#L89-L92
46,007
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/fov-rot.js
function(x, y, fieldRange, direction, maxViewDistance, entity){ if(fieldRange === void 0){ fieldRange = this.fieldRange; } if(direction === void 0){ direction = this.direction; } if(fieldRange !== 360 && typeof direction === 'string'){ direction = this.directionStringToArray(direction); } this.direction = direction; if(maxViewDistance === void 0){ maxViewDistance = this.maxViewDistance; } this.validateFieldRange(fieldRange); this.visibleTiles = []; this.visibleTileKeys = []; this.fovMap.reset(); var entityCanSeeThrough = this.getEntityCanSeeThroughCallback(entity); var fov = new ROT.FOV.RecursiveShadowcasting(entityCanSeeThrough); var setMapTileVisible = this.setMapTileVisible.bind(this); if(fieldRange === 360){ fov.compute(x, y, maxViewDistance, setMapTileVisible); } else { if(fieldRange === 180){ fov.compute180(x, y, maxViewDistance, direction, setMapTileVisible); } else if(fieldRange === 90){ fov.compute90(x, y, maxViewDistance, direction, setMapTileVisible); } } }
javascript
function(x, y, fieldRange, direction, maxViewDistance, entity){ if(fieldRange === void 0){ fieldRange = this.fieldRange; } if(direction === void 0){ direction = this.direction; } if(fieldRange !== 360 && typeof direction === 'string'){ direction = this.directionStringToArray(direction); } this.direction = direction; if(maxViewDistance === void 0){ maxViewDistance = this.maxViewDistance; } this.validateFieldRange(fieldRange); this.visibleTiles = []; this.visibleTileKeys = []; this.fovMap.reset(); var entityCanSeeThrough = this.getEntityCanSeeThroughCallback(entity); var fov = new ROT.FOV.RecursiveShadowcasting(entityCanSeeThrough); var setMapTileVisible = this.setMapTileVisible.bind(this); if(fieldRange === 360){ fov.compute(x, y, maxViewDistance, setMapTileVisible); } else { if(fieldRange === 180){ fov.compute180(x, y, maxViewDistance, direction, setMapTileVisible); } else if(fieldRange === 90){ fov.compute90(x, y, maxViewDistance, direction, setMapTileVisible); } } }
[ "function", "(", "x", ",", "y", ",", "fieldRange", ",", "direction", ",", "maxViewDistance", ",", "entity", ")", "{", "if", "(", "fieldRange", "===", "void", "0", ")", "{", "fieldRange", "=", "this", ".", "fieldRange", ";", "}", "if", "(", "direction", "===", "void", "0", ")", "{", "direction", "=", "this", ".", "direction", ";", "}", "if", "(", "fieldRange", "!==", "360", "&&", "typeof", "direction", "===", "'string'", ")", "{", "direction", "=", "this", ".", "directionStringToArray", "(", "direction", ")", ";", "}", "this", ".", "direction", "=", "direction", ";", "if", "(", "maxViewDistance", "===", "void", "0", ")", "{", "maxViewDistance", "=", "this", ".", "maxViewDistance", ";", "}", "this", ".", "validateFieldRange", "(", "fieldRange", ")", ";", "this", ".", "visibleTiles", "=", "[", "]", ";", "this", ".", "visibleTileKeys", "=", "[", "]", ";", "this", ".", "fovMap", ".", "reset", "(", ")", ";", "var", "entityCanSeeThrough", "=", "this", ".", "getEntityCanSeeThroughCallback", "(", "entity", ")", ";", "var", "fov", "=", "new", "ROT", ".", "FOV", ".", "RecursiveShadowcasting", "(", "entityCanSeeThrough", ")", ";", "var", "setMapTileVisible", "=", "this", ".", "setMapTileVisible", ".", "bind", "(", "this", ")", ";", "if", "(", "fieldRange", "===", "360", ")", "{", "fov", ".", "compute", "(", "x", ",", "y", ",", "maxViewDistance", ",", "setMapTileVisible", ")", ";", "}", "else", "{", "if", "(", "fieldRange", "===", "180", ")", "{", "fov", ".", "compute180", "(", "x", ",", "y", ",", "maxViewDistance", ",", "direction", ",", "setMapTileVisible", ")", ";", "}", "else", "if", "(", "fieldRange", "===", "90", ")", "{", "fov", ".", "compute90", "(", "x", ",", "y", ",", "maxViewDistance", ",", "direction", ",", "setMapTileVisible", ")", ";", "}", "}", "}" ]
Calculates the fovROT data relative to given coords. @method update @param {Number} x - The map coordinate position to calculate FovROT from on the x axis. @param {Number} y - The map coordinate position to calculate FovROT from on the y axis. @param {Number} [fieldRange = this.fieldRange || 360] - Field Range of view 90, 180, or 360. @param {String|ROT.DIRS[8].x} [direction = this.direction || 'up'] - Direction of fov (not used for fieldRange 360) valid directions: ['up', 'down', 'left', 'right', 'up_left', 'up_right', 'down_left', 'down_right'];. @param {Number} [maxViewDistance = this.maxViewDistance] - Max visible distance in tiles. @param {Entity} [entity] - The entity to check tile visibility with.
[ "Calculates", "the", "fovROT", "data", "relative", "to", "given", "coords", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/fov-rot.js#L104-L143
46,008
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/fov-rot.js
function(x, y, range, visibility){ this.fovMap.set(x, y, visibility); if(visibility){ var tile = this.game.map.get(x, y); if(tile){ var key = x + ',' + y; // check for duplicates if(this.visibleTileKeys.indexOf(key) === -1){ this.visibleTiles.push({ x: x, y: y, value: tile, range: range }); this.visibleTileKeys.push(key); } } } }
javascript
function(x, y, range, visibility){ this.fovMap.set(x, y, visibility); if(visibility){ var tile = this.game.map.get(x, y); if(tile){ var key = x + ',' + y; // check for duplicates if(this.visibleTileKeys.indexOf(key) === -1){ this.visibleTiles.push({ x: x, y: y, value: tile, range: range }); this.visibleTileKeys.push(key); } } } }
[ "function", "(", "x", ",", "y", ",", "range", ",", "visibility", ")", "{", "this", ".", "fovMap", ".", "set", "(", "x", ",", "y", ",", "visibility", ")", ";", "if", "(", "visibility", ")", "{", "var", "tile", "=", "this", ".", "game", ".", "map", ".", "get", "(", "x", ",", "y", ")", ";", "if", "(", "tile", ")", "{", "var", "key", "=", "x", "+", "','", "+", "y", ";", "// check for duplicates", "if", "(", "this", ".", "visibleTileKeys", ".", "indexOf", "(", "key", ")", "===", "-", "1", ")", "{", "this", ".", "visibleTiles", ".", "push", "(", "{", "x", ":", "x", ",", "y", ":", "y", ",", "value", ":", "tile", ",", "range", ":", "range", "}", ")", ";", "this", ".", "visibleTileKeys", ".", "push", "(", "key", ")", ";", "}", "}", "}", "}" ]
Sets the visibility of a checked map tile @method setMapTileVisible @param {Number} x - The map coord position to set. @param {Number} y - The map coord position to set. @param {Number} range - The distance from this fov origin. @param {Number} visibility - The visibility of this tile coord.
[ "Sets", "the", "visibility", "of", "a", "checked", "map", "tile" ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/fov-rot.js#L177-L195
46,009
THEjoezack/BoxPusher
public/js-roguelike-skeleton/manual-src/task.js
function(files, metalsmith, done){ var yuiDocsData = require('../docs/data.json'); var makeUrl = function(docClass, method){ var out = '/docs/classes/' + docClass + '.html'; if(method){ out += '#method_' + method; } return out; }; for(var key in files){ var file = files[key]; if(file.docs_class){ file.yui_class_data = yuiDocsData.classes[file.docs_class]; if(file.docs_method){ file.yui_method_url = makeUrl(file.docs_class) + '#method_' + file.docs_class; } } var relatedDocs = file.related_methods; var relatedDocsFormatted = []; if(relatedDocs){ relatedDocs.forEach(function(doc){ if(doc.indexOf('.') !== -1){ var arr = doc.split('.'); relatedDocsFormatted.push({ name: arr[0] + '.prototype.' + arr[1] + '()', class: arr[0], method: arr[1], url: makeUrl(arr[0], arr[1]) }); } else { relatedDocsFormatted.push({ name: doc + '()', class: doc, url: makeUrl(doc) }); } }); file.related_docs = relatedDocsFormatted; } } done(); }
javascript
function(files, metalsmith, done){ var yuiDocsData = require('../docs/data.json'); var makeUrl = function(docClass, method){ var out = '/docs/classes/' + docClass + '.html'; if(method){ out += '#method_' + method; } return out; }; for(var key in files){ var file = files[key]; if(file.docs_class){ file.yui_class_data = yuiDocsData.classes[file.docs_class]; if(file.docs_method){ file.yui_method_url = makeUrl(file.docs_class) + '#method_' + file.docs_class; } } var relatedDocs = file.related_methods; var relatedDocsFormatted = []; if(relatedDocs){ relatedDocs.forEach(function(doc){ if(doc.indexOf('.') !== -1){ var arr = doc.split('.'); relatedDocsFormatted.push({ name: arr[0] + '.prototype.' + arr[1] + '()', class: arr[0], method: arr[1], url: makeUrl(arr[0], arr[1]) }); } else { relatedDocsFormatted.push({ name: doc + '()', class: doc, url: makeUrl(doc) }); } }); file.related_docs = relatedDocsFormatted; } } done(); }
[ "function", "(", "files", ",", "metalsmith", ",", "done", ")", "{", "var", "yuiDocsData", "=", "require", "(", "'../docs/data.json'", ")", ";", "var", "makeUrl", "=", "function", "(", "docClass", ",", "method", ")", "{", "var", "out", "=", "'/docs/classes/'", "+", "docClass", "+", "'.html'", ";", "if", "(", "method", ")", "{", "out", "+=", "'#method_'", "+", "method", ";", "}", "return", "out", ";", "}", ";", "for", "(", "var", "key", "in", "files", ")", "{", "var", "file", "=", "files", "[", "key", "]", ";", "if", "(", "file", ".", "docs_class", ")", "{", "file", ".", "yui_class_data", "=", "yuiDocsData", ".", "classes", "[", "file", ".", "docs_class", "]", ";", "if", "(", "file", ".", "docs_method", ")", "{", "file", ".", "yui_method_url", "=", "makeUrl", "(", "file", ".", "docs_class", ")", "+", "'#method_'", "+", "file", ".", "docs_class", ";", "}", "}", "var", "relatedDocs", "=", "file", ".", "related_methods", ";", "var", "relatedDocsFormatted", "=", "[", "]", ";", "if", "(", "relatedDocs", ")", "{", "relatedDocs", ".", "forEach", "(", "function", "(", "doc", ")", "{", "if", "(", "doc", ".", "indexOf", "(", "'.'", ")", "!==", "-", "1", ")", "{", "var", "arr", "=", "doc", ".", "split", "(", "'.'", ")", ";", "relatedDocsFormatted", ".", "push", "(", "{", "name", ":", "arr", "[", "0", "]", "+", "'.prototype.'", "+", "arr", "[", "1", "]", "+", "'()'", ",", "class", ":", "arr", "[", "0", "]", ",", "method", ":", "arr", "[", "1", "]", ",", "url", ":", "makeUrl", "(", "arr", "[", "0", "]", ",", "arr", "[", "1", "]", ")", "}", ")", ";", "}", "else", "{", "relatedDocsFormatted", ".", "push", "(", "{", "name", ":", "doc", "+", "'()'", ",", "class", ":", "doc", ",", "url", ":", "makeUrl", "(", "doc", ")", "}", ")", ";", "}", "}", ")", ";", "file", ".", "related_docs", "=", "relatedDocsFormatted", ";", "}", "}", "done", "(", ")", ";", "}" ]
sets yui docs data to pages with "docs_class" set
[ "sets", "yui", "docs", "data", "to", "pages", "with", "docs_class", "set" ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/manual-src/task.js#L64-L107
46,010
jacoborus/deep-json
index.js
function (file) { var folder = path.dirname(file) + '/' + path.basename( file, '.json' ); return fs.existsSync(folder) && isDir(folder) ? folder : false; }
javascript
function (file) { var folder = path.dirname(file) + '/' + path.basename( file, '.json' ); return fs.existsSync(folder) && isDir(folder) ? folder : false; }
[ "function", "(", "file", ")", "{", "var", "folder", "=", "path", ".", "dirname", "(", "file", ")", "+", "'/'", "+", "path", ".", "basename", "(", "file", ",", "'.json'", ")", ";", "return", "fs", ".", "existsSync", "(", "folder", ")", "&&", "isDir", "(", "folder", ")", "?", "folder", ":", "false", ";", "}" ]
return path of folder with same name as .json file if exists
[ "return", "path", "of", "folder", "with", "same", "name", "as", ".", "json", "file", "if", "exists" ]
d41f35cc67b21b87c39da42d264bbdcf891ec93c
https://github.com/jacoborus/deep-json/blob/d41f35cc67b21b87c39da42d264bbdcf891ec93c/index.js#L13-L16
46,011
jacoborus/deep-json
index.js
function (parent) { var elems = fs.readdirSync( parent ), d = { files : [], folders : [] }; // get files and folders paths elems.forEach( function (elem) { var el = parent + '/' + elem; if (!isDir( el )) { d.files.push( el ); } else if (!fs.existsSync( el + '.json')) { // add folder only if has no namesake json d.folders.push( el ); } }); return d; }
javascript
function (parent) { var elems = fs.readdirSync( parent ), d = { files : [], folders : [] }; // get files and folders paths elems.forEach( function (elem) { var el = parent + '/' + elem; if (!isDir( el )) { d.files.push( el ); } else if (!fs.existsSync( el + '.json')) { // add folder only if has no namesake json d.folders.push( el ); } }); return d; }
[ "function", "(", "parent", ")", "{", "var", "elems", "=", "fs", ".", "readdirSync", "(", "parent", ")", ",", "d", "=", "{", "files", ":", "[", "]", ",", "folders", ":", "[", "]", "}", ";", "// get files and folders paths", "elems", ".", "forEach", "(", "function", "(", "elem", ")", "{", "var", "el", "=", "parent", "+", "'/'", "+", "elem", ";", "if", "(", "!", "isDir", "(", "el", ")", ")", "{", "d", ".", "files", ".", "push", "(", "el", ")", ";", "}", "else", "if", "(", "!", "fs", ".", "existsSync", "(", "el", "+", "'.json'", ")", ")", "{", "// add folder only if has no namesake json", "d", ".", "folders", ".", "push", "(", "el", ")", ";", "}", "}", ")", ";", "return", "d", ";", "}" ]
get the paths of files and folders inside a folder
[ "get", "the", "paths", "of", "files", "and", "folders", "inside", "a", "folder" ]
d41f35cc67b21b87c39da42d264bbdcf891ec93c
https://github.com/jacoborus/deep-json/blob/d41f35cc67b21b87c39da42d264bbdcf891ec93c/index.js#L19-L38
46,012
jacoborus/deep-json
index.js
function (file) { var config = require( file ), namesake = getNamesake( file ); return namesake ? extend( config, getData.folder( namesake )) : config; }
javascript
function (file) { var config = require( file ), namesake = getNamesake( file ); return namesake ? extend( config, getData.folder( namesake )) : config; }
[ "function", "(", "file", ")", "{", "var", "config", "=", "require", "(", "file", ")", ",", "namesake", "=", "getNamesake", "(", "file", ")", ";", "return", "namesake", "?", "extend", "(", "config", ",", "getData", ".", "folder", "(", "namesake", ")", ")", ":", "config", ";", "}" ]
get file data and extend it with folder data of folder with same name
[ "get", "file", "data", "and", "extend", "it", "with", "folder", "data", "of", "folder", "with", "same", "name" ]
d41f35cc67b21b87c39da42d264bbdcf891ec93c
https://github.com/jacoborus/deep-json/blob/d41f35cc67b21b87c39da42d264bbdcf891ec93c/index.js#L44-L49
46,013
jacoborus/deep-json
index.js
function (folder) { var elems = getFolderElements( folder ), result = {}; // files elems.files.forEach( function (route) { // get object name var fileName = path.basename( route, '.json' ); // assign object data from file result[ fileName ] = getData.file( route ); }); // no namesake folders elems.folders.forEach( function (route) { // get object name var fileName = path.basename( route ); // assign data from folder result[ fileName ] = extend( result[ fileName ] || {}, getData.folder( route )); }); return result; }
javascript
function (folder) { var elems = getFolderElements( folder ), result = {}; // files elems.files.forEach( function (route) { // get object name var fileName = path.basename( route, '.json' ); // assign object data from file result[ fileName ] = getData.file( route ); }); // no namesake folders elems.folders.forEach( function (route) { // get object name var fileName = path.basename( route ); // assign data from folder result[ fileName ] = extend( result[ fileName ] || {}, getData.folder( route )); }); return result; }
[ "function", "(", "folder", ")", "{", "var", "elems", "=", "getFolderElements", "(", "folder", ")", ",", "result", "=", "{", "}", ";", "// files", "elems", ".", "files", ".", "forEach", "(", "function", "(", "route", ")", "{", "// get object name", "var", "fileName", "=", "path", ".", "basename", "(", "route", ",", "'.json'", ")", ";", "// assign object data from file", "result", "[", "fileName", "]", "=", "getData", ".", "file", "(", "route", ")", ";", "}", ")", ";", "// no namesake folders", "elems", ".", "folders", ".", "forEach", "(", "function", "(", "route", ")", "{", "// get object name", "var", "fileName", "=", "path", ".", "basename", "(", "route", ")", ";", "// assign data from folder", "result", "[", "fileName", "]", "=", "extend", "(", "result", "[", "fileName", "]", "||", "{", "}", ",", "getData", ".", "folder", "(", "route", ")", ")", ";", "}", ")", ";", "return", "result", ";", "}" ]
get data from folders and files inside a folder
[ "get", "data", "from", "folders", "and", "files", "inside", "a", "folder" ]
d41f35cc67b21b87c39da42d264bbdcf891ec93c
https://github.com/jacoborus/deep-json/blob/d41f35cc67b21b87c39da42d264bbdcf891ec93c/index.js#L52-L73
46,014
commenthol/debug-level
src/browser.js
Log
function Log (name, opts) { if (!(this instanceof Log)) return new Log(name, opts) const _storage = storage() Object.assign(options, inspectOpts(_storage), inspectNamespaces(_storage) ) options.colors = options.colors === false ? false : supportsColors() LogBase.call(this, name, Object.assign({}, options, opts)) const colorFn = (c) => `color:${c}` this.color = selectColor(name, colorFn) this.levColors = levelColors(colorFn) this.queue = new Queue(this._sendLog.bind(this), 3) }
javascript
function Log (name, opts) { if (!(this instanceof Log)) return new Log(name, opts) const _storage = storage() Object.assign(options, inspectOpts(_storage), inspectNamespaces(_storage) ) options.colors = options.colors === false ? false : supportsColors() LogBase.call(this, name, Object.assign({}, options, opts)) const colorFn = (c) => `color:${c}` this.color = selectColor(name, colorFn) this.levColors = levelColors(colorFn) this.queue = new Queue(this._sendLog.bind(this), 3) }
[ "function", "Log", "(", "name", ",", "opts", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Log", ")", ")", "return", "new", "Log", "(", "name", ",", "opts", ")", "const", "_storage", "=", "storage", "(", ")", "Object", ".", "assign", "(", "options", ",", "inspectOpts", "(", "_storage", ")", ",", "inspectNamespaces", "(", "_storage", ")", ")", "options", ".", "colors", "=", "options", ".", "colors", "===", "false", "?", "false", ":", "supportsColors", "(", ")", "LogBase", ".", "call", "(", "this", ",", "name", ",", "Object", ".", "assign", "(", "{", "}", ",", "options", ",", "opts", ")", ")", "const", "colorFn", "=", "(", "c", ")", "=>", "`", "${", "c", "}", "`", "this", ".", "color", "=", "selectColor", "(", "name", ",", "colorFn", ")", "this", ".", "levColors", "=", "levelColors", "(", "colorFn", ")", "this", ".", "queue", "=", "new", "Queue", "(", "this", ".", "_sendLog", ".", "bind", "(", "this", ")", ",", "3", ")", "}" ]
creates a new logger for the browser @constructor @param {String} name - namespace of Logger
[ "creates", "a", "new", "logger", "for", "the", "browser" ]
e310fe5452984d898adfb8f924ac6f9021b05457
https://github.com/commenthol/debug-level/blob/e310fe5452984d898adfb8f924ac6f9021b05457/src/browser.js#L82-L96
46,015
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/object-manager.js
ObjectManager
function ObjectManager(game, ObjectConstructor, width, height) { this.game = game; this.ObjectConstructor = ObjectConstructor; this.objects = []; this.map = new RL.Array2d(width, height); }
javascript
function ObjectManager(game, ObjectConstructor, width, height) { this.game = game; this.ObjectConstructor = ObjectConstructor; this.objects = []; this.map = new RL.Array2d(width, height); }
[ "function", "ObjectManager", "(", "game", ",", "ObjectConstructor", ",", "width", ",", "height", ")", "{", "this", ".", "game", "=", "game", ";", "this", ".", "ObjectConstructor", "=", "ObjectConstructor", ";", "this", ".", "objects", "=", "[", "]", ";", "this", ".", "map", "=", "new", "RL", ".", "Array2d", "(", "width", ",", "height", ")", ";", "}" ]
Manages a list of all objects and their tile positions. Handles adding, removing, moving objects within the game. @class ObjectManager @constructor @param {Game} game - Game instance this `ObjectManager` is attached to. @param {Object} ObjectConstructor - Object constructor used to create new objects with `this.add()`. @param {Number} [width] - Width of current map in tiles. @param {Number} [height] - Height of current map in tiles.
[ "Manages", "a", "list", "of", "all", "objects", "and", "their", "tile", "positions", ".", "Handles", "adding", "removing", "moving", "objects", "within", "the", "game", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/object-manager.js#L14-L19
46,016
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/object-manager.js
function(x, y, obj) { if(typeof obj === 'string'){ obj = this.makeNewObjectFromType(obj); } var existing = this.get(x, y); if(existing){ this.remove(existing); } obj.game = this.game; obj.x = x; obj.y = y; this.objects.push(obj); this.map.set(x, y, obj); if(obj.onAdd){ obj.onAdd(); } return obj; }
javascript
function(x, y, obj) { if(typeof obj === 'string'){ obj = this.makeNewObjectFromType(obj); } var existing = this.get(x, y); if(existing){ this.remove(existing); } obj.game = this.game; obj.x = x; obj.y = y; this.objects.push(obj); this.map.set(x, y, obj); if(obj.onAdd){ obj.onAdd(); } return obj; }
[ "function", "(", "x", ",", "y", ",", "obj", ")", "{", "if", "(", "typeof", "obj", "===", "'string'", ")", "{", "obj", "=", "this", ".", "makeNewObjectFromType", "(", "obj", ")", ";", "}", "var", "existing", "=", "this", ".", "get", "(", "x", ",", "y", ")", ";", "if", "(", "existing", ")", "{", "this", ".", "remove", "(", "existing", ")", ";", "}", "obj", ".", "game", "=", "this", ".", "game", ";", "obj", ".", "x", "=", "x", ";", "obj", ".", "y", "=", "y", ";", "this", ".", "objects", ".", "push", "(", "obj", ")", ";", "this", ".", "map", ".", "set", "(", "x", ",", "y", ",", "obj", ")", ";", "if", "(", "obj", ".", "onAdd", ")", "{", "obj", ".", "onAdd", "(", ")", ";", "}", "return", "obj", ";", "}" ]
Adds an object to the manager at given map tile coord. If an object is already at this map tile coord it is removed from the manager completely. @method add @param {Number} x - The tile map coord x. @param {Number} y - The tile map coord y. @param {Object|String} obj - The Object being set at given coords. If obj is a string a new Object will be created using `this.makeNewObjectFromType(obj)`. @return {Object} The added object.
[ "Adds", "an", "object", "to", "the", "manager", "at", "given", "map", "tile", "coord", ".", "If", "an", "object", "is", "already", "at", "this", "map", "tile", "coord", "it", "is", "removed", "from", "the", "manager", "completely", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/object-manager.js#L65-L82
46,017
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/object-manager.js
function(object) { this.map.remove(object.x, object.y); var index = this.objects.indexOf(object); this.objects.splice(index, 1); if(object.onRemove){ object.onRemove(); } }
javascript
function(object) { this.map.remove(object.x, object.y); var index = this.objects.indexOf(object); this.objects.splice(index, 1); if(object.onRemove){ object.onRemove(); } }
[ "function", "(", "object", ")", "{", "this", ".", "map", ".", "remove", "(", "object", ".", "x", ",", "object", ".", "y", ")", ";", "var", "index", "=", "this", ".", "objects", ".", "indexOf", "(", "object", ")", ";", "this", ".", "objects", ".", "splice", "(", "index", ",", "1", ")", ";", "if", "(", "object", ".", "onRemove", ")", "{", "object", ".", "onRemove", "(", ")", ";", "}", "}" ]
Removes an object from the manager. @method remove @param {Object} object - The objectity to be removed.
[ "Removes", "an", "object", "from", "the", "manager", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/object-manager.js#L89-L96
46,018
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/object-manager.js
function(x, y, object) { var existing = this.get(object.x, object.y); if(existing !== object){ throw new Error({error: 'Attempting to move object not in correct position in Object manager', x: x, y: y, object: object}); } if(this.objects.indexOf(object) === -1){ throw new Error({error: 'Attempting to move object not in Object manager', x: x, y: y, object: object}); } this.map.remove(object.x, object.y); this.map.set(x, y, object); object.x = x; object.y = y; }
javascript
function(x, y, object) { var existing = this.get(object.x, object.y); if(existing !== object){ throw new Error({error: 'Attempting to move object not in correct position in Object manager', x: x, y: y, object: object}); } if(this.objects.indexOf(object) === -1){ throw new Error({error: 'Attempting to move object not in Object manager', x: x, y: y, object: object}); } this.map.remove(object.x, object.y); this.map.set(x, y, object); object.x = x; object.y = y; }
[ "function", "(", "x", ",", "y", ",", "object", ")", "{", "var", "existing", "=", "this", ".", "get", "(", "object", ".", "x", ",", "object", ".", "y", ")", ";", "if", "(", "existing", "!==", "object", ")", "{", "throw", "new", "Error", "(", "{", "error", ":", "'Attempting to move object not in correct position in Object manager'", ",", "x", ":", "x", ",", "y", ":", "y", ",", "object", ":", "object", "}", ")", ";", "}", "if", "(", "this", ".", "objects", ".", "indexOf", "(", "object", ")", "===", "-", "1", ")", "{", "throw", "new", "Error", "(", "{", "error", ":", "'Attempting to move object not in Object manager'", ",", "x", ":", "x", ",", "y", ":", "y", ",", "object", ":", "object", "}", ")", ";", "}", "this", ".", "map", ".", "remove", "(", "object", ".", "x", ",", "object", ".", "y", ")", ";", "this", ".", "map", ".", "set", "(", "x", ",", "y", ",", "object", ")", ";", "object", ".", "x", "=", "x", ";", "object", ".", "y", "=", "y", ";", "}" ]
Changes the position of an object already added to this objectManager. @method move @param {Number} x - The destination tile map coord x. @param {Number} y - The destination tile map coord y. @param {Obj} object - The objectity to be removed.
[ "Changes", "the", "position", "of", "an", "object", "already", "added", "to", "this", "objectManager", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/object-manager.js#L105-L118
46,019
nodeca/plurals-cldr
support/generate.js
toSingleRule
function toSingleRule(str) { return str // replace modulus with shortcuts .replace(/([nivwft]) % (\d+)/g, '$1$2') // replace ranges .replace(/([nivwft]\d*) (=|\!=) (\d+[.,][.,\d]+)/g, function (match, v, cond, range) { // range = 5,8,9 (simple set) if (range.indexOf('..') < 0 && range.indexOf(',') >= 0) { if (cond === '=') { return format('IN([ %s ], %s)', range.split(',').join(', '), v); } return format('!IN([ %s ], %s)', range.split(',').join(', '), v); } // range = 0..5 or 0..5,8..20 or 0..5,8 var conditions = range.split(',').map(function (interval) { // simple value if (interval.indexOf('..') < 0) { return format('%s %s %s', v, cond, interval); } // range var start = interval.split('..')[0], end = interval.split('..')[1]; if (cond === '=') { return format('B(%s, %s, %s)', start, end, v); } return format('!B(%s, %s, %s)', start, end, v); }); var joined; if (conditions.length > 1) { joined = '(' + conditions.join(cond === '=' ? ' || ' : ' && ') + ')'; } else { joined = conditions[0]; } return joined; }) .replace(/ = /g, ' === ') .replace(/ != /g, ' !== ') .replace(/ or /g, ' || ') .replace(/ and /g, ' && '); }
javascript
function toSingleRule(str) { return str // replace modulus with shortcuts .replace(/([nivwft]) % (\d+)/g, '$1$2') // replace ranges .replace(/([nivwft]\d*) (=|\!=) (\d+[.,][.,\d]+)/g, function (match, v, cond, range) { // range = 5,8,9 (simple set) if (range.indexOf('..') < 0 && range.indexOf(',') >= 0) { if (cond === '=') { return format('IN([ %s ], %s)', range.split(',').join(', '), v); } return format('!IN([ %s ], %s)', range.split(',').join(', '), v); } // range = 0..5 or 0..5,8..20 or 0..5,8 var conditions = range.split(',').map(function (interval) { // simple value if (interval.indexOf('..') < 0) { return format('%s %s %s', v, cond, interval); } // range var start = interval.split('..')[0], end = interval.split('..')[1]; if (cond === '=') { return format('B(%s, %s, %s)', start, end, v); } return format('!B(%s, %s, %s)', start, end, v); }); var joined; if (conditions.length > 1) { joined = '(' + conditions.join(cond === '=' ? ' || ' : ' && ') + ')'; } else { joined = conditions[0]; } return joined; }) .replace(/ = /g, ' === ') .replace(/ != /g, ' !== ') .replace(/ or /g, ' || ') .replace(/ and /g, ' && '); }
[ "function", "toSingleRule", "(", "str", ")", "{", "return", "str", "// replace modulus with shortcuts", ".", "replace", "(", "/", "([nivwft]) % (\\d+)", "/", "g", ",", "'$1$2'", ")", "// replace ranges", ".", "replace", "(", "/", "([nivwft]\\d*) (=|\\!=) (\\d+[.,][.,\\d]+)", "/", "g", ",", "function", "(", "match", ",", "v", ",", "cond", ",", "range", ")", "{", "// range = 5,8,9 (simple set)", "if", "(", "range", ".", "indexOf", "(", "'..'", ")", "<", "0", "&&", "range", ".", "indexOf", "(", "','", ")", ">=", "0", ")", "{", "if", "(", "cond", "===", "'='", ")", "{", "return", "format", "(", "'IN([ %s ], %s)'", ",", "range", ".", "split", "(", "','", ")", ".", "join", "(", "', '", ")", ",", "v", ")", ";", "}", "return", "format", "(", "'!IN([ %s ], %s)'", ",", "range", ".", "split", "(", "','", ")", ".", "join", "(", "', '", ")", ",", "v", ")", ";", "}", "// range = 0..5 or 0..5,8..20 or 0..5,8", "var", "conditions", "=", "range", ".", "split", "(", "','", ")", ".", "map", "(", "function", "(", "interval", ")", "{", "// simple value", "if", "(", "interval", ".", "indexOf", "(", "'..'", ")", "<", "0", ")", "{", "return", "format", "(", "'%s %s %s'", ",", "v", ",", "cond", ",", "interval", ")", ";", "}", "// range", "var", "start", "=", "interval", ".", "split", "(", "'..'", ")", "[", "0", "]", ",", "end", "=", "interval", ".", "split", "(", "'..'", ")", "[", "1", "]", ";", "if", "(", "cond", "===", "'='", ")", "{", "return", "format", "(", "'B(%s, %s, %s)'", ",", "start", ",", "end", ",", "v", ")", ";", "}", "return", "format", "(", "'!B(%s, %s, %s)'", ",", "start", ",", "end", ",", "v", ")", ";", "}", ")", ";", "var", "joined", ";", "if", "(", "conditions", ".", "length", ">", "1", ")", "{", "joined", "=", "'('", "+", "conditions", ".", "join", "(", "cond", "===", "'='", "?", "' || '", ":", "' && '", ")", "+", "')'", ";", "}", "else", "{", "joined", "=", "conditions", "[", "0", "]", ";", "}", "return", "joined", ";", "}", ")", ".", "replace", "(", "/", " = ", "/", "g", ",", "' === '", ")", ".", "replace", "(", "/", " != ", "/", "g", ",", "' !== '", ")", ".", "replace", "(", "/", " or ", "/", "g", ",", "' || '", ")", ".", "replace", "(", "/", " and ", "/", "g", ",", "' && '", ")", ";", "}" ]
Create equation for single form rule
[ "Create", "equation", "for", "single", "form", "rule" ]
d93a4f130d0610605ff76761ef8e6abd4271639d
https://github.com/nodeca/plurals-cldr/blob/d93a4f130d0610605ff76761ef8e6abd4271639d/support/generate.js#L92-L133
46,020
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/valid-targets-finder.js
function(game, settings){ this.game = game; settings = settings || {}; this.x = settings.x || this.x; this.y = settings.y || this.y; this.limitToFov = settings.limitToFov || this.limitToFov; this.limitToNonDiagonalAdjacent = settings.limitToNonDiagonalAdjacent || this.limitToNonDiagonalAdjacent; this.range = settings.range || this.range; this.validTypes = settings.validTypes || []; this.includeTiles = settings.includeTiles || this.includeTiles; this.includeSelf = settings.includeSelf || this.includeSelf; this.prepareValidTargets = settings.prepareValidTargets || this.prepareValidTargets; this.filter = settings.filter || this.filter; }
javascript
function(game, settings){ this.game = game; settings = settings || {}; this.x = settings.x || this.x; this.y = settings.y || this.y; this.limitToFov = settings.limitToFov || this.limitToFov; this.limitToNonDiagonalAdjacent = settings.limitToNonDiagonalAdjacent || this.limitToNonDiagonalAdjacent; this.range = settings.range || this.range; this.validTypes = settings.validTypes || []; this.includeTiles = settings.includeTiles || this.includeTiles; this.includeSelf = settings.includeSelf || this.includeSelf; this.prepareValidTargets = settings.prepareValidTargets || this.prepareValidTargets; this.filter = settings.filter || this.filter; }
[ "function", "(", "game", ",", "settings", ")", "{", "this", ".", "game", "=", "game", ";", "settings", "=", "settings", "||", "{", "}", ";", "this", ".", "x", "=", "settings", ".", "x", "||", "this", ".", "x", ";", "this", ".", "y", "=", "settings", ".", "y", "||", "this", ".", "y", ";", "this", ".", "limitToFov", "=", "settings", ".", "limitToFov", "||", "this", ".", "limitToFov", ";", "this", ".", "limitToNonDiagonalAdjacent", "=", "settings", ".", "limitToNonDiagonalAdjacent", "||", "this", ".", "limitToNonDiagonalAdjacent", ";", "this", ".", "range", "=", "settings", ".", "range", "||", "this", ".", "range", ";", "this", ".", "validTypes", "=", "settings", ".", "validTypes", "||", "[", "]", ";", "this", ".", "includeTiles", "=", "settings", ".", "includeTiles", "||", "this", ".", "includeTiles", ";", "this", ".", "includeSelf", "=", "settings", ".", "includeSelf", "||", "this", ".", "includeSelf", ";", "this", ".", "prepareValidTargets", "=", "settings", ".", "prepareValidTargets", "||", "this", ".", "prepareValidTargets", ";", "this", ".", "filter", "=", "settings", ".", "filter", "||", "this", ".", "filter", ";", "}" ]
Gets a list of valid targets filtered by provided criteria. @class ValidTargetsFinder @constructor @param {Game} game @param {Object} settings @param {Number} settings.x - The x map tile coord to use as the origin of the attack. @param {Number} settings.y - The y map tile coord to use as the origin of the attack. @param {FovROT} [settings.limitToFov=false] - If set only targets within the given `FovROT` will be valid. @param {Bool} [settings.limitToNonDiagonalAdjacent=false] - If true diagonally adjacent targets are not valid (only used if `range = 1`). @param {Number} [settings.range=1] - Max distance in tiles target can be from origin. @param {Array} [settings.validTypes=Array] - Array of valid target object types. Checked using `target instanceof type`. @param {Bool} [settings.includeTiles=false] - If true tile objects are can be valid targets. @param {Object|Array} [settings.exclude=false] - Object or Array of objects to exclude from results. @param {Bool} [settings.prepareValidTargets=true] - If true valid targets are wraped in an object with x, y, range, value properties. @param {Function} [settings.filter=false] - Function to filter objects when checking if they are valid. `function(obj){ return true }` . Targets must still be a valid type.
[ "Gets", "a", "list", "of", "valid", "targets", "filtered", "by", "provided", "criteria", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/valid-targets-finder.js#L21-L36
46,021
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/valid-targets-finder.js
function(){ var tiles = this.getValidTargetTiles(); var result = []; for (var i = 0; i < tiles.length; i++) { var tile = tiles[i]; var targets = this.getValidTargetsAtPosition(tile.x, tile.y); result = result.concat(targets); if(this.includeTiles){ result.push(tile); } } return result; }
javascript
function(){ var tiles = this.getValidTargetTiles(); var result = []; for (var i = 0; i < tiles.length; i++) { var tile = tiles[i]; var targets = this.getValidTargetsAtPosition(tile.x, tile.y); result = result.concat(targets); if(this.includeTiles){ result.push(tile); } } return result; }
[ "function", "(", ")", "{", "var", "tiles", "=", "this", ".", "getValidTargetTiles", "(", ")", ";", "var", "result", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "tiles", ".", "length", ";", "i", "++", ")", "{", "var", "tile", "=", "tiles", "[", "i", "]", ";", "var", "targets", "=", "this", ".", "getValidTargetsAtPosition", "(", "tile", ".", "x", ",", "tile", ".", "y", ")", ";", "result", "=", "result", ".", "concat", "(", "targets", ")", ";", "if", "(", "this", ".", "includeTiles", ")", "{", "result", ".", "push", "(", "tile", ")", ";", "}", "}", "return", "result", ";", "}" ]
Gets all valid targets. @method getValidTargets @return {Array}
[ "Gets", "all", "valid", "targets", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/valid-targets-finder.js#L125-L137
46,022
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/valid-targets-finder.js
function(){ var tiles = []; if(this.limitToFov){ var fovTiles = this.limitToFov.visibleTiles; for (var i = 0; i < fovTiles.length; i++) { var fovTile = fovTiles[i]; // if no max range, if there is a max range check it if(!this.range || fovTile.range <= this.range){ // if including tile objects in result but not preparing them if(this.includeTiles && !this.prepareValidTargets){ fovTile = fovTile.value; } tiles.push(fovTile); } } } else { var x = this.x, y = this.y; if(this.range === 1){ if(this.limitToNonDiagonalAdjacent){ tiles = this.game.map.getAdjacent(x, y, {withDiagonals: false}); } else{ tiles = this.game.map.getAdjacent(x, y); } } else { tiles = this.game.map.getWithinSquareRadius(x, y, {radius: this.range}); } // if including tile objects, prepare them if(this.includeTiles && this.prepareValidTargets){ var _this = this; tiles = tiles.map(function(tile){ return _this.prepareTargetObject(tile); }); } } return tiles; }
javascript
function(){ var tiles = []; if(this.limitToFov){ var fovTiles = this.limitToFov.visibleTiles; for (var i = 0; i < fovTiles.length; i++) { var fovTile = fovTiles[i]; // if no max range, if there is a max range check it if(!this.range || fovTile.range <= this.range){ // if including tile objects in result but not preparing them if(this.includeTiles && !this.prepareValidTargets){ fovTile = fovTile.value; } tiles.push(fovTile); } } } else { var x = this.x, y = this.y; if(this.range === 1){ if(this.limitToNonDiagonalAdjacent){ tiles = this.game.map.getAdjacent(x, y, {withDiagonals: false}); } else{ tiles = this.game.map.getAdjacent(x, y); } } else { tiles = this.game.map.getWithinSquareRadius(x, y, {radius: this.range}); } // if including tile objects, prepare them if(this.includeTiles && this.prepareValidTargets){ var _this = this; tiles = tiles.map(function(tile){ return _this.prepareTargetObject(tile); }); } } return tiles; }
[ "function", "(", ")", "{", "var", "tiles", "=", "[", "]", ";", "if", "(", "this", ".", "limitToFov", ")", "{", "var", "fovTiles", "=", "this", ".", "limitToFov", ".", "visibleTiles", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "fovTiles", ".", "length", ";", "i", "++", ")", "{", "var", "fovTile", "=", "fovTiles", "[", "i", "]", ";", "// if no max range, if there is a max range check it", "if", "(", "!", "this", ".", "range", "||", "fovTile", ".", "range", "<=", "this", ".", "range", ")", "{", "// if including tile objects in result but not preparing them", "if", "(", "this", ".", "includeTiles", "&&", "!", "this", ".", "prepareValidTargets", ")", "{", "fovTile", "=", "fovTile", ".", "value", ";", "}", "tiles", ".", "push", "(", "fovTile", ")", ";", "}", "}", "}", "else", "{", "var", "x", "=", "this", ".", "x", ",", "y", "=", "this", ".", "y", ";", "if", "(", "this", ".", "range", "===", "1", ")", "{", "if", "(", "this", ".", "limitToNonDiagonalAdjacent", ")", "{", "tiles", "=", "this", ".", "game", ".", "map", ".", "getAdjacent", "(", "x", ",", "y", ",", "{", "withDiagonals", ":", "false", "}", ")", ";", "}", "else", "{", "tiles", "=", "this", ".", "game", ".", "map", ".", "getAdjacent", "(", "x", ",", "y", ")", ";", "}", "}", "else", "{", "tiles", "=", "this", ".", "game", ".", "map", ".", "getWithinSquareRadius", "(", "x", ",", "y", ",", "{", "radius", ":", "this", ".", "range", "}", ")", ";", "}", "// if including tile objects, prepare them", "if", "(", "this", ".", "includeTiles", "&&", "this", ".", "prepareValidTargets", ")", "{", "var", "_this", "=", "this", ";", "tiles", "=", "tiles", ".", "map", "(", "function", "(", "tile", ")", "{", "return", "_this", ".", "prepareTargetObject", "(", "tile", ")", ";", "}", ")", ";", "}", "}", "return", "tiles", ";", "}" ]
Get tile coords a valid target may be on. Only checking range and fov, not objects on the tile. @method getValidTargetTiles @return {Array} of Tile objects
[ "Get", "tile", "coords", "a", "valid", "target", "may", "be", "on", ".", "Only", "checking", "range", "and", "fov", "not", "objects", "on", "the", "tile", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/valid-targets-finder.js#L144-L184
46,023
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/valid-targets-finder.js
function(x, y){ var objects = this.game.getObjectsAtPostion(x, y); var range = RL.Util.getDistance(this.x, this.y, x, y); var _this = this; var filtered = objects.filter(function(target){ return _this.checkValidTarget(target); }); return filtered.map(function(target){ return _this.prepareTargetObject(target, x, y, range); }); }
javascript
function(x, y){ var objects = this.game.getObjectsAtPostion(x, y); var range = RL.Util.getDistance(this.x, this.y, x, y); var _this = this; var filtered = objects.filter(function(target){ return _this.checkValidTarget(target); }); return filtered.map(function(target){ return _this.prepareTargetObject(target, x, y, range); }); }
[ "function", "(", "x", ",", "y", ")", "{", "var", "objects", "=", "this", ".", "game", ".", "getObjectsAtPostion", "(", "x", ",", "y", ")", ";", "var", "range", "=", "RL", ".", "Util", ".", "getDistance", "(", "this", ".", "x", ",", "this", ".", "y", ",", "x", ",", "y", ")", ";", "var", "_this", "=", "this", ";", "var", "filtered", "=", "objects", ".", "filter", "(", "function", "(", "target", ")", "{", "return", "_this", ".", "checkValidTarget", "(", "target", ")", ";", "}", ")", ";", "return", "filtered", ".", "map", "(", "function", "(", "target", ")", "{", "return", "_this", ".", "prepareTargetObject", "(", "target", ",", "x", ",", "y", ",", "range", ")", ";", "}", ")", ";", "}" ]
Get valid target objects on a tile coord. @method getValidTargetsAtPosition @param {Number} x - Map tile coord to get valid target objects from. @param {Number} y - Map tile coord to get valid target objects from. @return {Array} mixed objects
[ "Get", "valid", "target", "objects", "on", "a", "tile", "coord", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/valid-targets-finder.js#L193-L204
46,024
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/valid-targets-finder.js
function(target, x, y, range){ x = x || target.x; y = y || target.y; range = range || RL.Util.getDistance(this.x, this.y, x, y); return { x: x, y: y, range: range, value: target }; }
javascript
function(target, x, y, range){ x = x || target.x; y = y || target.y; range = range || RL.Util.getDistance(this.x, this.y, x, y); return { x: x, y: y, range: range, value: target }; }
[ "function", "(", "target", ",", "x", ",", "y", ",", "range", ")", "{", "x", "=", "x", "||", "target", ".", "x", ";", "y", "=", "y", "||", "target", ".", "y", ";", "range", "=", "range", "||", "RL", ".", "Util", ".", "getDistance", "(", "this", ".", "x", ",", "this", ".", "y", ",", "x", ",", "y", ")", ";", "return", "{", "x", ":", "x", ",", "y", ":", "y", ",", "range", ":", "range", ",", "value", ":", "target", "}", ";", "}" ]
Wraps a target object in a container object with x, y, range @method prepareTargetObject @param {Object} target @param {Number} [x=target.x] @param {Number} [y=target.y] @param {Number} [range] range from `this.x`, `this.y` to x,y @return {Object} result result object ` return { x: x, // target x tile coord y: y, // target y tile coord range: range, // distance to target value: target // target object }; ` @return {Object} result.x target x tile coord @return {Object} result.y target y tile coord @return {Object} result.range distance to target @return {Object} result.value target object
[ "Wraps", "a", "target", "object", "in", "a", "container", "object", "with", "x", "y", "range" ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/valid-targets-finder.js#L227-L237
46,025
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/valid-targets-finder.js
function(target){ // skip valid type check if value evaluating to false or empty array. if(!this.validTypes || !this.validTypes.length){ return true; } for(var i = this.validTypes.length - 1; i >= 0; i--){ var type = this.validTypes[i]; if(target instanceof type){ return true; } } // no valid type match found return false; }
javascript
function(target){ // skip valid type check if value evaluating to false or empty array. if(!this.validTypes || !this.validTypes.length){ return true; } for(var i = this.validTypes.length - 1; i >= 0; i--){ var type = this.validTypes[i]; if(target instanceof type){ return true; } } // no valid type match found return false; }
[ "function", "(", "target", ")", "{", "// skip valid type check if value evaluating to false or empty array.", "if", "(", "!", "this", ".", "validTypes", "||", "!", "this", ".", "validTypes", ".", "length", ")", "{", "return", "true", ";", "}", "for", "(", "var", "i", "=", "this", ".", "validTypes", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "var", "type", "=", "this", ".", "validTypes", "[", "i", "]", ";", "if", "(", "target", "instanceof", "type", ")", "{", "return", "true", ";", "}", "}", "// no valid type match found", "return", "false", ";", "}" ]
Checks if a target object is an instance of a type in `this.validTypes`. @method checkValidType @param {Object} target - The target to be checked. @return {Bool} `true` if valid.
[ "Checks", "if", "a", "target", "object", "is", "an", "instance", "of", "a", "type", "in", "this", ".", "validTypes", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/valid-targets-finder.js#L245-L260
46,026
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/valid-targets-finder.js
function(target){ if(this.exclude){ if(target === this.exclude){ return false; } // if exclude is array and target is in it if(Object.isArray(this.exclude) && this.exclude.indexOf(target) !== -1){ return false; } } if(!this.checkValidType(target)){ return false; } if(this.filter && !this.filter(target)){ return false; } return true; }
javascript
function(target){ if(this.exclude){ if(target === this.exclude){ return false; } // if exclude is array and target is in it if(Object.isArray(this.exclude) && this.exclude.indexOf(target) !== -1){ return false; } } if(!this.checkValidType(target)){ return false; } if(this.filter && !this.filter(target)){ return false; } return true; }
[ "function", "(", "target", ")", "{", "if", "(", "this", ".", "exclude", ")", "{", "if", "(", "target", "===", "this", ".", "exclude", ")", "{", "return", "false", ";", "}", "// if exclude is array and target is in it", "if", "(", "Object", ".", "isArray", "(", "this", ".", "exclude", ")", "&&", "this", ".", "exclude", ".", "indexOf", "(", "target", ")", "!==", "-", "1", ")", "{", "return", "false", ";", "}", "}", "if", "(", "!", "this", ".", "checkValidType", "(", "target", ")", ")", "{", "return", "false", ";", "}", "if", "(", "this", ".", "filter", "&&", "!", "this", ".", "filter", "(", "target", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Checks if an object is a valid target for this action. @method checkValidTarget @param {Object} target - The target to be checked. @return {Bool} `true` if valid.
[ "Checks", "if", "an", "object", "is", "a", "valid", "target", "for", "this", "action", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/valid-targets-finder.js#L268-L286
46,027
wilmoore/uuid-regexp.js
index.js
re
function re (opts) { opts = opts || {} return new RegExp( format('\\b(?:%s)\\b', regexp.versioned.source + (opts.nil ? '|' + regexp.nil.source : '')), 'i' + (opts.flags || '') ) }
javascript
function re (opts) { opts = opts || {} return new RegExp( format('\\b(?:%s)\\b', regexp.versioned.source + (opts.nil ? '|' + regexp.nil.source : '')), 'i' + (opts.flags || '') ) }
[ "function", "re", "(", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", "return", "new", "RegExp", "(", "format", "(", "'\\\\b(?:%s)\\\\b'", ",", "regexp", ".", "versioned", ".", "source", "+", "(", "opts", ".", "nil", "?", "'|'", "+", "regexp", ".", "nil", ".", "source", ":", "''", ")", ")", ",", "'i'", "+", "(", "opts", ".", "flags", "||", "''", ")", ")", "}" ]
RegExp for finding an RFC4122 compliant UUID in a string. @param {Object} opts Options object. @param {String} [opts.flags] Additional RegExp flags ('i' is always set). @param {Boolean} [opts.nil] Whether to include the nil/empty UUID pattern. @return {RegExp} RegExp for finding an RFC4122 compliant UUID in a string.
[ "RegExp", "for", "finding", "an", "RFC4122", "compliant", "UUID", "in", "a", "string", "." ]
674d65e5e371d7c126a58a09281e8e21ee503e9a
https://github.com/wilmoore/uuid-regexp.js/blob/674d65e5e371d7c126a58a09281e8e21ee503e9a/index.js#L32-L39
46,028
75lb/object-get
lib/object-get.js
objectGet
function objectGet (object, expression) { if (!(object && expression)) throw new Error('both object and expression args are required') return expression.trim().split('.').reduce(function (prev, curr) { var arr = curr.match(/(.*?)\[(.*?)\]/) if (arr) { return prev && prev[arr[1]][arr[2]] } else { return prev && prev[curr] } }, object) }
javascript
function objectGet (object, expression) { if (!(object && expression)) throw new Error('both object and expression args are required') return expression.trim().split('.').reduce(function (prev, curr) { var arr = curr.match(/(.*?)\[(.*?)\]/) if (arr) { return prev && prev[arr[1]][arr[2]] } else { return prev && prev[curr] } }, object) }
[ "function", "objectGet", "(", "object", ",", "expression", ")", "{", "if", "(", "!", "(", "object", "&&", "expression", ")", ")", "throw", "new", "Error", "(", "'both object and expression args are required'", ")", "return", "expression", ".", "trim", "(", ")", ".", "split", "(", "'.'", ")", ".", "reduce", "(", "function", "(", "prev", ",", "curr", ")", "{", "var", "arr", "=", "curr", ".", "match", "(", "/", "(.*?)\\[(.*?)\\]", "/", ")", "if", "(", "arr", ")", "{", "return", "prev", "&&", "prev", "[", "arr", "[", "1", "]", "]", "[", "arr", "[", "2", "]", "]", "}", "else", "{", "return", "prev", "&&", "prev", "[", "curr", "]", "}", "}", ",", "object", ")", "}" ]
Returns the value at the given property. @param {object} - the input object @param {string} - the property accessor expression. @returns {*} @alias module:object-get @example > objectGet({ animal: 'cow' }, 'animal') 'cow' > objectGet({ animal: { mood: 'lazy' } }, 'animal') { mood: 'lazy' } > objectGet({ animal: { mood: 'lazy' } }, 'animal.mood') 'lazy' > objectGet({ animal: { mood: 'lazy' } }, 'animal.email') undefined
[ "Returns", "the", "value", "at", "the", "given", "property", "." ]
67fe4b92af9a3f3311e90c9a89d35f24a956e5df
https://github.com/75lb/object-get/blob/67fe4b92af9a3f3311e90c9a89d35f24a956e5df/lib/object-get.js#L44-L54
46,029
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/input.js
Input
function Input(onKeyAction, bindings) { this.bindings = {}; if (onKeyAction !== void 0) { this.onKeyAction = onKeyAction; } if (bindings !== void 0) { this.addBindings(bindings); } this.startListening(); }
javascript
function Input(onKeyAction, bindings) { this.bindings = {}; if (onKeyAction !== void 0) { this.onKeyAction = onKeyAction; } if (bindings !== void 0) { this.addBindings(bindings); } this.startListening(); }
[ "function", "Input", "(", "onKeyAction", ",", "bindings", ")", "{", "this", ".", "bindings", "=", "{", "}", ";", "if", "(", "onKeyAction", "!==", "void", "0", ")", "{", "this", ".", "onKeyAction", "=", "onKeyAction", ";", "}", "if", "(", "bindings", "!==", "void", "0", ")", "{", "this", ".", "addBindings", "(", "bindings", ")", ";", "}", "this", ".", "startListening", "(", ")", ";", "}" ]
Helper for binding user key input to actions. @class Input @constructor @param {Function} onKeyAction - Function called when a key bound to an action is pressed (function(action){}). @param {Object} bindings - An object of key val pairs mapping an action to an array of keys that trigger it. Input.Keys is used to convert input key string names to key codes. @param bindings.action1 {Array} Input keys mapped to action1. ['A', 'B', ...] @param bindings.action2 {Array} Input keys mapped to action2. ['X', 'Y', ...] @param bindings.... @example bindings param example: { up: ['UP_ARROW'], down: ['DOWN_ARROW'], left: ['LEFT_ARROW'], right: ['RIGHT_ARROW'], }
[ "Helper", "for", "binding", "user", "key", "input", "to", "actions", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/input.js#L22-L31
46,030
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/input.js
function(bindings) { for (var action in bindings) { var keys = bindings[action]; for (var i = 0; i < keys.length; i++) { var key = keys[i]; this.bindAction(action, key); } } }
javascript
function(bindings) { for (var action in bindings) { var keys = bindings[action]; for (var i = 0; i < keys.length; i++) { var key = keys[i]; this.bindAction(action, key); } } }
[ "function", "(", "bindings", ")", "{", "for", "(", "var", "action", "in", "bindings", ")", "{", "var", "keys", "=", "bindings", "[", "action", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "var", "key", "=", "keys", "[", "i", "]", ";", "this", ".", "bindAction", "(", "action", ",", "key", ")", ";", "}", "}", "}" ]
Loads multiple action key bindings @method addBindings @param {Object} bindings - An object of key val pairs mapping an action to an array of keys that trigger it. Input.Keys is used to convert input key string names to key codes. @param bindings.action1 {Array} Input keys mapped to action1. ['A', 'B', ...] @param bindings.action2 {Array} Input keys mapped to action2. ['X', 'Y', ...] @param bindings.... @example bindings param example: { up: ['UP_ARROW'], down: ['DOWN_ARROW'], left: ['LEFT_ARROW'], right: ['RIGHT_ARROW'], }
[ "Loads", "multiple", "action", "key", "bindings" ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/input.js#L91-L99
46,031
sergeyt/fetch-stream
src/index.js
pump
function pump(reader, handler) { reader.read().then(result => { if (result.done) { return; } if (handler(result.value) === false) { // cancelling return; } pump(reader, handler); }); }
javascript
function pump(reader, handler) { reader.read().then(result => { if (result.done) { return; } if (handler(result.value) === false) { // cancelling return; } pump(reader, handler); }); }
[ "function", "pump", "(", "reader", ",", "handler", ")", "{", "reader", ".", "read", "(", ")", ".", "then", "(", "result", "=>", "{", "if", "(", "result", ".", "done", ")", "{", "return", ";", "}", "if", "(", "handler", "(", "result", ".", "value", ")", "===", "false", ")", "{", "// cancelling", "return", ";", "}", "pump", "(", "reader", ",", "handler", ")", ";", "}", ")", ";", "}" ]
reads all chunks
[ "reads", "all", "chunks" ]
eab91c059ce3b1d172fd44890769c761bb4b7aa3
https://github.com/sergeyt/fetch-stream/blob/eab91c059ce3b1d172fd44890769c761bb4b7aa3/src/index.js#L13-L24
46,032
nodeca/event-wire
index.js
_hook
function _hook(slf, name, handlerInfo, params) { if (!slf.__hooks[name]) return; slf.__hooks[name].forEach(function (hook) { hook(handlerInfo, params); }); }
javascript
function _hook(slf, name, handlerInfo, params) { if (!slf.__hooks[name]) return; slf.__hooks[name].forEach(function (hook) { hook(handlerInfo, params); }); }
[ "function", "_hook", "(", "slf", ",", "name", ",", "handlerInfo", ",", "params", ")", "{", "if", "(", "!", "slf", ".", "__hooks", "[", "name", "]", ")", "return", ";", "slf", ".", "__hooks", "[", "name", "]", ".", "forEach", "(", "function", "(", "hook", ")", "{", "hook", "(", "handlerInfo", ",", "params", ")", ";", "}", ")", ";", "}" ]
Helper to run hooks
[ "Helper", "to", "run", "hooks" ]
ae8d1e419bf20991ac716248914f688f1e2f6322
https://github.com/nodeca/event-wire/blob/ae8d1e419bf20991ac716248914f688f1e2f6322/index.js#L214-L220
46,033
nodeca/event-wire
index.js
wrap_cb
function wrap_cb(fn, P) { return function (params) { return new P(function (resolve, reject) { fn(params, function (err) { return !err ? resolve() : reject(err); }); }); }; }
javascript
function wrap_cb(fn, P) { return function (params) { return new P(function (resolve, reject) { fn(params, function (err) { return !err ? resolve() : reject(err); }); }); }; }
[ "function", "wrap_cb", "(", "fn", ",", "P", ")", "{", "return", "function", "(", "params", ")", "{", "return", "new", "P", "(", "function", "(", "resolve", ",", "reject", ")", "{", "fn", "(", "params", ",", "function", "(", "err", ")", "{", "return", "!", "err", "?", "resolve", "(", ")", ":", "reject", "(", "err", ")", ";", "}", ")", ";", "}", ")", ";", "}", ";", "}" ]
Wrap handler with callback
[ "Wrap", "handler", "with", "callback" ]
ae8d1e419bf20991ac716248914f688f1e2f6322
https://github.com/nodeca/event-wire/blob/ae8d1e419bf20991ac716248914f688f1e2f6322/index.js#L246-L252
46,034
nodeca/event-wire
index.js
finalizeHandler
function finalizeHandler(p, hInfo) { if (!p) return; return p .catch(storeErrOnce) .then(function () { if (errored && !hInfo.ensure) return null; _hook(self, 'eachAfter', hInfo, params); }) .catch(storeErrOnce); }
javascript
function finalizeHandler(p, hInfo) { if (!p) return; return p .catch(storeErrOnce) .then(function () { if (errored && !hInfo.ensure) return null; _hook(self, 'eachAfter', hInfo, params); }) .catch(storeErrOnce); }
[ "function", "finalizeHandler", "(", "p", ",", "hInfo", ")", "{", "if", "(", "!", "p", ")", "return", ";", "return", "p", ".", "catch", "(", "storeErrOnce", ")", ".", "then", "(", "function", "(", ")", "{", "if", "(", "errored", "&&", "!", "hInfo", ".", "ensure", ")", "return", "null", ";", "_hook", "(", "self", ",", "'eachAfter'", ",", "hInfo", ",", "params", ")", ";", "}", ")", ".", "catch", "(", "storeErrOnce", ")", ";", "}" ]
Finalize handler exec - should care about errors and post-hooks.
[ "Finalize", "handler", "exec", "-", "should", "care", "about", "errors", "and", "post", "-", "hooks", "." ]
ae8d1e419bf20991ac716248914f688f1e2f6322
https://github.com/nodeca/event-wire/blob/ae8d1e419bf20991ac716248914f688f1e2f6322/index.js#L303-L313
46,035
sergeyt/fetch-stream
lib/index.js
fetchStream
function fetchStream() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var callback = arguments[1]; var cb = callback; var stream = null; if (cb === undefined) { stream = makeStream(); cb = stream.handler; } var url = typeof options === 'string' ? options : options.url || options.path; if (supportFetch) { // TODO support Request object? var init = (typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object' ? options : {}; fetch(url, init).then(function (res) { if (res.status >= 200 && res.status < 300) { pump(res.body.getReader(), (0, _parser2.default)(cb)); } else { // TODO read custom error payload cb(null, { status: res.status, statusText: res.statusText }); } }, function (err) { cb(null, err); }); } else { (function () { var parser = (0, _parser2.default)(cb, _parser.BUFFER); var opts = (typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object' ? _extends({}, options) : {}; opts.path = url; var req = _streamHttp2.default.get(opts, function (res) { var status = res.status || res.statusCode; if (!(status >= 200 && status < 300)) { // TODO read custom error payload cb(null, { status: status, statusText: res.statusText || res.statusMessage }); return; } res.on('data', function (buf) { if (parser(buf) === false) { // cancelling req.abort(); } }); res.on('error', function (err) { req.abort(); cb(null, err); }); }); })(); } return stream; }
javascript
function fetchStream() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var callback = arguments[1]; var cb = callback; var stream = null; if (cb === undefined) { stream = makeStream(); cb = stream.handler; } var url = typeof options === 'string' ? options : options.url || options.path; if (supportFetch) { // TODO support Request object? var init = (typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object' ? options : {}; fetch(url, init).then(function (res) { if (res.status >= 200 && res.status < 300) { pump(res.body.getReader(), (0, _parser2.default)(cb)); } else { // TODO read custom error payload cb(null, { status: res.status, statusText: res.statusText }); } }, function (err) { cb(null, err); }); } else { (function () { var parser = (0, _parser2.default)(cb, _parser.BUFFER); var opts = (typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object' ? _extends({}, options) : {}; opts.path = url; var req = _streamHttp2.default.get(opts, function (res) { var status = res.status || res.statusCode; if (!(status >= 200 && status < 300)) { // TODO read custom error payload cb(null, { status: status, statusText: res.statusText || res.statusMessage }); return; } res.on('data', function (buf) { if (parser(buf) === false) { // cancelling req.abort(); } }); res.on('error', function (err) { req.abort(); cb(null, err); }); }); })(); } return stream; }
[ "function", "fetchStream", "(", ")", "{", "var", "options", "=", "arguments", ".", "length", "<=", "0", "||", "arguments", "[", "0", "]", "===", "undefined", "?", "{", "}", ":", "arguments", "[", "0", "]", ";", "var", "callback", "=", "arguments", "[", "1", "]", ";", "var", "cb", "=", "callback", ";", "var", "stream", "=", "null", ";", "if", "(", "cb", "===", "undefined", ")", "{", "stream", "=", "makeStream", "(", ")", ";", "cb", "=", "stream", ".", "handler", ";", "}", "var", "url", "=", "typeof", "options", "===", "'string'", "?", "options", ":", "options", ".", "url", "||", "options", ".", "path", ";", "if", "(", "supportFetch", ")", "{", "// TODO support Request object?", "var", "init", "=", "(", "typeof", "options", "===", "'undefined'", "?", "'undefined'", ":", "_typeof", "(", "options", ")", ")", "===", "'object'", "?", "options", ":", "{", "}", ";", "fetch", "(", "url", ",", "init", ")", ".", "then", "(", "function", "(", "res", ")", "{", "if", "(", "res", ".", "status", ">=", "200", "&&", "res", ".", "status", "<", "300", ")", "{", "pump", "(", "res", ".", "body", ".", "getReader", "(", ")", ",", "(", "0", ",", "_parser2", ".", "default", ")", "(", "cb", ")", ")", ";", "}", "else", "{", "// TODO read custom error payload", "cb", "(", "null", ",", "{", "status", ":", "res", ".", "status", ",", "statusText", ":", "res", ".", "statusText", "}", ")", ";", "}", "}", ",", "function", "(", "err", ")", "{", "cb", "(", "null", ",", "err", ")", ";", "}", ")", ";", "}", "else", "{", "(", "function", "(", ")", "{", "var", "parser", "=", "(", "0", ",", "_parser2", ".", "default", ")", "(", "cb", ",", "_parser", ".", "BUFFER", ")", ";", "var", "opts", "=", "(", "typeof", "options", "===", "'undefined'", "?", "'undefined'", ":", "_typeof", "(", "options", ")", ")", "===", "'object'", "?", "_extends", "(", "{", "}", ",", "options", ")", ":", "{", "}", ";", "opts", ".", "path", "=", "url", ";", "var", "req", "=", "_streamHttp2", ".", "default", ".", "get", "(", "opts", ",", "function", "(", "res", ")", "{", "var", "status", "=", "res", ".", "status", "||", "res", ".", "statusCode", ";", "if", "(", "!", "(", "status", ">=", "200", "&&", "status", "<", "300", ")", ")", "{", "// TODO read custom error payload", "cb", "(", "null", ",", "{", "status", ":", "status", ",", "statusText", ":", "res", ".", "statusText", "||", "res", ".", "statusMessage", "}", ")", ";", "return", ";", "}", "res", ".", "on", "(", "'data'", ",", "function", "(", "buf", ")", "{", "if", "(", "parser", "(", "buf", ")", "===", "false", ")", "{", "// cancelling", "req", ".", "abort", "(", ")", ";", "}", "}", ")", ";", "res", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "req", ".", "abort", "(", ")", ";", "cb", "(", "null", ",", "err", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", "(", ")", ";", "}", "return", "stream", ";", "}" ]
Fetches resource stream. @param {object} [options] URL or options of request. @param {function} [callback] The callback to process each chunk in the stream.
[ "Fetches", "resource", "stream", "." ]
eab91c059ce3b1d172fd44890769c761bb4b7aa3
https://github.com/sergeyt/fetch-stream/blob/eab91c059ce3b1d172fd44890769c761bb4b7aa3/lib/index.js#L94-L146
46,036
ahmed-dinar/codeforces-api-node
src/codeforces.js
callApi
function callApi(method, parameters, callback) { if (typeof parameters === 'undefined') { throw new Error('undefined is not a valid parameters object.'); } if( typeof parameters !== 'object' ){ throw new Error('valid parameters object required.'); } var opts = this.options; var noCallback = !callback || typeof callback !== 'function'; let noApiKey = typeof opts.API_KEY !== 'string' || opts.API_KEY.length === 0 || typeof opts.API_SECRET !== 'string' || opts.API_SECRET.length === 0; if( noApiKey ){ if( noCallback ){ throw new Error('API key and API secret required.'); } return callback(new Error("API key and API secret required.")); } opts.method = method; // // final API url with hashes // let url = makeApiUrl(opts, parameters); let reqOptions = { uri: url, json: true, timeout: process.env.CF_TIMEOUT || opts.DEFAULT_TIMEOUT }; // // callback not exists, just return the request modules Request class instance for event // if( noCallback ){ return new Request(reqOptions); } // // callback exists, return Request for streaming and handle callback for error handling and custom formatted data // return callRequest(reqOptions, handleCallback.bind(null,callback) ); }
javascript
function callApi(method, parameters, callback) { if (typeof parameters === 'undefined') { throw new Error('undefined is not a valid parameters object.'); } if( typeof parameters !== 'object' ){ throw new Error('valid parameters object required.'); } var opts = this.options; var noCallback = !callback || typeof callback !== 'function'; let noApiKey = typeof opts.API_KEY !== 'string' || opts.API_KEY.length === 0 || typeof opts.API_SECRET !== 'string' || opts.API_SECRET.length === 0; if( noApiKey ){ if( noCallback ){ throw new Error('API key and API secret required.'); } return callback(new Error("API key and API secret required.")); } opts.method = method; // // final API url with hashes // let url = makeApiUrl(opts, parameters); let reqOptions = { uri: url, json: true, timeout: process.env.CF_TIMEOUT || opts.DEFAULT_TIMEOUT }; // // callback not exists, just return the request modules Request class instance for event // if( noCallback ){ return new Request(reqOptions); } // // callback exists, return Request for streaming and handle callback for error handling and custom formatted data // return callRequest(reqOptions, handleCallback.bind(null,callback) ); }
[ "function", "callApi", "(", "method", ",", "parameters", ",", "callback", ")", "{", "if", "(", "typeof", "parameters", "===", "'undefined'", ")", "{", "throw", "new", "Error", "(", "'undefined is not a valid parameters object.'", ")", ";", "}", "if", "(", "typeof", "parameters", "!==", "'object'", ")", "{", "throw", "new", "Error", "(", "'valid parameters object required.'", ")", ";", "}", "var", "opts", "=", "this", ".", "options", ";", "var", "noCallback", "=", "!", "callback", "||", "typeof", "callback", "!==", "'function'", ";", "let", "noApiKey", "=", "typeof", "opts", ".", "API_KEY", "!==", "'string'", "||", "opts", ".", "API_KEY", ".", "length", "===", "0", "||", "typeof", "opts", ".", "API_SECRET", "!==", "'string'", "||", "opts", ".", "API_SECRET", ".", "length", "===", "0", ";", "if", "(", "noApiKey", ")", "{", "if", "(", "noCallback", ")", "{", "throw", "new", "Error", "(", "'API key and API secret required.'", ")", ";", "}", "return", "callback", "(", "new", "Error", "(", "\"API key and API secret required.\"", ")", ")", ";", "}", "opts", ".", "method", "=", "method", ";", "//", "// final API url with hashes", "//", "let", "url", "=", "makeApiUrl", "(", "opts", ",", "parameters", ")", ";", "let", "reqOptions", "=", "{", "uri", ":", "url", ",", "json", ":", "true", ",", "timeout", ":", "process", ".", "env", ".", "CF_TIMEOUT", "||", "opts", ".", "DEFAULT_TIMEOUT", "}", ";", "//", "// callback not exists, just return the request modules Request class instance for event", "//", "if", "(", "noCallback", ")", "{", "return", "new", "Request", "(", "reqOptions", ")", ";", "}", "//", "// callback exists, return Request for streaming and handle callback for error handling and custom formatted data", "//", "return", "callRequest", "(", "reqOptions", ",", "handleCallback", ".", "bind", "(", "null", ",", "callback", ")", ")", ";", "}" ]
Send request to api @param {string} method - method of API request. @param {object} parameters - API url parameters @param {function} callback @returns {*}
[ "Send", "request", "to", "api" ]
2f85a6d833b32012adbf87440b2c16aeb4c167f7
https://github.com/ahmed-dinar/codeforces-api-node/blob/2f85a6d833b32012adbf87440b2c16aeb4c167f7/src/codeforces.js#L98-L144
46,037
ahmed-dinar/codeforces-api-node
src/codeforces.js
handleCallback
function handleCallback(callback, err, httpResponse, body) { if(err){ return callback(err); } // // API returns error // if( body.status !== 'OK' ){ return callback(new Error(body.comment)); } return callback(null, body.result); }
javascript
function handleCallback(callback, err, httpResponse, body) { if(err){ return callback(err); } // // API returns error // if( body.status !== 'OK' ){ return callback(new Error(body.comment)); } return callback(null, body.result); }
[ "function", "handleCallback", "(", "callback", ",", "err", ",", "httpResponse", ",", "body", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "//", "// API returns error", "//", "if", "(", "body", ".", "status", "!==", "'OK'", ")", "{", "return", "callback", "(", "new", "Error", "(", "body", ".", "comment", ")", ")", ";", "}", "return", "callback", "(", "null", ",", "body", ".", "result", ")", ";", "}" ]
Handle user callback @param callback - user callback @param err - request errors @param httpResponse - request HTTP response @param body - request response body @returns {*}
[ "Handle", "user", "callback" ]
2f85a6d833b32012adbf87440b2c16aeb4c167f7
https://github.com/ahmed-dinar/codeforces-api-node/blob/2f85a6d833b32012adbf87440b2c16aeb4c167f7/src/codeforces.js#L156-L170
46,038
ahmed-dinar/codeforces-api-node
src/codeforces.js
makeApiUrl
function makeApiUrl(options,parameters) { var query = parameters; // // If any parameter given in array, make it string separated by semicolon(;) // for(let key in query){ if( _.isArray(query[key]) ){ query[key] = _.join(query[key],';'); } } let curTime = Math.floor(Date.now() / 1000); let randomToken = randomstring.generate(6); query.time = curTime; query.apiKey = options.API_KEY; // // Sort parameters according to codeforces API rules // query = _ .chain(query) .map( (value, key) => { return { key, value }; }) .orderBy(['key', 'value'], ['desc', 'desc']) .reverse() .keyBy('key') .mapValues('value') .value(); let qsFy = qs.stringify(query,{ encode: false }); let apiSig = `${randomToken}/${options.method}?${qsFy}#${options.API_SECRET}`; apiSig = sha512(apiSig).toString(); query.apiSig = randomToken + apiSig; qsFy = qs.stringify(query,{ encode: false }); let url = `${options.API_URL}/${options.method}?${qsFy}`; return url; }
javascript
function makeApiUrl(options,parameters) { var query = parameters; // // If any parameter given in array, make it string separated by semicolon(;) // for(let key in query){ if( _.isArray(query[key]) ){ query[key] = _.join(query[key],';'); } } let curTime = Math.floor(Date.now() / 1000); let randomToken = randomstring.generate(6); query.time = curTime; query.apiKey = options.API_KEY; // // Sort parameters according to codeforces API rules // query = _ .chain(query) .map( (value, key) => { return { key, value }; }) .orderBy(['key', 'value'], ['desc', 'desc']) .reverse() .keyBy('key') .mapValues('value') .value(); let qsFy = qs.stringify(query,{ encode: false }); let apiSig = `${randomToken}/${options.method}?${qsFy}#${options.API_SECRET}`; apiSig = sha512(apiSig).toString(); query.apiSig = randomToken + apiSig; qsFy = qs.stringify(query,{ encode: false }); let url = `${options.API_URL}/${options.method}?${qsFy}`; return url; }
[ "function", "makeApiUrl", "(", "options", ",", "parameters", ")", "{", "var", "query", "=", "parameters", ";", "//", "// If any parameter given in array, make it string separated by semicolon(;)", "//", "for", "(", "let", "key", "in", "query", ")", "{", "if", "(", "_", ".", "isArray", "(", "query", "[", "key", "]", ")", ")", "{", "query", "[", "key", "]", "=", "_", ".", "join", "(", "query", "[", "key", "]", ",", "';'", ")", ";", "}", "}", "let", "curTime", "=", "Math", ".", "floor", "(", "Date", ".", "now", "(", ")", "/", "1000", ")", ";", "let", "randomToken", "=", "randomstring", ".", "generate", "(", "6", ")", ";", "query", ".", "time", "=", "curTime", ";", "query", ".", "apiKey", "=", "options", ".", "API_KEY", ";", "//", "// Sort parameters according to codeforces API rules", "//", "query", "=", "_", ".", "chain", "(", "query", ")", ".", "map", "(", "(", "value", ",", "key", ")", "=>", "{", "return", "{", "key", ",", "value", "}", ";", "}", ")", ".", "orderBy", "(", "[", "'key'", ",", "'value'", "]", ",", "[", "'desc'", ",", "'desc'", "]", ")", ".", "reverse", "(", ")", ".", "keyBy", "(", "'key'", ")", ".", "mapValues", "(", "'value'", ")", ".", "value", "(", ")", ";", "let", "qsFy", "=", "qs", ".", "stringify", "(", "query", ",", "{", "encode", ":", "false", "}", ")", ";", "let", "apiSig", "=", "`", "${", "randomToken", "}", "${", "options", ".", "method", "}", "${", "qsFy", "}", "${", "options", ".", "API_SECRET", "}", "`", ";", "apiSig", "=", "sha512", "(", "apiSig", ")", ".", "toString", "(", ")", ";", "query", ".", "apiSig", "=", "randomToken", "+", "apiSig", ";", "qsFy", "=", "qs", ".", "stringify", "(", "query", ",", "{", "encode", ":", "false", "}", ")", ";", "let", "url", "=", "`", "${", "options", ".", "API_URL", "}", "${", "options", ".", "method", "}", "${", "qsFy", "}", "`", ";", "return", "url", ";", "}" ]
Generate API url according to CF API rules @param {array} options - main class options @param {array} parameters - API url parameters [see doc] @returns {string} - final url
[ "Generate", "API", "url", "according", "to", "CF", "API", "rules" ]
2f85a6d833b32012adbf87440b2c16aeb4c167f7
https://github.com/ahmed-dinar/codeforces-api-node/blob/2f85a6d833b32012adbf87440b2c16aeb4c167f7/src/codeforces.js#L192-L235
46,039
Lanfei/websocket-lib
lib/server.js
ServerSession
function ServerSession(request, socket, head, server) { Session.call(this, request, socket, head); this._resHeaders = {}; this._headerSent = false; /** * The server instance of this session. * @type {Server} */ this.server = server; /** * The HTTP status code of handshake. * @type {Number} * @default 200 */ this.statusCode = 200; /** * The HTTP status message of handshake. * @type {String} */ this.statusMessage = ''; }
javascript
function ServerSession(request, socket, head, server) { Session.call(this, request, socket, head); this._resHeaders = {}; this._headerSent = false; /** * The server instance of this session. * @type {Server} */ this.server = server; /** * The HTTP status code of handshake. * @type {Number} * @default 200 */ this.statusCode = 200; /** * The HTTP status message of handshake. * @type {String} */ this.statusMessage = ''; }
[ "function", "ServerSession", "(", "request", ",", "socket", ",", "head", ",", "server", ")", "{", "Session", ".", "call", "(", "this", ",", "request", ",", "socket", ",", "head", ")", ";", "this", ".", "_resHeaders", "=", "{", "}", ";", "this", ".", "_headerSent", "=", "false", ";", "/**\n\t * The server instance of this session.\n\t * @type {Server}\n\t */", "this", ".", "server", "=", "server", ";", "/**\n\t * The HTTP status code of handshake.\n\t * @type {Number}\n\t * @default 200\n\t */", "this", ".", "statusCode", "=", "200", ";", "/**\n\t * The HTTP status message of handshake.\n\t * @type {String}\n\t */", "this", ".", "statusMessage", "=", "''", ";", "}" ]
WebSocket Server Session @constructor @extends Session @param {IncomingMessage} request see {@link Session#request} @param {Socket} socket see {@link Session#socket} @param {Buffer} [head] Data that received with headers. @param {Server} [server] see {@link ServerSession#server}
[ "WebSocket", "Server", "Session" ]
d39f704490fb91b1e2897712b280c0e5ac79e123
https://github.com/Lanfei/websocket-lib/blob/d39f704490fb91b1e2897712b280c0e5ac79e123/lib/server.js#L227-L251
46,040
martinj/node-async-queue
async-queue.js
function (job) { if (job) { if (arguments.length > 1) { this.jobs = this.jobs.concat(Array.prototype.slice.call(arguments)); } else { this.jobs.push(job); } } return this; }
javascript
function (job) { if (job) { if (arguments.length > 1) { this.jobs = this.jobs.concat(Array.prototype.slice.call(arguments)); } else { this.jobs.push(job); } } return this; }
[ "function", "(", "job", ")", "{", "if", "(", "job", ")", "{", "if", "(", "arguments", ".", "length", ">", "1", ")", "{", "this", ".", "jobs", "=", "this", ".", "jobs", ".", "concat", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ")", ";", "}", "else", "{", "this", ".", "jobs", ".", "push", "(", "job", ")", ";", "}", "}", "return", "this", ";", "}" ]
Add job to the queue @param {Function} job
[ "Add", "job", "to", "the", "queue" ]
2b3870020611babbf2c4851c9b51da780da056eb
https://github.com/martinj/node-async-queue/blob/2b3870020611babbf2c4851c9b51da780da056eb/async-queue.js#L37-L46
46,041
martinj/node-async-queue
async-queue.js
function (err) { if (this.jobs.length) { var job = this.jobs.shift(); try { job(err, this); } catch (e) { this.next(e); } } else { this.running = false; } }
javascript
function (err) { if (this.jobs.length) { var job = this.jobs.shift(); try { job(err, this); } catch (e) { this.next(e); } } else { this.running = false; } }
[ "function", "(", "err", ")", "{", "if", "(", "this", ".", "jobs", ".", "length", ")", "{", "var", "job", "=", "this", ".", "jobs", ".", "shift", "(", ")", ";", "try", "{", "job", "(", "err", ",", "this", ")", ";", "}", "catch", "(", "e", ")", "{", "this", ".", "next", "(", "e", ")", ";", "}", "}", "else", "{", "this", ".", "running", "=", "false", ";", "}", "}" ]
Run the next job in queue @private @param {Object} err
[ "Run", "the", "next", "job", "in", "queue" ]
2b3870020611babbf2c4851c9b51da780da056eb
https://github.com/martinj/node-async-queue/blob/2b3870020611babbf2c4851c9b51da780da056eb/async-queue.js#L98-L109
46,042
juttle/juttle-elastic-adapter
lib/utils.js
index_date
function index_date(timestamp, interval) { function double_digitize(str) { return (str.length === 1) ? ('0' + str) : str; } var year = timestamp.getUTCFullYear(); var month = (timestamp.getUTCMonth() + 1).toString(); switch (interval) { case 'day': var day = timestamp.getUTCDate().toString(); return [year, double_digitize(month), double_digitize(day)].join('.'); case 'week': var week = current_week_number(timestamp); return [year, double_digitize(week)].join('.'); case 'month': return [year, double_digitize(month)].join('.'); case 'year': return year; case 'none': return ''; default: throw new Error('invalid interval: ' + interval + '; accepted intervals are "day", "week", "month", "year", and "none"'); } }
javascript
function index_date(timestamp, interval) { function double_digitize(str) { return (str.length === 1) ? ('0' + str) : str; } var year = timestamp.getUTCFullYear(); var month = (timestamp.getUTCMonth() + 1).toString(); switch (interval) { case 'day': var day = timestamp.getUTCDate().toString(); return [year, double_digitize(month), double_digitize(day)].join('.'); case 'week': var week = current_week_number(timestamp); return [year, double_digitize(week)].join('.'); case 'month': return [year, double_digitize(month)].join('.'); case 'year': return year; case 'none': return ''; default: throw new Error('invalid interval: ' + interval + '; accepted intervals are "day", "week", "month", "year", and "none"'); } }
[ "function", "index_date", "(", "timestamp", ",", "interval", ")", "{", "function", "double_digitize", "(", "str", ")", "{", "return", "(", "str", ".", "length", "===", "1", ")", "?", "(", "'0'", "+", "str", ")", ":", "str", ";", "}", "var", "year", "=", "timestamp", ".", "getUTCFullYear", "(", ")", ";", "var", "month", "=", "(", "timestamp", ".", "getUTCMonth", "(", ")", "+", "1", ")", ".", "toString", "(", ")", ";", "switch", "(", "interval", ")", "{", "case", "'day'", ":", "var", "day", "=", "timestamp", ".", "getUTCDate", "(", ")", ".", "toString", "(", ")", ";", "return", "[", "year", ",", "double_digitize", "(", "month", ")", ",", "double_digitize", "(", "day", ")", "]", ".", "join", "(", "'.'", ")", ";", "case", "'week'", ":", "var", "week", "=", "current_week_number", "(", "timestamp", ")", ";", "return", "[", "year", ",", "double_digitize", "(", "week", ")", "]", ".", "join", "(", "'.'", ")", ";", "case", "'month'", ":", "return", "[", "year", ",", "double_digitize", "(", "month", ")", "]", ".", "join", "(", "'.'", ")", ";", "case", "'year'", ":", "return", "year", ";", "case", "'none'", ":", "return", "''", ";", "default", ":", "throw", "new", "Error", "(", "'invalid interval: '", "+", "interval", "+", "'; accepted intervals are \"day\", \"week\", \"month\", \"year\", and \"none\"'", ")", ";", "}", "}" ]
YYYY.MM.dd
[ "YYYY", ".", "MM", ".", "dd" ]
7b3b1c46943381230bc7dde33874a738a0a50cbe
https://github.com/juttle/juttle-elastic-adapter/blob/7b3b1c46943381230bc7dde33874a738a0a50cbe/lib/utils.js#L40-L69
46,043
nickzuber/needle
src/BinarySearchTree/binarySearchTree.js
deleteHelper
function deleteHelper (data, node, nodeType, parentNode) { if (node === null) { return false; } // @TODO handle object comparisons -- doing a stringify is horrible dont do that if (data === node.data) { if (nodeType === Types.RIGHT) { parentNode.right = null; } else { parentNode.left = null; } // Fix tree if (node.left) { var nodeRightSubtree = node.right; parentNode[nodeType] = node.left; parentNode[nodeType].right = nodeRightSubtree; } else if (node.right) { var nodeLeftSubtree = node.left; parentNode[nodeType] = node.right; parentNode[nodeType].left = nodeLeftSubtree; } return true; } if (safeCompare(data, node.data, this.compare)) { return deleteHelper(data, node.left, Types.LEFT, node); } else { return deleteHelper(data, node.right, Types.RIGHT, node); } }
javascript
function deleteHelper (data, node, nodeType, parentNode) { if (node === null) { return false; } // @TODO handle object comparisons -- doing a stringify is horrible dont do that if (data === node.data) { if (nodeType === Types.RIGHT) { parentNode.right = null; } else { parentNode.left = null; } // Fix tree if (node.left) { var nodeRightSubtree = node.right; parentNode[nodeType] = node.left; parentNode[nodeType].right = nodeRightSubtree; } else if (node.right) { var nodeLeftSubtree = node.left; parentNode[nodeType] = node.right; parentNode[nodeType].left = nodeLeftSubtree; } return true; } if (safeCompare(data, node.data, this.compare)) { return deleteHelper(data, node.left, Types.LEFT, node); } else { return deleteHelper(data, node.right, Types.RIGHT, node); } }
[ "function", "deleteHelper", "(", "data", ",", "node", ",", "nodeType", ",", "parentNode", ")", "{", "if", "(", "node", "===", "null", ")", "{", "return", "false", ";", "}", "// @TODO handle object comparisons -- doing a stringify is horrible dont do that", "if", "(", "data", "===", "node", ".", "data", ")", "{", "if", "(", "nodeType", "===", "Types", ".", "RIGHT", ")", "{", "parentNode", ".", "right", "=", "null", ";", "}", "else", "{", "parentNode", ".", "left", "=", "null", ";", "}", "// Fix tree", "if", "(", "node", ".", "left", ")", "{", "var", "nodeRightSubtree", "=", "node", ".", "right", ";", "parentNode", "[", "nodeType", "]", "=", "node", ".", "left", ";", "parentNode", "[", "nodeType", "]", ".", "right", "=", "nodeRightSubtree", ";", "}", "else", "if", "(", "node", ".", "right", ")", "{", "var", "nodeLeftSubtree", "=", "node", ".", "left", ";", "parentNode", "[", "nodeType", "]", "=", "node", ".", "right", ";", "parentNode", "[", "nodeType", "]", ".", "left", "=", "nodeLeftSubtree", ";", "}", "return", "true", ";", "}", "if", "(", "safeCompare", "(", "data", ",", "node", ".", "data", ",", "this", ".", "compare", ")", ")", "{", "return", "deleteHelper", "(", "data", ",", "node", ".", "left", ",", "Types", ".", "LEFT", ",", "node", ")", ";", "}", "else", "{", "return", "deleteHelper", "(", "data", ",", "node", ".", "right", ",", "Types", ".", "RIGHT", ",", "node", ")", ";", "}", "}" ]
Deletes a node from the tree with the value of `data`. @param {any} data The data of the node to delete. @param {Node} node The current node being analyzed. @param {Node} nodeType The type of child of the current node being analyzed. @param {Node} parentNode The last node that was analyzed. @return {boolean} Returns the success of the deletion success.
[ "Deletes", "a", "node", "from", "the", "tree", "with", "the", "value", "of", "data", "." ]
9565b3c193b93d67ffed39d430eba395a7bb5531
https://github.com/nickzuber/needle/blob/9565b3c193b93d67ffed39d430eba395a7bb5531/src/BinarySearchTree/binarySearchTree.js#L231-L262
46,044
THEjoezack/BoxPusher
public/js-roguelike-skeleton/manual/index/entity/js/basic-movement.js
function(direction){ var directionCoords = { up: {x: 0, y:-1}, right: {x: 1, y: 0}, down: {x: 0, y: 1}, left: {x:-1, y: 0} }; return directionCoords[direction]; }
javascript
function(direction){ var directionCoords = { up: {x: 0, y:-1}, right: {x: 1, y: 0}, down: {x: 0, y: 1}, left: {x:-1, y: 0} }; return directionCoords[direction]; }
[ "function", "(", "direction", ")", "{", "var", "directionCoords", "=", "{", "up", ":", "{", "x", ":", "0", ",", "y", ":", "-", "1", "}", ",", "right", ":", "{", "x", ":", "1", ",", "y", ":", "0", "}", ",", "down", ":", "{", "x", ":", "0", ",", "y", ":", "1", "}", ",", "left", ":", "{", "x", ":", "-", "1", ",", "y", ":", "0", "}", "}", ";", "return", "directionCoords", "[", "direction", "]", ";", "}" ]
Gets the adjustment coord from a direction string. @method directionToAdjustCoord @param {String} direction - The current direction. @return {Object} {x: 0, y: 0}
[ "Gets", "the", "adjustment", "coord", "from", "a", "direction", "string", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/manual/index/entity/js/basic-movement.js#L21-L29
46,045
THEjoezack/BoxPusher
public/js-roguelike-skeleton/manual/index/entity/js/basic-movement.js
function(currentDirection){ var directions = ['up', 'right', 'down', 'left'], currentDirIndex = directions.indexOf(currentDirection), newDirIndex; // if currentDirection is not valid or is the last in the array use the first direction in the array if(currentDirIndex === -1 || currentDirIndex === directions.length - 1){ newDirIndex = 0; } else { newDirIndex = currentDirIndex + 1; } return directions[newDirIndex]; }
javascript
function(currentDirection){ var directions = ['up', 'right', 'down', 'left'], currentDirIndex = directions.indexOf(currentDirection), newDirIndex; // if currentDirection is not valid or is the last in the array use the first direction in the array if(currentDirIndex === -1 || currentDirIndex === directions.length - 1){ newDirIndex = 0; } else { newDirIndex = currentDirIndex + 1; } return directions[newDirIndex]; }
[ "function", "(", "currentDirection", ")", "{", "var", "directions", "=", "[", "'up'", ",", "'right'", ",", "'down'", ",", "'left'", "]", ",", "currentDirIndex", "=", "directions", ".", "indexOf", "(", "currentDirection", ")", ",", "newDirIndex", ";", "// if currentDirection is not valid or is the last in the array use the first direction in the array", "if", "(", "currentDirIndex", "===", "-", "1", "||", "currentDirIndex", "===", "directions", ".", "length", "-", "1", ")", "{", "newDirIndex", "=", "0", ";", "}", "else", "{", "newDirIndex", "=", "currentDirIndex", "+", "1", ";", "}", "return", "directions", "[", "newDirIndex", "]", ";", "}" ]
Gets the next direction in the list @method getNextDirection @param {String} direction - The current direction. @return {String}
[ "Gets", "the", "next", "direction", "in", "the", "list" ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/manual/index/entity/js/basic-movement.js#L37-L48
46,046
THEjoezack/BoxPusher
public/js-roguelike-skeleton/manual/index/entity/js/basic-movement.js
function(x, y) { // remove light from current position if(this.game.lighting.get(this.x, this.y)){ this.game.lighting.remove(this.x, this.y); } // add to new position this.game.lighting.set(x, y, this.light_r, this.light_g, this.light_b); RL.Entity.prototype.moveTo.call(this, x, y); }
javascript
function(x, y) { // remove light from current position if(this.game.lighting.get(this.x, this.y)){ this.game.lighting.remove(this.x, this.y); } // add to new position this.game.lighting.set(x, y, this.light_r, this.light_g, this.light_b); RL.Entity.prototype.moveTo.call(this, x, y); }
[ "function", "(", "x", ",", "y", ")", "{", "// remove light from current position", "if", "(", "this", ".", "game", ".", "lighting", ".", "get", "(", "this", ".", "x", ",", "this", ".", "y", ")", ")", "{", "this", ".", "game", ".", "lighting", ".", "remove", "(", "this", ".", "x", ",", "this", ".", "y", ")", ";", "}", "// add to new position", "this", ".", "game", ".", "lighting", ".", "set", "(", "x", ",", "y", ",", "this", ".", "light_r", ",", "this", ".", "light_g", ",", "this", ".", "light_b", ")", ";", "RL", ".", "Entity", ".", "prototype", ".", "moveTo", ".", "call", "(", "this", ",", "x", ",", "y", ")", ";", "}" ]
Changes the position of this entity on the map. @method moveTo @param {Number} x - The tile map x coord to move to. @param {Number} y - The tile map y coord to move to.
[ "Changes", "the", "position", "of", "this", "entity", "on", "the", "map", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/manual/index/entity/js/basic-movement.js#L84-L93
46,047
overtrue/validator.js
lib/validator.js
extend
function extend() { var src, copy, name, options, clone; var target = arguments[0] || {}; var i = 1; var length = arguments.length; for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( copy && typeof copy === "object" ) { clone = src && typeof src === "object" ? src : {}; // Never move original objects, clone them target[ name ] = extend( clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }
javascript
function extend() { var src, copy, name, options, clone; var target = arguments[0] || {}; var i = 1; var length = arguments.length; for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( copy && typeof copy === "object" ) { clone = src && typeof src === "object" ? src : {}; // Never move original objects, clone them target[ name ] = extend( clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }
[ "function", "extend", "(", ")", "{", "var", "src", ",", "copy", ",", "name", ",", "options", ",", "clone", ";", "var", "target", "=", "arguments", "[", "0", "]", "||", "{", "}", ";", "var", "i", "=", "1", ";", "var", "length", "=", "arguments", ".", "length", ";", "for", "(", ";", "i", "<", "length", ";", "i", "++", ")", "{", "// Only deal with non-null/undefined values", "if", "(", "(", "options", "=", "arguments", "[", "i", "]", ")", "!=", "null", ")", "{", "// Extend the base object", "for", "(", "name", "in", "options", ")", "{", "src", "=", "target", "[", "name", "]", ";", "copy", "=", "options", "[", "name", "]", ";", "// Prevent never-ending loop", "if", "(", "target", "===", "copy", ")", "{", "continue", ";", "}", "// Recurse if we're merging plain objects or arrays", "if", "(", "copy", "&&", "typeof", "copy", "===", "\"object\"", ")", "{", "clone", "=", "src", "&&", "typeof", "src", "===", "\"object\"", "?", "src", ":", "{", "}", ";", "// Never move original objects, clone them", "target", "[", "name", "]", "=", "extend", "(", "clone", ",", "copy", ")", ";", "// Don't bring in undefined values", "}", "else", "if", "(", "copy", "!==", "undefined", ")", "{", "target", "[", "name", "]", "=", "copy", ";", "}", "}", "}", "}", "// Return the modified object", "return", "target", ";", "}" ]
Based on jquery's extend function
[ "Based", "on", "jquery", "s", "extend", "function" ]
ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c
https://github.com/overtrue/validator.js/blob/ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c/lib/validator.js#L97-L133
46,048
overtrue/validator.js
lib/validator.js
_explodeRules
function _explodeRules(rules) { for (var i in rules) { if (is_string(rules[i])) { rules[i] = rules[i].split('|'); } } return rules; }
javascript
function _explodeRules(rules) { for (var i in rules) { if (is_string(rules[i])) { rules[i] = rules[i].split('|'); } } return rules; }
[ "function", "_explodeRules", "(", "rules", ")", "{", "for", "(", "var", "i", "in", "rules", ")", "{", "if", "(", "is_string", "(", "rules", "[", "i", "]", ")", ")", "{", "rules", "[", "i", "]", "=", "rules", "[", "i", "]", ".", "split", "(", "'|'", ")", ";", "}", "}", "return", "rules", ";", "}" ]
explode the rules into an array of rules. @return {Void}
[ "explode", "the", "rules", "into", "an", "array", "of", "rules", "." ]
ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c
https://github.com/overtrue/validator.js/blob/ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c/lib/validator.js#L211-L218
46,049
overtrue/validator.js
lib/validator.js
_parseRule
function _parseRule(rule) { var parameters = []; // The format for specifying validation rules and parameters follows an // easy {rule}:{parameters} formatting convention. For instance the // rule "Max:3" states that the value may only be three letters. if (rule.indexOf(':')) { var ruleInfo = rule.split(':'); parameters = _parseParameters(ruleInfo[0], ruleInfo[1]); } return { parameters: parameters, rule: ruleInfo[0]}; }
javascript
function _parseRule(rule) { var parameters = []; // The format for specifying validation rules and parameters follows an // easy {rule}:{parameters} formatting convention. For instance the // rule "Max:3" states that the value may only be three letters. if (rule.indexOf(':')) { var ruleInfo = rule.split(':'); parameters = _parseParameters(ruleInfo[0], ruleInfo[1]); } return { parameters: parameters, rule: ruleInfo[0]}; }
[ "function", "_parseRule", "(", "rule", ")", "{", "var", "parameters", "=", "[", "]", ";", "// The format for specifying validation rules and parameters follows an", "// easy {rule}:{parameters} formatting convention. For instance the", "// rule \"Max:3\" states that the value may only be three letters.", "if", "(", "rule", ".", "indexOf", "(", "':'", ")", ")", "{", "var", "ruleInfo", "=", "rule", ".", "split", "(", "':'", ")", ";", "parameters", "=", "_parseParameters", "(", "ruleInfo", "[", "0", "]", ",", "ruleInfo", "[", "1", "]", ")", ";", "}", "return", "{", "parameters", ":", "parameters", ",", "rule", ":", "ruleInfo", "[", "0", "]", "}", ";", "}" ]
parse the rule @param {Array} rule @return {Object}
[ "parse", "the", "rule" ]
ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c
https://github.com/overtrue/validator.js/blob/ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c/lib/validator.js#L227-L239
46,050
overtrue/validator.js
lib/validator.js
_parseParameters
function _parseParameters(rule, parameter) { if (rule.toLowerCase() == 'regex') return [parameter]; if (is_string(parameter)) { return parameter.split(','); }; return []; }
javascript
function _parseParameters(rule, parameter) { if (rule.toLowerCase() == 'regex') return [parameter]; if (is_string(parameter)) { return parameter.split(','); }; return []; }
[ "function", "_parseParameters", "(", "rule", ",", "parameter", ")", "{", "if", "(", "rule", ".", "toLowerCase", "(", ")", "==", "'regex'", ")", "return", "[", "parameter", "]", ";", "if", "(", "is_string", "(", "parameter", ")", ")", "{", "return", "parameter", ".", "split", "(", "','", ")", ";", "}", ";", "return", "[", "]", ";", "}" ]
parse parameters of rule @param {String} rule @param {String} parameter @return {Array}
[ "parse", "parameters", "of", "rule" ]
ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c
https://github.com/overtrue/validator.js/blob/ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c/lib/validator.js#L249-L256
46,051
overtrue/validator.js
lib/validator.js
_addFailure
function _addFailure(attribute, rule, parameters) { _addError(attribute, rule, parameters); if (! _failedRules[attribute]) { _failedRules[attribute] = {}; } _failedRules[attribute][rule] = parameters; }
javascript
function _addFailure(attribute, rule, parameters) { _addError(attribute, rule, parameters); if (! _failedRules[attribute]) { _failedRules[attribute] = {}; } _failedRules[attribute][rule] = parameters; }
[ "function", "_addFailure", "(", "attribute", ",", "rule", ",", "parameters", ")", "{", "_addError", "(", "attribute", ",", "rule", ",", "parameters", ")", ";", "if", "(", "!", "_failedRules", "[", "attribute", "]", ")", "{", "_failedRules", "[", "attribute", "]", "=", "{", "}", ";", "}", "_failedRules", "[", "attribute", "]", "[", "rule", "]", "=", "parameters", ";", "}" ]
add a failure rule @param {String} attribute @param {String} rule @param {Array} parameters @return {Void}
[ "add", "a", "failure", "rule" ]
ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c
https://github.com/overtrue/validator.js/blob/ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c/lib/validator.js#L267-L273
46,052
overtrue/validator.js
lib/validator.js
_addError
function _addError(attribute, rule, parameters) { if (_errors[attribute]) { return; }; _errors[attribute] = _formatMessage(_getMessage(attribute, rule) || '', attribute, rule, parameters); }
javascript
function _addError(attribute, rule, parameters) { if (_errors[attribute]) { return; }; _errors[attribute] = _formatMessage(_getMessage(attribute, rule) || '', attribute, rule, parameters); }
[ "function", "_addError", "(", "attribute", ",", "rule", ",", "parameters", ")", "{", "if", "(", "_errors", "[", "attribute", "]", ")", "{", "return", ";", "}", ";", "_errors", "[", "attribute", "]", "=", "_formatMessage", "(", "_getMessage", "(", "attribute", ",", "rule", ")", "||", "''", ",", "attribute", ",", "rule", ",", "parameters", ")", ";", "}" ]
add a error message @param {String} attribute @param {String} rule @param {Array} parameters @return {Void}
[ "add", "a", "error", "message" ]
ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c
https://github.com/overtrue/validator.js/blob/ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c/lib/validator.js#L284-L289
46,053
overtrue/validator.js
lib/validator.js
_getMessage
function _getMessage(attribute, rule) { var message = _messages[rule]; if (is_object(message)) { var value = _getValue(attribute); if (is_array(value) && message['array']) { return message['array']; } else if (_resolvers.numeric(value) && message['numeric']) { return message['numeric']; } else if (is_string(value) && message['string']){ return message['string']; } }; return message; }
javascript
function _getMessage(attribute, rule) { var message = _messages[rule]; if (is_object(message)) { var value = _getValue(attribute); if (is_array(value) && message['array']) { return message['array']; } else if (_resolvers.numeric(value) && message['numeric']) { return message['numeric']; } else if (is_string(value) && message['string']){ return message['string']; } }; return message; }
[ "function", "_getMessage", "(", "attribute", ",", "rule", ")", "{", "var", "message", "=", "_messages", "[", "rule", "]", ";", "if", "(", "is_object", "(", "message", ")", ")", "{", "var", "value", "=", "_getValue", "(", "attribute", ")", ";", "if", "(", "is_array", "(", "value", ")", "&&", "message", "[", "'array'", "]", ")", "{", "return", "message", "[", "'array'", "]", ";", "}", "else", "if", "(", "_resolvers", ".", "numeric", "(", "value", ")", "&&", "message", "[", "'numeric'", "]", ")", "{", "return", "message", "[", "'numeric'", "]", ";", "}", "else", "if", "(", "is_string", "(", "value", ")", "&&", "message", "[", "'string'", "]", ")", "{", "return", "message", "[", "'string'", "]", ";", "}", "}", ";", "return", "message", ";", "}" ]
get attribute message @param {String} attribute @param {String} rule @return {String}
[ "get", "attribute", "message" ]
ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c
https://github.com/overtrue/validator.js/blob/ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c/lib/validator.js#L310-L325
46,054
overtrue/validator.js
lib/validator.js
_formatMessage
function _formatMessage(message, attribute, rule, parameters) { parameters.unshift(_getAttribute(attribute)); for(i in parameters){ message = message.replace(/:[a-zA-z_][a-zA-z_0-9]+/, parameters[i]); } if (typeof _replacers[rule] === 'function') { message = _replacers[rule](message, attribute, rule, parameters); } return message; }
javascript
function _formatMessage(message, attribute, rule, parameters) { parameters.unshift(_getAttribute(attribute)); for(i in parameters){ message = message.replace(/:[a-zA-z_][a-zA-z_0-9]+/, parameters[i]); } if (typeof _replacers[rule] === 'function') { message = _replacers[rule](message, attribute, rule, parameters); } return message; }
[ "function", "_formatMessage", "(", "message", ",", "attribute", ",", "rule", ",", "parameters", ")", "{", "parameters", ".", "unshift", "(", "_getAttribute", "(", "attribute", ")", ")", ";", "for", "(", "i", "in", "parameters", ")", "{", "message", "=", "message", ".", "replace", "(", "/", ":[a-zA-z_][a-zA-z_0-9]+", "/", ",", "parameters", "[", "i", "]", ")", ";", "}", "if", "(", "typeof", "_replacers", "[", "rule", "]", "===", "'function'", ")", "{", "message", "=", "_replacers", "[", "rule", "]", "(", "message", ",", "attribute", ",", "rule", ",", "parameters", ")", ";", "}", "return", "message", ";", "}" ]
replace attributes. @param {String} message @param {String} attribute @param {String} rule @param {Array} parameters @return {String}
[ "replace", "attributes", "." ]
ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c
https://github.com/overtrue/validator.js/blob/ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c/lib/validator.js#L337-L349
46,055
overtrue/validator.js
lib/validator.js
_getAttribute
function _getAttribute(attribute) { if (is_string(_attributes[attribute])) { return _attributes[attribute]; } if ((line = _translator.trans(attribute)) !== attribute) { return line; } else { return attribute.replace('_', ' '); } }
javascript
function _getAttribute(attribute) { if (is_string(_attributes[attribute])) { return _attributes[attribute]; } if ((line = _translator.trans(attribute)) !== attribute) { return line; } else { return attribute.replace('_', ' '); } }
[ "function", "_getAttribute", "(", "attribute", ")", "{", "if", "(", "is_string", "(", "_attributes", "[", "attribute", "]", ")", ")", "{", "return", "_attributes", "[", "attribute", "]", ";", "}", "if", "(", "(", "line", "=", "_translator", ".", "trans", "(", "attribute", ")", ")", "!==", "attribute", ")", "{", "return", "line", ";", "}", "else", "{", "return", "attribute", ".", "replace", "(", "'_'", ",", "' '", ")", ";", "}", "}" ]
get attribute name @param {String} attribute @return {String}
[ "get", "attribute", "name" ]
ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c
https://github.com/overtrue/validator.js/blob/ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c/lib/validator.js#L358-L368
46,056
overtrue/validator.js
lib/validator.js
_getRule
function _getRule(attribute, rules) { rules = rules || []; if ( ! rules[attribute]) { return; } for(var i in rules[attribute]) { var value = rules[attribute][i]; parsedRule = _parseRule(rule); if (in_array(parsedRule.rule, rules)) return [parsedRule.rule, parsedRule.parameters]; } }
javascript
function _getRule(attribute, rules) { rules = rules || []; if ( ! rules[attribute]) { return; } for(var i in rules[attribute]) { var value = rules[attribute][i]; parsedRule = _parseRule(rule); if (in_array(parsedRule.rule, rules)) return [parsedRule.rule, parsedRule.parameters]; } }
[ "function", "_getRule", "(", "attribute", ",", "rules", ")", "{", "rules", "=", "rules", "||", "[", "]", ";", "if", "(", "!", "rules", "[", "attribute", "]", ")", "{", "return", ";", "}", "for", "(", "var", "i", "in", "rules", "[", "attribute", "]", ")", "{", "var", "value", "=", "rules", "[", "attribute", "]", "[", "i", "]", ";", "parsedRule", "=", "_parseRule", "(", "rule", ")", ";", "if", "(", "in_array", "(", "parsedRule", ".", "rule", ",", "rules", ")", ")", "return", "[", "parsedRule", ".", "rule", ",", "parsedRule", ".", "parameters", "]", ";", "}", "}" ]
get rule and parameters of a rules @param {String} attribute @param {String|array} rules @return {Array|null}
[ "get", "rule", "and", "parameters", "of", "a", "rules" ]
ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c
https://github.com/overtrue/validator.js/blob/ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c/lib/validator.js#L390-L404
46,057
overtrue/validator.js
lib/validator.js
_getSize
function _getSize(attribute, value) { hasNumeric = _hasRule(attribute, _numericRules); // This method will determine if the attribute is a number, string, or file and // return the proper size accordingly. If it is a number, then number itself // is the size. If it is a file, we take kilobytes, and for a string the // entire length of the string will be considered the attribute size. if (/^[0-9]+$/.test(value) && hasNumeric) { return getValue(attribute); } else if (value && is_string(value) || is_array(value)) { return value.length; } return 0; }
javascript
function _getSize(attribute, value) { hasNumeric = _hasRule(attribute, _numericRules); // This method will determine if the attribute is a number, string, or file and // return the proper size accordingly. If it is a number, then number itself // is the size. If it is a file, we take kilobytes, and for a string the // entire length of the string will be considered the attribute size. if (/^[0-9]+$/.test(value) && hasNumeric) { return getValue(attribute); } else if (value && is_string(value) || is_array(value)) { return value.length; } return 0; }
[ "function", "_getSize", "(", "attribute", ",", "value", ")", "{", "hasNumeric", "=", "_hasRule", "(", "attribute", ",", "_numericRules", ")", ";", "// This method will determine if the attribute is a number, string, or file and", "// return the proper size accordingly. If it is a number, then number itself", "// is the size. If it is a file, we take kilobytes, and for a string the", "// entire length of the string will be considered the attribute size.", "if", "(", "/", "^[0-9]+$", "/", ".", "test", "(", "value", ")", "&&", "hasNumeric", ")", "{", "return", "getValue", "(", "attribute", ")", ";", "}", "else", "if", "(", "value", "&&", "is_string", "(", "value", ")", "||", "is_array", "(", "value", ")", ")", "{", "return", "value", ".", "length", ";", "}", "return", "0", ";", "}" ]
get attribute size @param {String} attribute @param {Mixed} value @return {Number}
[ "get", "attribute", "size" ]
ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c
https://github.com/overtrue/validator.js/blob/ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c/lib/validator.js#L414-L428
46,058
overtrue/validator.js
lib/validator.js
_requireParameterCount
function _requireParameterCount(count, parameters, rule) { if (parameters.length < count) { throw Error('Validation rule"' + rule + '" requires at least ' + count + ' parameters.'); } }
javascript
function _requireParameterCount(count, parameters, rule) { if (parameters.length < count) { throw Error('Validation rule"' + rule + '" requires at least ' + count + ' parameters.'); } }
[ "function", "_requireParameterCount", "(", "count", ",", "parameters", ",", "rule", ")", "{", "if", "(", "parameters", ".", "length", "<", "count", ")", "{", "throw", "Error", "(", "'Validation rule\"'", "+", "rule", "+", "'\" requires at least '", "+", "count", "+", "' parameters.'", ")", ";", "}", "}" ]
check parameters count @param {Number} count @param {Array} parameters @param {String} rule @return {Void}
[ "check", "parameters", "count" ]
ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c
https://github.com/overtrue/validator.js/blob/ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c/lib/validator.js#L439-L443
46,059
overtrue/validator.js
lib/validator.js
_allFailingRequired
function _allFailingRequired(attributes) { for (var i in attributes) { var akey = attributes[i]; if (resolvers.validateRequired(key, self._getValue(key))) { return false; } } return true; }
javascript
function _allFailingRequired(attributes) { for (var i in attributes) { var akey = attributes[i]; if (resolvers.validateRequired(key, self._getValue(key))) { return false; } } return true; }
[ "function", "_allFailingRequired", "(", "attributes", ")", "{", "for", "(", "var", "i", "in", "attributes", ")", "{", "var", "akey", "=", "attributes", "[", "i", "]", ";", "if", "(", "resolvers", ".", "validateRequired", "(", "key", ",", "self", ".", "_getValue", "(", "key", ")", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
all failing check @param {Array} attributes @return {Boolean}
[ "all", "failing", "check" ]
ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c
https://github.com/overtrue/validator.js/blob/ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c/lib/validator.js#L452-L462
46,060
overtrue/validator.js
lib/validator.js
_anyFailingRequired
function _anyFailingRequired(attributes) { for (var i in attributes) { var key = attributes[i]; if ( ! _resolvers.validateRequired(key, self.date[key])) { return true; } } return false; }
javascript
function _anyFailingRequired(attributes) { for (var i in attributes) { var key = attributes[i]; if ( ! _resolvers.validateRequired(key, self.date[key])) { return true; } } return false; }
[ "function", "_anyFailingRequired", "(", "attributes", ")", "{", "for", "(", "var", "i", "in", "attributes", ")", "{", "var", "key", "=", "attributes", "[", "i", "]", ";", "if", "(", "!", "_resolvers", ".", "validateRequired", "(", "key", ",", "self", ".", "date", "[", "key", "]", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
determine if any of the given attributes fail the required test. @param array $attributes @return bool
[ "determine", "if", "any", "of", "the", "given", "attributes", "fail", "the", "required", "test", "." ]
ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c
https://github.com/overtrue/validator.js/blob/ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c/lib/validator.js#L470-L479
46,061
overtrue/validator.js
lib/validator.js
function(rule, message) { if (is_object(rule)) { _messages = extend({}, _messages, rule); } else if (is_string(rule)) { _messages[rule] = message; } }
javascript
function(rule, message) { if (is_object(rule)) { _messages = extend({}, _messages, rule); } else if (is_string(rule)) { _messages[rule] = message; } }
[ "function", "(", "rule", ",", "message", ")", "{", "if", "(", "is_object", "(", "rule", ")", ")", "{", "_messages", "=", "extend", "(", "{", "}", ",", "_messages", ",", "rule", ")", ";", "}", "else", "if", "(", "is_string", "(", "rule", ")", ")", "{", "_messages", "[", "rule", "]", "=", "message", ";", "}", "}" ]
add custom messages @param {String/Object} rule @param {String} message @return {Void}
[ "add", "custom", "messages" ]
ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c
https://github.com/overtrue/validator.js/blob/ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c/lib/validator.js#L741-L747
46,062
overtrue/validator.js
lib/validator.js
function(attribute, alias) { if (is_object(attribute)) { _attributes = extend({}, _attributes, attribute); } else if (is_string(attribute)) { _attributes[attribute] = alias; } }
javascript
function(attribute, alias) { if (is_object(attribute)) { _attributes = extend({}, _attributes, attribute); } else if (is_string(attribute)) { _attributes[attribute] = alias; } }
[ "function", "(", "attribute", ",", "alias", ")", "{", "if", "(", "is_object", "(", "attribute", ")", ")", "{", "_attributes", "=", "extend", "(", "{", "}", ",", "_attributes", ",", "attribute", ")", ";", "}", "else", "if", "(", "is_string", "(", "attribute", ")", ")", "{", "_attributes", "[", "attribute", "]", "=", "alias", ";", "}", "}" ]
add attributes alias @param {String/Object} attribute @param {String} alias @return {Void}
[ "add", "attributes", "alias" ]
ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c
https://github.com/overtrue/validator.js/blob/ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c/lib/validator.js#L757-L763
46,063
overtrue/validator.js
lib/validator.js
function(value, alias) { if (is_object(value)) { _values = extend({}, _values, value); } else if (is_string(rule)) { _values[value] = alias; } }
javascript
function(value, alias) { if (is_object(value)) { _values = extend({}, _values, value); } else if (is_string(rule)) { _values[value] = alias; } }
[ "function", "(", "value", ",", "alias", ")", "{", "if", "(", "is_object", "(", "value", ")", ")", "{", "_values", "=", "extend", "(", "{", "}", ",", "_values", ",", "value", ")", ";", "}", "else", "if", "(", "is_string", "(", "rule", ")", ")", "{", "_values", "[", "value", "]", "=", "alias", ";", "}", "}" ]
add values alias @param {String/Object} attribute @param {String} alias @return {Void}
[ "add", "values", "alias" ]
ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c
https://github.com/overtrue/validator.js/blob/ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c/lib/validator.js#L773-L779
46,064
overtrue/validator.js
lib/validator.js
function(rule, fn) { if (is_object(rule)) { _replacers = extend({}, _replacers, rule); } else if (is_string(rule)) { _replacers[rule] = fn; } }
javascript
function(rule, fn) { if (is_object(rule)) { _replacers = extend({}, _replacers, rule); } else if (is_string(rule)) { _replacers[rule] = fn; } }
[ "function", "(", "rule", ",", "fn", ")", "{", "if", "(", "is_object", "(", "rule", ")", ")", "{", "_replacers", "=", "extend", "(", "{", "}", ",", "_replacers", ",", "rule", ")", ";", "}", "else", "if", "(", "is_string", "(", "rule", ")", ")", "{", "_replacers", "[", "rule", "]", "=", "fn", ";", "}", "}" ]
add message replacers @param {String/Object} rule @param {Function} fn @return {Void}
[ "add", "message", "replacers" ]
ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c
https://github.com/overtrue/validator.js/blob/ae20d12cd097ef6dc2e7b13ee9e58d4ed617529c/lib/validator.js#L789-L795
46,065
elidoran/node-date-holidays-us
lib/index.js
makeHoliday
function makeHoliday(date, info, observedInfo) { // always make the holiday. var holiday = { info: info, date: { month: date.getMonth(), day : date.getDate() } } // if the holiday info's `bank` value has a function then // give it the date so it can evaluate the value. if ('function' === typeof info.bank) { info.bank = info.bank(date) } // without an observed holiday we return only the main holiday if (date.observed == null) { return holiday } // there's an observed date so return both holidays in an array. else { return [ holiday, // main holiday { // observed holiday info: observedInfo, date: { month: date.observed.getMonth(), day : date.observed.getDate() } } ] } }
javascript
function makeHoliday(date, info, observedInfo) { // always make the holiday. var holiday = { info: info, date: { month: date.getMonth(), day : date.getDate() } } // if the holiday info's `bank` value has a function then // give it the date so it can evaluate the value. if ('function' === typeof info.bank) { info.bank = info.bank(date) } // without an observed holiday we return only the main holiday if (date.observed == null) { return holiday } // there's an observed date so return both holidays in an array. else { return [ holiday, // main holiday { // observed holiday info: observedInfo, date: { month: date.observed.getMonth(), day : date.observed.getDate() } } ] } }
[ "function", "makeHoliday", "(", "date", ",", "info", ",", "observedInfo", ")", "{", "// always make the holiday.", "var", "holiday", "=", "{", "info", ":", "info", ",", "date", ":", "{", "month", ":", "date", ".", "getMonth", "(", ")", ",", "day", ":", "date", ".", "getDate", "(", ")", "}", "}", "// if the holiday info's `bank` value has a function then", "// give it the date so it can evaluate the value.", "if", "(", "'function'", "===", "typeof", "info", ".", "bank", ")", "{", "info", ".", "bank", "=", "info", ".", "bank", "(", "date", ")", "}", "// without an observed holiday we return only the main holiday", "if", "(", "date", ".", "observed", "==", "null", ")", "{", "return", "holiday", "}", "// there's an observed date so return both holidays in an array.", "else", "{", "return", "[", "holiday", ",", "// main holiday", "{", "// observed holiday", "info", ":", "observedInfo", ",", "date", ":", "{", "month", ":", "date", ".", "observed", ".", "getMonth", "(", ")", ",", "day", ":", "date", ".", "observed", ".", "getDate", "(", ")", "}", "}", "]", "}", "}" ]
helper function which accepts the calculated holiday date and holiday info's. if an observed date was produced then it returns both holidays. also helps with the `bank` boolean value.
[ "helper", "function", "which", "accepts", "the", "calculated", "holiday", "date", "and", "holiday", "info", "s", ".", "if", "an", "observed", "date", "was", "produced", "then", "it", "returns", "both", "holidays", ".", "also", "helps", "with", "the", "bank", "boolean", "value", "." ]
7e3ada9bddcbe79e4f1eaf7161629cd7759fc275
https://github.com/elidoran/node-date-holidays-us/blob/7e3ada9bddcbe79e4f1eaf7161629cd7759fc275/lib/index.js#L198-L233
46,066
elidoran/node-date-holidays-us
lib/index.js
newYearsSpecial
function newYearsSpecial(year) { // 1. hold onto the date, we'll need it in #3 var date = holidays.newYearsDay(year) // 2. do the usual. var newYears = makeHoliday( date, { name: 'New Year\'s Day', bank: !date.observed }, { name: 'New Year\'s Day (Observed)', bank: true } ) // 3. check if the observed date is in the previous year... if (date.observed && date.observed.getFullYear() < year) { // specify that year in the observed holiday's date. newYears[1].date.year = year - 1 } return newYears }
javascript
function newYearsSpecial(year) { // 1. hold onto the date, we'll need it in #3 var date = holidays.newYearsDay(year) // 2. do the usual. var newYears = makeHoliday( date, { name: 'New Year\'s Day', bank: !date.observed }, { name: 'New Year\'s Day (Observed)', bank: true } ) // 3. check if the observed date is in the previous year... if (date.observed && date.observed.getFullYear() < year) { // specify that year in the observed holiday's date. newYears[1].date.year = year - 1 } return newYears }
[ "function", "newYearsSpecial", "(", "year", ")", "{", "// 1. hold onto the date, we'll need it in #3", "var", "date", "=", "holidays", ".", "newYearsDay", "(", "year", ")", "// 2. do the usual.", "var", "newYears", "=", "makeHoliday", "(", "date", ",", "{", "name", ":", "'New Year\\'s Day'", ",", "bank", ":", "!", "date", ".", "observed", "}", ",", "{", "name", ":", "'New Year\\'s Day (Observed)'", ",", "bank", ":", "true", "}", ")", "// 3. check if the observed date is in the previous year...", "if", "(", "date", ".", "observed", "&&", "date", ".", "observed", ".", "getFullYear", "(", ")", "<", "year", ")", "{", "// specify that year in the observed holiday's date.", "newYears", "[", "1", "]", ".", "date", ".", "year", "=", "year", "-", "1", "}", "return", "newYears", "}" ]
The New Year's holiday can have an observed date in the previous year. That messes with the whole "generate and cache holidays by year" thing. This handles it by identifying when that happens and specifying the custom year. The @date/holidays package handles the custom year as of v0.3.1.
[ "The", "New", "Year", "s", "holiday", "can", "have", "an", "observed", "date", "in", "the", "previous", "year", ".", "That", "messes", "with", "the", "whole", "generate", "and", "cache", "holidays", "by", "year", "thing", ".", "This", "handles", "it", "by", "identifying", "when", "that", "happens", "and", "specifying", "the", "custom", "year", ".", "The" ]
7e3ada9bddcbe79e4f1eaf7161629cd7759fc275
https://github.com/elidoran/node-date-holidays-us/blob/7e3ada9bddcbe79e4f1eaf7161629cd7759fc275/lib/index.js#L339-L358
46,067
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/mixins/action-interface.js
function(action, implementation){ this.performableActions = this.performableActions || {}; this.performableActions[action] = this.performableActions[action] || {}; this.performableActions[action].actionName = this.performableActions[action].actionName || action; implementation = implementation || RL.PerformableAction.Types[action]; this.performableActions[action] = Object.create(implementation); // merge could be used instead of Object.create but is less desirable // RL.Util.merge(this.performableAction.Types[action], implementation); if(this.performableActions[action].init){ this.performableActions[action].init.call(this); } }
javascript
function(action, implementation){ this.performableActions = this.performableActions || {}; this.performableActions[action] = this.performableActions[action] || {}; this.performableActions[action].actionName = this.performableActions[action].actionName || action; implementation = implementation || RL.PerformableAction.Types[action]; this.performableActions[action] = Object.create(implementation); // merge could be used instead of Object.create but is less desirable // RL.Util.merge(this.performableAction.Types[action], implementation); if(this.performableActions[action].init){ this.performableActions[action].init.call(this); } }
[ "function", "(", "action", ",", "implementation", ")", "{", "this", ".", "performableActions", "=", "this", ".", "performableActions", "||", "{", "}", ";", "this", ".", "performableActions", "[", "action", "]", "=", "this", ".", "performableActions", "[", "action", "]", "||", "{", "}", ";", "this", ".", "performableActions", "[", "action", "]", ".", "actionName", "=", "this", ".", "performableActions", "[", "action", "]", ".", "actionName", "||", "action", ";", "implementation", "=", "implementation", "||", "RL", ".", "PerformableAction", ".", "Types", "[", "action", "]", ";", "this", ".", "performableActions", "[", "action", "]", "=", "Object", ".", "create", "(", "implementation", ")", ";", "// merge could be used instead of Object.create but is less desirable", "// RL.Util.merge(this.performableAction.Types[action], implementation);", "if", "(", "this", ".", "performableActions", "[", "action", "]", ".", "init", ")", "{", "this", ".", "performableActions", "[", "action", "]", ".", "init", ".", "call", "(", "this", ")", ";", "}", "}" ]
Sets a performable action implementation on object. @method setPerformableAction @param {String} action - The action name. @param {PerformableAction} implementation - Object to set as the action implementation. or a string to lookup an implementation `RL.PerformableActions[implementation]`.
[ "Sets", "a", "performable", "action", "implementation", "on", "object", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/mixins/action-interface.js#L20-L34
46,068
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/mixins/action-interface.js
function(action, settings){ var handler = this.performableActions[action]; if(!handler){ return false; } if(!handler.getTargetsForAction){ return false; } settings = settings || {}; if(!settings.skipCanPerformAction && !this.canPerformAction(action, settings)){ return false; } return handler.getTargetsForAction.call(this, settings); }
javascript
function(action, settings){ var handler = this.performableActions[action]; if(!handler){ return false; } if(!handler.getTargetsForAction){ return false; } settings = settings || {}; if(!settings.skipCanPerformAction && !this.canPerformAction(action, settings)){ return false; } return handler.getTargetsForAction.call(this, settings); }
[ "function", "(", "action", ",", "settings", ")", "{", "var", "handler", "=", "this", ".", "performableActions", "[", "action", "]", ";", "if", "(", "!", "handler", ")", "{", "return", "false", ";", "}", "if", "(", "!", "handler", ".", "getTargetsForAction", ")", "{", "return", "false", ";", "}", "settings", "=", "settings", "||", "{", "}", ";", "if", "(", "!", "settings", ".", "skipCanPerformAction", "&&", "!", "this", ".", "canPerformAction", "(", "action", ",", "settings", ")", ")", "{", "return", "false", ";", "}", "return", "handler", ".", "getTargetsForAction", ".", "call", "(", "this", ",", "settings", ")", ";", "}" ]
Returns a list of valid targets to perform an action on. @method getTargetsForAction @param {String} action - The action to get targets for. @param {Object} [settings] - Settings for the action. @return {Array} Array of valid targets.
[ "Returns", "a", "list", "of", "valid", "targets", "to", "perform", "an", "action", "on", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/mixins/action-interface.js#L43-L59
46,069
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/mixins/action-interface.js
function(action, target, settings){ if(!this.performableActions){ return false; } var handler = this.performableActions[action]; if(!handler){ return false; } // target cannot resolve any actions if(!target.canResolveAction){ return false; } settings = settings || {}; if(!settings.skipCanPerformAction && !this.canPerformAction(action, settings)){ return false; } if(!(handler.canPerformActionOnTarget === true || handler.canPerformActionOnTarget.call(this, target, settings))){ return false; } return target.canResolveAction(action, this, settings); }
javascript
function(action, target, settings){ if(!this.performableActions){ return false; } var handler = this.performableActions[action]; if(!handler){ return false; } // target cannot resolve any actions if(!target.canResolveAction){ return false; } settings = settings || {}; if(!settings.skipCanPerformAction && !this.canPerformAction(action, settings)){ return false; } if(!(handler.canPerformActionOnTarget === true || handler.canPerformActionOnTarget.call(this, target, settings))){ return false; } return target.canResolveAction(action, this, settings); }
[ "function", "(", "action", ",", "target", ",", "settings", ")", "{", "if", "(", "!", "this", ".", "performableActions", ")", "{", "return", "false", ";", "}", "var", "handler", "=", "this", ".", "performableActions", "[", "action", "]", ";", "if", "(", "!", "handler", ")", "{", "return", "false", ";", "}", "// target cannot resolve any actions", "if", "(", "!", "target", ".", "canResolveAction", ")", "{", "return", "false", ";", "}", "settings", "=", "settings", "||", "{", "}", ";", "if", "(", "!", "settings", ".", "skipCanPerformAction", "&&", "!", "this", ".", "canPerformAction", "(", "action", ",", "settings", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "(", "handler", ".", "canPerformActionOnTarget", "===", "true", "||", "handler", ".", "canPerformActionOnTarget", ".", "call", "(", "this", ",", "target", ",", "settings", ")", ")", ")", "{", "return", "false", ";", "}", "return", "target", ".", "canResolveAction", "(", "action", ",", "this", ",", "settings", ")", ";", "}" ]
Checks if source can perform an action on target with given settings. @method canPerformActionOnTarget @param {string} action - The action to check. @param {Object} target - The target object to check against. @param {Object} [settings] - Settings for the action. @param {Object} [settings.skipCanPerformAction] - If true skips checking that `this.canPerformAction(action, settings) == true` @return {Boolean} `true` if the action can be performed on target.
[ "Checks", "if", "source", "can", "perform", "an", "action", "on", "target", "with", "given", "settings", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/mixins/action-interface.js#L96-L118
46,070
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/mixins/action-interface.js
function(action, target, settings){ if(!this.performableActions){ return false; } var handler = this.performableActions[action]; if(!handler){ return false; } settings = settings || {}; // the functions are in this order because `this.canPerformActionOnTarget` will check `this.canPerformAction` // unless flaged to be skipped. if(!settings.skipCanPerformActionOnTarget && !this.canPerformActionOnTarget(action, target, settings)){ return false; } else if(!settings.skipCanPerformAction && !this.canPerformAction(action, settings)){ return false; } var result; if(handler.performAction === true){ result = {}; } else { result = handler.performAction.call(this, target, settings); } if(result === false){ return false; } settings.result = result; var outcome = target.resolveAction(action, this, settings); if(outcome && handler.afterPerformActionSuccess){ handler.afterPerformActionSuccess.call(this, target, settings); } else if(!outcome && handler.afterPerformActionFailure){ handler.afterPerformActionFailure.call(this, target, settings); } return outcome; }
javascript
function(action, target, settings){ if(!this.performableActions){ return false; } var handler = this.performableActions[action]; if(!handler){ return false; } settings = settings || {}; // the functions are in this order because `this.canPerformActionOnTarget` will check `this.canPerformAction` // unless flaged to be skipped. if(!settings.skipCanPerformActionOnTarget && !this.canPerformActionOnTarget(action, target, settings)){ return false; } else if(!settings.skipCanPerformAction && !this.canPerformAction(action, settings)){ return false; } var result; if(handler.performAction === true){ result = {}; } else { result = handler.performAction.call(this, target, settings); } if(result === false){ return false; } settings.result = result; var outcome = target.resolveAction(action, this, settings); if(outcome && handler.afterPerformActionSuccess){ handler.afterPerformActionSuccess.call(this, target, settings); } else if(!outcome && handler.afterPerformActionFailure){ handler.afterPerformActionFailure.call(this, target, settings); } return outcome; }
[ "function", "(", "action", ",", "target", ",", "settings", ")", "{", "if", "(", "!", "this", ".", "performableActions", ")", "{", "return", "false", ";", "}", "var", "handler", "=", "this", ".", "performableActions", "[", "action", "]", ";", "if", "(", "!", "handler", ")", "{", "return", "false", ";", "}", "settings", "=", "settings", "||", "{", "}", ";", "// the functions are in this order because `this.canPerformActionOnTarget` will check `this.canPerformAction`", "// unless flaged to be skipped.", "if", "(", "!", "settings", ".", "skipCanPerformActionOnTarget", "&&", "!", "this", ".", "canPerformActionOnTarget", "(", "action", ",", "target", ",", "settings", ")", ")", "{", "return", "false", ";", "}", "else", "if", "(", "!", "settings", ".", "skipCanPerformAction", "&&", "!", "this", ".", "canPerformAction", "(", "action", ",", "settings", ")", ")", "{", "return", "false", ";", "}", "var", "result", ";", "if", "(", "handler", ".", "performAction", "===", "true", ")", "{", "result", "=", "{", "}", ";", "}", "else", "{", "result", "=", "handler", ".", "performAction", ".", "call", "(", "this", ",", "target", ",", "settings", ")", ";", "}", "if", "(", "result", "===", "false", ")", "{", "return", "false", ";", "}", "settings", ".", "result", "=", "result", ";", "var", "outcome", "=", "target", ".", "resolveAction", "(", "action", ",", "this", ",", "settings", ")", ";", "if", "(", "outcome", "&&", "handler", ".", "afterPerformActionSuccess", ")", "{", "handler", ".", "afterPerformActionSuccess", ".", "call", "(", "this", ",", "target", ",", "settings", ")", ";", "}", "else", "if", "(", "!", "outcome", "&&", "handler", ".", "afterPerformActionFailure", ")", "{", "handler", ".", "afterPerformActionFailure", ".", "call", "(", "this", ",", "target", ",", "settings", ")", ";", "}", "return", "outcome", ";", "}" ]
Performs an action on target with given settings. @method performAction @param {String} action - The action to perform. @param {Object} target - The target object to perform the action on. @param {Object} [settings] - Settings for the action. @param {Object} [settings.skipCanPerformAction] - If true skips checking that `this.canPerformAction(action, settings) == true` @param {Object} [settings.skipCanPerformActionOnTarget] - If true skips checking that `this.skipCanPerformActionOnTarget(action, target, settings) == true` @return {Boolean} `true` if the action has been successfully completed.
[ "Performs", "an", "action", "on", "target", "with", "given", "settings", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/mixins/action-interface.js#L130-L166
46,071
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/mixins/action-interface.js
function(action, implementation){ this.resolvableActions = this.resolvableActions || {}; this.resolvableActions[action] = this.resolvableActions[action] || {}; this.resolvableActions[action].actionName = this.resolvableActions[action].actionName || action; implementation = implementation || RL.ResolvableAction.Types[action]; this.resolvableActions[action] = Object.create(implementation); // merge could be used instead of Object.create but is less desirable // RL.Util.merge(this.resolvableAction.Types[action], implementation); if(this.resolvableActions[action].init){ this.resolvableActions[action].init.call(this); } }
javascript
function(action, implementation){ this.resolvableActions = this.resolvableActions || {}; this.resolvableActions[action] = this.resolvableActions[action] || {}; this.resolvableActions[action].actionName = this.resolvableActions[action].actionName || action; implementation = implementation || RL.ResolvableAction.Types[action]; this.resolvableActions[action] = Object.create(implementation); // merge could be used instead of Object.create but is less desirable // RL.Util.merge(this.resolvableAction.Types[action], implementation); if(this.resolvableActions[action].init){ this.resolvableActions[action].init.call(this); } }
[ "function", "(", "action", ",", "implementation", ")", "{", "this", ".", "resolvableActions", "=", "this", ".", "resolvableActions", "||", "{", "}", ";", "this", ".", "resolvableActions", "[", "action", "]", "=", "this", ".", "resolvableActions", "[", "action", "]", "||", "{", "}", ";", "this", ".", "resolvableActions", "[", "action", "]", ".", "actionName", "=", "this", ".", "resolvableActions", "[", "action", "]", ".", "actionName", "||", "action", ";", "implementation", "=", "implementation", "||", "RL", ".", "ResolvableAction", ".", "Types", "[", "action", "]", ";", "this", ".", "resolvableActions", "[", "action", "]", "=", "Object", ".", "create", "(", "implementation", ")", ";", "// merge could be used instead of Object.create but is less desirable", "// RL.Util.merge(this.resolvableAction.Types[action], implementation);", "if", "(", "this", ".", "resolvableActions", "[", "action", "]", ".", "init", ")", "{", "this", ".", "resolvableActions", "[", "action", "]", ".", "init", ".", "call", "(", "this", ")", ";", "}", "}" ]
Sets a resolvable action implementation on object. @method setResolvableAction @param {String} action - The action name. @param {ResolvableAction} [implementation] - Object to set as the action implementation.
[ "Sets", "a", "resolvable", "action", "implementation", "on", "object", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/mixins/action-interface.js#L184-L197
46,072
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/mixins/action-interface.js
function(action, source, settings){ if(!this.resolvableActions){ return false; } var handler = this.resolvableActions[action]; if(!handler){ return false; } if(handler.canResolveAction === false){ return false; } if(handler.canResolveAction === true){ return true; } return handler.canResolveAction.call(this, source, settings); }
javascript
function(action, source, settings){ if(!this.resolvableActions){ return false; } var handler = this.resolvableActions[action]; if(!handler){ return false; } if(handler.canResolveAction === false){ return false; } if(handler.canResolveAction === true){ return true; } return handler.canResolveAction.call(this, source, settings); }
[ "function", "(", "action", ",", "source", ",", "settings", ")", "{", "if", "(", "!", "this", ".", "resolvableActions", ")", "{", "return", "false", ";", "}", "var", "handler", "=", "this", ".", "resolvableActions", "[", "action", "]", ";", "if", "(", "!", "handler", ")", "{", "return", "false", ";", "}", "if", "(", "handler", ".", "canResolveAction", "===", "false", ")", "{", "return", "false", ";", "}", "if", "(", "handler", ".", "canResolveAction", "===", "true", ")", "{", "return", "true", ";", "}", "return", "handler", ".", "canResolveAction", ".", "call", "(", "this", ",", "source", ",", "settings", ")", ";", "}" ]
Checks if a target can resolve an action with given source and settings. `this` is the target. @method canResolveAction @param {String} action - The action being performed on this target to resolve. @param {Object} source - The source object performing the action on this target. @param {Object} [settings] - Settings for the action. @return {Boolean} `true` if action was successfully resolved
[ "Checks", "if", "a", "target", "can", "resolve", "an", "action", "with", "given", "source", "and", "settings", ".", "this", "is", "the", "target", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/mixins/action-interface.js#L207-L222
46,073
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/mixins/action-interface.js
function(action, source, settings){ if(!this.resolvableActions){ return false; } var handler = this.resolvableActions[action]; if(!handler){ return false; } settings = settings || {}; if(!settings.skipCanResolveAction && !this.canResolveAction(action, source, settings)){ return false; } if(handler.resolveAction === false){ return false; } if(handler.resolveAction === true){ return true; } return handler.resolveAction.call(this, source, settings); }
javascript
function(action, source, settings){ if(!this.resolvableActions){ return false; } var handler = this.resolvableActions[action]; if(!handler){ return false; } settings = settings || {}; if(!settings.skipCanResolveAction && !this.canResolveAction(action, source, settings)){ return false; } if(handler.resolveAction === false){ return false; } if(handler.resolveAction === true){ return true; } return handler.resolveAction.call(this, source, settings); }
[ "function", "(", "action", ",", "source", ",", "settings", ")", "{", "if", "(", "!", "this", ".", "resolvableActions", ")", "{", "return", "false", ";", "}", "var", "handler", "=", "this", ".", "resolvableActions", "[", "action", "]", ";", "if", "(", "!", "handler", ")", "{", "return", "false", ";", "}", "settings", "=", "settings", "||", "{", "}", ";", "if", "(", "!", "settings", ".", "skipCanResolveAction", "&&", "!", "this", ".", "canResolveAction", "(", "action", ",", "source", ",", "settings", ")", ")", "{", "return", "false", ";", "}", "if", "(", "handler", ".", "resolveAction", "===", "false", ")", "{", "return", "false", ";", "}", "if", "(", "handler", ".", "resolveAction", "===", "true", ")", "{", "return", "true", ";", "}", "return", "handler", ".", "resolveAction", ".", "call", "(", "this", ",", "source", ",", "settings", ")", ";", "}" ]
Resolves an action on target from source with given settings. @method performAction @param {String} action - The action being performed on this target to resolve. @param {Object} source - The source object performing the action on this target. @param {Object} [settings] - Settings for the action. @param {Object} [settings.skipCanResolveAction] - If true skips checking that `this.skipCanResolveAction(action, source, settings) == true` @return {Boolean} `true` if the action was successfully resolved.
[ "Resolves", "an", "action", "on", "target", "from", "source", "with", "given", "settings", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/mixins/action-interface.js#L233-L253
46,074
sematext/spm-agent-os
linuxAgent.js
function (metric) { var now = (new Date().getTime()).toFixed(0) var line = null if (metric.sct === 'OS' && /collectd/.test(metric.name)) { line = this.collectdFormatLine(metric) } else { if (metric.sct === 'OS') { // new OS metric format if (metric.filters instanceof Array) { line = util.format('%d\t%s\t%d\t%s\t%s', now, metric.name, metric.ts, formatArray(metric.filters), formatArray(metric.value)) } else { line = util.format('%d\t%s\t%d\t%s', now, metric.name, metric.ts, formatArray(metric.value)) } logger.log(line) } else { line = util.format('%d\t%s\t%d\t%s\t%s', now, (metric.type || this.defaultType) + '-' + metric.name, metric.ts, formatArray(metric.filters), formatArray(metric.value)) logger.log(line) } } return line }
javascript
function (metric) { var now = (new Date().getTime()).toFixed(0) var line = null if (metric.sct === 'OS' && /collectd/.test(metric.name)) { line = this.collectdFormatLine(metric) } else { if (metric.sct === 'OS') { // new OS metric format if (metric.filters instanceof Array) { line = util.format('%d\t%s\t%d\t%s\t%s', now, metric.name, metric.ts, formatArray(metric.filters), formatArray(metric.value)) } else { line = util.format('%d\t%s\t%d\t%s', now, metric.name, metric.ts, formatArray(metric.value)) } logger.log(line) } else { line = util.format('%d\t%s\t%d\t%s\t%s', now, (metric.type || this.defaultType) + '-' + metric.name, metric.ts, formatArray(metric.filters), formatArray(metric.value)) logger.log(line) } } return line }
[ "function", "(", "metric", ")", "{", "var", "now", "=", "(", "new", "Date", "(", ")", ".", "getTime", "(", ")", ")", ".", "toFixed", "(", "0", ")", "var", "line", "=", "null", "if", "(", "metric", ".", "sct", "===", "'OS'", "&&", "/", "collectd", "/", ".", "test", "(", "metric", ".", "name", ")", ")", "{", "line", "=", "this", ".", "collectdFormatLine", "(", "metric", ")", "}", "else", "{", "if", "(", "metric", ".", "sct", "===", "'OS'", ")", "{", "// new OS metric format", "if", "(", "metric", ".", "filters", "instanceof", "Array", ")", "{", "line", "=", "util", ".", "format", "(", "'%d\\t%s\\t%d\\t%s\\t%s'", ",", "now", ",", "metric", ".", "name", ",", "metric", ".", "ts", ",", "formatArray", "(", "metric", ".", "filters", ")", ",", "formatArray", "(", "metric", ".", "value", ")", ")", "}", "else", "{", "line", "=", "util", ".", "format", "(", "'%d\\t%s\\t%d\\t%s'", ",", "now", ",", "metric", ".", "name", ",", "metric", ".", "ts", ",", "formatArray", "(", "metric", ".", "value", ")", ")", "}", "logger", ".", "log", "(", "line", ")", "}", "else", "{", "line", "=", "util", ".", "format", "(", "'%d\\t%s\\t%d\\t%s\\t%s'", ",", "now", ",", "(", "metric", ".", "type", "||", "this", ".", "defaultType", ")", "+", "'-'", "+", "metric", ".", "name", ",", "metric", ".", "ts", ",", "formatArray", "(", "metric", ".", "filters", ")", ",", "formatArray", "(", "metric", ".", "value", ")", ")", "logger", ".", "log", "(", "line", ")", "}", "}", "return", "line", "}" ]
osnet 1457010656149 lo 0 0
[ "osnet", "1457010656149", "lo", "0", "0" ]
e3083f56b9d8542de29fc53679da8e8f4d1d4493
https://github.com/sematext/spm-agent-os/blob/e3083f56b9d8542de29fc53679da8e8f4d1d4493/linuxAgent.js#L49-L69
46,075
deepstreamIO/deepstream.io-service
src/daemon.js
monitor
function monitor() { if(!child.pid) { // If the number of periodic starts exceeds the max, kill the process if (starts >= options.maxRetries) { if ((Date.now() - startTime) > maxMilliseconds) { console.error( `Too many restarts within the last ${maxMilliseconds / 1000} seconds. Please check the script.` ) process.exit(1) } } setTimeout(() => { wait = wait * options.growPercentage attempts += 1; if (attempts > options.maxRestarts && options.maxRestarts >= 0){ console.error( `${options.name} will not be restarted because the maximum number of total restarts has been exceeded.` ) process.exit() } else { launch() } }, wait) } else { attempts = 0 wait = options.restartDelay * 1000 } }
javascript
function monitor() { if(!child.pid) { // If the number of periodic starts exceeds the max, kill the process if (starts >= options.maxRetries) { if ((Date.now() - startTime) > maxMilliseconds) { console.error( `Too many restarts within the last ${maxMilliseconds / 1000} seconds. Please check the script.` ) process.exit(1) } } setTimeout(() => { wait = wait * options.growPercentage attempts += 1; if (attempts > options.maxRestarts && options.maxRestarts >= 0){ console.error( `${options.name} will not be restarted because the maximum number of total restarts has been exceeded.` ) process.exit() } else { launch() } }, wait) } else { attempts = 0 wait = options.restartDelay * 1000 } }
[ "function", "monitor", "(", ")", "{", "if", "(", "!", "child", ".", "pid", ")", "{", "// If the number of periodic starts exceeds the max, kill the process", "if", "(", "starts", ">=", "options", ".", "maxRetries", ")", "{", "if", "(", "(", "Date", ".", "now", "(", ")", "-", "startTime", ")", ">", "maxMilliseconds", ")", "{", "console", ".", "error", "(", "`", "${", "maxMilliseconds", "/", "1000", "}", "`", ")", "process", ".", "exit", "(", "1", ")", "}", "}", "setTimeout", "(", "(", ")", "=>", "{", "wait", "=", "wait", "*", "options", ".", "growPercentage", "attempts", "+=", "1", ";", "if", "(", "attempts", ">", "options", ".", "maxRestarts", "&&", "options", ".", "maxRestarts", ">=", "0", ")", "{", "console", ".", "error", "(", "`", "${", "options", ".", "name", "}", "`", ")", "process", ".", "exit", "(", ")", "}", "else", "{", "launch", "(", ")", "}", "}", ",", "wait", ")", "}", "else", "{", "attempts", "=", "0", "wait", "=", "options", ".", "restartDelay", "*", "1000", "}", "}" ]
Monitor the process to make sure it is running
[ "Monitor", "the", "process", "to", "make", "sure", "it", "is", "running" ]
f0a4f482eb027cc503e86d7d6a298cfee03883e3
https://github.com/deepstreamIO/deepstream.io-service/blob/f0a4f482eb027cc503e86d7d6a298cfee03883e3/src/daemon.js#L16-L44
46,076
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/game.js
Game
function Game() { // un-populated instance of Array2d this.map = new RL.Map(this); this.entityManager = new RL.ObjectManager(this, RL.Entity); this.renderer = new RL.Renderer(this); this.console = new RL.Console(this); this.lighting = new RL.LightingROT(this); // player purposefully not added to entity manager (matter of preference) this.player = new RL.Player(this); // make sure "this" is this instance of Game when this.onKeyAction is called this.onKeyAction = this.onKeyAction.bind(this); this.onClick = this.onClick.bind(this); this.onHover = this.onHover.bind(this); this.input = new RL.Input(this.onKeyAction); this.mouse = new RL.Mouse(this.onClick, this.onHover); var el = this.renderer.canvas; this.mouse.startListening(el); }
javascript
function Game() { // un-populated instance of Array2d this.map = new RL.Map(this); this.entityManager = new RL.ObjectManager(this, RL.Entity); this.renderer = new RL.Renderer(this); this.console = new RL.Console(this); this.lighting = new RL.LightingROT(this); // player purposefully not added to entity manager (matter of preference) this.player = new RL.Player(this); // make sure "this" is this instance of Game when this.onKeyAction is called this.onKeyAction = this.onKeyAction.bind(this); this.onClick = this.onClick.bind(this); this.onHover = this.onHover.bind(this); this.input = new RL.Input(this.onKeyAction); this.mouse = new RL.Mouse(this.onClick, this.onHover); var el = this.renderer.canvas; this.mouse.startListening(el); }
[ "function", "Game", "(", ")", "{", "// un-populated instance of Array2d", "this", ".", "map", "=", "new", "RL", ".", "Map", "(", "this", ")", ";", "this", ".", "entityManager", "=", "new", "RL", ".", "ObjectManager", "(", "this", ",", "RL", ".", "Entity", ")", ";", "this", ".", "renderer", "=", "new", "RL", ".", "Renderer", "(", "this", ")", ";", "this", ".", "console", "=", "new", "RL", ".", "Console", "(", "this", ")", ";", "this", ".", "lighting", "=", "new", "RL", ".", "LightingROT", "(", "this", ")", ";", "// player purposefully not added to entity manager (matter of preference)", "this", ".", "player", "=", "new", "RL", ".", "Player", "(", "this", ")", ";", "// make sure \"this\" is this instance of Game when this.onKeyAction is called", "this", ".", "onKeyAction", "=", "this", ".", "onKeyAction", ".", "bind", "(", "this", ")", ";", "this", ".", "onClick", "=", "this", ".", "onClick", ".", "bind", "(", "this", ")", ";", "this", ".", "onHover", "=", "this", ".", "onHover", ".", "bind", "(", "this", ")", ";", "this", ".", "input", "=", "new", "RL", ".", "Input", "(", "this", ".", "onKeyAction", ")", ";", "this", ".", "mouse", "=", "new", "RL", ".", "Mouse", "(", "this", ".", "onClick", ",", "this", ".", "onHover", ")", ";", "var", "el", "=", "this", ".", "renderer", ".", "canvas", ";", "this", ".", "mouse", ".", "startListening", "(", "el", ")", ";", "}" ]
Container for all game objects. Handles updating the state of game objects each turn. Listens for player input to trigger and resolve new turns. @class Game @constructor
[ "Container", "for", "all", "game", "objects", ".", "Handles", "updating", "the", "state", "of", "game", "objects", "each", "turn", ".", "Listens", "for", "player", "input", "to", "trigger", "and", "resolve", "new", "turns", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/game.js#L11-L33
46,077
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/game.js
function(width, height){ this.map.setSize(width, height); this.player.fov.setSize(width, height); this.entityManager.setSize(width, height); this.lighting.setSize(width, height); }
javascript
function(width, height){ this.map.setSize(width, height); this.player.fov.setSize(width, height); this.entityManager.setSize(width, height); this.lighting.setSize(width, height); }
[ "function", "(", "width", ",", "height", ")", "{", "this", ".", "map", ".", "setSize", "(", "width", ",", "height", ")", ";", "this", ".", "player", ".", "fov", ".", "setSize", "(", "width", ",", "height", ")", ";", "this", ".", "entityManager", ".", "setSize", "(", "width", ",", "height", ")", ";", "this", ".", "lighting", ".", "setSize", "(", "width", ",", "height", ")", ";", "}" ]
Sets the size of the map resizing this.map and this.entityManager. @method setMapSize @param {Number} width - Width in tilse to set map and entityManager to. @param {Number} height - Height in tilse to set map and entityManager to.
[ "Sets", "the", "size", "of", "the", "map", "resizing", "this", ".", "map", "and", "this", ".", "entityManager", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/game.js#L115-L120
46,078
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/game.js
function(action) { if(!this.gameOver){ var result = this.player.update(action); if(result){ this.entityManager.update(this.player); this.player.updateFov(); this.lighting.update(); this.renderer.setCenter(this.player.x, this.player.y); this.renderer.draw(); } else if(this.queueDraw){ this.renderer.draw(); } } this.queueDraw = false; }
javascript
function(action) { if(!this.gameOver){ var result = this.player.update(action); if(result){ this.entityManager.update(this.player); this.player.updateFov(); this.lighting.update(); this.renderer.setCenter(this.player.x, this.player.y); this.renderer.draw(); } else if(this.queueDraw){ this.renderer.draw(); } } this.queueDraw = false; }
[ "function", "(", "action", ")", "{", "if", "(", "!", "this", ".", "gameOver", ")", "{", "var", "result", "=", "this", ".", "player", ".", "update", "(", "action", ")", ";", "if", "(", "result", ")", "{", "this", ".", "entityManager", ".", "update", "(", "this", ".", "player", ")", ";", "this", ".", "player", ".", "updateFov", "(", ")", ";", "this", ".", "lighting", ".", "update", "(", ")", ";", "this", ".", "renderer", ".", "setCenter", "(", "this", ".", "player", ".", "x", ",", "this", ".", "player", ".", "y", ")", ";", "this", ".", "renderer", ".", "draw", "(", ")", ";", "}", "else", "if", "(", "this", ".", "queueDraw", ")", "{", "this", ".", "renderer", ".", "draw", "(", ")", ";", "}", "}", "this", ".", "queueDraw", "=", "false", ";", "}" ]
Handles user input actions. @method onKeyAction @param {String} action - Action triggered by user input.
[ "Handles", "user", "input", "actions", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/game.js#L140-L157
46,079
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/game.js
function(x, y){ var coords = this.renderer.mouseToTileCoords(x, y), tile = this.map.get(coords.x, coords.y); if(!tile){ return; } var entityTile = this.entityManager.get(tile.x, tile.y); if(entityTile){ this.console.log('Looks like a <strong>' + entityTile.name + '</strong> standing on a <strong>' + tile.name + '</strong> to me.'); } else{ this.console.log('Looks like a <strong>' + tile.name + '</strong> to me.'); } }
javascript
function(x, y){ var coords = this.renderer.mouseToTileCoords(x, y), tile = this.map.get(coords.x, coords.y); if(!tile){ return; } var entityTile = this.entityManager.get(tile.x, tile.y); if(entityTile){ this.console.log('Looks like a <strong>' + entityTile.name + '</strong> standing on a <strong>' + tile.name + '</strong> to me.'); } else{ this.console.log('Looks like a <strong>' + tile.name + '</strong> to me.'); } }
[ "function", "(", "x", ",", "y", ")", "{", "var", "coords", "=", "this", ".", "renderer", ".", "mouseToTileCoords", "(", "x", ",", "y", ")", ",", "tile", "=", "this", ".", "map", ".", "get", "(", "coords", ".", "x", ",", "coords", ".", "y", ")", ";", "if", "(", "!", "tile", ")", "{", "return", ";", "}", "var", "entityTile", "=", "this", ".", "entityManager", ".", "get", "(", "tile", ".", "x", ",", "tile", ".", "y", ")", ";", "if", "(", "entityTile", ")", "{", "this", ".", "console", ".", "log", "(", "'Looks like a <strong>'", "+", "entityTile", ".", "name", "+", "'</strong> standing on a <strong>'", "+", "tile", ".", "name", "+", "'</strong> to me.'", ")", ";", "}", "else", "{", "this", ".", "console", ".", "log", "(", "'Looks like a <strong>'", "+", "tile", ".", "name", "+", "'</strong> to me.'", ")", ";", "}", "}" ]
Handles tile mouse click events. @method onClick @param {Number} x - Mouse x coord relative to window. @param {Number} y - Mouse y coord relative to window.
[ "Handles", "tile", "mouse", "click", "events", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/game.js#L165-L178
46,080
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/game.js
function(x, y){ var coords = this.renderer.mouseToTileCoords(x, y), tile = this.map.get(coords.x, coords.y); if(tile){ this.renderer.hoveredTileX = tile.x; this.renderer.hoveredTileY = tile.y; } else { this.renderer.hoveredTileX = null; this.renderer.hoveredTileY = null; } this.renderer.draw(); }
javascript
function(x, y){ var coords = this.renderer.mouseToTileCoords(x, y), tile = this.map.get(coords.x, coords.y); if(tile){ this.renderer.hoveredTileX = tile.x; this.renderer.hoveredTileY = tile.y; } else { this.renderer.hoveredTileX = null; this.renderer.hoveredTileY = null; } this.renderer.draw(); }
[ "function", "(", "x", ",", "y", ")", "{", "var", "coords", "=", "this", ".", "renderer", ".", "mouseToTileCoords", "(", "x", ",", "y", ")", ",", "tile", "=", "this", ".", "map", ".", "get", "(", "coords", ".", "x", ",", "coords", ".", "y", ")", ";", "if", "(", "tile", ")", "{", "this", ".", "renderer", ".", "hoveredTileX", "=", "tile", ".", "x", ";", "this", ".", "renderer", ".", "hoveredTileY", "=", "tile", ".", "y", ";", "}", "else", "{", "this", ".", "renderer", ".", "hoveredTileX", "=", "null", ";", "this", ".", "renderer", ".", "hoveredTileY", "=", "null", ";", "}", "this", ".", "renderer", ".", "draw", "(", ")", ";", "}" ]
Handles tile mouse hover events @method onHover @param {Number} x - Mouse x coord relative to window. @param {Number} y - Mouse y coord relative to window.
[ "Handles", "tile", "mouse", "hover", "events" ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/game.js#L186-L197
46,081
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/game.js
function(x, y){ var result = []; var entity = this.entityManager.get(x, y); if(entity){ result.push(entity); } // add items or any other objects that can be placed at a tile coord position return result; }
javascript
function(x, y){ var result = []; var entity = this.entityManager.get(x, y); if(entity){ result.push(entity); } // add items or any other objects that can be placed at a tile coord position return result; }
[ "function", "(", "x", ",", "y", ")", "{", "var", "result", "=", "[", "]", ";", "var", "entity", "=", "this", ".", "entityManager", ".", "get", "(", "x", ",", "y", ")", ";", "if", "(", "entity", ")", "{", "result", ".", "push", "(", "entity", ")", ";", "}", "// add items or any other objects that can be placed at a tile coord position", "return", "result", ";", "}" ]
Gets all objects at tile position @method getObjectsAtPostion @param {Number} x @param {Number} y @return {Array}
[ "Gets", "all", "objects", "at", "tile", "position" ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/game.js#L206-L217
46,082
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/game.js
function(entity, x, y){ var tile = this.map.get(x, y); // if tile blocks movement if(!tile || !tile.passable){ return false; } return true; }
javascript
function(entity, x, y){ var tile = this.map.get(x, y); // if tile blocks movement if(!tile || !tile.passable){ return false; } return true; }
[ "function", "(", "entity", ",", "x", ",", "y", ")", "{", "var", "tile", "=", "this", ".", "map", ".", "get", "(", "x", ",", "y", ")", ";", "// if tile blocks movement", "if", "(", "!", "tile", "||", "!", "tile", ".", "passable", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Checks if an entity can move through a map tile. This does NOT check for entities on the tile blocking movement. This is where code for special cases changing an entity's ability to pass through a tile should be placed. Things like flying, swimming and ghosts moving through walls. @method entityCanMoveThrough @param {Entity} entity - The entity to check. @param {Number} x - The x map tile coord to check. @param {Number} y - The y map tile coord to check. @return {Bool}
[ "Checks", "if", "an", "entity", "can", "move", "through", "a", "map", "tile", ".", "This", "does", "NOT", "check", "for", "entities", "on", "the", "tile", "blocking", "movement", ".", "This", "is", "where", "code", "for", "special", "cases", "changing", "an", "entity", "s", "ability", "to", "pass", "through", "a", "tile", "should", "be", "placed", ".", "Things", "like", "flying", "swimming", "and", "ghosts", "moving", "through", "walls", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/game.js#L230-L237
46,083
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/game.js
function(entity, x, y){ if(!this.entityCanMoveThrough(entity, x, y)){ return false; } // check if occupied by entity if(this.entityManager.get(x, y)){ return false; } return true; }
javascript
function(entity, x, y){ if(!this.entityCanMoveThrough(entity, x, y)){ return false; } // check if occupied by entity if(this.entityManager.get(x, y)){ return false; } return true; }
[ "function", "(", "entity", ",", "x", ",", "y", ")", "{", "if", "(", "!", "this", ".", "entityCanMoveThrough", "(", "entity", ",", "x", ",", "y", ")", ")", "{", "return", "false", ";", "}", "// check if occupied by entity", "if", "(", "this", ".", "entityManager", ".", "get", "(", "x", ",", "y", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Checks if an entity can move through and into a map tile and that tile is un-occupied. @method entityCanMoveTo @param {Entity} entity - The entity to check. @param {Number} x - The x map tile coord to check. @param {Number} y - The y map tile coord to check. @return {Bool}
[ "Checks", "if", "an", "entity", "can", "move", "through", "and", "into", "a", "map", "tile", "and", "that", "tile", "is", "un", "-", "occupied", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/game.js#L247-L256
46,084
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/game.js
function(entity, x, y){ var tile = this.map.get(x, y); return tile && !tile.blocksLos; }
javascript
function(entity, x, y){ var tile = this.map.get(x, y); return tile && !tile.blocksLos; }
[ "function", "(", "entity", ",", "x", ",", "y", ")", "{", "var", "tile", "=", "this", ".", "map", ".", "get", "(", "x", ",", "y", ")", ";", "return", "tile", "&&", "!", "tile", ".", "blocksLos", ";", "}" ]
Checks if a map tile can be seen through. This is where code for special cases like smoke, fog, x-ray vision can be implemented by checking the entity param. @method entityCanSeeThrough @param {Number} x - The x map tile coord to check. @param {Number} y - The y map tile coord to check. @return {Bool}
[ "Checks", "if", "a", "map", "tile", "can", "be", "seen", "through", ".", "This", "is", "where", "code", "for", "special", "cases", "like", "smoke", "fog", "x", "-", "ray", "vision", "can", "be", "implemented", "by", "checking", "the", "entity", "param", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/game.js#L283-L286
46,085
alexandrudima/typescript-with-globs
lib/tscg.js
handleRecipeFiles
function handleRecipeFiles(folderPath) { if (handled[folderPath]) { return; } handled[folderPath] = true; handleRecipeFile(path.join(folderPath, 'tsconfig.json')); handleRecipeFiles(path.dirname(folderPath)); }
javascript
function handleRecipeFiles(folderPath) { if (handled[folderPath]) { return; } handled[folderPath] = true; handleRecipeFile(path.join(folderPath, 'tsconfig.json')); handleRecipeFiles(path.dirname(folderPath)); }
[ "function", "handleRecipeFiles", "(", "folderPath", ")", "{", "if", "(", "handled", "[", "folderPath", "]", ")", "{", "return", ";", "}", "handled", "[", "folderPath", "]", "=", "true", ";", "handleRecipeFile", "(", "path", ".", "join", "(", "folderPath", ",", "'tsconfig.json'", ")", ")", ";", "handleRecipeFiles", "(", "path", ".", "dirname", "(", "folderPath", ")", ")", ";", "}" ]
Walk up all folders and discover `tsconfig.json` files.
[ "Walk", "up", "all", "folders", "and", "discover", "tsconfig", ".", "json", "files", "." ]
ac63cf7a20f75626aee7c817a31af7e14a4e3603
https://github.com/alexandrudima/typescript-with-globs/blob/ac63cf7a20f75626aee7c817a31af7e14a4e3603/lib/tscg.js#L11-L19
46,086
alexandrudima/typescript-with-globs
lib/tscg.js
handleRecipeFile
function handleRecipeFile(recipePath) { var contents = null; try { contents = fs.readFileSync(recipePath); } catch (err) { // Not finding a recipe is OK return; } var config = null; try { config = JSON.parse(contents.toString()); } catch (err) { // Finding a recipe that cannot be parsed is a disaster console.log('Error in parsing JSON for ' + recipePath); process.exit(-1); } // Determine the glob patterns var filesGlob = ['**/*.ts']; if (typeof config.filesGlob === 'string') { filesGlob = [config.filesGlob]; } else if (Array.isArray(config.filesGlob)) { filesGlob = config.filesGlob; } var resultConfig = {}; for (var prop in config) { resultConfig[prop] = config[prop]; } resultConfig.files = findFiles(recipePath, filesGlob); var resultTxt = JSON.stringify(resultConfig, null, ' '); var resultPath = path.join(path.dirname(recipePath), 'tsconfig.json'); fs.writeFileSync(resultPath, resultTxt); console.log('Updated ' + resultPath); }
javascript
function handleRecipeFile(recipePath) { var contents = null; try { contents = fs.readFileSync(recipePath); } catch (err) { // Not finding a recipe is OK return; } var config = null; try { config = JSON.parse(contents.toString()); } catch (err) { // Finding a recipe that cannot be parsed is a disaster console.log('Error in parsing JSON for ' + recipePath); process.exit(-1); } // Determine the glob patterns var filesGlob = ['**/*.ts']; if (typeof config.filesGlob === 'string') { filesGlob = [config.filesGlob]; } else if (Array.isArray(config.filesGlob)) { filesGlob = config.filesGlob; } var resultConfig = {}; for (var prop in config) { resultConfig[prop] = config[prop]; } resultConfig.files = findFiles(recipePath, filesGlob); var resultTxt = JSON.stringify(resultConfig, null, ' '); var resultPath = path.join(path.dirname(recipePath), 'tsconfig.json'); fs.writeFileSync(resultPath, resultTxt); console.log('Updated ' + resultPath); }
[ "function", "handleRecipeFile", "(", "recipePath", ")", "{", "var", "contents", "=", "null", ";", "try", "{", "contents", "=", "fs", ".", "readFileSync", "(", "recipePath", ")", ";", "}", "catch", "(", "err", ")", "{", "// Not finding a recipe is OK\r", "return", ";", "}", "var", "config", "=", "null", ";", "try", "{", "config", "=", "JSON", ".", "parse", "(", "contents", ".", "toString", "(", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "// Finding a recipe that cannot be parsed is a disaster\r", "console", ".", "log", "(", "'Error in parsing JSON for '", "+", "recipePath", ")", ";", "process", ".", "exit", "(", "-", "1", ")", ";", "}", "// Determine the glob patterns\r", "var", "filesGlob", "=", "[", "'**/*.ts'", "]", ";", "if", "(", "typeof", "config", ".", "filesGlob", "===", "'string'", ")", "{", "filesGlob", "=", "[", "config", ".", "filesGlob", "]", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "config", ".", "filesGlob", ")", ")", "{", "filesGlob", "=", "config", ".", "filesGlob", ";", "}", "var", "resultConfig", "=", "{", "}", ";", "for", "(", "var", "prop", "in", "config", ")", "{", "resultConfig", "[", "prop", "]", "=", "config", "[", "prop", "]", ";", "}", "resultConfig", ".", "files", "=", "findFiles", "(", "recipePath", ",", "filesGlob", ")", ";", "var", "resultTxt", "=", "JSON", ".", "stringify", "(", "resultConfig", ",", "null", ",", "' '", ")", ";", "var", "resultPath", "=", "path", ".", "join", "(", "path", ".", "dirname", "(", "recipePath", ")", ",", "'tsconfig.json'", ")", ";", "fs", ".", "writeFileSync", "(", "resultPath", ",", "resultTxt", ")", ";", "console", ".", "log", "(", "'Updated '", "+", "resultPath", ")", ";", "}" ]
Given a recipe is found at `recipePath`, create a `tsconfig.json` sibling file with the glob resolved.
[ "Given", "a", "recipe", "is", "found", "at", "recipePath", "create", "a", "tsconfig", ".", "json", "sibling", "file", "with", "the", "glob", "resolved", "." ]
ac63cf7a20f75626aee7c817a31af7e14a4e3603
https://github.com/alexandrudima/typescript-with-globs/blob/ac63cf7a20f75626aee7c817a31af7e14a4e3603/lib/tscg.js#L24-L60
46,087
commenthol/debug-level
src/middleware.js
middleware
function middleware (opts) { opts = Object.assign({maxSize: 100, logAll: false}, opts) const log = opts.logAll ? new CustomLog() : void (0) const loggers = new Loggers(opts.maxSize) return function (req, res) { let query = req.query if (!req.query) { query = qsParse(urlParse(req.url).query) } res.setHeader('Cache-Control', 'no-store, no-cache') res.write(gif) res.end() const str = query.log if (!str) return if (/^{.*?}\s*$/.test(str)) { // check if `str` looks like JSON try { const obj = JSON.parse(str) const level = adjustLevel(String(obj.level), DEBUG) const name = String(obj.name).substr(0, 50) if (obj.name && name) { const l = loggers.get(name) if (l.enabled[level]) { if (req.ip) obj.ip = req.ip delete obj.name delete obj.level l._log(level, [obj]) } return } } catch (e) {} } log && log.log(str) } }
javascript
function middleware (opts) { opts = Object.assign({maxSize: 100, logAll: false}, opts) const log = opts.logAll ? new CustomLog() : void (0) const loggers = new Loggers(opts.maxSize) return function (req, res) { let query = req.query if (!req.query) { query = qsParse(urlParse(req.url).query) } res.setHeader('Cache-Control', 'no-store, no-cache') res.write(gif) res.end() const str = query.log if (!str) return if (/^{.*?}\s*$/.test(str)) { // check if `str` looks like JSON try { const obj = JSON.parse(str) const level = adjustLevel(String(obj.level), DEBUG) const name = String(obj.name).substr(0, 50) if (obj.name && name) { const l = loggers.get(name) if (l.enabled[level]) { if (req.ip) obj.ip = req.ip delete obj.name delete obj.level l._log(level, [obj]) } return } } catch (e) {} } log && log.log(str) } }
[ "function", "middleware", "(", "opts", ")", "{", "opts", "=", "Object", ".", "assign", "(", "{", "maxSize", ":", "100", ",", "logAll", ":", "false", "}", ",", "opts", ")", "const", "log", "=", "opts", ".", "logAll", "?", "new", "CustomLog", "(", ")", ":", "void", "(", "0", ")", "const", "loggers", "=", "new", "Loggers", "(", "opts", ".", "maxSize", ")", "return", "function", "(", "req", ",", "res", ")", "{", "let", "query", "=", "req", ".", "query", "if", "(", "!", "req", ".", "query", ")", "{", "query", "=", "qsParse", "(", "urlParse", "(", "req", ".", "url", ")", ".", "query", ")", "}", "res", ".", "setHeader", "(", "'Cache-Control'", ",", "'no-store, no-cache'", ")", "res", ".", "write", "(", "gif", ")", "res", ".", "end", "(", ")", "const", "str", "=", "query", ".", "log", "if", "(", "!", "str", ")", "return", "if", "(", "/", "^{.*?}\\s*$", "/", ".", "test", "(", "str", ")", ")", "{", "// check if `str` looks like JSON", "try", "{", "const", "obj", "=", "JSON", ".", "parse", "(", "str", ")", "const", "level", "=", "adjustLevel", "(", "String", "(", "obj", ".", "level", ")", ",", "DEBUG", ")", "const", "name", "=", "String", "(", "obj", ".", "name", ")", ".", "substr", "(", "0", ",", "50", ")", "if", "(", "obj", ".", "name", "&&", "name", ")", "{", "const", "l", "=", "loggers", ".", "get", "(", "name", ")", "if", "(", "l", ".", "enabled", "[", "level", "]", ")", "{", "if", "(", "req", ".", "ip", ")", "obj", ".", "ip", "=", "req", ".", "ip", "delete", "obj", ".", "name", "delete", "obj", ".", "level", "l", ".", "_log", "(", "level", ",", "[", "obj", "]", ")", "}", "return", "}", "}", "catch", "(", "e", ")", "{", "}", "}", "log", "&&", "log", ".", "log", "(", "str", ")", "}", "}" ]
connect middleware which logs browser based logs on server side sends a transparent gif as response @param {Object} [opts] @param {Object} [opts.maxSize=100] - max number of different name loggers @param {Object} [opts.logAll=false] - log everything even strings @return {function} connect middleware
[ "connect", "middleware", "which", "logs", "browser", "based", "logs", "on", "server", "side", "sends", "a", "transparent", "gif", "as", "response" ]
e310fe5452984d898adfb8f924ac6f9021b05457
https://github.com/commenthol/debug-level/blob/e310fe5452984d898adfb8f924ac6f9021b05457/src/middleware.js#L44-L81
46,088
nickzuber/needle
src/RollingHash/rollingHash.js
function(base){ if(typeof base === 'undefined'){ throw new Error("Too few arguments in RollingHash constructor"); }else if(typeof base !== 'number'){ throw new TypeError("Invalid argument; expected a number in RollingHash constructor"); } // The base of the number system this.BASE = base; // The internal hash value of the window this.state = 0; // A block of expensive code we will cache in order to optimize runtime this.CACHE = 1; // The amount of digits a number can hold given the base // TODO: unused.. figure out why I thought I needed this this.BUFFER_SIZE = Math.log(base) * Math.LOG10E + 1 | 0; // The modular inverse of the base this.INVERSE_BASE = modInverse(this.BASE, PRIME_BASE) % PRIME_BASE; // An offset to add when calculating a modular product, to make sure it can not go negative this.OFFSET_IF_NEGATIVE = PRIME_BASE * this.BASE; }
javascript
function(base){ if(typeof base === 'undefined'){ throw new Error("Too few arguments in RollingHash constructor"); }else if(typeof base !== 'number'){ throw new TypeError("Invalid argument; expected a number in RollingHash constructor"); } // The base of the number system this.BASE = base; // The internal hash value of the window this.state = 0; // A block of expensive code we will cache in order to optimize runtime this.CACHE = 1; // The amount of digits a number can hold given the base // TODO: unused.. figure out why I thought I needed this this.BUFFER_SIZE = Math.log(base) * Math.LOG10E + 1 | 0; // The modular inverse of the base this.INVERSE_BASE = modInverse(this.BASE, PRIME_BASE) % PRIME_BASE; // An offset to add when calculating a modular product, to make sure it can not go negative this.OFFSET_IF_NEGATIVE = PRIME_BASE * this.BASE; }
[ "function", "(", "base", ")", "{", "if", "(", "typeof", "base", "===", "'undefined'", ")", "{", "throw", "new", "Error", "(", "\"Too few arguments in RollingHash constructor\"", ")", ";", "}", "else", "if", "(", "typeof", "base", "!==", "'number'", ")", "{", "throw", "new", "TypeError", "(", "\"Invalid argument; expected a number in RollingHash constructor\"", ")", ";", "}", "// The base of the number system", "this", ".", "BASE", "=", "base", ";", "// The internal hash value of the window", "this", ".", "state", "=", "0", ";", "// A block of expensive code we will cache in order to optimize runtime", "this", ".", "CACHE", "=", "1", ";", "// The amount of digits a number can hold given the base", "// TODO: unused.. figure out why I thought I needed this", "this", ".", "BUFFER_SIZE", "=", "Math", ".", "log", "(", "base", ")", "*", "Math", ".", "LOG10E", "+", "1", "|", "0", ";", "// The modular inverse of the base", "this", ".", "INVERSE_BASE", "=", "modInverse", "(", "this", ".", "BASE", ",", "PRIME_BASE", ")", "%", "PRIME_BASE", ";", "// An offset to add when calculating a modular product, to make sure it can not go negative", "this", ".", "OFFSET_IF_NEGATIVE", "=", "PRIME_BASE", "*", "this", ".", "BASE", ";", "}" ]
Single argument constructor which defines the base of the working @param {number} the base value of the rolling hash to compute its operations @return {void}
[ "Single", "argument", "constructor", "which", "defines", "the", "base", "of", "the", "working" ]
9565b3c193b93d67ffed39d430eba395a7bb5531
https://github.com/nickzuber/needle/blob/9565b3c193b93d67ffed39d430eba395a7bb5531/src/RollingHash/rollingHash.js#L85-L110
46,089
loverly/lexerific
lib/Lexerific.js
Lexerific
function Lexerific(config, _, FSM, Lexeme, StateGenerator, Token, TreeNode) { var _this = this; this._ = _; // Create a finite state machine for lexing this.fsm = new FSM({ name: 'lexerific', debug: true, resetAtRoot: true // erase history for every root bound transition }); this.fsm.on('return', function (data) { _this.push(data.toObject()); }); this.Lexeme = Lexeme; this.Token = Token; this.stateGenerator = new StateGenerator(this._, this.Token, TreeNode); /** * Either 'string' or 'token' to determine what type of input stream to expect */ this._mode = config.mode; /** * In `string` mode, we need a list of regular expression patterns (as strings) * to differentiate between text that is important in our lexicon and text * that is not. */ this._specialCharacters = config.specialCharacters; /** * Indicates whether the FSM has been initialized with all of the states */ this._isReady = false; // We always read and write token objects TransformStream.call(this, { objectMode: true, readableObjectMode: true, writableObjectMode: true }); }
javascript
function Lexerific(config, _, FSM, Lexeme, StateGenerator, Token, TreeNode) { var _this = this; this._ = _; // Create a finite state machine for lexing this.fsm = new FSM({ name: 'lexerific', debug: true, resetAtRoot: true // erase history for every root bound transition }); this.fsm.on('return', function (data) { _this.push(data.toObject()); }); this.Lexeme = Lexeme; this.Token = Token; this.stateGenerator = new StateGenerator(this._, this.Token, TreeNode); /** * Either 'string' or 'token' to determine what type of input stream to expect */ this._mode = config.mode; /** * In `string` mode, we need a list of regular expression patterns (as strings) * to differentiate between text that is important in our lexicon and text * that is not. */ this._specialCharacters = config.specialCharacters; /** * Indicates whether the FSM has been initialized with all of the states */ this._isReady = false; // We always read and write token objects TransformStream.call(this, { objectMode: true, readableObjectMode: true, writableObjectMode: true }); }
[ "function", "Lexerific", "(", "config", ",", "_", ",", "FSM", ",", "Lexeme", ",", "StateGenerator", ",", "Token", ",", "TreeNode", ")", "{", "var", "_this", "=", "this", ";", "this", ".", "_", "=", "_", ";", "// Create a finite state machine for lexing", "this", ".", "fsm", "=", "new", "FSM", "(", "{", "name", ":", "'lexerific'", ",", "debug", ":", "true", ",", "resetAtRoot", ":", "true", "// erase history for every root bound transition", "}", ")", ";", "this", ".", "fsm", ".", "on", "(", "'return'", ",", "function", "(", "data", ")", "{", "_this", ".", "push", "(", "data", ".", "toObject", "(", ")", ")", ";", "}", ")", ";", "this", ".", "Lexeme", "=", "Lexeme", ";", "this", ".", "Token", "=", "Token", ";", "this", ".", "stateGenerator", "=", "new", "StateGenerator", "(", "this", ".", "_", ",", "this", ".", "Token", ",", "TreeNode", ")", ";", "/**\n * Either 'string' or 'token' to determine what type of input stream to expect\n */", "this", ".", "_mode", "=", "config", ".", "mode", ";", "/**\n * In `string` mode, we need a list of regular expression patterns (as strings)\n * to differentiate between text that is important in our lexicon and text\n * that is not.\n */", "this", ".", "_specialCharacters", "=", "config", ".", "specialCharacters", ";", "/**\n * Indicates whether the FSM has been initialized with all of the states\n */", "this", ".", "_isReady", "=", "false", ";", "// We always read and write token objects", "TransformStream", ".", "call", "(", "this", ",", "{", "objectMode", ":", "true", ",", "readableObjectMode", ":", "true", ",", "writableObjectMode", ":", "true", "}", ")", ";", "}" ]
The Lexerific library extends the Transform stream class. Depending on the mode it either takes in buffers as input or a stream of token objects. Configuration options: * `mode` - Either `string` or `token` depending on what type of input should be consumed. `token` mode is for secondary scanning passes In `string` mode, there is an extra pre-processing step to divide the raw strings into special characters and just plain text.
[ "The", "Lexerific", "library", "extends", "the", "Transform", "stream", "class", ".", "Depending", "on", "the", "mode", "it", "either", "takes", "in", "buffers", "as", "input", "or", "a", "stream", "of", "token", "objects", "." ]
ba10e4fdadd0d627a57b1997044d6f7b0282b862
https://github.com/loverly/lexerific/blob/ba10e4fdadd0d627a57b1997044d6f7b0282b862/lib/Lexerific.js#L17-L59
46,090
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/mixins.js
function() { return { char: this.char, color: this.color, bgColor: this.bgColor, borderColor: this.borderColor, borderWidth: this.borderWidth, charStrokeColor: this.charStrokeColor, charStrokeWidth: this.charStrokeWidth, font: this.font, fontSize: this.fontSize, textAlign: this.textAlign, textBaseline: this.textBaseline, offsetX: this.offsetX, offsetY: this.offsetY, }; }
javascript
function() { return { char: this.char, color: this.color, bgColor: this.bgColor, borderColor: this.borderColor, borderWidth: this.borderWidth, charStrokeColor: this.charStrokeColor, charStrokeWidth: this.charStrokeWidth, font: this.font, fontSize: this.fontSize, textAlign: this.textAlign, textBaseline: this.textBaseline, offsetX: this.offsetX, offsetY: this.offsetY, }; }
[ "function", "(", ")", "{", "return", "{", "char", ":", "this", ".", "char", ",", "color", ":", "this", ".", "color", ",", "bgColor", ":", "this", ".", "bgColor", ",", "borderColor", ":", "this", ".", "borderColor", ",", "borderWidth", ":", "this", ".", "borderWidth", ",", "charStrokeColor", ":", "this", ".", "charStrokeColor", ",", "charStrokeWidth", ":", "this", ".", "charStrokeWidth", ",", "font", ":", "this", ".", "font", ",", "fontSize", ":", "this", ".", "fontSize", ",", "textAlign", ":", "this", ".", "textAlign", ",", "textBaseline", ":", "this", ".", "textBaseline", ",", "offsetX", ":", "this", ".", "offsetX", ",", "offsetY", ":", "this", ".", "offsetY", ",", "}", ";", "}" ]
Returns as `tileData`object used by `Renderer` objects to draw tiles. @method getTileDrawData @return {TileDrawData}
[ "Returns", "as", "tileData", "object", "used", "by", "Renderer", "objects", "to", "draw", "tiles", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/mixins.js#L27-L43
46,091
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/util.js
function(defaults, settings) { var out = {}; for (var key in defaults) { if (key in settings) { out[key] = settings[key]; } else { out[key] = defaults[key]; } } return out; }
javascript
function(defaults, settings) { var out = {}; for (var key in defaults) { if (key in settings) { out[key] = settings[key]; } else { out[key] = defaults[key]; } } return out; }
[ "function", "(", "defaults", ",", "settings", ")", "{", "var", "out", "=", "{", "}", ";", "for", "(", "var", "key", "in", "defaults", ")", "{", "if", "(", "key", "in", "settings", ")", "{", "out", "[", "key", "]", "=", "settings", "[", "key", "]", ";", "}", "else", "{", "out", "[", "key", "]", "=", "defaults", "[", "key", "]", ";", "}", "}", "return", "out", ";", "}" ]
Merges settings with default values. @method mergeDefaults @static @param {Object} defaults - Default values to merge with. @param {Object} settings - Settings to merge with default values. @return {Object} A new object with settings replacing defaults.
[ "Merges", "settings", "with", "default", "values", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/util.js#L137-L147
46,092
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/util.js
function(destination){ var sources = Array.prototype.slice.call(arguments, 1); for (var i = 0; i < sources.length; i++) { var source = sources[i]; for(var key in source){ destination[key] = source[key]; } } return destination; }
javascript
function(destination){ var sources = Array.prototype.slice.call(arguments, 1); for (var i = 0; i < sources.length; i++) { var source = sources[i]; for(var key in source){ destination[key] = source[key]; } } return destination; }
[ "function", "(", "destination", ")", "{", "var", "sources", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "sources", ".", "length", ";", "i", "++", ")", "{", "var", "source", "=", "sources", "[", "i", "]", ";", "for", "(", "var", "key", "in", "source", ")", "{", "destination", "[", "key", "]", "=", "source", "[", "key", "]", ";", "}", "}", "return", "destination", ";", "}" ]
Copy all of the properties in the source objects over to the destination object, and return the destination object. It's in-order, so the last source will override properties of the same name in previous arguments. @method merge @static @param {Object} destination - The object to copy properties to. @param {Object} source* - The object to copy properties from. @return {Object} The `destination` object.
[ "Copy", "all", "of", "the", "properties", "in", "the", "source", "objects", "over", "to", "the", "destination", "object", "and", "return", "the", "destination", "object", ".", "It", "s", "in", "-", "order", "so", "the", "last", "source", "will", "override", "properties", "of", "the", "same", "name", "in", "previous", "arguments", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/util.js#L158-L167
46,093
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/util.js
function(x1, y1, x2, y2, diagonalMovement){ if(!diagonalMovement){ return Math.abs(x2 - x1) + Math.abs(y2 - y1); } else { return Math.max(Math.abs(x2 - x1), Math.abs(y2 - y1)); } }
javascript
function(x1, y1, x2, y2, diagonalMovement){ if(!diagonalMovement){ return Math.abs(x2 - x1) + Math.abs(y2 - y1); } else { return Math.max(Math.abs(x2 - x1), Math.abs(y2 - y1)); } }
[ "function", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "diagonalMovement", ")", "{", "if", "(", "!", "diagonalMovement", ")", "{", "return", "Math", ".", "abs", "(", "x2", "-", "x1", ")", "+", "Math", ".", "abs", "(", "y2", "-", "y1", ")", ";", "}", "else", "{", "return", "Math", ".", "max", "(", "Math", ".", "abs", "(", "x2", "-", "x1", ")", ",", "Math", ".", "abs", "(", "y2", "-", "y1", ")", ")", ";", "}", "}" ]
Gets the distance in tile moves from point 1 to point 2. @method getTileMoveDistance @param {Number} x1 @param {Number} y1 @param {Number} x2 @param {Number} y2 @param {Bool} [diagonalMovement=false]if true, calculate the distance taking into account diagonal movement. @return {Number}
[ "Gets", "the", "distance", "in", "tile", "moves", "from", "point", "1", "to", "point", "2", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/util.js#L193-L199
46,094
soliton4/promiseland
promiseland.js
function(jsStr, __parObj){ if (!__parObj){ return eval(jsStr); }; var s = ""; var n; for (n in __parObj){ s += "var " + n + " = __parObj." + n + ";"; }; //s = "(function(){" + s; s += jsStr; //s += "})();"; return eval(s); }
javascript
function(jsStr, __parObj){ if (!__parObj){ return eval(jsStr); }; var s = ""; var n; for (n in __parObj){ s += "var " + n + " = __parObj." + n + ";"; }; //s = "(function(){" + s; s += jsStr; //s += "})();"; return eval(s); }
[ "function", "(", "jsStr", ",", "__parObj", ")", "{", "if", "(", "!", "__parObj", ")", "{", "return", "eval", "(", "jsStr", ")", ";", "}", ";", "var", "s", "=", "\"\"", ";", "var", "n", ";", "for", "(", "n", "in", "__parObj", ")", "{", "s", "+=", "\"var \"", "+", "n", "+", "\" = __parObj.\"", "+", "n", "+", "\";\"", ";", "}", ";", "//s = \"(function(){\" + s;", "s", "+=", "jsStr", ";", "//s += \"})();\";", "return", "eval", "(", "s", ")", ";", "}" ]
eval this is here because its pure javascript
[ "eval", "this", "is", "here", "because", "its", "pure", "javascript" ]
27ccbe9cabbfa4b36fb0395dbcc5d30470f2ba89
https://github.com/soliton4/promiseland/blob/27ccbe9cabbfa4b36fb0395dbcc5d30470f2ba89/promiseland.js#L40-L56
46,095
vmgltd/hlr-lookup-api-nodejs-sdk
src/lib/node-hlr-client.js
HlrLookupClient
function HlrLookupClient(username, password, noSsl) { this.username = username; this.password = password; this.url = (noSsl ? 'http' : 'https') + '://www.hlr-lookups.com/api'; }
javascript
function HlrLookupClient(username, password, noSsl) { this.username = username; this.password = password; this.url = (noSsl ? 'http' : 'https') + '://www.hlr-lookups.com/api'; }
[ "function", "HlrLookupClient", "(", "username", ",", "password", ",", "noSsl", ")", "{", "this", ".", "username", "=", "username", ";", "this", ".", "password", "=", "password", ";", "this", ".", "url", "=", "(", "noSsl", "?", "'http'", ":", "'https'", ")", "+", "'://www.hlr-lookups.com/api'", ";", "}" ]
Initializes the HLR Lookup Client @param username - www.hlr-lookups.com username @param password - www.hlr-lookups.com password @param noSsl - set to true to disable SSL @constructor
[ "Initializes", "the", "HLR", "Lookup", "Client" ]
d36bb40152622b5854b05ef90a6a5748045af408
https://github.com/vmgltd/hlr-lookup-api-nodejs-sdk/blob/d36bb40152622b5854b05ef90a6a5748045af408/src/lib/node-hlr-client.js#L13-L19
46,096
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/renderer-layer.js
RendererLayer
function RendererLayer(game, type, settings) { this.game = game; this.type = type; var typeData = RendererLayer.Types[type]; RL.Util.merge(this, typeData); for(var key in settings){ if(this[key] !== void 0){ this[key] = settings[key]; } } }
javascript
function RendererLayer(game, type, settings) { this.game = game; this.type = type; var typeData = RendererLayer.Types[type]; RL.Util.merge(this, typeData); for(var key in settings){ if(this[key] !== void 0){ this[key] = settings[key]; } } }
[ "function", "RendererLayer", "(", "game", ",", "type", ",", "settings", ")", "{", "this", ".", "game", "=", "game", ";", "this", ".", "type", "=", "type", ";", "var", "typeData", "=", "RendererLayer", ".", "Types", "[", "type", "]", ";", "RL", ".", "Util", ".", "merge", "(", "this", ",", "typeData", ")", ";", "for", "(", "var", "key", "in", "settings", ")", "{", "if", "(", "this", "[", "key", "]", "!==", "void", "0", ")", "{", "this", "[", "key", "]", "=", "settings", "[", "key", "]", ";", "}", "}", "}" ]
Represents a map tile layer to be rendered. @class RendererLayer @constructor @param {Game} game - Game instance this obj is attached to. @param {String} type - Type of `RendererLayer`. When created this object is merged with the value of `RendererLayer.Types[type]`.
[ "Represents", "a", "map", "tile", "layer", "to", "be", "rendered", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/renderer-layer.js#L11-L22
46,097
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/renderer-layer.js
function(x, y, prevTileData){ var tileData = this.getTileData(x, y, prevTileData); if(this.mergeWithPrevLayer && prevTileData){ return this.mergeTileData(prevTileData, tileData); } return tileData; }
javascript
function(x, y, prevTileData){ var tileData = this.getTileData(x, y, prevTileData); if(this.mergeWithPrevLayer && prevTileData){ return this.mergeTileData(prevTileData, tileData); } return tileData; }
[ "function", "(", "x", ",", "y", ",", "prevTileData", ")", "{", "var", "tileData", "=", "this", ".", "getTileData", "(", "x", ",", "y", ",", "prevTileData", ")", ";", "if", "(", "this", ".", "mergeWithPrevLayer", "&&", "prevTileData", ")", "{", "return", "this", ".", "mergeTileData", "(", "prevTileData", ",", "tileData", ")", ";", "}", "return", "tileData", ";", "}" ]
Get layer's `TileData` for a given map tile coord. Optionally modifying the `prevTileData` object param if `this.mergeWithPrevLayer = true`. @method getModifiedTileData @param {Number} x - Map tile x coord. @param {Object} y - Map tile y coord. @param {Object} [prevTileData] - `tileData` object for the given map tile coord from previous layer. @return {TileData|Bool} false if nothing to render
[ "Get", "layer", "s", "TileData", "for", "a", "given", "map", "tile", "coord", ".", "Optionally", "modifying", "the", "prevTileData", "object", "param", "if", "this", ".", "mergeWithPrevLayer", "=", "true", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/renderer-layer.js#L99-L105
46,098
THEjoezack/BoxPusher
public/js-roguelike-skeleton/src/renderer-layer.js
function(tileData1, tileData2){ var result = {}, key, val; for(key in tileData1){ result[key] = tileData1[key]; } for(key in tileData2){ val = tileData2[key]; if(val !== false && val !== void 0){ result[key] = val; } } return result; }
javascript
function(tileData1, tileData2){ var result = {}, key, val; for(key in tileData1){ result[key] = tileData1[key]; } for(key in tileData2){ val = tileData2[key]; if(val !== false && val !== void 0){ result[key] = val; } } return result; }
[ "function", "(", "tileData1", ",", "tileData2", ")", "{", "var", "result", "=", "{", "}", ",", "key", ",", "val", ";", "for", "(", "key", "in", "tileData1", ")", "{", "result", "[", "key", "]", "=", "tileData1", "[", "key", "]", ";", "}", "for", "(", "key", "in", "tileData2", ")", "{", "val", "=", "tileData2", "[", "key", "]", ";", "if", "(", "val", "!==", "false", "&&", "val", "!==", "void", "0", ")", "{", "result", "[", "key", "]", "=", "val", ";", "}", "}", "return", "result", ";", "}" ]
Merges 2 `tileData` objects. Used to Merges layers of the same tile before drawing them. @method mergeTileData @param {TileData} tileData1 - `tileData` to merge to. @param {TileData} tileData2 - `tileData` to merge from, properties with values on tileData2 replace matching properties on tileData1 @return {TileData} A new `tileData` object with merged values.
[ "Merges", "2", "tileData", "objects", ".", "Used", "to", "Merges", "layers", "of", "the", "same", "tile", "before", "drawing", "them", "." ]
ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5
https://github.com/THEjoezack/BoxPusher/blob/ebd506f7e61d10e4d493cf1cad1fbd4b43be28d5/public/js-roguelike-skeleton/src/renderer-layer.js#L115-L128
46,099
jkphl/gulp-concat-flatten
index.js
endStream
function endStream(cb) { // If no files were passed in, no files go out ... if (!latestFile || (Object.keys(concats).length === 0 && concats.constructor === Object)) { cb(); return; } // Prepare a method for pushing the stream const pushJoinedFile = (joinedBase) => { const joinedFile = new File({ path: joinedBase, contents: concats[joinedBase].concat.content, stat: concats[joinedBase].stats }); if (concats[joinedBase].concat.sourceMapping) { joinedFile.sourceMap = JSON.parse(concats[joinedBase].concat.sourceMap); } this.push(joinedFile); delete concats[joinedBase]; }; // Refine the dependency graph const refinedDependencyMap = []; dependencyGraph.forEach(edge => { if ((edge[0] in nameBaseMap) && (edge[1] in nameBaseMap)) { refinedDependencyMap.push([nameBaseMap[edge[0]], nameBaseMap[edge[1]]]); } }); const sortedDependencies = refinedDependencyMap.length ? toposort(refinedDependencyMap).reverse() : []; sortedDependencies.map(pushJoinedFile); // Run through all registered contact instances for (const targetBase in concats) { pushJoinedFile(targetBase); } cb(); }
javascript
function endStream(cb) { // If no files were passed in, no files go out ... if (!latestFile || (Object.keys(concats).length === 0 && concats.constructor === Object)) { cb(); return; } // Prepare a method for pushing the stream const pushJoinedFile = (joinedBase) => { const joinedFile = new File({ path: joinedBase, contents: concats[joinedBase].concat.content, stat: concats[joinedBase].stats }); if (concats[joinedBase].concat.sourceMapping) { joinedFile.sourceMap = JSON.parse(concats[joinedBase].concat.sourceMap); } this.push(joinedFile); delete concats[joinedBase]; }; // Refine the dependency graph const refinedDependencyMap = []; dependencyGraph.forEach(edge => { if ((edge[0] in nameBaseMap) && (edge[1] in nameBaseMap)) { refinedDependencyMap.push([nameBaseMap[edge[0]], nameBaseMap[edge[1]]]); } }); const sortedDependencies = refinedDependencyMap.length ? toposort(refinedDependencyMap).reverse() : []; sortedDependencies.map(pushJoinedFile); // Run through all registered contact instances for (const targetBase in concats) { pushJoinedFile(targetBase); } cb(); }
[ "function", "endStream", "(", "cb", ")", "{", "// If no files were passed in, no files go out ...", "if", "(", "!", "latestFile", "||", "(", "Object", ".", "keys", "(", "concats", ")", ".", "length", "===", "0", "&&", "concats", ".", "constructor", "===", "Object", ")", ")", "{", "cb", "(", ")", ";", "return", ";", "}", "// Prepare a method for pushing the stream", "const", "pushJoinedFile", "=", "(", "joinedBase", ")", "=>", "{", "const", "joinedFile", "=", "new", "File", "(", "{", "path", ":", "joinedBase", ",", "contents", ":", "concats", "[", "joinedBase", "]", ".", "concat", ".", "content", ",", "stat", ":", "concats", "[", "joinedBase", "]", ".", "stats", "}", ")", ";", "if", "(", "concats", "[", "joinedBase", "]", ".", "concat", ".", "sourceMapping", ")", "{", "joinedFile", ".", "sourceMap", "=", "JSON", ".", "parse", "(", "concats", "[", "joinedBase", "]", ".", "concat", ".", "sourceMap", ")", ";", "}", "this", ".", "push", "(", "joinedFile", ")", ";", "delete", "concats", "[", "joinedBase", "]", ";", "}", ";", "// Refine the dependency graph", "const", "refinedDependencyMap", "=", "[", "]", ";", "dependencyGraph", ".", "forEach", "(", "edge", "=>", "{", "if", "(", "(", "edge", "[", "0", "]", "in", "nameBaseMap", ")", "&&", "(", "edge", "[", "1", "]", "in", "nameBaseMap", ")", ")", "{", "refinedDependencyMap", ".", "push", "(", "[", "nameBaseMap", "[", "edge", "[", "0", "]", "]", ",", "nameBaseMap", "[", "edge", "[", "1", "]", "]", "]", ")", ";", "}", "}", ")", ";", "const", "sortedDependencies", "=", "refinedDependencyMap", ".", "length", "?", "toposort", "(", "refinedDependencyMap", ")", ".", "reverse", "(", ")", ":", "[", "]", ";", "sortedDependencies", ".", "map", "(", "pushJoinedFile", ")", ";", "// Run through all registered contact instances", "for", "(", "const", "targetBase", "in", "concats", ")", "{", "pushJoinedFile", "(", "targetBase", ")", ";", "}", "cb", "(", ")", ";", "}" ]
End the stream @param {Function} cb Callback
[ "End", "the", "stream" ]
0b59787b2ceb4538fcfb7907c2cec6ac452b4d87
https://github.com/jkphl/gulp-concat-flatten/blob/0b59787b2ceb4538fcfb7907c2cec6ac452b4d87/index.js#L175-L211