Tasks

Π·Π°ΠΌΡ‹ΠΊΠ°Π½ΠΈΠ΅

function closure() {
  let count = 0;
  
  return function coun1t() {
    return count++;
  }
}

let count1 = closure();
console.log(count1());
console.log(count1());
console.log(count1());

debounce

function debounce(f, ms) {
	let isCooldown = false;
	return (...args) => {
		if (isCooldown) return;
		f.apply(this, args);
		isCooldown = true;
		setTimeout(() => isCooldown = false, ms);
	};
}

bubble sort

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

[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, index, array) {
  return accumulator + currentValue;
}, 10);

random min man

function randomNumber(min, max) {
  return Math.random() * (max - min) + min;
}

Redux

createStore(redux)

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

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

function insertAfter(referenceNode, newNode) {
  referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

querystring /queryparams

{
	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

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

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

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];

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

//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

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

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).

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

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

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:

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}.

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.

//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.

function isPalindrome(line) {
  let reverse = String(line).split('').reverse().join('');
  return typeof line === 'number' ? Number(reverse) === line : reverse === line
}

Anagram Detection

An anagram is the result of rearranging the letters of a word to produce a new word (see wikipedia).

Note: anagrams are case insensitive

Complete the function to return true if the two arguments given are anagrams of each other; return false otherwise.

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

let isAnagram = function(test, original) {
  return test.toLowerCase().split("").sort().join("") === original.toLowerCase().split("").sort().join("");
};

Reverse

function solution(str){
  return str.split('').reverse().join('')
}

Number

Is a number prime?

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

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

-------------------------------------------------------------------------------------------------------------------------------------------------------------

ΠŸΠΎΡΡ‡ΠΈΡ‚Π°Ρ‚ΡŒ ΠΊΠΎΠ»-Π²ΠΎ Ρ†ΠΈΡ„Ρ€ Π² числС

let numberr = 124535;

console.log(String(numberr).length)

-------------------------------------------------------------------------------------------------------------------------------------------------------------

ΠŸΠ΅Ρ€Π΅ΠΌΠ½ΠΎΠΆΠΈΡ‚ΡŒ массив чисСл (ΠΊΠΎΠ»-Π²ΠΎ ΠΌΠΎΠΆΠ΅Ρ‚ ΠΎΡ‚Π»ΠΈΡ‡Π°Ρ‚ΡŒΡΡ)

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);

-------------------------------------------------------------------------------------------------------------------------------------------------------------

Π‘Ρ‚Ρ€ΠΎΠΊΠ° со словами. ВывСсти массив со словами с большой Π±ΡƒΠΊΠ²Ρ‹ + строку с ΠΏΠ΅Ρ€Π²Ρ‹ΠΌΠΈ Π±ΡƒΠΊΠ²Π°ΠΌΠΈ этих слов

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);

----------------------------------------------------------------------------------------------------------------------------------------------------------------

Last updated