Skip to content

Instantly share code, notes, and snippets.

@whitershade
Last active May 24, 2019 13:40
Show Gist options
  • Save whitershade/899d94f545b1fdc83944d8a9b32b013c to your computer and use it in GitHub Desktop.
Save whitershade/899d94f545b1fdc83944d8a9b32b013c to your computer and use it in GitHub Desktop.
eloquent javascript
Треугольник в цикле
for (let i = ''; i.length < 8; i += '#')
console.log(i);
FizzBuzz
for (let i = 1; i <= 100; i += 1) {
switch (true) {
case i % 3 === 0 && i % 5 === 0:
console.log('fizz buzz');
break;
case i % 3 === 0:
console.log('fizz');
break;
case i % 5 === 0:
console.log('buzz');
break;
default:
console.log(i);
}
}
Шахматная доска
let boardSize = 8;
let desk = ''
let oddRow = true;
for (let i = 1, iEnd = boardSize * boardSize + 1; i < iEnd; i += 1) {
if (oddRow) desk += i % 2 === 0 ? ' ' : '#';
else desk += i % 2 === 0 ? '#' : ' ';
if (i % boardSize === 0) {
desk += '\n';
oddRow = !oddRow;
}
}
Минимальное из двух
const min = (a, b) => a < b ? a : b;
Рекурсионное isEven:
const isEven = number => {
const absNumber = Math.abs(number);
switch(absNumber) {
case 0:
return true;
case 1:
return false;
case 2:
return true;
default:
return isEven(absNumber - 2);
}
}
Подсчет букв в строке
const countBs = string => countChar(string, 'b');
const countChar = (string, char) =>
string
.split('')
.reduce((accum, letter) => letter.toLowerCase() === char ? accum + 1 : accum, 0)
Рэндж
const range = (from, to, step = 1) => {
const array = [];
if (step > 0) {
for (let i = from; i <= to; i += step)
array.push(i);
} else {
for (let i = from; i >= to; i += step)
array.push(i);
}
return array;
}
Сумма элементов массива
const sum = array => array.reduce((sum, number) => sum + number, 0);
Обратный порядок массива не изменяя аргумент
const reverseArray = array => {
const reversedArray = [];
for (let i = array.length - 1; i >= 0; i -= 1)
reversedArray.push(array[i]);
return reversedArray;
}
Обратный порядок массива изменяя аргумент
const reverseArrayInPlace = array => {
for (let i = 0, j = array.length - 1; i < j; i += 1, j -= 1) {
if (i === j) break;
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
List to array, array to list, порядоковый номер в list
const arrayToList = array => {
if (array.length === 0) return null;
return { value: array[0], rest: arrayToList(array.slice(1)) }
}
const listToArray = list => {
if (list.rest === null) return [list.value];
return [ list.value, ...listToArray(list.rest) ]
}
const prepend = (value, rest) => ({ value, rest });
const nth = (list, position, currentPosition = 0) => {
if (position === currentPosition) return list.value;
return nth(list.rest, position, currentPosition += 1);
};
Flat array
var arrays = [[1, 2, 3], [4, 5], [6]];
console.log(arrays.reduce((accum, item) => accum.concat(item), []))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment