Best JavaScript code snippet using sinon
Map-test.jsx
Source:Map-test.jsx
...873 });874 it('test getResolutions default', () => {875 const maxResolution = 2 * 20037508.34;876 const tileSize = 256;877 const expectedResolutions = Array.from(Array(29).keys()).map( k=> maxResolution / tileSize / Math.pow(2, k));878 let map = ReactDOM.render(<OpenlayersMap id="ol-map" center={{ y: 43.9, x: 10.3 }} zoom={11} mapOptions={{ attribution: { container: 'body' } }} />, document.getElementById("map"));879 expect(map.getResolutions().length).toBe(expectedResolutions.length);880 // NOTE: round881 expect(map.getResolutions().map(a => a.toFixed(4))).toEqual(expectedResolutions.map(a => a.toFixed(4)));882 });883 it('test getResolutions with custom projection', () => {884 const projectionDefs = [885 {886 "code": "EPSG:3003",887 "def": "+proj=tmerc +lat_0=0 +lon_0=9 +k=0.9996 +x_0=1500000 +y_0=0 +ellps=intl+towgs84=-104.1,-49.1,-9.9,0.971,-2.917,0.714,-11.68 +units=m +no_defs",888 "extent": [889 1241482.0019432348,890 972767.2605398067,891 1847542.2626266503,892 5215189.085323715893 ],894 "worldExtent": [895 6.6500,896 8.8000,897 12.0000,898 47.0500899 ]900 }901 ];902 proj.defs(projectionDefs[0].code, projectionDefs[0].def);903 const maxResolution = 1847542.2626266503 - 1241482.0019432348;904 const tileSize = 256;905 const expectedResolutions = Array.from(Array(29).keys()).map(k => maxResolution / tileSize / Math.pow(2, k));906 let map = ReactDOM.render(<OpenlayersMap907 id="ol-map"908 center={{909 x: 10.710054361528954,910 y: 43.69814562139725,911 crs: 'EPSG:4326'912 }}913 projectionDefs={projectionDefs}914 zoom={11}915 mapOptions={{ attribution: { container: 'body' } }}916 projection={projectionDefs[0].code}917 />, document.getElementById("map"));918 expect(map.getResolutions()).toExist();919 expect(map.getResolutions().length).toBe(expectedResolutions.length);920 // NOTE: round921 expect(map.getResolutions().map(a => a.toFixed(4))).toEqual(expectedResolutions.map(a => a.toFixed(4)));922 });923 it('test double attribution on document', () => {924 let map = ReactDOM.render(925 <span>926 <div className="ol-attribution"></div>927 <div id="map-attribution"></div>928 <OpenlayersMap id="ol-map" center={{y: 43.9, x: 10.3}} zoom={11} mapOptions={{attribution: {container: '#map-attribution'}}}/>929 </span>930 , document.getElementById("map"));931 expect(map).toExist();932 const domMap = document.getElementById('ol-map');933 let attributions = domMap.getElementsByClassName('ol-attribution');934 expect(attributions.length).toBe(0);935 attributions = document.getElementsByClassName('ol-attribution');...
path.js
Source:path.js
1import * as Utils from './utils.js';2import { def, make } from './gw.js';3var PATH = {};4export { PATH as path };5const PDS_FORBIDDEN = def.PDS_FORBIDDEN = -1;6const PDS_OBSTRUCTION = def.PDS_OBSTRUCTION = -2;7const PDS_AVOIDED = def.PDS_AVOIDED = 10;8const PDS_NO_PATH = def.PDS_NO_PATH = 30000;9// GW.actor.avoidsCell = GW.actor.avoidsCell || Utils.FALSE;10// GW.actor.canPass = GW.actor.canPass || ((a, b) => a === b);11function makeCostLink(i) {12 return {13 distance: 0,14 cost: 0,15 index: i,16 left: null, right: null17 };18}19function makeDijkstraMap(w, h) {20 return {21 eightWays: false,22 front: makeCostLink(-1),23 links: make.array(w * h, (i) => makeCostLink(i) ),24 width: w,25 height: h,26 };27}28function getLink(map, x, y) {29 return (map.links[x + map.width * y]);30}31const DIRS = def.dirs;32function update(map) {33 let dir, dirs;34 let linkIndex;35 let left = null, right = null, link = null;36 dirs = map.eightWays ? 8 : 4;37 let head = map.front.right;38 map.front.right = null;39 while (head != null) {40 for (dir = 0; dir < dirs; dir++) {41 linkIndex = head.index + (DIRS[dir][0] + map.width * DIRS[dir][1]);42 if (linkIndex < 0 || linkIndex >= map.width * map.height) continue;43 link = map.links[linkIndex];44 // verify passability45 if (link.cost < 0) continue;46 let diagCost = 0;47 if (dir >= 4) {48 diagCost = 0.4142;49 let way1, way1index, way2, way2index;50 way1index = head.index + DIRS[dir][0];51 if (way1index < 0 || way1index >= map.width * map.height) continue;52 way2index = head.index + map.width * DIRS[dir][1];53 if (way2index < 0 || way2index >= map.width * map.height) continue;54 way1 = map.links[way1index];55 way2 = map.links[way2index];56 if (way1.cost == PDS_OBSTRUCTION || way2.cost == PDS_OBSTRUCTION) continue;57 }58 if (head.distance + link.cost + diagCost < link.distance) {59 link.distance = head.distance + link.cost + diagCost;60 // reinsert the touched cell; it'll be close to the beginning of the list now, so61 // this will be very fast. start by removing it.62 if (link.right != null) link.right.left = link.left;63 if (link.left != null) link.left.right = link.right;64 left = head;65 right = head.right;66 while (right != null && right.distance < link.distance) {67 left = right;68 right = right.right;69 }70 if (left != null) left.right = link;71 link.right = right;72 link.left = left;73 if (right != null) right.left = link;74 }75 }76 right = head.right;77 head.left = null;78 head.right = null;79 head = right;80 }81}82function clear(map, maxDistance, eightWays) {83 let i;84 map.eightWays = eightWays;85 map.front.right = null;86 for (i=0; i < map.width*map.height; i++) {87 map.links[i].distance = maxDistance;88 map.links[i].left = map.links[i].right = null;89 }90}91// function pdsGetDistance(map, x, y) {92// update(map);93// return getLink(map, x, y).distance;94// }95function setDistance(map, x, y, distance) {96 let left, right, link;97 if (x > 0 && y > 0 && x < map.width - 1 && y < map.height - 1) {98 link = getLink(map, x, y);99 if (link.distance > distance) {100 link.distance = distance;101 if (link.right != null) link.right.left = link.left;102 if (link.left != null) link.left.right = link.right;103 left = map.front;104 right = map.front.right;105 while (right != null && right.distance < link.distance) {106 left = right;107 right = right.right;108 }109 link.right = right;110 link.left = left;111 left.right = link;112 if (right != null) right.left = link;113 }114 }115}116function pdsSetCosts(map, costMap) {117 let i, j;118 for (i=0; i<map.width; i++) {119 for (j=0; j<map.height; j++) {120 if (i != 0 && j != 0 && i < map.width - 1 && j < map.height - 1) {121 getLink(map, i, j).cost = costMap[i][j];122 } else {123 getLink(map, i, j).cost = PDS_FORBIDDEN;124 }125 }126 }127}128function pdsBatchInput(map, distanceMap, costMap, maxDistance, eightWays) {129 let i, j;130 let left, right;131 map.eightWays = eightWays;132 left = null;133 right = null;134 map.front.right = null;135 for (i=0; i<map.width; i++) {136 for (j=0; j<map.height; j++) {137 let link = getLink(map, i, j);138 if (distanceMap != null) {139 link.distance = distanceMap[i][j];140 } else {141 if (costMap != null) {142 // totally hackish; refactor143 link.distance = maxDistance;144 }145 }146 let cost;147 if (costMap.isBoundaryXY(i, j)) {148 cost = PDS_OBSTRUCTION;149 } else {150 cost = costMap[i][j];151 }152 link.cost = cost;153 if (cost > 0) {154 if (link.distance < maxDistance) {155 if (right == null || right.distance > link.distance) {156 // left and right are used to traverse the list; if many cells have similar values,157 // some time can be saved by not clearing them with each insertion. this time,158 // sadly, we have to start from the front.159 left = map.front;160 right = map.front.right;161 }162 while (right != null && right.distance < link.distance) {163 left = right;164 right = right.right;165 }166 link.right = right;167 link.left = left;168 left.right = link;169 if (right != null) right.left = link;170 left = link;171 } else {172 link.right = null;173 link.left = null;174 }175 } else {176 link.right = null;177 link.left = null;178 }179 }180 }181}182function batchOutput(map, distanceMap) {183 let i, j;184 update(map);185 // transfer results to the distanceMap186 for (i=0; i<map.width; i++) {187 for (j=0; j<map.height; j++) {188 distanceMap[i][j] = getLink(map, i, j).distance;189 }190 }191}192var DIJKSTRA_MAP = null;193export function dijkstraScan(distanceMap, costMap, useDiagonals) {194 // static makeDijkstraMap map;195 if (!DIJKSTRA_MAP || DIJKSTRA_MAP.width < distanceMap.width || DIJKSTRA_MAP.height < distanceMap.height) {196 DIJKSTRA_MAP = makeDijkstraMap(distanceMap.width, distanceMap.height);197 }198 DIJKSTRA_MAP.width = distanceMap.width;199 DIJKSTRA_MAP.height = distanceMap.height;200 pdsBatchInput(DIJKSTRA_MAP, distanceMap, costMap, PDS_NO_PATH, useDiagonals);201 batchOutput(DIJKSTRA_MAP, distanceMap);202}203PATH.dijkstraScan = dijkstraScan;204//205// function populateGenericCostMap(costMap, map) {206// let i, j;207//208// for (i=0; i<map.width; i++) {209// for (j=0; j<map.height; j++) {210// if (map.hasTileFlag(i, j, def.T_OBSTRUCTS_PASSABILITY)211// && (!map.hasTileMechFlag(i, j, def.TM_IS_SECRET) || (map.discoveredTileFlags(i, j) & def.T_OBSTRUCTS_PASSABILITY)))212// {213// costMap[i][j] = map.hasTileFlag(i, j, def.T_OBSTRUCTS_DIAGONAL_MOVEMENT) ? PDS_OBSTRUCTION : PDS_FORBIDDEN;214// } else if (map.hasTileFlag(i, j, def.T_PATHING_BLOCKER & ~def.T_OBSTRUCTS_PASSABILITY)) {215// costMap[i][j] = PDS_FORBIDDEN;216// } else {217// costMap[i][j] = 1;218// }219// }220// }221// }222//223// GW.path.populateGenericCostMap = populateGenericCostMap;224//225//226// function baseCostFunction(blockingTerrainFlags, traveler, canUseSecretDoors, i, j) {227// let cost = 1;228// monst = GW.MAP.actorAt(i, j);229// const monstFlags = (monst ? (monst.info ? monst.info.flags : monst.flags) : 0) || 0;230// if ((monstFlags & (def.MONST_IMMUNE_TO_WEAPONS | def.MONST_INVULNERABLE))231// && (monstFlags & (def.MONST_IMMOBILE | def.MONST_GETS_TURN_ON_ACTIVATION)))232// {233// // Always avoid damage-immune stationary monsters.234// cost = PDS_FORBIDDEN;235// } else if (canUseSecretDoors236// && GW.MAP.hasTileMechFlag(i, j, TM_IS_SECRET)237// && GW.MAP.hasTileFlag(i, j, T_OBSTRUCTS_PASSABILITY)238// && !(GW.MAP.hasDiscoveredFlag(i, j) & T_OBSTRUCTS_PASSABILITY))239// {240// cost = 1;241// } else if (GW.MAP.hasTileFlag(i, j, T_OBSTRUCTS_PASSABILITY)242// || (traveler && traveler === GW.PLAYER && !(GW.MAP.hasCellFlag(i, j, (REVEALED | MAGIC_MAPPED)))))243// {244// cost = GW.MAP.hasTileFlag(i, j, T_OBSTRUCTS_DIAGONAL_MOVEMENT) ? PDS_OBSTRUCTION : PDS_FORBIDDEN;245// } else if ((traveler && GW.actor.avoidsCell(traveler, i, j)) || GW.MAP.hasTileFlag(i, j, blockingTerrainFlags)) {246// cost = PDS_FORBIDDEN;247// }248//249// return cost;250// }251//252// GW.path.costFn = baseCostFunction;253// GW.path.simpleCost = baseCostFunction.bind(undefined, 0, null, false);254// GW.path.costForActor = ((actor) => baseCostFunction.bind(undefined, GW.actor.forbiddenFlags(actor), actor, actor !== GW.PLAYER));255export function calculateDistances(distanceMap,256 destinationX, destinationY,257 costMap,258 eightWays)259{260 if (!DIJKSTRA_MAP || DIJKSTRA_MAP.width < distanceMap.width || DIJKSTRA_MAP.height < distanceMap.height) {261 DIJKSTRA_MAP = makeDijkstraMap(distanceMap.width, distanceMap.height);262 }263 DIJKSTRA_MAP.width = distanceMap.width;264 DIJKSTRA_MAP.height = distanceMap.height;265 let i, j;266 for (i=0; i<distanceMap.width; i++) {267 for (j=0; j<distanceMap.height; j++) {268 getLink(DIJKSTRA_MAP, i, j).cost = costMap.isBoundaryXY(i, j) ? PDS_OBSTRUCTION : costMap[i][j];269 }270 }271 clear(DIJKSTRA_MAP, PDS_NO_PATH, eightWays);272 setDistance(DIJKSTRA_MAP, destinationX, destinationY, 0);273 batchOutput(DIJKSTRA_MAP, distanceMap);274 distanceMap.x = destinationX;275 distanceMap.y = destinationY;276}277PATH.calculateDistances = calculateDistances;278// function pathingDistance(x1, y1, x2, y2, blockingTerrainFlags, actor) {279// let retval;280// const distanceMap = GW.grid.alloc(DUNGEON.width, DUNGEON.height, 0);281// const costFn = baseCostFunction.bind(undefined, blockingTerrainFlags, actor, true);282// calculateDistances(distanceMap, x2, y2, costFn, true);283// retval = distanceMap[x1][y1];284// GW.grid.free(distanceMap);285// return retval;286// }287//288// GW.path.distanceFromTo = pathingDistance;289// function monstTravelDistance(monst, x2, y2, blockingTerrainFlags) {290// let retval;291// const distanceMap = GW.grid.alloc(DUNGEON.width, DUNGEON.height, 0);292// calculateDistances(distanceMap, x2, y2, blockingTerrainFlags, monst, true, true);293// retval = distanceMap[monst.x][monst.y];294// GW.grid.free(distanceMap);295// return retval;296// }297//298// GW.actor.travelDistance = monstTravelDistance;299//300// function getClosestValidLocationOnMap(map, x, y) {301// let i, j, dist, closestDistance, lowestMapScore;302// let locX = -1;303// let locY = -1;304//305// closestDistance = 10000;306// lowestMapScore = 10000;307// for (i=1; i<map.width-1; i++) {308// for (j=1; j<map.height-1; j++) {309// if (map[i][j] >= 0 && map[i][j] < PDS_NO_PATH) {310// dist = (i - x)*(i - x) + (j - y)*(j - y);311// //hiliteCell(i, j, &purple, min(dist / 2, 100), false);312// if (dist < closestDistance313// || dist == closestDistance && map[i][j] < lowestMapScore)314// {315// locX = i;316// locY = j;317// closestDistance = dist;318// lowestMapScore = map[i][j];319// }320// }321// }322// }323// if (locX >= 0) return [locX, locY];324// return null;325// }326//327//328// // Populates path[][] with a list of coordinates starting at origin and traversing down the map. Returns the number of steps in the path.329// function getMonsterPathOnMap(distanceMap, originX, originY, monst) {330// let dir, x, y, steps;331//332// // monst = monst || GW.PLAYER;333// x = originX;334// y = originY;335// steps = 0;336//337//338// if (distanceMap[x][y] < 0 || distanceMap[x][y] >= PDS_NO_PATH) {339// const loc = getClosestValidLocationOnMap(distanceMap, x, y);340// if (loc) {341// x = loc[0];342// y = loc[1];343// }344// }345//346// const path = [[x, y]];347// dir = 0;348// while (dir != def.NO_DIRECTION) {349// dir = GW.path.nextStep(distanceMap, x, y, monst, true);350// if (dir != def.NO_DIRECTION) {351// x += DIRS[dir][0];352// y += DIRS[dir][1];353// // path[steps][0] = x;354// // path[steps][1] = y;355// path.push([x,y]);356// steps++;357// // brogueAssert(coordinatesAreInMap(x, y));358// }359// }360//361// return steps ? path : null;362// }363//...
map-controller.js
Source:map-controller.js
1/**2 * @ngdoc controller3 * @name MapController4 */5(function() {6 'use strict';7 var Attr2MapOptions;8 var __MapController = function(9 $scope, $element, $attrs, $parse, _Attr2MapOptions_, NgMap, NgMapPool10 ) {11 Attr2MapOptions = _Attr2MapOptions_;12 var vm = this;13 vm.mapOptions; /** @memberof __MapController */14 vm.mapEvents; /** @memberof __MapController */15 vm.eventListeners; /** @memberof __MapController */16 /**17 * Add an object to the collection of group18 * @memberof __MapController19 * @function addObject20 * @param groupName the name of collection that object belongs to21 * @param obj an object to add into a collection, i.e. marker, shape22 */23 vm.addObject = function(groupName, obj) {24 if (vm.map) {25 vm.map[groupName] = vm.map[groupName] || {};26 var len = Object.keys(vm.map[groupName]).length;27 vm.map[groupName][obj.id || len] = obj;28 if (vm.map instanceof google.maps.Map) {29 //infoWindow.setMap works like infoWindow.open30 if (groupName != "infoWindows" && obj.setMap) {31 obj.setMap && obj.setMap(vm.map);32 }33 if (obj.centered && obj.position) {34 vm.map.setCenter(obj.position);35 }36 (groupName == 'markers') && vm.objectChanged('markers');37 (groupName == 'customMarkers') && vm.objectChanged('customMarkers');38 }39 }40 };41 /**42 * Delete an object from the collection and remove from map43 * @memberof __MapController44 * @function deleteObject45 * @param {Array} objs the collection of objects. i.e., map.markers46 * @param {Object} obj the object to be removed. i.e., marker47 */48 vm.deleteObject = function(groupName, obj) {49 /* delete from group */50 if (obj.map) {51 var objs = obj.map[groupName];52 for (var name in objs) {53 if (objs[name] === obj) {54 console.log('Deleting', groupName, obj);55 google.maps.event.clearInstanceListeners(obj);56 delete objs[name];57 }58 }59 /* delete from map */60 obj.map && obj.setMap && obj.setMap(null);61 (groupName == 'markers') && vm.objectChanged('markers');62 (groupName == 'customMarkers') && vm.objectChanged('customMarkers');63 }64 };65 /**66 * @memberof __MapController67 * @function observeAttrSetObj68 * @param {Hash} orgAttrs attributes before its initialization69 * @param {Hash} attrs attributes after its initialization70 * @param {Object} obj map object that an action is to be done71 * @description watch changes of attribute values and72 * do appropriate action based on attribute name73 */74 vm.observeAttrSetObj = function(orgAttrs, attrs, obj) {75 if (attrs.noWatcher) {76 return false;77 }78 var attrsToObserve = Attr2MapOptions.getAttrsToObserve(orgAttrs);79 for (var i=0; i<attrsToObserve.length; i++) {80 var attrName = attrsToObserve[i];81 attrs.$observe(attrName, NgMap.observeAndSet(attrName, obj));82 }83 };84 /**85 * @memberof __MapController86 * @function zoomToIncludeMarkers87 */88 vm.zoomToIncludeMarkers = function() {89 // Only fit to bounds if we have any markers90 // object.keys is supported in all major browsers (IE9+)91 if ((vm.map.markers != null && Object.keys(vm.map.markers).length > 0) || (vm.map.customMarkers != null && Object.keys(vm.map.customMarkers).length > 0)) {92 var bounds = new google.maps.LatLngBounds();93 for (var k1 in vm.map.markers) {94 bounds.extend(vm.map.markers[k1].getPosition());95 }96 for (var k2 in vm.map.customMarkers) {97 bounds.extend(vm.map.customMarkers[k2].getPosition());98 }99 if (vm.mapOptions.maximumZoom) {100 vm.enableMaximumZoomCheck = true; //enable zoom check after resizing for markers101 }102 vm.map.fitBounds(bounds);103 }104 };105 /**106 * @memberof __MapController107 * @function objectChanged108 * @param {String} group name of group e.g., markers109 */110 vm.objectChanged = function(group) {111 if ( vm.map &&112 (group == 'markers' || group == 'customMarkers') &&113 vm.map.zoomToIncludeMarkers == 'auto'114 ) {115 vm.zoomToIncludeMarkers();116 }117 };118 /**119 * @memberof __MapController120 * @function initializeMap121 * @description122 * . initialize Google map on <div> tag123 * . set map options, events, and observers124 * . reset zoom to include all (custom)markers125 */126 vm.initializeMap = function() {127 var mapOptions = vm.mapOptions,128 mapEvents = vm.mapEvents;129 var lazyInitMap = vm.map; //prepared for lazy init130 vm.map = NgMapPool.getMapInstance($element[0]);131 NgMap.setStyle($element[0]);132 // set objects for lazyInit133 if (lazyInitMap) {134 /**135 * rebuild mapOptions for lazyInit136 * because attributes values might have been changed137 */138 var filtered = Attr2MapOptions.filter($attrs);139 var options = Attr2MapOptions.getOptions(filtered);140 var controlOptions = Attr2MapOptions.getControlOptions(filtered);141 mapOptions = angular.extend(options, controlOptions);142 console.log('map options', mapOptions);143 for (var group in lazyInitMap) {144 var groupMembers = lazyInitMap[group]; //e.g. markers145 if (typeof groupMembers == 'object') {146 for (var id in groupMembers) {147 vm.addObject(group, groupMembers[id]);148 }149 }150 }151 vm.map.showInfoWindow = vm.showInfoWindow;152 vm.map.hideInfoWindow = vm.hideInfoWindow;153 }154 // set options155 mapOptions.zoom = mapOptions.zoom || 15;156 var center = mapOptions.center;157 if (!mapOptions.center ||158 ((typeof center === 'string') && center.match(/\{\{.*\}\}/))159 ) {160 mapOptions.center = new google.maps.LatLng(0, 0);161 } else if (!(center instanceof google.maps.LatLng)) {162 var geoCenter = mapOptions.center;163 delete mapOptions.center;164 NgMap.getGeoLocation(geoCenter, mapOptions.geoLocationOptions).165 then(function (latlng) {166 vm.map.setCenter(latlng);167 var geoCallback = mapOptions.geoCallback;168 geoCallback && $parse(geoCallback)($scope);169 }, function () {170 if (mapOptions.geoFallbackCenter) {171 vm.map.setCenter(mapOptions.geoFallbackCenter);172 }173 });174 }175 vm.map.setOptions(mapOptions);176 // set events177 for (var eventName in mapEvents) {178 var event = mapEvents[eventName];179 var listener = google.maps.event.addListener(vm.map, eventName, event);180 vm.eventListeners[eventName] = listener;181 }182 // set observers183 vm.observeAttrSetObj(orgAttrs, $attrs, vm.map);184 vm.singleInfoWindow = mapOptions.singleInfoWindow;185 google.maps.event.trigger(vm.map, 'resize');186 google.maps.event.addListenerOnce(vm.map, "idle", function () {187 NgMap.addMap(vm);188 if (mapOptions.zoomToIncludeMarkers) {189 vm.zoomToIncludeMarkers();190 }191 //TODO: it's for backward compatibiliy. will be removed192 $scope.map = vm.map;193 $scope.$emit('mapInitialized', vm.map);194 //callback195 if ($attrs.mapInitialized) {196 $parse($attrs.mapInitialized)($scope, {map: vm.map});197 }198 });199 200 //add maximum zoom listeners if zoom-to-include-markers and and maximum-zoom are valid attributes201 if (mapOptions.zoomToIncludeMarkers && mapOptions.maximumZoom) {202 google.maps.event.addListener(vm.map, 'zoom_changed', function() {203 if (vm.enableMaximumZoomCheck == true) {204 vm.enableMaximumZoomCheck = false;205 google.maps.event.addListenerOnce(vm.map, 'bounds_changed', function() { 206 vm.map.setZoom(Math.min(mapOptions.maximumZoom, vm.map.getZoom())); 207 });208 }209 });210 }211 };212 $scope.google = google; //used by $scope.eval to avoid eval()213 /**214 * get map options and events215 */216 var orgAttrs = Attr2MapOptions.orgAttributes($element);217 var filtered = Attr2MapOptions.filter($attrs);218 var options = Attr2MapOptions.getOptions(filtered, {scope: $scope});219 var controlOptions = Attr2MapOptions.getControlOptions(filtered);220 var mapOptions = angular.extend(options, controlOptions);221 var mapEvents = Attr2MapOptions.getEvents($scope, filtered);222 console.log('ng-map Options', mapOptions);223 Object.keys(mapEvents).length && console.log('ng-map Events', mapEvents);224 vm.mapOptions = mapOptions;225 vm.mapEvents = mapEvents;226 vm.eventListeners = {};227 if (options.lazyInit) { // allows controlled initialization228 // parse angular expression for dynamic ids229 if (!!$attrs.id && 230 // starts with, at position 0231 $attrs.id.indexOf("{{", 0) === 0 &&232 // ends with233 $attrs.id.indexOf("}}", $attrs.id.length - "}}".length) !== -1) {234 var idExpression = $attrs.id.slice(2,-2);235 var mapId = $parse(idExpression)($scope);236 } else {237 var mapId = $attrs.id;238 }239 vm.map = {id: mapId}; //set empty, not real, map240 NgMap.addMap(vm);241 } else {242 vm.initializeMap();243 }244 //Trigger Resize245 if(options.triggerResize) {246 google.maps.event.trigger(vm.map, 'resize');247 }248 $element.bind('$destroy', function() {249 NgMapPool.returnMapInstance(vm.map);250 NgMap.deleteMap(vm);251 });252 }; // __MapController253 __MapController.$inject = [254 '$scope', '$element', '$attrs', '$parse', 'Attr2MapOptions', 'NgMap', 'NgMapPool'255 ];256 angular.module('ngMap').controller('__MapController', __MapController);...
SourceMapManager.js
Source:SourceMapManager.js
...20 this._resolvedSourceMapURL = new Map();21 /** @type {!Map<string, !SDK.SourceMap>} */22 this._sourceMapByURL = new Map();23 /** @type {!Multimap<string, !T>} */24 this._sourceMapURLToLoadingClients = new Multimap();25 /** @type {!Multimap<string, !T>} */26 this._sourceMapURLToClients = new Multimap();27 SDK.targetManager.addEventListener(SDK.TargetManager.Events.InspectedURLChanged, this._inspectedURLChanged, this);28 }29 /**30 * @param {boolean} isEnabled31 */32 setEnabled(isEnabled) {33 if (isEnabled === this._isEnabled)34 return;35 this._isEnabled = isEnabled;36 const clients = Array.from(this._resolvedSourceMapURL.keys());37 for (const client of clients) {38 const relativeSourceURL = this._relativeSourceURL.get(client);39 const relativeSourceMapURL = this._relativeSourceMapURL.get(client);40 this.detachSourceMap(client);...
demo15.js
Source:demo15.js
...166 [...map0].filter(([k, v]) => k < 3)167);168// 产çMapç»æ {1 => 'a', 2 => 'b'}169let map2 = new Map(170 [...map0].map(([k, v]) => [k * 2, '_' + v])171);172// 产çMapç»æ {2 => '_a', 4 => '_b', 6 => '_c'}173//æ¤å¤ï¼Mapè¿æä¸ä¸ªforEachæ¹æ³ï¼ä¸æ°ç»çforEachæ¹æ³ç±»ä¼¼ï¼ä¹å¯ä»¥å®ç°éåã174map.forEach(function(value, key, map) {175 console.log("Key: %s, Value: %s", key, value);176});177//æ©å±å
容ï¼è¡¥å
æèï¼178//Mapä¸å
¶ä»æ°æ®ç»æ对象ç转æ¢ï¼åèçµå书13.3.4ç« è179//Map转为æ°ç»180//åé¢å·²ç»æè¿ï¼Map转为æ°ç»ææ¹ä¾¿çæ¹æ³ï¼å°±æ¯ä½¿ç¨æ©å±è¿ç®ç¬¦ï¼...ï¼ã181let myMap = new Map().set(true, 7).set({foo: 3}, ['abc']);182[...myMap]183// [ [ true, 7 ], [ { foo: 3 }, [ 'abc' ] ] ]184//æ°ç»è½¬ä¸ºMap...
map.js
Source:map.js
1// Copyright 2014 the V8 project authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4var MapSmiBenchmark = new BenchmarkSuite('Map-Smi', [1000], [5 new Benchmark('Set', false, false, 0, MapSetSmi, MapSetupSmiBase, MapTearDown),6 new Benchmark('Has', false, false, 0, MapHasSmi, MapSetupSmi, MapTearDown),7 new Benchmark('Get', false, false, 0, MapGetSmi, MapSetupSmi, MapTearDown),8 new Benchmark('Delete', false, false, 0, MapDeleteSmi, MapSetupSmi, MapTearDown),9]);10var MapStringBenchmark = new BenchmarkSuite('Map-String', [1000], [11 new Benchmark('Set', false, false, 0, MapSetString, MapSetupStringBase, MapTearDown),12 new Benchmark('Has', false, false, 0, MapHasString, MapSetupString, MapTearDown),13 new Benchmark('Get', false, false, 0, MapGetString, MapSetupString, MapTearDown),14 new Benchmark('Delete', false, false, 0, MapDeleteString, MapSetupString, MapTearDown),15]);16var MapObjectBenchmark = new BenchmarkSuite('Map-Object', [1000], [17 new Benchmark('Set', false, false, 0, MapSetObject, MapSetupObjectBase, MapTearDown),18 new Benchmark('Has', false, false, 0, MapHasObject, MapSetupObject, MapTearDown),19 new Benchmark('Get', false, false, 0, MapGetObject, MapSetupObject, MapTearDown),20 new Benchmark('Delete', false, false, 0, MapDeleteObject, MapSetupObject, MapTearDown),21]);22var MapDoubleBenchmark = new BenchmarkSuite('Map-Double', [1000], [23 new Benchmark('Set', false, false, 0, MapSetDouble, MapSetupDoubleBase, MapTearDown),24 new Benchmark('Has', false, false, 0, MapHasDouble, MapSetupDouble, MapTearDown),25 new Benchmark('Get', false, false, 0, MapGetDouble, MapSetupDouble, MapTearDown),26 new Benchmark('Delete', false, false, 0, MapDeleteDouble, MapSetupDouble, MapTearDown),27]);28var MapObjectLargeBenchmark = new BenchmarkSuite('Map-Object-Set-Get-Large', [1e7], [29 new Benchmark('Set-Get', false, false, 0, MapSetGetObjectLarge,30 MapSetupObjectBaseLarge, MapTearDown),31]);32var MapIterationBenchmark = new BenchmarkSuite('Map-Iteration', [1000], [33 new Benchmark('ForEach', false, false, 0, MapForEach, MapSetupSmi, MapTearDown),34]);35var MapIterationBenchmark = new BenchmarkSuite('Map-Iterator', [1000], [36 new Benchmark('Iterator', false, false, 0, MapIterator, MapSetupSmi, MapTearDown),37]);38var MapConstructorBenchmark = new BenchmarkSuite('Map-Constructor', [1000], [39 new Benchmark('Smi', false, false, 0, MapConstructorSmi, SetupSmiKeyValuePairs, MapTearDown),40 new Benchmark('String', false, false, 0, MapConstructorString, SetupStringKeyValuePairs, MapTearDown),41 new Benchmark('Object', false, false, 0, MapConstructorObject, SetupObjectKeyValuePairs, MapTearDown),42 new Benchmark('Double', false, false, 0, MapConstructorDouble, SetupDoubleKeyValuePairs, MapTearDown),43]);44var map;45function MapSetupSmiBase() {46 SetupSmiKeys();47 map = new Map;48}49function MapSetupSmi() {50 MapSetupSmiBase();51 MapSetSmi();52}53function MapSetupStringBase() {54 SetupStringKeys();55 map = new Map;56}57function MapSetupString() {58 MapSetupStringBase();59 MapSetString();60}61function MapSetupObjectBase() {62 SetupObjectKeys();63 map = new Map;64}65function MapSetupObjectBaseLarge() {66 SetupObjectKeys(2 * LargeN);67 map = new Map;68}69function MapSetupObject() {70 MapSetupObjectBase();71 MapSetObject();72}73function MapSetupDoubleBase() {74 SetupDoubleKeys();75 map = new Map;76}77function MapSetupDouble() {78 MapSetupDoubleBase();79 MapSetDouble();80}81function MapTearDown() {82 map = null;83}84function MapConstructorSmi() {85 map = new Map(keyValuePairs);86}87function MapSetSmi() {88 for (var i = 0; i < N; i++) {89 map.set(keys[i], i);90 }91}92function MapHasSmi() {93 for (var i = 0; i < N; i++) {94 if (!map.has(keys[i])) {95 throw new Error();96 }97 }98 for (var i = N; i < 2 * N; i++) {99 if (map.has(keys[i])) {100 throw new Error();101 }102 }103}104function MapGetSmi() {105 for (var i = 0; i < N; i++) {106 if (map.get(keys[i]) !== i) {107 throw new Error();108 }109 }110 for (var i = N; i < 2 * N; i++) {111 if (map.get(keys[i]) !== undefined) {112 throw new Error();113 }114 }115}116function MapDeleteSmi() {117 // This is run more than once per setup so we will end up deleting items118 // more than once. Therefore, we do not the return value of delete.119 for (var i = 0; i < N; i++) {120 map.delete(keys[i]);121 }122}123function MapConstructorString() {124 map = new Map(keyValuePairs);125}126function MapSetString() {127 for (var i = 0; i < N; i++) {128 map.set(keys[i], i);129 }130}131function MapHasString() {132 for (var i = 0; i < N; i++) {133 if (!map.has(keys[i])) {134 throw new Error();135 }136 }137 for (var i = N; i < 2 * N; i++) {138 if (map.has(keys[i])) {139 throw new Error();140 }141 }142}143function MapGetString() {144 for (var i = 0; i < N; i++) {145 if (map.get(keys[i]) !== i) {146 throw new Error();147 }148 }149 for (var i = N; i < 2 * N; i++) {150 if (map.get(keys[i]) !== undefined) {151 throw new Error();152 }153 }154}155function MapDeleteString() {156 // This is run more than once per setup so we will end up deleting items157 // more than once. Therefore, we do not the return value of delete.158 for (var i = 0; i < N; i++) {159 map.delete(keys[i]);160 }161}162function MapConstructorObject() {163 map = new Map(keyValuePairs);164}165function MapSetObject() {166 for (var i = 0; i < N; i++) {167 map.set(keys[i], i);168 }169}170function MapHasObject() {171 for (var i = 0; i < N; i++) {172 if (!map.has(keys[i])) {173 throw new Error();174 }175 }176 for (var i = N; i < 2 * N; i++) {177 if (map.has(keys[i])) {178 throw new Error();179 }180 }181}182function MapGetObject() {183 for (var i = 0; i < N; i++) {184 if (map.get(keys[i]) !== i) {185 throw new Error();186 }187 }188 for (var i = N; i < 2 * N; i++) {189 if (map.get(keys[i]) !== undefined) {190 throw new Error();191 }192 }193}194function MapSetGetObjectLarge() {195 for (var i = 0; i < LargeN; i++) {196 map.set(keys[i * 2], i);197 }198 for (var i = 0; i < LargeN; i++) {199 if (map.get(keys[i * 2]) !== i) {200 throw new Error();201 }202 }203 for (var i = N; i < 2 * LargeN; i++) {204 if (map.get(keys[i * 2 + 1]) !== undefined) {205 throw new Error();206 }207 }208}209function MapDeleteObject() {210 // This is run more than once per setup so we will end up deleting items211 // more than once. Therefore, we do not the return value of delete.212 for (var i = 0; i < N; i++) {213 map.delete(keys[i]);214 }215}216function MapConstructorDouble() {217 map = new Map(keyValuePairs);218}219function MapSetDouble() {220 for (var i = 0; i < N; i++) {221 map.set(keys[i], i);222 }223}224function MapHasDouble() {225 for (var i = 0; i < N; i++) {226 if (!map.has(keys[i])) {227 throw new Error();228 }229 }230 for (var i = N; i < 2 * N; i++) {231 if (map.has(keys[i])) {232 throw new Error();233 }234 }235}236function MapGetDouble() {237 for (var i = 0; i < N; i++) {238 if (map.get(keys[i]) !== i) {239 throw new Error();240 }241 }242 for (var i = N; i < 2 * N; i++) {243 if (map.get(keys[i]) !== undefined) {244 throw new Error();245 }246 }247}248function MapDeleteDouble() {249 // This is run more than once per setup so we will end up deleting items250 // more than once. Therefore, we do not the return value of delete.251 for (var i = 0; i < N; i++) {252 map.delete(keys[i]);253 }254}255function MapForEach() {256 map.forEach(function(v, k) {257 if (v !== k) {258 throw new Error();259 }260 });261}262function MapIterator() {263 var result = 0;264 for (const v of map.values()) result += v;265 return result;...
config.js
Source:config.js
...32 let mapState = action.legacy && !hasVersion ? ConfigUtils.convertFromLegacy(action.config) : ConfigUtils.normalizeConfig(action.config.map);33 // regenerate geodesic lines as property since that info has not been saved34 let annotationsLayerIndex = findIndex(mapState.layers, layer => layer.id === "annotations");35 if (annotationsLayerIndex !== -1) {36 let featuresLayer = mapState.layers[annotationsLayerIndex].features.map(feature => {37 if (feature.type === "FeatureCollection") {38 return {39 ...feature,40 features: feature.features.map(f => {41 if (f.properties.useGeodesicLines) {42 return set("properties.geometryGeodesic", {type: "LineString", coordinates: transformLineToArcs(f.geometry.coordinates)}, f);43 }44 return f;45 })46 };47 }48 if (feature.properties.geometryGeodesic) {49 return set("properties.geometryGeodesic", {type: "LineString", coordinates: transformLineToArcs(feature.geometry.coordinates)}, feature);50 }51 return state;52 });53 mapState.layers[annotationsLayerIndex] = set("features", featuresLayer, mapState.layers[annotationsLayerIndex]);54 }55 let newMapState = {56 ...mapState,57 layers: mapState.layers.map( l => {58 if (l.group === "background" && (l.type === "ol" || l.type === "OpenLayers.Layer")) {59 l.type = "empty";60 }61 return l;62 }),63 mapConfigRawData: { ...action.config }64 };65 newMapState.map = assign({}, newMapState.map, {mapId: action.mapId, size, version: hasVersion ? action.config.version : 1});66 // we store the map initial state for future usage67 return assign({}, newMapState, {mapInitialConfig: {...newMapState.map, mapId: action.mapId}});68 case MAP_CONFIG_LOAD_ERROR:69 return {70 loadingError: {...action.error, mapId: action.mapId}71 };...
ng-map-pool.js
Source:ng-map-pool.js
1/**2 * @ngdoc factory3 * @name NgMapPool4 * @description5 * Provide map instance to avoid memory leak6 */7(function() {8 'use strict';9 /**10 * @memberof NgMapPool11 * @desc map instance pool12 */13 var mapInstances = [];14 var $window, $document, $timeout;15 var add = function(el) {16 var mapDiv = $document.createElement("div");17 mapDiv.style.width = "100%";18 mapDiv.style.height = "100%";19 el.appendChild(mapDiv);20 var map = new $window.google.maps.Map(mapDiv, {});21 mapInstances.push(map);22 return map;23 };24 var findById = function(el, id) {25 var notInUseMap;26 for (var i=0; i<mapInstances.length; i++) {27 var map = mapInstances[i];28 if (map.id == id && !map.inUse) {29 var mapDiv = map.getDiv();30 el.appendChild(mapDiv);31 notInUseMap = map;32 break;33 }34 }35 return notInUseMap;36 };37 var findUnused = function(el) { //jshint ignore:line38 var notInUseMap;39 for (var i=0; i<mapInstances.length; i++) {40 var map = mapInstances[i];41 if (map.id) {42 continue;43 }44 if (!map.inUse) {45 var mapDiv = map.getDiv();46 el.appendChild(mapDiv);47 notInUseMap = map;48 break;49 }50 }51 return notInUseMap;52 };53 /**54 * @memberof NgMapPool55 * @function getMapInstance56 * @param {HtmlElement} el map container element57 * @return map instance for the given element58 */59 var getMapInstance = function(el) {60 var map = findById(el, el.id) || findUnused(el);61 if (!map) {62 map = add(el);63 } else {64 /* firing map idle event, which is used by map controller */65 $timeout(function() {66 google.maps.event.trigger(map, 'idle');67 }, 100);68 }69 map.inUse = true;70 return map;71 };72 /**73 * @memberof NgMapPool74 * @function returnMapInstance75 * @param {Map} an instance of google.maps.Map76 * @desc sets the flag inUse of the given map instance to false, so that it 77 * can be reused later78 */79 var returnMapInstance = function(map) {80 map.inUse = false;81 };82 83 /**84 * @memberof NgMapPool85 * @function resetMapInstances86 * @desc resets mapInstance array87 */88 var resetMapInstances = function() {89 for(var i = 0;i < mapInstances.length;i++) {90 mapInstances[i] = null;91 }92 mapInstances = [];93 };94 var NgMapPool = function(_$document_, _$window_, _$timeout_) {95 $document = _$document_[0], $window = _$window_, $timeout = _$timeout_;96 return {97 mapInstances: mapInstances,98 resetMapInstances: resetMapInstances,99 getMapInstance: getMapInstance,100 returnMapInstance: returnMapInstance101 };102 };103 NgMapPool.$inject = [ '$document', '$window', '$timeout'];104 angular.module('ngMap').factory('NgMapPool', NgMapPool);...
Using AI Code Generation
1var sinon = require('sinon');2var stub = sinon.stub();3stub.withArgs('first').returns('first');4stub.withArgs('second').returns('second');5stub.withArgs('third').returns('third');6console.log(stub('first'));7console.log(stub('second'));8console.log(stub('third'));9var sinon = require('sinon');10var stub = sinon.stub();11stub.withArgs('first').returns('first');12stub.withArgs('second').returns('second');13stub.withArgs('third').returns('third');14console.log(stub('first'));15console.log(stub('second'));16console.log(stub('third'));17var sinon = require('sinon');18var stub = sinon.stub();19stub.withArgs('first').returns('first');20stub.withArgs('second').returns('second');21stub.withArgs('third').returns('third');22console.log(stub('first'));23console.log(stub('second'));24console.log(stub('third'));25var sinon = require('sinon');26var stub = sinon.stub();27stub.withArgs('first').returns('first');28stub.withArgs('second').returns('second');29stub.withArgs('third').returns('third');30console.log(stub('first'));31console.log(stub('second'));32console.log(stub('third'));33var sinon = require('sinon');34var stub = sinon.stub();35stub.withArgs('first').returns('first');36stub.withArgs('second').returns('second');37stub.withArgs('third').returns('third');38console.log(stub('first'));39console.log(stub('second'));40console.log(stub('third'));
Using AI Code Generation
1var map = sinon.spy(Array.prototype, 'map');2var result = [1,2,3].map(function (n) {3 return n * 2;4});5var obj = {6 foo: function () {7 return 1;8 }9};10var spy = sinon.spy(obj, "foo");11var result = obj.foo();12var obj = {13 foo: function () {14 return 1;15 }16};17var spy = sinon.spy(obj, "foo");18var result = spy();19var obj = {20 foo: function () {21 return 1;22 }23};24var spy = sinon.spy(obj, "foo");25var result = spy(1, 2, 3);26var obj = {27 foo: function () {28 return 1;29 }30};31var spy = sinon.spy(obj, "foo");32var result = spy.withArgs(1, 2, 3).calledWith(1, 2, 3);33var obj = {34 foo: function () {35 return 1;
Using AI Code Generation
1var spy = sinon.spy();2spy("foo", "bar");3var spy = sinon.spy();4spy("foo", "bar");5var spy = sinon.spy();6spy("foo", "bar");7var spy = sinon.spy();8spy("foo", "bar");9var spy = sinon.spy();10spy("foo", "bar");11var spy = sinon.spy();12spy("foo", "bar");13var spy = sinon.spy();14spy("foo", "bar");15console.log(spy.calledWith
Using AI Code Generation
1var sinon = require('sinon');2var assert = require('assert');3var myFunction = function (a, b) {4 return a + b;5}6var myFunctionSpy = sinon.spy(myFunction);7assert(myFunctionSpy(1, 2) === 3);8assert(myFunctionSpy.withArgs(1, 2).calledOnce);9assert(myFunctionSpy.withArgs(1, 3).notCalled);10assert(myFunctionSpy.withArgs(2, 2).notCalled);11assert(myFunctionSpy.withArgs(2, 3).notCalled);12assert(myFunctionSpy.withArgs(3, 3).notCalled);13var sinon = require('sinon');14var assert = require('assert');15var myFunction = function (a, b) {16 return a + b;17}18var myFunctionSpy = sinon.spy(myFunction);19assert(myFunctionSpy(1, 2) === 3);20assert(myFunctionSpy.withArgs(1, 2).calledOnce);21assert(myFunctionSpy.withArgs(1, 3).notCalled);22assert(myFunctionSpy.withArgs(2, 2).notCalled);23assert(myFunctionSpy.withArgs(2, 3).notCalled);24assert(myFunctionSpy.withArgs(3, 3).notCalled);25assert(myFunctionSpy.withArgs(4, 4).notCalled);26assert(myFunctionSpy.withArgs(5, 5).notCalled);
Using AI Code Generation
1const sinon = require('sinon');2const assert = require('assert');3const map = require('lodash/map');4const obj = {5 myMethod: function() {6 return 1;7 }8};9describe('MyObject', function() {10 it('should call myMethod', function() {11 const spy = sinon.spy(obj, 'myMethod');12 map([1, 2, 3], obj.myMethod);13 assert(spy.calledThrice);14 });15});16{17 "scripts": {18 },19 "dependencies": {20 }21}22const sinon = require('sinon');23const assert = require('assert');24const map = require('lodash/map');25const obj = {26 myMethod: function() {27 return 1;28 }29};30describe('MyObject', function() {31 it('should call myMethod', function() {32 const spy = sinon.spy(obj, 'myMethod');33 map([1, 2, 3], obj.myMethod);34 assert(spy.calledThrice);35 });36});37{38 "scripts": {39 },40 "dependencies": {41 }42}
Using AI Code Generation
1var map = sinon.spy([1,2,3], "map");2map.withArgs(1).returns(2);3var map = sinon.spy([1,2,3], "map");4map.withArgs(2).returns(3);5var map = sinon.spy([1,2,3], "map");6map.withArgs(3).returns(4);7var sandbox = sinon.sandbox.create();8sandbox.restore();9var mock = sinon.mock(obj);10mock.expects("method").withArgs("arg").once();11obj.method("arg");12mock.verify();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!