如何实现一个函数重载的功能

函数重载 将函数接收到的不同参数,进行不同处理。

import createOverLoad from './funReload.js'
const getUsers = createOverLoad()

getUsers.addImpl(() => {
    console.log('查询所有用户')
})

getUsers.addImpl('string', (name) => {
    console.log('根据name用户名查询用户')
})
getUsers.addImpl('string', 'string', (name, sex) => {
    console.log('根据性别查询用户')
})

const searchPage = (page, size=10) => {
    console.log('根据page和size查询')
}
getUsers.addImpl('number', searchPage)
getUsers.addImpl('number', 'number', searchPage)

--------------------------------------------------------------
getUsers('是谁','qwqw') //根据性别查询用户
getUsers('qwqw') //根据name用户名查询用户
getUsers(1,10) //根据page和size查询
getUsers()//查询所有用户

createOverLoad实现方法:

function createOverLoad(){
    const callMap = new Map()
    function overLoad(...args){
        const key = args.map(arg => typeof arg).join(',')
        // 根据剩余参数的类型 找到再map集合中对应需要处理的函数
        const fn = callMap.get(key)
        if(!fn){
            throw new TypeError('no matching the function')
        } else {
           return fn.apply(this, args)
        }
    }

    //addImpl 函数 用来创建一个函数枚举的map
    overLoad.addImpl = function(...args){
        const fn = args.pop()
        if(typeof fn !== 'function') {
            throw new TypeError('not a function')
        }
        const types = args
        callMap.set(types.join(','), fn)

    }

    return overLoad

}

export default createOverLoad

 

posted @ 2023-06-13 14:01  10后程序员劝退师  阅读(37)  评论(0)    收藏  举报