Skip to content

Instantly share code, notes, and snippets.

View G-MontaG's full-sized avatar

Artur Osypenko G-MontaG

  • Bynder
  • Netherlands
View GitHub Profile
@G-MontaG
G-MontaG / backwardsPath.js
Created March 7, 2020 12:13
DOM tree search
function backwardsPath(element, root) {
const path = [];
let current = element;
while (current.parentNode) {
const index = [...current.parentNode.children].indexOf(current);
path.push(index);
current = parentNode;
}
@G-MontaG
G-MontaG / throttle.js
Created March 7, 2020 11:51
Throttle function
function throttle(fn, time, ...args) {
let id;
return function() {
if (id) return;
id = setTimeout(() => {
fn.apply(this, args);
id = null;
}, time);
}
}
@G-MontaG
G-MontaG / debounce.js
Created March 7, 2020 11:46
Debounce function
function debounce(fn, time, ...args) {
let id;
return function() {
if (id) clearTimeout(id);
id = setTimeout(() => {
fn.apply(this, args);
id = null;
}, time);
}
}
@G-MontaG
G-MontaG / bind.js
Last active March 7, 2020 11:46
Implementation of native bind
function bind(fn, context, ...args) {
return function() {
return fn.apply(context, args);
}
}
const foo = function (param) {
console.log('Context:', this.bar);
console.log('Params:', param);
}
@G-MontaG
G-MontaG / flatten.js
Created March 1, 2020 19:56
Flattening an array
function flatten(arr) {
return arr.reduce((acc, item) => {
if (Array.isArray(item)) {
acc = acc.concat(flatten(item));
} else {
acc.push(item);
}
return acc;
}, []);
}
@G-MontaG
G-MontaG / removeDuplicateWithCaseSensitive.js
Created February 23, 2020 11:38
Remove duplicate strings with case sensitive
function removeDuplicateWithCaseSensitive(string) {
const arrayOfWords = string.split(' ');
const mapOfWords = {};
return arrayOfWords.reduce((newString, word) => {
const lowerCasedWord = word.toLowerCase();
if (mapOfWords[lowerCasedWord]) return newString;
mapOfWords[lowerCasedWord] = word;
return `${newString} ${word}`;
}, '');
}
@G-MontaG
G-MontaG / removeDuplicates.js
Last active February 23, 2020 11:40
Removing duplicate strings
function removeDuplicates(string) {
const arrayOfWords = string.split(' ');
const mapOfWords = {};
return arrayOfWords.reduce((newString, word) => {
if (mapOfWords[word]) return newString;
mapOfWords[word] = true;
return `${newString} ${word}`;
});
}
@G-MontaG
G-MontaG / index.js
Created February 23, 2020 10:32
Reimplement lodash without
// reimplemented pull
const without = (arr, ...values) => {
return arr.filter((item) => {
return values.indexOf(item) < 0;
});
};
const arr = ['a', 'b', 'c', 'a', 'b', 'c'];
console.log('Lodash pull: ', _.without(['a', 'b', 'c', 'a', 'b', 'c'], 'a', 'c'));