Published
Edited
Aug 26, 2020
Insert cell
md`# 面试题-JS编程`
Insert cell
md`## 随机生成16位颜色值
generator:():string
\`\`\`javascript
generator(); // #C1C1C1
\`\`\`
思路:<br/>
1. 找到色值特点:十六进制;维护一个十六进制原子列表
2. 生成随机数
3. 从列表里面随机取
`
Insert cell
generator = ()=>{
const colorArr = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'];
const arr = new Array(6).fill('');
for(let i=0;i<arr.length;i++){
const tag = Math.round(Math.random()*16);
arr[i] = colorArr[tag];
}
return `#${arr.join('')}`;
}
Insert cell
r1 = generator();
Insert cell
md`## 16位颜色值转成RGB`
Insert cell
md`
translate:(value:string):string
\`\`\`javascript
translate(#C1C1C1); // "(12,12,12)"
\`\`\`
思路:00AAFFF => 0,170,255
1. 两个一对 ['00','AA','FF']
2. 转换成16进制表示 [0,170,255 ]
`
Insert cell
translate = (colorStr)=>{
const result = [];
const v = colorStr.slice(1).split('');
let tag='';
for(let i=0,len=v.length;i<len;i++){
tag += v[i];
if(i % 2 === 1){
const num = parseInt(tag,16);
num
result.push(num);
tag = '';
}
}
return `(${result.join(',')})`
}

Insert cell
r2 =translate('#00AAFFF');
Insert cell
md`## Promise.allSetled polyfill实现`
Insert cell
md`
\`\`\`
Promise<Array<{
status: 'fulfilled',
value: any,
} | {
status: 'rejected',
reason: any,
}>>
\`\`\`
思路:<br/>
1. 每一个异步的结果无论什么结果都resolve
2. 依赖Promise.all实现allSettled时机
3. polyfill
`
Insert cell
{
const allSettled = (arr,callback)=>{
const tmp = [];
for(let i=0,len=arr.length;i<len;i++){
const item = arr[i];
const v = handle(item);
tmp.push(v);
}
// 依赖Promise.all实现allSettled时机
Promise.all(tmp).then((res)=>{
callback(res)
});
}

// 每一个异步的结果无论什么结果都resolve
const handle = (item)=>{
// 重新包装成 promise.resolve
return new Promise((resolve,reject)=>{
item.then((res)=>{
resolve({
status:'fulfilled',
value:res
});
}).catch((e)=>{
resolve({
status:'rejected',
reason:e
})
})
});
}

// 挂载到Promise.prototype
if(typeof Promise.prototype.allSettled === undefined){
Promise.prototype.allSettled = allSettled;
}
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more