Best JavaScript code snippet using wpt
worker.ts
Source:worker.ts
1import {CalculationResponse, CellData, Color, GridState, TileEnum, Universe} from "rgb-solver";2import * as _ from "lodash";3import {4 RequestTypes,5 ResponseDataLoaded,6 ResponseProgressMessage,7 ResponseTypes,8 ResponseWasmLoaded,9 WasmWebWorkerRequest10} from "./interface_types";11export type WASM_TYPE = typeof import ('rgb-solver');12const ITER_CHUNK = 50000;13let g_worker: RgbWasmWorker;14const ctx: Worker = self as any;15ctx.addEventListener("message", ev => {16 let requestMessage: WasmWebWorkerRequest = ev.data;17 //console.log("Got message", requestMessage.tag);18 switch (requestMessage.tag) {19 case RequestTypes.LOAD_WASM: {20 console.log("Loading wasm");21 //npm link rgb-solver22 import("rgb-solver").then(wasm => {23 g_worker = new RgbWasmWorker(wasm);24 let readyMsg: ResponseWasmLoaded = {25 tag: ResponseTypes.WASM_LOADED,26 colors: wasm.get_colors()27 };28 ctx.postMessage(readyMsg);29 g_worker.reloadGridData();30 });31 break;32 }33 case RequestTypes.LOAD_GRID_STATE: {34 g_worker.loadGridState(requestMessage.gridState);35 break;36 }37 case RequestTypes.SET_GRID_SQUARE: {38 g_worker.setGridSquare(requestMessage.cellData);39 break;40 }41 case RequestTypes.INIT_CALCULATIONS: {42 g_worker.universe.init_calculate();43 console.log("Init calculations, max ticks: ", requestMessage.maxSteps);44 g_worker.universe.set_max_ticks(requestMessage.maxSteps);45 g_worker.reloadGridData();46 break;47 }48 case RequestTypes.RUN_CALCULATE_STEPS: {49 let startedMs = performance.now();50 let lastUpdate = startedMs;51 if (requestMessage.numSteps < ITER_CHUNK) {52 const calcResponse: CalculationResponse = g_worker.universe.next_batch_calculate(requestMessage.numSteps);53 handleWasmCalcResponse(startedMs, calcResponse);54 } else {55 //batch the batch56 for (let i = 0; i < requestMessage.numSteps; i += ITER_CHUNK) {57 const calcResponse: CalculationResponse = g_worker.universe.next_batch_calculate(ITER_CHUNK);58 if (performance.now() - lastUpdate > 2000 || i + ITER_CHUNK >= requestMessage.numSteps) {59 handleWasmCalcResponse(startedMs, calcResponse);60 lastUpdate = performance.now();61 }62 //should stop63 if (calcResponse.success) {64 console.log("Success!");65 handleWasmCalcResponse(startedMs, calcResponse);66 break;67 }68 if (!_.isNil(calcResponse.error_message)) {69 console.error("Received error: ", calcResponse.error_message);70 handleWasmCalcResponse(startedMs, calcResponse);71 break;72 }73 }74 }75 break;76 }77 case RequestTypes.SET_OVERRIDE_LIST: {78 //console.log("Setting Overrides", requestMessage.overRideList);79 g_worker.universe.set_overrides(requestMessage.overRideList);80 break;81 }82 }83 //console.log("data", u.get_data());84});85function sendUpdate(data: GridState) {86 if (_.isNil(data)) {87 console.log("Null grid state after batch");88 } else {89 let dataLoadedMessage: ResponseDataLoaded = {90 tag: ResponseTypes.GRID_STATE_LOADED,91 data92 };93 ctx.postMessage(dataLoadedMessage);94 }95}96function handleWasmCalcResponse(97 startedMs: number,98 calcResponse: CalculationResponse) {99 let progressMessage: ResponseProgressMessage = {100 tag: ResponseTypes.BATCH_PROGRESS_MESSAGE,101 startedMs,102 currentMs: performance.now(),103 stepsCompleted: calcResponse.iteration_count104 };105 if (!_.isNil(calcResponse.grid_state)) {106 sendUpdate(calcResponse.grid_state);107 } else {108 progressMessage.success = false;109 }110 if (calcResponse.success) {111 progressMessage.success = true;112 }113 ctx.postMessage(progressMessage);114}115class RgbWasmWorker {116 //wasm: WASM_TYPE;117 universe: Universe;118 constructor(private wasm: WASM_TYPE) {119 this.universe = this.wasm.Universe.new(3, 3);120 }121 static tileToCellState(gridState: GridState, tile: TileEnum, index: number): CellData {122 if (!_.isFinite(index)) {123 throw Error(`Index is not a number: ${index}`);124 }125 const w = gridState.width;126 if (!_.isFinite(w) || w < 0) {127 throw Error(`Width must be >0: ${w}`);128 }129 if (!_.isFinite(index)) {130 throw Error(`Index is not a number: ${index}`);131 }132 return {133 tile,134 row_index: _.floor(index / w),135 col_index: index % w136 };137 }138 /**139 * Loads from local storage / file.140 *141 * Not for calculations142 *143 */144 loadGridState(jsonData: GridState) {145 console.log("Loading json data", jsonData);146 if (!_.isFinite(jsonData.width) || jsonData.width < 0) {147 throw Error(`Invalid width: ${jsonData.width}`);148 }149 this.universe = this.wasm.Universe.new(jsonData.height, jsonData.width);150 console.log("Universe initial data", this.universe.get_data());151 //Giving web assembly the loaded data152 if (!_.isNil(jsonData) && _.isArray(jsonData.tiles)) {153 jsonData.tiles.forEach((tile, idx) => {154 const cellData = RgbWasmWorker.tileToCellState(jsonData, tile, idx);155 this.setGridSquare(cellData, false);156 });157 }158 this.universe.init_calculate();159 //get correct form back from wasm160 this.reloadGridData();161 }162 /**163 * Cleans data (colors), then transfers to WASM164 */165 setGridSquare(cellData: CellData, refreshData: boolean = true) {166 //Correct colors167 if (cellData.tile.type === "TileRoad") {168 if (!_.isNil(cellData.tile.block) && !_.isNumber(cellData.tile.block)) {169 //assume its a color170 cellData.tile.block = (cellData.tile.block as Color).color_index;171 }172 if (!_.isNil(cellData.tile.van) && !_.isNil(cellData.tile.van.boxes)) {173 if (!_.isNumber(cellData.tile.van.color)) {174 //assume its a color175 cellData.tile.van.color = (cellData.tile.van.color as Color).color_index;176 }177 cellData.tile.van.boxes.map(box => {178 if (_.isNil(box) || _.isNumber(box)) {179 return box;180 } else {181 //assume its a color182 return (box as Color).color_index;183 }184 });185 }186 } else if (cellData.tile.type === "TileWarehouse") {187 if (!_.isNil(cellData.tile.color) && !_.isNumber(cellData.tile.color)) {188 //assume its a color189 cellData.tile.color = (cellData.tile.color as Color).color_index;190 }191 } else if (cellData.tile.type === "TileBridge") {192 let is_open = (cellData.tile as any)["is_open"];193 if (!_.isNil(is_open)) {194 cellData.tile.is_up = is_open;195 }196 }197 try {198 //console.log("Setting square", cellData);199 this.universe.set_square(cellData);200 if (refreshData) {201 this.reloadGridData();202 }203 } catch (e) {204 console.log("Error with", cellData);205 }206 }207 reloadGridData() {208 const data = this.universe.get_data();209 if (_.isNil(data)) {210 console.log("Data is null");211 } else {212 let dataLoadedMessage: ResponseDataLoaded = {213 tag: ResponseTypes.GRID_STATE_LOADED,214 data215 };216 ctx.postMessage(dataLoadedMessage);217 }218 }...
calculator.js
Source:calculator.js
1"use sctrict";2function calc() {3 const calcInput = document.getElementById('calcInput').value;4 const oper = calcInput.replace(/\d/g, '');5 const calcArray = calcInput.split(oper);6 const item0 = parseFloat(calcArray[0]);7 const item1 = parseFloat(calcArray[1]);8 switch(oper) {9 case '+':10 calcResponse = item0 + item1;11 break;12 case '-':13 calcResponse = item0 - item1;14 break;15 case '*':16 calcResponse = item0 * item1;17 break;18 case '/':19 calcResponse = item0 / item1;20 break;21 }22 23 console.log(calcResponse);24var a = document.getElementById("calcResponse");25 a.innerText = calcResponse;...
WorkerSendingPerformanceNow.js
Source:WorkerSendingPerformanceNow.js
1function calcResponse() {2 const response = [3 typeof(workerStart),4 typeof(performance),5 typeof(performance.now),6 performance.now()7 ];8 return response;9}10self.onmessage = function(event) {11 postMessage(calcResponse());12 self.close();13}14self.addEventListener("connect", function(event) {15 const port = event.ports[0];16 port.onmessage = function(event) {17 port.postMessage(calcResponse());18 port.close();19 };...
Using AI Code Generation
1var wptService = require('wpt-service');2var wpt = new wptService();3wpt.calcResponse(function(err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});
Using AI Code Generation
1var wpt = require('wpt');2var wpt = new wpt('API_KEY');3var options = {4 videoParams: {5 }6};7wpt.runTest(options, function(err, data) {8 if (err) {9 console.log('Error: ' + err);10 } else {11 console.log('Test status: ' + data.statusCode);12 console.log('Test ID: ' + data.data.testId);13 wpt.getTestResults(data.data.testId, function(err, data) {14 if (err) {15 console.log('Error: ' + err);16 } else {17 console.log('Test status: ' + data.statusCode);18 console.log('Test results: ' + JSON.stringify(data.data));19 }20 });21 }22});23var wpt = require('wpt');24var wpt = new wpt('API_KEY');25var options = {26 videoParams: {27 }28};29wpt.runTest(options, function(err, data) {30 if (err) {31 console.log('Error: ' + err);32 } else {33 console.log('Test status: ' + data.statusCode);34 console.log('Test ID: ' + data.data.testId);35 wpt.getTestResults(data.data.testId, function(err, data) {36 if (err) {37 console.log('Error: ' + err);38 } else {39 console.log('Test status: ' + data.statusCode);40 console.log('Test results: ' + JSON.stringify(data.data));41 }42 });43 }44});
Using AI Code Generation
1var wpt = require('./wpt.js');2var config = require('./config.js');3var wpt = new wpt(config.apiKey, config.host, config.port);4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});
Using AI Code Generation
1var wpt = require('wpt');2var options = {3};4wpt.runTest(options, function(err, data) {5 if (err) {6 console.log('Error: ' + err);7 } else {8 console.log('Test ID: ' + data.data.testId);9 wpt.getTestResults(data.data.testId, function(err, data) {10 if (err) {11 console.log('Error: ' + err);12 } else {13 console.log('Test Status: ' + data.data.testState);14 }15 });16 }17});
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!!