Skip to content

This repository contains solutions to various coding challenges from CodeWars implemented in JavaScript. CodeWars is a platform where developers can improve their programming skills by solving programming puzzles called "kata".

License

Notifications You must be signed in to change notification settings

LevinIgor/Codewars

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

31 Commits
 
 
 
 
 
 
 
 
 
 
 
 

JavaScript Collection of solved tasks from the codewars site

There will be examples of solutions, I do not recommend using the offered code to solve your tasks. I want to warn you that if you try to use the answers shown, you are likely to be blocked by the site. The repository was created primarily as a collection of examples for possible study, and help newcomers.



GitHub commit activity (branch) GitHub Repo stars GitHub forks GitHub contributors GitHub closed pull requests GitHub last commit

Kata


8 Kyu

  • Heads and Legs | 8 kyu | ⬆️UP

    function animals(heads, legs){
      for(var i = 0; i <= heads; i++){
        if( (i * 4 + (heads- i) * 2) == legs){
          return [heads- i,i];
        }
      }
      return 'No solutions';
    }
    


  • Hello, Name or World! | 8 kyu | ⬆️UP

    const hello = name => return `Hello, ${name ? name.at(0).toUpperCase() + name?.slice(1).toLowerCase() : 'World'}!`


  • A Strange Trip to the Market | 8 kyu | ⬆️UP

    const isLockNessMonster = s => s.includes('tree fiddy') || s.includes('3.50') || s.includes('three fifty')


  • Add new item (collections are passed by reference) | 8 kyu | ⬆️UP

    const addExtra = listOfNumbers => [...listOfNumbers,'cock']


  • Exclamation marks series #4: Remove all exclamation marks from sentence but ensure a exclamation mark at the end of string | 8 kyu | ⬆️UP

    const remove = string => string.replace(/!/g, '') + '!'


  • Exclamation marks series #2: Remove all exclamation marks from the end of sentence | 8 kyu | ⬆️UP

    const remove = s => s.replace(/!+$/, '');


  • Grasshopper - Variable Assignment Debug | 8 kyu | ⬆️UP

    var a = "dev"
    var b = "Lab"
    
    var name = a + b


  • Return Two Highest Values in List | 8 kyu | ⬆️UP

    const twoHighest = arr => [...new Set(arr)].sort((a,b) => a-b).slice(-2).reverse()


  • How old will I be in 2099? | 8 kyu | ⬆️UP

    const calculateAge = (m, n) => {
      if(m == n) return 'You were born this very year!';
    
      const year = Math.abs(m-n) == 1 ? 'year' : 'years';
    
      if(m < n) return "You are "+(n-m)+' '+year+' old.';
      if(m > n) return "You will be born in "+(-n+m)+' '+year+'.';
    }


  • Ensure question | 8 kyu | ⬆️UP

    const ensureQuestion = s => s.endsWith('?') ? s : s + '?'


  • Total pressure calculation | 8 kyu | ⬆️UP

    function solution(M1, M2, m1, m2, V, T) {
    		M1 = m1 * 0.001/M1;
        M2 = m2 * 0.001/M2;
        T = T + 273.15;
    	  const R = 0.082;
    
    	  return (((M1 + M2) * R * T) / V) * 1000;
    }


  • Enumerable Magic #1 - True for All? | 8 kyu | ⬆️UP

    const all = ( arr, fun ) => arr.every(fun)


  • Parse float | 8 kyu | ⬆️UP

    const parseF = s =>  isNaN(parseFloat(s)) ? null : parseFloat(s)


  • SpeedCode #2 - Array Madness | 8 kyu | ⬆️UP

    const arrayMadness = (a, b) => a.reduce((acc, x) => acc + x**2, 0) > b.reduce((acc, x) => acc + x**3, 0) 


  • easy logs | 8 kyu | ⬆️UP

    const logs = (x , a, b) =>  (Math.log(a*b) / Math.log(x))


  • Classy Classes | 8 kyu | ⬆️UP

    class Person {
    
      constructor(name, age) {
        this.name = name;
        this.age = age;
      }
      
      get info() {
        return `${this.name}s age is ${this.age}`;
      }
    }


  • Pole Vault Starting Marks | 8 kyu | ⬆️UP

    const startingMark = bodyHeight => +(bodyHeight * 3.9354 + 3.4681).toFixed(2);


  • Training JS #6: Basic data types--Boolean and conditional statements if..else | 8 kyu | ⬆️UP

    const trueOrFalse =(val) => Boolean(val).toString()


  • Fuel Calculator: Total Cost | 8 kyu | ⬆️UP

    function fuelPrice(litres, pricePerLiter) {
      var discount = Math.min(Math.floor(litres/2) * 0.05, 0.25);
      var price = litres * (pricePerLiter - discount);
      return Math.round(price*100) / 100;
    }


  • Days in the year | 8 kyu | ⬆️UP

    const yearDays = year => `${year} has 36${6 - !!(year % 400 && !(year % 100) || year % 4)} days`;


  • Arguments to Binary addition | 8 kyu | ⬆️UP

    const arr2bin = arr => arr.filter(x => typeof x == 'number').reduce((x, y) => x + y, 0).toString(2);


  • Training JS #34: methods of Math---pow() sqrt() and cbrt() | 8 kyu | ⬆️UP

    function cutCube(volume,n){
      return !(Math.cbrt(n) % 1) && !(Math.cbrt(volume / n) % 1);
    }


  • Training JS #17: Methods of String object--indexOf(), lastIndexOf() and search() | 8 kyu | ⬆️UP

    const firstToLast = (str,c) => (str.indexOf(c) < 0) ? -1 : str.lastIndexOf(c) - str.indexOf(c)


  • Implement Array.prototype.filter() | 8 kyu | ⬆️UP

    Array.prototype.filter = function (func) {
      const result = []
      this.forEach(el => func(el) ? result.push(el) : null)      
      return result
    }


  • Job Matching #1 | 8 kyu | ⬆️UP

    function match(candidate, job) {
        if(!candidate.minSalary || !job.maxSalary) throw "Error!!";
        return (candidate.minSalary * 0.9) <= job.maxSalary;
    }


  • Lexical this | 8 kyu | ⬆️UP

     var Person = function(){
        var person = {
          _name: "Leroy",
          _friends: [],
          fillFriends(f){
            this._friends.push(...f);
          }
        }
        return person;
    }


