Skip to content

Instantly share code, notes, and snippets.

@johanquiroga
Last active April 20, 2021 22:46
Show Gist options
  • Save johanquiroga/48a7f647b513f2a97fe12c9fa37ed8fe to your computer and use it in GitHub Desktop.
Save johanquiroga/48a7f647b513f2a97fe12c9fa37ed8fe to your computer and use it in GitHub Desktop.
/** REMOVE DUPLICATES */
// BigO = n^2
// function removeDuplicates(str) {
// const words = str.split(' ');
// const filteredWords = words.filter((word, i, list) => list.indexOf(word) === i)
// return filteredWords.join(' ');
// }
// BigO = n
// function removeDuplicates(str) {
// const words = str.split(' ');
// const table = {}
// const filteredString = words.reduce((currentStr, nextWord) => {
// if (!table[nextWord]) {
// table[nextWord] = true;
// return `${currentStr} ${nextWord}`
// }
// return currentStr
// }, '')
// return filteredString;
// }
function removeDuplicates(str) {
const words = str.split(" ");
const wordsSet = new Set(words);
return [...wordsSet].join(" ");
}
console.log(removeDuplicates("this is is a test test string"));
/** FLATTEN ARRAY */
function flatten(arr) {
const newArr = [];
for (const item of arr) {
if (Array.isArray(item)) {
const flatArr = flatten(item);
newArr.push(...flatArr);
} else {
newArr.push(item);
}
}
return newArr;
}
console.log(flatten([1, 2, 3, [4], [[5, 6], [7]]]));
/** IMPLEMENT `Function.prototype.bind()` */
Function.prototype.bind = function bind(ctx) {
// return (...args) => this.apply(ctx, args);
// const fn = this;
// return function() {
// fn.apply(ctx, arguments)
// }
return (...args) => this.call(ctx, ...args);
};
const foo = function () {
console.log(this.bar);
};
let baz = foo.bind({ bar: "hello" });
baz(); // Hello
/** IMPLEMENT `debounce` */
function debounce(fn, time) {
let timeout;
return (...args) => {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
console.log("executing");
timeout = null;
fn(...args);
}, time);
};
}
function throttle(fn, time) {
let timeout;
return (...args) => {
if (timeout) {
return;
}
timeout = setTimeout(() => {
console.log("executing");
timeout = null;
fn(...args);
}, time);
};
}
// UNCOMMENT THESE TO TEST YOUR WORK!
function giveHi() {
return "hi";
}
const giveHiSometimes = debounce(giveHi, 3000);
console.log(giveHiSometimes()); // -> 'hi'
setTimeout(function () {
console.log(giveHiSometimes());
}, 2000); // -> undefined
setTimeout(function () {
console.log(giveHiSometimes());
}, 4000); // -> undefined
setTimeout(function () {
console.log(giveHiSometimes());
}, 8000); // -> 'hi'
/** TREES */
/**
* @typedef {Object} TreeNode
* @property {?TreeNode} parent
* @property {TreeNode[]} children
*/
/**
*
* @param {TreeNode} element
* @param {TreeNode} root
* @returns
*/
function reversePath(element, root) {
/** @type {number[]} */
const path = [];
let pointer = element;
while (pointer.parent) {
path.push(pointer.parent.children.indexOf(pointer));
pointer = pointer.parent;
}
// /** @type {TreeNode} */
// const otherElement = path.reverse().reduce((node, childIndex) => {
// return node.children[childIndex];
// }, root);
pointer = root;
while (path.length) {
pointer = pointer.children[path.pop()];
}
return pointer;
}
/** RENDERING: MOVE ELEMENT */
/**
*
* @param {number} duration
* @param {number} distance
* @param {HTMLElement} element
*/
function moveElement(duration, distance, element) {
const start = performance.now();
function move(currentTime) {
const elapsed = currentTime - start;
const progress = elapsed / duration;
const amountToMove = progress * distance;
element.style.transform = `translateX(${amountToMove}px)`;
if (amountToMove < distance) {
requestAnimationFrame(move);
}
}
requestAnimationFrame(move);
}
/** PROMISES */
function promisify(fn) {
return function (...args) {
return new Promise((resolve, reject) => {
function cb(err, result) {
if (err) return reject(err);
resolve(result);
}
fn.apply(this, args.concat(cb));
});
};
}
function sleep(time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
/** PARTIAL APPLICATION */
function partial(fn, ...partialArgs) {
return function (...args) {
return fn.apply(this, [...partialArgs, ...args]);
};
}
// function partial(fn, ...partialArgs) {
// return fn.bind(this, ...partialArgs)
// }
function addAllTheThings() {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
const addOne = partial(addAllTheThings, 1);
console.log(addOne()); // 1
console.log(addOne(2)); // 3
console.log(addOne(2, 3)); // 6
console.log(addOne(4, 9, 16, 25)); // 55
/** CURRYING */
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
}
return function (...args2) {
return curried.apply(this, [...args, ...args2]);
};
};
}
function sum(a, b, c) {
return a + b + c;
}
let curriedSum = curry(sum);
console.log(curriedSum(1, 2, 3)); // 6, still callable normally
console.log(curriedSum(1)(2, 3)); // 6, currying of 1st arg
console.log(curriedSum(1)(2)(3)); // 6, full currying
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment