Adapter
ary
Creates a function that accepts up to n arguments, ignoring any additional arguments.
Call the provided function, fn, with up to n arguments, using Array.slice(0,n) and the spread operator (...).
const ary = (fn, n) => (...args) => fn(...args.slice(0, n)); + }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Adapter
ary
Creates a function that accepts up to
narguments, ignoring any additional arguments.Call the provided function,
fn, with up tonarguments, usingArray.slice(0,n)and the spread operator (...).const ary = (fn, n) => (...args) => fn(...args.slice(0, n));const firstTwoMax = ary(Math.max, 2); [[2, 6, 'a'], [8, 4, 6], [10]].map(x => firstTwoMax(...x)); // [6, 8, 10]call
Given a key and a set of arguments, call them when given a context. Primarily useful in composition.
Use a closure to call a stored key with stored arguments.
const call = (key, ...args) => context => context[key](...args); @@ -800,6 +800,12 @@ document.bodyShow examplessetStyle(document.querySelector('p'), 'font-size', '20px'); // The first <p> element on the page will have a font-size of 20pxshow
Shows all the elements specified.
Use the spread operator (
...) andArray.forEach()to clear thedisplayproperty for each element specified.const show = (...el) => [...el].forEach(e => (e.style.display = ''));show(...document.querySelectorAll('img')); // Shows all <img> elements on the page +smoothScroll
Smoothly scrolls the element on which it's called into the visible area of the browser window.
Use
.scrollIntoViewmethod to scroll the element. Pass{ behavior: 'smooth' }to.scrollIntoViewso it scrolls smoothly.const smoothScroll = element => + document.querySelector(element).scrollIntoView({ + behavior: 'smooth' + }); +smoothScroll('#fooBar'); // scrolls smoothly to the element with the id fooBar +smoothScroll('.fooBar'); // scrolls smoothly to the first element with a class of fooBartoggleClass
Toggle a class for an element.
Use
element.classList.toggle()to toggle the specified class for the element.const toggleClass = (el, className) => el.classList.toggle(className);toggleClass(document.querySelector('p.special'), 'special'); // The paragraph will not have the 'special' class anymoreUUIDGeneratorBrowser
Generates a UUID in a browser.
Use
cryptoAPI to generate a UUID, compliant with RFC4122 version 4.const UUIDGeneratorBrowser = () => diff --git a/snippets/smoothScroll.md b/snippets/smoothScroll.md index de024bf68..c3e045ab7 100644 --- a/snippets/smoothScroll.md +++ b/snippets/smoothScroll.md @@ -8,7 +8,7 @@ Pass `{ behavior: 'smooth' }` to `.scrollIntoView` so it scrolls smoothly. ```js const smoothScroll = element => document.querySelector(element).scrollIntoView({ - behavior: 'smooth' + behavior: 'smooth' }); ```