preface
One difference between this year and the past is that some big factories have added handwritten front-end logic or collection algorithms. Some of the front-end language features, asynchronous control relatively well prepared, are mostly the use of Promise plus recursion. Algorithms are harder to prepare. It takes a long time to accumulate. This article is divided into several categories to give examples. Throw away the jade.
Front-end language features
This part mainly investigates the understanding of JS language itself, such as this, the understanding of prototype chain, instanceOf, new keyword and so on.
- Implement bind for function
Function.prototype.mybind = function(context, ... args) {
let fun = this;
function bound(. args2) {
let self = this instanceof bound ? this : context;
return fun.apply(self, args.concat(args2));
}
bound.prototype = Object.create(fun.prototype);
return bound;
};
Copy the code
- Implement InstanceOf(look at the understanding of prototype chains)
function isInstanceOf(child, fun) {
if (typeoffun ! = ="function") {
throw new TypeError("arg2 fun is not a function");
}
if (child === null) {
return false;
}
if(child.__proto__ ! == fun.prototype) {return isInstanceOf(child.__proto__, fun);
}
return true;
}
Copy the code
- Implement the new keyword function (examine the process of new)
functionmyNew(fun, ... arg) {if(typeof fun ! = ="function") {
throw new TypeError(" fun is not a function");
}
let obj = {};
Object.setPrototypeOf(obj, fun.prototype);
fun.apply(obj, arg);
return obj;
}
Copy the code
- Implement the json.parse function
function JSONParse(strs) {
if (strs === "" || typeofstrs ! = ="string") {
throw new SyntaxError("JSONParse error");
}
if (strs[0= = ="{") {
let obj = {};
if (strs[strs.length - 1] = ="}") {
let fields = strs.substring(1, strs.length - 1).split(",");
for (let field of fields) {
let index = field.indexOf(":");
let temp = [];
if(index ! = =- 1) {
temp[0] = field.substring(0, index);
temp[1] = field.substring(index + 1, field.length);
}
let key = temp[0].substring(1, temp[0].length - 1);
let value = parseValue(temp[1]);
//if (value ! == undefined) {
obj[key] = value;
/ /}}}console.log("prase:", obj);
return obj;
}
if (strs[0= = ="[") {
if (strs[strs.length - 1] = ="]") {
let result = [];
let fields = strs.substring(1, strs.length - 1).split(",");
for (let field of fields) {
result.push(parseValue(field));
}
returnresult; }}}Copy the code
- Implement json.stringify
function JSONStringify(obj) {
if (
obj === undefined ||
obj === null ||
typeof obj === "string" ||
typeof obj === "boolean" ||
typeof obj === "number"
) {
return obj;
}
if (typeof obj === "function") {
return "";
}
if (Array.isArray(obj)) {
let result = [];
for (let i = 0; i < obj.length; i++) {
result.push(JSONStringify(obj[i]));
}
return "[" + result.join(",") + "]";
} else {
let result = [];
for (let key in obj) {
result.push(`"${key}":${JSONStringify(obj[key])}`);
}
return "{" + result.join(",") + "}"; }}Copy the code
- Implement an inheritance (prototype chain)
function myExtends(parent, child) {
function nop() {}
nop.prototype = parent.prototype;
child.prototype = new nop();
}
Copy the code
Front-end utility class
These are all higher-order functions (closures) on the front end. Usually used to solve general problems. The idea is very similar to AOP in J2EE (aspect oriented programming). Such as the debounce, memorize
- Implement debounce
debounce(fun, delay, immediate) {
let timer = null;
return (. args) = > {
if (timer) {
clearTimeout(timer);
} else {
timer = setTimeout((a)= > {
fun.apply(this, args); }, delay); }}; }Copy the code
- Implement throttle function
throttle(fun, delay, immediate) {
let flag = false;
return (. args) = > {
if(! flag) { flag =true;
setTimeout((a)= > {
fun.apply(this, args);
flag = false; }, delay); }}; },Copy the code
- Implement memeorize function, you can cache the results of the function. It accelerates after the second call.
memeorize(fun) {
let cache = {};
return (. args) = > {
const key = args.toString();
if (cache[key]) {
return cache[key];
}
let value = fun.apply(this, args);
cache[key] = value;
return value;
};
}
Copy the code
- Implement the promisy function. Convert a callback function to a promise chain call.
promisy(fun) {
return (. args) = > {
return new Promise((resolve, reject) = > {
try{ fun(... args, resolve); }catch(e) { reject(e); }}); }; }// How to use it
fun(arg1,callback);
let promisey = promisy(fun);
promisey().then((res) = >());
Copy the code
- Implement currying. This is the concept of functional programming. Currie. Distributes function calls with multiple arguments.
currying(fun) {
function helper(fn, ... arg1) {
let length = fn.length;
let self = this;
return function(. arg2) {
let arg = arg1.concat(arg2);
if (arg.length < length) {
returnhelper.call(self, fn, ... arg); }return fn.apply(this, arg);
};
}
return helper(fun);
}
/ / case
function add(a, b) {
return a + b;
}
let curryadd = util.currying(add);
let add1 = curryadd(1);
t.is(add1(2), 3);
Copy the code
- Format numbers in thousandths. Input 123456, output 123,456
formatNumber(number) {
if (typeofnumber ! = ="number") {
return null;
}
if (isNaN(number)) {
return null;
}
let result = [];
let tmp = number + "";
let num = number;
let suffix = "";
if (tmp.indexOf(".")! = =- 1) {
suffix = tmp.substring(tmp.indexOf(".") + 1);
num = parseInt(tmp.substring(0, tmp.indexOf(".")));
}
while (num > 0) {
result.unshift(num % 1000);
num = Math.floor(num / 1000);
}
let ret = result.join(",");
if(suffix ! = ="") {
ret += "." + suffix;
}
return ret;
}
Copy the code
Front-end logic control classes
Most of these questions are recursive and promise based. You can focus on the use of promise. Mastering Promise was a good way to solve these problems. – Implement a function of sleep. sleep(3000).then(()=>{})
function sleep(delay){
return new Promise((resolve,reject) = >{
setTimeout((a)= >{ resolve() },delay); })}Copy the code
– Implement a Promise ajax using XMLHttpRequest
function myRequest(url, method, params) {
return new Promise((resolve, reject) = > {
let xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onreadystatechange = (a)= > {
if(xhr.readyState ! =4) {
return;
}
if (xhr.state === 200) { resolve(xhr.response); }}; xhr.addEventListener("error", e => {
reject(error);
});
xhr.send(params);
});
}
Copy the code
-用promise 实现一个lazyman. LazyManAsync(“Hank”).sleepFirst(5).eat(“supper”); LazyManAsync(“Hank”).sleep(10).eat(“dinner”)
export function LazyManAsync(name) {
return new LazyManFactory(name);
}
function LazyManFactory(name) {
this.tasks = [];
this.tasks.push((a)= > {
return new Promise((resolve, reject) = > {
console.log("hi", name); resolve(); })}); setTimeout((a)= > {
this.run();
}, 0);
}
LazyManFactory.prototype.run = function () {
if (this.tasks.length === 0) {
return;
}
let task = this.tasks.shift();
task().then((a)= > {
this.run();
}).catch((a)= > {
this.run();
})
}
LazyManFactory.prototype.sleep = function (time) {
this.tasks.push((a)= > {
return new Promise((resolve, reject) = > {
setTimeout((a)= > {
resolve();
}, time * 1000)})})return this;
}
LazyManFactory.prototype.eat = function (name) {
this.tasks.push((a)= > {
return new Promise((resolve, reject) = > {
console.log("eat:", name); resolve(); })})return this;
}
LazyManFactory.prototype.sleepFirst = function (time) {
this.tasks.unshift((a)= > {
return new Promise((resolve, reject) = > {
setTimeout((a)= > {
resolve();
}, time * 1000)})})return this;
}
Copy the code
Algorithm class
This class usually involves algorithms. This part is not ready for a short time, so it can be reviewed as a long-term strategy. I’m only going to list the very high frequency simple questions for now. The actual interview can be much more difficult than this.
- The sum of two Numbers
const twoSum = function(arys, target) {
if (!Array.isArray(arys)) {
throw new TypeError("arg1 is not a array");
}
const map = new Map(a);for (let i = 0; i < arys.length; i++) {
let num = target - arys[i];
if(map.get(num) ! = =undefined) {
return [map.get(num), i];
}
map.set(arys[i], i);
}
return [];
};
Copy the code
- Quick sort
const quickSort = function(ary = [], start = 0, end = ary.length - 1) {
if (!Array.isArray(ary)) {
throw new TypeError("arg1 is not a array");
}
if (start >= end || isNaN(start) || isNaN(end)) {
return;
}
let index = partition(start, end);
quickSort(ary, start, index - 1);
quickSort(ary, index + 1, end);
function partition(left, right) {
let priviot = ary[right];
let k = left - 1;
for (let i = left; i <= right - 1; i++) {
if (ary[i] <= priviot) {
swap(++k, i);
}
}
swap(++k, right);
return k;
}
function swap(i, j) {
lettemp = ary[i]; ary[i] = ary[j]; ary[j] = temp; }};Copy the code
- Binary search. Given a sorted array, use binary search to find the target element.
const binarySearch = function(ary, target) {
if (!Array.isArray(ary)) {
throw new TypeError("arg1 is not a array");
}
let start = 0,
end = ary.length - 1;
while (start <= end) {
let mid = Math.floor(start + (end - start) / 2);
if (ary[mid] === target) {
return mid;
} else if (ary[mid] < target) {
start = mid + 1;
} else {
end = mid - 1; }}return - 1;
};
Copy the code
- Array shuffle. Shuffle the numbers in the array so that each position is equally likely.
const flush = function(num = []) {
for (let i = 0; i < num.length; i++) {
let index = Math.floor(Math.random() * (num.length - 1));
lettemp = num[i]; num[i] = num[index]; num[index] = temp; }};Copy the code
- Fibonacci sequence realization function F (n) = F (n-1)+ F (n-2)
const f = (n) = >{
if(n<0) {return 0;
}
if(n === 0) {return 1;
}
return f(n- 1)+f(n2 -);
}
Copy the code
- Subsets of sets. Find all subsets of a function. For example, the set [A,B]. Output [], [A], [B], [A, B]
var subsets = function(nums) {
let result = [];
function dfs(index,ans){
let ans2 = ans.concat();
ans2.push(nums[index]);
if(index === 0){
result.push(ans);
result.push(ans2);
return;
}else{
dfs(index- 1,ans);
dfs(index- 1,ans2);
}
}
dfs(nums.length- 1[]);return result;
};
Copy the code
conclusion
I summarized a project turtle-Rock on Github for the title that appears in the article. If you feel helped you, please help to give a star. Your star is my motivation to write.
instructions
Due to my level, it is hard to avoid some omissions. If there is any mistake, please comment, I will reply and correct in time. This article is a handwritten problem of the older front-end series.
How to prepare for interview in 2019?