I'll-Be-Back
I'll-Be-Back

Reputation: 10828

Reduce the number of loop or code readability issues

The code is working as expected but is there a way to reduce the number of loops or improve the readability of this code to ES6/ES7 way? As you can see I am repeating the number of .split and .join

It will convert Total.Subtotal": "10.50 into an array with the fields names and update string.

  {
    "Update": "+Total.+Subtotal = val:TotalSubtotal",
    "Field": {
      "+Total": "Total",
      "+Subtotal": "Subtotal"
    },
    "Value": {
      "val:TotalSubtotal": "10.50"
    }
  }

function createMap(val) {
    const maps = [];

    Object.keys(val).forEach(entry => {
      const param = entry.split('.').join('');
      const names = {};

      for(const name of entry.split('.')) {
        names[`+${name}`] = name;
      }

      const setName = Object.keys(names).join(".");

      maps.push({
        Update: `${setName} = val:${param}`,
        Field: names,
        Value: { [`val:${param}`]: val[entry] },
      });
    });

    return maps;
  }


  console.log(
    createMap({
        "Total.Subtotal": "10.50"
    })
  )

Upvotes: 0

Views: 103

Answers (1)

Freddy
Freddy

Reputation: 1229

A couple of ideas:

  1. Move any repeated logic up earlier into the function and reuse, this means you are only computing once.
  2. Try using array methods like map and reduce, which will avoid you having to write weird for loops etc

function createMap(val) {
  return Object.keys(val).map(entry => {
    const splitValues = entry.split('.');
    const param = splitValues.join('');
    const names = splitValues.reduce((obj, currentValue) => {
      return { ...obj, [`+${currentValue}`]: currentValue };
    }, {});

    const setName = Object.keys(names).join('.');

    return {
      Update: `${setName} = val:${param}`,
      Field: names,
      Value: { [`val:${param}`]: val[entry] }
    };
  });
}

console.log(
  createMap({
    'Total.Subtotal': '10.50'
  })
);

Upvotes: 1

Related Questions