rules-machine icon indicating copy to clipboard operation
rules-machine copied to clipboard

Input mutation

Open chhatch opened this issue 2 years ago • 3 comments

When a rule set is executed on an object that object gets mutated.

const fishRhyme = ruleFactory([
  { if: 'fish == "oneFish"', then: 'fish = "twoFish"' },
  { if: 'fish == "redFish"', then: 'fish = "blueFish"' },
]);
const fish = { fish: "oneFish" };
fishRhyme(fish); 
console.log(fish);
// { fish: 'twoFish' }

I found // input = cloneDeep(input); at index.ts:49, so it looks like Lodash was being used to deep clone the input object.

chhatch avatar May 05 '22 14:05 chhatch

My initial benchmarks suffered greatly if cloneDeep was the default. I figured I could leave it up to the caller/user? Should there be a warning in the function's JSDoc?

justsml avatar May 24 '22 04:05 justsml

I think that's a fine solution as long as it's clear in the docs.

chhatch avatar May 24 '22 12:05 chhatch

There's a few possible options around this that I want to consider:

  1. Ticket #27 is an indirect way to mitigate.
  2. The diff ticket #22 will likely need to snapshot/freeze the object anyway to track changes (using the proposed method.)
  3. More complex/efficient approach: use ES6 Proxy class/objects to observe changes, however that might require re-writing several built-in methods to align with that.
  4. Pre-scan the rule to know what change to expect (based on variable assignment); and only compare changes on a limited subset of the object/value.

justsml avatar Jul 15 '22 23:07 justsml