Skip to content

Instantly share code, notes, and snippets.

View batogov's full-sized avatar

Dmitrii Batogov batogov

View GitHub Profile
@batogov
batogov / currying.js
Last active May 11, 2019 14:11
Currying [JavaScript]
// Каррирование в JavaScript
function curry(fn) {
// Запоминаем количество аргументов
var arity = fn.length;
return function f1(...args) {
if (args.length >= arity) {
return fn(...args);
} else {
@batogov
batogov / quicksort.js
Created August 21, 2017 08:53
QuickSort [JavaScript]
function swap(arr, firstIndex, secondIndex) {
const buf = arr[firstIndex];
arr[firstIndex] = arr[secondIndex];
arr[secondIndex] = buf;
}
function partition(arr, left, right) {
let pivot = arr[Math.floor((right + left) / 2)],
i = left,
j = right;
@batogov
batogov / tree.js
Created September 14, 2017 13:00
Tree [JavaScript]
function Node(data) {
this.data = data;
this.parent = null;
this.children = [];
}
function Tree(data) {
var node = new Node(data);
this._root = node;
}
@batogov
batogov / bind.js
Last active September 29, 2017 19:12
Custom bind [JavaScript]
// В виде функции
function bind(func, context) {
return function() {
return func.apply(context, arguments);
};
}
// В виде полифилла
if (!Function.prototype.bind) {
Function.prototype.bind = function(context) {
@batogov
batogov / map-reduce.js
Created September 17, 2017 20:52
Map and reduce
a = [1, 2, 3, 4];
/*
Реализовать map через reduce.
Внимание! Если initialValue передано, то на первой итерации функция будет вызвана с
этим значением и значением первого элемента массива. Если же initialValue не передано,
то функция будет вызвана со значениями первого и второго элементов массива. Отсюда также
следует, что если начальное значение не передано, то функция вызывается на один раз меньше,
иначе ровно столько раз, сколько элементов в массиве.
@batogov
batogov / task.js
Created September 20, 2017 13:38
Наибольшее произведение
var unsortedArray = [-10, 7, 29, 30, 5, -10, -70];
computeProduct(unsortedArray);
/*
Сортирующая функция. Если её не передать методу sort, то элементы
сортируются путём преобразования их в строки и сравнения строк.
*/
function sortIntegers(a, b) {
return a - b;
@batogov
batogov / main.js
Last active October 2, 2017 11:12
Custom constructor
/*
Кастомный оператор new. Принимает функцию-конструктор и её аргументы.
Возвращает инстанс класса.
*/
function newOperator(constr, args) {
// Создаём объект через Object.create (он наследуется от прототипа конструктора)
// Конструктор не вызывается!
var thisValue = Object.create(constr.prototype);
// Вызывает конструктор, указав в качестве this созданный объект
@batogov
batogov / main.js
Created September 22, 2017 13:16
Process Template
function processTemp(tempString, dataObject) {
for(var key in dataObject) {
if (dataObject.hasOwnProperty(key)) {
tempString = tempString.replace(new RegExp('{' + key + '}', 'g'), dataObject[key]);
}
}
return tempString;
}
var str = 'Hello {name}';
@batogov
batogov / main.js
Created September 23, 2017 10:58
Make Array Flat Again!
var result = [];
function flatten(val) {
if (Array.isArray(val)) {
for (var i = 0; i < val.length; i++) {
flatten(val[i]);
}
} else {
result.push(val);
}
@batogov
batogov / main.js
Created September 24, 2017 19:55
Sort odd and even
var magicSort = function(arr) {
var temp = 0;
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr.length - 2; j++) {
if (j % 2 === 0 && arr[j] < arr[j + 2]) {
temp = arr[j];
arr[j] = arr[j + 2];
arr[j + 2] = temp;
} else if (j % 2 === 1 && arr[j] > arr[j + 2]) {