Jamison Prianos, Accusoft Software Development Manager, SaaS
Looking at the piece of code here, you can see we have a single function that does some sort of synchronous task.
- We keep a state.
- We set the state to processing.
- We loop through and run this function.
- We set the state to completed.
With last year’s release of the language (ES2015), they do now have the actual ‘class’ keyword, which basically desugars to prototype stuff, but it lets you say `class myClass` and treat the object line a traditional class.
This example is too complex for what it does, but we have functions that will double the value, add five to that value, and put an X at the end of it. And then we make a function that takes any number of arguments, and composes them as a chain of functions—so F of X of G of Y, and make a new function. This defines the new function that composes all those together. So anything we pass here now we will take all three of those numbers and process them. It’s going to take the number (3), double the value (6), add 5 (11), append an X, so the output of this is going to be 11x 19x 9x. All of that by taking all these functions, composing them, and passing them as values. You treat functions no differently than you treat a number or a string or anything else. In fact, you can take a function variable and recast it to a string to see the name of the function. They are fully first-class functions.
As we see here, console.log spits something out. So here’s our output—Hello, World! It’s like we’d expect. We can then grab that to another function and override it with a new function that figures out the date and prepends it. And now, anywhere else in our code, every console.log we do we throw a timestamp in front of it.
This is why it’s so powerful to be able to mutate things. Doing something like this in a language that’s managed and requires you to define everything ahead of time isn’t impossible with language internals. You have to write your own mylogger.log, and then everywhere in your code, replace console.log with mylogger.log. This lets us put this chunk of code as a library in our clients-side text, right in line of our HTML page, and now every library that runs, everything in my third-party libraries, everything that I have no access to, all their logs suddenly have time stamps on them. It’s very powerful but also very dangerous in that you can completely break third-party libraries by changing dependencies that were expecting to be there. So, it’s important to use that carefully and remember that with great power comes great responsibility.
Jamison Prianos is a Software Development Manager in the SaaS division of Accusoft Corporation. In addition to coordinating engineering efforts for his teams, Jamison acts as an evangelist for solid Node development patterns and specifically microservices both within and outside of Accusoft, while also holding on to actual development work for dear life.