Skip to content

Instantly share code, notes, and snippets.

@themgoncalves
Last active May 31, 2021 16:06
Show Gist options
  • Save themgoncalves/094e1421d549c39f7fb7422b7362080c to your computer and use it in GitHub Desktop.
Save themgoncalves/094e1421d549c39f7fb7422b7362080c to your computer and use it in GitHub Desktop.
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