2023년 12월 26일 화요일

modern javascript snippets

 

1. How to get the base URL?

const getBaseURL = url => url.replace(/[?#].*$/, '');

getBaseURL('http://url.com/page?name=Adam&surname=Smith');
// 'http://url.com/page'

2. How to check if the URL is absolute?

const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);

isAbsoluteURL('https://google.com'); // true
isAbsoluteURL('ftp://www.myserver.net'); // true
isAbsoluteURL('/foo/bar'); // false

3. How to get URL parameters as object?

const getURLParameters = url =>
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) => (
(a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a
),
{}
);

getURLParameters('google.com'); // {}
getURLParameters('http://url.com/page?name=Adam&surname=Smith');
// {name: 'Adam', surname: 'Smith'}

4. How to check if the element contains another element?

const elementContains = (parent, child) =>
parent !== child && parent.contains(child);

elementContains(
document.querySelector('head'),
document.querySelector('title')
);
// true
elementContains(document.querySelector('body'), document.querySelector('body'));

5. How to get all the ancestors of the element?

const getAncestors = el => {
let ancestors = [];
while (el) {
ancestors.unshift(el);
el = el.parentNode;
}
return ancestors;
};

getAncestors(document.querySelector('nav'));
// [document, html, body, header, nav]

6. How to smooth-scroll element into view?

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 fooBar

7. How to handle click outside the element?

const onClickOutside = (element, callback) => {
document.addEventListener('click', e => {
if (!element.contains(e.target)) callback();
});
};

onClickOutside('#my-element', () => console.log('Hello'));
// Will log 'Hello' whenever the user clicks outside of #my-element

8. How to generate UUID?

const UUIDGeneratorBrowser = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(
c ^
(crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
).toString(16)
);

UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d'

9. How to get the selected text?

const getSelectedText = () => window.getSelection().toString();

getSelectedText(); // 'Lorem ipsum'

10. How to copy text to the clipboard?

const copyToClipboard = str => {
if (navigator && navigator.clipboard && navigator.clipboard.writeText)
return navigator.clipboard.writeText(str);
return Promise.reject('The Clipboard API is not available.');
};

11. How to add styles to HTML element?

const addStyles = (el, styles) => Object.assign(el.style, styles);

addStyles(document.getElementById('my-element'), {
background: 'red',
color: '#ffff00',
fontSize: '3rem'
});

12. How to toggle full-screen mode?

const fullscreen = (mode = true, el = 'body') =>
mode
? document.querySelector(el).requestFullscreen()
: document.exitFullscreen();

fullscreen(); // Opens `body` in fullscreen mode
fullscreen(false); // Exits fullscreen mode

13. How to detect if Caps lock is on?

<form>
<label for="username">Username:</label>
<input id="username" name="username">

<label for="password">Password:</label>
<input id="password" name="password" type="password">
<span id="password-message" style="display: none">Caps Lock is on</span>
</form>
const el = document.getElementById('password');
const msg = document.getElementById('password-message');

el.addEventListener('keyup', e => {
msg.style = e.getModifierState('CapsLock')
? 'display: block'
: 'display: none';
});

14. How to check if the Date is valid?

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());

isDateValid('December 17, 1995 03:24:00'); // true
isDateValid('1995-12-17T03:24:00'); // true
isDateValid('1995-12-17 T03:24:00'); // false
isDateValid('Duck'); // false
isDateValid(1995, 11, 17); // true
isDateValid(1995, 11, 17, 'Duck'); // false
isDateValid({}); // false

15. How to get colon time from Date?

const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);

getColonTimeFromDate(new Date()); // '08:38:00'

17. How to check the preferred language of the current user?

const detectLanguage = (defaultLang = 'en-US') =>
navigator.language ||
(Array.isArray(navigator.languages) && navigator.languages[0]) ||
defaultLang;

detectLanguage(); // 'nl-NL'

18. How to check the preferred color scheme of the user?

const prefersDarkColorScheme = () =>
window &&
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches;

prefersDarkColorScheme(); // true

19. How to check if the device supports touch events?

const supportsTouchEvents = () =>
window && 'ontouchstart' in window;

supportsTouchEvents(); // true

20. Url objects

const url = new URL("https://example.com/login?user=someguy&page=news");

url.origin
// "https://example.com"
url.host
// "example.com"
url.protocol
// "https:"
url.pathname
// "/login"
url.searchParams.get('user')
// "someguy"

21.  Dynamically Load JS Files

function loadJS(files, done) {
// Get the head tag
const head = document.getElementsByTagName('head')[0];
Promise.all(files.map(file => {
return new Promise(resolve => {
//Create a script tag and add it to the head
const s = document.createElement('script');
s.type = "text/javascript";
s.async = true;
s.src = file;
//Listen to the load event and resolve if the loading is completed
s.addEventListener('load', (e) => resolve(), false);
head.appendChild(s);
});
})).then(done); // Everything is completed, execute the user's callback event
}
loadJS(["test1.js", "test2.js"], () => {
//User callback logic
});


