Codewars
所属分类:教育系统应用
开发工具:Others
文件大小:0KB
下载次数:0
上传日期:2024-03-22 02:46:17
上 传 者:
sh-1993
说明: 该存储库包含用JavaScript实现的CodeWars的各种编码挑战的解决方案。CodeWars是一个平台,开发人员可以通过解决称为“kata”的编程难题来提高他们的编程技能。
(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".)
文件列表:
CODE_OF_CONDUCT.md
CONTRIBUTING.md
LICENSE
SECURITY.md
# **JavaScript Collection of solved tasks from the [codewars](https://www.codewars.com) 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.
![](https://www.codewars.com/users/3au4onok/badges/small)
![GitHub commit activity (branch)](https://img.shields.io/github/commit-activity/t/LevinIgor/Codewars)
![GitHub Repo stars](https://img.shields.io/github/stars/LevinIgor/Codewars)
![GitHub forks](https://img.shields.io/github/forks/LevinIgor/Codewars)
![GitHub contributors](https://img.shields.io/github/contributors/LevinIgor/codewars)
![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/LevinIgor/Codewars)
![GitHub last commit](https://img.shields.io/github/last-commit/LevinIgor/codewars)
# **Kata**
- **[8 - kyu](#8-kyu)**
- **[7 - kyu](#7-kyu)**
- **[6 - kyu](#6-kyu)**
- **[5 - kyu](#5-kyu)**
- **[4 - kyu](#4-kyu)**
- **[3 - kyu](#3-kyu)**
- **[2 - kyu](#2-kyu)**
- **[1 - kyu](#1-kyu)**
## 8 Kyu
- ### Heads and Legs | 8 kyu | [:arrow_up:UP](#kata)
```javascript
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 | [:arrow_up:UP](#kata)
```javascript
const hello = name => return `Hello, ${name ? name.at(0).toUpperCase() + name?.slice(1).toLowerCase() : 'World'}!`
```
- ### A Strange Trip to the Market | 8 kyu | [:arrow_up:UP](#kata)
```javascript
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 | [:arrow_up:UP](#kata)
```javascript
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 | [:arrow_up:UP](#kata)
```javascript
const remove = string => string.replace(/!/g, '') + '!'
```
- ### Exclamation marks series #2: Remove all exclamation marks from the end of sentence | 8 kyu | [:arrow_up:UP](#kata)
```javascript
const remove = s => s.replace(/!+$/, '');
```
- ### Grasshopper - Variable Assignment Debug | 8 kyu | [:arrow_up:UP](#kata)
```javascript
var a = "dev"
var b = "Lab"
var name = a + b
```
- ### Return Two Highest Values in List | 8 kyu | [:arrow_up:UP](#kata)
```javascript
const twoHighest = arr => [...new Set(arr)].sort((a,b) => a-b).slice(-2).reverse()
```
- ### How old will I be in 2099? | 8 kyu | [:arrow_up:UP](#kata)
```javascript
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 | [:arrow_up:UP](#kata)
```javascript
const ensureQuestion = s => s.endsWith('?') ? s : s + '?'
```
- ### Total pressure calculation | 8 kyu | [:arrow_up:UP](#kata)
```javascript
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 | [:arrow_up:UP](#kata)
```javascript
const all = ( arr, fun ) => arr.every(fun)
```
- ### Parse float | 8 kyu | [:arrow_up:UP](#kata)
```javascript
const parseF = s => isNaN(parseFloat(s)) ? null : parseFloat(s)
```
- ### SpeedCode #2 - Array Madness | 8 kyu | [:arrow_up:UP](#kata)
```javascript
const arrayMadness = (a, b) => a.reduce((acc, x) => acc + x**2, 0) > b.reduce((acc, x) => acc + x**3, 0)
```
- ### easy logs | 8 kyu | [:arrow_up:UP](#kata)
```javascript
const logs = (x , a, b) => (Math.log(a*b) / Math.log(x))
```
- ### Classy Classes | 8 kyu | [:arrow_up:UP](#kata)
```javascript
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 | [:arrow_up:UP](#kata)
```javascript
const startingMark = bodyHeight => +(bodyHeight * 3.9354 + 3.4681).toFixed(2);
```
- ### Training JS #6: Basic data types--Boolean and conditional statements if..else | 8 kyu | [:arrow_up:UP](#kata)
```javascript
const trueOrFalse =(val) => Boolean(val).toString()
```
- ### Fuel Calculator: Total Cost | 8 kyu | [:arrow_up:UP](#kata)
```javascript
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 | [:arrow_up:UP](#kata)
```javascript
const yearDays = year => `${year} has 36${6 - !!(year % 400 && !(year % 100) || year % 4)} days`;
```
- ### Arguments to Binary addition | 8 kyu | [:arrow_up:UP](#kata)
```javascript
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 | [:arrow_up:UP](#kata)
```javascript
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 | [:arrow_up:UP](#kata)
```javascript
const firstToLast = (str,c) => (str.indexOf(c) < 0) ? -1 : str.lastIndexOf(c) - str.indexOf(c)
```
- ### Implement Array.prototype.filter() | 8 kyu | [:arrow_up:UP](#kata)
```javascript
Array.prototype.filter = function (func) {
const result = []
this.forEach(el => func(el) ? result.push(el) : null)
return result
}
```
- ### Job Matching #1 | 8 kyu | [:arrow_up:UP](#kata)
```javascript
function match(candidate, job) {
if(!candidate.minSalary || !job.maxSalary) throw "Error!!";
return (candidate.minSalary * 0.9) <= job.maxSalary;
}
```
- ### Lexical this | 8 kyu | [:arrow_up:UP](#kata)
```javascript
var Person = function(){
var person = {
_name: "Leroy",
_friends: [],
fillFriends(f){
this._friends.push(...f);
}
}
return person;
}
```
## 7 Kyu
- ### ASCII letters from Number | 7 kyu | [:arrow_up:UP](#kata)
```javascript
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 | [:arrow_up:UP](#kata)
```javascript
function findNextSquare(sq) {
return Math.sqrt(sq)%1? -1 : Math.pow(Math.sqrt(sq)+1,2);
}
```
- ### Ones and Zeros | 7 kyu | [:arrow_up:UP](#kata)
```javascript
const binaryArrayToNumber = arr => {
return parseInt(arr.join(""), 2)
};
```
- ### Sum of the first nth term of Series | 7 kyu | [:arrow_up:UP](#kata)
```javascript
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 | [:arrow_up:UP](#kata)
```javascript
let sortByLength = arr => arr.sort((a,b) => a.length - b.length);
```
- ### Find the middle element | 7 kyu | [:arrow_up:UP](#kata)
```javascript
const gimme = function (arr) {
return arr.indexOf([...arr].sort((x, y) => x > y)[1]);
};
```
- ### Round up to the next multiple of 5 | 7 kyu | [:arrow_up:UP](#kata)
```javascript
function roundToNext5(n){
return Math.ceil(n/5)*5;
}
```
- ### Simple Fun #176: Reverse Letter | 7 kyu | [:arrow_up:UP](#kata)
```javascript
function reverseLetter(str) {
return str.replace(/[^a-z]/gi,'').split('').reverse().join('')
}
```
- ### Summing a number's digits | 7 kyu | [:arrow_up:UP](#kata)
```javascript
function sumDigits(number) {
return `${Math.abs(number)}`.split('').reduce((acc,el) => acc + +el,0)
}
```
- ### Check the exam | 7 kyu | [:arrow_up:UP](#kata)
```javascript
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 | [:arrow_up:UP](#kata)
```javascript
function solve(s){
return s.match(/[a-z]/g).length >= s.length / 2 ? s.toLowerCase() : s.toUpperCase()
}
```
- ### Triangular Treasure | 7 kyu | [:arrow_up:UP](#kata)
```javascript
function triangular( n ) {
return n > 0 ? n * (n + 1) / 2 : 0;
}
```
- ### Most digits | 7 kyu | [:arrow_up:UP](#kata)
```javascript
const findLongest = l => l.reduce((a, b) => (`${b}`.length > `${a}`.length) ? b : a);
```
- ### Reverse a Number 7 kyu | [:arrow_up:UP](#kata)
```javascript
const reverseNumber = n => (n > 0 ? 1 : -1) * Math.abs(n).toString().split('').reverse().join('')
```
- ### Minimize Sum Of Array (Array Series #1) | [:arrow_up:UP](#kata)
```javascript
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) | [:arrow_up:UP](#kata)
```javascript
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 | [:arrow_up:UP](#kata)
```javascript
let hasUniqueChars = (str) => new Set(str).size === str.length;
```
- ### Palindrome chain length | [:arrow_up:UP](#kata)
```javascript
const palindromeChainLength = n => {
let count = 0;
while(+[...`${n}`].reverse().join('') !== n){
n+= +[...`${n}`].reverse().join('')
count++;
}
return count
};
```
- ### Speed Control | [:arrow_up:UP](#kata)
```javascript
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 | [:arrow_up:UP](#kata)
```javascript
const greetDevelopers = list => list.map(dev => ({...dev, greeting: `Hi ${dev.firstName}, what do you like the most about ${dev.language}?`}));
```
- ### Halving Sum | [:arrow_up:UP](#kata)
```javascript
const halvingSum = n => n > 1 ? n + halvingSum(n / 2 | 0) : n
```
- ### max diff - easy | [:arrow_up:UP](#kata)
```javascript
function maxDiff(list) {
return list.length ? Math.max(...list) - Math.min(...list) : 0;
};
```
- ### Over The Road | [:globe_with_meridians:Source](https://www.codewars.com/kata/5f0ed36164f2bc00283aed07/javascript) | [:arrow_up:UP](#kata)
```javascript
function maxDiff(list) {
return list.length ? Math.max(...list) - Math.min(...list) : 0;
};
```
- ### Simple beads count | [:globe_with_meridians:Source](https://www.codewars.com/kata/58712dfa5c538b6fc7000569/javascript) | [:arrow_up:UP](#kata)
```javascript
function countRedBeads(n) {
return n < 2 ? 0 : 2 * n - 2;
}
```
- ### Boiled Eggs | [:globe_with_meridians:Source](https://www.codewars.com/kata/52b5247074ea613a09000164/javascript) | [:arrow_up:UP](#kata)
```javascript
function cookingTime(eggs) {
return 5 * Math.ceil(eggs / 8);
}
```
- ### Simple remove duplicates | [:globe_with_meridians:Source](https://www.codewars.com/kata/5ba38ba180824a86850000f7/javascript) | [:arrow_up:UP](#kata)
```javascript
function solve(arr){
return arr.filter((val,i) => arr.lastIndexOf(val) == i);
}
```
- ### Find the nth Digit of a Number | [:globe_with_meridians:Source](https://www.codewars.com/kata/577b9960df78c19bca00007e/javascript) | [:arrow_up:UP](#kata)
```javascript
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 | [:globe_with_meridians:Source](https://www.codewars.com/kata/5413759479ba273f8100003d/javascript) | [:arrow_up:UP](#kata)
```javascript
reverse = function(array) {
return array.map((c, i) => array[array.length - 1 - i]);
}
```
- ### Sum of array singles | [:globe_with_meridians:Source](https://www.codewars.com/kata/59f11118a5e129e591000134/javascript) | [:arrow_up:UP](#kata)
```javascript
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). | [:globe_with_meridians:Source](https://www.codewars.com/kata/54df2067ecaa226eca000229/javascript) | [:arrow_up:UP](#kata)
```javascript
function f(n){
if(typeof n !== 'number' || !Number.isInteger(n) || n <= 0) return false
return ((1 + n)*n)/2
};
```
- ### Alphabetical Addition | [:globe_with_meridians:Source](https://www.codewars.com/kata/5d50e3914861a500121e1958/javascript) | [:arrow_up:UP](#kata)
```javascript
function addLetters(...letters) {
const alpha = 'zabcdefghijklmnopqrstuvwxy';
const sum = letters.reduce((sum, letter) => sum + alpha.indexOf(letter), 0) % 26;
return alpha[sum];
}
```
- ### Filter the number | [:globe_with_meridians:Source](https://www.codewars.com/kata/55b051fac50a3292a9000025/javascript) | [:arrow_up:UP](#kata)
```javascript
const FilterString = value => +value.replace(/\D/g, '');
```
- ### Simple Fun #74: Growing Plant | [:globe_with_meridians:Source](https://www.codewars.com/kata/58941fec8afa3618c9000184/javascript) | [:arrow_up:UP](#kata)
```javascript
function growingPlant(upSpeed, downSpeed, desiredHeight) {
let count = 0, height = 0;
while(true){
count++;
height+=upSpeed;
if(height >= desiredHeight) return count;
height-=downSpeed;
}
}
```
- ### Coloured Triangles | [:globe_with_meridians:Source](codewars.com/kata/5a25ac6ac5e284cfbe000111/javascript) | [:arrow_up:UP](#kata)
```javascript
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) | [:globe_with_meridians:Source](https://www.codewars.com/kata/5a4d303f880385399b000001/javascript) | [:arrow_up:UP](#kata)
```javascript
function strong(n) {
return [1,2,145,40585].includes(n) ? 'STRONG!!!!' : 'Not Strong !!'
}
```
- ### Help the Fruit Guy | [:globe_with_meridians:Source](https://www.codewars.com/kata/557af4c6169ac832300000ba/javascript) | [:arrow_up:UP](#kata)
```javascript
function removeRotten(arr){
return arr ? arr.map(x=>x.replace('rotten', '').toLowerCase()) : [] ;
}
```
- ### Currying functions: multiply all elements in an array | [:globe_with_meridians:Source](https://www.codewars.com/kata/586909e4c66d18dd1800009b/javascript) | [:arrow_up:UP](#kata)
```javascript
const multiplyAll = arr => n => arr.map(x => n * x);
```
- ### Alternate case | [:globe_with_meridians:Source](https://www.codewars.com/kata/57a62154cf1fa5b25200031e/javascript) | [:arrow_up:UP](#kata)
```javascript
function alternateCase(s) {
return [...s].map(el => el === el.toLowerCase() ? el.toUpperCase() : el.toLowerCase()).join('')
}
```
- ### Basic Calculator | [:globe_with_meridians:Source](https://www.codewars.com/kata/5296455e4fe0cdf2e000059f/javascript) | [:arrow_up:UP](#kata)
```javascript
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] || func ... ...
近期下载者:
相关文件:
收藏者: