drops
Implement a returnType
type MyReturnType<T> = T extends(... args)=> infer P ? P :never;
Copy the code
Implement a custom react anti-shake hook
function useDebounce(fn, delay = 100) {
const ref = useRef(fn);
ref.current = function () {
let timer;
return function () {
const context = this;
const args = arguments;
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = seTimeout(fn.apply(context, args), delay)
}
}
return ref.current;
}
Copy the code
The maximum sum of paths in a binary tree
function findMaxPath(node) {
let maxVal = -Infinity;
function findMaxPath(node) {
if(! node)return 0;
const leftVal = Math.max(findMaxPath(node.left), 0);
const rightVal = Math.max(findMaxPath(node.right), 0);
const ps1 = node.val + Math.max(leftVal, rightVal);
const ps2 = node.val + leftVal + rightVal;
maxVal = Math.max(... [maxVal, ps1, ps2]);return ps1;
}
findMaxPath(node);
return maxVal;
}
Copy the code
To digital conversion
Write a function trans to convert the numbers into Chinese output, the input is not more than 1 trillion numbers.
For example: trans(123456) — one hundred and twenty three thousand four hundred and fifty-six
Trans (100010001) — 1010,001
let numChar = ['zero'.'一'.'二'.'三'.'four'.'five'.'六'.'seven'.'eight'.'九'];
let numUnit = [' '.'ten'.'best'.'千'];
let numSection = [' '.'万'.'亿'.'$'.'YiYi'];
// Map numbers to Chinese
function formatSection(num) {
let arr = (num + ' ').split(' ').reverse();
let str = ' ';
for (let i = 0; i < arr.length; i++) {
let char = arr[i] === 0 ? numChar[0] : numChar[arr[i]] + numUnit[i];
str = char + str;
}
let s = str.replace(/ zero + / g.'zero').replace(+ $/ / to zero.' ');
return s;
}
// Split the string by number
function formatNum(num, str) {
let len = Math.ceil(str.length / num);
let arr = [];
let reverseStr = str.split(' ').reverse().join(' ');
for (let i = 0; i < len; i++) {
let result = reverseStr
.slice(i * num, i * num + 4)
.split(' ')
.reverse()
.join(' ');
arr.unshift(result);
}
return arr;
}
function numberTranToCN(num) {
let arr = formatNum(4, num + ' ');
let list = [];
for (let i = 0; i < arr.length; i++) {
let str = formatSection(arr[i]);
list.push(str);
}
let reverseList = list.reverse();
// add interval units
for (let j = 0; j < reverseList.length; j++) {
reverseList[j] += numSection[j];
}
return reverseList.reverse().join(' ');
}
console.log(numberTranToCN(12345));
console.log(numberTranToCN(1000003));
Copy the code
Removes the least frequently occurring character from the string without changing the order of the original string
Example 1: “Ababac” — “ababa”
Example 2: “aaabbbcceeff” — “Aaabbb”
function task(str) {
let min = Infinity;
let map = new Map(a);for (let i = 0; i < str.length; i++) {
const count = (map.get(str[i]) ?? 0) + 1;
map.set(str[i], count);
}
min = Math.min(... map.values());return str.split(' ').reduce((pre, cur) = > {
if (map.get(cur) === min) {
return pre;
} else {
returnpre + cur; }},' ');
}
Copy the code
Bytes to beat
Sword refers to Offer II 103. Minimum number of coins
79. Word search
affectionately
Hand write a usePrevious
function usePervious(newValue) {
const pre = useRef();
const cur = useRef();
pre.current = cur.current;
cur.current = newValue;
return pre;
}
Copy the code
Prototype chain
console.log(Function.__proto__ === Function.prototype);
//Function is a machine that makes machines
console.log(Object.__proto__ === Function.prototype);
console.log(Function.prototype.__proto__ === Object.prototype);
Copy the code
Write a deep comparison
function compareObj(obj1, obj2) {
if (typeofobj1 ! = ='object' && typeofobj2 ! = ='object') {
return obj1 === obj2;
}
if (
Array.isArray(obj1) &&
Array.isArray(obj2) &&
obj1.length === obj2.length
) {
let result;
for (let key in obj1) {
result = compareObj(obj1[key], obj2[key]);
if(! result) {return false; }}return true;
}
if (Object.keys(obj1).length === Object.keys(obj2).length) {
if (Object.is(obj1, obj2)) return true;
let result;
let diff = true;
Object.keys(obj1).forEach((key) = > {
result = compareObj(obj1[key], obj2[key]);
if(! result) { diff =false; }});return diff;
}
return false;
}
console.log(compareObj(1.1));
console.log(compareObj([1], [1]));
console.log(compareObj([1], [1.2]));
console.log(compareObj({ name: 123 }, { name: 123 }));
Copy the code
Algorithm problem
All numbers in an array of length n+1 are in the range 1 to n, so at least one number in the array is repeated. Find any duplicate number in the array, but do not modify the input array. For example, if you input an array of length 8, “2,3,5,4,3,2,6,7”, the corresponding output would be duplicate numbers 2 or 3
function task(numbs) {
for (let i = 0; i < numbs.length; i++) {
const k = numbs[i];
const j = numbs[k];
if (k === j) {
return k;
} else{ [numbs[i], numbs[k]] = [numbs[k], numbs[i]]; }}}console.log(task([2.3.5.4.3.2.6.7]));
Copy the code
Binary search
Given an ordered (non-descending) array A, which may contain repeating elements, minimize I such that A[I] is equal to target, and return -1 if it does not exist.
Array =,2,3,5,6,7,7,10 [1]
Target = 7, return 5
target = 8, return -1
function task(arr, target) {
if(! arr || arr.length ===0) return -1;
let left = 0,
right = arr.length;
while (left < right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
for (let i = mid; i > 0; i--) {
if(arr[i] === target && arr? .[i -1] !== target) {
returni; }}}else if (arr[mid] > target) {
right = mid - 1;
} else {
left = mid + 1; }}return -1;
}
console.log(task([1.2.3.5.6.7.7.10].7));
console.log(task([1.2.3.5.6.7.7.10].8));
Copy the code
Algorithm problem
347. The first K high frequency elements
var topKFrequent = function (nums, k) {
const map = new Map(a);for (let i = 0; i < nums.length; i++) {
map.set(nums[i], (map.get(nums[i]) ?? 0) + 1)}return Array.from(map).sort((a, b) = > b[1] - a[1]).slice(0, k).map(item= > item[0])};Copy the code
The ant gold dress
William chain calls macro task micro task
class PersonReal {
constructor(name) {
this.name = name;
this.taskQueue = [];
this.taskIsRunning = false;
function task(name) {
console.log(`Hi! This is ${name}! `);
}
this.taskQueue.push(task.bind(this, name));
this._runQueue();
}
eat(food) {
const task = (food) = > {
console.log('Eat ' + food + '~');
};
this.taskQueue.push(task.bind(this, food));
this._runQueue();
return this;
}
sleep(time) {
const task = new Promise((resolve, reject) = > {
setTimeout(() = > {
console.log(`Wake up after ${time}`);
resolve();
}, time * 1000);
});
this.taskQueue.push(task);
this._runQueue();
return this;
}
sleepFirst(time) {
const task = new Promise((resolve, reject) = > {
setTimeout(() = > {
console.log(`Wake up after ${time}`);
resolve();
}, time * 1000);
});
this.taskQueue.unshift(task);
this._runQueue();
return this;
}
_runQueue() {
if (this.taskIsRunning) return;
this.taskIsRunning = true;
const goNext = () = > {
if (this.taskQueue.length) {
let task = this.taskQueue.shift();
if (task.then) {
task.then(() = > {
goNext();
});
} else{ task(); goNext(); }}else {
this.taskIsRunning = false; }};Promise.resolve().then(() = >{ goNext(); }); }}function Person(name) {
return new PersonReal(name);
}
Copy the code
Netease Lingxi Business Division
Ts the topic
type DeepReadonly<T extends Record<string.any> > = {readonly [K in keyof T]: T[K] extends Record<string.any>? DeepReadonly<T[K]> : T[K]; };Copy the code
Extract and concatenate all strings under an Object that are not more than 50 characters long
/ / input:
const input = {
a1: 'heading 1'.b2: 'title 2'.x3: {
d: 'paragraph 1'.m: 12.k: true.c7: {
s: 'abc'.k: [],},},};function getSummary(object) {
let result = ' ';
if (Object.keys(object).length === 0) return result;
const task = (obj) = > {
for (let key in obj) {
if (typeof obj[key] === 'string') {
const resultLen = result.length;
const canAdd = resultLen + obj[key].length <= 50;
if(canAdd) { result += obj[key]; }}else {
task(obj[key])
}
}
};
task(object);
return result;
}
console.log(getSummary(input));
/ / output:
// 'heading 1, heading 2, paragraph 1abc'
Copy the code
To be continued