7 Kyu

  • ASCII letters from Number | 7 kyu | ⬆️UP

    function convert(number){
      const arr = []
      
      for(let i = 0; i < number.length; i+=2){
        arr.push(String.fromCharCode(number.substr(i,2)))
      }
      
      return arr.join('')
     }


  • Find the next perfect square! | 7 kyu | ⬆️UP

    function findNextSquare(sq) {
      return Math.sqrt(sq)%1? -1 : Math.pow(Math.sqrt(sq)+1,2);
    }


  • Ones and Zeros | 7 kyu | ⬆️UP

    const binaryArrayToNumber = arr => {
      return parseInt(arr.join(""), 2)
    };


  • Sum of the first nth term of Series | 7 kyu | ⬆️UP

    function SeriesSum(n) {
      var sum = 0;
      for(var i = 0; i < n; i++) {
        sum += 1 / (3 * i + 1);
      }
      return sum.toFixed(2);
    }


  • Sort array by string length | 7 kyu | ⬆️UP

     let sortByLength = arr => arr.sort((a,b) => a.length - b.length);


  • Find the middle element | 7 kyu | ⬆️UP

     const gimme = function (arr) {
        return arr.indexOf([...arr].sort((x, y) => x > y)[1]);
     };
    


  • Round up to the next multiple of 5 | 7 kyu | ⬆️UP

     function roundToNext5(n){
        return Math.ceil(n/5)*5;
      }
    


  • Simple Fun #176: Reverse Letter | 7 kyu | ⬆️UP

     function reverseLetter(str) {
        return str.replace(/[^a-z]/gi,'').split('').reverse().join('')  
    }
    


  • Summing a number's digits | 7 kyu | ⬆️UP

    function sumDigits(number) {
      return `${Math.abs(number)}`.split('').reduce((acc,el) => acc + +el,0)
    }
    


  • Check the exam | 7 kyu | ⬆️UP

    function checkExam(array1, array2) {
      let result = 0;
      
      for(let i in array1){
        if(array2[i] === '') continue;
        array1[i] === array2[i] ? result+=4 : result-=1;
      }
      
      return Math.max(result,0)
    }
    


  • Fix string case | 7 kyu | ⬆️UP

    function solve(s){
        return s.match(/[a-z]/g).length >= s.length / 2 ? s.toLowerCase() : s.toUpperCase()
    }
    


  • Triangular Treasure | 7 kyu | ⬆️UP

    function triangular( n ) {
      return n > 0 ? n * (n + 1) / 2 : 0;
    }
    


  • Most digits | 7 kyu | ⬆️UP

    const findLongest = l => l.reduce((a, b) => (`${b}`.length > `${a}`.length) ? b : a);
    


  • Reverse a Number 7 kyu | ⬆️UP

    const reverseNumber = n => (n > 0 ? 1 : -1) * Math.abs(n).toString().split('').reverse().join('')
    


  • Minimize Sum Of Array (Array Series #1) | ⬆️UP

    function minSum(arr) {
      const l = arr.length;
      const sorted = arr.sort((a, b) => b - a);
      const max = sorted.slice(0, l/2);
      const min = sorted.slice(l/2, l).reverse();
      
      return max.reduce((sum, el, i) => sum + el * min[i], 0);
    }
    


  • Moves in squared strings (I) | ⬆️UP

    const vertMirror = s => s.map(s => [...s].reverse().join(''));
    const horMirror = s => s.reverse();
    
    const oper = (fct, s) => fct(s.split("\n")).join("\n");


  • All unique | ⬆️UP

    let hasUniqueChars = (str) => new Set(str).size === str.length;


  • Palindrome chain length | ⬆️UP

    const palindromeChainLength = n => {
      let count = 0;
    
      while(+[...`${n}`].reverse().join('') !== n){
        n+= +[...`${n}`].reverse().join('')
        count++;
      }
      
      return count
    };


  • Speed Control | ⬆️UP

    const gps = (s, x) => {
    
      if (x.length<=1) {
        return 0;
      }
      
      let output = [];
      for (let i = 0; i < x.length-1; i++) { 
        output.push((x[i+1]-x[i])*3600/s);
      }
      
      return Math.max(...output);
    }


  • Coding Meetup #2 - Higher-Order Functions Series - Greet developers | ⬆️UP

     const greetDevelopers = list => list.map(dev => ({...dev, greeting: `Hi ${dev.firstName}, what do you like the most about ${dev.language}?`}));


  • Halving Sum | ⬆️UP

     const halvingSum = n => n > 1 ? n + halvingSum(n / 2 | 0) : n


  • max diff - easy | ⬆️UP

     function maxDiff(list) {
       return list.length ? Math.max(...list) - Math.min(...list) : 0;
     };


  • Over The Road | 🌐Source | ⬆️UP

     function maxDiff(list) {
       return list.length ? Math.max(...list) - Math.min(...list) : 0;
     };


  • Simple beads count | 🌐Source | ⬆️UP

     function countRedBeads(n) {
       return n < 2 ? 0 : 2 * n - 2;
     }


  • Boiled Eggs | 🌐Source | ⬆️UP

    function cookingTime(eggs) {
      return 5 * Math.ceil(eggs / 8);
    }


  • Simple remove duplicates | 🌐Source | ⬆️UP

     function solve(arr){
       return arr.filter((val,i) => arr.lastIndexOf(val) == i);
     }


  • Find the nth Digit of a Number | 🌐Source | ⬆️UP

    var findDigit = function(num, nth){
      if(nth <= 0) return -1
      num = `${Math.abs(num)}`
      
      return num.length >= nth ? +num.at(num.length - nth) : 0
    }


  • esreveR | 🌐Source | ⬆️UP

     reverse = function(array) {
       return array.map((c, i) => array[array.length - 1 - i]);
     }


  • Sum of array singles | 🌐Source | ⬆️UP

     function repeats(arr){
       return arr.reduce((acc,el) => arr.indexOf(el) === arr.lastIndexOf(el) ? acc+=el : acc,0)
     };


  • Gauß needs help! (Sums of a lot of numbers). | 🌐Source | ⬆️UP

     function f(n){
       if(typeof n !== 'number' || !Number.isInteger(n) || n <= 0) return false
       return ((1 + n)*n)/2
     };


  • Alphabetical Addition | 🌐Source | ⬆️UP

    function addLetters(...letters) {
      const alpha = 'zabcdefghijklmnopqrstuvwxy';
      const sum = letters.reduce((sum, letter) => sum + alpha.indexOf(letter), 0) % 26;
      return alpha[sum];
    }


  • Filter the number | 🌐Source | ⬆️UP

    const FilterString = value => +value.replace(/\D/g, '');


  • Simple Fun #74: Growing Plant | 🌐Source | ⬆️UP

    function growingPlant(upSpeed, downSpeed, desiredHeight) {
      let count = 0, height = 0;
      while(true){
        count++;
        height+=upSpeed;
        if(height >= desiredHeight) return count;
        height-=downSpeed;
      }
    }


  • Coloured Triangles | 🌐Source | ⬆️UP

    function triangle(row) {
      let result = ''
      if(row.length == 1) result = row;
      
      for(let i = 0; i < row.length - 1; i++){
        if(row[i] === row[i+1]) result+= row[i]
        else result+= 'RGB'.replace(row[i],'').replace(row[i+1],'')
      }
      
      if(row.length > 1) return triangle(result)
      else return result
    }


  • Strong Number (Special Numbers Series #2) | 🌐Source | ⬆️UP

    function strong(n) {
      return [1,2,145,40585].includes(n) ? 'STRONG!!!!' : 'Not Strong !!'
    }


  • Help the Fruit Guy | 🌐Source | ⬆️UP

    function removeRotten(arr){
      return arr ? arr.map(x=>x.replace('rotten', '').toLowerCase()) : [] ;
    }


  • Currying functions: multiply all elements in an array | 🌐Source | ⬆️UP

    const multiplyAll = arr => n => arr.map(x => n * x);


  • Alternate case | 🌐Source | ⬆️UP

    function alternateCase(s) {
      return [...s].map(el => el === el.toLowerCase() ? el.toUpperCase() : el.toLowerCase()).join('')
    }
    


  • Basic Calculator | 🌐Source | ⬆️UP

    function calculate(num1, operation, num2) {
      var ops = {
        '+': function(x, y) { return x + y; },
        '-': function(x, y) { return x - y; },
        '*': function(x, y) { return x * y; },
        '/': function(x, y) { return y === 0 ? null : x / y; }
      };
      return (ops[operation] || function() { return null; })(num1, num2);
    }
    


  • Disarium Number (Special Numbers Series #3) | 🌐Source | ⬆️UP

    function disariumNumber(n){
      return [...`${n}`].reduce((acc,el,i) => acc+=el**(i+1),0) === n ? 'Disarium !!' : 'Not !!'
    }


  • Building blocks | 🌐Source | ⬆️UP

    class Block{
    
      constructor(data){
        [this.width, this.length, this.height] = data;
      }
      
      getWidth() {
        return this.width;
      }
      
      getLength() {
        return this.length;
      }
      
      getHeight() {
        return this.height;
      }
      
      getVolume() {
        return this.width * this.length * this.height;
      }
      
      getSurfaceArea () {
        return 2 * (this.width * this.length + this.width * this.height + this.length * this.height);
      }
    }


  • SevenAte9 | 🌐Source | ⬆️UP

    function sevenAte9(str){
      return str.replace(/79(?=7)/g, '7');
    }


  • Difference Of Squares | 🌐Source | ⬆️UP

    function differenceOfSquares(n){
      const arr = Array.from({length:n}, (_,i) => i+1)
      return arr.reduce((acc,el) => acc+el,0)**2 - arr.reduce((acc,el) => acc+=el**2,0)
    }


  • Digital cypher | 🌐Source | ⬆️UP

    function encode(str,  n){
      return  [...str].map((el,i) => (el.charCodeAt() - 96) + +`${n}`.at(i%`${n}`.length))
    }


  • Return the closest number multiple of 10 | 🌐Source | ⬆️UP

    const closestMultiple10 = num => Math.round(num / 10) * 10;
    


  • Substituting Variables Into Strings: Padded Numbers | 🌐Source | ⬆️UP

    function solution(value){
      return "Value is " + ("00000" + value).slice(-5);
    }
    


  • The old switcheroo | 🌐Source | ⬆️UP

    function vowel2index(str) {
       return str.replace(/[aeiou]/ig, (m, i) => i + 1);
    }
    


  • Word values | 🌐Source | ⬆️UP

    function wordValue(a) {
    	return a.map((el,i) => el.replace(/ /g, '').split('').reduce((acc,letter) => acc+letter.charCodeAt() - 96,0) * (i+1))
    }
    


  • Convert a linked list to a string | 🌐Source | ⬆️UP

    function stringify(list) {
    	return list === null ? "null" : `${list.data} -> ${stringify(list.next)}`; 
    }
    


  • ToLeetSpeak | 🌐Source | ⬆️UP

    const toLeetSpeak = s => s.replace(/[ABCEGHILOSTZ]/g, c => D[c]);   


  • Split In Parts | 🌐Source | ⬆️UP

    var splitInParts = function(s, partLength){
      let result = []
      
      for(let i = 0; i < s.length; i+=partLength){
        result.push(s.substr(i,partLength))
      }
      
      return result.join(' ')
    }		
    


  • Valid Spacing | 🌐Source | ⬆️UP

    function validSpacing(s) {
      return s.trim() == s && !s.includes("  ");
    }


  • Count all the sheep on farm in the heights of New Zealand | 🌐Source | ⬆️UP

    const lostSheep = (f,s,n) => n - [...f,...s].reduce((a,b) => a + b,0)


  • Insert dashes | 🌐Source | ⬆️UP

    function insertDash(num) {
      let result = ''
      num = `${num}`
      for(let i = 0; i < num.length; i++){
        if(num[i]&1 && num[i+1]&1) result+=`${num[i]}-`
        else result+=num[i]
      }
      
      return result
    }


  • Band name generator | 🌐Source | ⬆️UP

    function bandNameGenerator(str) {
      return str.at(0) !== str.at(-1) ? `The ${str.at(0).toUpperCase() + str.slice(1)}` : `${str.charAt(0).toUpperCase() + str.slice(1) + str.slice(1)}`
    }


  • Arithmetic progression | 🌐Source | ⬆️UP

    function arithmeticSequenceElements(a, r, n) {
      return Array.from({length: n}, (_, i) => a + r * i).join(', ');
    }


  • Stanton measure | 🌐Source | ⬆️UP

    function stantonMeasure(arr) {
      const count = n => arr.filter(x => x === n).length;
      return count(count(1));
    }


  • Length and two values. | 🌐Source | ⬆️UP

    function alternate(n, firstValue, secondValue){
      return Array.from({length:n}, (_,i) => i&1 ?  secondValue : firstValue)
    }


  • makeBackronym | 🌐Source | ⬆️UP

    var makeBackronym = function(string){
      return [...string].map(el => dict[el.toUpperCase()]).join(' ');
    };


  • Frequency sequence | 🌐Source | ⬆️UP

    function freqSeq(str, sep) {
      return [...str].map(el => str.replace(new RegExp(`[^${el}]`,'g'),'').length).join(sep)
    }


  • Find Duplicates | 🌐Source | ⬆️UP

    const duplicates = arr => [...new Set(arr.filter((el, i) => i !== arr.indexOf(el)))];


  • TV Remote | 🌐Source | ⬆️UP

    const tvRemote = function(word) {
    
      let keys = 'abcde123fghij456klmno789pqrst.@0uvwxyz_/';
      let pos = [ 0, 0 ];
      let res = 0;
      
      for (let char of word) {
    
        let i = keys.indexOf(char);
        let dest  = [ i / 8 | 0, i % 8 ];
    
        res += Math.abs(dest[0] - pos[0]) + Math.abs(dest[1] - pos[1]) + 1;
        pos = dest;
        
      }
    
      return res;
    
    }


  • Delta Bits | 🌐Source | ⬆️UP

    function convertBits(a, b){
      var x = a ^ b, count = 0;
      do { count += x & 1 } while (x >>= 1);
      return count;
    }


6 Kyu

  • Random Sequence Generator | 🌐Source | ⬆️UP

    function Randomizer(min, max) {
      for (this.num = []; min <= max; min++) this.num.push(min)
      for (var i = 10; i--;) this.num.sort(function() { return Math.random() - 0.5 })
    }
    
    Randomizer.prototype.next = function() {
      if (!this.num.length) throw new Error('No more numbers')
    	return this.num.pop()
    }
    
    Randomizer.prototype.sequence = function(size) {
      if (size > this.num.length || !this.num.length) throw new Error('Too many numbers')
    	return this.num.splice(0, size || Infinity);
    }
    function Randomizer(min, max) {
      this.numbers = [...'0'.repeat(max-min+1)].map((_, i) => min + i);
      this.numbers.sort((a, b) => Math.random() - 0.5);
    }
    
    Randomizer.prototype.next = function() {
      if (this.numbers.length === 0) throw new Error('No more numbers');
      return this.numbers.pop();
    };
    
    Randomizer.prototype.sequence = function(size = this.numbers.length) {
      if (size > this.numbers.length) throw new Error('Too many numbers');
      return this.numbers.splice(0, size);
    };


  • Arc Length | 🌐Source | ⬆️UP

    function distance([x1, y1], [x2, y2]) {
        return Math.hypot(x1 - x2, y1 - y2);
    }
    
    function linspace(start, stop, length) {
        const step = (stop - start) / (length - 1);
        return Array.from({length: length}, (_, i) => start + step * i);
    }
    
    function arcLen(fn, range, intervals = 200) {
        const coords = linspace(...range, intervals).map(fn);
        const lengths = Array.from({length: intervals - 1}, (_, i) => distance(coords[i], coords[i + 1]));
        return parseFloat(lengths.reduce((a, b) => a + b).toFixed(2));
    }
    function arcLen(fn, [b, e]) {
      const n = 100000;
      let res = 0;
      for (let i = 0, pp; i < n; i++) {
        const p = fn(b * i / n + e * (n - i) / n);
        if (i != 0)
          res += Math.hypot(p[0] - pp[0], p[1] - pp[1]);
        pp = p;
      }
      return res;
    }


  • Quantum Bogosort | 🌐Source | ⬆️UP

    Array.prototype.qbsort = function() {
      this.qshuffle()  
      this.some((_,i,a) => i && a[i]<a[i-1] ) && QSC.destroyUniverse();
    }


5 Kyu

4 Kyu

3 Kyu

2 Kyu

1 Kyu

About

This repository contains solutions to various coding challenges from CodeWars implemented in JavaScript. CodeWars is a platform where developers can improve their programming skills by solving programming puzzles called "kata".

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published