javascriptnanobject-notation

How do I increment and decrement values in an object using JavaScript Classes?


I am trying to do a simple Backpack class to review objects with vanilla javascript. While doing so, I've run into a block because I am unable to create a proper AddItem method or get my decrementItem method to work either.

My code is below:

class Backpack {
  constructor(name) {
    this.name = name;
    this.items = {};
  }

  name() {
    return `My backpack's name is ${this.name}`;
  }

  addItem(i, value) {
    return this.items[i] ? (this.items[i] += value) : (this.items[i] = 1);
  }

  decrementItem(i) {
    if (this.items[i]) {
    }
    return this.items[i] ? this.items[i]-- : (this.items[i] = 0);
  }
}

let newBackpack = new Backpack("Bacon");

newBackpack.addItem("pencil", 3);
newBackpack.addItem("book");
newBackpack.addItem("pen");
newBackpack.addItem("paper");

console.log(newBackpack.items);

I am also curious as to how I could add validation to my decrementItem method to check to see if a value doesn't go negative as that would cause some issues.


Solution

  • You could add these changes:

    class Backpack {
      constructor(name) {
        this.name = name;
        this.items = {};
      }
    
      name() {
        return `My backpack's name is ${this.name}`;
      }
    
      addItem(item, value = 1) { // 1 by default if not provided
        return this.items[item] = (this.items[item] || 0) + value; // Add the value
      }
    
      decrementItem(item) {
        return this.items[item] = Math.max((this.items[item] || 0) - 1, 0); // 0 minimum
      }
    }
    
    let newBackpack = new Backpack("Bacon");
    
    newBackpack.addItem("pencil", 3);
    newBackpack.decrementItem("pencil");
    newBackpack.addItem("book");
    newBackpack.addItem("pen");
    newBackpack.addItem("paper");
    
    console.log(newBackpack.items);