Best JavaScript code snippet using playwright-internal
index.js
Source: index.js
1/********************************* 2 * Intro3 * 4************************************/5// function someFunction(input) {6// let t0 = performance.now(); //O(1)7// let x = 'foo'; //O(1)8// let y = 'bar'; //O(1)9// let sum = 0;10// for(let i = 0; i < input.length; i++) { //O(n)11// sum+= i; //O(1)12// someOtherFunction(); //O(1)13// }14// let t1 = performance.now(); //O(1)15// console.log(t1 - t0 + ' miliseconds'); //O(2)16// return sum; //O(1)17// }18// function someOtherFunction() {19// console.log('Executed');20// }21// const array = new Array(5000).fill('data');22// console.log(array);23// console.log(someFunction(array));24// //therefore total O of someFunction is O(1 + 1 + 1 + n * (1 + 2 + 1)) = O(3 + 2n) 25// //the constants get removed usually so it's O(n)26// //if you'd like you can also include i++ but doesn't change the result if we reduce to O(n)27/********************************* 28 * Nesting29 * 30************************************/31// const array = [];32// for(let i = 0; i < 10; i++) {33// array[i] = i;34// }35// function logPairs(input) {36// for(let j = 0; j < input.length; j++) {37// for(let k = 0; k < input.length; k++) {38// console.log(array[j], array[k]);39// }40// }41// }42 43// logPairs(array);44//So for input function will be executed n times, and for each of those times another function is executed n times45//Like multiplying constants this time we will mutliply n by how many operations are there inside the inner function. And there are n operations46//So naturally that is O(n*n) = O(n^2)47/********************************* 48 * Different terms49 * 50************************************/51// //what if there are different terms, that is - different inputs of variable size52// const nums1 = [1, 5, 3, 10, 500];53// const nums2 = [50, 1, 2, 4];54// function multiplyFactors(inputX, inputY) {55// inputX.forEach(function(factor1) {56// inputY.forEach(function(factor2) {57// console.log(`${factor1} * ${factor2} = ${factor1 * factor2}`);58// });59// });60// }61// multiplyFactors(nums1, nums2);62// //as we see we can't just say it's O(n^2) because they're 2 different unknown size inputs. So it will be63// //O(n * m) which we could say is similar to O(n^2) - if we wanted to be specific then64// //of course if m == n then O(n*m) == O(n^2) 65// //if m > n then O(n*m) > O(n^2)66// //if n > m then O(n*m) < O(n^2)67/********************************* 68 * Recursion69 * 70************************************/71//Sum72//set up function test to assert73// const assert = {74// equal: function(result1, result2) {75// if(result1 === result2) {76// console.log(true);77// return; 78// } 79// console.log(false);80// }81// }82// assert.equal(sum(10, 89, 4), 103);83// console.log(sum(10,89,4));84// function sum(...args) {85// if(args.length == 1) return args[0];86// let currentVal = args.splice(0,1)[0];87// return currentVal + sum(...args);88// }89// //exponentiation90// assert.equal(exponent(2, 8), 64);91// function exponent(exp, base) {92// if(exp == 0) return 1;93// return base * exponent(exp-1, base);94// }95// //Fibonacci(n) returning array of sums96// assert.equal(fibonacci(5), [0, 1, 1, 2, 3]);97// function fibonacci(n) {98// if(n == 1 ) {99// let arr = [];100// arr.push(0);101// return arr;102// }103// if(n == 2) {104// let arr = fibonacci(n-1);105// arr.push(1);106// return arr;107// }108// let arr = fibonacci(n-1);109// arr.push(arr[n-2] + arr[n-3]);110// return arr;111// }112// //will not work until assert equal arrays(based on values) is implemented113//Get an exclusive range of values and return array114// assert.equal(range(3, 9), [4, 5, 6, 7, 8]);115// function range(lower, upper) {116// let diff = upper - lower;117// if(diff < 2) return;118// if(diff == 2) return [lower+1];119// let arr = range(lower, upper-1);120// arr.push(upper-1);121// return arr;122// }123/********************************* 124 * Sorting125 * 126************************************/127//Bubble sort128// let unsorted = 129// [9, 10, 3, 50, 11, 2, 5];130// function BubbleSort(arr) {131// for(let i = 0; i < arr.length; i++) {132// for(let j = 0; j < arr.length; j++) {133// if(arr[j] > arr[j+1]) {134// let temp = arr[j];135// arr[j] = arr[j+1];136// arr[j+1] = temp;137// }138// }139// }140// }141// BubbleSort(unsorted);142// console.log(unsorted);143/**144 * select sort 145 */146// let unsorted = 147// [9, 10, 3, 50, 11, 2, 5, 30, 1, 2];148// function SelectionSort(arr) {149// for(let i = 0; i < arr.length -1; i++) {150// let tempMin = arr[i];151// let index = arr[i];152// for(let j = i+1; j < arr.length -1; j++) {153// if(arr[j] < tempMin) {154// tempMin = arr[j];155// index = j;156// }157// }158// if(i != index) {159// let temp = arr[i];160// arr[i] = arr[index];161// arr[index] = temp;162// }163// }164// }165// SelectionSort(unsorted);166// console.log(unsorted);167/**168 * 169 * Binary search170 */171 ////Search for a value in an array - with O(log N) time complexity and O(1) space complexity172// const arr = [0, 1, 5, 10, 15, 30, 55, 100, 101, 102, 105, 205, 210, 215, 220, 356, 452];173 /**174 * Get length of array175 * Figure out where the middle element is arr.length / 2176 * there must be a max nr of searches according to the formula searches = log2(arr.length)177 * check if that's the value we're searching for178 * if not halve the middle 179 * value we're searching for is < or >180 * repeat until boundaries intersect181 */182// function binarySearch(arr, value) {183// let middle, upperBoundary, lowerBoundary;184// lowerBoundary = 0;185// upperBoundary = arr.length - 1;186// while(lowerBoundary <= upperBoundary) {187// middle = Math.floor((upperBoundary + lowerBoundary) / 2);188// if(value > arr[middle]) {189// lowerBoundary = middle + 1;190// } else if(value < arr[middle]) {191// upperBoundary = middle - 1;192// }193// if(value === arr[middle]) {194// return value;195// }196// } 197// return -1;198// }199// console.log(binarySearch(arr, 9));200/**201 * Quicksort 202 * Original array remains, output = sorted array203 * (O(n) space and O(N logN) time complexity)204 * O(n) space is okay because in this case we're making a new array and leaving the old array205 * Naturally we must take up new O(n) space206 */207/**208 * mergeSort(arr, 0, 8) -> mergeSort(arr, 0, 4), 209 * */210// //outer function to receive an arr211// function mergeSort(arr) {212// return mergeSort(arr, 0, arr.length - 1);213// //inner function to implement recursion and pass the arr's parameters214// //we could instead just have this as the outer func and have to pass 0 and arr.length-1 215// //but this way the user will just pass an array and not worry about all that216// function mergeSort(arr, leftIndex, rightIndex) {217// //we need arraySize because we don't determine the size of the initial array218// //instead we look at the size of the "chunk" which was sent by looking at 219// //left and right index220// let arrSize = rightIndex - leftIndex + 1;221// if(arrSize > 0) {222// if(arrSize == 1 ) return [arr[leftIndex]];223// if(arrSize == 2) {224// if(arr[leftIndex] > arr[rightIndex]) {225// return [arr[rightIndex], arr[leftIndex]];226// } return [arr[leftIndex], arr[rightIndex]];227// }228// let leftHalfRightBoundary = leftIndex + Math.floor((rightIndex - leftIndex) / 2);229// let rightHalfLeftBoundary = leftHalfRightBoundary + 1;230// let leftSortedHalf = mergeSort(arr, leftIndex, leftHalfRightBoundary);231// let rightSortedHalf = mergeSort(arr, rightHalfLeftBoundary, rightIndex);232// //after we return the sorted halves, we need to merge them233// sortedArray = mergeSortedHalves(leftSortedHalf, rightSortedHalf);234// return sortedArray;235// } 236// }237// }238// //merge 2 already sorted arrays239// //sorting logic: start both from beginning index(0)240// //whichever is smaller, pop it from the array and move it to the sorted array241// //increment counter in the array in which the element was popped242// //if at some point any array is left without elements243// //then if there are remaining elements in the other array, just append them244// //return the result245// function mergeSortedHalves(leftHalf, rightHalf) {246// // left and right counter indicate how far off we are 247// // in traversing a sorted array248// let leftCounter = 0; 249// let rightCounter = 0;250// let leftHalfSize = leftHalf.length;251// let rightHalfSize = rightHalf.length;252// //this will represent the merged sorted array253// let newSortedArray = [];254// //each time we "pop" an element from an array, we increase the counter255// //if at any time the counter becomes as big as the size of the array256// //that naturally means we sorted all elements from that array. at that point, we exit the loop257// while((leftCounter < leftHalfSize) && (rightCounter < rightHalfSize)) {258// if(leftHalf[leftCounter] < rightHalf[rightCounter]) {259// newSortedArray.push(leftHalf[leftCounter]);260// leftCounter++;261// } else {262// newSortedArray.push(rightHalf[rightCounter]);263// rightCounter++;264// }265// }266// //how do we know if there are remaining elements once at least one of the arrays267// //is completely pushed into the new array? check the counter for that half - if it's smaller than268// //the corresponding half size, that means there are elements left269// if(rightCounter < rightHalfSize) {270// //so there are remaining elements, how to know where to start appending from?271// //coincidentally, the counter will indicate the index where we will start272// //we will continue as long as counter 273// for(let i = rightCounter; i < rightHalfSize; i++) {274// newSortedArray.push(rightHalf[i]);275// }276// //do the same if there are remaning elements in the left half277// } else if(leftCounter < leftHalfSize) {278// for(let i = leftCounter; i < leftHalfSize; i++) {279// newSortedArray.push(leftHalf[i]);280// }281// }282// //finally, return the sorted array283// return newSortedArray;284 285// }286// //testing mergeSortedArrays function287// let arr1 = [10];288// let arr2 = [5];289// console.log(mergeSortedHalves(arr1, arr2));290// // test mergeSort291// const arr = [5, 10, 30, 2, 8, 1, 6, 0, 4];292// console.log(mergeSort(arr));293// console.log(arr);294/**295 * What is the time complexity of pushing an element to an array?296 * Take into account different kinds of arrays we might encounter297 * pushing => append to the end298 */299/**300 * What is the worst runtime(time complexity) of calculating all possible301 * routes between 2 nodes in a graph302 */303/**304 * Calculate the time complexity of the following function305 * 306 */307// function intersection(intArray1, intArray2) {308// mergeSort(intArray2);309// let commonNumbers = 0;310// for(let number of intArray1) {311// if(binarySearch(intArray2, number)) commonNumbers++;312// }313// return commonNumbers;314// }315/**316 * What is the time complexity of recursively317 * calculating fibonacci(n)?318 * 319 * How to optimize it?320 */321// function fibonacci(n) {322// if(n == 0) return -1;323// if(n == 1) return 0;324// if(n == 2) return 1;325// return fibonnaci(n-1) + fibonacci(n-2);326// }327 /**328* What is the time complexity of the following function?329* Assume n is a positive integer330*/331// function calculate(n) 332// { 333// for (let i = 1; i <= n; i++) 334// { 335// for (let j = 1; j < n; j += i) 336// { 337// // Some O(1) task 338// } 339// } 340// } 341//To do today: code singly, doubly circular and non-circular linked lists342//implement stack and queue with linked list and array343//implement binary search tree - insert, remove and search344//implement heap tree - each node at nth level has higher values than nodes at nth+1 level 345//implement inorder, postorder, preorder and level order traversals on each346// class SinglyLinkedList {347// constructor() {348// this.length = 0;349// this.head = null;350// this.tail = null;351// }352// _traverse(numberOfNodes) {353// //traverse the required number of nodes354// //if the number of nodes to traverse is higher than the actual 355// //length, just go to tail356// //this will shorten time complexity of appending to end357// let traverseNode;358// let possibleNodeTraversals = this.length - 1;359// if(possibleNodeTraversals <= numberOfNodes) {360// //saves us the time needed to traverse if we'll just end up at tail to O(1)361// //in that case just go to tail362// traverseNode = this.tail;363// } else {364// traverseNode = this.head;365// while(numberOfNodes > 0) {366// numberOfNodes--;367// traverseNode = traverseNode.next;368// }369// }370// //return the reference of node which is at the required destionation371// return traverseNode;372// }373// insert(value) {374// //just insert value, so it is at the beginning375// let newNode = {376// data : value,377// next : this.head378// }379// this.head = newNode;380// this.length++;381// //if this was also the first node, then just set tail to also be head382// if(this.length === 1) {383// this.tail = this.head;384// }385// }386// remove() {387// //just remove so remove from beginning388// if(this.head) {389// this.head = this.head.next;390// this.length--;391// }392// }393// insertAt(position, value) {394// //if there are no elements just do the default insert395// if(this.length === 0) {396// this.insert(value);397// return;398// }399// //insert at certain position400// //for this purpose, position should be > 1401// //position 1 indicates after inserting, the node which we inserted will be Node 1(first node is #1)402// //let's get to the right place with the function we implemented403// //we need to be ahead of the place we're traversing. so number of nodes to traverse is 404// //equal to position - 1405// let traverseNode = this._traverse(position - 2);406// let newNode = {407// data : value,408// next : null409// }410// if(traverseNode.next) {411// //if we're not at end412// newNode.next = traverseNode.next;413// traverseNode.next = newNode;414// } else {415// //we're at tail416// traverseNode.next = newNode;417// this.tail = newNode;418// }419// this.length++;420// }421// removeAt(position) {422// //if it's empty or just 1 element do the normal remove or notify about empty list423// if(this.length === 0) {424// console.log(`Can't remove from empty list`);425// return;426// }427// if(this.length === 1) {428// this.remove();429// return;430// }431// //position indicates the number of node to remove432// //so 2 would remove the 2nd, 4 the 4th node etc.433// //we have to traverse a bit differently here434// //to always end up one node ahead of the place we're removing435// let traversals;436// if(position > this.length) {437// traversals = this.length - 2;438// } {439// traversals = position - 2;440// }441// let traverseNode = this._traverse(traversals);442// //we're finally at the required place443// //we have to also see if the next node is tail or not444// //if it's tail we'll set the tail to the previous node of the tail445// //otherwise we have to make a connection between the adjacent nodes of the node we are removing446// if(traverseNode.next) {447// traverseNode.next = traverseNode.next.next;448// } else {449// traverseNode.next = null;450// this.tail = traverseNode;451// }452// }453// print() {454// console.log('Printing linked list ------');455// if(this.length === 0) {456// console.log('***List empty***');457// return;458// };459// let traverseNode = this.head;460// console.log(this.head.data);461// while(traverseNode.next) {462// traverseNode = traverseNode.next;463// console.log(traverseNode.data);464// }465// console.log('Printing done ------');466// }467// search(value) {468// }469// }470// let mySinglyLinkedList = new SinglyLinkedList();471// mySinglyLinkedList.insert(5);472// mySinglyLinkedList.insert(10);473// mySinglyLinkedList.insert(11);474// mySinglyLinkedList.insertAt(2, 10);475// mySinglyLinkedList.print();476// mySinglyLinkedList.insertAt(2, 4);477// mySinglyLinkedList.removeAt(2);478// mySinglyLinkedList.print();479// class SinglyLinkedListCircular {480// constructor() {481// this.length = 0;482// this.head = null;483// this.tail = null;484// }485// insert(value) {486// let newNode = {487// data : value,488// next : null489// }490// if(this.length === 0) {491// newNode.next = newNode;492// this.head = newNode;493// this.tail = newNode;494// }495// if(this.length > 0) {496// newNode.next = this.head;497// this.head = newNode;498// this.tail.next = this.head;499// }500// this.length++;501// }502// insertAt(position, value) {503// if(position === 1) {504// this.insert(value);505// return;506// }507// let traverseNode = this._traverse(position - 2);508// let newNode = {509// data : value,510// next : null511// }512// //are we at tail? if yes make a new tail and point it to head513// if(traverseNode !== this.tail) {514// newNode.next = traverseNode.next;515// traverseNode.next = newNode;516// } else {517// //if not do the standard insert like with non-circular list518// newNode.next = this.head;519// this.tail.next = newNode;520// this.tail = newNode;521// }522// this.length++;523// }524// remove() {525// //just remove assumes remove from beginning526// if(this.length === 0) {527// console.log(`Can't remove from empty list`);528// return;529// }530// if(this.length === 1) {531// this.length = 0;532// this.head = this.tail = null;533// return;534// }535// this.head = this.head.next;536// this.tail.next = this.head;537// this.length--;538// }539// removeAt(position) {540// if(this.length === 0) {541// console.log(`Can't remove from empty list`);542// return;543// }544// if(position === 1) {545// this.remove();546// return;547// }548// let traversals = position - 2;549// if(traversals > (this.length - 2)) traversals = this.length-2;550// let traverseNode = this._traverse(traversals);551// if(traverseNode.next !== this.tail) {552// //we're in between 2 nodes553// traverseNode.next = traverseNode.next.next;554// } else {555// //we're in front of tail556// traverseNode.next = this.head;557// this.tail = traverseNode;558// }559// this.length--;560// }561// print() {562// console.log(`Printing list----------`);563// if(this.length === 0) {564// console.log(`Empty list`);565// return;566// }567// let traverseNode = this.head;568// console.log(traverseNode.data);569// //there was just 1 element, return570// if(this.length === 1) return;571// //otherwise let's keep going572// let traversals = this.length - 1;573// while(traverseNode.next && traversals > 0) {574// traversals--;575// traverseNode = traverseNode.next;576// console.log(traverseNode.data);577// }578// console.log(`End----------`);579// }580// testCircularity() {581// if(this.head === this.tail.next) console.log(`List is circular`);582// else console.log(`List isn't circular`);583// }584// // _ indicates a private function585// _traverse(numberOfNodes) {586// let traverseNode = this.head;587// if((this.length - 1) <= numberOfNodes) {588// traverseNode = this.tail;589// } else {590// while(numberOfNodes > 0) {591// numberOfNodes--;592// traverseNode = traverseNode.next;593// }594// }595// return traverseNode;596// }597// }598// //Testing599// let mySinglyLinkedListCircular = new SinglyLinkedListCircular();600// mySinglyLinkedListCircular.insert(5);601// mySinglyLinkedListCircular.insert(10);602// mySinglyLinkedListCircular.insert(11);603// //test insert at, print and see if it's still circular604// mySinglyLinkedListCircular.insertAt(4, 3);605// mySinglyLinkedListCircular.print();606// mySinglyLinkedListCircular.testCircularity();607// //remove at a certain position, print and test if it's still properly circularž608// mySinglyLinkedListCircular.removeAt(3);609// mySinglyLinkedListCircular.print();610// mySinglyLinkedListCircular.testCircularity();611/**612 * Doubly linked list circular613 * with head, tail, length614 * and optimization for inserting to max O(n/2)615 */616class DoublyLinkedList {617 constructor() {618 this.length = 0;619 this.head = null;620 this.tail = null;621 }622 insert(value) {623 let newNode = {624 data : value,625 next: null,626 previous: null627 }628 if(this.length === 0) {629 this.head = this.tail = newNode;630 }631 if(this.length > 0) {632 newNode.next = this.head;633 this.head.previous = newNode;634 this.head = newNode;635 }636 this.length++;637 }638 remove() {639 if(this.length === 0) {640 console.log('List is already empty.');641 return;642 } 643 if(this.length === 1) {644 this.head = null;645 this.tail = null;646 } else {647 this.head = this.head.next;648 this.head.previous = null;649 }650 this.length--;651 }652 insertAt(position, value) {653 if(this.length === 0) {654 this.insert();655 return;656 }657 //so if the position given is bigger than list size just append to end658 if(position > this.length) {659 let newNode = {660 data : value,661 next : null,662 previous : this.tail663 }664 this.tail.next = newNode;665 this.tail = newNode;666 return;667 }668 //since we're talking about a doubly linked list there can be669 //2 possible directions, by default it's towards right but if the 670 //position we're talking about is bigger than half the size then we will "come in" from the right side671 //that means direction is 'L' which means left672 //this will save time in traversing the node to worse case of O(n/2)673 let direction = 'R';674 if(position > Math.round(this.length / 2)) direction = 'L';675 //number of required traversals to get 1 position "in front of" where we need to insert676 let traversals;677 let newNode = {678 data : value679 }680 if(direction === 'R') {681 traversals = position - 2;682 let tN = this._traverse(traversals, 'R');683 //we're finally at the required position so do the insert684 newNode.next = tN.next;685 newNode.previous = tN;686 tN.next.previous = newNode;687 tN.next = newNode;688 } else if(direction === 'L') {689 traversals = this.length - position - 1;690 let tN;691 if(traversals > 0) {692 tN = this._traverse(traversals, 'L');693 } else {694 tN = this.tail;695 }696 let newNode = {697 data : value698 }699 newNode.previous = tN.previous;700 newNode.next = tN;701 tN.previous.next = newNode;702 tN.previous = newNode;703 this.length++;704 }705 }706 removeAt(position, value) {707 }708 _traverse(numberOfNodes, direction) {709 if(direction === 'R') {710 let tN = this.head;711 while(numberOfNodes > 0) {712 tN = tN.next;713 }714 } else if(direction === 'L') {715 let tN = this.tail;716 while(numberOfNodes > 0) {717 tN = tN.previous;718 }719 }720 }721 print() {722 console.log(`Printing linked list: ------`);723 if(this.length === 0) {724 console.log(`***List empty***`);725 }726 if(this.length > 0) {727 console.log(`Length: ${this.length}`)728 let tN = this.head; 729 console.log(tN.data);730 while(tN.next) {731 tN = tN.next;732 console.log(tN.data);733 }734 }735 console.log(`End: ------`);736 }737 printBackwards() {738 console.log(`Printing linked list backwards: ------`);739 if(this.length === 0) {740 console.log(`***List empty***`);741 }742 if(this.length > 0) {743 console.log(`Length: ${this.length}`)744 let tN = this.tail;745 console.log(tN.data);746 while(tN.previous) {747 tN = tN.previous;748 console.log(tN.data);749 }750 }751 }752 search(value) {753 754 }755}756myDoublyLinkedList = new DoublyLinkedList();757myDoublyLinkedList.insert(5);758myDoublyLinkedList.insert(10);759myDoublyLinkedList.insert(4);760myDoublyLinkedList.insertAt(3, 8);761myDoublyLinkedList.print();762myDoublyLinkedList.printBackwards();763/**764 * Doubly linked list circular...
runtime.js
Source: runtime.js
...48 ...defaultCallExpressions,49 ...callExpressions,50 };51 function traverseArray(array) {52 return array.map(x => traverseNode(x)).filter(x => x != null);53 }54 function traverseCallExpression(node) {55 const call = callExpr[node.name.toLowerCase()];56 if (!call) return unsupported(`CallExpression: ${node.name}`);57 return call(node, { traverseNode, traverseArray, Types, invariant });58 }59 function traverseSelect(node) {60 const keyed = [];61 for (const field of node.fields) {62 if (isType(Types.FieldIdentifier, field)) {63 const value = traverseNode(field);64 keyed.push([ field.value, value ]);65 } else if (isType(Types.AsExpression, field)) {66 const value = traverseNode(field.value);67 if (isType(Types.Wildcard, field.prop)) {68 return value;69 } else {70 keyed.push([ field.prop.value, value ]);71 }72 } else return traverseNode(field);73 }74 return input => Object.fromEntries(keyed.map(([ k, v ]) => [ k, v(input) ]));75 }76 function traverseBinaryExpression(node) {77 switch (node.operator.value) {78 case 'like':79 case 'ilike':80 case 'not like':81 case 'not ilike': {82 const types = [83 Types.StringLiteral,84 Types.NumberLiteral,85 Types.NullLiteral,86 Types.BooleanLiteral,87 ];88 const validLHS = [ Types.FieldIdentifier, ...types ];89 const validRHS = [ Types.MatcherLiteral, ...types ];90 91 const target = invariant(validLHS, node.left);92 const matcher = invariant(validRHS, node.right);93 const flags = node.operator.value.includes('il') ? 'i' : void 0;94 const regex = toRegex(matcher.value, flags);95 const field = traverseNode(target, '');96 const inversed = node.operator.value.includes('not');97 return inversed98 ? input => !regex.test(field(input))99 : input => regex.test(field(input));100 }101 case 'in':102 case 'not in': {103 const array = traverseNode(node.right, []);104 const value = traverseNode(node.left);105 const inversed = node.operator.value.includes('not');106 107 return inversed108 ? input => !array(input).includes(value(input))109 : input => array(input).includes(value(input));110 }111 default: {112 const left = traverseNode(node.left);113 const operator = traverseNode(node.operator);114 const right = traverseNode(node.right);115 return operator(left, right);116 }117 }118 }119 function chainFromPath(path, coalesce = null) {120 const p = path.split('.');121 return (input) => p.reduce((o, k) => o?.[k], input) ?? coalesce;122 }123 function traverseNode(node, whenNull) {124 if (!node) return null;125 switch (node.type) {126 case Types.Wildcard:127 return input => input;128 case Types.StringLiteral:129 case Types.NumberLiteral:130 case Types.BooleanLiteral:131 return () => node.value;132 case Types.NullLiteral:133 return () => null;134 case Types.FieldIdentifier:135 return chainFromPath(node.value, whenNull);136 case Types.ArrayLiteral: {137 const elements = traverseArray(node.values);138 return input => elements.map(f => f(input));139 }140 case Types.BinaryOperator:141 return operatorMapping[node.value];142 case Types.LogicalOr:143 return or;144 case Types.LogicalAnd:145 return and;146 case Types.Query:147 return traverseArray(node.body);148 case Types.LogicalExpression: {149 const left = traverseNode(node.left);150 const right = traverseNode(node.right);151 const op = traverseNode(node.operator);152 return op(left, right);153 }154 case Types.BinaryExpression:155 return traverseBinaryExpression(node);156 case Types.SelectExpression:157 select = traverseSelect(node);158 return;159 case Types.LimitExpression:160 limit = node.count.value;161 return;162 case Types.OffsetExpression:163 offset = node.count.value;164 return;165 case Types.SortOrderExpression:166 case Types.OrderExpression:167 case Types.OptionExpression:168 return unsupported(node.type);169 case Types.CallExpression:170 return traverseCallExpression(node);171 default:172 throw new Error(`Unknown type: ${node.type}`);173 }174 }175 const [ filter = () => true ] = traverseNode(ast);176 filter.select = select;177 filter.limit = limit;178 filter.offset = offset;179 return filter;180};...
SingleLinkedList.js
Source: SingleLinkedList.js
1// Node Class2class Node {3 constructor(data) {4 this.data = data;5 this.next = null;6 }7}8// LinkedList class9class LinkedList {10 constructor() {11 this.head = null;12 }13 isEmpty() {14 return this.head === null;15 }16 getLength() {17 let tempNode = this.head;18 let length = 0;19 while (tempNode !== null) {20 tempNode = tempNode.next;21 length += 1;22 }23 return length;24 }25 print() {26 if (this.isEmpty()) {27 return "Linked List is Empty.";28 }29 let tempNode = this.head;30 let str = "";31 const seperator = " -> ";32 while (tempNode !== null) {33 str += `${tempNode.data}${seperator}`;34 tempNode = tempNode.next;35 }36 str += "null";37 return str;38 }39 insertAtPosition(data, position) {40 if (position < 0) {41 throw Error("Invalid position.");42 }43 let tempNode = this.head;44 let previousNode = null;45 while (position !== 0 && tempNode !== null) {46 position -= 1;47 previousNode = tempNode;48 tempNode = tempNode.next;49 }50 if (position !== 0) { // if the position is not zero, after the loop ends, 51 // it means that the tempNode is null. 52 // So the given position is more than the length of the linked list.53 // So it is an Invalid position.54 throw Error("Invalid Position.");55 }56 let newNode = new Node(data);57 newNode.next = tempNode;58 if (previousNode !== null) {59 previousNode.next = newNode;60 } else {61 // if previousNode is null, then the code in loop didn't run62 // which means the position is 0 or the head is null. So we update the head.63 this.head = newNode;64 }65 }66 insertAtBegining(data) {67 let tempNode = new Node(data);68 tempNode.next = this.head;69 this.head = tempNode;70 }71 insertAtLast(data) {72 if (this.isEmpty()) {73 this.insertAtBegining(data);74 } else {75 let tempNode = new Node(data);76 let traverseNode = this.head;77 while (traverseNode.next !== null) {78 traverseNode = traverseNode.next;79 }80 traverseNode.next = tempNode;81 }82 }83 deleteAtPosition(position) {84 if (this.isEmpty()) {85 throw Error("Empty Linked List.");86 }87 if (position < 0) {88 throw Error("Invalid Position.");89 }90 let traverseNode = this.head;91 let previousNode = null;92 while (position !== 0 && traverseNode.next !== null) {93 position -= 1;94 previousNode = traverseNode;95 traverseNode = traverseNode.next;96 }97 if (position !== 0) {98 throw Error("Invalid Position.")99 }100 if (previousNode === null) {101 // if previousNode is null, then the code in loop didn't run102 // which means the position is 0. So we update the head.103 this.head = this.head.next;104 } else {105 previousNode.next = traverseNode.next;106 }107 traverseNode.next = null;108 return traverseNode;109 }110 deleteAtBegining() {111 if (this.isEmpty()) {112 throw Error("Empty Linked List.");113 }114 let tempNode = this.head;115 this.head = this.head.next;116 tempNode.next = null;117 return tempNode;118 }119 deleteAtEnd() {120 if (this.isEmpty()) {121 throw Error("Empty Linked List.");122 }123 let traverseNode = this.head;124 let previousNode = null;125 while (traverseNode.next !== null) {126 previousNode = traverseNode;127 traverseNode = traverseNode.next;128 }129 if (previousNode !== null) {130 previousNode.next = null;131 }132 if (this.head === traverseNode) {133 this.head = null;134 }135 traverseNode.next = null;136 return traverseNode;137 }138}139// Usage140ll = new LinkedList();141ll.insertAtPosition(1, 0); // 1 -> null142ll.insertAtLast(2); // 1 -> 2 -> null143ll.insertAtBegining(0); // 0 -> 1 -> 2 -> null144console.log(`${ll.print()}`); // prints "0 -> 1 -> 2 -> null"145ll.deleteAtPosition(0);146console.log(`${ll.print()}`); // 1 -> 2 -> null147ll.insertAtLast(3); // 1 -> 2 -> 3-> null148ll.insertAtPosition(4, ll.getLength()); // 1 -> 2 -> 3 -> 4 -> null149console.log(`${ll.print()}`); // prints "1 -> 2 -> 3 -> 4 -> null"150console.log(`Length = ${ll.getLength()}`); // prints "Length = 4"151ll.deleteAtPosition(ll.getLength() - 1); // 1 -> 2 -> 3 -> null152console.log(`${ll.print()}`); // prints "1 -> 2 -> 3 -> null"153ll.deleteAtBegining(); // 2 -> 3 -> null154console.log(`${ll.print()}`); // prints "2 -> 3 -> null"155ll.deleteAtEnd(); // 2 -> null...
radix-trie.js
Source: radix-trie.js
1/**2 * a space-optimized trie, each node that is the only child is merged with its parent.3 * the result is that the number of children of every internal node is at most the radix r of the radix tree.4 * r is a positive integer and a power x of 2, when the r is 2, the radix trie is binary.5 * when r >= 4, the radix trie is an r-ary trie6 * sparseness vs trie depth7 *8 * applications: associative array, IP routing9 */10class Edge {11 constructor(node, str) {12 this.targetNode = node;13 this.label = str;14 }15}16class Node {17 constructor() {18 this.edges = [];19 }20 isLeaf() {21 return this.edges.length === 0;22 }23}24function insert(node, str) {25 let traverseNode = node;26 let traverseEdge = null;27 //find common prefix28 let prefix = "";29 let index = -1;30 while (31 traverseNode !== null &&32 !traverseNode.isLeaf() &&33 prefix.length < str.length34 ) {35 let idx = -1;36 for (let i = 0; i < traverseNode.edges.length; i++) {37 let e = traverseNode.edges[i];38 idx = commonPrefixIdx(e.label, str.slice(prefix.length, str.length));39 if (idx !== -1) {40 prefix += e.label.slice(0, idx + 1);41 traverseNode = e.targetNode;42 traverseEdge = e;43 index = idx;44 break;45 }46 }47 if (idx === -1) {48 break;49 }50 }51 if (prefix.length === 0) {52 let newEdge = new Edge(new Node(), str);53 node.edges.push(newEdge);54 } else if (prefix.length < str.length) {55 let plen = prefix.length;56 let remain_str = str.slice(plen, str.length);57 let old_remain_str = traverseEdge.label.slice(58 index + 1,59 traverseEdge.label.length60 );61 if (remain_str !== "") {62 traverseNode.edges.push(new Edge(new Node(), remain_str));63 }64 if (old_remain_str !== "") {65 traverseNode.edges.push(new Edge(new Node(), old_remain_str));66 traverseEdge.label = traverseEdge.label.slice(0, index + 1);67 }68 }69}70function commonPrefixIdx(str1, str2) {71 let idx = -1;72 while (idx < Math.min(str1.length, str2.length) - 1) {73 if (str1[idx + 1] === str2[idx + 1]) {74 idx++;75 } else {76 break;77 }78 }79 return idx;80}81function lookup(node, str) {82 let traverseNode = node;83 let elementsLen = 0;84 while (85 traverseNode !== null &&86 !traverseNode.isLeaf() &&87 elementsLen < str.length88 ) {89 let edge = traverseNode.edges.find((e) => str.includes(e.label));90 if (edge) {91 traverseNode = edge.targetNode;92 elementsLen += edge.label.length;93 } else {94 traverseNode = null;95 }96 }97 return (98 traverseNode !== null && traverseNode.isLeaf() && elementsLen === str.length99 );100}101function print(node, char = "") {102 let traverseNode = node;103 if (traverseNode.isLeaf()) {104 console.log(char);105 }106 traverseNode.edges.forEach((e) => {107 print(e.targetNode, char + e.label);108 });109}110let root = new Node();111function test() {112 // let list = ["tree", "map", "try", "mouse", "apple"];113 let list = ["apple", "cat", "cup", "application", "concat", "cute"];114 // let list = ["slow", "slower", "slowly", "test", "toaster", "toasting"];115 list.forEach((l) => {116 insert(root, l);117 });118}119test();120// console.log(root);121console.log("===================================");122print(root);123// console.log(root);124// console.log(root.edges[0].targetNode);125// console.log(root.edges[1].targetNode);126// console.log(root.edges[1].targetNode.edges[0].targetNode);127console.log("===================================");128// console.log("has tree: ", lookup(root, "tree"));129// console.log("has map: ", lookup(root, "map"));130// console.log("has try: ", lookup(root, "try"));131// console.log("has mouse: ", lookup(root, "mouse"));132// console.log("has apple: ", lookup(root, "apple"));...
transformer.js
Source: transformer.js
...23 throw new Error('traverseArray arr must be an array.');24 }25 arr.forEach(node => {26 // eslint-disable-next-line no-use-before-define27 traverseNode(node, parent);28 });29 }30 function traverseNode(node, parent) {31 if (!node) {32 return;33 }34 // è°ç¨ visitor ä¸å®ä¹çç±»åå¤çå½æ°35 const method = visitor[node.type];36 if (method) {37 method(node, parent);38 }39 // éå½è°ç¨40 switch (node.type) {41 case 'Program':42 traverseArray(node.body, node);43 break;44 case 'VariableDeclaration':45 traverseArray(node.declarations, node);46 break;47 case 'VariableDeclarator':48 traverseNode(node.id, node);49 traverseNode(node.init, node);50 break;51 case 'Identifier':52 break;53 case 'Literal':54 break;55 case 'ArrowFunctionExpression':56 case 'FunctionExpression':57 traverseNode(node.id, node);58 traverseArray(node.params, node);59 traverseNode(node.body, node);60 break;61 case 'BlockStatement':62 traverseArray(node.body, node);63 break;64 case 'ReturnStatement':65 traverseNode(node.argument, node);66 break;67 case 'BinaryExpression':68 traverseNode(node.left, node);69 traverseNode(node.right, node);70 break;71 default:72 break;73 }74 }75 traverseNode(ast, null);76}77/**78 * å®ä¹ transformer å½æ°ï¼æ¥æ¶æ们å¨ä¹åæ建好ç AST79 * å¨ visitor 对象ä¸ï¼ç®åå®ä¹ä¸äºç±»å访é®å½æ°ï¼æåå¾å°ä¸ä¸ªæ°ç AST80 */81function transformer(ast) {82 const newAST = deepclone(ast);83 // ES6 é»è®¤å¼å¯äºä¸¥æ ¼æ¨¡å¼ï¼æ以æå¼å§éè¦å ä¸ 'use strict' æ è¯84 newAST.body.unshift(new ExpressionStatement({85 expression: new Literal({86 value: 'use strict',87 }),88 directive: 'use strict',89 }));...
traverse-node.spec.js
Source: traverse-node.spec.js
1import domParser from '../src/dom-parser';2import traverseNode from '../src/traverse-node';3describe('traverseNode', () => {4 it('TypeError is thrown is node is not a Node', () => {5 expect(() => traverseNode(1)).toThrowError(TypeError);6 });7 it('TypeError is thrown is onStep is not a Function', () => {8 expect(() => traverseNode(document.body, 1)).toThrowError(TypeError);9 });10 it('all dom nodes are reached', () => {11 const html = '<html><head></head><body></body></html>';12 const dom = domParser.parseFromString(html, 'text/html');13 const nodes = ['HTML', 'HEAD', 'BODY'];14 traverseNode(dom, (node) => {15 const index = nodes.indexOf(node.tagName);16 nodes.splice(index, 1);17 });18 expect(nodes.length).toBe(0);19 });20 it('single node tree is passed', () => {21 const element = document.createElement('div');22 const nodes = ['DIV'];23 traverseNode(element, (node) => {24 const index = nodes.indexOf(node.tagName);25 nodes.splice(index, 1);26 });27 expect(nodes.length).toBe(0);28 });29 it('childless node is reached', () => {30 const htmlDocument = document.implementation.createHTMLDocument();31 traverseNode(htmlDocument.body, (node) => {32 expect(node).toBe(htmlDocument.body);33 });34 });35 it('paths are built correctly', () => {36 const element = document.createElement('div');37 element.innerHTML = '<section><!--comment--><h1></h1></section>text';38 const paths = {39 DIV: '0',40 SECTION: '0,0',41 comment: '0,0,0',42 H1: '0,0,1',43 text: '0,1',44 };45 traverseNode(element, (node, path) => {46 const id = node.tagName || node.textContent;47 expect(paths[id]).toBe(path.toString());48 }, true);49 });50 it('traverse is breakable', () => {51 const onStep = jasmine.createSpy();52 traverseNode(document, () => {53 onStep();54 return true;55 });56 expect(onStep).toHaveBeenCalledTimes(1);57 });58 describe('when rootNode has nextSibling textNode', () => {59 it('all rootNode nodes are reached', () => {60 const html = '<html><head></head><body><h1>Hello World</h1> </body></html>';61 const dom = domParser.parseFromString(html, 'text/html');62 const nodes = [];63 const rootNode = dom.querySelector('h1');64 traverseNode(rootNode, (node) => {65 nodes.push(node);66 });67 expect(nodes.length).toBe(2);68 });69 });70 describe('when rootNode does not have children and has nextSibling', () => {71 it('only rootNode is reached', () => {72 const html = '<html><head></head><body><h1></h1> </body></html>';73 const dom = domParser.parseFromString(html, 'text/html');74 const nodes = [];75 const rootNode = dom.querySelector('h1');76 traverseNode(rootNode, (node) => {77 nodes.push(node);78 });79 expect(nodes.length).toBe(1);80 });81 });...
traverse.js
Source: traverse.js
...12 }13}14function traverse(ast, visitor) {15 function traverseArray(array, parent) {16 array.forEach((child) => traverseNode(child, parent))17 }18 function traverseNode(node, parent) {19 let replaceWidth = reaplce.bind(null, parent, node)20 let method = visitor[node.type]21 // å¼å§éåèç¹çæ¶å22 if (method) {23 if (typeof method === 'function') {24 method({ node, replaceWidth }, parent)25 } else {26 method.enter({ node, replaceWidth }, parent)27 }28 }29 switch (node.type) {30 case nodeTypes.Program:31 traverseArray(node.body, node)32 break33 case nodeTypes.ExpressionStatement:34 traverseNode(node.expression, node)35 break36 case nodeTypes.JSXElement:37 traverseNode(node.openingElement, node)38 traverseArray(node.children, node)39 traverseNode(node.closingElement, node)40 break41 case nodeTypes.JSXOpeningElement:42 traverseNode(node.name, node)43 traverseArray(node.attributes, node)44 break45 case nodeTypes.JSXAttribute:46 traverseNode(node.name, node)47 traverseNode(node.value, node)48 break49 case nodeTypes.JSXClosingElement:50 traverseNode(node.name, node)51 break52 case nodeTypes.JSXIdentifier:53 case nodeTypes.JSXText:54 case nodeTypes.Literal:55 break56 default:57 break58 }59 // éåå®èç¹60 if (method && method.exit) {61 method.exit({ node, replaceWidth }, parent)62 }63 }64 traverseNode(ast, null)65}66module.exports = {67 traverse,68}69// let sourceCode = `<h1 id="title"><span>hello</span>world</h1>`70// let ast = parser(sourceCode)71// traverse(ast, {72// JSXOpeningElement: {73// enter: (nodePath, parent) => {74// console.log(`è¿å
¥å¼å§å
ç´ `, nodePath.node)75// },76// exit: (nodePath, parent) => {77// console.log(`离å¼å¼å§å
ç´ `, nodePath.node)78// },...
binary-search-tree.js
Source: binary-search-tree.js
1function Bst(num) {2 var parentnode = new node();3 parentnode.data = num; 4 console.log(parentnode.data);5 6 parentnode.insert = function(num) {7 traversenode = parentnode;8 newnode = new node();9 newnode.data = num;10 console.log(">" + parentnode.data);11 12 while (true) {13 if (num <= traversenode.data) {14 if (typeof traversenode.left != "undefined")15 traversenode = traversenode.left;16 else {17 traversenode.left = newnode;18 break;19 }20 }21 else { 22 if (typeof traversenode.right != "undefined")23 traversenode = traversenode.right;24 else {25 traversenode.right = newnode; 26 break;27 }28 }29 }30 31 };32 return parentnode;33};34var node = function () {35 var data;36 var left;37 var right;38};39// iteration function skipped...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 const element = await page.$('text=Docs');7 const box = await element.boundingBox();8 const x = box.x + box.width / 2;9 const y = box.y + box.height / 2;10 const node = await page.traverseNode({ x, y });11 console.log(node);12 await browser.close();13})();
Using AI Code Generation
1const { chromium } = require('playwright-chromium');2const { traverseNode } = require('playwright-core/lib/server/dom.js');3(async () => {4 const browser = await chromium.launch({ headless: false, slowMo: 500 });5 const context = await browser.newContext();6 const page = await context.newPage();7 const root = await page.mainFrame()._utilityContext();8 const handle = await root.evaluateHandle(() => document.body);9 const node = await handle.asElement().evaluateHandle(node => node);10 const result = await traverseNode(node, {11 });12 console.log(result);13 await browser.close();14})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 const root = await page._document;6 const node = await root.traverseNode({7 predicate: (node) => node.getAttribute('id') === 'box'8 });9 console.log(node);10 await browser.close();11})();12const { chromium } = require('playwright');13(async () => {14 const browser = await chromium.launch();15 const page = await browser.newPage();16 const context = await browser.newContext();17 const root = await context._document;18 const node = await root.traverseNode({19 predicate: (node) => node.getAttribute('id') === 'box'20 });21 console.log(node);22 await browser.close();23})();24const { chromium } = require('playwright');25(async () => {26 const browser = await chromium.launch();27 const page = await browser.newPage();28 const context = await browser.newContext();29 const root = await context._document;30 const node = await root.traverseNode({31 predicate: (node) => node.getAttribute('id') === 'box'32 });33 console.log(node);34 await browser.close();35})();36const { chromium } = require('playwright');37(async () => {38 const browser = await chromium.launch();39 const page = await browser.newPage();40 const context = await browser.newContext();41 const root = await context._document;42 const node = await root.traverseNode({43 predicate: (node) => node.getAttribute('id') === 'box'44 });45 console.log(node);46 await browser.close();47})();
Using AI Code Generation
1const { test, expect } = require("@playwright/test");2test("test", async ({ page }) => {3 const element = await page.$("text=Get Started");4 const handle = await element.asElement();5 const box = await handle._page._delegate.traverseNode(handle._remoteObject.objectId);6 expect(box).toBeTruthy();7});8 FAIL test.js (5.613 s)9 ✕ test (5.567 s)10 Protocol error (Runtime.callFunctionOn): Traversal of the given node is not supported. (Session info: chrome=92.0.4515.131)11 at Object.error (node_modules/playwright/lib/client/protocol/protocol.js:123:13)12 at CDPSession.dispatch (node_modules/playwright/lib/client/protocol/transport.js:207:24)13 at CDPSession._onMessage (node_modules/playwright/lib/client/protocol/transport.js:127:12)14 at WebSocketTransport._ws.addEventListener.event (node_modules/playwright/lib/client/protocol/transport.js:43:28)15 at WebSocket.onMessage (node_modules/ws/lib/event-target.js:132:16)16 at WebSocket.emit (events.js:315:20)17 at Receiver.receiverOnMessage (node_modules/ws/lib/websocket.js:800:20)18 at Receiver.emit (events.js:315:20)19 at Receiver.dataMessage (node_modules/ws/lib/receiver.js:437:14)20 at Receiver.getData (node_modules/ws/lib/receiver.js:367:17)21 at Receiver.startLoop (node_modules/ws/lib/receiver.js:153:22)22 at Receiver._write (node_modules/ws/lib/receiver.js:74:10)23 at doWrite (node_modules/ws/lib/websocket.js:359:12)24 at writeOrBuffer (node_modules/ws/lib/websocket.js:349:5)25 at WebSocket.send (node_modules/ws/lib/websocket.js:295:11)26 at CDPSession.send (node_modules/playwright/lib/client/protocol/transport.js:103:28)
Using AI Code Generation
1const { traverseNode } = require('playwright/lib/server/dom.js');2const { getBoundingBox } = require('playwright/lib/server/dom.js');3const { getClientRects } = require('playwright/lib/server/dom.js');4const { getAttribute } = require('playwright/lib/server/dom.js');5const { getAttributes } = require('playwright/lib/server/dom.js');6const { getInnerHTML } = require('playwright/lib/server/dom.js');7const { getOuterHTML } = require('playwright/lib/server/dom.js');8const { getTextContent } = require('playwright/lib/server/dom.js');9const { getFrame } = require('playwright/lib/server/dom.js');10const { getOwnerFrame } = require('playwright/lib/server/dom.js');11const { getBoundingBoxCenter } = require('playwright/lib/server/dom.js');12const { scrollRectIntoViewIfNeeded } = require('playwright/lib/server/dom.js');13const { focus } = require('playwright/lib/server/dom.js');14const { dispatchEvent } = require('playwright/lib/server/dom.js');15const { scrollIntoViewIfNeeded } = require('playwright/lib/server/dom.js');16const { checkHitTargetAt } = require('playwright/lib/server/dom.js');17const { scrollBy } = require('playwright/lib/server/dom
Using AI Code Generation
1const { parse } = require('path');2const { traverseNode } = require('@playwright/test/lib/utils/ast');3const { parseScript } = require('shift-parser');4const { generate } = require('shift-codegen');5const { test } = require('@playwright/test');6test('test', async ({ page }) => {7 const code = await page.textContent('.navbar__inner');8 const ast = parseScript(code);9 traverseNode(ast, {10 enter(node, parent) {11 if (node.type === 'IdentifierExpression' && node.name === 'Playwright') {12 node.name = 'Playwright Test';13 }14 }15 });16 console.log(generate(ast));17});
Using AI Code Generation
1const { traverseNode } = require('@playwright/test/lib/server/dom');2const { chromium } = require('playwright');3const { test } = require('@playwright/test');4test('traverseNode', async ({ page }) => {5 await page.setContent(`<div id="root"><div id="child1"><div id="child2"></div></div></div>`);6 const root = await page.$('#root');7 const child1 = await page.$('#child1');8 const child2 = await page.$('#child2');9 const result = await traverseNode(root);10 console.log(result);11 expect(result).toEqual({12 nodeId: expect.any(Number),13 backendNodeId: expect.any(Number),14 children: [{15 nodeId: expect.any(Number),16 backendNodeId: expect.any(Number),17 children: [{18 nodeId: expect.any(Number),19 backendNodeId: expect.any(Number),20 frameId: expect.any(String),21 importedDocument: null,22 }],23 frameId: expect.any(String),24 importedDocument: null,25 }],26 frameId: expect.any(String),27 importedDocument: null,28 });29 expect(await traverseNode(child1)).toEqual({30 nodeId: expect.any(Number),31 backendNodeId: expect.any(Number),
Using AI Code Generation
1const { chromium } = require("playwright");2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const root = await page._client.send("DOM.getDocument");7 const rootChildren = await page._client.send("DOM.getFlattenedDocument", {8 });9 traverseNode(root.root, rootChildren.nodes, 0);10 await browser.close();11})();12function traverseNode(node, allNodes, depth) {13 let indent = "";14 for (let i = 0; i < depth; i++) {15 indent += " ";16 }17 console.log(18 );19 if (node.children) {20 node.children.forEach((childNodeId) => {21 const childNode = allNodes.find((node) => node.nodeId === childNodeId);22 traverseNode(childNode, allNodes, depth + 1);23 });24 }25}
Jest + Playwright - Test callbacks of event-based DOM library
firefox browser does not start in playwright
Is it possible to get the selector from a locator object in playwright?
How to run a list of test suites in a single file concurrently in jest?
Running Playwright in Azure Function
firefox browser does not start in playwright
This question is quite close to a "need more focus" question. But let's try to give it some focus:
Does Playwright has access to the cPicker object on the page? Does it has access to the window object?
Yes, you can access both cPicker and the window object inside an evaluate call.
Should I trigger the events from the HTML file itself, and in the callbacks, print in the DOM the result, in some dummy-element, and then infer from that dummy element text that the callbacks fired?
Exactly, or you can assign values to a javascript variable:
const cPicker = new ColorPicker({
onClickOutside(e){
},
onInput(color){
window['color'] = color;
},
onChange(color){
window['result'] = color;
}
})
And then
it('Should call all callbacks with correct arguments', async() => {
await page.goto(`http://localhost:5000/tests/visual/basic.html`, {waitUntil:'load'})
// Wait until the next frame
await page.evaluate(() => new Promise(requestAnimationFrame))
// Act
// Assert
const result = await page.evaluate(() => window['color']);
// Check the value
})
Check out the latest blogs from LambdaTest on this topic:
Native apps are developed specifically for one platform. Hence they are fast and deliver superior performance. They can be downloaded from various app stores and are not accessible through browsers.
One of the essential parts when performing automated UI testing, whether using Selenium or another framework, is identifying the correct web elements the tests will interact with. However, if the web elements are not located correctly, you might get NoSuchElementException in Selenium. This would cause a false negative result because we won’t get to the actual functionality check. Instead, our test will fail simply because it failed to interact with the correct element.
Smartphones have changed the way humans interact with technology. Be it travel, fitness, lifestyle, video games, or even services, it’s all just a few touches away (quite literally so). We only need to look at the growing throngs of smartphone or tablet users vs. desktop users to grasp this reality.
As part of one of my consulting efforts, I worked with a mid-sized company that was looking to move toward a more agile manner of developing software. As with any shift in work style, there is some bewilderment and, for some, considerable anxiety. People are being challenged to leave their comfort zones and embrace a continuously changing, dynamic working environment. And, dare I say it, testing may be the most ‘disturbed’ of the software roles in agile development.
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!