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.

[NodeJS] Pushing posts to Blogger from commandline

I was trying to write some small cli to push my posts to Blogger from the commandline. There are some tools out there, including googlecl and blogger-cli but no nodejs tool as far as I know. So, I registered to use Blogger API. Unfortunately, you'll have to wait 5 days just to get approval and instruction from Google, and that process is handled by only one man, Brett. So, while waiting for the API, here's my work around.

Install Powerline for Mac OS X

Powerline is a shell prompt and statusline plugin for vim, written in Python. It makes working with terminal much more fun and colorful. Here is an example of how the prompt looks like with Powerline.

As you can see from the screenshot, powerline gives you a colorful and visual attractive prompt. If you are in a git repository, it also tells you which branch you are currently working on. It also tells you the exit code of previous process (the number in the last red tab), etc. In this post, I'll show you how to install and setup powerline for Mac OS X bash shell and vim.

How to insert code snippets to Blogger blogs

This is my third day, i.e. roughly more than 2 hours, playing with Blogger. So, this post reflects my minimal knowledge of the system. If you have better solutions, please drop me a comment below. So far, I really like Blogger for its simplicity. However, I didn't find a nice and efficient way to put code snippets into my blog posts. A quick google search reveals that many people have struggled with this problem before. The most popular solution I found is SyntaxHighlighter, written by Alex Gorbatchev.

Git aliases with autocompletion

If you are using git on daily basis, you probably want to create some shorthands, aka. aliases, to save time. The very first option that is documented in tutorials and books about git is through git configuration.

$ vi ~/.gitconig

[alias]
st = status
co = checkout
br = branch
up = rebase
ci = commit

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?

Update bash shell for Mac OS X

Apple releases software update quite often but, unfortunately, bash shell is never updated. The version of bash shell that comes with Max OS is quite old and lacks many features such as globing, exclude-dir when grepping, etc. If you need these features, you will need to update bash shell. First, check the version of your bash.


$ echo $BASH_VERSION
3.2.53(1)-release

$ which bash
/bin/bash