-1

I'm trying to learn functional javascript with Ramda and I'm stuck with this. Here is the JS Bin: http://jsbin.com/kozeka/

And this is the code:

const date = new Date()
const addDays = R.add(date.getDate())
const getDate = R.compose(date.setDate, addDays)

console.log(date.setDate(date.getDate() + 6)) //Works
console.log(date.setDate(R.add(date.getDate(), 6))) // Works
console.log(date.setDate(addDays(6))) //Works
console.log(getDate(6)) //Doesn't Work

But I got this error. What I'm doing wrong?

"TypeError: Method Date.prototype.setDate called on incompatible receiver undefined
    at setDate (<anonymous>)
    at http://cdnjs.cloudflare.com/ajax/libs/ramda/0.22.1/ramda.min.js:6:3064
    at http://cdnjs.cloudflare.com/ajax/libs/ramda/0.22.1/ramda.min.js:6:182
    at kozeka.js:10:38"
KadoBOT
  • 2,944
  • 4
  • 16
  • 34
  • So where does the functional programming come in ? – Mulan Dec 07 '16 at 02:56
  • @naomik: Ramda is "A practical functional library for Javascript programmers"; `R.compose(date.setDate, addDays)` is functional programming. – Amadan Dec 07 '16 at 04:41
  • @Amadan functional programming is more than just using Ramda or a function composition. – Mulan Dec 07 '16 at 11:51
  • @naomik: So? JavaScript is more than `getElementsByClassName`; do you feel also that "How do I get elements if I have a class name in JavaScript" shouldn't be tagged as [tag:javascript]? – Amadan Dec 07 '16 at 22:40
  • @Amadan that's a bit dramatic. I ask because the code posted here is a huge slurry of oop style, imperative style, referentially opaque functions, and side effects – these go against the grain of functional programming. – Mulan Dec 08 '16 at 19:07

1 Answers1

2

The problem is that the setDate loses the bound date instance when passed as a function.

This can be resolved by explicitly binding the method to the date instance when passing it to compose:

const getDate = R.compose(date.setDate.bind(date), addDays)
Scott Christopher
  • 6,458
  • 23
  • 26