Search code examples
javascriptfunctional-programmingjavascript-objects

If objects are passed by reference how do I handle them in functional programming


I have been playing with some code over the last few days and I am trying to get more into functional programming but I am at a road block. I don't understand how to handle an object. Essentially I have an object that I want to add key value pairs to. I understand in function programming you don't reassign you just make a new object with the added key value pair. I was thinking about putting the object in some type of container like 'Box'

const Box = x =>
({
  map: f => Box(f(x)),
  fold: f => f(x),
})

And then using the 'Box' and adding all my key value pairs, something like

const formData = obj =>
  Box(obj)
  .map(s => s.key1 = document.getElementById("value1").value)
  .map(s => s.key2 = document.getElementById("value2").value)
  .fold(s => s)

var emptyObj = {};
const test = formData(emptyObj);

I noticed that 'emptyObj' will have both key value pairs but 'test' will not. I know that I am either completely missing it or just not understanding the process. I have been watching

https://egghead.io/courses/professor-frisby-introduces-composable-functional-javascript

and it is great along with the ebook but there must be something that I am missing. Any help would be greatly appreciated.


Solution

  • I think you need to do something like this:

    const formData = obj =>
      Box(obj)
       .map(s => ({ ...s, key: document.getElementById("value1").value }) )
       .map(s => ({ ...s, key2: document.getElementById("value2").value } )) 
       .fold(s => s)
    

    Note that I would not have used map and fold rather monadic names then and bind.