matthewp / robot

🤖 A functional, immutable Finite State Machine library
https://thisrobot.life
BSD 2-Clause "Simplified" License
1.92k stars 88 forks source link

[Question] Using the returned objects in place of the function calls #177

Closed sunny-mittal closed 2 years ago

sunny-mittal commented 2 years ago

Hello, I'm trying out robot after having used xstate fairly extensively and the best way for me to learn a lib is to just play around with various functions in node to get a feel for what they do. When trying out reduce, I see it just returns the anonymous (or named) function you provide it mapped to the fn key of an object, so:

const fn = () => {}
reduce(fn).fn === fn // true

So I figured I could probably (I'd never do this) just use that object shape in place of the reduce call, something like:

loading: invoke(
  invocable,
  transition(
    'done',
    'success',
    { fn: (ctx, evt) => ({...ctx, title: evt.data }) }
  )
)

but this doesn't work. I'm curious what I'm missing here. Looking forward to an answer :)

sunny-mittal commented 2 years ago

After looking at the source code, I see that it's a bit more magical and clever than I could deduce from simple node output. I see that reduceType is used as a prototype for all reducer objects so they can be distinguished from actions/guards that have the same shape. I've never thought to do that but it's pretty dang smart. Closing now.

matthewp commented 2 years ago

@sunny-mittal The prototype system in Robot is intended to be extended. So creating your own type that extends reduceType, etc is encourage (albeit advanced, not something most people will do).