Skip to content

Instantly share code, notes, and snippets.

View batogov's full-sized avatar

Dmitrii Batogov batogov

View GitHub Profile
@batogov
batogov / template.js
Created October 4, 2017 15:39
Template
const getElementFromTemplate = (template) => {
const container = document.createElement('template');
container.innerHTML = template;
// В этом месте функция неявно вернёт DocumentFragment,
// который при добавлении в DOM исчезает, а вместо него
// вставляются его дети.
return container.content;
}
@batogov
batogov / oloo.js
Created October 1, 2017 19:53
Использование "OLOO" (objects-linked-to-other-objects) стиля
/* POINT */
var Point = {
init: function(x, y) {
this.x = x;
this.y = y;
},
move: function(deltaX, deltaY) {
this.x += deltaX;
this.y += deltaY;
@batogov
batogov / prototypes.js
Created October 1, 2017 16:21
Prototypes
/* POINT */
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.move = function(deltaX, deltaY) {
this.x += deltaX;
this.y += deltaY;
@batogov
batogov / count-rotations.js
Created October 1, 2017 09:54
Поиск количества разворотов массива
/*
Поиск количества разворотов массива за O(n)
*/
function countRotations(arr) {
var min = arr[0], minIndex = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
minIndex = i;
}
@batogov
batogov / object-create-polyfill.js
Last active July 15, 2023 20:43
Simplest polyfill for Object.create()
if (!Object.create) {
Object.create = function(o) {
function F() {}
F.prototype = o;
return new F();
};
}
@batogov
batogov / task.js
Created September 29, 2017 18:51
Задачка на асинхронность
var order = ['A', 'B', 'C'];
var memory = [];
function worker() {
// Находим в памяти индекс нужного нам по порядку значения
var i = memory.findIndex(function(curr) {
return order[0] === curr;
});
// Если оно есть
@batogov
batogov / knapsack-problem.js
Created September 26, 2017 18:47
Knapsack Problem
function comp(firstItem, secondItem) {
const firstCoeff = firstItem['value'] / firstItem['weight'];
const secondCoeff = secondItem['value'] / secondItem['weight'];
return secondCoeff - firstCoeff;
}
function knapsack(w, items) {
let result = [];
items = items.sort(comp);
@batogov
batogov / atm.js
Created September 26, 2017 17:08
ATM
function comp(a, b) {
return b - a;
}
function atm(total, values) {
values = values.sort(comp);
let counts = {};
let success = true;
@batogov
batogov / is-balanced.js
Created September 25, 2017 18:02
Is Balanced
function isBalanced(expr) {
let stack = [];
for (let i = 0, length = expr.length; i < length; i++) {
if (expr[i] === '{') {
stack.push(expr[i]);
} else if (expr[i] === '}') {
if (stack.length > 0) {
stack.pop();
} else {
@batogov
batogov / is-palindrome.js
Created September 25, 2017 17:50
Palindrome
function isPalindrome(str) {
str = str.toLowerCase().replace(/\s/g, '');
return str === str.split('').reverse().join('');
}
function isPalindromeWithoutReverse(str) {
str = str.toLowerCase().replace(/\s/g, '');
let result = true;
let l = 0;