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
}
发布了256 篇原创文章 · 获赞 868 · 访问量 118万+

猜你喜欢

转载自blog.csdn.net/ligang2585116/article/details/103723454
今日推荐