DEV Community

Nat's Tech Notes
Nat's Tech Notes

Posted on

Day 1/30 Days of CodeWars: JavaScript Edition

CodeWars challenges solved
1) Sum of positive (8 kyu)
2) Counting sheep (8 kyu)
3) Keep up the hoop (8 kyu)


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.

Examples

[1,-4,7,12] => 1 + 7 + 12 = 20
[] => 0
Enter fullscreen mode Exit fullscreen mode

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

Parameters
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 
Enter fullscreen mode Exit fullscreen mode

Returns
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
Enter fullscreen mode Exit fullscreen mode
The function should return a positive number if 
there is at least 1 positive number inside the array
Enter fullscreen mode Exit fullscreen mode

Examples
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
Enter fullscreen mode Exit fullscreen mode

The number following the array is the value/sum that should be returned.

Pseudo code
See pseudo code section for each solution


Solution 1: Using a for loop

Pseudo code

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
Enter fullscreen mode Exit fullscreen mode

JavaScript code

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

Notes

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 - 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 and is shorthand for variable = variable + value (in this case sum = sum + arr[i]).


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

Pseudo code

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.
Enter fullscreen mode Exit fullscreen mode

JavaScript code

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

Notes

1) Both the filter() and 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.

JavaScript code

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

Notes

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 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).

Example

[true,  true,  true,  false,
  true,  true,  true,  true ,
  true,  false, true,  false,
  true,  false, false, true ,
  true,  true,  true,  true ,
  false, false, true,  true]
Enter fullscreen mode Exit fullscreen mode

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.

Parameters
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 
Enter fullscreen mode Exit fullscreen mode

Returns
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
Enter fullscreen mode Exit fullscreen mode
The function should return a positive number if 
there is at least 1 sheep present (true) inside the array
Enter fullscreen mode Exit fullscreen mode

Examples
The test case in this challenge is the same as the example given in the instructions above.

Pseudo code
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.

Pseudo code

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
Enter fullscreen mode Exit fullscreen mode

JavaScript code

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

Notes

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) and to false if the value is falsy.

2) The increment operator (++) 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.

JavaScript code

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

Notes

1) The forEach loop 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

Pseudo code

1) Create a new array containing only TRUE values.
2) Return the length of that array.
Enter fullscreen mode Exit fullscreen mode

JavaScript code

function countSheeps(arrayOfSheep) {
  return arrayOfSheep.filter(sheep => sheep).length;
}
Enter fullscreen mode Exit fullscreen mode

Notes

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 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.

Parameters
The function expects one parameter: a number.

The number can be 0 or greater than 0, but should not be a
negative number.
Enter fullscreen mode Exit fullscreen mode

Returns
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.
Enter fullscreen mode Exit fullscreen mode
The function should return "Keep at it until you get it" if
the number is smaller than 10.
Enter fullscreen mode Exit fullscreen mode

Examples
The following test cases are provided by CodeWars.

3 => "Keep at it until you get it" 
11 => "Great, now move on to tricks" 
Enter fullscreen mode Exit fullscreen mode

Pseudo code
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";
  }
}
Enter fullscreen mode Exit fullscreen mode

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";
}
Enter fullscreen mode Exit fullscreen mode

Notes

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"
  }
}
Enter fullscreen mode Exit fullscreen mode

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
GitHub

Top comments (4)

Collapse
 
zerodragon profile image
Zero Dragon

I'd use just a short circuit for the third exercice.
Also the initial parameters does not make account for invalid inputs, but for what is worth, adding error handling is just a couple of lines.

Collapse
 
nats_tech_notes profile image
Nat's Tech Notes

Oh I like that solution! Especially how you write your if/else if statements in 1 line instead of adding the {} and then writing the code block on the next line. Very elegant.

And yeah, I did mention in the third solution of that kata that the first 2 solutions don't really account for error handling/invalid input, which is why I added the third solution. The error handling wasn't actually required to pass the CodeWars test, but I did want to at least mention it in one of the solutions!

Collapse
 
andrewbaisden profile image
Andrew Baisden

Add some syntax highlighting to the markdown code blocks this article will become more readable for users that way.

Collapse
 
nats_tech_notes profile image
Nat's Tech Notes

Good point! I'll add this to my posts from now on.