Moshe's Blog

Tips and tricks learnt along the way.

Removing Css From Your Workflow

| Comments

I recently started a new project using webpack and babel and react. In the process I was able to eliminate css completely from my workflow. Here’s how it used to look:

1
2
3
4
5
6
7
8
9
10
11
12
13
const MyComponent = React.createClass({
  render() {
    return (
      <ul className="my-list">
        {
          items.map(item => {
            return <li className="list-item">{item}</li>;
          })
        }
      </ul>
    );
  }
})
1
2
3
4
5
6
7
8
9
/* sass or less */
.my-list {
  font-size: 10px;
  position: relative;

  .list-item {
    color: red;
  }
}

or something like that. The problem with this approach is that all the css rules are global so you have to make sure not to step on anyone else’s toes. Projects like CSS Modules address this problem. Of course you can always namespace your modules with a root CSS class, but when you do have specific rules that are shared (invalid inputs for example), things start getting messy.

If you’re already using babel and react then there’s a similar solution you can use without installing anything else. The idea is to use react inline style. Using that we get rid of the everything being global and colliding with everything else problem So that’s half the battle.

What about inheriting styles from other elements? Well instead of having a cascade happen, we can be explicit and declare exactly how we want to inherit other styles by using the spread operator. Here’s the final version of what the code would look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// style.js
export const ul {
  position: 'relative',
  fontSize: 10
};

export const li {
  ...ul,
  color: 'red'
};

// index.js
import {ul, li} from './style';
const MyComponent = React.createClass({
  render() {
    return (
      <ul style={ul}>
        {
          items.map(item => {
            return <li style={li}>{item}</li>;
          })
        }
      </ul>
    );
  }
})

A great thing about this is that looking at the class and the spreads on it, you can easily see which rules will override other rules based on the spread position, for example o1:{a:1}, o2={b:2}, o3={a:3}, final={ ...o1, ...o2, ...o3 } then final will equal {a:3, b:2}

This would make deep inheritance somewhat of a pain, but how often is deep inheritance actually needed? I suspect not that often

The One Hour Side Project

| Comments

I’d like to talk about side projects. If you’re a strict nine to fiver then this blog post probably isn’t for you.

A lot of the side projects that I created when I first started programming were fairly ambitious in their functionality and complexity, this led to the average project I started taking at least a week to get to the point of releasable. Recently I started what I call “The One Hour Side Project”.

One of the things I love about javascript and web in general is the lack of effort required to get started. The popularity of PHP regardless of your opinion of the language is further proof of that. This idea of making things consumable in bite sized pieces is an extremely powerful concept and attracts people to it.

“The One Hour Side Project” takes this idea to the area of side projects.

The first thing I would recommend would be to create a RandomProjects folder or something of that nature in your home/projects directory. When you think of something small or see a novel way to extend another library go ahead and create a folder/fork a repo and start hacking. The goal is to have something workable before you get up.

Ever create a browserify transform? Make a toUppercase transform
Curious about testing frameworks? Make a micro clone
Don’t really “get” promises? Create your own take on it
Want it include jQuery on any page? Create a bookmarklet
Don’t like the exact functionality of an extension? Fork it and modify

Screw around with some async stuff. Write a 10 line quicksort. Try to break babel. Start a blog.

Now get out there any make something!

Solving the “Where Did This Tab Come From?” Question

| Comments

Sometimes I find myself with long lived tabs and I don’t always remember how I wound up on some of those pages.

Here’s a neat little trick I discovered today while trying to find out if I should share an article with someone or if they already shared it with me.

First things first, open dev-tools

Then go to the network panel network panel

Now refresh the page and scroll to the top of the list of resources and click the top one referer

Under the referer request header you should see how you wound up on that page.


Thanks for mkoldnd for inspiring this bookmarklet Referer

Handling Optional Args in JS

| Comments

Often times I find myself writing functions which have optional args, while it’s generally a better idea to pass an options object instead for mutliple arguments, three (maybe four) can still be considered an acceptable arity.

