DEV Community

Discussion on: Practical Functional Programming in JavaScript - Side Effects and Purity

Collapse
 
functional_js profile image
Functional Javascript

Nice work on the functional paradigm Richard,

Let me give you a couple ideas I use with piping and logging.

Let's say we have this...

const p1 = pipe(
  func1,
  func2,
  func3,
  func4,
);

//@tests
p1(val)

I keep log statements out of the funcs themselves, otherwise you can't run them in a loop.

One of the cognitively challenging things about pipes is keeping the output of one func compatible with the input of the next. So I'll use a set of strongly-typed log utils for dev-side troubleshooting.

Here's an example of logging a pipe (exaggerated with lots of log utils for demo purposes)

const p1 = pipe(
  func1, llArr,
  func2, lFirstElems(3),
  func3, lStr,
  func4, lNum,
);

//@tests
p1(val)

The "l" prefix means "log"
The "ll" prefix means "log length"
"Elems" implies an arr, so in this case only the first 3 elems (elements) are logged
Note that I keep the log util on the same line of the returning func, for readability.

If the type passed into the log util is wrong, it throws. (we have a bug!)
The throw message tells me what this "wrong" type was, and it's value (up to 500 chars).

By reading this, I know, for example, that func3 takes an arr and returns a str, and func4 takes a str and returns a num.

If not, this pipe won't run, it'll throw.

Collapse
 
richytong profile image
Richard Tong

Glad to hear from you functional, interesting idea for a strongly typed log util. What are you using for that right now?

Collapse
 
functional_js profile image
Functional Javascript

I'll do an article on logging and troubleshooting pipes later this week.
But here's an example of one of the log utils throwing on an unexpected type...

logging functional pipelines

Thread Thread
 
tech6hutch profile image
Hutch

This seems like a poor man's TypeScript.

Thread Thread
 
functional_js profile image
Functional Javascript

Typescript does not do runtime type checking.

Thread Thread
 
tech6hutch profile image
Hutch

Because I'm saying you should check it at compile time

Thread Thread
 
functional_js profile image
Functional Javascript

That won't help you with dynamic data at runtime.
That's where the runtime bugs are.
Thus this is outside the scope of Typescript.

Thread Thread
 
tech6hutch profile image
Hutch

Ok then I guess I misunderstood, sorry