Skip to content

Instantly share code, notes, and snippets.

@nickccm1122
Last active February 21, 2019 03:30
Show Gist options
  • Save nickccm1122/77e86a0ee4b3d52e254c97385301c6c5 to your computer and use it in GitHub Desktop.
Save nickccm1122/77e86a0ee4b3d52e254c97385301c6c5 to your computer and use it in GitHub Desktop.
Create Nested Immutable Record with full type support
// @flow strict
/**
* Purpose: convert object
* {
* name: 'Andrew',
* email: 'andrew@gmail.com',
* 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: 'andrew@gmail.com',
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