Pages

[JS] Currying with Javascript

I first read about the term curry in the book "Javascript: The Good Parts" by Douglas Crockford. According to the author, currying allows us to create a new function by combining a function and some arguments. The example in the book was something along the following line.


function addBase(base) {
  return function(num) {
    return num + base;
  };
}

var add2 = addBase(2);
add2(6); // => 8

When I first read about it, I thought it was a cool thing to show off with your friends about your coding skills. Nevertherless, I didn't find currying to be very useful. But after a few times seeing it being used in different repos, I just realize how powerful it is as a tool to generate function and simplify callback.

[NodeJS] What is a thunk?

What is a thunk?

A thunk, as Michael Fogus defines in his book "Functional Javascript", is "a function that wraps some behavior for later execuation". Specifically, in Node.js, a thunk of a function fn is a function that partially applies all the arguments of fn except the callback. As a result, the returned function accepts only one argument, which is a callback. For example, let's take a look at the readFile function. Its syntax is as following.


var readFile = require('fs').readFile;

readFile('path/to/file', 'utf-8', function(err, data) {
  if (err) throw err;
  console.log(data);
});

[JS] Understand Javascript event loop

Ever wonder how a single threaded language like Javascript can support concurrency? Of course, via asynchronous callback you will say. But how exactly does it work? or why setTimeout to zero does not enforce a function to be executed immediately?


console.log('Top');

setTimeout(function() {
  console.log('Middle');
}, 0); 

console.log('Bottom');

[NodeJS] How to behave synchronously in an asynchronous world

Dispite the power of asynchronous programming in Javascript, there's time when you want to execute code synchronously. An example is when you have an array of tasks that must be completed sequentially. In this post, we are going to look at different ways to implement this in NodeJS.

Settings

Image you want to simulate the activities in a restaurants. The tasks are: server takes order, chef cooks, server serves food, customers enjoy the food. Since the level of details of simulation can be expanded in the future, we'll maintain an array of all the tasks and pass it to a task runner to handle the tasks.


function order() { console.log('Server gets order.'); }
function cook() {
  fs.readFile('cookbook.txt', function() {
    console.log('Chef cooks food.');
  };
}
function serve() { console.log('Server serves food.'); }
function dine() { console.log('Customers enjoy food.'); }

function run(tasks) {
  // run tasks
}

var tasks = [order, cook, serve, dine];
run(tasks);

As you can see, among these tasks, cook is the longest one because chef must find the recipe in a cookbok before starting to cook. Obviously, it's not a very good restaurant as you can tell but you get the idea.

[NodeJS] Command line tool

Basics

With NodeJS, it's fairly simple to create a command-line tool. First, you need to add bin field into package.json file.


# File: package.json
"bin": {
    "command1": "path/to/command1/implementation",
    "command2": "path/to/command2/implementation",
    "command3": "path/to/command3/implementation"
}

You can have as many commands as you want. I like to store all the executable files in bin/ directory. Let say I want to create a command named node-greet to simply print out a greeting message. Here's the bin field of my package.json

[JS] Convert dash-separated string to camelCased using reduce

It's very common in JS to name files using dash-separated string, and functions using camel case. In fact, many libraries use this rules to automatically discover files. Hence, a function to convert dash-separated string to camelCase is of great use. There are, certainly, many ways to implement this function. I just want to show here one way to it using reduce function.

Just in case you didn't know about reduce function, it executes a call back function once for each element of a collection and store the result in an accumulator, which is the first argument of the callback function. The last argument of reduce function is the inital value of the accumulator. Although, ES standard only supports reducing on Array, lodash library allows you to apply it on objects as well. Following is the syntax of reduce.

[JS] Use object instead of swictch case

If you find yourself writing switch-case or long if-else clauses based on string comparision condition, consider switching it to use object instead. Object in Javascript can be dynamically updated which makes it very flexible. It works as a map so lookup is quick. For example, if you have some code like below.