Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lodash.once #222

Open
qiuye-zhou opened this issue Nov 4, 2022 · 0 comments
Open

lodash.once #222

qiuye-zhou opened this issue Nov 4, 2022 · 0 comments

Comments

@qiuye-zhou
Copy link
Contributor

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第二次调用'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant