Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@skava/utils / src / remapProps.ts
Size: Mime:
import { isObj, hasOwnProp } from 'exotic'

/**
 * @desc remap properties from 1 to another, for example, apis with inconsistent naming
 * @symb 🗺
 *
 * @param from property name string, or {[from]: to}
 * @param [to=undefined] property name to change key to
 *
 * @example
 *  const disToDat = remap({dis: 'dat'})
 *  disToDat({dis: 1, other: true})
 *  //=> {dist: 1, other: true}
 *
 */
export interface RemapAnyObjDefault {
  [key: string]: any
}
function remap<Props extends {} = RemapAnyObjDefault>(
  from: object | string,
  to: string
) {
  const remapFromTo = isObj(from) ? from : { [from]: to }
  const keys = Object.keys(remapFromTo)

  return function remapObjCurried(props: Props): Props {
    // ensure they are not frozen
    const remapped = { ...(props as any) }

    for (let index = 0; index < keys.length; index++) {
      const fromKey = keys[index]

      if (hasOwnProp(props, fromKey)) {
        const toKey = remapFromTo[fromKey]
        remapped[toKey] = remapFromTo[fromKey]
      }
    }

    return remapped
  }
}

export { remap }
export { remap as remapProps }
export default remap