Functional programming in Javascript: The basics

This post will be an intro to the very basics of functional programming style. Before I begin, let’s defins what I mean by functional.

Functional programming is a paradigm, style, just like object oriented programming is.
There are two differences you must understand if you’re coming from a OO background.

Composition over inheritance: In functional programming there’s no inheritance. Objects and functions are composed to become what you want.

Functions must be pure / have no side effects: A function should never mutate / change the value of anything outside it’s own scope. It must always leave it untouced so that calling the function has no side effects in our app and we should always expect the same result if we call it multiple times.

let myVar = 'Hello'

function pureReverseString(s) {
return s.split('').reverse().join('')

function unPureReverseString(s) {
myVar = s.split('').reverse().join('')
return myVar

const rev1 = pureReverseString(myVar)
console.log(myVar, rev1) // Outputs 'Hello' 'olleH'
const rev11 = pureReverseString(myVar)
console.log(myVar, rev11) // Outputs 'Hello' 'olleH'

const rev2 = unPureReverseString(myVar)
console.log(myVar, rev2) // Outputs 'olleH' 'olleH'
const rev21 = unPureReverseString(myVar)
console.log(myVar, rev21) // Outputs 'Hello' 'Hello'

Quite silly example, but we clearly see that the second function mutates the myVar variable which could have side effects on our app. And also, when calling it multiple times with the same input variable we get different results.
Hard to test and debug.

This is the basics.

Functional programming also uses something called curried functions or just currying. This is a quite cool and handy way of composing functions that can be used later over and over again.

// Let's say we have a simple add function that adds two integers
function add(x,y) {
return x + y

// This is the curried function
// You can call the curried function by addCurried(1)(2) to add 1+2
function addCurried(what) {
return function(num) {
return what+num

const addFive = addCurried(5) // Partial curried function
const addThree = addCurried(3) // Partial curried function

console.log(addFive(4)) // Outputs 9
console.log(addFive(4)) // Outputs 9

console.log(addThree(4)) // Outputs 7
console.log(addThree(4)) // Outputs 7

Again, not super useful example but consider a role play where addFive could be something like swordHit and addThree might be knifeHit.

I’ll continue exploring functional programming in Javascript more in depth in future posts.

Throttle function calls

A throttle function is a function that limit the number of calls to 1 per x time units.
I recently wanted to capture the mousemove event and reset a timer when the mouse was moved. Since the mousemove event is triggered several times per second I don’t want my reset function to be called every time. It would be fine for my reset function to be called once every 5 seconds or something like that.
Resetting a timer is quite cheap, but if I wanted to do something expensive the app would be very sluggish doing these expensive operations too often.

So I came up with this function, written in Coffeescript.

throttle = (func, wait) ->
  last_timestamp = null
  limit = wait
    context = @
    args = arguments
    now =
    if !last_timestamp || now - last_timestamp >= limit
      last_timestamp = now
      func.apply(context, args)

mythrottle = throttle(
  (e) ->
    console.log e

elem.bind('mousemove', (e)->

And in Javascript.

var throttle = function(func, wait) {
  var last_timestamp, limit;
  last_timestamp = null;
  limit = wait;
  return function() {
    var args, context, now;
    context = this;
    args = arguments;
    now =;
    if (!last_timestamp || now - last_timestamp >= limit) {
      last_timestamp = now;
      return func.apply(context, args);

var mythrottle = throttle(function(e) {
  return console.log(e);
}, 5000);

elem.bind('mousemove', function(e) {
  return mythrottle(e);

elem is the selected element, like $('#id') in jQuery.

We’re calling mythrottle(e) every 5 seconds on constant mousemove now, instead of several times every second.

Writing the book: Build your own PaaS with Docker

So, I’ve written a book. A real book that’s sold on Amazon (amongst other stores). Printed on paper (or as an ebook as well, of course).

It was a lot harder than I thought.
Getting the language right (since I’m not a native english speaker) and getting a good flow within every chapter as well as through the whole book.
Authoring chapters that will give readers insights and knowledge. It’s hard.

It took much longer than I thought. I’d just started working for Neo4j and had 2,5 years old daughter that wanted attention all awake time.
So there were lots of late night writing done. Lots. Days before some deadlines I hardly didn’t sleep at all.

The book is about how you can use Docker to build your own Platform as a Service. Docker is still pretty young and breaking changes come pretty often which had the effect that I had to rewrite parts of the book from time to time to reflect these Docker changes.
And I wrote about Fig and they get acquired by Docker, changing it’s name to Docker Compose so I had to rewrite that part as well. You get the idea.

It’s published by PACKT Publishing, which is a brittish publishing company founded in 2004.

If was a fun and educating experice and I wouldn’t mind writing another book. Not right now, but in the near future.
But I would choose a more stable topic and probably not have such short deadlines (I would write on my terms).

I’m super exited that I’ve written a book and can call myself an author / published writer.
I’m also very self critical and find things I’m not happy with through out the whole book. On the other hand, the book would never have been published if I was to be happy with every sentence in it.

The book is called Build your own PaaS with Docker and can be found on Amazon and in Packts webshop.
Check it out.


Offline mode in OS X

When working on web apps we have to keep in mind that the client might not have access to the internet all the time. Chrome has a great feature for this:
Chrome network settings

When working on a web app that make requests to a API located at localhost but also make requests to external API:s, it’s harder.
I solved this issue by creating a new Location in OS X Network part of System Preferences. The new Location has WiFi and Ethernet Configure IPv4 set to Off, which means that it’s offline but you can still reach your localhost server.

OS X Network Location

Good times!

Untracked files in newly cloned Git repo?

It has happend a few times for me: I clone a remote Git repository, and when I do git status to see info one or more untracked files are listed.
It’s quite annoying and I could see the pattern that the filenames of these files has UTF-8 / special characters in them (åäö).

What to do to resolve this?

Do this: git config core.precomposeunicode false and they’re tracked.



This option is only used by Mac OS implementation of Git. When core.precomposeunicode=true, 
Git reverts the unicode decomposition of filenames done by Mac OS. 
This is useful when sharing a repository between Mac OS and Linux or Windows. 
(Git for Windows 1.7.10 or higher is needed, or Git under cygwin 1.7). 
When false, file names are handled fully transparent by Git, which is backward compatible with 
older versions of Git.


Git - Feature branch model

Whether you use Git with a centralized repository (like Github or Bitbucket) or just a local copy, I would always advice you to use the Feature branch model as your Git workflow.

Here are the key points that describes the Git feature branch workflow:

  • No development happens or are pushed directly to the master branch.
  • Create a new branch, a feature branch, when you start development on a new feature.
  • Feature branches should have descriptive names, like add-printing-stylesheet.
  • When the feature is finished, you merge in into master or create a pull request if you use a central repository and use pull requests / code review.
  • When it’s merged, delete the feature branch. Keep the branches as short lived as possible.

If you follow this you will always have a working master branch and all feature development is isolated from the main codebase until they are finished.

Angular - Bootstrap - Jade - Stylus - CoffeeScript boilerplate webapp with Yeoman

Sorry about all the buzzwords in the title but it really describes what this note-to-self post is about.

How to create a boilerplate web app using AngularJS as framework, Bootstrap as HTML/CSS base, Jade as HTML replacement, Stylus as CSS replacement, and CoffeeScript as a Javascript replacement/generator/transpiler. All using Grunt as the glue that keeps everything together.

Npm and Bower makes sure all dependencies are in place. And Karma for the testing.

To create the scaffolding I use a tool named Yeoman that has all these generators that installs all tolls you need, configures Grunt, npm and Bower and generates a basic app file structure so you can jump straight into the code.

Lots of tools and replacements/generators/transpiler languages and there certainly are better or faster ones out there, but these makes me comfortable and I can get to work in 2 min.

Anyway, this is how I do it:

npm install --global yo bower grunt-cli
npm install --global generator-angular-jade-stylus

mkdir newapp && cd $_
yo angular-jade-stylus --coffee --jade --stylus newapp

Run npm cache clean and repeat the last line if it fails.

Answer yes to all questions.

Run grunt serve and point your browser to localhost:9000 unless it does so for you.

Bam, done.

Thank you Yeoman.

Again: Add Authorization header to AngularJS $http

In my last post I showed how I add an Authorization header to outgoing $http calls in AngularJS. I’ve changed the way I do it, this which I think is easier to read.

  .factory('RequestInterceptor', [
    (AuthDataService) ->
      interceptor = 
        request: (config) ->
          header = AuthDataService.getAuthData()
          if header then config.headers['Authorization'] = "Basic #{header}"

angular.module('app').config(['$httpProvider', ($httpProvider) ->
  $httpProvider.interceptors.push 'RequestInterceptor'

The AuthDataService is the same as in my last post, but without the the setting of $http.defaults.headers.common['Authorization'].

Add Authorization header to AngularJS $http

I recently had to add an Authorization header to all $http requests in an AngularJS app.

Here’s how I did it in Coffeescript.

.factory 'AuthDataService', [
  (localStorageService, $base64, $http) ->
    current_auth_data = localStorageService.get('authorization_token')
    if current_auth_data
      $http.defaults.headers.common['Authorization'] = "Basic #{current_auth_data}"

    return {
      setAuthData: (authdata) ->
        return unless authdata
        encoded = $base64.encode(authdata)
        localStorageService.set('authorization_token', encoded)
        $http.defaults.headers.common['Authorization'] = "Basic #{encoded}"
      clearAuthData: ->
        $http.defaults.headers.common['Authorization'] = ''
      getAuthData: ->
        return localStorageService.get('authorization_token')

Upon initialization it checks if there’s a authorization_token saved in your local storage. If there is, set it as a Authorization header on $http.

Whenever you set or clear the auth data, the header for $http changes as well.

EDIT: I’ve written another post about how to add Authorization header to AngularJS $http

AngularJS: $watch and $timeout

As you might know, AngularJS has an event loop, called $digest, that checks and updates all bindings and values.

You can have a DOM element only show when a scope variable has a certain value, like this:

<div ng-show="show_div">Text in div</div>

Whenever the $digest runs, it checks if $scope.show_div is true and if it is, the div is shown. If not true, the div is hidden.

That means that in your controller you can toggle the visibility of the div by simply setting $scope.show_div = true/false. However, if you do this on mouseover an element or change the value very frequently some other way the $digest might not have had the time to finish it’s loop and the div won’t toggle as it should.

That’s where $timeout comes in. It’s a wrapper for javascript’s setTimeout with the addition that it triggers a $digest loop at the end meaning that anything you changed will be updated as it should.

So instead of $scope.show_div = true and then $scope.show_div = false you do:

$timeout(function() { $scope.show_div = true; }, 0);
$timeout(function() { $scope.show_div = false; }, 0);

Note to self on updating Wordpress plugins via git-svn

I host my Two Factor Auth Wordpress Plugin on Github and I run git svn locally to be able to sync the Github git repo with the Wordpress plugins SVN repo.

But, it’s a bit of a hassle and I don’t update the plugin often enough to remember what step to take.

The assumption is that you’ve followed this guide to setup you local repo with svn and git remotes.


Write code in local git feature branches as usual. Push the finished code to Githubs master branch and add a git tag.


Create a new local git branch (or use a clean old one) and merge local master branch (remember to squash all commits!) into this one. It has to have a straight history.


Run git svn rebase the see that the history matches with the remote Worpress svn repo.


Run git svn dcommit --username yourusername to push the code to Wordpress svn repo. Remember that you have to change all the tags in your readme.txt and you main plugin file to match the new release version.


Run git svn tag x.x to copy trunk and create a new remote tag/release from it.