Lead Developer, radify.io
warren@radify.io
@woogoose
forEach([4, 8, 15, 16, 23, 42], function(n) {
console.log(n + 1);
});
// 5 9 16 17 24 43(Functions as arguments to other functions)
function forEach(array, fn) {
for(var i = 0; i < array.length; i++) {
fn(array[i]);
}
}var numbers = [4, 8, 15, 16, 23, 42];_.map, _.reduce and friends
_.map(numbers, function(n) {
return n * 2;
}); // => [8, 16, 30, 32, 46, 84]_.reduce(numbers, function(sum, n) {
return sum + n;
}, 0); // => 108_.filter(numbers, function(n) {
return n > 10;
}); // => [15, 16, 23, 42]_(numbers)_.chain(value) ▸ operations ▸ .value()
.filter(function(n) {
return n > 10;
}) .reverse() .map(function(n) {
return n * 2;
}) .value();
// => [84, 46, 32, 30]Powerful, useful, oh-so slightly lacking
function greaterThan(compare, number) {
return number > compare;
}_.partial(fn, arguments)
_.filter(numbers, greaterThanTen);
// => [15, 16, 23, 42]var greaterThanTen = _.partial(greaterThan, 10);Inflexible
ramdajs.com
R.map(function(n) {
return n * 2;
}, numbers); // => [8, 16, 30, 32, 46, 84]map(fn, data);
R.reduce(function(sum, n) {
return sum + n;
}, 0, numbers); // => 108R.filter(function(n) {
return n > 10;
}, numbers); // => [15, 16, 23, 42]f(x, y) ▸ f(x)(y)
var add = function(a, b) {
return a + b;
};
add(4, 5); // => 9var cAdd = R.curry(add);
var addFourTo = cAdd(4);
addFourTo(5); // => 9aka: a better _.partial
cAdd(4)(5); // => 9
cAdd(4, 5); // => 9currying
[glencurry like a glenboss]
var times = R.curry(function(a, b) {
return a * b;
});
R.map(times(2), numbers)
// => [8, 16, 30, 32, 46, 84]map(c(x), data)
Ramda functions are auto-curried!
R.map(fn, data)
var mapTimes2 = R.map(times(2));
mapTimes2(numbers);function firstToUpper(string) {
return R.head(R.toUpper(string));
}
firstToUpper('abc'); // => 'A'f(g(x)) ▸ c(f, g)(x)
var firstToUpper = R.compose(R.head, R.toUpper);
firstToUpper('abc'); // => 'A'f(g(x)) ▸ c(f, g)(x)
f(g(x)) ▸ p(g, f)(x)
f(g(x)) ▸ c(f, g)(x)
var pipe = R.pipe(
R.filter(R.lt(10)),
R.reverse,
R.map(R.multiply(2))
);
pipe(numbers)
// => [84, 46, 32, 30][whoa]
I'm looking at you, _.extend!
var source = { foo: 'bar' };
var dest = _.extend(source, {
baz: 'qux'
});
console.log(dest);
// { foo: 'bar', baz: 'qux' }
console.log(source);
// { foo: 'bar', baz: 'qux' }var source = { foo: 'bar' };
var dest = R.merge(source, {
baz: 'qux'
});
console.log(dest);
// { foo: 'bar', baz: 'qux' }
console.log(source);
// { foo: 'bar' }Returns merged object and mutates source
Does not mutate source
_.extend({}, source, dest)
// bleugh!var source = {foo: 'bar'};
var dest = R.assoc('baz', 'qux', source);
console.log(dest);
// { foo: 'bar', baz: 'qux' }
console.log(source);
// { foo: 'bar' }@see R.assocPath
var source = [4, 8, 15];
var dest = R.append(16, source);
console.log(dest);
// [4, 8, 15, 16]
console.log(source);
// [4, 8, 15]