又在「杂乱的工作台上」完成文章……
没错又错过一个非常好的机会。与其说是因为时间不够做不完,还不如说是因为陷入斐波那契思考导致做不完。
不留遗憾,把它搞完。题源就不说了。
1. 现有 /a, /b, /c, /d 四个接口,找出最快的那个。异步用 setTimeout 模拟
const requests: Promise<string>[]
= ['/a', '/b', '/c', '/d']
.map(v => new Promise(resolve => {
const time = Math.floor(Math.random()*1000)
setTimeout(() => {
resolve(`${v} spent ${time}`)
}, time);
}))
Promise.race(requests).then(console.log)
2. 使用你擅长的方式实现 Dialog
这个一直在暗示可以使用 vue
或者 react
,但是我有些紧张,一时半会只能想到只能用原生的方式
最后只能说是搬石头砸自己的脚,没写过一时没思路,导致写不完
<body>
<div>
<button id="dialog">直视我!栽种!</button>
</div>
<style>
.dialog {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #fff;
box-shadow: 1px 2px 8px 0 #c0c0c0;
color: #666;
}
.mask {
z-index: 1;
position: fixed;
top: 0;
left: 0;
background: rgba(0, 0, 0, 0.65);
filter: blur(80%);
}
.dialog-header {
width: 100%;
height: 45px;
margin: 8px 16px;
}
.isShow {
display: block;
}
.footer {
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 50px;
display: flex;
flex-flow: row nowrap;
justify-content: flex-end;
align-items: center;
margin: 0 16px;
}
.cancel-btn {
outline: 0;
border: 2px solid #ccc;
color: #999;
display: flex;
justify-content: center;
align-items: center;
padding: 8px;
border-radius: 8px;
}
</style>
<script>
class TheDialog {
constructor(id) {
this.btn = document.querySelector('#dialog')
this.width = 500
this.height = 300
this.template()
this.listener()
document.body.appendChild(this.container)
}
template() {
const container = document.createElement('div')
container.style.width = this.width + 'px'
container.style.height = this.height + 'px'
container.classList.add('dialog')
container.appendChild(this.headerTem())
container.appendChild(this.bodyTem())
container.appendChild(this.footerTem())
this.container = container
}
bodyTem() {
const body = document.createElement('div')
body.innerHTML = 'Hello World'
body.style.margin = '16px'
body.style.color = '#333'
body.style.fontSize = '24px'
return body
}
headerTem() {
const header = document.createElement('div')
header.classList.add('dialog-header')
const title = document.createElement('div')
title.innerHTML = 'Dialog'
header.appendChild(title)
return header
}
footerTem() {
const footer = document.createElement('div')
const btn = document.createElement('button')
footer.classList.add('footer')
btn.classList.add('cancel-btn')
btn.innerHTML = 'CANCEL'
btn.addEventListener('click', e => {
e.stopPropagation()
this.close()
})
footer.appendChild(btn)
return footer
}
listener() {
this.btn.addEventListener('click', e => {
e.stopPropagation()
this.toggle()
})
}
toggle() {
const isShow = this.container.classList.contains('isShow')
if (isShow) {
this.close()
} else {
this.container.classList.add('isShow')
document.body.classList.add('mask')
}
}
close() {
this.container.classList.remove('isShow')
document.body.classList.remove('mask')
}
}
(() => {
const theDialog = new TheDialog()
window.dialog = theDialog
})()
</script>
</body>
这样凑合能用