Skip to content

Instantly share code, notes, and snippets.

@edtoken
Last active April 20, 2024 19:14
Show Gist options
  • Star 44 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save edtoken/fec7a606a3eecca1954405075db951af to your computer and use it in GitHub Desktop.
Save edtoken/fec7a606a3eecca1954405075db951af to your computer and use it in GitHub Desktop.
Javascript Russian Knowledge NOTE

OUTDATED

This this super outdated, see v2 here

Posts

https://egghead.io/
https://github.com/trekhleb/javascript-algorithms
https://habr.com/post/359192/ алгоритмы на js все
https://www.youtube.com/watch?v=j4_9BZezSUA event loop
https://fseby.wordpress.com/2016/02/25/практическая-вводная-в-монады-в-javascript/
https://habrahabr.ru/company/mailru/blog/327522/   (Функциональное программирование в JavaScript с практическими примерами)
https://habrahabr.ru/post/298134/ (FizzBuzz, или почему программисты не умеют программировать)     http://dmitrysoshnikov.com/ecmascript/javascript-the-core-2nd-edition-rus/ (всякое общее)
https://medium.com/@frontman/приведение-типов-в-js-9d6f1845ea96   (приведение типов и др. инфа)   https://ru.wikipedia.org/wiki/Шаблон_проектирования           http://prt56.ru/kak-proisxodit-zagruzka-stranic-sajtov/ (как происходит получение страницы)
https://habrahabr.ru/post/262239/ (критический путь рендера)
https://habrahabr.ru/post/243819 (За один проход)
https://habrahabr.ru/post/171359 (10 странностей и секретов JavaScript)
https://habrahabr.ru/post/132472 (JavaScript паттерны… для чайников)
https://habrahabr.ru/post/196560 (Введение в анализ сложности алгоритмов)
https://habrahabr.ru/company/ruvds/blog/337662 (Асинхрощина)
https://tproger.ru/articles/computational-complexity-explained (Оценка сложности алгоритмов)

https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/Operator_Precedence приоритет операторов

https://github.com/getify/You-Dont-Know-JS/tree/master/scope%20%26%20closures
https://github.com/getify/You-Dont-Know-JS/blob/master/types%20%26%20grammar/ch4.md
https://github.com/getify/You-Dont-Know-JS/blob/master/types%20&%20grammar/README.md#you-dont-know-js-types--grammar

https://gist.github.com/edtoken/85cd8d10b395567c5494b5a2ab636351 немного простых вопросов, вспомнить

https://github.com/h5bp/Front-end-Developer-Interview-Questions
https://github.com/utatti/Front-end-Developer-Interview-Questions-And-Answers
https://github.com/h5bp/Front-end-Developer-Interview-Questions/tree/master/Translations/Russian https://github.com/khan4019/front-end-Interview-Questions

https://learn.javascript.ru/types-conversion Преобразование типов для примитивов

Code examples

Cинглтон

https://gist.github.com/edtoken/83cdfe9c1f9e6a995cd1e815213baaee

// // USING:
// // Module.js
// import Singleton from './Singleton';
// export default Singleton(() => {
// 	// logic...
// 	return new YourClass.apply(this, arguments);
// });
//
// // app.js
// import Module from './Module';
// const obj = Module.inst();
//
// // other.js
// import Module from './Module';
// const obj = Module.inst();

// Singleton.js
export const Singleton = (callBackObjectCreate) => {
	return (function() {
		let instance = undefined;

		function createInstance() {
			instance = callBackObjectCreate();
		}

		return {
			inst: function() {
				if (!instance) {
					createInstance();
				}
				return instance;
			}
		};
	})();
};
Make uniq prefixes

https://gist.github.com/edtoken/b0ab698208038f3fed36fc220a96c076

const uniqPrefix = (() => {
	let START_UNIQ_PREFIX = 0
  const uniq = () => {}
  uniq.toString = uniq.valueOf = () => {
    START_UNIQ_PREFIX += 1
    return `uniq${START_UNIQ_PREFIX}`
  }
  return uniq
})()

console.log('uniqPrefix', uniqPrefix)
Переместить все нули в конец, линейно по памяти O(n) сложность

https://gist.github.com/edtoken/564234f5c8405cdd9bdfe342fcf2cc77

function moveZeros(array) {
    let i = 0;
    let len = array.length;
    let s = undefined;
    let e = undefined;
    
    while(i < len){

        if(!array[i]){
            if(s == undefined){
                s = i;
                e = i;
            }else{
                e = i;
            }
            
            i++;
            continue;
        }
        
        if(s != undefined){
            array[s] = array[i];
            array[i] = 0;
            i--;
            
            if(s < e){
                s ++;
            }else{
                s = undefined;
                e = undefined;
            }
        }
        
        i++;
    }

    return array;
}

alert(moveZeros([0,1,4,0,0,0,2,2,2,2,2,0,0,10]))
Реализация паралельных ajax запросов со стеком

https://gist.github.com/edtoken/4b43fb55d9b9fc5798b04a1c0dffcbe0

const call = (function() {
  const maxParallelCalls = 5;
  let activeCalls = 0;
  let requestsStack = [];

  // outside promise proxy
  const Defer = function() {
    this.promise = new Promise((resolve, reject) => {
      this.resolve = resolve;
      this.reject = reject;
    });
  };

  // your library async call
  const axiosCall = data => {
    return new Promise((resolve, reject) => {
      console.log("start", data.path);

      setTimeout(() => {
        resolve([data.path, data.start, new Date()]);

        // handle new calls from stack
        activeCalls -= 1;
        handle();
      }, 0.1 + Math.random() * (4 + 1 - 0.1));
    });
  };

  // handler - make new requests
  const handle = () => {
    if (activeCalls >= maxParallelCalls) {
      return;
    }

    while (activeCalls < maxParallelCalls && requestsStack.length) {
      activeCalls += 1;
      const data = requestsStack.shift();
      axiosCall(data).then(r => data.defer.resolve(r));
    }
  };

  return function(type, path, query, body) {
    const data = {
      type,
      path,
      query,
      body,
      defer: new Defer(),
      created: new Date()
    };

    requestsStack.push(data);
    handle();
    return data.defer.promise;
  };
})();

const get = (path, query) => {
  return call("get", path, query);
};

const post = (path, query, body) => {
  return call("post", path, query, body);
};

let c = 50;
while (c) {
  c -= 1;
  get(`api/user/${c}`).then(resp => {
    console.log("FINALLY SUCCESS", resp[0]);
  });
}
какой-то парень делал тестовое для яндекса

https://github.com/JorJeG/entrance-task-2

попробовать ката

https://www.codewars.com/kata/will-it-balance/train/python
https://www.codewars.com/kata/fizz-slash-buzz/train/javascript

пример небольшой верстки (фильмы)

https://jsfiddle.net/3pgp8n51/1/

какие-то задачки

https://github.com/skoloney/practice-1/blob/master/README.md

Google queries and tips :)

event loop
приоритет обработки операторов (преобразование [] + {}) https://habrahabr.ru/post/159313/#comment_5461903
Асинхронная проверка дом узлов и валидация контента к них
Hеализация параллельных запросов
Асинхрощина
Как работают сравнения в javascript
Преобразование к примитиву
Задача с полиндром
Замыкания
Как работает this
Наследования по старинке
Object.create
proto
Задача с банкоматом
полиндром с знаками препинания
localstorage || sessionstorage
пайп оператор

x |> f = f x
f <| x = f x

Other tasks

func1
/** нужно чтобы выполнился console.log(), код функции модифицировать запрещено **/
(function accountant(){
	const balance = [1,2,3,4,5]
	let sum = 0
	for(const next of balance){
		sum += next
	}
	if(isNaN(sum) || sum !== 15){
		throw new Error(`Error`)
	}
	console.log(`YEAH`)
})()
func2
/** console.log() должен сработать, модифицировать после if(this !== 1) (включительно) запрещено **/
(function isNumberOne(one){
	function numberOne(){
		if(this !== 1){
			throw new Error(`Error`)
		}else {
			console.log('SUCCESS')
		}
	}
	numberOne.call(one)
})(1)

Dirty source

https://www.npmjs.com/package/redux-symbiote

@edtoken
Copy link
Author

edtoken commented Sep 24, 2018

todo: Надо добавить микро и макро таски

@edtoken
Copy link
Author

edtoken commented Jun 14, 2019

TODO: привести док в порядок

@edtoken
Copy link
Author

edtoken commented Jun 14, 2019

@edtoken
Copy link
Author

edtoken commented Apr 20, 2024

See v2 here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment