Day 1/30 Days of CodeWars: JavaScript Edition
Tags: javascript, tutorial, codewars, challenge
Published: 2022-05-30 08:25:52

**CodeWars challenges solved**
1) [Sum of positive (8 kyu)](https://www.codewars.com/kata/5715eaedb436cf5606000381/train/javascript)
2) [Counting sheep (8 kyu)](https://www.codewars.com/kata/54edbc7200b811e956000556/train/javascript)
3) [Keep up the hoop (8 kyu)](https://www.codewars.com/kata/55cb632c1a5d7b3ad0000145/train/javascript)

---

## Kata 1: Sum of positive

### Instructions
You get an array of numbers, return the sum of all of the positives ones. Note: if there is nothing to sum, the sum is default to 0.

<u>Examples</u>

```
[1,-4,7,12] => 1 + 7 + 12 = 20
[] => 0
```

---

### Breaking down the problem with P.R.E.P.

<u>Parameters</u>
The function expects one parameter: an array of numbers. 

```
The given array of numbers can ...
1) be empty 
2) contain only positive numbers 
3) contain only negative numbers 
4) contain a combination of both 
```

<u>Returns</u>
The function should return one value: a number. 

```
The function should return 0 if ...
1) the array is empty
2) the array only contains negative numbers
```

```
The function should return a positive number if 
there is at least 1 positive number inside the array
```

<u>Examples</u>
The following test cases are provided by CodeWars.

```
[1,2,3,4,5], 15
[1,-2,3,4,5], 13
[], 0
[-1,-2,-3,-4,-5],0
[-1,2,3,4,-5], 9
```
_The number following the array is the value/sum that should be returned._

<u>Pseudo code</u>
_See pseudo code section for each solution_

---

### Solution 1: Using a for loop

<u>Pseudo code</u>
```
1) Declare a 'sum' variable.
2) Loop over the given array.
3) Check if the current number in the loop is positive.
4) If it is, add that number to the current value of 'sum'.
5) Return the 'sum' variable
```

<u>JavaScript code</u>

```
function positiveSum(arr) {
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > 0) {
      sum += arr[i];
    }
  }
  return sum;
}
```

<u>Notes</u>

1) The sum variable is declared with a default value of 0 to ensure that it returns 0 if the array is empty or does not contain any positive numbers.

2) The loop starts at index 0 instead of 1 - just like an array - and continues to loop as long as the loop index is smaller than the array length to ensure no off-by-one errors occur.

3) The [bracket notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#access_an_array_item_by_its_index) - `arr[1]` - is used to select the element in the array at the current loop index (so if the loop is at index 0, it selects the element in the array at index 0, meaning the first item in the array).

4) The `+=` operator is an [addition assignment operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Addition_assignment) and is shorthand for `variable = variable + value` (in this case `sum = sum + arr[i]`). 

---

### Solution 2: Using the filter() and reduce() array methods

<u>Pseudo code</u>
```
1) Create a new array containing only positive numbers.
2) Loop over the new array.
3) Sum up all values in the new array.
4) Return the 'sum' variable.
```

<u>JavaScript code</u>

```
function positiveSum(arr) {
  return arr.filter(num => num > 0)                   
            .reduce((sum, curr) => sum + curr, 0);     
}
```

<u>Notes</u>

1) Both the [filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) and [reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) array methods are used to loop over arrays and receive a callback function as its parameter.

2) The filter() callback function tests each element for a specified condition (like the if statement in solution 1) and the method creates a new array with all the elements that passed that test.

3) The reduce() method returns a single value. The callback function specifies a calculation (like adding or subtracting) or action (like concatenation) to perform on each element, followed by an initial value (in this case `0`). Each iteration, the previous (or initial) value of that calculation/action is passed to the current iteration until a single value remains.

4) Both of these methods do not make any changes to the original array.

---


> _This is the solution I submitted for this challenge. In my  opinion, it is an elegant solution that doesn't require a lot of code, but is still much easier to read and understand than the next solution._

---

### Solution 3: Using the reduce() array method only
_This implementation combines the approaches of solution 1 and solution 2 into a single line of code inside the function, though it was spread over 2 lines in this article to avoid having a horizontal scroll bar in the code block below._

<u>JavaScript code</u>

```
function positiveSum(arr) {
  return arr.reduce((sum, curr) => 
    curr > 0 ? sum + curr : sum, 0);  
}
```

<u>Notes</u>

1) Similar to solution 1, we loop over all the elements in the given array, except using the reduce() array method instead of a for loop.

2) The if statement from solution 1 is replaced by a [conditional ternary operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) to check if the number is positive. If it is, it should return the value of the sum and add the current number to it. If it isn't a positive number, it should just return the  value of the sum for that iteration.

---

## Kata 2: Counting sheep

### Instructions
Consider an array/list of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present).

<u>Example</u>

```
[true,  true,  true,  false,
  true,  true,  true,  true ,
  true,  false, true,  false,
  true,  false, false, true ,
  true,  true,  true,  true ,
  false, false, true,  true]
```

The correct answer would be `17`.

Hint: Don't forget to check for bad values like `null`/`undefined`

---

### Breaking down the problem with P.R.E.P.

<u>Parameters</u>
The function expects one parameter: an array of values. 

```
The given array of numbers can ...
1) be empty 
2) contain only true values
3) contain only falsy values (like false, null, undefined)
4) contain a combination of both 
```

<u>Returns</u>
The function should return one value: a number. 

