0

What would be the best way to achieve this using Ramda.js?

function innerVals(array) {
  const lengthMinus1 = array.length - 1;
  return array.slice(1, lengthMinus1);
}

I cannot seem to find a good way to slice until length - 1 without storing that variable somewhere. The best I could come up with is using Ramda's converge function like this:

// innerVals :: Array -> Array
function innerVals(array) {
  // lengthMinus1 :: Array -> Number
  const lengthMinus1 = R.pipe(R.length, R.subtract(_, 1));

  // getVals :: Array -> Array
  const getVals = R.converge(
    R.slice(1, _, _),
    [lengthMinus1, R.identity]
  );

  return getVals(array);
}

I'm having a difficult time believing that this is a clean way to accomplish such a simple goal. There's significantly more code in the functional programming approach, and I also think it would be more difficult for other developers to read / maintain. Am I missing something? If anyone has a different approach, please let me know. Thanks!

wpcarro
  • 1,528
  • 10
  • 13

3 Answers3

4

I recommend R.slice:

> R.slice(1, -1, [1, 2, 3, 4, 5])
[2, 3, 4]

> R.slice(1, -1)([1, 2, 3, 4, 5])
[2, 3, 4]
davidchambers
  • 23,918
  • 16
  • 76
  • 105
3

Ramda has the function init, which "returns all but the last element of the given list or string." So

 R.compose(R.init, R.tail)([1, 2, 3, 4, 5]); //=> [2, 3, 4]

You can see this on the Ramda REPL

Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103
1

How about

innerVals = R.compose(
    R.drop(1),
    R.dropLast(1));

console.log(innerVals([1,2,3,4,5])) // [2,3,4]

or simply slice:

innerVals = R.slice(1, -1)
georg
  • 211,518
  • 52
  • 313
  • 390
  • Neat solution. If slice was used, how would you supply its second parameter with length - 1 without storing it as a variable? This is what I was trying to replicate using converge, which worked. It just seemed clunky to me. – wpcarro Mar 10 '16 at 20:15
  • 3
    @wcarroll: `innerVals = R.slice(1, -1)` – georg Mar 10 '16 at 20:18
  • I totally forgot about negative indexes. This is too simple. Love it. Thanks, @georg – wpcarro Mar 10 '16 at 20:20