lodash.once
qiuye-zhou opened this issue · comments
type newOnceFun = {
[propsName: string | symbol | number]: Function
}
type newOnceResult = {
[propsName: string | symbol | number]: string | boolean | Function
}
class Once2 {
private result: newOnceResult = {}
private Fun: newOnceFun = {}
once (type: string, fun: Function) {
this.Fun[type] = fun
this.result[type] = false
return this.fun(this)
}
fun (that: Once2) {
return function (type: string, ...args: any) {
if (!that.result[type]) {
console.log(`---${type}调用成功---`)
that.result[type]= that.Fun[type](...args)
if (!that.result[type]) {
that.result[type] = that.Fun[type]
}
return that.result[type]
} else {
return that.result[type]
}
}
}
}
// 测试test
const newonce = new Once2()
const newonce1 = newonce.once('new1', function (str: string) {
console.log(str)
})
newonce1('new1', '第一次调用的结果')
newonce1('new1', '第二次调用的结果')
const newonce2 = newonce.once('new2', function (str: string) {
return `${str}---返回结果`
})
console.log(newonce2('new2', '第一次调用'))
console.log(newonce2('new2', '第二次调用'))
const newonce3 = newonce.once('new3', function (str: string) {
return `${str}---once3`
})
const newonce4 = newonce.once('new4', function (str: string) {
return `${str}---once4`
})
console.log(newonce3('new3', 'once3第一次调用的结果'))
console.log(newonce4('new4', 'once4第一次调用的结果'))
console.log('\n---下面是二次调用once3,once4---\n')
console.log(newonce3('new3', 'once3第二次调用'))
console.log(newonce4('new4', 'once4第二次调用'))