source: node_modules/es-toolkit/dist/compat/object/get.mjs

Last change on this file was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago

Added visualizations

  • Property mode set to 100644
File size: 2.2 KB
Line 
1import { isUnsafeProperty } from '../../_internal/isUnsafeProperty.mjs';
2import { isDeepKey } from '../_internal/isDeepKey.mjs';
3import { toKey } from '../_internal/toKey.mjs';
4import { toPath } from '../util/toPath.mjs';
5
6function get(object, path, defaultValue) {
7 if (object == null) {
8 return defaultValue;
9 }
10 switch (typeof path) {
11 case 'string': {
12 if (isUnsafeProperty(path)) {
13 return defaultValue;
14 }
15 const result = object[path];
16 if (result === undefined) {
17 if (isDeepKey(path)) {
18 return get(object, toPath(path), defaultValue);
19 }
20 else {
21 return defaultValue;
22 }
23 }
24 return result;
25 }
26 case 'number':
27 case 'symbol': {
28 if (typeof path === 'number') {
29 path = toKey(path);
30 }
31 const result = object[path];
32 if (result === undefined) {
33 return defaultValue;
34 }
35 return result;
36 }
37 default: {
38 if (Array.isArray(path)) {
39 return getWithPath(object, path, defaultValue);
40 }
41 if (Object.is(path?.valueOf(), -0)) {
42 path = '-0';
43 }
44 else {
45 path = String(path);
46 }
47 if (isUnsafeProperty(path)) {
48 return defaultValue;
49 }
50 const result = object[path];
51 if (result === undefined) {
52 return defaultValue;
53 }
54 return result;
55 }
56 }
57}
58function getWithPath(object, path, defaultValue) {
59 if (path.length === 0) {
60 return defaultValue;
61 }
62 let current = object;
63 for (let index = 0; index < path.length; index++) {
64 if (current == null) {
65 return defaultValue;
66 }
67 if (isUnsafeProperty(path[index])) {
68 return defaultValue;
69 }
70 current = current[path[index]];
71 }
72 if (current === undefined) {
73 return defaultValue;
74 }
75 return current;
76}
77
78export { get };
Note: See TracBrowser for help on using the repository browser.