

export function hasKey (o, k) {
  return Object.prototype.hasOwnProperty.call(o, k)
}

export function objectGet(o = {}, k = '') {
  let found = true
  return k.split('.').reduce((acc, key) => {
    if (!found) return acc;

    if (acc === 0) {
      if (hasKey(o, key)) {
        return o[key]
      } else {
        found = false
        return {}
      }
    } else {
      if (hasKey(acc, key)) {
        return acc[key]
      } else {
        found = false
        return acc
      }
    }
  }, 0)
}

export function replaceUrlParams(url, params) {
  if (!params) return url

  const pathItems = (url || '').split('/')

  Object.keys(params).forEach((k) => {
    const inx = pathItems.indexOf(`:${k}`)
    if (inx > -1) {
      pathItems[inx] = params[k]
    }
  })

  return pathItems.join('/')
}

// groupBy 只支持数组
// it 只支持字符串与函数, 其中字符串必须是对象的一个属性名称
export function groupBy(collection, it) {
  if (Array.isArray(collection)) {
    return collection.reduce((acc, x) => {
      const v = typeof it === 'function' ? it(x) : x[it]

      if (hasKey(acc, v)) {
        acc[v].push(x)
      } else {
        acc[v] = [x]
      }
      return acc
    }, {})
  } else {
    return {}
  }
}
