0

I have created, or am creating, a function that will take an array with arbitrary values, and return an object of the format {array_value1: count2, array_value2: count2, ...}.

Is it possible to override or extend the default get attribute of the object, such that I can return a value or run a function when another piece of code accesses a key that does not exist within the object? Eg. if someone tries to access return_object[key_does_not_exist], can I modify the getter such that the object does not return a value of null, but rather returns 0?

I know you can cetainly modify the getter, but it doesn't seem there is the ability to modify what happens when a non-existent property is accessed -- I know Ruby has this ability (and it is IIRC fairly widely used). Is there a way to do this that I haven't found?

Specific problem below

Task: count a number of tickets contained in an array of the following form,

const tickets = [
  'red',
  'red',
  'green',
  'blue',
  'green'
]

and return the count in the following format:

{
  red: 2,
  green: 2,
  blue: 1
}

The function I have thus far:

const countTickets = (tickets) => {

  let ret_obj = {};

  // I did not include this initially, which I think should be fine
  ret_obj["red"] = 0
  ret_obj["green"] = 0
  ret_obj["blue"] = 0

  for (let ticket of tickets) {
    if (ret_obj.hasOwnProperty(ticket)) {
      ret_obj[ticket] += 1;
    } else {
      ret_obj[ticket] = 1;
    }
  }
  return ret_obj;
}
NotAnAmbiTurner
  • 2,553
  • 2
  • 21
  • 44
  • 1
    For the first part of the question: possible, with a Proxy, but best to avoid those when possible. For the second part, use `ret_obj[ticket] = (ret_object[ticket] || 0) + 1;` – CertainPerformance Nov 18 '19 at 08:44
  • 1
    [Set default value of javascript object attributes](https://stackoverflow.com/questions/6600868) – adiga Nov 18 '19 at 08:52

0 Answers0