Return number of hashes and plus sigs in JavaScript string

Viewed 258

I'm working through some JS problems over at edabit and am having some issues with this one. The task asks us to create a function that returns the number of hashes and pluses in a string and return the answer in an array. It returns [0,0] if given an empty string. Examples below.

hashPlusCount("###+") ➞ [3, 1]

hashPlusCount("##+++#") ➞ [3, 3]

hashPlusCount("#+++#+#++#") ➞ [4, 6]

hashPlusCount("") ➞ [0, 0]

Here is the code I came up with using regex.

const hashPlusCount = str =>  
str === "" ? [0,0] :

[str.match(/\#/gi).length,
str.match(/\+/gi).length];

The code works fine on repl.it and outside editors. It even works on the code playground on edabit itself! But on the challenge page, it is returning " Cannot read property 'length' of null at hashPlusCount".

Any help in resolving this and helping me understand what's going on is appreciated.

3 Answers

You need to move the empty search inside of the returning array.

const hashPlusCount = str => [
    (str.match(/\#/gi) || '').length,
    (str.match(/\+/gi) || '').length
];

Another approach is to convert the string into array using Array.from().The Array.from() static method creates a new, shallow-copied Array instance from an array-like or iterable object.

Then, create variables numberofDash and numberofPlush to count number of dash and plus.After that using forEach(), to count the number of dash and plus.

function hashPlusCount(str) {
  let numberofDash = 0,
    numberofPlus = 0;
  Array.from(str).forEach(function (ch) {
    if (ch === "#") {
      numberofDash++;
    }
    if (ch === "+") {
      numberofPlus++;
    }
  });
  return [numberofDash, numberofPlus];
}

console.log(hashPlusCount("###+"));

console.log(hashPlusCount("##+++#"));

console.log(hashPlusCount("#+++#+#++#"));

console.log(hashPlusCount(""));

function hashPlusCount(str) {
    let newstr = str.split('+').join('').length;
    //return newstr;
    let newstr1 = str.split('#').join('').length;
   // return newstr1;
    return [newstr, newstr1]
}
console.log(hashPlusCount("+++++++"))

Output - [ 0, 7 ]

Related