Repository URL to install this package:
|
Version:
1.0.0 ▾
|
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