javascript - Create a factory function that returns an object with immutable state -


link codepen https://codepen.io/jaspercreel/pen/mvaodp

basically, function this:

const factory = (args) => {    const state = {     args   }    const methods = {        getstate() => {       return args;     },      setstate(args) => {       state.args = args;     },      dostuffwithstate() => {       let args = this.getstate();       function(args) {         return args plus else;       }();     }    }    return object.assign({}, methods);  } 

the problem whenever call dostuffwithstate() changes state object. thought safe creating new variable returned state, learned when referencing object creating new reference. question this, how can create immutable state can referenced not changed (except helper functions) in factory function?

my end goal create sorter factory function create object takes arrays , sorts , searches them in different ways. want able store default array in sorter can referenced return different sorting options not changed. advice?

one approach store javascript object json string json.stringify() , use json.parse() parse json string javascript object, not reference original object passed stored string.

you can utilize promise return javascript object reflecting properties of json string, passed object.assign(), can return modified properties or values of original object, without affecting original object passed factory, returns promise value json string format of original passed object.

// `const` declaration cannot changed or deleted  const factory = (args) => promise.resolve(json.stringify(args));    const state = factory({    abc: [1, 2, 3]  });    state.then(data => console.log(data)); // `{"abc":[1,2,3]}`    // change object passed `factory`  state.then(data => object.assign(json.parse(data), {      abc: json.parse(data).abc.concat(4, 5, 6)  }))  // stuff modified `json` `args` javascript object  .then(res => {console.log(res); return res}) // `{"abc":[1,2,3,4,5,6]}`  .then(res =>    // `res` : `{"abc":[1,2,3,4,5,6]}`    // `state` `promise` value original object     // valid `json` `{"abc":[1,2,3]}`    // return original `args` `json` string    state.then(data => {console.log(res, data); return data})  )  // original `args` javascript object  .then(o => console.log(json.parse(o)))


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -