https://bigfrontend.dev/zh/problem/implement-Promise-allSettled
Promise.allSettled()
方法接受一组Promise
实例作为参数,包装成一个新的Promise
实例。只有等到所有这些参数实例都返回结果,不管是fulfilled
还是rejected
,包装实例才会结束 ```typescript function allSettled(promises: Promise [] | []): Promise<{ status: ‘fulfilled’, value: T } | { status: ‘rejected’, reason: any }[]> { if (!Array.isArray(promises)) { throw new Error(‘promises must be an array’); } let count = promises.length; if (count === 0) { return Promise.resolve([]); }
let result = [];
return new Promise((resolve, reject) => { for (let i = 0; i < count; i++) {
let promise = promises[i];
promise = promise instanceof Promise ? promise : Promise.resolve(promise);
promise.then(res => {
result[i] = {
status: "fulfilled",
value: res,
};
}).catch(err => {
result[i] = {
status: "rejected",
reason: err,
};
}).finally(() => {
count--;
if (count === 0) {
resolve(result);
}
})
} }); }
[https://leetcode-cn.com/problems/design-a-stack-with-increment-operation/](https://leetcode-cn.com/problems/design-a-stack-with-increment-operation/)
```typescript
class CustomStack {
private maxSize: number = 0
private list: number[] = [];
constructor(maxSize: number) {
this.maxSize = maxSize;
}
push(x: number): void {
if (this.list.length < this.maxSize) {
this.list.push(x);
}
}
pop(): number {
const item = this.list.pop();
return item === void 0 ? -1 : item;
}
increment(k: number, val: number): void {
const len = this.list.length;
for (let i = 0; i < k && i < len; i++) {
this.list[i] += val;
}
}
}