#ScienceToTech 2: My Javascript Kata [CodeWars] Solutions
Tags: javascript, beginners, webdev, careerchange
Published: 2023-01-28 14:29:36

_In these #ScienceToTech posts, I'm documenting my journey from a Science-centered career (with 0 programming experience) to a Dev career_

For context,I [switched careers](https://dev.to/aucodes/sciencetotech-1-a-biologist-trying-to-code-13jo) from Science (for >5 yrs) to Tech just last year. The only experience I have with Tech, is using R for data analysis & visualization as well as the usual highschool computer "programming" subjects.

To help me transition my career from Science to Tech, I'm currently taking [Zero To Mastery's](https://www.udemy.com/course/the-complete-web-developer-zero-to-mastery/) Complete Web Dev course. After the Javascript part, I felt that I needed more (and consistent) practice. That's where [Code Wars](https://www.codewars.com) was recommended to me. Everyday, I try to solve at least 2 "kata" to help me be more comfortable with Javascript. As I solve more and more kata, I can see that my coding is definitely improving especially the way I solve and answer problems. 

Here, I want to share the Kata problems and solutions I've came up with to document my journey and even share these to people who are in the same situation as me. Since I'm using this to document my solutions, the first ones are when I JUST started kata.

`This list is always being updated`

1. Write a function that displays your score IF your score is higher than the class average. The class scores are given as an array.

```js
function betterThanAverage(classPoints, yourPoints) {
  let average = (classPoints.reduce((sum,num) =>
      sum + num, 0))/classPoints.length
  return yourPoints > average
}
```

2\. Write a function to convert a number to a string

```js
function numberToString(num) {
   return num.toString();
}
```

3\. Function that can count the number of "Sheeps". Given an array, count the number of "True" that represents a present sheep. "False" represents a missing sheep.

```js
function countSheeps(arrayOfSheep) {
  return arrayOfSheep.filter(value =>
         value === true).length;
}
```

4\. Function to get result of numbers after applying the chosen operation.

```js
function basicOp(operation, value1, value2) {
   switch (operation) {
      case"+":
        output = value1+value2;
        break;
      case"-":
        output = value1-value2;
        break;
      case"*":
        output = value1*value2;
        break;
      case"/":
        output = value1/value2;
        break;
      default:
        output = "Please enter a valid operation";
   }
return output;
}
```

5\. Given an array with positive and negative numbers, return an array where the first element is the COUNT of positives and the second element is the SUM of negatives. If the input is an empty array or is null, return an empty array.

```js
function countPositivesSumNegatives(input) {
   if (input === null || input.length<1) {
   return [];
}
var array = [0,0];
for (var i = 0; i < input.length; i++) {
  if (input[i] <=0) {
   array[1] += input[i];
  }else{
   array[0] += 1;
  } return array;
}
```

6\. Write a function to get the sum of an array but return "0" if the array doesn't contain any number.

```js
function sum(numbers) {
  return numbers.reduce((a,b) => a+b, 0);
  }
}
```
7\. Needle in a haystack. Find the location (or the index) of one "needle" in an array that contain strings such as "hay", "junk", "needle". Return the statement, "found the needle at position [index]"

```js
function findNeedle(haystack) {
  return "found the needle at position" +
          haystack.indexOf("needle");
}
```
8\. Check whether a value (x) is present in an array (a). Output should be either true or false.

```js
function check(a,x) {
   return a.includes(x);
}
```
9\. Scores of several games are recorded in an array where one game is recorded as a string as x:y (e.g., "4:0") where x is the team score and y is the opponent's score. Calculate the team's score based on the following scoring points:

- if x>y = +3 pts

- if x<y = +0 pts

- if x=y = +1 pt
*Based this answer from someone elses because mine was QUITE long:*
```js
const points = games => games.reduce((output,current) => {
      return output += current[0] > current[2]?3:
                       current[0] === current[2]?1:
                       0;
},0)
```
10\. Return the input (boolean) into a string.

```js
function booleanToString(b) {
     return b.toString();
}
```
11\. Returns "Even" if the input is an even number and "Odd" if not.

```js
function evenOrOdd(number) {
     return number % 2 == 0? "Even":"Odd";
}
```
12\. Add 2 numbers and return the sum in binary.

```js
function addBinary(a,b) {
  return (a+b).toString(2);
}
```
13\. Delete all spaces in the string.

```js
function noSpace(x) {
    return x.replaceAll(' ', '');
}
```
14\. Given a string of digits, replace the digits (num) within the string:

- num<5 with 0 

- num>5 with 1
 
and return the resulting string.

```js
function fakeBin(x) {
   let endString = "";
   for (let num of x) {
       endString += num < 5 ? "0": "1";
   } return endString;
}
```
15\. Opposites attract
Timmy & Sarah think they are in love, but around where they live, they will only know once they pick a flower each. If one of the flowers has an even number of petals and the other has an odd number of petals it means they are in love.

Write a function that will take the number of petals of each flower and return true if they are in love and false if they aren't.

```js
function lovefunc(flower1, flower2) {
  return (flower1 % 2 == 0 && flower2 % 2 != 0) || 
         (flower2 % 2 == 0 && flower1 % 2 != 0)?
         true : false;
}

```
better: 

```js
function lovefunc(flower1, flower2){
  return flower1 % 2 !== flower2 % 2;
}

```
16\. Your task is to write a function which returns the sum of following series upto nth term(parameter).

Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...
Rules:

You need to round the answer to 2 decimal places and return it as String.

If the given value is 0 then it should return 0.00

You will only be given Natural Numbers as arguments.

Examples:(Input --> Output)

1 --> 1 --> "1.00"
2 --> 1 + 1/4 --> "1.25"
5 --> 1 + 1/4 + 1/7 + 1/10 + 1/13 --> "1.57"

```js
function SeriesSum(n) {
    let sum = 0;
    let num = 1;
    for (let i = 0; i < n; i += 1) {
    if (i === 0) {
      sum = 1;
    } else {
      num += 3;
      sum = sum + (1 / num);
    }
  }
  return sum.toFixed(2);
}

```

17\. Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).

