const deleteDupicate=(str)=>{
let map = new Map();
for(let char of str) {
if(!map.has(char)) {
map.set(char,1);
}
else map.set(char,map.get(char)+1);
}
for(let i=0;i<str.length;i++) {
if(map.get(str[i])===1) return i;
}
return -1;
}
const Input = "loveleetcode"
const reverseStr=(str)=>{
let right = str.length-1;
let left = 0;
let ans = "";
while(right>=0) {
while(right>=0&&str[right]===" "){
right--;
}
left = right-1;
while(left>0&&str[left]!==" ") left--;
ans+=str.slice(left+1,right+1)+" ";
right = left-1;
}
return ans.slice(0,ans.length-1);
}
const str = " the sky is blue "
const flatten=(arr)=>{
let result = [];
for(let item of arr) {
Array.isArray(item)
?result.push(...flatten(item))
:result.push(item);
}
return result;
}
const frequency=(str)=>{
let map = new Map();
let ans = "";
for(let char of str) {
map.has(char)
?map.set(char,map.get(char)+1)
:map.set(char,1)
}
let arr = Array.from(map).sort((a,b)=>{
return b[1]-a[1];
})
for(let [key,value] of arr) {
ans+=key.repeat(value);
}
return ans;
}
const str2="Aabbdddcc"
const intersection=(num1,num2)=>{
let set1 = new Set(num1);
let set2 = new Set();
for(let n of num2) {
if(set1.has(n)) set2.add(n);
}
return Array.from(set2);
}
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.cache = new Map();
}
get(key) {
if(!this.cache.has(key)) return -1;
const value = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key,value);
return value;
}
put(key,value) {
if(this.cache.has(key)) this.cache.delete(key);
if(this.cache.size>=this.capacity) {
this.cache.delete(this.cache.keys().next().value)
}
this.cache.set(key,value);
}
}
const deepClone=(obj,cache=new Map())=>{
if(obj===null||typeof obj!=="object") return obj;
if(cache.has(obj)) return cache.get(obj);
const clone = obj.isArray?[]:{};
cache.set(obj,clone);
for(let key in obj) {
clone[key] = deepClone(obj[key],cache)
}
return clone;
}
const obj = {
name: 'Alice',
info: {
age: 25,
favorites: ['music', 'chess'],
},
};
obj.self = obj;
const myPromiseRace=(promises)=>{
return new Promise((resolve,reject)=>{
for(let p of promises) {
Promise.resolve(p)
.then(resolve)
.catch(reject)
}
})
}
const myPromiseAny=(promises)=>{
return new Promise((resolve,reject)=>{
let count = 0;
let rejectArr = [];
if(promises.length===0) {
return reject(new AggregateError([],"All promises are error"))
}
for(let p of promises) {
Promise.resolve(p)
.then(resolve)
.catch(err=>{
rejectArr.push(err);
count++;
if(count===promises.length) {
reject(new AggregateError(rejectArr,"All promises were rejected"))
}
})
}
})
}
const p1 = Promise.reject("fail A");
const p2 = Promise.reject("fail B");
const p3 = Promise.resolve("success C");
myPromiseAny([p1, p2, p3])
.then(console.log)
.catch(err => console.error(err));
myPromiseAny([Promise.reject("A"), Promise.reject("B")])
.then(console.log)
.catch(err => console.error(err));
console