0

I have some objects:

var a = {
   toString: () => 'a'
}
var b = {
   toString: () => 'b'
}

function someFunc(...params) {
    params.forEach((p)=>{
        console.log(p);   //consoles - {toString: ƒ toString()} for both objects
   })
 }

someFunc(a,b);

I want to pass these objects to some functions like memoize function, isEqual function, deepCopy function etc. I don't want to use any third party library such as lodash. I want to understand how do we differentiate between these objects inside someFunc? I have tried : JSON.parse(JSON.stringify()) but this doesn't work in case of objects having functions. Codesandbox

Edit: I have tried Implementing the object refrence method.

function someFunc() {
  let cache = {};
  return function (...params) {
    var ObjectReference = [];
    let set = {};
    params.forEach((p) => {
      ObjectReference.push(p);
      set["ObjectReference." + ObjectReference.indexOf(p)+p] =     true;
    });
    let key = JSON.parse(JSON.stringify(set))
    console.log(key);
    if (cache[key]) {
      console.log("cached");
    } else {
      cache[key] = true;
      console.log("Not cached");
        }
     };
  }

mem(a, b); //not cached
mem(b, a);  //cached - should be **not cached**

console.log(key); gives:

  1. {ObjectReference.0a: true, ObjectReference.1b: true}
  2. {ObjectReference.0b: true, ObjectReference.1a: true} As we can see the two objects are different. I'm unable to understand why it goes inside cached block?

Edit 2 : The above is happening because the key is getting set as [object object]. To avoid this I tried using Map and WeakMap but they are failing for

    mem(a, b); //not cached
    mem(a, b); // not cached
era s'q
  • 537
  • 1
  • 7
  • 27

0 Answers0