Last active
February 21, 2019 03:30
-
-
Save nickccm1122/77e86a0ee4b3d52e254c97385301c6c5 to your computer and use it in GitHub Desktop.
Create Nested Immutable Record with full type support
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
// @flow strict | |
/** | |
* Purpose: convert object | |
* { | |
* name: 'Andrew', | |
* email: '[email protected]', | |
* car: { | |
* type: 'Ford', | |
* cost: 10, | |
* usageDetails: { | |
* distanceTravelled: 0, | |
* averageMileage: 0 | |
* } | |
* } | |
* } | |
* | |
* into immutable object | |
* | |
* result: | |
* | |
* [Flow] | |
* car: ?RecordOf<{ | |
* cost: ?number, | |
* type: ?string, | |
* usageDetails: ?RecordOf<{ | |
* averageMileage: ?number, | |
* distanceTravelled: ?number | |
* }> | |
* }> | |
*/ | |
const _UsageDetails: RecordFactory<{ | |
distanceTravelled: ?number, | |
averageMileage: ?number | |
}> = Record({ distanceTravelled: null, averageMileage: null }) | |
const _Car: RecordFactory<{ | |
type: ?string, | |
cost: ?number, | |
usageDetails: ?$Call<typeof _UsageDetails, {}> | |
}> = Record({ type: null, cost: null, usageDetails: null }) | |
const createCarRecord = ( | |
obj: Object | |
): $Call<RecordFactory<{ | |
name: ?string, | |
email: ?number, | |
car: ?$Call<typeof _Car, {}> | |
}>, | |
{}> => { | |
// start with converting the nested object fields | |
const usageDetails = _UsageDetails(obj.car.usageDetails) | |
const car = _Car({ | |
...obj.car, | |
usageDetails | |
}) | |
return Record({ | |
name: null, | |
email: null, | |
car: null | |
})({ | |
...obj, | |
car | |
}) | |
} | |
const carRecord = createCarRecord({ | |
name: 'Andrew', | |
email: '[email protected]', | |
car: { | |
type: 'Ford', | |
cost: 10, | |
usageDetails: { | |
distanceTravelled: 0, | |
averageMileage: 0 | |
} | |
} | |
}) | |
const car = carRecord.car | |
export default createCarRecord |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment