Best JavaScript code snippet using playwright-internal
ArrayHeap.mjs
Source:ArrayHeap.mjs
1/** @file ArrayHeap.mjs2 *3 * @author Jon Turner4 * @date 20215 * This is open source software licensed under the Apache 2.0 license.6 * See http://www.apache.org/licenses/LICENSE-2.0 for details.7 */8import { assert, AssertError} from '../../common/Errors.mjs';9import Top from '../Top.mjs';10import Scanner from '../basic/Scanner.mjs';11/** This class implements a heap data structure.12 * The heap elements are identified by indexes in 1..n where n13 * is specified when a heap object is constructed.14 */15export default class ArrayHeap extends Top {16 #d; ///< base of heap17 #m; ///< # of items in the heap set18 #item; ///< {#item[1],...,#item[m]} is the items in the heap19 #pos; ///< #pos[i] gives position of i in #item20 #key; ///< #key[i] is key of item i21 #offset; ///< offset for key values, allowing all to shift at once22 #insertCount; // calls to insert23 #deleteCount; // calls to delete24 #changekeyCount; // calls to changekey25 #siftupSteps; // steps taken by siftup26 #siftdownSteps; // steps taken by siftdown27 /** Constructor for ArrayHeap object.28 * @param n is index range for object29 * @parm d is the base of the heap (defaults to 4)30 * @param capacity is maximum index range (defaults to n)31 */32 constructor(n, d=4, capacity=n) { super(n); this.#init(d, capacity); }33 34 /** Allocate space and initialize ArrayHeap object.35 * @param d is the base of the heap.36 * @param capacity is the maximum range37 */38 #init(d, capacity) {39 this.#item = new Int32Array(capacity+1);40 this.#pos = new Int32Array(capacity+1);41 this.#key = new Float32Array(capacity+1);42 this.#item[0] = this.#m = 0; this.#d = d;43 this.#offset = 0;44 this.clearStats();45 }46 /** Reset the heap discarding old value.47 * @param n is the new range of the index set48 * @param d is the new base of the heap.49 * @param capacity the new max range.50 */51 reset(n, d=4, capacity=n) {52 assert(capacity >= n); this._n = n; this.#init(d, capacity);53 }54 55 /** Assign a new value by copying from another heap.56 * @param h is another heap57 */58 assign(h) {59 if (h == this) return;60 if (h.n > this.n) { reset(h.n, h.d); }61 else { clear(); this._n = h.n; }62 this.m = h.m;63 for (p = 1; p <= h.m; p++) {64 x = h.#item[p];65 this.#item[p] = x; this.#pos[x] = p; this.#key[x] = h.#key[x];66 }67 this.clearStats();68 }69 /** Assign a new value by transferring from another heap.70 * @param h is another heap71 */72 xfer(h) {73 if (h == this) return;74 if (!(h instanceof ArrayHeap)) return;75 this.#d = h.#d; this.#m = h.#m; this.#offset = h.#offset;76 this.#item = h.#item; this.#pos = h.#pos; this.#key = h.#key;77 h.#item = h.#pos = h.#key = null;78 this.clearStats();79 }80 81 /** Expand the space available for this ArrayHeap.82 * Rebuilds old value in new space.83 * @param size is the size of the resized object.84 */85 expand(n) {86 if (n <= this.n) return;87 if (n > this.capacity) {88 let nu = new ArrayHeap(this.n, this.#d,89 Math.max(n, ~~(1.25 * this.capacity)));90 nu.assign(this); this.xfer(nu);91 }92 this._n = n;93 }94 /** Remove all elements from heap. */95 clear() {96 for (let x = 1; x <= this.#m; x++) this.#pos[this.#item[x]] = 0;97 this.#m = 0; this.#offset = 0;98 this.clearStats();99 }100 clearStats() {101 this.#insertCount = this.#deleteCount = this.#changekeyCount = 0102 this.#siftupSteps = this.#siftdownSteps = 0103 }104 get capacity() { return this.#item.length-1; }105 get d() { return this.#d; }106 get m() { return this.#m; }107 /** Return position of parent of a heap item.108 * @param p is position of item in heap109 * @param return position where parent would go if there were one110 */111 p(pos) { return Math.ceil((pos-1)/this.d); }112 /** Return position of leftmost child of a heap item.113 * @param pos is position of item in heap114 * @param return position where left child would go if there were one115 */116 left(pos) { return this.d*(pos-1)+2; }117 /** Return position of rightmost child of a heap item.118 * @param pos is position of item in heap119 * @param return position where right child would go if there were one120 */121 right(pos) { return this.d*pos+1; }122 123 /** Find an item in the heap with the smallest key.124 * @return the number of an item that has the smallest key125 */126 findmin() { return this.empty() ? 0 : this.#item[1]; }127 128 /** Delete a minimum key item from the heap and return it.129 * @return an item of minimum key from the heap, after deleting it130 * from the heap131 */132 deletemin() {133 if (this.empty()) return 0;134 let i = this.#item[1]; this.delete(i);135 return i;136 }137 138 /** Get the key of an item.139 * @param i is an item in the heap140 * @return the value of i's key141 */142 key(i) { return this.#offset + this.#key[i]; }143 add2keys(delta) { this.#offset += delta; }144 145 /** Determine if an item is in the heap.146 * @param i is an item147 * @return true if i is in the heap, else false148 */149 contains(i) { return this.#pos[i] != 0; }150 151 /** Determine if the heap is empty.152 * @return true if heap is empty, else false153 */154 empty() { return this.m == 0; };155 156 /** Add index to the heap.157 * @param i is an index that is not in the heap158 * @param key is the key value under which i is to be inserted159 */160 insert(i, key) {161 assert(i > 0);162 this.#insertCount++;163 if (i > this.capacity) this.expand(i);164 this.#key[i] = key - this.#offset; this.#m++; this.#siftup(i, this.m);165 }166 167 /** Remove an index from the heap.168 * @param i is an index in the heap169 */170 delete(i) {171 assert(i > 0);172 this.#deleteCount++;173 let j = this.#item[this.#m--];174 if (i != j) {175 if (this.#key[j] <= this.#key[i])176 this.#siftup(j, this.#pos[i]);177 else178 this.#siftdown(j, this.#pos[i]);179 }180 this.#pos[i] = 0;181 }182 183 /** Perform siftup operation to restore heap order.184 * This is a private helper function.185 * @param i is an item to be positioned in the heap186 * @param x is a tentative position for i in the heap187 */188 #siftup(i, x) {189 this.#siftupSteps++;190 let px = this.p(x);191 while (x > 1 && this.#key[i] < this.#key[this.#item[px]]) {192 this.#item[x] = this.#item[px]; this.#pos[this.#item[x]] = x;193 x = px; px = this.p(x);194 this.#siftupSteps++;195 }196 this.#item[x] = i; this.#pos[i] = x;197 }198 199 /** Perform siftdown operation to restore heap order.200 * This is a private helper function.201 * @param i is an item to be positioned in the heap202 * @param x is a tentative position for i in the heap203 */204 #siftdown(i, x) {205 let cx = this.#minchild(x);206 while (cx != 0 && this.#key[this.#item[cx]] < this.#key[i]) {207 this.#item[x] = this.#item[cx]; this.#pos[this.#item[x]] = x;208 x = cx; cx = this.#minchild(x);209 }210 this.#item[x] = i; this.#pos[i] = x;211 }212 213 /** Find the position of the child with the smallest key.214 * This is a private helper function, used by siftdown.215 * @param x is a position of an index in the heap216 * @return the position of the child of the item at x, that has217 * the smallest key218 */219 #minchild(x) {220 this.#siftdownSteps++;221 let minc = this.left(x);222 if (minc > this.m) return 0;223 for (let y = minc + 1; y <= this.right(x) && y <= this.m; y++) {224 this.#siftdownSteps++;225 if (this.#key[this.#item[y]] < this.#key[this.#item[minc]])226 minc = y;227 }228 return minc;229 }230 231 /** Change the key of an item in the heap.232 * @param i is an item in the heap233 * @param k is a new key value for item i234 */235 changekey(i, k) {236 this.#changekeyCount++;237 let ki = this.#key[i] - this.#offset;238 this.#key[i] = k - this.#offset;239 if (k == ki) return;240 if (k < ki) this.#siftup(i, this.#pos[i]);241 else this.#siftdown(i, this.#pos[i]);242 }243 /** Determine if two heaps are equal.244 * @param h is a heap to be compared to this245 * @return true if both heap sets contain the same items with the246 * the same keys; otherwise, return false247 */248 equals(h) {249 if (this === h) return true;250 if (typeof h == 'string') {251 let s = h; h = new ArrayHeap(this.n); h.fromString(s);252 }253 if (!(h instanceof ArrayHeap)) return false;254 if (this.m != h.m) return false;255 for (let i = 1; i <= this.m; i++) {256 let x = this.#item[i];257 if (!h.contains(x) || this.key(x) != h.key(x)) return false;258 let y = h.#item[i];259 if (!this.contains(y) || this.key(y) != h.key(y)) return false;260 }261 return true;262 }263 264 /** Produce a string representation of the heap.265 * @param details is a flag that (when true) causes implementation266 * details to be shown.267 * @param pretty is a flag that (when true) produces a more readable268 * representation269 * @param label is a function that is used to label heap items270 * numerical values, not letters.271 * @param u is intended only for recursive calls to toString; it272 * identifies a position in the heap structure273 */274 toString(details=0, pretty=0, label=0, u=1) {275 if (this.empty()) return '{}';276 if (u == 0) return '';277 let s = this.index2string(this.#item[u], label) +278 ':' + this.key(this.#item[u]);279 if (this.left(u) <= this.m)280 s += (details ? '(' : ' ');281 for (let v = this.left(u); v <= this.right(u) && v <= this.m; v++) {282 if (v != this.left(u)) s += ' ';283 s += this.toString(details, label, pretty, v);284 }285 if (details && this.left(u) <= this.m) s += ')';286 return (u == 1 ? '{' + s + '}' : s);287 }288 /** Initialize this ArrayHeap object from a string.289 * @param s is a string representing a heap.290 * @return on if success, else false291 */292 fromString(s) {293 let sc = new Scanner(s);294 let l = sc.nextPairList('{','}');295 if (l == null) return null;296 let n = 0; let items = new Set();297 for (let [i,k] of l) {298 n = Math.max(n,i);299 if (items.has(i)) return null;300 items.add(i);301 }302 if (n <= this.n) this.reset(n);303 else this.clear();304 for (let [i,k] of l) this.insert(i, k);305 return true;306 }307 /** Return statistics object. */308 getStats() {309 return {310 'insert' : this.#insertCount, 'delete' : this.#deleteCount,311 'changekey' : this.#changekeyCount,312 'siftup' : this.#siftupSteps, 'siftdown' : this.#siftdownSteps313 };314 }...
test.js
Source:test.js
...38 expect(heap.getRightChild(7)).to.equal(15);39 expect(heap.getRightChild(4)).to.equal(9);40 });41 });42 describe('#siftUp(idx)', () => {43 it('should continually sift up the element at given index until max heap property is restored', () => {44 let heap1 = new MaxHeap();45 heap1.array = [null, 100, 50, 27, 60];46 heap1.siftUp(4);47 expect(heap1.array).to.eql([null, 100, 60, 27, 50]);48 let heap2 = new MaxHeap();49 heap2.array = [null, 100, 50, 27, 101];50 heap2.siftUp(4);51 expect(heap2.array).to.eql([null, 101, 100, 27, 50]);52 });53 });54 describe('#insert(val)', () => {55 it('should insert the given value into the heap', () => {56 let heap = new MaxHeap();57 heap.insert(42);58 heap.insert(32);59 heap.insert(24);60 expect(heap.array).to.eql([null, 42, 32, 24]);61 });62 context('when max heap property is broken', () => {63 it ('should restore max heap property', () => {64 let heap = new MaxHeap();...
HeapFunction.js
Source:HeapFunction.js
1//class PathFinding.libs.HeapFunction2var HeapFunction=(function(){3 function HeapFunction(){4 //};5 this.defaultCmp=function(x,y){6 if (x < y){7 return-1;8 }9 if (x > y){10 return 1;11 }12 return 0;13 }14 }15 __class(HeapFunction,'PathFinding.libs.HeapFunction');16 var __proto=HeapFunction.prototype;17 //};18 __proto.insort=function(a,x,lo,hi,cmp){19 var mid=NaN;20 if (lo==null){21 lo=0;22 }23 if (cmp==null){24 cmp=this.defaultCmp;25 }26 if (lo < 0){27 throw new Error('lo must be non-negative');28 }29 if (hi==null){30 hi=a.length;31 }32 while (lo < hi){33 mid=Math.floor((lo+hi)/ 2);34 if (cmp(x,a[mid])< 0){35 hi=mid;36 }37 else{38 lo=mid+1;39 }40 }41 return ([].splice.apply(a,[lo,lo-lo].concat(x)),x);42 }43 //};44 __proto.heappush=function(array,item,cmp){45 if (cmp==null){46 cmp=this.defaultCmp;47 }48 array.push(item);49 return this._siftdown(array,0,array.length-1,cmp);50 }51 //};52 __proto.heappop=function(array,cmp){53 var lastelt,returnitem;54 if (cmp==null){55 cmp=this.defaultCmp;56 }57 lastelt=array.pop();58 if (array.length){59 returnitem=array[0];60 array[0]=lastelt;61 this._siftup(array,0,cmp);62 }63 else{64 returnitem=lastelt;65 }66 return returnitem;67 }68 //};69 __proto.heapreplace=function(array,item,cmp){70 var returnitem;71 if (cmp==null){72 cmp=this.defaultCmp;73 }74 returnitem=array[0];75 array[0]=item;76 this._siftup(array,0,cmp);77 return returnitem;78 }79 //};80 __proto.heappushpop=function(array,item,cmp){81 var _ref;82 if (cmp==null){83 cmp=this.defaultCmp;84 }85 if (array.length && cmp(array[0],item)< 0){86 _ref=[array[0],item],item=_ref[0],array[0]=_ref[1];87 this._siftup(array,0,cmp);88 }89 return item;90 }91 //};92 __proto.heapify=function(array,cmp){93 var i=0,_i=0,_j=0,_len=0,_ref,_ref1,_results,_results1;94 if (cmp==null){95 cmp=this.defaultCmp;96 }97 _ref1=(function(){98 _results1=[];99 for (_j=0,_ref=Math.floor(array.length / 2);0 <=_ref ? _j < _ref :_j > _ref;0 <=_ref ? _j++:_j--){100 _results1.push(_j);101 }102 return _results1;103 }).apply(this).reverse();104 _results=[];105 for (_i=0,_len=_ref1.length;_i < _len;_i++){106 i=_ref1[_i];107 _results.push(this._siftup(array,i,cmp));108 }109 return _results;110 }111 //};112 __proto.updateItem=function(array,item,cmp){113 var pos=0;114 if (cmp==null){115 cmp=this.defaultCmp;116 }117 pos=array.indexOf(item);118 if (pos===-1){119 return null;120 }121 this._siftdown(array,0,pos,cmp);122 return this._siftup(array,pos,cmp);123 }124 //};125 __proto.nlargest=function(array,n,cmp){126 var elem,result,_i=0,_len=0,_ref;127 if (cmp==null){128 cmp=this.defaultCmp;129 }130 result=array.slice(0,n);131 if (!result.length){132 return result;133 }134 this.heapify(result,cmp);135 _ref=array.slice(n);136 for (_i=0,_len=_ref.length;_i < _len;_i++){137 elem=_ref[_i];138 this.heappushpop(result,elem,cmp);139 }140 return result.sort(cmp).reverse();141 }142 //};143 __proto.nsmallest=function(array,n,cmp){144 var elem,i,los,result,_i=0,_j=0,_len,_ref,_ref1,_results;145 if (cmp==null){146 cmp=this.defaultCmp;147 }148 if (n *10 <=array.length){149 result=array.slice(0,n).sort(cmp);150 if (!result.length){151 return result;152 }153 los=result[result.length-1];154 _ref=array.slice(n);155 for (_i=0,_len=_ref.length;_i < _len;_i++){156 elem=_ref[_i];157 if (cmp(elem,los)< 0){158 this.insort(result,elem,0,null,cmp);159 result.pop();160 los=result[result.length-1];161 }162 }163 return result;164 }165 this.heapify(array,cmp);166 _results=[];167 for (i=_j=0,_ref1=Math.min(n,array.length);0 <=_ref1 ? _j < _ref1 :_j > _ref1;i=0 <=_ref1 ?++_j :--_j){168 _results.push(this.heappop(array,cmp));169 }170 return _results;171 }172 //};173 __proto._siftdown=function(array,startpos,pos,cmp){174 var newitem,parent,parentpos=0;175 if (cmp==null){176 cmp=this.defaultCmp;177 }178 newitem=array[pos];179 while (pos > startpos){180 parentpos=(pos-1)>> 1;181 parent=array[parentpos];182 if (cmp(newitem,parent)< 0){183 array[pos]=parent;184 pos=parentpos;185 continue ;186 }187 break ;188 }189 return array[pos]=newitem;190 }191 //};192 __proto._siftup=function(array,pos,cmp){193 var childpos=0,endpos=0,newitem,rightpos=0,startpos=0;194 if (cmp==null){195 cmp=this.defaultCmp;196 }197 endpos=array.length;198 startpos=pos;199 newitem=array[pos];200 childpos=2 *pos+1;201 while (childpos < endpos){202 rightpos=childpos+1;203 if (rightpos < endpos && !(cmp(array[childpos],array[rightpos])< 0)){204 childpos=rightpos;205 }206 array[pos]=array[childpos];207 pos=childpos;208 childpos=2 *pos+1;209 }210 array[pos]=newitem;211 return this._siftdown(array,startpos,pos,cmp);212 }213 return HeapFunction;214})()215/**216*...217*@author ......
max_heap.js
Source:max_heap.js
...4// #getParent(idx) => idx 5// #getLeftChild(idx) => idx6// #getRightChild(idx) => idx7// #insert(val) => undefined O(logN) TIME, O(N) SPACE8// #siftUp(idx) => undefined 9// #deleteMax() => val (int) O(logN) TIME, O(N) SPACE10// #siftDown(idx) => undefined 11// 12// Run `npx mocha` in terminal for testing13class MaxHeap {14 constructor() {15 this.array = [null];16 }17 getParent(idx) {18 return Math.floor(idx / 2);19 }20 getLeftChild(idx) {21 return idx * 2;22 }23 getRightChild(idx) {24 return idx * 2 + 1;25 }26 insert(val) {27 this.array.push(val); // push value to end of array (add node to farthest bottom left of tree)28 this.siftUp(this.array.length - 1); // continuously swap value toward front of array to maintain maxHeap property29 }30 siftUp(idx) {31 if (idx === 1) return; // no need to siftUp if node is at root32 let parentIdx = this.getParent(idx); // grab parent node idx33 if (this.array[idx] > this.array[parentIdx]) { // if node is bigger than parent, we're breaking heap proprty, so siftUp34 [this.array[idx], this.array[parentIdx]] = // swap node w/ parent35 [this.array[parentIdx], this.array[idx]];36 this.siftUp(parentIdx); // recursively siftUp node37 }38 }39 deleteMax() {40 // recall that we have an empty position at the very front of the array, 41 // so an array length of 2 means there is only 1 item in the heap42 if (this.array.length === 1) return null; // edge case- if no nodes in tree, exit43 if (this.array.length === 2) return this.array.pop(); // edge case- if only 1 node in heap, just remove it (2 bec. null doesnt count)44 let max = this.array[1]; // save reference to root value (max)45 let last = this.array.pop(); // remove last val in array (farthest right node in tree), and update root value with it46 this.array[1] = last;47 this.siftDown(1); // continuoully swap the new root toward the back of the array to maintain maxHeap property48 return max; // return max value49 }50 siftDown(idx) {...
heap.js
Source:heap.js
...41 }42 function isIndexInBounds(i){43 return 0 <= i && i < self.size; // there was a bug: return 0 <= i && i <= self.size;44 }45 function siftUp(i){46 pIndex = self.parentIndex(i);47 if( self.isIndexInBounds(pIndex) && self.array[i] < self.array[pIndex] ){48 // swap49 var temp = self.array[i];50 self.array[i] = self.array[pIndex];51 self.array[pIndex] = temp;52 self.siftUp(pIndex);53 } 54 }55 function siftDown(i){56 // check if there should be children57 // if its a leaf, there is no children58 if(self.isLeaf(i)){59 //console.log('array[' + i + '] -> ' + self.array[i] + ' is leaf');60 return;61 }62 var rightChildIndex = self.rightChildIndex(i);63 var leftChildIndex = self.leftChildIndex(i);64 var smallest = leftChildIndex;65 // check if there is a right child66 if( self.isIndexInBounds(rightChildIndex) && self.array[rightChildIndex] < self.array[leftChildIndex]){67 smallest = rightChildIndex;68 } 69 if(self.array[i] > self.array[smallest]){70 // swap71 var temp = self.array[smallest];72 self.array[smallest] = self.array[i];73 self.array[i] = temp;74 self.siftDown(smallest);75 }76 }77 function push(data){78 // add to last index, siftUp79 //console.log('pushing ' + data + '...');80 var lastIndex = self.size;81 self.array[lastIndex] = data;82 self.siftUp(lastIndex);83 self.size++;84 //console.log(self.array);85 }86 function pop(){87 // swap first and last, size--, siftDown top, return the pop88 //console.log('poping...');89 90 if(self.size == 0){91 return;92 }93 var firstIndex = 0;94 var lastIndex = self.size - 1;95 var firstVal = self.array[firstIndex];96 // swap...
minHeapConstruction.js
Source:minHeapConstruction.js
...26 getParentIdx(i) {27 let newIdx = Math.floor((i - 1) / 2);28 return newIdx >= 0 ? newIdx : -129 }30 siftUp(idx, heap = this.heap) {31 let pIdx = this.getParentIdx(idx);32 while(pIdx !== -1 && heap[pIdx] > heap[idx]){33 this.swap(pIdx, idx, heap);34 idx = pIdx;35 pIdx = this.getParentIdx(pIdx)36 }37 }38 // siftDown(idx, endIdx, array) {39 // let LChildIdx = this.getLeftChildIdx(idx, endIdx);40 // let RChildIdx = this.getRightChildIdx(idx, endIdx);41 // while (LChildIdx !== -1 && LChildIdx <= endIdx) {42 // let idxToSwap;43 // if (RChildIdx !== -1 && array[RChildIdx] < array[LChildIdx]) {44 // idxToSwap = RChildIdx45 // } else {46 // idxToSwap = LChildIdx47 // }48 // if (array[idxToSwap] < array[idx]) {49 // this.swap(idx, idxToSwap, array)50 // idx = idxToSwap;51 // LChildIdx = this.getLeftChildIdx(idx, endIdx)52 // } else {53 // return54 // }55 // }56 // }57 siftDown(currentIdx, endIdx, heap){58 let childOneIdx = currentIdx * 2 + 1;59 while(childOneIdx <= endIdx){60 const childTwoIdx = currentIdx * 2 + 2 <= endIdx ? currentIdx * 2 + 2 : -1;61 let idxToSwap;62 if(childTwoIdx !== -1 && heap[childTwoIdx] < heap[childOneIdx]){63 idxToSwap = childTwoIdx64 } else {65 idxToSwap = childOneIdx66 }67 if(heap[idxToSwap] < heap[currentIdx]){68 this.swap(currentIdx, idxToSwap, heap);69 currentIdx = idxToSwap;70 childOneIdx = currentIdx * 2 + 171 } else {72 return73 }74 }75 }76 77 swap(pIdx, idx, array = this.heap) {78 const temp = array[pIdx];79 array[pIdx] = array[idx];80 array[idx] = temp81 }82 insert(val) {83 this.heap.push(val);84 let idx = this.heap.length - 1;85 this.siftUp(idx, this.heap)86 }87 peek() {88 return this.heap[0]89 }90 remove() {91 this.swap(0, this.heap.length - 1, this.heap);92 const valToRemove = this.heap.pop();93 this.siftDown(0, this.heap.length, this.heap)94 return valToRemove95 }96}97let test = new MinHeap([8,12,23,17,31,30,44,102,18])98console.log(test.heap)99test.siftUp(4)100console.log(test.heap)...
implement-heap-solution.js
Source:implement-heap-solution.js
...10 }11 getRightChild(idx) {12 return idx * 2 + 1;13 }14 siftUp(idx) {15 // base case if the node is at the root16 if (idx === 1) return;17 let parentIdx = this.getParent(idx);18 if (this.array[parentIdx] < this.array[idx]) {19 [this.array[parentIdx], this.array[idx]] = [this.array[idx],this.array[parentIdx]];20 this.siftUp(parentIdx);21 }22 }23 insert(val) {24 this.array.push(val);25 let idx = this.array.length - 1;26 if (val > this.array[this.getParent(idx)]) {27 this.siftUp(idx);28 }29 }30 siftDown(idx) {31 let ary = this.array 32 let leftChildIdx = this.getLeftChild(idx)33 let rightChildIdx = this.getRightChild(idx)34 let leftChildVal = ary[leftChildIdx]35 let rightChildVal = ary[rightChildIdx]36 if (leftChildVal === undefined) leftChildVal = -Infinity37 if (rightChildVal === undefined) rightChildVal = - Infinity38 if (ary[idx] > leftChildVal && ary[idx] > rightChildVal) return;39 let swapIdx;40 if (leftChildVal > rightChildVal){41 swapIdx = leftChildIdx42 } else {43 swapIdx = rightChildIdx44 }45 [ary[idx], ary[swapIdx]] = [ary[swapIdx], ary[idx]]46 this.siftDown(swapIdx)47 }48 deleteMax(){49 if (this.array.length === 2) return this.array.pop();50 if (this.array.length === 1) return null;51 let max = this.array[1]52 this.array[1] = this.array.pop(); 53 this.siftDown(1);54 return max;55 }56}57class minHeap {58 constructor(){59 this.array = [null]60 }61 getParent(idx) {62 return Math.floor(idx / 2);63 }64 getLeftChild(idx) {65 return idx * 2;66 }67 getRightChild(idx) {68 return idx * 2 + 1;69 }70 insert(val){71 this.array.push(val)72 let idx = this.array.length - 173 if (val < this.array[this.getParent(idx)]){74 this.siftUp(idx)75 }76 }77 siftUp(idx){78 if (idx === 1) return;79 let parentIdx = this.getParent(idx)80 if (this.array[parentIdx] > this.array[idx]){81 [this.array[parentIdx], this.array[idx]] = [this.array[idx], this.array[parentIdx]]82 this.siftUp(parentIdx)83 }84 }85 deleteMin(){86 if (this.array.length === 2) return this.array.pop()87 if (this.array.length === 1) return null;88 let min = this.array[1]89 this.array[1] = this.array.pop()90 this.siftDown(1)91 return min92 }93 siftDown(idx){94 let val = this.array[idx]95 let left = this.getLeftChild(idx)96 let right = this.getRightChild(idx)...
m_sift_up.js
Source:m_sift_up.js
1function siftUp(heap, idx) {2 if(idx === 1){3 return idx;4 }5 let parent_index = Math.floor(idx / 2);6 if( heap[parent_index] < heap[idx] ){7 let tmp = heap[parent_index];8 heap[parent_index] = heap[idx];9 heap[idx] = tmp;10 return siftUp(heap, parent_index);11 }12 return idx;13}14// function test() {15// var sample = [-1, 12, 6, 8, 3, 15, 7];16// console.log( siftUp(sample, 5) );17// }...
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 await page.screenshot({ path: 'google.png' });7 await browser.close();8})();9at Object.<anonymous> (/Users/username/Desktop/playwrighttest/test.js:6:17)10at Module._compile (internal/modules/cjs/loader.js:1200:30)11at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)12at Module.load (internal/modules/cjs/loader.js:1050:32)13at Function.Module._load (internal/modules/cjs/loader.js:938:14)14at Module.require (internal/modules/cjs/loader.js:1090:19)15at require (internal/modules/cjs/helpers.js:75:18)16at Object.<anonymous> (/Users/username/Desktop/playwrighttest/node_modules/playwright/lib/server/protocol.js:1:1)17at Module._compile (internal/modules/cjs/loader.js:1200:30)18at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)19const { chromium } = require('playwright');20(async () => {21 const browser = await chromium.launch();22 const context = await browser.newContext();23 const page = await context.newPage();24 await page.siftUp(100, 200);25 await page.screenshot({ path: 'google.png' });26 await browser.close();27})();28const { chromium } = require('playwright');29(async () => {30 const browser = await chromium.launch();31 const context = await browser.newContext();32 const page = await context.newPage();33 await page.siftUp();34 await page.screenshot({ path: 'google
Using AI Code Generation
1const { Page } = require('playwright');2const { Screenshotter } = require('playwright/lib/server/screenshotter');3const { ScreenshotterDelegate } = require('playwright/lib/server/screenshotterDelegate');4const { ScreenshotterDelegateImpl } = require('playwright/lib/server/screenshotterDelegateImpl');5const page = new Page();6const screenshotter = new Screenshotter(new ScreenshotterDelegateImpl(page));7const screenshotterDelegate = new ScreenshotterDelegate(screenshotter);8const elementHandle = await page.$('#someElement');9await screenshotterDelegate.siftUp(elementHandle);10const { Page } = require('playwright');11const { Screenshotter } = require('playwright/lib/server/screenshotter');12const { ScreenshotterDelegate } = require('playwright/lib/server/screenshotterDelegate');13const { ScreenshotterDelegateImpl } = require('playwright/lib/server/screenshotterDelegateImpl');14const page = new Page();15const screenshotter = new Screenshotter(new ScreenshotterDelegateImpl(page));16const screenshotterDelegate = new ScreenshotterDelegate(screenshotter);17const elementHandle = await page.$('#someElement');18await screenshotterDelegate.siftUp(elementHandle);19const { Page } = require('playwright');20const { Screenshotter } = require('playwright/lib/server/screenshotter');21const { ScreenshotterDelegate } = require('playwright/lib/server/screenshotterDelegate');22const { ScreenshotterDelegateImpl } = require('playwright/lib/server/screenshotterDelegateImpl');23const page = new Page();24const screenshotter = new Screenshotter(new ScreenshotterDelegateImpl(page));25const screenshotterDelegate = new ScreenshotterDelegate(screenshotter);26const elementHandle = await page.$('#someElement');27await screenshotterDelegate.siftUp(elementHandle);28const { Page } = require('playwright');29const { Screenshotter } = require('playwright/lib/server/screenshotter');30const { ScreenshotterDelegate } = require('playwright/lib/server/screenshotterDelegate');31const { ScreenshotterDelegateImpl } = require('playwright/lib/server/screenshotterDelegateImpl');32const page = new Page();33const screenshotter = new Screenshotter(new ScreenshotterDelegate
Using AI Code Generation
1const { Playwright } = require('playwright');2const { Screenshotter } = require('playwright/lib/server/screenshotter');3const { ScreenshotterDelegate } = require('playwright/lib/server/screenshotterDelegate');4const { ScreenshotterDelegateImpl } = require('playwright/lib/server/screenshotterDelegateImpl');5const { Page } = require('playwright/lib/server/page');6const { Frame } = require('playwright/lib/server/frame');7const { FrameTree } = require('playwright/lib/server/frameTree');8const { chromium } = require('playwright');9(async () => {10 const browser = await chromium.launch();11 const context = await browser.newContext();12 const page = await context.newPage();13 const screenshotter = new Screenshotter();14 const screenshotterDelegate = new ScreenshotterDelegateImpl();15 await screenshotter.initialize(screenshotterDelegate);16 const frameTree = new FrameTree(page);17 const frame = new Frame(frameTree, '', null);18 const delegate = new ScreenshotterDelegateImpl();19 await frame.initialize(delegate);20 const screenshot = await screenshotter.screenshotPage(page, {21 viewport: {22 },23 });24 console.log(screenshot);25 await browser.close();26})();
Using AI Code Generation
1const { Playwright } = require('@playwright/test');2const { BrowserContext } = require('@playwright/test/lib/server/browserContext');3const { Page } = require('@playwright/test/lib/server/page');4const { Screenshotter } = require('@playwright/test/lib/server/screenshotter');5const { Test } = require('@playwright/test/lib/test/test');6const { TestRunner } = require('@playwright/test/lib/test/testRunner');7const test = Test.create();8const runner = new TestRunner([test]);9runner.run().then(() => {10 const context = test._browserContext;11 const page = test._page;12 const screenshotter = new Screenshotter(context);13 const { _pageProxy } = page;14 const { _browserContextProxy } = context;15 const { _browserProxy } = context._browser;16 const { _delegate } = _browserProxy;17 const { _browser } = _delegate;18 const { _transport } = _browser;19 const { _screenshotter } = _transport;20 const { _dispatcher } = _screenshotter;21 const { _connection } = _dispatcher;22 const { _sessions } = _connection;23 const session = _sessions.get(_browserContextProxy._guid);24 const { _object } = session;25 const { _screenshotter } = _object;26 const { _delegate } = _screenshotter;27 const { _screenshotter } = _delegate;28 const { _screenshotter } = _screenshotter;29 const { _delegate } = _screenshotter;30 const { _screenshotter } = _delegate;31 const { _screenshotter } = _screenshotter;32 const { _delegate } = _screenshotter;33 const { _screenshotter } = _delegate;34 const { _screenshotter } = _screenshotter;35 const { _delegate } = _screenshotter;36 const { _screenshotter } = _delegate;37 const { _screenshotter } = _screenshotter;38 const { _delegate } = _screenshotter;39 const { _screenshotter } = _delegate;40 const { _screenshotter } = _screenshotter;41 const { _delegate } = _screenshotter;42 const { _screenshotter } = _delegate;
Using AI Code Generation
1const { Playwright } = require('playwright-core');2const { Screenshotter } = require('playwright-core/lib/server/screenshotter');3const { ScreenshotterDelegate } = require('playwright-core/lib/server/screenshotterDelegate');4const { Page } = require('playwright-core/lib/server/page');5const { BrowserContext } = require('playwright-core/lib/server/browserContext');6const { Browser } = require('playwright-core/lib/server/browser');7const { Frame } = require('playwright-core/lib/server/frames');8const { ScreenshotterDelegate } = require('playwright-core/lib/server/screenshotterDelegate');9const { Screenshotter } = require('playwright-core/lib/server/screenshotter');10const browser = await Playwright.chromium.launch();11const context = await browser.newContext();12const page = await context.newPage();13const screenshotter = new Screenshotter(new ScreenshotterDelegate(), page);14const elementHandle = await page.$('input[name="q"]');15const boundingBox = await elementHandle.boundingBox();16await screenshotter.screenshotElement(elementHandle, {17 clip: { x: boundingBox.x, y: boundingBox.y, width: boundingBox.width, height: boundingBox.height },18});
Using AI Code Generation
1const {siftUp} = require('playwright/lib/server/keyboard');2siftUp();3const {siftDown} = require('playwright/lib/server/keyboard');4siftDown();5const {siftLeft} = require('playwright/lib/server/keyboard');6siftLeft();7const {siftRight} = require('playwright/lib/server/keyboard');8siftRight();9const {siftPageUp} = require('playwright/lib/server/keyboard');10siftPageUp();11const {siftPageDown} = require('playwright/lib/server/keyboard');12siftPageDown();13const {siftHome} = require('playwright/lib/server/keyboard');14siftHome();15const {siftEnd} = require('playwright/lib/server/keyboard');16siftEnd();17const {siftTab} = require('playwright/lib/server/keyboard');18siftTab();19const {siftEnter} = require('playwright/lib/server/keyboard');20siftEnter();21const {siftEscape} = require('playwright/lib/server/keyboard');22siftEscape();23const {siftBackspace} = require('playwright/lib/server/keyboard');24siftBackspace();25const {siftDelete} = require('playwright/lib/server/keyboard');26siftDelete();27const {siftInsert} = require('playwright/lib/server/keyboard');28siftInsert();29const {siftF1} = require('playwright/lib/server/keyboard');30siftF1();
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 await page.click('text=France');7 await page.click('text=Germany');8 await page.click('text=UK');9 await page.click('text=USA');10 await page.click('text=Japan');11 await page.click('text=India');12 await page.click('text=China');13 await page.click('text=Italy');14 await page.click('text=Spain');15 await page.click('text=Romania');16 await page.click('text=Canada');17 await page.click('text=France');18 await page.click('text=Germany');19 await page.click('text=UK');20 await page.click('text=USA');21 await page.click('text=Japan');22 await page.click('text=India');23 await page.click('text=China');24 await page.click('text=Italy');25 await page.click('text=Spain');26 await page.click('text=Romania');27 await page.click('text=Canada');28 await page.click('text=France');29 await page.click('text=Germany');30 await page.click('text=UK');31 await page.click('text=USA');32 await page.click('text=Japan');33 await page.click('text=India');34 await page.click('text=China');35 await page.click('text=Italy');36 await page.click('text=Spain');37 await page.click('text=Romania');38 await page.click('text=Canada');39 await page.click('text=France');40 await page.click('text=Germany');41 await page.click('text=UK');42 await page.click('text=USA');43 await page.click('text
Using AI Code Generation
1const { PlaywrightInternal } = require('playwright/lib/server/playwright');2const { Page } = require('playwright/lib/server/page');3const internal = new PlaywrightInternal();4const page = new Page(internal, 'page1', {}, () => {});5page._siftUp(1);6console.log(page._priorityQueue);7import { PlaywrightInternal } from 'playwright/lib/server/playwright';8import { Page } from 'playwright/lib/server/page';9const internal = new PlaywrightInternal();10const page = new Page(internal, 'page1', {}, () => {});11page._siftUp(1);12console.log(page._priorityQueue);
Using AI Code Generation
1const path = require('path');2const { Playwright } = require('@playwright/test');3const { test } = Playwright;4const { testInfo } = require('./utils');5const { expect } = require('@playwright/test');6const { describe, it, beforeAll, afterAll } = test;7const { getTestState, setupTestBrowserHooks } = require('./utils');8const { setTestOptions } = require('@playwright/test');9setTestOptions({10});11describe('test', () => {12 beforeAll(async ({ browser }) => {13 const page = await browser.newPage();14 await page.waitForSelector('input[name="q"]');15 await page.fill('input[name="q"]', 'playwright');16 });17 it('test', async ({ browser }) => {18 const page = await browser.newPage();19 await page.waitForSelector('input[name="q"]');20 await page.fill('input[name="q"]', 'playwright');21 });22});23const { Playwright } = require('@playwright/test');24const { test } = Playwright;25const { testInfo } = require('./utils');26const { expect } = require('@playwright/test');27const { describe, it, beforeAll, afterAll } = test;28const { getTestState, setupTestBrowserHooks } = require('./utils');29const { setTestOptions } = require('@playwright/test');30setTestOptions({31});32describe('test', () => {33 beforeAll(async ({ browser }) => {34 const page = await browser.newPage();35 await page.waitForSelector('input[name="q"]');36 await page.fill('input[name="q"]', 'playwright');37 });38 it('test', async ({ browser }) => {39 const page = await browser.newPage();40 await page.waitForSelector('input[name="q"]');41 await page.fill('input[name="q"]', 'playwright');42 });43});
Using AI Code Generation
1const {siftUp} = require('playwright/lib/utils/stackTrace');2const {createTestState} = require('playwright/lib/utils/test');3const testState = createTestState();4testState.attachToError = function(error) {5 const stack = error.stack || '';6 const frames = stack.split('7');8 frames.splice(1, 0, ' at ' + siftUp('test.js', 1));9 error.stack = frames.join('10');11};12const error = new Error('Test Error');13testState.attachToError(error);14throw error;15 at siftUp (/Users/anshul/.nvm/versions/node/v14.16.0/lib/node_modules/playwright/lib/utils/stackTrace.js:12:18)16 at Object.<anonymous> (/Users/anshul/Desktop/test.js:9:7)17 at Module._compile (node:internal/modules/cjs/loader:1108:14)18 at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)19 at Module.load (node:internal/modules/cjs/loader:988:32)20 at Function.Module._load (node:internal/modules/cjs/loader:828:14)21 at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
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!!