```js
function solution(str, ending){
    return str.endsWith(ending);
}
```

18\. You have to write a function printer_error which given a string will return the error rate of the printer as a string representing a rational whose numerator is the number of errors and the denominator the length of the control string. Don't reduce this fraction to a simpler expression. Letters outside "a" to "m" is equivalent to one error.

The string has a length greater or equal to one and contains only letters from a to z.

Examples:

s="aaabbbbhaijjjm"
printer_error(s) => "0/14"

s="aaaxbbbbyyhwawiwjjjwwm"
printer_error(s) => "8/22"

```js
function printerError(s) {
  const errors = 'nopqrstuvwxyz';
  const count = s.split('').filter(c =>     
                errors.includes(c)).length
  return `${count}/${s.length}`
}

```
19\. Create a function with two arguments that will return an array of the first n multiples of x.

Assume both the given number and the number of times to count will be positive numbers greater than 0.

Return the results as an array or list ( depending on language ).

Examples

countBy(1,10) === [1,2,3,4,5,6,7,8,9,10]
countBy(2,5) === [2,4,6,8,10]

```js
function countBy(x, n) {
  let z = [];
  for (let i = 0; i < n; i++) {
      z.push(x + (x*i));    
  }
  return z;
}
```
20\. Write a function that takes an array of words and smashes them together into a sentence and returns the sentence. You can ignore any need to sanitize words or add punctuation, but you should add spaces between each word.
```js
if (words.length===0){
    return ""
  } else {
    return words.join(" ")
  }
```
21\.Given two integers a and b, which can be positive or negative, find the sum of all the integers between and including them and return it. If the two numbers are equal return a or b.
```js
function getSum(a, b) {
  if (a === b) {
     return a
  } 

  const min = a < b ? a : b;
  const max = a > b ? a : b;
  let sum = 0;

  for(let i = min; i <= max; i++) {
     sum += i;
  }
  return sum;
}
```
22\. It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry with strings with less than two characters.
```js
function removeChar(str){
  return str.substring(1,str.length-1);
};
```
23\. Return the number (count) of vowels in the given string.
```js
function getCount(str) {
  return (str.match( /a|e|i|o|u/g ) || []).length;
}
```
24\. Complete the findNextSquare method that finds the next integral perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer.

If the parameter is itself not a perfect square then -1 should be returned. You may assume the parameter is non-negative.
```js
function findNextSquare(sq) {  
  if (!Number.isInteger(Math.sqrt(sq))) {
      return -1;
  } 
  for (let i=sq+1; ;i++) {
    if (Number.isInteger(Math.sqrt(i))) {
      return i;
    }
  }
}
```
25\.Complete the square sum function so that it squares each number passed into it and then sums the results together.

For example, for [1, 2, 2] it should return 9 
```js
function squareSum(numbers){
  return sum = numbers.flatMap((x) => 
           x *   x).reduce((partialSum, a) => 
           partialSum + a, 0);
}
```