```
The function should return 0 if ...
1) the array is empty
2) the array only contains falsy values
```

```
The function should return a positive number if 
there is at least 1 sheep present (true) inside the array
```

<u>Examples</u>
_The test case in this challenge is the same as the example given in the instructions above._

<u>Pseudo code</u>
_See pseudo code section for each solution_

---

### Solution 1: Using a for loop
_This problem is fairly similar to the problem in kata 1 and will have a similar solution, except for a few minor tweaks._

<u>Pseudo code</u>
```
1) Declare a 'count' variable.
2) Loop over the given array.
3) Check if the current value in the loop is TRUE.
4) If it is, add 1 to the current value of 'count'.
5) Return the 'count' variable
```

<u>JavaScript code</u>

```
function countSheeps(arrayOfSheep) {
  let count = 0;
  for (let i = 0; i < arrayOfSheep.length; i++) {
    if (arrayOfSheep[i]) {
      count++;
    }
  }
  return count;
}
```

<u>Notes</u>

1) Often times, code newbies will write `if (condition === true)`, which isn't inherently wrong, but is in fact unnecessary. In this case `arrayOfSheep[i]` will evaluate to `true` if the value is `true` (or [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy)) and to `false` if the value is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy).
 
2) The [increment operator (++)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment) is used to add 1 to our counter of sheep present.

---

### Solution 2: Using a forEach loop
_The code from solution 1 can reduced to just 3 lines inside of the function using a forEach loop instead of a for loop and combining it with the conditional ternary operator seen in solution 3 of kata 1._

<u>JavaScript code</u>

```
function countSheeps(arrayOfSheep) {
  let count = 0;
  arrayOfSheep.forEach(sheep => sheep ? count++ : count);
  return count;
}
```

<u>Notes</u>

1) The [forEach loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) executes the code specified in the callback function on each element in the array. 

2) Unlike the filter() and reduce() array methods, the forEach() array method returns `undefined`, unless something is explicitly returned inside the callback function. 

3) The forEach loop is a great alternative to a for loop when looping over an array. It is less prone to off-by-one mistakes since it simply loops over every item in the array without us having to define the amount of times it should iterate like we do in a for loop.

---

### Solution 3: Using the filter() array method and length property

<u>Pseudo code</u>
```
1) Create a new array containing only TRUE values.
2) Return the length of that array.
```

<u>JavaScript code</u>

```
function countSheeps(arrayOfSheep) {
  return arrayOfSheep.filter(sheep => sheep).length;
}
```

<u>Notes</u>

1) Like kata 1, we use the filter() array method to create a new array, this time containing only the values of the sheep that are present in the array.

2) Then we simply use the [length](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length) property to count the number of values in the newly created array.

---

> _This is the solution I submitted for this kata. It is only 1 line of code, but is still easy to read and understand._
 
---

## Kata 3: Keep up the hoop

### Instructions
Alex just got a new hula hoop, he loves it but feels discouraged because his little brother is better than him.

Write a program where Alex can input (n) how many times the hoop goes round and it will return him an encouraging message :)

- If Alex gets 10 or more hoops, return the string "Great, now move on to tricks".
- If he doesn't get 10 hoops, return the string "Keep at it until you get it".

---

### Breaking down the problem with P.R.E.P.

<u>Parameters</u>
The function expects one parameter: a number. 

```
The number can be 0 or greater than 0, but should not be a
negative number.
```

<u>Returns</u>
The function should return one value: a string (message). 

```
The function should return "Great, now move on to tricks" if
the number is greater than or equal to 10.
```

```
The function should return "Keep at it until you get it" if
the number is smaller than 10.
```

<u>Examples</u>
The following test cases are provided by CodeWars.

```
3 => "Keep at it until you get it" 
11 => "Great, now move on to tricks" 
```

<u>Pseudo code</u>
_No pseudo code for this solution since it's been pretty much provided in the parameters and returns sections above._

---

### Solution 1: Using an if/else statement


```
function hoopCount (n) {
  if (n >= 10) {
    return "Great, now move on to tricks";
  } else {
    return "Keep at it until you get it";
  }
}
```

---

### Solution 2: Using a conditional ternary operator

```
function hoopCount (n) {
  return n >= 10 
    ? "Great, now move on to tricks" 
    : "Keep at it until you get it";
}
```

<u>Notes</u>

It is not uncommon to see the code inside conditional ternary operators broken up into multiple lines like the code block above. This helps with legibility since the condition is one 1 line, followed by the code to be executed if it evaluates to true and lastly the code to be executed it evaluates to false.

---

> _This is the solution I submitted for this challenge. I'm personally a big fan of ternary operators. I know some people find them hard to read, but for me, they're often easier to read then if/else statements (unless you have a lot of statements and/or they are nested)._

---

### Solution 3: Adding error handlers
_The first 2 solutions don't execute any code if the input given is invalid (a negative number or not a number at all). This was not a requirement to pass the test cases in the challenge, but a nice added extra._

```
function hoopCount (n) {
  if (n >= 10) {
    return "Great, now move on to tricks";
  } else if (n < 10 && n >= 0) {
    return "Keep at it until you get it";
  } else {
    return "Invalid input"
  }
}
```

---

**What solution did you implement?** 
**What solution did you find the most elegant?**
**What solution did you have trouble understanding?**

**Let me know, I'd love to hear from you!**

**I hope you found this article helpful.**

---

Connect with me on ...
[Twitter](https://twitter.com/Nat_A_Number)
[GitHub](https://github.com/NatGeyzenTech)