@codady/utils 0.0.11 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @since Last modified: 2025/12/25 12:07:26
3
+ * shallowCopy
4
+ *
5
+ * This function performs a shallow copy of various data structures:
6
+ * - Set
7
+ * - Map
8
+ * - Array
9
+ * - Plain Object (including properties with Symbol keys)
10
+ *
11
+ * It returns a new instance of the data structure, but the elements or properties of reference types (such as objects or arrays) will be copied by reference.
12
+ * Primitive types (e.g., number, string, boolean) will be returned directly.
13
+ */
14
+ 'use strict';
15
+
16
+ import getDataType from "./getDataType";
17
+
18
+ const shallowCopy = (data: any): any => {
19
+ const dataType = getDataType(data);
20
+
21
+ // Check if data is a Set
22
+ if (dataType === 'Set') {
23
+ // Shallow copy Set
24
+ return new Set([...data]);
25
+ }
26
+
27
+ // Check if data is a Map
28
+ if (dataType === 'Map') {
29
+ // Shallow copy Map
30
+ return new Map([...data]);
31
+ }
32
+
33
+ // Check if data is an Array
34
+ if (Array.isArray(data)) {
35
+ // Shallow copy Array
36
+ return [...data];
37
+ }
38
+
39
+ // Check if data is a Plain Object (including Symbol keys)
40
+ if (dataType === 'object') {
41
+ const obj = data as { [key: string | symbol]: any }; // Ensure the object type includes string and symbol keys
42
+ const symbolProperties = Object.getOwnPropertySymbols(obj).reduce((acc: { [key: symbol]: any }, sym: symbol) => {
43
+ acc[sym] = obj[sym];
44
+ return acc;
45
+ }, {});
46
+
47
+ // Shallow copy the object and include the Symbol properties
48
+ return { ...obj, ...symbolProperties };
49
+ }
50
+
51
+ // For other types (such as numbers, strings, booleans, etc.), return the original value
52
+ return data;
53
+ };
54
+
55
+ export default shallowCopy;