How to use readOperator method in Playwright Internal

Best JavaScript code snippet using playwright-internal

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

calculator.js

Source: calculator.js Github

copy
1var num1str = "";
2var num2str = "";
3var readOperator = "";
4var intermediateResult = 0;
5var isIntermediateResultPresent = false;
6var existPoint = false;
7var countOperator = 0;
8var countPoint = 0;
9
10const digits = document.querySelectorAll('.digit').forEach(item => {
11    item.addEventListener('click', event => {
12        itemString = item.innerText;
13        //doesn't allow entering multiple points decimals
14        if (itemString === "." && countPoint !== 0) {
15            return;
16        } else if(itemString === "." && countPoint === 0) {
17            countPoint++;
18            storeVariable(itemString);
19            display(num1str);
20        } else {
21            storeVariable(itemString);
22            display(num1str);
23        }
24    });
25});
26
27const operators = document.querySelectorAll('.operator').forEach(item => {
28    item.addEventListener('click', event => {
29        countPoint=0;
30        //doesn't allow entering first an operator
31        if (num1str != "") {
32        itemOperator = item.innerText;
33        } else {
34            return;
35        }
36        //first operator
37        if (countOperator === 0) {
38            num2str = num1str;
39            storeOperator(itemOperator);
40            display(readOperator);
41            num1str = ""; 
42
43        //every other operator
44        } else {
45            isIntermediateResultPresent = true;
46            intermediateResult = operate(num2str, readOperator, num1str);
47            secondaryDisplay(num2str, readOperator, num1str);
48            num2str = intermediateResult;
49            storeOperator(itemOperator);
50            display(readOperator);
51            intermediateResult = "";
52            num1str = "";
53        }
54        countOperator++;
55    });
56});
57
58const equal = document.getElementById('equal').addEventListener('click', event => {
59    if (num2str != "" && readOperator != "") {
60        if (num2str == "Math Error!" || (num2str != "" && readOperator !="%" && num1str === "")) {
61            secondaryDisplay(" ", " ", " ");
62            display("Math Error!");
63        } else {
64            intermediateResult = operate(num2str, readOperator, num1str);
65            secondaryDisplay(num2str, readOperator, num1str);
66            num2str = intermediateResult;
67            display(intermediateResult);
68        }
69    //empty variables
70    clearDisplay();
71    } 
72    secondaryDisplay(" "," "," ",);
73});
74
75const clear =  document.getElementById('clear').addEventListener('click', event => {
76    clearDisplay();
77    secondaryDisplay(" "," "," ",);
78    display(" ");
79});
80
81const back = document.getElementById('backspace').addEventListener('click', event => {
82    var newNum1str = num1str.slice(0, -1);
83    num1str = newNum1str;
84    countPoint = 0;
85    display(num1str);
86})
87
88//operational functions
89function adding(num1, num2) {return num1 + num2;} 
90function subtracting(num1, num2) {return num1 - num2;}
91function multiplying(num1, num2) {return num1 * num2;}
92function dividing(num1, num2) {return num1/num2;}
93function exponential(num1, num2) {return num1**num2;}
94function percentage(num1) {return num1/100;}
95function operate(num1, operator, num2) {
96    let result;
97    let resultStr;
98    if (typeof(num1) != "number" && typeof(num2) != "number") {
99        num1Float = parseFloat(num1);
100        num2Float = parseFloat(num2);
101        switch(true) {
102            case operator === "+":
103                result = adding(num1Float, num2Float);
104                resultStr = result.toString();
105                return resultStr;
106            break;
107            case operator === "-":
108                result = subtracting(num1Float, num2Float);
109                resultStr = result.toString();
110                return resultStr;
111            break;
112            case operator === "*":
113                result = multiplying(num1Float, num2Float);
114                resultStr = result.toString();
115                return resultStr;
116            break;
117            case operator === "/":
118                if (num2Float == 0) {
119                    resultStr = "Math Error!";
120                } else {
121                result = dividing(num1Float, num2Float);
122                resultStr = result.toString();
123                }
124                return resultStr;
125            break;
126            case operator === "^":
127                result = exponential(num1Float, num2Float);
128                resultStr = result.toString();
129                return resultStr;
130            break;
131            case operator === "%":
132                result = percentage(num1Float);
133                resultStr = result.toString();
134                return resultStr;
135            break;
136        }
137    }
138}
139
140//helping functions
141function storeVariable(stringValue) {
142    if (stringValue === "+/-"){ 
143        if (num1str !== "") {
144            var stringArray = num1str.split('');
145            stringArray.unshift('-');
146            var newString = stringArray.join('');
147            num1str = newString; 
148        }
149        else {
150            stringValue = "-";
151            num1str = stringValue;
152        }
153    } else if (!intermediateResult) {
154        var firstDigit = stringValue;
155        num1str += firstDigit;
156    }   
157}
158
159function storeOperator(operator) {readOperator=operator;}
160
161function display(displayValue) {document.querySelector('.main-display').innerText=displayValue;}
162function secondaryDisplay(value1, value2, value3) {document.querySelector('.second-display').innerText=value1.concat(value2, value3);}
163
164function clearDisplay() {
165    countPoint = 0;
166    countOperator = 0;
167    intermediateResult = 0;
168    isIntermediateResultPresent = false;
169    existPoint = false;
170    num1str = "";
171    num2str = "";
172    readOperator = "";
173}
Full Screen