Let’s take a simple signature and implement some optional args.

1
function require(name, deps, fn) {}

The way I started to deal with cases like this is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function require(name, deps, fn) {
  var args = [].slice.call(arguments);

  if (typeof args[0] !== 'string') {
    args.splice(0, 0, null);
  }

  if (!(args[1] instanceof Array)) {
    args.splice(1, 0, []);
  }

  if (typeof args[2] !== 'function') {
    args.splice(2, 0, function() {});
  }

  [name, deps, fn] = args; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

}

I find this the clearest way to deal with optional args and I find the logic very easy to follow.

Evaling With Style

| Comments

A couple of projects I’ve been working on, required me to turn strings into functions (templating, custom require, mocha clone) and it didn’t seem like there was a good way to do it with things I needed in scope.

Let’s take a look at a couple of ways to do it.

There’s John Resig’s microtemplating way which is something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var str = 'hello <%= obj.name %>, upperized: <%= obj.name.toUpperCase() %>';
var ctx = { name: 'Moshe' };
var go = function(str) {
  return new Function('obj',
    [
      'var p = [];',
      'p.push(',
        '"' + str.replace(/<%= (.*?) %>/g, '", $1, "') + '"',
      ');',
      'return p.join("")',
    ].join('')
  )
}
console.log(go(str)(ctx))

The issue with this way is that this doesn’t scale, since you have to keep adding more params of things you need scope for. For example if we wanted to add helper functions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var str = 'hello <%= obj.name %>, upperized: <%= helpers.up(obj.name) %>';
var helpers = {up: function(str) { return str.toUpperCase(); }};
var ctx = { name: 'Moshe' };
var go = function(str) {
  return new Function('obj', 'helpers',
    [
      'var p = [];',
      'p.push(',
        '"' + str.replace(/<%= (.*?) %>/g, '", $1, "') + '"',
      ');',
      'return p.join("")',
    ].join('')
  )
}
go(str)(ctx, helpers)

You can see that this doesn’t really work as more things are needed.

Another way is to use with to put things in scope:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var str = 'hello <%= obj.name %>, upperized: <%= h.up(obj.name) %>';
var helpers = {up: function(str) { return str.toUpperCase(); }};
var ctx = { name: 'Moshe' };
var go = function(str) {
  return new Function('obj', 'expose',
    [
      'with (expose) {',
        'var p = [];',
        'p.push(',
          '"' + str.replace(/<%= (.*?) %>/g, '", $1, "') + '"',
        ');',
        'return p.join("")',
      '}',
    ].join('')
  )
}
go(str)(ctx, {h:helpers})

This works really well but there’s a huge performance hit from using with

If you’re using node there’s a vm module which is really what we’re looking for, but I wanted something I could also use in the browser.

After playing around with this problem, I came up with the following solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
function eval2(str, context, expose) {
  var exposeKeys = [];
  var exposeValues = [];
  for (var i in expose) {
    if (Object.hasOwnProperty.call(expose, i)) {
      exposeKeys.push(i);
      exposeValues.push(expose[i]);
    }
  }
  return (new Function(
    'return function(' + exposeKeys + '){return function(){' + str + '}.bind(this)}'
  ))().apply(context, exposeValues);
}

You would use something like that as follows:

1
2
3
var ctx = {};
var expose = {up: function(str) { return str.toUpperCase() }};
eval2('console.log(arguments)', ctx, expose)('Look! Even has args!')

Let’s go through how this works.

Consider this:

1
2
3
4
5
6
7
8
var r = new Function('return function inner() {}');
console.log(r.toString()); // 'function anonymous() {\nreturn function inner() {}\n}'
console.log(r().toString()) // 'function inner() {}'

var s = new Function('return function(a,b,c){console.log(a,b,c)}');
console.log(s.toString()) // 'function anonymous() {\nreturn function(a,b,c){console.log(a,b,c)}\n} '
console.log(s().toString()) // 'function (a,b,c){console.log(a,b,c)}'
s()('aa', 'bb', 'cc') // logs 'aa', 'bb', 'cc'

Now going to back to the way we use it:

1
2
3
var code = 'console.log(this)';
var ctx = {the: 'context'};
var fn = (new Function('return function() {' + code + '}'))().call(ctx);

If you wanted to have some stuff in scope:

1
2
3
4
5
var code = 'log(this); hey(this.the)';
var ctx = {the: 'context'};
var params = ['log', 'hey']; // [].toString joins on comma by default so it just works
var applies = [function(str) { console.log(str) }, alert];
var fn = (new Function('return function(' + params + ') {' + code + '}'))().apply(ctx, applies);

And if you wanted to curry it just wrap it in another function:

1
2
3
4
5
var code = 'log(this); hey(this.the)';
var ctx = {the: 'context'};
var params = ['log', 'hey']; // [].toString joins on comma by default so it just works
var applies = [function(str) { console.log(str) }, alert];
var fn = (new Function('return function(' + params + ') {return function(){' + code + '}.bind(this)}'))().apply(ctx, applies);

I didn’t really run any benchmarks but I suspect that this is pretty performant and once you wrap your head around it, is actually pretty simple.

Happy Coding!

Piping to Sublime

| Comments

Every now and then I need to do a quick and dirty transform to a pipe. When it’s a one off type of thing and I don’t want to bother with awd sed or nip, I’ll use sublime to do a quick transform

in progress saved

And when you save and exit:

done

When Programming Goes Bad - Debugging the Impossible

| Comments

Sometimes code for a project gets so big and so deeply indirected that debugging is nearly impossible.

We had a bug similar to this where a controller was changing models which triggered avalanches of cascades that no human could follow. The only thing we knew was that a select with an id of elusive was being changed through jQuery.

After trying in vain to figure out where the change was happening, I had an aha! moment

This is basically how I solved it:

(function($) {
    var oldAttr = $.fn.attr;
    var oldProp = $.fn.prop;
    $.fn.attr = function() {
        if (this.id === 'elusive') {
            debugger;           
        }
        return oldAttr.apply(this, arguments);
    };
    $.fn.prop = function() {
        if (this.id === 'elusive') {
            debugger;           
        }
        return oldProp(this, arguments);
    };
})(jQuery);

Then it’s just a matter of looking at the call stack and working backwards from there.

Writing Async Javascript Code in Sync Format - Part 2

| Comments

This is a continuation of Writing Async Javascript Code in Sync Format – Part 1

There’s a new es6 feature called Destructuring Assignment that looks like this:

1
2
3
4
5
6
var [a, b] = ['a', 'b'];
a === 'a';
b === 'b';
var {q:q, r:r} = {q: 'q', r: 'r'};
q === 'q';
r === 'r';

Keep in mind that objects can mimic arrays so this works:

1
2
3
var [x,y] = {0: 'x', 1: 'y'};
x === 'x';
y === 'y';

There’s also a shortcut available for assigning to objects in es6 where var {x:x, y:y} can be written as var {x, y} This means we could have written

1
2
3
var {q, r} = {q: 'q', r: 'r'};
q === 'q';
r === 'r';

Using this knowledge and what we did in the first part we can write really cool concurrent code:

Promise.props is a bluebird specific function that does what Promise.all except on objects. If you’re using native Promises it doesn’t take much to polyfill it

Writing Async Javascript Code in Sync Format - Part 1

| Comments

Writing async code is hard when not done properly. However there are ways to make it a breeze. One of them is to use promises and not have to worry about code being async or not.

I was looking around at different things and came across koa and got inspired to try a similar idea.

The basic idea of Koa is that when you need some async functionality you yield an async thingy like a promise or something similar and then koa waits for it to resolve and then continues your program injecting the new value into the function.

Sounds complicated? Let’s try an example (all examples will only run in FF unless Chrome decides to support generators)

Let’s start with a simple generator.

As you can see the syntax is function *() {} and you need to instantiate a generator before you can use it. For more info on the basics of generators see MDN

A cool thing about generators is that you can inject a value back into the generator function like so:

You actually can’t inject something into the first .next() call, if you try you get this error: TypeError: attempt to send "a" to newborn generator

Using just these two concepts and the very basics about Promises, we can write something that:

  1. Runs a generator until control is given back
  2. If result if promise like, then resolve it and inject the resolved value back to the generator
  3. Rinse and repeat.

Let’s start to write just that. Here’s what out program will look like:

function *program() {
    var rand;
    rand = yield getRandAsync();
    console.log('first time around = ' + rand);
    rand = yield getRandAsync();
    console.log('second time around = ' + rand);
}

function getRandAsync() {
    return Promise.resolve(Math.random())
}

run(program());

Now all we need to do is write the run function:

function run(gen) {

    step();

    function step(value) {
        var result = gen.next(value);
        if (result.value instanceof Promise) {
            result.value.then(step);
        }
    }

}

Putting that all together:

Now a couple of nice thigs to have. Let’s assume that sometime in the future getRandAsync is changed to just return a value and not a promise, we should handle that:

function run(gen) {

    step();

    function step(value) {
        var result = gen.next(value);
        if (result.value instanceof Promise) {
            result.value.then(step);
        } else if (!result.done) {
            step(result.value);
        }
    }

}

Easy enough. Now how would we handle concurrent async functions? Well the Promise object has a method all which handles it nicely, we just need to utilize it (MDN ctrl+f Promise.all):

function run(gen) {

    step();

    function step(value) {
        var result = gen.next(value);
        if (result.value instanceof Promise) {
            result.value.then(step);
        } else if (result.value instanceof Array) {
            Promise.all(result.value).then(step);
        } else if (!result.done) {
            step(result.value);
        }
    }

}

Now we can yield an array of promises to run and Promise.all will handle them. The great thing about Promise.all is that it will handle an array of non promises just as well

putting that all together we get a very powerfull way to write javascript:

Gist

Require a Promise

| Comments

I was recently asked how to make a node module that needs to do a database lookup or something else before it can give you an API. The main problem is that require is synchronize and doesn’t have a concept of callback or a mechanism to wait for a response The are a couple of ways to solve this, I’ll first go through the standard solution and then how I would do it.

The standard way people solve this is by having the API take a callback:

var gister = require('gister');

gister(function(err, create) {
    if (err) throw err;
    create(fileContents);
});

Now this is easy to read and makes a lot of sense, but you run into a problem of when you have more than one module like this:

var gister = require('gister');
var snippeter = require('snippeter');
var apis = {};
var ticks = 2;

gister(function(err, create) {
    if (err) throw err;
    apis.gister = create;
    if (--ticks === 0) ready(apis);
});
snippeter(function(err, create) {
    if (err) throw err;
    apis.snippeter = create;
    if (--ticks === 0) ready(apis);
});
function ready(apis) {
    // apis.gister
    // apis.snippeter
}

This definitly doesn’t scale, fortunately we can solve this using the magic of Promises

File index.js:

var Promise = require("bluebird");

var soon = require('./soon.js');

Promise.all([soon]).then(function(soon) {
    console.log(soon);
});

File soon.js

var Promise = require("bluebird");

var ret = {
    obj: 'to return'
};

module.exports = new Promise(function(resolve, reject) {
    setTimeout(function() {
        if (Math.random() < .1) {
            console.log('about to reject');
            reject(new Error('Db error'));
            console.log('rejected');
        } else {
            console.log('about to resolve');
            resolve(ret);
            console.log('resolved');
        }
    }, 5000);
});

//module.exports = ret;

Now the cool thing about doing it this way is that we can switch back to a synchronize way of loading without having to change any code. We can simulate this by uncommenting the last line //module.exports = ret; and it will still run the same