Π·Π°ΠΌΡΠΊΠ°Π½ΠΈΠ΅
Copy function closure() {
let count = 0;
return function coun1t() {
return count++;
}
}
let count1 = closure();
console.log(count1());
console.log(count1());
console.log(count1());
debounce
Copy function debounce(f, ms) {
let isCooldown = false;
return (...args) => {
if (isCooldown) return;
f.apply(this, args);
isCooldown = true;
setTimeout(() => isCooldown = false, ms);
};
}
bubble sort
Copy function sort(arr) {
let n = arr.lenght
for ( let i = 0; i < n - 1; i++ ) {
for ( let j = 0; j < n - 1 - i; j++ ) {
if ( arr[j] > arr[j+1] ) {
let temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
reduce
Copy [0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, index, array) {
return accumulator + currentValue;
}, 10);
random min man
Copy function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
Redux
createStore(redux)
Copy const createStore = (initialState, reducer) => {
let state = initialState;
let subscribers = [];
return {
dispatch: (action) => {
state = reducer(state, action);
subscribers.forEach((fn)=>fn());
},
getState: () => state,
subscribe: (fn) => subscribers.push(fn)
}
}
Or
Copy const createStore = (inState, reducer) =>{
let state = inState;
let subscribers = [];
const getState = () => state;
const subscribe = (fn) => subscribers.push(fn);
const dispatch = (action) => {
const fsf = reducer(state, action);
subscribers.forEach(fn => fn(fsf));
}
return {
dispatch,
getState,
subscribe
}
}
const initialState = {
counter: 0;
}
const ACTION_ADD_1 = {
type: 'ACTION_ADD_1',
}
const ACTION_Substract_1 = {
type: 'ACTION_SUBSCTRACT_1',
}
const reducer = (state, action) {
if(action.type === 'ACTION_ADD_1') {
return {...state, state.counter + 1}
}
if (action.type === 'ACTION_SUBSCTRACT_1'){
return {...state, state.counter - 1}
}
return state
}
const selectCounter = (state) {
return state.counter
}
insertAfter
Copy function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
querystring /queryparams
Copy {
a: 1,
b: 2,
c: 3
}
result => ?a=1&b=2&c=3
let obj = {
a: 1,
b: 2,
c: 3
}
function queryParams(obj) {
let keysValues = Object.entries(obj).map((item) => item.join('='));
console.log(`?${keysValues.join("&")}`)
// or
// console.log(`?${keysValues.join('&').replace(/,/g,'=')}`)
}
queryParams(obj);
Sum function with different number of params
sum(1, 2, 3) => 6
sum(3, 4) => 7
Copy function fn(...arg) {
return arg.reduce((acc, currentItem) => {
acc += currentItem;
return acc
}, 1);
}
// OR:
function fn() {
return [...arguments].reduce((acc, currentItem) => {
acc += currentItem;
return acc
}, 1);
}
let result = fn(1,2,3)
console.log(result);
//OR
function sum() {
return Array.prototype.reduce.call(arguments, function(a, b) {
return a+b
}, 0);
}
console.log(sum(1,2,5)) //8
Array
Deep of Array
Copy const arr = [1, [2], [3, [4, 5]]];
type d = number | d[];
const deepsMatrix = [0, calcDeep([2]), calcDeep([3, [4, 5]])];
const deepsMatrix2 = 2;
function calcDeep (arr: d[]): number{
const deeps = arr.map(item => {
if(Array.isArray(item)){
return calcDeep(item)
} else return 0
})
return Math.max(...deeps) + 1
}
console.log(calcDeep(arr));
///
const arr = [1, [8, [[]]], 2, 3, [8, []], 4, 5, []]
function deepsArray(arr) {
let deeps = (!arr.length) ? [0] : arr.map(item => {
if(Array.isArray(item)){
return deepsArray(item)
} else return 0
})
return Math.max(...deeps) + 1
}
console.log(deepsArray(arr))
Currying
Copy function multiply(a) {
return (b) => {
return (c) => {
return a * b * c
}
}
}
console.log(multiply(1)(2)(3)) // 6
To make a function multiplyAll
which takes an array of integers as an argument. This function must return another function, which takes a single integer as an argument and returns a new array.
The returned array should consist of each of the elements from the first array multiplied by the integer.
multiplyAll([1, 2, 3])(2) ======> [2, 4, 6];
Copy function multiplyAll(arr) {
return (number) => {
return arr.map(item => item * number)
}
}
multiplyAll([1, 2, 3])(2)
ΠΠ°ΡΡΠΈΡΠΎΠ²Π°Π½ΠΈΠ΅ sum(a,b) ΡΠ°Π·Π½ΠΎΠ΅ ΠΊΠΎΠ»-Π²ΠΎ ΠΏΠ°ΡΠ°ΠΌΠ΅ΡΡΠΎΠ²
Sport
Remove duplicates from the list
Copy //distinct([1,1,2] => [1,2]
function distinct(arr) {
return Array.from(new Set(arr));
}
or
function removeDuplicates( arr ){
let withoutDuplicatesArray = arr.filter((item, index, array) => array.indexOf(item) == index)
// let withoutDuplicatesArray = arr.filter((item, index, array) => !array.slice(0, index).includes(item))
return withoutDuplicatesArray;
}
console.log(removeDuplicates([1,2,3,3]));
Or
Copy function distinct(arr) {
return a.filter(function(elem, index, arr) {
return index === arr.indexOf(elem);
})
}
Return an array containing the numbers from 1 to N, where N is the parametered value. N will never be less than 1.
If the value is a multiple of 3: use the value 'Fizz' instead
If the value is a multiple of 5: use the value 'Buzz' instead
If the value is a multiple of 3 & 5: use the value 'FizzBuzz' instead
Copy function fizzbuzz(n)
{
let arr = [];
for (let i = 1; i <= n; i ++) {
arr.push(i);
}
let result = arr.map(item => {
// item % 3 === 0 ? 'Fizz' : item
if (item % 3 === 0 && item % 5 === 0) {
return 'FizzBuzz'
} else if (item % 3 === 0){
return 'Fizz'
} else if (item % 5 === 0) {
return 'Buzz'
} else return item
})
return result
}
fizzbuzz(10)
Given a string of words, return the length of the shortest word(s).
Copy function findShort(s){
let result = s.split(' ').filter(item => typeof item === 'string').reduce((shortLenght, currentItem)=>{
currentItem.length < shortLenght ? shortLenght = currentItem.length : shortLenght
return shortLenght
}, 1000);
return result
}
//
function findShort(s){
let result = s.split(' ')
.reduce((shortLength, currentItem) => Math.min(currentItem.length, shortLength), Number.MAX_SAFE_INTEGER);
return result
Square every digit of a number and concatenate them.
For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
Note: The function accepts an integer and returns an integer
Copy function squareDigits(num){
let result = String(num).split('').map(item => Math.pow(item, 2)).join('');
return Number(result)
}
Find The Duplicated Number in a Consecutive Unsorted List
Copy function findDup( arr ){
let duplicateValue = arr
.find((item, index, array) => array.slice(index+1).includes(item))
// or: let duplicateValue = arr
.find((item, index, array) => array.indexOf(item, index + 1) !== -1)
return duplicateValue;
}
Objects
Get output:
Solution:
Copy const input = {
Id: 1,
Name: 'Vasya',
Address: {
City: 'Minsk',
},
Roles: [
{
Id: 1,
Name: 'Admin'
}
]
};
function getKeysAndValues(obj) {
return Object.entries(obj);
}
function getNewKey(oldKey){
return oldKey.replace(oldKey.charAt(0), oldKey.charAt(0).toLowerCase());
}
function makeOutput(obj) {
const output = {};
const arrayForOutput = [];
for ([key, value] of getKeysAndValues(obj)) {
if(Array.isArray(value)){
arrayForOutput.push(makeOutput(value[0]));
output[getNewKey(key)] = arrayForOutput;
} else if(typeof value === 'object'){
output[getNewKey(key)] = makeOutput(value);
} else {
let newKey = getNewKey(key);
output[getNewKey(key)] = value;
}
}
return output
}
console.log(makeOutput(input))
Count all the occurring characters in a string. If you have a string like aba, then the result should be {'a': 2, 'b': 1}.
Copy function count (str) {
let obj = {};
for(let i = 0; i < str.length; i++){
let character = str.charAt(i);
if(obj[character]){
obj[character]++
} else obj[character] = 1;
}
return obj;
}
//
split + reduce
ΠΠ°Π½ ΠΎΠ±ΡΠ΅ΠΊΡ {name: 'ΠΠ΅ΡΡ', 'surname': 'ΠΠ΅ΡΡΠΎΠ²', 'age': '20 Π»Π΅Ρ', }. ΠΠ°ΠΏΠΈΡΠΈΡΠ΅ ΡΠΎΠΎΡΠ²Π΅ΡΡΡΠ²ΡΡΡΠΈΠ΅ Π·Π½Π°ΡΠ΅Π½ΠΈΡ Π² ΠΏΠ΅ΡΠ΅ΠΌΠ΅Π½Π½ΡΠ΅ name, surname ΠΈ age. Π‘Π΄Π΅Π»Π°ΠΉΡΠ΅ ΡΠ°ΠΊ, ΡΡΠΎΠ±Ρ, Π΅ΡΠ»ΠΈ ΠΊΠ°ΠΊΠΎΠ΅-ΡΠΎ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅ Π½Π΅ Π·Π°Π΄Π°Π½ΠΎ - ΠΎΠ½ΠΎ ΠΏΡΠΈΠ½ΠΈΠΌΠ°Π»ΠΎ ΡΠ»Π΅Π΄ΡΡΡΠ΅Π΅ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅ ΠΏΠΎ ΡΠΌΠΎΠ»ΡΠ°Π½ΠΈΡ: {name: 'ΠΠ½ΠΎΠ½ΠΎΠΌ', 'surname': 'ΠΠ½ΠΎΠ½ΠΈΠΌΠΎΠ²ΠΈΡ', 'age': '? Π»Π΅Ρ'}.
detectCollision function
The detectCollision function searches through an array of rectangles and returns the first rectangle that the given point is inside of.
Use destructuring and a higher-order function to make this code cleaner. You might want to use the new array method find, which takes a function as argument, and returns the first element in the array (the element, not its index) for which the function returns true.
Copy //function detectCollision(objects, point) {
// for (let i = 0; i < objects.length; i++) {
// let object = objects[i]
// if (point.x >= object.x && point.x <= object.x + object.width &&
// point.y >= object.y && point.y <= object.y + object.height)
// return object
// }
//}
detectCollision = (array, { x, y }) =>
array.find(({ x: xRect, y: yRect, width: widthRect, height: heightRect }) =>
(x >= xRect &&
x <= xRect + widthRect &&
y >= yRect &&
y <= yRect + heightRect))
const myObjects = [
{x: 10, y: 20, width: 30, height: 30},
{x: -40, y: 20, width: 30, height: 30},
{x: 0, y: 0, width: 10, height: 5}
]
console.log(detectCollision(myObjects, {x: 4, y: 2}));
// console.log(myObjects.find((item, index, arr) => {
// let { x: xRect, y: yRect, width: widthRect, height: heightRect } = item;
// if (x >= xRect && x <= xRect + widthRect &&
// y >= yRect && y <= yRect + heightRect)
// return true
// else return false
// }))
String
Palindrome
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. This includes capital letters, punctuation, and word dividers.
Copy function isPalindrome(line) {
let reverse = String(line).split('').reverse().join('');
return typeof line === 'number' ? Number(reverse) === line : reverse === line
}
Anagram Detection
Note: anagrams are case insensitive
Complete the function to return true
if the two arguments given are anagrams of each other; return false
otherwise.
Copy let isAnagram = function(test, original) {
let originalArray = original.split('');
return originalArray.length === test.split('').length
? test.split('').every(item => originalArray.includes(item.toLowerCase()) || originalArray.includes(item.toUpperCase()))
: false
};
or
Copy let isAnagram = function(test, original) {
return test.toLowerCase().split("").sort().join("") === original.toLowerCase().split("").sort().join("");
};
Reverse
Copy function solution(str){
return str.split('').reverse().join('')
}
Number
Is a number prime?
Copy function isPrime(num) {
let isPrime = true;
if(num <= 1){
return false
}
for(let i = 2; i <= Math.sqrt(num); i++) {
if(num % i === 0){
isPrime = false
}
}
return isPrime
}
console.log(isPrime(2));
Century From Year
Copy function century(year) {
return Math.ceil(year/100)
}
console.log(century(1705), 18)
Node Js
/file?rout=text.txt
ΠΠ°ΠΊ ΠΎΡΠΏΡΠ°Π²ΠΈΡΡ ΡΠ°ΠΉΠ», ΠΊΠΎΡΠΎΡΡΠΉ Π½Π°Ρ
ΠΎΠ΄ΠΈΡΡΡ Π² ΠΏΡΡΠΈ ΡΠΎΡΡΠ°?
TS
To create functions
Π’Π°ΡΠΊΠ° Π½Π°Π΄ΠΎ ΠΎΠΏΡΠ΅Π΄Π΅Π»ΠΈΡΡ ΡΡΠΎ Π² ΡΡΡΠΎΠΊΠ΅ Π²ΡΠ΅ ΡΠΊΠΎΠ±ΠΊΠΈ ΡΡΠΎΡΡ Π²Π°Π»ΠΈΠ΄Π½ΠΎ ΠΈ ΠΏΠΎΠΏΠ°ΡΠ½ΠΎ
fn("(|)") - return true
fn ("{(})") - return false
-------------------------------------------------------------------------------------------------------------------------------------------------------------
ΠΠΎΡΡΠΈΡΠ°ΡΡ ΠΊΠΎΠ»-Π²ΠΎ ΡΠΈΡΡ Π² ΡΠΈΡΠ»Π΅
Copy let numberr = 124535;
console.log(String(numberr).length)
-------------------------------------------------------------------------------------------------------------------------------------------------------------
ΠΠ΅ΡΠ΅ΠΌΠ½ΠΎΠΆΠΈΡΡ ΠΌΠ°ΡΡΠΈΠ² ΡΠΈΡΠ΅Π» (ΠΊΠΎΠ»-Π²ΠΎ ΠΌΠΎΠΆΠ΅Ρ ΠΎΡΠ»ΠΈΡΠ°ΡΡΡΡ)
Copy function fn(...arg) {
return arg.reduce((acc, currentItem) => {
acc *= currentItem;
return acc
}, 1);
}
// OR:
function fn() {
return [...arguments].reduce((acc, currentItem) => {
acc *= currentItem;
return acc
}, 1);
}
let result = fn(1,2,3)
console.log(result);
-------------------------------------------------------------------------------------------------------------------------------------------------------------
Π‘ΡΡΠΎΠΊΠ° ΡΠΎ ΡΠ»ΠΎΠ²Π°ΠΌΠΈ. ΠΡΠ²Π΅ΡΡΠΈ ΠΌΠ°ΡΡΠΈΠ² ΡΠΎ ΡΠ»ΠΎΠ²Π°ΠΌΠΈ Ρ Π±ΠΎΠ»ΡΡΠΎΠΉ Π±ΡΠΊΠ²Ρ + ΡΡΡΠΎΠΊΡ Ρ ΠΏΠ΅ΡΠ²ΡΠΌΠΈ Π±ΡΠΊΠ²Π°ΠΌΠΈ ΡΡΠΈΡ
ΡΠ»ΠΎΠ²
Copy let words = 'First two Thrird Forth';
//let newArray = words.split(' ').filter(item => item.charAt(0) === item.charAt(0).toUpperCase());
let newArray = words.split(' ').filter(item => item.match(/^[A-Z]/));
let newArray2 = words.split(' ').filter(item => item.substr(0,1).match(/[A-Z]/)).map(item => item.charAt(0)).join(',')
console.log(newArray1);
console.log(newArray2);
----------------------------------------------------------------------------------------------------------------------------------------------------------------