Skip to content

Instantly share code, notes, and snippets.

@OliverJAsh
Last active December 27, 2015 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OliverJAsh/7392379 to your computer and use it in GitHub Desktop.
Save OliverJAsh/7392379 to your computer and use it in GitHub Desktop.
Functional programming experiment
/**
* Goal: add 10 to each persons age using functions from Lodash and curry only.
*
* I have provided a custom version of curry, instead of using _.curry, as
* the one in Lodash sadly doesn't play nicely here.
*
* Transform:
* [ { name: 'Foo', age: 20 }, { name: 'Baz', age: 21 } ]
* into:
* [ { name: 'Foo', age: 30 }, { name: 'Baz', age: 31 } ]
*
* Is there a better way than the one below?
*/
var people = [ { name: 'Foo', age: 20 }, { name: 'Baz', age: 21 } ];
people.map(_.pairs).map(curry(_.partialRight(_.map, function (item) {
if (_.first(item) === 'age') item[1] = item[1] + 10;
return item;
}))).map(curry(_.zipObject));
function curry(fn) {
return function (arg1) {
return fn(arg1);
};
}
/**
* I know very little Scala, but off the top of my head, I think
* this is what it might look like:
*
* people.map(pairs(_)).map(_.map({
* item => if (first(item) === 'age') item[1] = item[1] + 10;
* })).map(zipObject(_))
*/
/**
* Another way of doing it would be to write a custom `transform` function.
*/
people.map(transform('age', function (age) { return age + 10; }));
function transform(key, fn) {
return function (object) {
// Immutability by inheritance – delegate to our original object
var newObject = Object.create(object);
newObject[key] = fn(object[key]);
return newObject;
};
}
@OliverJAsh
Copy link
Author

Also looking for a way to use functions only from Lodash, if that's possible. It would be nice if I didn't have to write my own curry function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment