Skip to content

Commit 9d565fa

Browse files
committed
Enhance getIn tool
1 parent 67365b7 commit 9d565fa

File tree

2 files changed

+26
-11
lines changed

2 files changed

+26
-11
lines changed

src/get-in.test.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ const testCases: {
2020
parameters: [{ key: 'value' }, 'ZZZ'],
2121
result: undefined
2222
},
23+
{
24+
parameters: [{ key: 'value' }, 'ZZZ', 'fallbackValue'],
25+
result: 'fallbackValue'
26+
},
2327
{
2428
parameters: [
2529
{
@@ -42,6 +46,16 @@ const testCases: {
4246
],
4347
result: 'value1'
4448
},
49+
{
50+
parameters: [
51+
{
52+
key1: ['value0', 'value1', 'value2']
53+
},
54+
'key1[10]',
55+
'fallbackValue'
56+
],
57+
result: 'fallbackValue'
58+
},
4559
{
4660
parameters: [
4761
{

src/get-in.ts

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
// Deps
33
// -----------------------------------------------------------------------------
44

5-
import { IPlainObject } from './types';
65
import { toPath } from './to-path';
76
import { isPlainObject } from './is-plain-object';
87

@@ -14,28 +13,30 @@ import { isPlainObject } from './is-plain-object';
1413
* Convert string sample in to the path (array)
1514
* Inspired by final-form's `getIn` helper
1615
* {@link https://github.com/final-form/final-form/blob/master/src/structure/getIn.js}
17-
* @param {IPlainObject|Array} sample
16+
* @param {*} sample
1817
* @param {string} keyPath
18+
* @param {*} fallback
1919
*/
20-
export function getIn<GValue = any>(
21-
sample: IPlainObject | GValue[],
22-
keyPath: string
23-
): GValue | undefined {
20+
export function getIn<GReturnValue = any>(
21+
sample: any | any[],
22+
keyPath: string,
23+
fallback?: GReturnValue
24+
): GReturnValue {
2425
const path = toPath(keyPath);
2526
const pathLength = path.length;
2627

2728
let current: any = sample;
2829
for (let i = 0; i < pathLength; i++) {
2930
const key: string = path[i];
30-
if (
31-
(isPlainObject(current) && current.hasOwnProperty(key)) ||
32-
(Array.isArray(current) && !isNaN(+key))
33-
) {
31+
const index = parseInt(key, 10);
32+
if (isPlainObject(current) && current.hasOwnProperty(key)) {
3433
current = current[key];
34+
} else if (Array.isArray(current) && !Number.isNaN(index) && index > -1) {
35+
current = current[index];
3536
} else {
3637
current = undefined;
3738
break;
3839
}
3940
}
40-
return current;
41+
return current === undefined ? fallback : current;
4142
}

0 commit comments

Comments
 (0)