Best JavaScript code snippet using best
runner-stream.ts
Source:runner-stream.ts
1/*2 * Copyright (c) 2019, salesforce.com, inc.3 * All rights reserved.4 * SPDX-License-Identifier: MIT5 * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT6*/7import path from "path";8import { isInteractive as globaIsInteractive } from "@best/utils";9import chalk from "chalk";10import trimPath from "./utils/trim-path";11import countEOL from "./utils/count-eod";12import { ProxiedStream, proxyStream } from "./utils/proxy-stream";13import {14 BenchmarkRuntimeConfig,15 RunnerStream,16 BenchmarksBundle,17 BenchmarkUpdateState,18} from "@best/types";19enum State {20 QUEUED = 'QUEUED',21 RUNNING = 'RUNNING',22 DONE = 'DONE',23 ERROR = 'ERROR',24}25interface BenchmarkStatus { state: State; displayPath: string; projectName: string, progress?: BenchmarkProgress }26type AllBencharkRunnerState = Map<string, BenchmarkStatus>27interface BenchmarkProgress {28 executedIterations: number,29 estimated: number,30 runtime: number,31 avgIteration: number,32}33const STATE_ANSI = {34 RUNNING: chalk.reset.inverse.yellow.bold(` ${State.RUNNING} `),35 QUEUED: chalk.reset.inverse.gray.bold(` ${State.QUEUED} `),36 ERROR: chalk.reset.inverse.redBright.bold(` ${State.ERROR} `),37 DONE: chalk.reset.inverse.green.bold(` ${State.DONE} `),38};39const INIT_MSG = '\n Running benchmarks... \n\n';40const PROGRESS_TEXT = chalk.dim('Progress running: ');41const PROGRESS_BAR_WIDTH = 40;42const DEFAULT_TIMEOUT = 60;43function printState(state: State) {44 return STATE_ANSI[state];45}46function printDisplayName(displayPath: string, overflow: number) {47 const dirname = overflow ? trimPath(path.dirname(displayPath), overflow) : path.dirname(displayPath);48 const basename = path.basename(displayPath);49 return chalk.dim(dirname + path.sep) + chalk.bold(basename);50}51function printProjectName(projectName: string) {52 return ' ' + chalk.reset.cyan.dim(`(${projectName})`);53}54function calculateBenchmarkProgress(progress: BenchmarkUpdateState, { iterations, maxDuration, minSampleCount }: BenchmarkRuntimeConfig): BenchmarkProgress {55 const { executedIterations, executedTime } = progress;56 const avgIteration = executedTime / executedIterations;57 const runtime = parseInt((executedTime / 1000) + '', 10);58 let estimated: number;59 if (iterations) {60 estimated = Math.round(iterations * avgIteration / 1000) + 1;61 } else if (avgIteration * minSampleCount > maxDuration) {62 estimated = Math.round(minSampleCount * avgIteration / 1000) + 1;63 } else {64 estimated = maxDuration / 1000;65 }66 return {67 executedIterations,68 estimated,69 runtime,70 avgIteration,71 };72}73function printProgressBar(runTime: number, estimatedTime: number, width: number) {74 // If we are more than one second over the estimated time, highlight it.75 const renderedTime = estimatedTime && runTime >= estimatedTime + 1 ? chalk.bold.yellow(runTime + 's') : runTime + 's';76 let time = chalk.bold(`Time:`) + ` ${renderedTime}`;77 if (runTime < estimatedTime) {78 time += `, estimated ${estimatedTime}s`;79 }80 // Only show a progress bar if the test run is actually going to take some time81 if (estimatedTime > 2 && runTime < estimatedTime && width) {82 const availableWidth = Math.min(PROGRESS_BAR_WIDTH, width);83 const length = Math.min(Math.floor(runTime / estimatedTime * availableWidth), availableWidth);84 if (availableWidth >= 2) {85 time += '\n' + chalk.green('â').repeat(length) + chalk.white('â').repeat(availableWidth - length);86 }87 }88 return time;89}90export default class RunnerOutputStream implements RunnerStream {91 stdoutColumns: number;92 stdoutWrite: Function;93 isInteractive: boolean;94 _streamBuffer: string = '';95 _state: AllBencharkRunnerState;96 _innerLog: string = '';97 _scheduled: NodeJS.Timeout | null = null;98 _proxyStream: ProxiedStream;99 constructor(buildConfig: BenchmarksBundle[], stream: NodeJS.WriteStream, isInteractive?: boolean) {100 this.stdoutColumns = stream.columns || 80;101 this.stdoutWrite = stream.write.bind(stream);102 this.isInteractive = isInteractive !== undefined ? isInteractive : globaIsInteractive;103 this._state = this.initState(buildConfig);104 this._proxyStream = proxyStream(stream, this.isInteractive);105 }106 initState(buildConfigs: BenchmarksBundle[]): AllBencharkRunnerState {107 return buildConfigs.reduce((state: AllBencharkRunnerState, benchmarkBundle: BenchmarksBundle): AllBencharkRunnerState => {108 benchmarkBundle.benchmarkBuilds.forEach(({ benchmarkEntry, benchmarkSignature, projectConfig: { projectName }}) => {109 state.set(benchmarkSignature, {110 projectName,111 state: State.QUEUED,112 displayPath: benchmarkEntry,113 });114 });115 return state;116 }, new Map());117 }118 clearBufferStream() {119 let buffer = this._streamBuffer;120 const lines = countEOL(buffer);121 if (lines) {122 buffer = '\r\x1B[K\r\x1B[1A'.repeat(lines);123 }124 if (this.isInteractive) {125 // clear last line126 this.stdoutWrite('\x1b[999D\x1b[K');127 }128 this.stdoutWrite(buffer);129 this._streamBuffer = '';130 }131 writeBufferStream(str: string) {132 this._streamBuffer += str;133 this.stdoutWrite(str);134 }135 updateRunnerState(benchmarkSignature: string, state: State) {136 const stateConfig = this._state.get(benchmarkSignature);137 if (!stateConfig) {138 throw new Error(`Unknown benchmark build started (${benchmarkSignature})`);139 }140 if (stateConfig.state !== State.ERROR) {141 stateConfig.state = state;142 }143 }144 scheduleUpdate(time?: number, fn?: Function) {145 if (!this._scheduled) {146 this._scheduled = setTimeout(() => {147 fn ? fn() : this.updateStream();148 this._scheduled = null;149 }, time || DEFAULT_TIMEOUT);150 }151 }152 printBenchmarkState({ state, projectName, displayPath }: { state: State, projectName: string, displayPath: string }) {153 const columns = this.stdoutColumns;154 const overflow = columns - (state.length + projectName.length + displayPath.length + /* for padding */ 14);155 const hasOverflow = overflow < 0;156 const ansiState = printState(state);157 const ansiProjectName = printProjectName(projectName);158 const ansiDisplayname = printDisplayName(displayPath, hasOverflow ? Math.abs(overflow): 0);159 return `${ansiState} ${ansiProjectName} ${ansiDisplayname}\n`;160 }161 printProgress(progress: BenchmarkProgress, { displayPath }: BenchmarkStatus): string {162 const benchmarkName = chalk.bold.black(path.basename(displayPath));163 return [164 `\n${PROGRESS_TEXT} ${benchmarkName}`,165 chalk.bold.black('Avg iteration: ') + progress.avgIteration.toFixed(2) + 'ms',166 chalk.bold.black('Completed iterations: ') + progress.executedIterations,167 printProgressBar(progress.runtime, progress.estimated, 40)168 ].join('\n') + '\n\n';169 }170 updateStream() {171 let buffer = INIT_MSG;172 let progressStr: string = '';173 for (const benchmarkState of this._state.values()) {174 const { state, displayPath, projectName, progress } = benchmarkState;175 buffer += this.printBenchmarkState({ state, displayPath, projectName });176 if (state === State.RUNNING && progress) {177 progressStr += this.printProgress(progress, benchmarkState);178 }179 }180 const streamProxyBuffer = this._proxyStream.readBuffer();181 streamProxyBuffer ? `Buffered console logs:\n ${streamProxyBuffer}` : '';182 this.clearBufferStream();183 this.writeBufferStream(buffer + progressStr + streamProxyBuffer);184 }185 log(message: string) {186 this._innerLog = message;187 if (this.isInteractive) {188 this.scheduleUpdate();189 } else {190 this.stdoutWrite(` :: ${message}\n`);191 }192 }193 _clearTimeout() {194 if (this._scheduled) {195 clearTimeout(this._scheduled);196 this._scheduled = null;197 }198 }199 // -- Lifecycle200 onBenchmarkStart(benchmarkSignature: string) {201 this.updateRunnerState(benchmarkSignature, State.RUNNING);202 if (this.isInteractive) {203 this.scheduleUpdate();204 } else {205 const benchmarkState = this._state.get(benchmarkSignature);206 if (benchmarkState) {207 this.stdoutWrite(this.printBenchmarkState(benchmarkState));208 }209 }210 }211 onBenchmarkEnd(benchmarkSignature: string) {212 this.updateRunnerState(benchmarkSignature, State.DONE);213 this._innerLog = '';214 const benchmarkState = this._state.get(benchmarkSignature);215 if (benchmarkState) {216 if (this.isInteractive) {217 if (benchmarkState.state === State.ERROR) {218 this.updateStream();219 this.stdoutWrite('\n');220 } else {221 this.scheduleUpdate();222 }223 } else {224 this._clearTimeout();225 this.stdoutWrite(this.printBenchmarkState(benchmarkState) + '\n');226 }227 }228 }229 onBenchmarkError(benchmarkSignature: string) {230 this.updateRunnerState(benchmarkSignature, State.ERROR);231 }232 updateBenchmarkProgress(benchmarkSignature: string, updatedBenchmarkState: BenchmarkUpdateState, runtimeOpts: BenchmarkRuntimeConfig) {233 const progress = calculateBenchmarkProgress(updatedBenchmarkState, runtimeOpts);234 const benchmarkState = this._state.get(benchmarkSignature);235 benchmarkState!.progress = progress;236 const { executedIterations, avgIteration, estimated, runtime } = progress;237 const runIter = executedIterations.toString().padEnd(5, " ");238 const avgIter = `${avgIteration.toFixed(2)}ms`.padEnd(10, " ");239 const remaining = estimated - runtime;240 if (this.isInteractive) {241 this.scheduleUpdate();242 } else {243 this.scheduleUpdate(2500, () => {244 this.stdoutWrite(245 ` :: ${benchmarkState!.displayPath} > ran: ${runIter} | avg: ${avgIter} | remainingTime: ${remaining}s \n`246 );247 });248 }249 }250 init() {251 if (this.isInteractive) {252 this.updateStream();253 } else {254 this.stdoutWrite(INIT_MSG);255 }256 }257 finish() {258 this._clearTimeout();259 this._proxyStream.unproxyStream();260 if (this.isInteractive) {261 this.updateStream();262 } else {263 this.stdoutWrite('\n');264 }265 }...
gcd.js
Source:gcd.js
1var { log, max, ceil, sqrt, PI } = Math;2function gcd(x, y) {3 var iter = 0;4 if(y > x) {5 var t = x;6 x = y;7 y = t;8 }9 while(y > 0) {10 var t = x;11 x = y;12 y = t % y;13 iter += 1;14 }15 return [x, iter];16}17function gcdIterMax(x, y) {18 var N = max(x, y);19 var maxIter = ceil(log(N * sqrt(5)) / log((1 + sqrt(5)) / 2)) - 2;20 return maxIter;21}22function gcdIterAvg(x, y) {23 var N = max(x, y);24 var avgIter = 12 * log(2) / (PI * PI) * log(N);25 return avgIter;26}27export function iterations(xMin, xMax, yMin, yMax) {28 const surface = [];29 for(let y = yMin; y < yMax; y++) {30 const plane = [];31 surface.push(plane);32 for(let x = xMin; x < xMax; x++) {33 plane.push(gcd(x, y)[1]);34 }35 }36 return surface;37}38export function maxIterations(xMin, xMax, yMin, yMax) {39 const surface = [];40 for(let y = yMin; y < yMax; y++) {41 const plane = [];42 surface.push(plane);43 for(let x = xMin; x < xMax; x++) {44 plane.push(gcdIterMax(x, y));45 }46 }47 return surface;48}49export function avgIterations(xMin, xMax, yMin, yMax) {50 const surface = [];51 for(let y = yMin; y < yMax; y++) {52 const plane = [];53 surface.push(plane);54 for(let x = xMin; x < xMax; x++) {55 plane.push(gcdIterAvg(x, y));56 }57 }58 return surface;...
Using AI Code Generation
1var BestTimeToBuyAndSellStock = require('./BestTimeToBuyAndSellStock.js');2var b = new BestTimeToBuyAndSellStock([7,1,5,3,6,4]);3console.log(b.avgIter());4var BestTimeToBuyAndSellStock = require('./BestTimeToBuyAndSellStock.js');5var b = new BestTimeToBuyAndSellStock([7,6,4,3,1]);6console.log(b.avgIter());7var BestTimeToBuyAndSellStock = require('./BestTimeToBuyAndSellStock.js');8var b = new BestTimeToBuyAndSellStock([2,4,1]);9console.log(b.avgIter());10var BestTimeToBuyAndSellStock = require('./BestTimeToBuyAndSellStock.js');11var b = new BestTimeToBuyAndSellStock([1,2]);12console.log(b.avgIter());13var BestTimeToBuyAndSellStock = require('./BestTimeToBuyAndSellStock.js');14var b = new BestTimeToBuyAndSellStock([2,1]);15console.log(b.avgIter());16var BestTimeToBuyAndSellStock = require('./BestTimeToBuyAndSellStock.js');17var b = new BestTimeToBuyAndSellStock([2,4,1]);18console.log(b.avgIter());19var BestTimeToBuyAndSellStock = require('./BestTimeToBuyAndSellStock.js');20var b = new BestTimeToBuyAndSellStock([1,2,4,2,5
Using AI Code Generation
1var BestAverage = require('./BestAverage.js');2var arr1 = [1,2,3,4,5,6,7,8,9,10];3var arr2 = [1,2,3,4,5,6,7,8,9,10];4var arr3 = [1,2,3,4,5,6,7,8,9,10];5var arr4 = [1,2,3,4,5,6,7,8,9,10];6var arr5 = [1,2,3,4,5,6,7,8,9,10];7var arr6 = [1,2,3,4,5,6,7,8,9,10];8var arr7 = [1,2,3,4,5,6,7,8,9,10];9var arr8 = [1,2,3,4,5,6,7,8,9,10];10var arr9 = [1,2,3,4,5,6,7,8,9,10];11var arr10 = [1,2,3,4,5,6,7,8,9,10];12var test = new BestAverage();13console.log(test.avgIter(arr1));14console.log(test.avgIter(arr2));15console.log(test.avgIter(arr3));16console.log(test.avgIter(arr4));17console.log(test.avgIter(arr5));18console.log(test.avgIter(arr6));19console.log(test.avgIter(arr7));20console.log(test.avgIter(arr8));21console.log(test.avgIter(arr9));22console.log(test.avgIter(arr10));
Using AI Code Generation
1var BestAverage = require('./BestAverage.js');2var bestAvg = new BestAverage();3var avg = bestAvg.avgIter(1,2,3,4,5);4console.log(avg);5var BestAverage = require('./BestAverage.js');6var bestAvg = new BestAverage();7var avg = bestAvg.avgIter(1,2,3,4,5,6,7,8);8console.log(avg);9var BestAverage = require('./BestAverage.js');10var bestAvg = new BestAverage();11var avg = bestAvg.avgIter(1,2,3,4,5,6,7,8,9);12console.log(avg);13var BestAverage = require('./BestAverage.js');14var bestAvg = new BestAverage();15var avg = bestAvg.avgIter(1,2,3,4,5,6,7,8,9,10);16console.log(avg);17var BestAverage = require('./BestAverage.js');18var bestAvg = new BestAverage();19var avg = bestAvg.avgIter(1,2,3,4,5,6,7,8,9,10,11,12,13);20console.log(avg);21var BestAverage = require('./BestAverage.js');22var bestAvg = new BestAverage();23var avg = bestAvg.avgIter(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);24console.log(avg);25var BestAverage = require('./BestAverage.js');26var bestAvg = new BestAverage();27var avg = bestAvg.avgIter(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);28console.log(avg);
Using AI Code Generation
1var BestAvg = require('./bestAvg');2var avg = new BestAvg();3avg.add(100);4avg.add(90);5avg.add(80);6avg.add(70);7avg.add(60);8avg.add(50);9avg.add(40);10avg.add(30);11avg.add(20);12avg.add(10);
Using AI Code Generation
1var BestGrades = require('./BestGrades');2var grades = new BestGrades();3grades.add(90);4grades.add(100);5grades.add(95);6grades.add(85);7grades.add(80);8grades.add(70);
Using AI Code Generation
1var BestAvg = require('./BestAvg');2var avg = new BestAvg();3var avg1 = avg.avgIter([1, 5, 8, 3, 7, 9, 2, 4, 6]);4console.log(avg1);5var BestAvg = require('./BestAvg');6var avg = new BestAvg();7var avg1 = avg.avgRec([1, 5, 8, 3, 7, 9, 2, 4, 6]);8console.log(avg1);9var BestAvg = require('./BestAvg');10var avg = new BestAvg();11var avg1 = avg.avgRec([1, 5, 8, 3, 7, 9, 2, 4, 6]);12console.log(avg1);13var BestAvg = require('./BestAvg');14var avg = new BestAvg();15var avg1 = avg.avgRec([1, 5, 8, 3, 7, 9, 2, 4, 6]);16console.log(avg1);17var BestAvg = require('./BestAvg');18var avg = new BestAvg();19var avg1 = avg.avgRec([1, 5, 8, 3, 7, 9, 2, 4, 6]);20console.log(avg1);21var BestAvg = require('./BestAvg');22var avg = new BestAvg();23var avg1 = avg.avgRec([1, 5, 8, 3, 7, 9, 2, 4, 6]);24console.log(avg1);25var BestAvg = require('./BestAvg');26var avg = new BestAvg();27var avg1 = avg.avgRec([1, 5, 8, 3, 7, 9, 2, 4, 6]);
Using AI Code Generation
1var BestPathFinder = require('./BestPathFinder.js');2var bestPathFinder = new BestPathFinder();3var gridSize = 10;4var numIterations = 1000;5var numIterationsNeeded = 0;6var numIterationsNeeded = 0;7var numPathsFound = 0;8var numPathsNotFound = 0;9var numIterationsNeeded = 0;10var numPathsFound = 0;11var numPathsNotFound = 0;12for (var i = 1; i <= numIterations; i++) {13 var start = [Math.floor(Math.random() * gridSize), Math.floor(Math.random() * gridSize)];14 var end = [Math.floor(Math.random() * gridSize), Math.floor(Math.random() * gridSize)];15 var path = bestPathFinder.findPath(start, end, gridSize);16 if (path) {17 numPathsFound++;18 numIterationsNeeded += path.length;19 } else {20 numPathsNotFound++;21 }22}23var avgIterations = numIterationsNeeded / numPathsFound;24console.log("Average number of iterations needed to find a path: " + avgIterations);25var avgIterations = numIterationsNeeded / numPathsFound;26console.log("Average number of iterations needed to find a
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!!