Last active
May 31, 2021 16:06
-
-
Save themgoncalves/094e1421d549c39f7fb7422b7362080c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import typeOf from './type-of'; | |
/** | |
* Shallow copy | |
* @description Create a copy of a original collection with same structure. | |
* @param value | |
*/ | |
const shallowCopy = <T>(value: T): T extends [] ? T[] : T => { | |
let copy: unknown; | |
if (typeOf(value) === 'array') { | |
copy = [...(value as unknown[])]; | |
} else if (typeOf(value) === 'object') { | |
copy = { ...(value as Record<string, unknown>) }; | |
} else if (typeOf(value) === 'date') { | |
copy = new Date((value as unknown) as Date); | |
} else if (typeOf(value) === 'map') { | |
copy = new Map((value as unknown) as Map<unknown, unknown>); | |
} else if (typeOf(value) === 'set') { | |
copy = new Set((value as unknown) as Set<unknown>); | |
} else { | |
copy = value; | |
} | |
return copy as T extends [] ? T[] : T; | |
}; | |
export default shallowCopy; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment