Open Sogrey opened 3 months ago
function createOverLoad () { const callMap = new Map(); function overLoad (...args) { const key = args.map(arg => typeof arg).join(','); const fn = callMap.get(key); if (fn) { return fn.apply(this, args); } throw "No match function." } overLoad.addImpl = function (...args) { if (args.length == 0) return; const fn = args.pop(); if (!fn || typeof fn !== 'function') { return; } const types = args; callMap.set(types.join(','), fn); } return overLoad } const getUsers = createOverLoad(); getUsers.addImpl(() => { console.log("无参") }) const searchPage = (page, size = 10) => { console.log("查询页码和数量", page, size) } getUsers.addImpl('number', searchPage) getUsers.addImpl('number', 'number', searchPage) getUsers.addImpl('string', (name) => { console.log("根据用户名查询", name) }) getUsers.addImpl('string', 'string', (name, sex) => { console.log("根据用户名和性别查询", name, sex) })
getUsers() getUsers(1) getUsers(1, 20) getUsers("张三") getUsers("张三", "女")
返回:
无参 查询页码和数量 1 10 查询页码和数量 1 20 根据用户名查询 张三 根据用户名和性别查询 张三 女
返回: