Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Last active December 11, 2015 06:08
Show Gist options
  • Save pyrtsa/4556680 to your computer and use it in GitHub Desktop.
Save pyrtsa/4556680 to your computer and use it in GitHub Desktop.
Get at it!
// Public domain.
// Attribution welcome, but not required. -- Pyry Jahkola.
// What's the point in all this? To get the equivalent of CoffeeScript's
// (?.) operator into vanilla JavaScript.
// get(x, key1, key2, ...) -- Get the result of x[key1][key2]..., or undefined.
// Will short circuit if a key is not found.
function get(x) {
var keys = Array.prototype.slice.call(arguments, 1);
for (var i = 0; x !== undefined && i < keys.length; i++) {
x = (x && x.hasOwnProperty(keys[i])) ? x[keys[i]] : undefined;
}
return x;
}
// at(x, path) -- Given path='a.b.c', return x['a']['b']['c'], or undefined.
function at(x, path) { return get.apply(null, [x].concat(path.split('.'))); }
// var g = it('a.b.c') -- Make a getter function g(x) to the given key path of x.
function it(path) { return function (x) { return at(x, path); }; }
// Examples:
var x = {x: 1, y: ['a', 'b', {'c': false, 'd': null}]};
get(x, 'x') //=> 1
get(x, 'y') //=> ['a', 'b', {'c': false, 'd': null}]
get(x, 'y', 2, 'c') //=> false
get(x, 'y', 2, 'd') //=> null
get(x, 'z') //=> undefined
get(x, 'z', 0) //=> undefined
at(x, 'x') //=> 1
at(x, 'y') //=> ['a', 'b', {'c': false, 'd': null}]
at(x, 'y.2.c') //=> false
at(x, 'y.2.d') //=> null
at(x, 'z') //=> undefined
at(x, 'z.0') //=> undefined
it('x')(x) //=> 1
it('y')(x) //=> ['a', 'b', {'c': false, 'd': null}]
it('y.2.c')(x) //=> false
it('y.2.d')(x) //=> null
it('z')(x) //=> undefined
it('z.0')(x) //=> undefined
// With `Array.map` or `_.map`, you can use `it` similarly as `_.pluck`:
var people = [
{ name: 'Practical', home: { material: 'bricks', color: 'red' } },
{ name: 'Fiddler', home: { material: 'stricks', color: 'brown' } },
{ name: 'Fifer', home: { material: 'straws', color: 'yellow' } },
{ name: 'The Big Bad', food: 'pork' }
];
people.map(it('name')) //=> ['Practical', 'Fiddler', 'Fifer', 'The Big Bad']
people.map(it('home.color')) //=> ['red', 'brown', 'yellow', undefined]
_.pluck(people, 'name') //=> ['Practical', 'Fiddler', 'Fifer', 'The Big Bad']
_.map(people, it('name')) //=> ['Practical', 'Fiddler', 'Fifer', 'The Big Bad']
_.map(people, it('home.color')) //=> ['red', 'brown', 'yellow', undefined]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment