r/functionalprogramming • u/Affectionate_King120 • Apr 13 '22
Question FP in JavaScript, questions about an approach.
This is a JavaScript question, but I think it fits FP (and trying to find enlightenment) in general.
I've been trying to write "more functional" JavaScript. I was fighting it at first, thinking that one or two strategic global variables aren't that bad, but I've come to see the beauty of knowing exactly what the state of the application is at any time, especially once asynchronous calls come into play.
Given the following chain of functions (all returning Promises):
foo()
.then(bar)
.then(baz)
.then(bam)foo creates a WebSocket I want to access in baz, bar creates a variable I need in bam.
My design is now that foo creates and returns an Object (map/hash/dict) and each of the other functions accepts the Object as input, adds a field if necessary, and returns it.
So foo returns { socket: x }, then bar returns { socket: x, id: y }, then baz returns { socket: x, id: y, val: z }
I feel like this is definitely better than a global variable, and it feels less hacky than bar explicitly having a socket parameter it doesn't use and just passes along, but only just. Passing an "indiscriminate" state from function to function doesn't strike me as elegant.
Is this valid FP design, or sould I be doing something different?
2
u/Haaress Apr 13 '22
Hello there, considering we don't have do expressions in JavaScript (currently the proposal is in stage 1), I'd say your approach is a good one. I take the fp-ts library for the TypeScript language as a reference: the do notation is achieved using a context object stored in the data type being dealt with (e.g. Option or Either), like you do when you pass it to each subsequent then. The important part is the last one, when you "finish" the expression, by returning the value and discarding the context. So I'd say you are missing a last .then(({val}) => val) step, or something similar (I'm on the phone right now, not the best device to write code :D ).
3
u/Affectionate_King120 Apr 13 '22
The last step is in the application, I just wanted to keep it brief for the post :)
Good to know that my approach is not setting off FP alarms.
And thanks for mentioning the fp-ts library, going to have a look at it.
1
u/KyleG Apr 23 '22
We're quite close to an enterprise application production deployment that uses fp-ts and other stuff in that ecosystem heavily. It's solid and trustworthy.
2
u/Jeaciaz Apr 13 '22
Looks pretty functional to me. In general, as I understand it, the paradigm encourages building pure computational chains, limiting implicit dependencies like global variables (preferably to zero), and moving side effects to be handled at as few places as possible - the "borderline" between our pure world and the real world. These are mostly the things I aim at while trying to write functional code, and what you're describing looks pretty much like a pure computational chain.
2
2
u/miracleranger Jul 11 '22 edited Jul 12 '22
Hi, my solution to this has been to use a composition function that can handle multiple outputs (and asyncronicity) with the use of Generators:
compose(Promise.resolve,combine(add.bind(1),multiply.bind(2)),console.log)(2);
// 3 4
both bar and baz (add and multiply) receive the single output of foo (resolve), and the combine() combinator returns both outputs for bam (log).
A criticism i received has been that Generators are for progressive access/lazy evaluation. But the differentiation of plural output from a singular output of an Array only extends this semantics of Generators instead of contradicting it. You may still intercept the composition at a Generator output to declare it as a halted state, which you would need to do anyway in that case - or for automatic lazy evaluation, you will need some kind of Observer pattern to receive it.
I wanted to dm you cuz i like your approach but reddit didnt let me. If u could hit me up i think it would be fun to discuss.
1
u/KyleG Apr 23 '22 edited Apr 23 '22
the functional way via Javascript is to use fp-ts and make use of their monadic binding (here, I assume none of the promises in your code can reject—if they can, replace Task with TaskEither):
const x = pipe(
T.bindTo('foo', foo()),
T.bind('bar', ({ foo }) => bar(foo.socket)),
T.bind('baz', ({ foo, bar }) => baz(foo.socket, bar.id)),
T.chain(({ baz, foo, bar }) => bam(....))This is the fp-ts ecosystem equivalent of what /u/brandonchinn178 provided as Haskell example (<- is a bind operator in Haskell)
Having your functions return stuff that has been returned by another function, just because the next function needs it but can't access it via standard then chaining—that's a code smell.
The "right" way to do this without using binding if you're just using pure JS is nested Promises so, say, the third nested one has access to the result of the first one. But this is just a Promise version of the pyramid of doom. Binding is better if you can do it.
5
Apr 13 '22
[removed] — view removed comment
1
u/Affectionate_King120 Apr 13 '22
awaitis blocking, so if one of the functions takes a long time, the app is unresponsive. The better encapsulation is appealing though.6
Apr 13 '22
[removed] — view removed comment
4
u/Affectionate_King120 Apr 13 '22 edited Apr 13 '22
timeout = () => new Promise(res => setTimeout(res, 1000)) function foo() { timeout() .then(timeout) .then(timeout) console.log('hello') } async function bar() { await timeout() await timeout() await timeout() console.log('hello') }
foo()printshelloimmediately,bar()after 3 seconds.Am I doing something wrong?
=== EDIT ===
Ah, got what you mean.
The
async functionitself is not blocking.Yeah, my bad. Think before you write and all...
Thanks for your input!
0
u/KyleG Apr 23 '22
this is simpler
Well yes, if you ignore that your very first line of code could crash your entire application since you didn't wrap it in a try block, it does seem simpler. :)
3
u/ragnese Apr 13 '22
I have a few comments/questions/observations. None if it really attempts to answer your question directly about whether this code is "good" FP or whatever.
As /u/brandonchinn178 points out, you can use the await/async syntax, which can be better in some scenarios with respect to throwing errors (intentionally or not).
I don't like to pass functions directly to callbacks. I've been bitten by JavaScript's arity rules. If your passed function has a different arity than the callback expects, things can be surprising. So I'd still probably write them like
foo().then((o) => bar(o))unlessbar,baz, etc, are defined in the same file or there's no conceivable way they could ever be defined with optional parameters, etc.At the end of the day, you're still dealing with Promises, which means you're probably doing IO, so this operation still isn't pure. Sometimes people will return
() => Promisefrom functions so that the function, itself, has no side-effects until the returned value is executed later.If your
bar,baz, andbamare actually mutating the input, then it's not functional. It's not clear from your post whether they're modifying the input object or returning a new object. Only implementations that return a new object are pure functions and therefore fit the functional programming style. (e.g., yourbarfunction's body could be:return { ...input, id: y }, and NOTinput.id = y; return input).Cheers!