How to conditionally check if object value isset or equals smth and track change?

Viewed 60

I don't know how to make this code shorter, there are many other values I need to check and track change, so the code gets big and complicated

doc.name = doc.name === offer.title
  ? doc.name
  : () => {
      shouldUpdate = true ;
      return offer.title
  };

doc.uri = doc.uri
  ? doc.uri
  : () => {
    shouldUpdate = true;
    return encodeURI(offer.title)
  };

doc.info = doc.info
  ? doc.info
  : () => {
    shouldUpdate = true;
    return {
      activation: offer.activation,
      image: offer.image
    };
  };
4 Answers

For doc.uri and doc.infom you could use either the value it self, or a function.

doc.uri = doc.uri
    || () => {
        shouldUpdate = true;
        return encodeURI(offer.title)
    };

doc.info = doc.info
    || () => {
        shouldUpdate = true;
        return {
            activation: offer.activation,
            image: offer.image
        };
    };

You can use Short-circuit operators to transform doc.uri and doc.info assignments to:

doc.uri = doc.uri || () => {shouldUpdate = true; return encodeURI(offer.title)};
doc.info = doc.info || () => {shouldUpdate = true; return {
    activation: offer.activation,
    image: offer.image
}};

This function will compare all properties in those two objects of the same type. In the function takeAction it will take a proper action. Probably could be done better but I find it more readable.

let a = { name : 'same', uri: 'samee', info: 'not same'};
const b = { name : 'same', uri: 'samee', info: 'same'};
areSame(a,b);
console.log(a, b);

function areSame(a,b){
  const aKeys = Object.keys(a);
  for(let key of aKeys){
    if(a[key] !== b[key]){
      // shouldUpdate = true;
      takeAction(a,b, key)
    } 
  }
}

function takeAction(a,b, key){
  switch(key){
    case "name": {
      a.name = b.name;
      document.write('name action taken');
      break;
    }
    case "uri": {
      // parse uri
      a.uri = b.uri;
      document.write('uri action taken');
      break;
    }
      
    case "info": {
        // activation: offer.activation,
        // image: offer.image
      document.write('info action taken');
      break;
    }
  }
}

You can make it even worse and use commas, look!

doc.name = doc.name === offer.title ? doc.name : (shouldUpdate = true, offer.title);
doc.uri = doc.uri || (shouldUpdate = true, encodeURI(offer.title));
doc.info = doc.info || (shouldUpdate = true, {
      activation: offer.activation,
      image: offer.image
});
Related