22// Deps
33// -----------------------------------------------------------------------------
44
5- import { IPlainObject } from './types' ;
65import { toPath } from './to-path' ;
76import { 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