source: node_modules/es-toolkit/dist/compat/object/unset.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.0 KB
Line 
1import { get } from './get.mjs';
2import { isUnsafeProperty } from '../../_internal/isUnsafeProperty.mjs';
3import { isDeepKey } from '../_internal/isDeepKey.mjs';
4import { toKey } from '../_internal/toKey.mjs';
5import { toPath } from '../util/toPath.mjs';
6
7function unset(obj, path) {
8 if (obj == null) {
9 return true;
10 }
11 switch (typeof path) {
12 case 'symbol':
13 case 'number':
14 case 'object': {
15 if (Array.isArray(path)) {
16 return unsetWithPath(obj, path);
17 }
18 if (typeof path === 'number') {
19 path = toKey(path);
20 }
21 else if (typeof path === 'object') {
22 if (Object.is(path?.valueOf(), -0)) {
23 path = '-0';
24 }
25 else {
26 path = String(path);
27 }
28 }
29 if (isUnsafeProperty(path)) {
30 return false;
31 }
32 if (obj?.[path] === undefined) {
33 return true;
34 }
35 try {
36 delete obj[path];
37 return true;
38 }
39 catch {
40 return false;
41 }
42 }
43 case 'string': {
44 if (obj?.[path] === undefined && isDeepKey(path)) {
45 return unsetWithPath(obj, toPath(path));
46 }
47 if (isUnsafeProperty(path)) {
48 return false;
49 }
50 try {
51 delete obj[path];
52 return true;
53 }
54 catch {
55 return false;
56 }
57 }
58 }
59}
60function unsetWithPath(obj, path) {
61 const parent = path.length === 1 ? obj : get(obj, path.slice(0, -1));
62 const lastKey = path[path.length - 1];
63 if (parent?.[lastKey] === undefined) {
64 return true;
65 }
66 if (isUnsafeProperty(lastKey)) {
67 return false;
68 }
69 try {
70 delete parent[lastKey];
71 return true;
72 }
73 catch {
74 return false;
75 }
76}
77
78export { unset };
Note: See TracBrowser for help on using the repository browser.