Day 5/30 Days of CodeWars: JavaScript Edition
Tags: javascript, tutorial, codewars, challenge
Published: 2022-07-05 01:14:35

I'm back with more CodeWars katas! I took a break to focus on other things for a while, but now my mind is refreshed and ready to solve some more coding challenges.

---

CodeWars challenges solved
1) [Sum of two lowest positive integers (7 kyu)](https://www.codewars.com/kata/558fc85d8fd1938afb000014/train/javascript)
2) [Ones and Zeros (7 kyu)](https://www.codewars.com/kata/578553c3a1b8d5c40300037c/train/javascript)
3) [Shortest Word (7 kyu)](https://www.codewars.com/kata/57cebe1dc6fdc20c57000ac9/train/javascript)

---

## Kata 1: Sum of two lowest positive integers
### Instructions

Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed.

For example, when an array is passed like `[19, 5, 42, 2, 77]`, the output should be `7`.

`[10, 343445353, 3453445, 3453545353453]` should return `3453455`.

---

### Breaking down the problem with P.R.E.P.
<u>Parameters</u>
The function expects one parameter: an array of 4 or more 
positive integers.

<u>Returns</u>
The function should return one value: the sum of the 2 lowest numbers in the array.

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

```
[5, 8, 12, 19, 22], 13
[15, 28, 4, 2, 43], 6
[3, 87, 45, 12, 7], 1
[23, 71, 33, 82, 1], 24
[52, 76, 14, 12, 4], 16
```
_The array is the parameter passed to the function and the number is the integer that should be returned from the function._

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

---

### Solution 1: Sorting the array

<u>Pseudo code</u>
```
1) Create a new array with sorted numbers from smallest to largest.
2) Return the sum of the first two numbers in the array.
```

<u>Solution</u>
```javascript
function sumTwoSmallestNumbers(numbers) {  
  const sortedNums = numbers.sort((a, b) => a - b);
  return sortedNums[0] + sortedNums[1];
}
```

**_Notes_**

The [`.sort()` array method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) - as the name suggests - sorts the elements of the array and returns the sorted array. It can receive an optional comparison function - like in the solution above - to sort the array in a specific manner. In this solution, passing it the comparison function of `a - b` will sort the numbers from lowest value to highest value.

---

### Solution 2: Using array destructuring

_This solution is similar to the one above but uses a different method of selecting the numbers inside the array called [array destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment). When working with arrays, it can be a very useful method to work with the elements inside the array._

```javascript
function sumTwoSmallestNumbers(numbers) {  
  const [a, b] = numbers.sort((a, b) => a - b);
  return a + b;
}
```

**_Notes_**

Instead of declaring a variable storing the complete sorted array, a new array is declared holding only two values: `a` and `b`, which will automatically hold the values of the first two numbers in the sorted array.

---

### Solution 3: One-liner

_The following solution combines the two lines of code from solution 1 into a single line of code._

```javascript
function sumTwoSmallestNumbers(numbers) {  
  return numbers.sort((a, b) => a - b)[0] + numbers[1];
}
```

**_Notes_**

The `.sort()` array method does not actually make a copy of the array but mutates the original array. So instead of storing the sorted array in a new variable like in solution 1, the elements can be selected directly from the array passed to the argument once it has been sorted.

---

## Kata 2: Ones and Zeros
### Instructions

Given an array of ones and zeroes, convert the equivalent binary value to an integer.

Eg: `[0, 0, 0, 1]` is treated as `0001` which is the binary representation of `1`.

Examples:

```
Testing: [0, 0, 0, 1] ==> 1
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 0, 1] ==> 5
Testing: [1, 0, 0, 1] ==> 9
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 1, 0] ==> 6
Testing: [1, 1, 1, 1] ==> 15
Testing: [1, 0, 1, 1] ==> 11
```

However, the arrays can have varying lengths, not just limited to `4`.

---

### Breaking down the problem with P.R.E.P.
<u>Parameters</u>
The function expects one parameter: an array of ones and zeroes of any given length.

<u>Returns</u>
The function should return one value: the integer representation of the binary inside the array.

<u>Examples</u>
_All test cases provided can be found in the instructions._

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

---

### Solution 1: Parsing a binary string

<u>Pseudo code</u>

```
1) Convert array to string.
2) Convert the string to an integer by parsing it.
3) Return the integer.
```

<u>Solution</u>

```javascript
const binaryArrayToNumber = arr => parseInt(arr.join(''), 2);
```

**_Notes_**

1) Unlike the solutions from kata 1, all the solutions in this kata use the ES6 [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) syntax. 

2) The [`.join()` array method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) is used to convert the array into a string. It concatenates the array elements into a string using either commas to separate the array values inside the string (default) or by using the separator specified inside the parenthesis. In this case all the numbers are joined together without a comma or any spaces between the numbers. 

3) The [`parseInt()` function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt) receives two parameters: the string to parse and the radix that will be used for parsing - in our case 2 for binary. 

---

### Solution 2: Reducing the value with math 

<u>Pseudo code</u>

```
1) Start with a sum (accumulator) value of 0.
2) Multiple the accumulator by 2 and add 1 each iteration of the loop.
3) Return the accumulated value.
```

<u>Solution</u>

```javascript
const binaryArrayToNumber = arr => {
  return arr.reduce((acc, cur) => acc * 2 + cur, 0);
}
```

**_Notes_**

1) The [`.reduce()` array method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) is used to "loop over" an array, executing a callback function on each element of the array. The callback function has access to both the current element in the array and the previous value, which is an accumulation of all the executed calculations combined (often called the accumulator). This sum or accumulator value can be passed a default value, which is specified after the comma (in this case the default value is `0`).

2) Since the `.()reduce` method essentially loops over each item in the array, it takes more time to execute than the first solution, which has the same execution time regardless of the array length. While the difference in time will be rather small because of how fast execution time is nowadays, it is still something to take into account, especially when dealing with longer arrays. Solutions that can operate in constant time - meaning independent of the array length - are more favorable than solutions that take more time depending on array length.  

---

_No third solution for this kata will be provided. There are technically other ways to solve this challenge, but they are much more difficult to understand and/or have significant downsides, which make them less desirable as a solution._

---
## Kata 3: Shortest Word
### Instructions

Simple, given a string of words, return the length of the shortest word(s).

String will never be empty and you do not need to account for different data types.

---

### Breaking down the problem with P.R.E.P.
<u>Parameters</u>
The function expects one parameter: a string of words.

<u>Returns</u>
The function should return one value: the length of the shortest word in the string.

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

```
("bitcoin take over the world maybe who knows perhaps"), 3
("turns out random test cases are easier than writing basic ones"), 3
("Let's travel abroad shall we"), 2
```
_The string of words between the parenthesis is the string passed to the function, followed by the number that should be returned from the function._

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

---

### Solution 1: Using a for loop

<u>Pseudo code</u>

```
1) Create an array of the words contained in the string.
2) Declare a new variable with a value of the first word's length.
3) Loop over each word in the array. 
4) Check if word's length is smaller than the value of the variable.
5) If it is, set the word's length as the new value of the variable.
6) Return the variable's value.
```

<u>Solution</u>

```javascript
function findShort(s){
  const arr = s.split(' ');
  let shortest = arr[0].length;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].length < shortest) {
      shortest = arr[i].length;
    }
  }
  return shortest;
}
```

**_Notes_**

The [`.split()` array method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) is used to convert the string into an array of words. The string is split into substrings each time a space is encountered, which is not included in the substrings. 

---

### Solution 2: Sorting the words by word length

This solution uses a very similar approach as solution 3 of kata 1, except with one extra step (turning the string into an array) and the sorting is done based on word length.

<u>Solution</u>

```javascript
function findShort(s){
  return s.split(' ')
          .sort((a, b) => a.length - b.length)[0].length;
}
```

**_Notes_**

Just like in the 3rd solution of kata 1, the first element in the array is selected once the array has been sorted. We then get the length of that word since we don't want to return the word itself, but its length.

---

### Solution 3: Finding the min in an array of word lengths

<u>Pseudo code</u>

```
1) Create an array of the words contained in the string.
2) Create another array containing the length of each word.
3) Find the lowest number in that array.
4) Return it.
```

<u>Solution</u>

```javascript
function findShort(s){
  return Math.min(...s.split(' ').map(word => word.length));
}
```

**_Notes_**

1) The [`.map()` array method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) is used to create a new array by looping over the original array and executing a function on each element inside the array. An arrow function is used in this solution, which can be read as `for each word in the array, return the length of the word`. 

2) The [`Math.min()` function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min) receives numbers as its parameter and returns the number with the lowest value out of those numbers. The numbers passed to it have to be separated by a comma and cannot be contained inside an array. 

3) The [spread operator (...array)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) is used to turn the array of numbers into numbers that can be passed to the `Math.min()` function.

---

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