Skip to content

Instantly share code, notes, and snippets.

View YozhEzhi's full-sized avatar

Alexandr Zhidovlenko YozhEzhi

  • Sportmaster Lab
  • Saint-Petersburg, Russia
View GitHub Profile
/**
* Factory Functions.
*/
/*
* ES6 class vs Factory function:
* With class -- Be wary
*/
class Dog {
constructor() {
this.sound = 'woof';
@YozhEzhi
YozhEzhi / remarks.md
Last active July 21, 2020 20:27
[Заметки] JS

В JavaScript используется интересный подход к работе с необъявленными переменными.

Обращение к такой переменной создаёт новую переменную в глобальном объекте. В случае с браузерами, глобальным объектом является window. Рассмотрим такую конструкцию:

function foo(arg) {
    bar = "some text";
}
Array.apply(null, {length: 20}).map(Number.call, Number)
// -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
// Данный код будет работать некорректно без точек с запятыми:
function getN() {
return 2
}
var a = getN()
(function(){
return 6
})()
@YozhEzhi
YozhEzhi / loop.js
Last active May 19, 2020 20:49
Remove files by name.
const fs = require('fs');
const path = require('path');
const updateFile = filename => {
const search = "postcss 'src/**/*.css' -d ./build --base src/";
const shouldBe =
"postcss 'src/**/*.css' -d ./build --base src/ --config '../../postcss.config.js'";
fs.readFile(filename, 'utf8', (err, data) => {
if (err) {
@YozhEzhi
YozhEzhi / cats.md
Last active February 19, 2024 20:06
[Конспект] Дж.Ханк Рейнвотер - Как пасти котов. Наставление для программистов, руководящих другими программистами
@YozhEzhi
YozhEzhi / Singleton.ts
Last active September 17, 2019 21:19
Singleton in Typescript
class Singleton {
private static instance: Singleton;
private constructor() {
// do something construct...
}
static getInstance() {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
@YozhEzhi
YozhEzhi / remarks.md
Last active November 1, 2018 10:39
Максим Горький

"...Как много человек тратит на борьбу с мелочами. Если б нас не одолевали гнусные черви мелких будничных зол, - мы легко раздавили бы страшных змей наших несчастий." [Ирония]

"Истинное призвание каждого из нас - установлять правила поведения для наших ближних, и несправедливы те проповедники, которые упрекают нас в эгоизме, ибо в бескорыстном стремлении видеть людей лучшими мы всегда забываем о себе." [Ирония]

"Есть же люди, для которых самым ценным и лучшим в жизни является какая-нибудь болезнь их души или тела. Они носятся с ней все время жизни и лишь ею живы; страдая от нее, они питают себя ею, они на нее жалуются другим и этим обращают на себя внимание ближних. За это взимают с людей сочувствие себе, и, кроме этого, — у них нет ничего. Отнимите у них эту болезнь, вылечите их, и они будут несчастны, потому что лишатся единственного средства к жизни, — они станут пусты тогда. Иногда жизнь человека бывает до того бедна, что он невольно принужден ценить свой порок и им жить; и можно сказать, что часто люди

@YozhEzhi
YozhEzhi / AVLTree.md
Created September 19, 2018 09:06
Алгоритмы. AVL деревья. (AVL Tree)

http://btholt.github.io/four-semesters-of-cs/img/avl.gif

AVL tree are the answer to the problem that BST have: BST can easily get out of balance. Even if it's not the worst case scenario of ascending or descending lists being added, even a random distribution on numbers on a BST is going to pretty heavy in places. There are several ways to balance these trees and we're going to tackle one of them: AVL trees. AVL is the initials of its authors: Georgy Adelson-Velsky and Evgenii Landis.

AVLs are specialized BSTs. That is to say a valid AVL tree is always a valid BST (but not necessarily vice versa.) When you add a new value to a AVL tree, you do it the same way. The only difference is on the way up your recursive calls you check to see if the node is balanced after you added the new node. A tree is out of balance if its subtrees' difference of heights is greater than one.

![http://btholt.github.io/four-semesters-of-cs/img/avl2.gif](http://btholt.gi

@YozhEzhi
YozhEzhi / binaryTree.md
Last active September 19, 2018 08:27
Алгоритмы. Бинарные деревья.

http://btholt.github.io/four-semesters-of-cs/img/bst.png

Демо: https://codepen.io/YozhEzhi/pen/oPJggP

Trees cans be a useful structure for a middle ground between LinkedLists and ArrayLists. We're going to look a simple flavor of trees: the trusty binary search tree. The gist of the BST is that a node in a BST has zero, one, or two subtrees. Every element in the left subtree is lesser than the value of the node and every node in the right is greater. By being able to depend on this fact, it makes it very simple to add and find new elements. Like LinkedLists, we just have to change pointers when we add new elements. Let's step through an add.

Current Tree:

      10