Pages

Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

[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.

[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.

[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.

Lodash merge without overwriting

In many cases, you want to combine small objects into a big object. Lodash gives you _.merge() method to do so. (For more usages of _.merge(), see the lodash's docs).


let name = {name: 'Joe'},
    age = {age: 18},
    user = _.merge(name, age); // user = {name: 'Joe', age: 18}     

But what if you want to merge more than 2 objects together? Say, an array of objects? Well, remember apply method?