a-synchronous / rubico

[a]synchronous functional programming
https://rubico.land
MIT License
272 stars 15 forks source link

flatMap #38

Closed richytong closed 4 years ago

richytong commented 4 years ago

Why: flatMap gives that one-to-many mapping I so desperately desire. It would greatly simplify a ton of transformations. It's like the missing piece. It would change this

/*
 * vendors => Map { record_uLID -> Set { vendor_uLID } }
 */
const createRecordToVendorMap = pipe([
  map(vendor => pipe([ // for each vendor of vendors
    get('productVariations'),
    map(pipe([ // for each productVariation of productVariations
      get('variationOptions'),
      reduce(map(fork({ // for each record of each variationOption of each variationOptions, create a new object
        record_uLID: get('record_uLID'),
        vendor_uLID: () => vendor.vendor_uLID,
      }))(incMap), new Map()), // reduce the new object via incMap into a new Map()
    ])),
    reduce(combineMaps, new Map()), // combine array of Maps into one Map
  ])(vendor)),
  reduce(combineMaps, new Map()), // combine array of Maps into one Map
])

To this

// normal version
const createRecordToVendorMap = pipe([
  flatMap(vendor => pipe([
    get('productVariations'),
    flatMap(pipe([
      get('variationOptions'),
      map(fork({
        record_uLID: get('record_uLID'),
        vendor_uLID: () => vendor.vendor_uLID,
      })),
    ]))
  ])(vendor)),
  reduce(incMap, new Map()),
])

// transducer version
reduce(flatMap(vendor => pipe([
  get('productVariations'),
  flatMap(pipe([
    get('variationOptions'),
    map(fork({
      record_uLID: get('record_uLID'),
      vendor_uLID: () => vendor.vendor_uLID,
    })),
  ]))
])(vendor))(incMap), new Map())

flatMap can mux async iterables

flatMap would go under transformations. It would have similar behavior to Array.prototype.flatMap.

Here's a nice reference from martin fowler flat-map

flatMap

y = flatMap(f)(x) f is a function x is an Iterable, AsyncIterable, or reducer function

f is applied to the elements of x in parallel y is the one-to-many, map then flatten transformation of x with f y is a Promise if any of the following are true

TODO:

richytong commented 4 years ago

Laying out the ground work now.

richytong commented 4 years ago

I'll do flatMapArray