Skip to content

Instantly share code, notes, and snippets.

const factorial = trampoline(function _factorial(n, acc = 1) {
if (n <= 1) return acc;
return () => _factorial(n - 1, n * acc);
});
console.log(factorial(5));
function trampoline(f) {
return function trampolined(...args) {
let result = f.bind(null, ...args);
while (typeof result === 'function') result = result();
return result;
};
}
function traverseDOM(tree) {
if (isLeaf(tree)) tree.className = 'leaf';
else for (const leaf of tree.childNodes) traverseDOM(leaf);
}
function recursiveFn(n) {
if (n < 0) return true;
recursiveFn(n - 1);
}
recursiveFn(100000); // RangeError: Maximum call stack size exceeded
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
const Modal = ({children}) => <div className='Modal'>
{children}
</div>;
const App = () => {
const [showModal, setShowModal] = useState(false);
const handleKeyup = e => e.keyCode === 27 && setShowModal(false);
const toggleModal = () => setShowModal(!showModal);
useEffect(() => {
if (showModal) window.addEventListener('keyup', handleKeyup);
return () => window.removeEventListener('keyup', handleKeyup);
});
return <div onClick={toggleModal} className="App">
.Modal {
/* fixed position will always show modal in the top left corner */
position: fixed;
top: 0;
left: 0;
/* z-index to show modal even if it is used before some other elements */
z-index: 5;
/* make modal fill whole window */
width: 100vw;
height: 100vh;
for (const el of array) {
// do something here
}
Array.prototype.forEach(el => {
// do something here
});