It’s job-hopping season again, so it’s time to brush up. Here’s a summary of some of the interview questions you might be asked
1. Swap two numbers without using variables
1. Arithmetic swap
For Number, or a variable type whose type can be converted to a Number
function swap(a, b) {
a = a + b;
b = a - b;
a = a - b;
}
Copy the code
By the tricks of the arithmetic process, the two values can be cleverly interchanged. However, there is a disadvantage of variable data overflow. Because JavaScript can store numbers with accuracy ranging from -2^53 to 2^53. So there’s an overflow problem with addition.
2. Xor operation
^ Bitwise xor is 0 if the two bits involved in the operation have the same value, otherwise it is 1. This algorithm can be implemented because of the characteristics of xor operation, which can flip some bits in the data and leave others unchanged. This means that any number and any given value are xor twice in a row, and the value remains the same.
a = a ^ b;
b = a ^ b;
a = a ^ b;
Copy the code
3. Deconstruction of ES6
[a, b] = [b, a];
Copy the code
More references:
- Juejin. Cn/post / 684490…
- www.jianshu.com/p/61370227d…
2. Implement the sum (1, 2, 3) = = sum (1) (2) (3)
function sum(. args){
function currySum(. rest){ args.push(... rest)return currySum
}
currySum.toString= function(){
return args.reduce((result,cur) = >{
return result + cur
})
}
currySum.toNumber= function(){
return args.reduce((result,cur) = >{
return result + cur
})
}
return currySum
}
Copy the code
More references: github.com/Advanced-Fr…
3. Observer vs. Publish-subscribe. Tell me the difference
The concept of the observer model
The observer pattern pattern, one of the behavioral patterns, defines a one-to-many dependency in which multiple observer objects listen on a subject object at the same time. This principal object notifies all observer objects of state changes, enabling them to update themselves automatically.
The concept of publishing the subscriber model
In the publish-subscribe model, the senders of messages are called publishers, and messages are not sent directly to specific recipients, called subscribers. This means that publishers and subscribers are unaware of each other’s existence. You need a third-party component, called a message mediator, that connects subscribers and publishers, and that filters and allocates all incoming messages. In other words, the publish-subscribe pattern is used to handle the exchange of information between different system components, even if they are unaware of each other’s existence.
The difference between
Let’s quickly summarize the differences:
In the observer mode, the observer is aware of the Subject, and the Subject keeps a record of the observer. However, in the publish-subscribe model, publishers and subscribers are unaware of each other’s existence. They communicate only through the message broker.
In the publish-subscribe pattern, components are loosely coupled, as opposed to the observer pattern.
The observer pattern is synchronous most of the time, such that when an event is triggered, the Subject calls the observer’s methods. The publish-subscribe pattern is asynchronous most of the time (using message queues).
The observer pattern needs to be implemented in a single application address space, whereas publish-subscribe is more like the cross-application pattern.
More: juejin. Cn/post / 684490… PS: it is best to write the model code of the corresponding pattern
4. Implement LRU algorithm
KV cache that implements an LRU expiration algorithm, all KV expiration intervals are the same, and it satisfies the following properties:
- Maximum storage n pairs of KV;
- If the number is greater than N, one KV that has expired will be removed at will.
- If there is no expired KV, one KV will be removed according to LRU rules.
- If the query has expired, return null;
class LRUCache {
constructor(capacity,intervalTime){
this.cache = new Map(a);this.capacity = capacity;
this.intervalTime = intervalTime;
}
get(key){
if(!this.cache.has(key)){
return null
}
const tempValue = this.cache.get(key)
this.cache.delete(key);
if(Date.now() - tempValue.time > this.intervalTime){
return null
}
this.cache.set(key, {value: tempValue.value, time: Date.now()})
return tempValue.value
}
put(key, value){
if(this.cache.has(key)){
this.cache.delete(key)
}
if(this.cache.size >= capacity){ / / is full
const keys = this.cache.keys()
this.cache.delete(keys.next().value)
}
this.cache.set(key, {value,time:Date.now()})
}
}
Copy the code
Cleverly takes advantage of the fact that the Map structure’s keys are ordered. The key of a normal Object is unordered.
5. How to monitor web crashes?
Crash statistics scheme based on Service Worker
With the popularity of the PWA concept, Service workers are becoming more and more familiar to everyone. We can use Service workers to monitor web crashes for the following reasons:
- The Service Worker has its own independent Worker thread, which is separated from the web page. If the web page crashes, the Service Worker will not crash in general.
- Service workers typically have longer life cycles than web pages and can be used to monitor the state of web pages;
- Web pages can be through the navigator. ServiceWorker. Controller. PostMessage API to run their own SW send messages.
Based on the above points, we can realize a monitoring scheme based on heartbeat detection:
- P1: after the web page is loaded, it sends a heartbeat to sw every 5s through postMessageAPI to indicate that it is online. Sw registers the online web page and updates the registration time.
- P2: Web pages in beforeUnload, through postMessageAPI to inform itself that it has been properly closed, sw will clear the registered web pages;
- P3: If the webpage crashes during running, the running state in SW will not be cleared, and the update time stays at the last heartbeat before crash.
- Sw: The Service Worker checks the registered web page every 10 seconds and finds that the registered time has exceeded a certain time (such as 15s), then the web page can be judged as crashing.
More: zhuanlan.zhihu.com/p/40273861
6. Evaluate the code output and say why
var obj = {
'2':3.'3':4.'length':2.'splice':Array.prototype.splice,
'push':Array.prototype.push
}
obj.push(1)
obj.push(2)
obj.push(3)
console.log(obj)
Copy the code
The answer:
{
'2':1
'3':2.'4':3.'length':5.'splice':Array.prototype.splice,
'push':Array.prototype.push
}
Copy the code
Obj has length, which is like an array, and when you call push, you add an item to the end of the array, and the first time you call push, which is like length 3, then the item with subscript 2 is assigned 1, subscript 2, and when it’s the key of the object, it implicitly calls toString toString 2, Obj has the same key ‘2’ as obj does, so the value with key 2 is overwritten. And so on for the next two pushes.
Details: github.com/LuckyWinty/…
7. What is the difference between setTimeout and setImmediate
SetImmediate () is similar to setTimeout(), but depending on the timing of the call, they behave differently.
- SetImmediate setImmediate is designed to perform when the poll phase is complete, the Check phase;
- The setTimeout design is executed when the poll phase is idle and the set time is up, but it is executed during the timer phase
The order in which timers are executed will vary depending on the context in which they are invoked. If both are called from within the main module, the timer is constrained by process performance. For example, there is code like this:
setTimeout((a)= > console.log(1));
setImmediate((a)= > console.log(2));
Copy the code
The code above should print 1 and then 2, but when executed, the result is inconclusive, and sometimes 2 and then 1.
This is because the second argument to setTimeout defaults to 0. In fact, Node takes at least 1 millisecond, and the second parameter ranges from 1 millisecond to 2,147,483,647 milliseconds, according to the official documentation. In other words, setTimeout(f, 0) is the same as setTimeout(f, 1).
When you actually execute, once you get into the event loop, it might be 1 millisecond, or it might not be 1 millisecond, depending on what the system is doing. If less than 1 millisecond is reached, the Timers phase is skipped and proceeds to the Check phase, where the setImmediate callback function is first executed.
However, if this is the case, the output order is fixed, for example:
const fs = require('fs');
fs.readFile('test.js', () => {
setTimeout((a)= > console.log(1));
setImmediate((a)= > console.log(2));
});
Copy the code
In the above code, 2 must be printed first, then 1. The poll state does not allow the operator to perform the callback. The poll state does not allow the operator to perform the callback. The poll state does not allow the operator to perform the callback. The Poll state does not allow the operator to perform the callback. Then execute setTimeout.
8. Write a re that takes the value in the cookie based on name.
function get(name){
var reg = new RegExp(name+'= (/ ^; *)? (; | $) ');
var res = reg.exec(document.cookie);
if(! res || ! res[1])return ' ';
try{
if(/(%[0-9A-F]{2}){2,}/.test(res)){/ / utf8 encoding
return decodeURIComponent(res);
}else{/ / unicode
return unescape(res); }}catch(e){
return unescape(res); }}Copy the code
In regular expressions, focus on these lines: ‘([^;]). )’, meaning that the match after STR = is not; ([^;] It means non-set, that is, all not; ), which occurs 0 or more times (), after which the matched string is placed in the first capture group.
Details: github.com/LuckyWinty/…
9. Write at least seven ways to achieve the following layout without changing the HTML structure.
Requirements: 2 columns on the left, 1 column on the right, adaptive in the middle
<div class="parent" style="width: 200px">
<div class="child child1" style="width: 20px"></div>
<div class="child child2" style="width: 20px">2</div>
<div class="child child3" style="width: 20px">3</div>
</div>
Copy the code
The answer:
/ * 1 * /
.parent{
background-color: burlywood;
display: flex;
}
.child{
background-color: black;
font-size: 20px;
color: white;
}
.child3{
margin-left: auto;
}
/ * 2 * /
.parent{
background-color: burlywood;
position: relative;
}
.child{
font-size: 20px;
color: white;
}
.child1{
background-color: black;
position: absolute;
left: 0;
}
.child2{
background-color: black;
position: absolute;
left: 20px;
}
.child3{
background-color: black;
position: absolute;
right: 0;
}
/ * * / 3
.parent{
background-color: burlywood;
}
.child1{
background-color: black;
float: left;
}
.child2{
background-color: red;
float: left;
}
.child3{
float: right;
background-color: blue
}
/ * * / 4
.parent{
background-color: burlywood;
display: table;
}
.child{
background-color: black;
display: table-cell;
height: 20px;
}
.child3{
display: block;
margin-left: auto;
}
/ * * / 5
.parent{
background-color: burlywood;
position: relative;
}
.child{
background-color: black;
position: absolute;
top:0;
left:0;
}
.child2{
transform: translate(20px, 0);
}
.child3{
transform: translate(180px, 0);
}
/ * * / 6
.parent{
background-color: burlywood;
display: grid;
grid-template-columns: repeat(10, 1fr);
}
.child{
background-color: black;
font-size: 20px;
color:white;
}
.child3{
grid-column: 10 / 11;
}
/ * * / 7
.parent{
background-color: burlywood;
font-size: 0;
}
.child{
background-color: black;
display: inline-block;
font-size: 20px;
color: white;
}
.child3{
margin-left: 140px;
}
Copy the code
10. Draw a fan with CSS?
width: 0;
height: 0;
border: solid 100px red;
border-color: red transparent transparent transparent;
border-radius: 100px;
Copy the code
instructions
Part of the title and answer of this article come from the network, if there is a mistake, welcome to correct, if there is a problem of infringement, please contact Winty230 wechat negotiation processing.
The last
- Welcome to add my wechat (Winty230), pull you into the technology group, long-term exchange learning…
- Welcome to pay attention to “front-end Q”, seriously learn front-end, do a professional technical people…