orc-parser.js

Source: orc-parser.js Github

copy
1//
2// orc-parser.js -- JavaScript source to parse Orc text for the CodeMirror editor
3// Project Orchard
4//
5// Copyright (c) 2011 The University of Texas at Austin. All rights reserved.
6//
7// Use and redistribution of this file is governed by the license terms in
8// the LICENSE file found in the project's top-level directory and also found at
9// URL: http://orc.csres.utexas.edu/license.shtml .
10//
11
12/**
13 * Syntax-highlighting parser for Orc.
14 * - This depends on the CodeMirror library: http://marijn.haverbeke.nl/codemirror
15 * - Recognizes the following syntactic entities
16 *   - combinator, pattern, site, variable, keyword, literal, comment
17 * - The actual parsing is very shallow, mostly we just tokenize
18 * - sites are distinguished from variables based on whether they
19 *   are followed by a "(".
20 * - The actual styles are defined in orc-syntax.css
21 */
22Editor.Parser = (function() {
23
24// 2-character symbolic tokens
25var ops2 = {
26"{-": readCommentML,
27"<:": readOperator,
28":=": readOperator,
29":>": readOperator,
30"<=": readOperator,
31">=": readOperator,
32"||": readOperator,
33"&&": readOperator,
34"--": readCommentSL,
35"/=": readOperator,
36"{.": readOperator,
37".}": readOperator };
38
39// 1-character symbolic tokens
40var ops1 = {
41"<": readCombinator,
42">": readCombinator,
43"|": readCombinator,
44":": readOperator,
45"&": readOperator,
46"-": readOperator,
47"/": readOperator,
48";": readCombinator,
49',': readOperator,
50'!': readOperator,
51'=': readOperator,
52'(': readOperator,
53')': readOperator,
54'.': readOperator,
55'[': readOperator,
56']': readOperator,
57'#': readOperator,
58'~': readOperator,
59'+': readOperator,
60'*': readOperator,
61'%': readOperator,
62'@': readOperator,
63'?': readOperator,
64'"': readString };
65
66// useful matchers
67var isWord = matcher(/[\w_0-9']/);
68var isDigit = matcher(/[0-9]/);
69
70/**
71 * Custom tokenizer. This always separates whitespace and
72 * non-whitespace tokens so we can get more accurate information
73 * for indentation. We may have to rethink that if it makes the parser
74 * inefficient.
75 */
76function tokenizer(source, state) {
77	function isSpace(ch) {
78		// The messy regexp is because IE's regexp matcher is of the
79		// opinion that non-breaking spaces are no whitespace.
80		return ch != "\n" && /^[\s\u00a0]$/.test(ch);
81	}
82
83	function out(token) {
84		token.value = token.content = (token.content || "") + source.get();
85		return token;
86	}
87
88	function next() {
89		var token;
90		if (!source.more()) throw StopIteration;
91		if (source.peek() == "\n") {
92			source.next();
93			return out({ type:"whitespace", style:"whitespace" });
94		} else if (source.applies(isSpace)) {
95			source.nextWhile(isSpace);
96			return out({ type:"whitespace", style:"whitespace" });
97		} else {
98			while (!token) token = state(source, function (s) { state = s; });
99			return out(token);
100		}
101	}
102
103	return { next: next, state: function() { return state; } };
104}
105
106/**
107 * Read one token.
108 */
109function readToken(source, setState) {
110	var ch1 = source.next();
111	var ch2 = ch1 + source.peek();
112	var reader;
113	// try to match 2 and 1 character symbolic tokens,
114	// then try numbers, then try words
115	if ((reader = ops2[ch2])) {
116		source.next();
117		return reader(source, setState, ch2);
118	} else if ((reader = ops1[ch1])) {
119		return reader(source, setState, ch1);
120	} else if (isDigit(ch1)) {
121		return readNumber(source, setState, ch1);
122	} else {
123		return readWord(source, setState, ch1);
124	}
125}
126
127function readOperator(_1, _2, type) {
128	return { type:type, style:"operator" };
129}
130
131function readCombinator(_1, _2, type) {
132	return { type:type, style:"combinator" };
133}
134
135function readNumber(source, _, ch1) {
136	source.nextWhile(isDigit);
137	if (source.peek() == ".") {
138		source.next();
139		source.nextWhile(isDigit);
140	}
141	if (source.peek() == "E" || source.peek() == "e") {
142		source.next();
143		switch (source.peek()) {
144		case "-": case "+":
145			source.next();
146		}
147		source.nextWhile(isDigit);
148	}
149	// FIXME: handle decimals
150	return { type:"number", style:"literal" };
151}
152
153function readWord(source, _, ch1) {
154	source.nextWhile(isWord);
155	var word = source.get();
156	switch (word) {
157	// literals
158	case "true": case "false": case "null":
159		return { type:word, content:word, style:"literal" };
160	// keywords
161	case "as": case "def": case "else": case "if": case "import":
162	case "include": case "lambda": case "signal": case "stop":
163	case "then": case "type": case "val": case "_":
164		return { type:word, content:word, style:"keyword" };
165	default:
166		return { type:"variable", content:word, style:"variable" };
167	}
168}
169
170function readString(source, setState, _) {
171	setState(readString);
172	while (!source.endOfLine()) {
173		var ch = source.next();
174		if (ch == '"') {
175			setState(readToken);
176			break;
177		} else if (ch == '\\' && !source.endOfLine()) {
178			source.next();
179		}
180	}
181	return { type:"string", style:"literal" };
182}
183
184function readCommentML(source, setState) {
185	setState(readCommentML);
186	while (!source.endOfLine()) {
187		var ch = source.next();
188		if (ch == "-" && source.peek() == "}") {
189			source.next();
190			setState(readToken);
191			break;
192		}
193	}
194	return { type:"comment", style:"comment" };
195}
196
197function readCommentSL(source, setState, _) {
198	while (!source.endOfLine()) source.next();
199	return { type:"comment", style:"comment" };
200}
201
202/**
203 * Orc parser factory. A codemirror parser is just a token stream
204 * with a copy method that is used to cache the parser state at the
205 * start of each line.
206 */
207function newParser(source) {
208	var tokensState = readToken;
209	var tokens = tokenizer(source, tokensState);
210	// buffer for look-ahead tokens; holds {token, state} records
211	var lookahead = [];
212	// while looking, where are we in the lookahead buffer?
213	var lookaheadIndex = 0;
214	// the current tabstop column
215	var tabstop = null;
216	// are we inside a pattern?
217	var inPattern = false;
218	// are we immediately preceeded by whitspace?
219	var inWhitespace = false;
220	/** Reset the lookahead pointer to the current token. */
221	function startLooking() {
222		lookaheadIndex = 0;
223	}
224	/** Get the next token for real and move the "current" token pointer. */
225	function nextToken() {
226		startLooking();
227		if (lookahead.length) {
228			var r = lookahead.shift();
229			tokensState = r.state;
230			return r.token;
231		} else {
232			var out = tokens.next();
233			tokensState = tokens.state();
234			return out;
235		}
236	}
237	/**
238	 * Get the next token speculatively. Repeated calls
239	 * will move forward in the token stream. May be reset
240	 * to the "current" token using startLooking().
241	 */
242	function look() {
243		try {
244			if (lookahead.length > lookaheadIndex) {
245				return lookahead[lookaheadIndex++].token;
246			} else {
247				lookahead.push({token: tokens.next(), state: tokens.state()});
248				return look();
249			}
250		} catch (e) {}
251	}
252	/** Get the next token and change its style based on the parse state. */
253	function next() {
254		var out = nextToken();
255		// if we're in a pattern, apply the "pattern" style
256		if (inPattern) out.style += " pattern";
257		if (out.content == "\n") {
258			if (tabstop == null) tabstop = 0;
259			var _tabstop = tabstop;
260			out.indentation = function (start) {
261				return _tabstop;
262			};
263			tabstop = null;
264		} else {
265			// if the variable is in function call position,
266			// change it to a "site"
267			if (out.type == "variable") {
268				startLooking();
269                var tmp;
270				do {
271					tmp = look();
272					if (!tmp) break;
273					if (tmp.type == "(" || tmp.type == "[") {
274						out.style = "site";
275						break;
276					}
277				} while (tmp.type == "whitespace");
278			}
279			// if no tabstop has been set yet, use the
280			// length of the first whitespace token
281			if (tabstop == null) {
282				if (out.type == "whitespace") {
283					tabstop = out.value.length;
284				} else {
285					tabstop = 0;
286				}
287			}
288		}
289		inWhitespace = (out.type == "whitespace");
290		return out;
291	}
292	function copy() {
293		var _tokensState = tokensState;
294		var _inPattern = inPattern;
295		return function (source) {
296			tokens = tokenizer(source, _tokensState);
297			tokensState = _tokensState;
298			inPattern = _inPattern;
299			// the copy starts at the beginning
300			// of the line, so most of the within-line
301			// state should just be reset
302			lookahead = [];
303			lookaheadIndex = 0;
304			tabstop = null;
305			inWhitespace = true;
306			return parser;
307		};
308	}
309	var parser = { next: next, copy: copy };
310	return parser;
311}
312
313return { make: newParser };
314
315})();
316
Full Screen

part2.js

Source: part2.js Github

copy
1let hexArray = [];
2let bits = [];
3let packets = [];
4
5let lineReader = require('readline').createInterface({
6  input: require('fs').createReadStream('Day16/input.txt')
7});
8
9lineReader.on('line', function (line) {
10  hexArray = line.match(/.{1,2}/g);
11});
12
13
14
15function printResult() {
16  for (let i = 0; i < template.length; i++) {
17    if (calc[template[i]] == undefined) {
18      calc[template[i]] = 1;
19      continue;
20    }
21
22    calc[template[i]]++;
23  }
24
25  let results = Object.values(calc);
26
27  console.log(Math.max.apply(null, results) - Math.min.apply(null, results));
28}
29
30function process() {
31  convertToBits();
32  console.log(bits.join(""));
33
34  let processing = true;
35  let index = 0;
36  let valueCount = 0;
37
38  while (processing) {
39    let newPacket = new Packet(index, bits);
40    index = newPacket.endingIndex;
41    processing = newPacket.isLastPacket;
42    valueCount += newPacket.value;
43    packets.push(newPacket);
44  }
45
46  console.log(valueCount);
47}
48
49function convertToBits() {
50  hexArray.forEach(str => {
51    bits.push(...hexTobinary(str));
52  })
53}
54
55function hexTobinary(hex) {
56  return (parseInt(hex, 16).toString(2)).padStart(8, '0').split("");
57}
58
59class Packet {
60  constructor(index, bits) {
61    this.children = [];
62    this.bits = bits;
63    this.startingIndex = index;
64    this.endingIndex = null;
65    this.isLastPacket = false;
66
67    this.version = 0;
68    this.packetType = 0;
69    this.value = 0;
70
71    this.process();
72  }
73
74  process() {
75    this.readVersion();
76    this.readPacketType();
77    this.value = this.readData();
78
79    this.endingIndex = this.startingIndex;
80
81    if (this.endingIndex == this.bits.length) {
82      this.isLastPacket = true;
83    }
84  }
85
86  readVersion() {
87    let versionStr = this.bits.slice(this.startingIndex, this.startingIndex + 3).join("");
88    this.startingIndex += 3;
89    this.version += this.binaryToDecimal(versionStr);
90  }
91
92  readPacketType() {
93    let packetStr = this.bits.slice(this.startingIndex, this.startingIndex + 3).join("");
94    this.startingIndex += 3;
95    this.packetType = this.binaryToDecimal(packetStr);
96  }
97
98  readData() {
99    switch (this.packetType) {
100      case 0:
101        return this.processSum();
102        break;
103      case 1:
104        return this.processProduct();
105        break;
106      case 2:
107        return this.processMinimum();
108        break;
109      case 3:
110        return this.processMaximum();
111        break;
112      case 4:
113        return this.readLiteralValue();
114      case 5:
115        return this.processGreaterThan();
116        break;
117      case 6:
118        return this.processLessThan();
119        break;
120      case 7:
121        return this.processEqualTo();
122        break;
123      default:
124        this.readOperator(this.packetType);
125        break;
126    }
127  }
128  
129  processSum() {
130    // Packets with type ID 0 are sum packets - their value is the sum of the values of their sub-packets. If they only have a single sub-packet, their value is the value of the sub-packet.
131    
132    // V   T   ID    Length - 2    V    T  value  V   T   value
133    // 110 000 1    00000000010    110 100 00001 010 100 00010
134    let values = this.readOperator();
135    return values.reduce((x,y) => x + y);
136  }
137
138  processProduct() {
139    // Packets with type ID 1 are product packets - their value is the result of multiplying together the values of their sub-packets. If they only have a single sub-packet, their value is the value of the sub-packet.
140    let values = this.readOperator();
141    return values.reduce((x,y) => x * y);
142  }
143
144  processMinimum() {
145    // Packets with type ID 2 are minimum packets - their value is the minimum of the values of their sub-packets.
146    let values = this.readOperator();
147    return Math.min(...values);
148  }
149
150  processMaximum() {
151    // Packets with type ID 3 are maximum packets - their value is the maximum of the values of their sub-packets.
152    let values = this.readOperator();
153    return Math.max(...values);
154  }
155
156  processGreaterThan() {
157    // Packets with type ID 5 are greater than packets - their value is 1 if the value of the first sub-packet is greater than the value of the second sub-packet; otherwise, their value is 0. These packets always have exactly two sub-packets.
158    let values = this.readOperator();
159    return values[0] > values[1] ? 1 : 0;
160  }
161
162  processLessThan() {
163    // Packets with type ID 6 are less than packets - their value is 1 if the value of the first sub-packet is less than the value of the second sub-packet; otherwise, their value is 0. These packets always have exactly two sub-packets.
164    let values = this.readOperator();
165    return values[0] < values[1] ? 1 : 0;
166  }
167
168  processEqualTo() {
169    // Packets with type ID 7 are equal to packets - their value is 1 if the value of the first sub-packet is equal to the value of the second sub-packet; otherwise, their value is 0. These packets always have exactly two sub-packets.
170    let values = this.readOperator();
171    return values[0] == values[1] ? 1 : 0;
172  }
173
174  readLiteralValue() {
175    let processing = true;
176    let returnValue = "";
177
178    while (processing) {
179      let lastValue = this.bits[this.startingIndex] == "0";
180      this.startingIndex++;
181
182      returnValue += this.bits.slice(this.startingIndex, this.startingIndex + 4).join("");
183      this.startingIndex += 4;
184
185      processing = !lastValue;
186    }
187
188    return this.binaryToDecimal(returnValue);
189  }
190
191  readOperator() {
192    let lengthTypeId = this.bits[this.startingIndex];
193    this.startingIndex += 1;
194
195    let values = [];
196    // If the length type ID is 0, then the next 15 bits are a number that represents the total length in bits
197    if (lengthTypeId == "0") {
198      let lengthOfPacketsStr = this.bits.slice(this.startingIndex, this.startingIndex + 15).join("");
199      this.startingIndex += 15;
200      let subPacketLength = this.binaryToDecimal(lengthOfPacketsStr);
201      let targetEnd = this.startingIndex + subPacketLength;
202
203      let processing = true;
204      while (processing) {
205        this.readVersion();
206        this.readPacketType();
207        values.push(this.readData());
208
209        if (this.startingIndex == targetEnd) {
210          processing = false;
211        }
212      }
213
214    }
215
216    if (lengthTypeId == "1") {
217      let numberOfSubPacketsStr = this.bits.slice(this.startingIndex, this.startingIndex + 11).join("");
218      this.startingIndex += 11;
219      let numberOfSubPackets = this.binaryToDecimal(numberOfSubPacketsStr);
220
221      for (let i = 0; i < numberOfSubPackets; i++) {
222        this.readVersion();
223        this.readPacketType();
224        values.push(this.readData());
225      }
226    }
227
228    return values;
229
230    // If the length type ID is 1, then the next 11 bits are a number that represents the number of sub-packets immediately contained by this packet.
231  }
232
233  binaryToDecimal(str) {
234    return parseInt(str, 2);
235  }
236}
237
238lineReader.on('close', function () {
239  process();
240  // printResult();
241});
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Internal on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)