jgrewal
jgrewal

Reputation: 342

incrementing a set if existing

I have a string "abacabad" being passed in to my function as s

What I want to do:

What my code is logging:

Set(0) { a: 1, b: 1, c: 1, d: 1 }

what it should be logging:

Set(0) { a: 4, b: 2, c: 1, d: 1 }


function solution(s) {
  arr = new Set()
  for (e of s) {
    if (e in arr) {
      arr[e]++;
    }
    if (arr.has(e) == false) {
      arr[e] = 1;
    }
  }
  console.log(arr)
}

solution('abacabad');

Upvotes: 1

Views: 442

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 371019

You're conflating two different data structures:

  • Sets, which are collections of values only (eg ('a, 'b', 'c', 'd'), and
  • Objects, which are collections of key-value pairs (eg { a: 1, b: 2 })

Set methods include .has and .add. But Sets are also objects, so you can use standard object property assignment on them as well - but you shouldn't. If you want a Set, use Set methods (and Set methods only) for collecting data on it. Here, you're putting a property directly onto the Set object (with arr[e] =), but you're using the Set method .has, which checks something completely different. .add and has looks at values in the Set's internal data structure (not visible by any mechanism other than other Set methods), and you're never using .add, so your Set never gets any values put into it.

A Set won't work well here anyway, because you want a collection of key-value pairs, not just a collection of values. Use a standard object instead, or a Map.

function solution(s) {
  const obj = {};
  for (const char of s) {
    obj[char] ??= 0;
    obj[char]++;
  }
  console.log(obj);
}

solution('abacabad');

If you wanted a Map:

function solution(s) {
  const map = new Map();
  for (const char of s) {
    map.set(
      char,
      (map.get(char) || 0) + 1
    );
  }
  console.log([...map.entries()]);
}

solution('abacabad');

Upvotes: 1

plalx
plalx

Reputation: 43728

A Set is a collection of unique elements. It's not a Map (key/value) store.

There's tons of issues in that code so I won't enumerate them all, but you simply aren't using the right kind of object and then are mixing APIs, notably defining keys of objects mixed with the actual Set's API.

function solution(s) {
  const countByChar = new Map();
  for (char of s) {
    const count = countByChar.get(char) || 0;
    countByChar.set(char, count + 1);
  }
  return countByChar;
}

const countByChar = solution('abacabad');

console.log(Array.from(countByChar.entries()));

Upvotes: 2

Related Questions