22. Scroll to the bottom of the page

Of course, if you know the height of the document, you can also scroll smoothly to the bottom of the page.


const scrollToBottom = () => {
window.scrollTo({
top: document.documentElement.offsetHeight,
left: 0,
behavior: "smooth",
});
};

23. Display the element in fullscreen mode

You must have encountered such a scenario, where you need to play the video in full screen and open the page in full screen in the browser.



const goToFullScreen = (element) => {
element = element || document.body;
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullScreen();
}
};

24. Exit browser full-screen state

Yes, this is used with the fourth point, you will also have the scenario of exiting the full-screen state of the browser.



const goExitFullscreen = () => {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
};

25. Stop bubbling events

A method for preventing event bubbling that works on all platforms is necessary.



const stopPropagation = (event) => {
event = event || window.event;
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
};

26. Determine if the device is Android or IOS

In addition to distinguishing whether it is mobile or PC, many times we also need to distinguish whether the current device is Android or IOS.


const isAndroid = () => {
return /android/i.test(navigator.userAgent.toLowerCase());
};
const isIOS = () => {
let reg = /iPhone|iPad|iPod|iOS|Macintosh/i;
return reg.test(navigator.userAgent.toLowerCase());
};

27. Get the type of browser and its version

As a front-end developer, you may encounter various compatibility issues. At this time, you may need to obtain the type and version of the browser.



const getExplorerInfo = () => {
let t = navigator.userAgent.toLowerCase();
return 0 <= t.indexOf("msie")
? {
//ie < 11
type: "IE",
version: Number(t.match(/msie ([\d]+)/)[1]),
}
: !!t.match(/trident\/.+?rv:(([\d.]+))/)
? {
// ie 11
type: "IE",
version: 11,
}
: 0 <= t.indexOf("edge")
? {
type: "Edge",
version: Number(t.match(/edge\/([\d]+)/)[1]),
}
: 0 <= t.indexOf("firefox")
? {
type: "Firefox",
version: Number(t.match(/firefox\/([\d]+)/)[1]),
}
: 0 <= t.indexOf("chrome")
? {
type: "Chrome",
version: Number(t.match(/chrome\/([\d]+)/)[1]),
}
: 0 <= t.indexOf("opera")
? {
type: "Opera",
version: Number(t.match(/opera.([\d]+)/)[1]),
}
: 0 <= t.indexOf("Safari")
? {
type: "Safari",
version: Number(t.match(/version\/([\d]+)/)[1]),
}
: {
type: t,
version: -1,
};
};
















2023년 12월 19일 화요일

새롭지만 잘 알려지지 않은 JavaScript API 및 기능

 .groupBy()

const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
{ name: "fish", type: "meat", quantity: 22 },
];


const result = Object.groupBy(inventory, ({ type }) => type);

/* Result is:
{
vegetables: [
{ name: 'asparagus', type: 'vegetables', quantity: 5 },
],
fruit: [
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "cherries", type: "fruit", quantity: 5 }
],
meat: [
{ name: "goat", type: "meat", quantity: 23 },
{ name: "fish", type: "meat", quantity: 22 }
]
}
*/


.toSorted()

The method of instances is the copying version of the method. It returns a new array with the elements sorted in ascending order.toSorted()Arraysort()

const months = ["Mar", "Jan", "Feb", "Dec"];
const sortedMonths = months.toSorted();
console.log(sortedMonths); // ['Dec', 'Feb', 'Jan', 'Mar']
console.log(months); // ['Mar', 'Jan', 'Feb', 'Dec']

const values = [1, 10, 21, 2];
const sortedValues = values.toSorted((a, b) => a - b);
console.log(sortedValues); // [1, 2, 10, 21]
console.log(values); // [1, 10, 21, 2]


<dialog>: The Dialog element

The The HTML element represents a modal or non-modal dialog box or another interactive component, such as a dismissible alert, inspector, or subwindow.<dialog>


The HTML element is used to create both modal and non-modal dialog boxes. Modal dialog boxes interrupt interaction with the rest of the page being inert, while non-modal dialog boxes allow interaction with the rest of the page.<dialog>


JavaScript should be used to display the element. Use the method to display a modal dialog and the method to display a non-modal dialog. The dialog box can be closed using the method or using the method when submitting a that is nested within the element. Modal dialogs can also be closed by pressing the Esc key.<dialog>.showModal().show().close()dialog<form><dialog>


<dialog open>
<p>Greetings, one and all!</p>
<form method="dialog">
<button>OK</button>
</form>
</dialog>
const dialog = document.querySelector("dialog");
const showButton = document.querySelector("dialog + button");
const closeButton = document.querySelector("dialog button");

// "Show the dialog" button opens the dialog modally
showButton.addEventListener("click", () => {
dialog.showModal();
});

// "Close" button closes the dialog
closeButton.addEventListener("click", () => {
dialog.close();
});


<search>: The generic search element

The HTML element is a container representing the parts of the document or application with form controls or other content related to performing a search or filtering operation. The element semantically identifies the purpose of the element's contents as having search or filtering capabilities. The search or filtering functionality can be for the website or application, the current web page or document, or the entire Internet or subsection thereof.<search><search>

<search>
<label>
Find and filter your query
<input type="search" id="query" />
</label>
<label>
<input type="checkbox" id="exact-only" />
Exact matches only
</label>

<section>
<h3>Results:</h3>
<ul id="results">
<!-- search result content -->
</ul>
<output id="no-results">
<!-- no results content -->
</output>
</section>
</search>

This example demonstrates potential DOM content when dynamically including JavaScript search functionality in a web application. When search functionality is implemented entirely with JavaScript, if no form is submitted, neither a element nor a submit is required. For semantics, the element is included to contain the search and filtering capabilities.<form><button><search>


.findLast()

The method of instances iterates the array in reverse order and returns the value of the first element that satisfies the provided testing function. If no elements satisfy the testing function, is returned.findLast()Arrayundefined

const array1 = [5, 12, 50, 130, 44];

const found = array1.findLast((element) => element > 45);

console.log(found);
// Expected output: 130


.with()

The method of instances is the copying version of using the bracket notation to change the value of a given index. It returns a new array with the element at the given index replaced with the given value.with()Array


Creating a new array with a single changed element

const arr = [1, 2, 3, 4, 5];
console.log(arr.with(2, 6)); // [1, 2, 6, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5]

With the method, you can update a single element in an array and then apply other array methods.with()

const arr = [1, 2, 3, 4, 5];
console.log(arr.with(2, 6).map((x) => x ** 2)); // [1, 4, 36, 16, 25]

The method creates and returns a new array. It reads the property of and then accesses each property whose key is a nonnegative integer less than . As each property of is accessed, the array element having an index equal to the key of the property is set to the value of the property. Finally, the array value at is set to .with() length this length this index value

const arrayLike = {
length: 3,
unrelated: "foo",
0: 5,
2: 4,
3: 3, // ignored by with() since length is 3
};
console.log(Array.prototype.with.call(arrayLike, 0, 1));
// [ 1, undefined, 4 ]


Use “await” at the top level of a module

from mdnThe await operator is used to wait for a Promise and get its fulfillment value.

const getUserInfo = () => {
return new Promise((rs) => {
setTimeout(() => {
rs({
name: 'fatfish'
})
}, 2000)
})
}
// If you want to use await, you must use the async function.
const fetch = async () => {
const userInfo = await getUserInfo()
console.log('userInfo', userInfo)
}

fetch()
// SyntaxError: await is only valid in async functions
const userInfo = await getUserInfo()
console.log('userInfo', userInfo)

In fact, after ES13, we can use await at the top level of a module, which is a really happy new feature for developers. That’s great.

const getUserInfo = () => {
return new Promise((rs) => {
setTimeout(() => {
rs({
name: 'fatfish'
})
}, 2000)
})
}

const userInfo = await getUserInfo()
console.log('userInfo', userInfo)

Use “#” to declare private properties

In the past, we used "_" To represent private properties, but it is not secure and may still be modified externally.

class Person {
constructor (name) {
this._money = 1
this.name = name
}

get money () {
return this._money
}
set money (money) {
this._money = money
}
showMoney () {
console.log(this._money)
}
}

const p1 = new Person('fatfish')

console.log(p1.money) // 1
console.log(p1._money) // 1
p1._money = 2 // Modify private property _money from outside
console.log(p1.money) // 2
console.log(p1._money) // 2

We can use “#” to implement truly secure private properties

class Person {
#money=1
constructor (name) {
this.name = name
}
get money () {
return this.#money
}
set money (money) {
this.#money = money
}
showMoney () {
console.log(this.#money)
}
}
const p1 = new Person('fatfish')
console.log(p1.money) // 1
// p1.#money = 2 // We cannot modify #money in this way
p1.money = 2
console.log(p1.money) // 2
// Uncaught SyntaxError: Private field '#money' must be declared
// in an enclosing classconsole.log(p1.#money)


Easier to set member variables for classes

class Person {
constructor () {
this.age = 1000
this.name = 'fatfish'
}

showInfo (key) {
console.log(this[ key ])
}
}
const p1 = new Person()
p1.showInfo('name') // fatfish
p1.showInfo('age') // 1000

Now you can use the following way, which is really more convenient to use.

class Person {
age = 1000
name = 'fatfish'
showInfo (key) {
console.log(this[ key ])
}
}

const p1 = new Person()
p1.showInfo('name') // fatfish
p1.showInfo('age') // 1000


FileReader API

https://12daysofweb.dev/2023/filereader-api/