0

I'm new to functional programming and I'm trying to refactor my code to have no side-effect.

let keywords = _.get(content, '[0].keywords', []);
keywords = keywords.slice(0, config.keywordLimit);

I'm using lodash. I believe you can just chain these two methods and be something like this.

const keywords = _.get(content, '[0].keywords', []).slice(0, config.keywordLimit);

But I'm just wondering if there's a more functional way of doing this in JavaScript?

1
  • 2
    That's how I would do it. Commented Dec 14, 2016 at 18:47

1 Answer 1

2

Basically, functional style is all about composition. Here is a sample:

var get = _.curry(_.flip(_.get), 3);
var slice = _.curry(_.flip(_.slice), 3);

var comp = function(f, g) {
  return function(x) {
    return f(g(x));
  }
};

var config = {
  keywordLimit: 2
};

var program = comp(
  slice(config.keywordLimit, 0),
  get([], 'x')
)

var x = program({
  x: ['abc', 'qwe', 'sdf']
});

console.log(x);
<script src="https://raw.githubusercontent.com/lodash/lodash/4.17.2/dist/lodash.min.js"></script>

In case, this fiddle doesn't work, here's jsbin: http://jsbin.com/gicocivife/edit?js,console

Pay attention to ugly curry(flip(get)) and curry(flip(slise)). The problem is that functions in lodash has such an order of arguments that prevents you from composition. Your function expects data to work with, right? Thus, the argument for this data must be the last one. Therefore, you can compose functions. I'd recommend to look at Ramda. Not only from my point of view this is a great library for FP. Here's the same example written with it.

var config = { keywordLimit: 2 };

var program = compose(
  slice(0, config.keywordLimit),
  view(lensProp('x'))
)

program({
  x: ['abc', 'qwe', 'sdf']
});

The thing is, functions are curried by default. Thus, the partial application comes naturally. It also features Lenses, which is an awesome thing!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.