I am trying to do this for learning. But I can't get it to work (big surprise since you're reading this :) )
The algo:
- Have a mixed list of valid/invalid objects as input
- Extract the desired property from each object (or null)
- Transform to a list of Options
- Reduce the list of Options by using a function that operates on Aggregate types.
I couldn't get the types to work by elegantly lifting sumAggregates
so I tried to do it with pipe, ap
. But I would like to see how we would properly lift sumAggregates
to be used in the reduce.
Please note that my goal isn't to get the correct result in a different way, but to learn why my implementation of this one fails.
type Actionable = {
action?: string
}
type Aggregate = {
allowed: number,
blocked: number
}
const emptyAggregate: Aggregate = {
allowed: 0,
blocked: 0
}
const list: Actionable[] = [ { action: 'block'}, { }, { action: 'block'}, { }, { action: 'allow'}]
const extractAction = (a: Actionable) => a.action
const stringToAggregator = (str: string): Aggregate => {
return {
allowed: str === 'allow' ? 1 : 0,
blocked: str === 'block' ? 1 : 0,
}
}
const sumAggregates = (a: Aggregate) => (b: Aggregate): Aggregate => {
return {
allowed: a.allowed + b.allowed,
blocked: b.blocked + b.blocked,
}
}
const totals: O.Option<Aggregate> = pipe(
list,
A.map(extractAction),
A.map(O.fromNullable),
A.map(O.map(stringToAggregator)),
A.reduce(
O.some(emptyAggregate),
(a: O.Option<Aggregate>, b: O.Option<Aggregate>) => {
return pipe(O.of(sumAggregates), O.ap(a), O.ap(b))
}
)
)
Returns None
instead of some({allowed: 1, blocked: 2})