0
点赞
收藏
分享

微信扫一扫

Thinking--函数参数重载


Thinking系列,旨在利用10分钟的时间传达一种可落地的编程思想。

前段时间分享过 ​​Thinking–函数参数Normalize思想在前端中的应用​​ ,对于函数多类型参数很是实用。

今天 ,阐述一种更小范围,业务中也更容易出现的场景 – “函数可接收数组或字符串,数组中每个元素的处理逻辑同字符串。”

实现

常规方式

function test (data : string | Array<string>): void {
if (Array.isArray(data)) {
for (let item of data) {
_do(item) // 直接调用处理逻辑
}
} else {
_do(data)
}
}

// 处理逻辑
function _do (params: string): void {
console.log(params)
}

test('start')
test(['1', '2'])

递归方式

function test (data : string | Array<any>): void {
if (Array.isArray(data)) {
for (let item of data) {
test(item) // 递归调用
}
} else {
_do(data)
}
}

// 处理逻辑
function _do (params: string): void {
console.log(params)
}

test(['3', ['4', '5']])

这里使用递归的好处,​​data​​​ 可以是嵌套数组 ​​['3', ['4', '5']]​​。

类似实现

​​https://github.com/vuejs/vue/blob/master/src/core/instance/events.js#L47​​

Vue.prototype.$on = function (event: string | Array<string>, fn: Function): Component {
const vm: Component = this
if (Array.isArray(event)) {
for (let i = 0, l = event.length; i < l; i++) {
this.$on(event[i], fn)
}
} else {
(vm._events[event] || (vm._events[event] = [])).push(fn)
// optimize hook:event cost by using a boolean flag marked at registration
// instead of a hash lookup
if (hookRE.test(event)) {
vm._hasHookEvent = true
}
}
return vm
}


举报

相关推荐

0 条评论