| 1 | import { toPath } from './toPath.mjs';
|
|---|
| 2 | import { toKey } from '../_internal/toKey.mjs';
|
|---|
| 3 | import { last } from '../array/last.mjs';
|
|---|
| 4 | import { get } from '../object/get.mjs';
|
|---|
| 5 |
|
|---|
| 6 | function invoke(object, path, ...args) {
|
|---|
| 7 | args = args.flat(1);
|
|---|
| 8 | if (object == null) {
|
|---|
| 9 | return;
|
|---|
| 10 | }
|
|---|
| 11 | switch (typeof path) {
|
|---|
| 12 | case 'string': {
|
|---|
| 13 | if (typeof object === 'object' && Object.hasOwn(object, path)) {
|
|---|
| 14 | return invokeImpl(object, [path], args);
|
|---|
| 15 | }
|
|---|
| 16 | return invokeImpl(object, toPath(path), args);
|
|---|
| 17 | }
|
|---|
| 18 | case 'number':
|
|---|
| 19 | case 'symbol': {
|
|---|
| 20 | return invokeImpl(object, [path], args);
|
|---|
| 21 | }
|
|---|
| 22 | default: {
|
|---|
| 23 | if (Array.isArray(path)) {
|
|---|
| 24 | return invokeImpl(object, path, args);
|
|---|
| 25 | }
|
|---|
| 26 | else {
|
|---|
| 27 | return invokeImpl(object, [path], args);
|
|---|
| 28 | }
|
|---|
| 29 | }
|
|---|
| 30 | }
|
|---|
| 31 | }
|
|---|
| 32 | function invokeImpl(object, path, args) {
|
|---|
| 33 | const parent = get(object, path.slice(0, -1), object);
|
|---|
| 34 | if (parent == null) {
|
|---|
| 35 | return undefined;
|
|---|
| 36 | }
|
|---|
| 37 | let lastKey = last(path);
|
|---|
| 38 | const lastValue = lastKey?.valueOf();
|
|---|
| 39 | if (typeof lastValue === 'number') {
|
|---|
| 40 | lastKey = toKey(lastValue);
|
|---|
| 41 | }
|
|---|
| 42 | else {
|
|---|
| 43 | lastKey = String(lastKey);
|
|---|
| 44 | }
|
|---|
| 45 | const func = get(parent, lastKey);
|
|---|
| 46 | return func?.apply(parent, args);
|
|---|
| 47 | }
|
|---|
| 48 |
|
|---|
| 49 | export { invoke };
|
|---|