Home > Software design >  Extending usage of set to have multiple indeces
Extending usage of set to have multiple indeces

Time:11-25

I'm trying to figure out how I can extend my usage of set and has so that I can add other indexes to the set.

Currently, I'm creating a set of identifiers from an existing object which works just fine, but I'd also like to add the other indexes in the set if possible so that I can check first to see if the set has the identifier I'm looking for, and then if so, i can do a comparison on the quantity (and eventually other indexes too)

Is there a way to extend this approach to add the other index(es) to the set and still use has in a performant way? If not, what would be a better approach to achieve what I want here?

const testFunc = (rows) => {
  let itemSet = new Set(vm.$data.categoryItems.map((category) => category.category_identifier))

  category_ID = 1234;

  if (itemSet.has(category_ID)) {

    qty = 10;

    if(qty > itemSet.cagegory_qty){
      console.log('good')
    }
  }
}

var vm = 
new Vue({

  data: {
    parsedResults: [],
    categoryItems:[
      {
          category_identifier:1234,
          category_qty:50,
          available_date:"2021-11-02",
      },
      {
          category_identifier:2345,
          category_qty:15,
          available_date:"2021-11-02",
      },
      {
          category_identifier:3456,
          category_qty:25,
          available_date:"2021-11-02",
      },
      {
          category_identifier:6533,
          category_qty:2,
          available_date:"2021-11-02",
      }
    ]
  },
  computed: {
    getTestSet() {
      setRows = testFunc(this.rows)
      this.parsedResults = setRows
      return this.parsedResults
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can use a Map instead where the key is the identifier and the value can be the object if you want to use multiple attributes in it:

const itemMap = new Map(
  vm.$data.categoryItems.map(category => [category.category_identifier, {...category}])
)

To check if the Map has a certain key, you can use Map#has.

To get an attribute of a certain object by the identifier, you can use Map#get.

if (itemMap.has(category_ID)) {
  const qty = 10;
  if(qty > itemMap.get(category_ID).category_qty){
    console.log('good')
  }
}
  • Related