-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #22 from jungsoft/21-values-should-be-touched-when…
…-initialized 21 values should be touched when initialized
- Loading branch information
Showing
2 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
/** | ||
* Recursively maps touched fields in an object. | ||
* @param obj The object | ||
*/ | ||
const recursiveMapTouched = (obj: object): object => { | ||
const result = { | ||
...(obj || {}), | ||
}; | ||
|
||
Object | ||
.keys(result) | ||
.forEach((key) => { | ||
const value = result[key]; | ||
|
||
if (typeof value === 'object') { | ||
recursiveMapTouched(value); | ||
return; | ||
} | ||
|
||
// eslint-disable-next-line no-param-reassign | ||
result[key] = true; | ||
}); | ||
|
||
return result; | ||
}; | ||
|
||
/** | ||
* Recursively maps initial touched fields according to custom initial values. | ||
* Any value initialized with initialValues will be marked as touched. | ||
* | ||
* You can override the touched values by passing an object as the second parameter, | ||
* which is optional. | ||
* | ||
* @param initialValues Value of initialValues | ||
* @param initialTouched Value of initialTouched | ||
*/ | ||
const mapInitialTouched = ( | ||
initialValues?: object, | ||
initialTouched?: object, | ||
) => { | ||
if (initialTouched) { | ||
return initialTouched; | ||
} | ||
|
||
if (!initialValues) { | ||
return undefined; | ||
} | ||
|
||
return recursiveMapTouched(initialValues); | ||
}; | ||
|
||
export default mapInitialTouched; |