Best JavaScript code snippet using wpt
SearchableList.js
Source: SearchableList.js
1import _ from "../../lib/lodash";2export default class SearchableList {3 constructor(itemsList, resultsFormat = {type: 'text'}) {4 this.searching = false;5 this.items = itemsList;6 this.resultsFormat = resultsFormat;7 }8 preprocessParams(searchParameters) {9 // Can be overriden by subclasses10 return searchParameters;11 }12 postProcessStats() {13 // Can be overriden by subclasses14 return {}15 }16 incrementalSearch() {17 throw new Error('Method incrementalSearch should be implemented by SearchableList subclasses')18 }19 search(searchParameters, sendProgress) {20 this.lastSearch = searchParameters;21 this.searching = true;22 this.progressSent = false;23 let params = this.preprocessParams(searchParameters);24 // Cancel any ongoing search25 clearTimeout(this.nextTick);26 if(this.items.length === 0) return;27 let searchId = searchParameters;28 // Save the "current" search, on ignore any other previous partial or final result29 this.lastSearchId = searchId;30 const shouldPause = (lastIteration) => {31 let now = new Date();32 // Check if it is time to send partial results33 if (now - startTime > 35 && (!this.progressSent || now - this.lastProgressSent > 250)) {34 sendProgress('partialSearchResult', {35 matchSamples: searchState.sampleMatches.slice(0, 50),36 resultsFormat: this.resultsFormat,37 searchId: searchId,38 stats: {39 matchesCount: searchState.matchesIndex.length,40 totalCount: this.items.length41 }42 });43 this.lastProgressSent = now;44 this.progressSent = true;45 }46 // Every 50ms stop search to allow cancellation47 if (now - this.lastPause > 50) {48 this.lastPause = now;49 sendProgress("loadProgress", `Searching ${(lastIteration / this.items.length * 100).toFixed(0)}%`);50 return true;51 }52 };53 let startTime = new Date();54 this.lastPause = new Date();55 this.lastProgressSent = new Date();56 let searchState = {57 sampleMatches: [],58 matchesIndex: [],59 uniqueCount: 0,60 stats: {},61 };62 const resumeSearch = (startIndex) => {63 console.log(`Searching ${searchId} '${searchParameters}' from`, startIndex)64 let lastItemIndex = this.incrementalSearch(params, startIndex, searchState, shouldPause);65 if(lastItemIndex < this.items.length){66 this.nextTick = setTimeout(() => resumeSearch(lastItemIndex), 0);67 } else {68 // Post process search stats69 let otherStats = this.postProcessStats(searchState.stats);70 this.searching = false;71 const lastSearchTime = new Date().valueOf() - startTime;72 // TODO: Needed for download results. Stop doing this EVERY TIME73 // and only do it, searching again, if someone clicks export results74 // Then change `if (sampleMatches.length < 100000) {` to `< 2000`75 this.lastFilteredResults = searchState.matchesIndex;76 sendProgress('searchDone', {77 matchSamples: searchState.sampleMatches.slice(0, 2000),78 resultsFormat: this.resultsFormat,79 searchId: searchId,80 stats: {81 searchTime: lastSearchTime,82 matchesCount: searchState.matchesIndex.length,83 totalCount: this.items.length84 },85 extras: {86 ... otherStats,87 matchesCount: searchState.matchesIndex.length88 }89 });90 }91 };92 resumeSearch(0);93 }...
index.test.js
Source: index.test.js
1const {2 parseMatch,3 reduceMatches,4 sortPointsMap,5 decorateRank,6 formatTeamEntry,7 formatPointsUnitsLabel,8} = require('.')9describe('Match utils', () => {10 const sampleMatches = [11 'Lions 3, Snakes 3',12 'Tarantulas 1, FC Awesome 0',13 'Lions 1, FC Awesome 1',14 'Tarantulas 3, Snakes 1',15 'Lions 4, Grouches 0',16 ]17 const rankedTeams = {18 ['Tarantulas']: 6,19 ['Lions']: 5,20 ['FC Awesome']: 1,21 ['Snakes']: 1,22 ['Grouches']: 0,23 }24 it('should format singular point', () => {25 expect(formatPointsUnitsLabel(1)).toEqual('pt')26 })27 it('should format plural points', () => {28 expect(formatPointsUnitsLabel(2)).toEqual('pts')29 expect(formatPointsUnitsLabel(3)).toEqual('pts')30 })31 it('should parse matches', () => {32 expect(parseMatch('Tarantulas 1, FC Awesome 0')).toEqual([33 {34 teamName: 'Tarantulas',35 score: 1,36 },37 {38 teamName: 'FC Awesome',39 score: 0,40 },41 ])42 })43 it('should reduce matches', () => {44 expect(45 Array.from(46 reduceMatches([47 [48 {49 teamName: 'Tarantulas',50 score: 3,51 },52 {53 teamName: 'FC Awesome',54 score: 0,55 },56 ],57 ]).entries(),58 ),59 ).toStrictEqual([60 ['Tarantulas', 3],61 ['FC Awesome', 0],62 ])63 })64 it('should reduce sample matches', () => {65 const teams = reduceMatches(66 sampleMatches.map((matchText) => parseMatch(matchText)),67 )68 expect(Array.from(teams.keys())).toStrictEqual([69 'Lions',70 'Snakes',71 'Tarantulas',72 'FC Awesome',73 'Grouches',74 ])75 expect(teams.get('Lions')).toStrictEqual(5)76 expect(teams.get('Snakes')).toStrictEqual(1)77 expect(teams.get('Tarantulas')).toStrictEqual(6)78 expect(teams.get('FC Awesome')).toStrictEqual(1)79 })80 it('should format ranked teams', () => {81 const teams = reduceMatches(82 sampleMatches.map((matchText) => parseMatch(matchText)),83 )84 const formatted = decorateRank(sortPointsMap(teams)).map((entry) =>85 formatTeamEntry(entry),86 )87 expect(formatted).toStrictEqual([88 '1. Tarantulas, 6 pts',89 '2. Lions, 5 pts',90 '3. Snakes, 1 pt',91 '3. FC Awesome, 1 pt',92 '5. Grouches, 0 pts',93 ])94 })...
SearchableTextList.js
Source: SearchableTextList.js
1import _ from "../../lib/lodash";2import SearchableList from "./SearchableList";3export default class SearchableTextList extends SearchableList {4 preprocessParams(regex) {5 if(!regex) {6 regex = /.*/g;7 }8 return regex;9 }10 postProcessStats({topMatches}) {11 return {12 topMatches: _.mapValues(topMatches, groupTop => _.sortBy(_.toPairs(groupTop), "1").reverse())13 }14 }15 incrementalSearch(re, start, searchState, shouldPause) {16 const {matchesIndex, sampleMatches, stats} = searchState;17 stats.topMatches = stats.topMatches || {}18 let topMatches = stats.topMatches;19 for (let i = start; i < this.items.length; i++) {20 const text = this.items[i];21 let execRes = null;22 let matches = null;23 let lastIndex = null;24 while ((execRes = re.exec(text))) {25 // Prevent infinite loop if the regex does not consume characters26 if(execRes.index === lastIndex)27 break;28 for(let groupIndex = 0; groupIndex < execRes.length;groupIndex++) {29 let match = execRes[groupIndex] || "-";30 topMatches[groupIndex] = topMatches[groupIndex] || {};31 let matchCount = topMatches[groupIndex][match];32 if (!matchCount)33 searchState.uniqueCount++;34 topMatches[groupIndex][match] = (matchCount || 0) + 1;35 }36 (matches = matches || []).push(execRes)37 lastIndex = execRes.index;38 }39 if(matches) {40 matchesIndex.push(i);41 if (sampleMatches.length < 2000) {42 sampleMatches.push({item: text, matches});43 }44 }45 // Make periodical pauses to check search should not be cancelled46 // but check it only in some iterations for performance47 if (i % 1000 === 0 && shouldPause(i)) {48 return i;49 }50 }51 return this.items.length;52 }...
Using AI Code Generation
1var wpt = require('webpagetest');2var options = {3};4var test = new wpt('www.webpagetest.org', options.key);5 if (err) return console.error(err);6 console.log(data);7 test.getTestResults(data.data.testId, function(err, data) {8 if (err) return console.error(err);9 console.log(data);10 });11});12### wpt(host, key)13### wpt.runTest(url, options, callback)14### wpt.getTestResults(testId, callback)
Using AI Code Generation
1var wpt = require('wpt-api');2var client = new wpt('API_KEY');3var params = {4};5client.sampleMatches(params, function(err, data) {6 if (err) {7 return console.error(err);8 }9 console.log(data);10});11client.getTestResults('201605_3E_1A6', function(err, data) {12 if (err) {13 return console.error(err);14 }15 console.log(data);16});
Using AI Code Generation
1const wptApi = require('./wptApi.js');2wptApi.sampleMatches('test');3module.exports = {4 sampleMatches: function (test) {5 console.log(test);6 },7};8exports.sampleMatches = function (test) {9 console.log(test);10};11exports.sampleMatches = (test) => {12 console.log(test);13};14exports.sampleMatches = test => console.log(test);15module.exports.sampleMatches = test => console.log(test);16const wptApi = require('./wptApi.js');17wptApi.sampleMatches('test');18module.exports = {19 sampleMatches: function (test) {20 console.log(test);21 },22};23exports.sampleMatches = function (test) {24 console.log(test);25};26exports.sampleMatches = (test) => {27 console.log(test);28};29exports.sampleMatches = test => console.log(test);30module.exports.sampleMatches = test => console.log(test);31const wptApi = require('./wptApi.js');32wptApi.sampleMatches('test');33module.exports = {34 sampleMatches: function (test) {35 console.log(test);36 },37};
Using AI Code Generation
1var wptree = require('wptree');2var samples = ['apple','banana','orange','grapes','pineapple','mango','watermelon','papaya','guava','kiwi','peach','coconut','strawberry','cherry','lemon','grapefruit','melon','plum','lychee','blueberry','fig','pomegranate','apricot','pears','avocado'];3var sampleTree = new wptree(samples);4var matches = sampleTree.sampleMatches('app', 3);5console.log(matches);6var wptree = require('wptree');7var samples = ['apple','banana','orange','grapes','pineapple','mango','watermelon','papaya','guava','kiwi','peach','coconut','strawberry','cherry','lemon','grapefruit','melon','plum','lychee','blueberry','fig','pomegranate','apricot','pears','avocado'];8var sampleTree = new wptree(samples);9var matches = sampleTree.sampleMatches('app', 3);10console.log(matches);11var wptree = require('wptree');12var samples = ['apple','banana','orange','grapes','pineapple','mango','watermelon','papaya','guava','kiwi','peach','coconut','strawberry','cherry','lemon','grapefruit','melon','plum','lychee','blueberry','fig','pomegranate','apricot','pears','avocado'];13var sampleTree = new wptree(samples);14var matches = sampleTree.sampleMatches('app', 3);15console.log(matches);16var wptree = require('wptree');
Check out the latest blogs from LambdaTest on this topic:
Automating testing is a crucial step in the development pipeline of a software product. In an agile development environment, where there is continuous development, deployment, and maintenance of software products, automation testing ensures that the end software products delivered are error-free.
In an ideal world, you can test your web application in the same test environment and return the same results every time. The reality can be difficult sometimes when you have flaky tests, which may be due to the complexity of the web elements you are trying to perform an action on your test case.
So, now that the first installment of this two fold article has been published (hence you might have an idea of what Agile Testing is not in my opinion), I’ve started feeling the pressure to explain what Agile Testing actually means to me.
Agile has unquestionable benefits. The mainstream method has assisted numerous businesses in increasing organizational flexibility as a result, developing better, more intuitive software. Distributed development is also an important strategy for software companies. It gives access to global talent, the use of offshore outsourcing to reduce operating costs, and round-the-clock development.
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!!