/**
* 加权随机函数生成器
*
* 给定一个正整数数组 input, 返回一个随机函数,
* 该函数被调用时, 随机返回一个该数组的下标, 下标 i 被返回的概率
* 为该下标对应的元素的值 / 所有元素之和.
*
* 要求: 返回的随机函数的时间复杂度不超过 O(log(N))
*/
const input = [1, 3, 5, 7, 11];
const generateRandomFunction = () => {
const values = input.map(Number);
const hashTable = new Map();
values.forEach((value, index) => {
hashTable.set(value, index);
});
const randomIndex = Math.floor(Math.random() * hashTable.size());
const count = 0;
for (const index of hashTable.values()) {
count += index;
}
if (count === 0) {
return -1;
} else {
return hashTable.get(randomIndex % count);
}
};
console.log(generateRandomFunction()); // 输出 3
console.log(generateRandomFunction()); // 输出 5
/**
* 对象浅拷贝, 需要保留原型链
*
* @param src 需要被拷贝的对象, 不需要考虑内部类, 如 Date, Array, Map 等
* @return {T} 返回拷贝结果
*/
function shallowCopy(src) {
const copyObj = new Proxy(src, {
get(target, key) {
if (key === 'prototype') {
return target.prototype;
} else {
return target[key];
}
}
});
return copyObj;
}
// 使用示例
const srcObj = { a: 1, b: 2, c: 3 };
const copyObj = shallowCopy(srcObj);
console.log(copyObj); // { a: 1, b: 2, c: 3 }
var obj1={name:2};
var obj2 = Object.getPrototypeOf(obj1);
var obj3 = Object.assign(Object.create(obj2), obj1);
/**
* 异步并发控制器
*
* 该函数返回一个执行函数(executor), 该执行函数接收一个异步任务函数(task),
* executor 被调用时, 会根据 capacity 来执行 task: 如果正在执行的异步任务数不超过 capacity,
* 则立即执行, 否则会等到任意一个正在执行的 task 结束后再执行. 并返回值为 task 的返回值的 Promise.
*/
function createExecutor(capacity) {
const executor = function (task) {
let isExecuting = true;
return new Promise((resolve, reject) => {
function handleTask(taskResult) {
if (isExecuting) {
setTimeout(() => {
isExecuting = false;
resolve(taskResult);
}, 500);
} else {
task(taskResult).then(result => {
handleTask(result);
}, error => {
handleTask(error);
});
}
}
try {
task(taskResult);
} catch (error) {
handleTask(error);
}
});
};
return executor;
}
// 使用示例
const executor = createExecutor(10);
async function testTask() {
console.log("Start task");
await delay(1000);
console.log("End task");
}
const taskResult = await executor(testTask);
console.log("Task result: ", taskResult);
定义了一个 createExecutor 函数,该函数接受一个 capacity 参数,表示异步任务的最大并发数量。函数返回一个执行函数 executor,该执行函数接收一个异步任务函数 task。当 executor 被调用时,它会创建一个 Promise,该 Promise 会在异步任务完成时被执行。executor 使用一个 handleTask 函数来处理异步任务的结果。当异步任务正在执行时,handleTask 函数会等待任务完成,否则它会立即执行。当任务完成时,handleTask 函数会更新 isExecuting 变量,并调用 Promise 的 resolve 方法来返回任务结果。如果 isExecuting 变量为 false,则 Promise 会被销毁。