// index.js
export * as MathUtils from "./math.js";
export * as StringUtils from "./string-utils.js";
// Usage:
// import { MathUtils, StringUtils } from './index.js';
// modules/index.js
export { default as Calculator } from "./calculator.js";
export { default as Logger } from "./logger.js";
export * from "./math.js";
export * from "./string-utils.js";
export { ApiClient as Client, HTTP_METHODS as Methods } from "./config.js";
// https://medium.com/@bestowensss/4-ways-to-dynamically-execute-javascript-code-on-the-front-end-01648b4f527a
// 1
/*
Synchronous execution;
The execution context is the current scope .
*/
let a = 1;
function test() {
let a = 2;
eval('console.log(a)'); // 2
}
test();
// 2
/*
Synchronous execution;
The execution environment is the global scope .
*/
let a = 1;
function test() {
let a = 2;
let fn = new Function('console.log(a)');
fn(); // 1
}
test();
// 3
// 2
/*
Asynchronous execution;
The execution environment is the global scope .
*/
let a = 1;
function test() {
let a = 2;
setTimeout('console.log(a)', 1000); // 1
}
test();
//4
/*
Synchronous execution;
The execution environment is the global scope .
*/
var a = 1;
let script = document.createElement('script');
script.textContent = 'console.log(1)';
document.body.appendChild(script); // 1
// https://medium.com/@genildocs/mastering-object-oriented-programming-in-javascript-from-zero-to-hero-c718c3182eba
// Mixin for logging functionality
const LoggerMixin = {
log(message) {
console.log(`[${this.constructor.name}] ${message}`);
},
logError(error) {
console.error(`[${this.constructor.name}] ERROR: ${error}`);
}
};
// Mixin for validation
const ValidatorMixin = {
validate(data, rules) {
for (const [field, rule] of Object.entries(rules)) {
if (!rule(data[field])) {
return { valid: false, field };
}
}
return { valid: true };
}
};
class UserService {
constructor() {
// Apply mixins
Object.assign(this, LoggerMixin, ValidatorMixin);
}
// Pattern 1 — Bind Helper
export function S(selector) {
const nodes = document.querySelectorAll(selector);
nodes.forEach(bindAll); // Bind helpers to node(s)
return nodes.length > 1 ? nodes : nodes[0]; // native node(s) returned
}
export function C(tag) {
const node = document.createElement(tag);
return bindAll(node); // Bind helpers to node(s)
}
function bindAll(node) {
node.addClass = addClass.bind(node);
node.attr = attr.bind(node);
return node;
}
//--- Extension functions ---//
function addClass(...cls) {
this.classList.add(...cls);
return this;
}
function attr(key, val) {
if (val !== undefined) {
this.setAttribute(key, val);
return this;
}
return this.getAttribute(key);
}
// Usage:
import { S, C } from './helper.js';
const btn = C('button').addClass('btn', 'primary').attr('type', 'submit');
btn.click(); // native method
S('.card').forEach(el => el.addClass('highlight').attr('data-live', '1'));
/*
@source: https://javascript.plainenglish.io/50-javascript-shortcuts-that-will-make-you-a-code-wizard-in-2025-14dd7aee319c
*/
// 1. Ternary Operator
const status = loggedIn ? "Welcome!" : "Please login.";
// 2. Default Parameters
function greet(name = "Stranger") {
return `Hello, ${name}`;
}
// 3. Arrow Functions
const multiply = (a, b) => a * b;
// 4. Destructuring Objects
const { title, year } = movie;
// 5. Destructuring Arrays
const [first, second] = topResults;
// 6. Template Literals
const greeting = `Hey, ${user.name}!`;
// 7. Spread Operator
const newTeam = [...oldTeam, "Alice"];
// 8. Rest Parameters
function logAll(...args) {
console.log(args);
}
// 9. Optional Chaining
const city = user?.address?.city;
// 10. Nullish Coalescing
const nickname = inputName ?? "Anonymous";
// 12. Logical OR Assignment
settings.volume ||= 50;
// 13. Logical AND Assignment
user.isAdmin &&= false;
// 14. Object Property Shorthand
const age = 24;
const person = { name, age };
// 15. Computed Property Names
const field = "score";
const stats = { [field]: 100 };
// 16. For-of Loop
for (const char of name) {
console.log(char);
}
// 17. forEach
tags.forEach(tag => console.log(`#${tag}`));
// 18. map()
const lengths = names.map(n => n.length);
// 19. filter()
const passed = grades.filter(g => g >= 60);
// 20. reduce()
const sum = numbers.reduce((a, b) => a + b, 0);
// 21. includes()
if (items.includes("🚀")) launch();
// 22. Unique Array with Set
const unique = [...new Set(tags)];
// 23. Object.entries()
Object.entries(data).forEach(([k, v]) => console.log(k, v));
// 24. Object.values()
const values = Object.values(config);
// 25. Object.keys()
const keys = Object.keys(settings);
// 26. Array Method Chaining
data.filter(a => a.active).map(a => a.name);
// 27. Flatten Arrays
const flat = nested.flat(2);
// 28. String.trim()
const cleaned = input.trim();
// 29. padStart()
const padded = id.padStart(5, "0");
// 30. Format Numbers
const price = new Intl.NumberFormat().format(1234567);
// 31. Dynamic Import
const module = await import("./utils.js");
// 32. Promise.all()
await Promise.all([loadUser(), loadPosts()]);
// 33. Async/Await
const getData = async () => {
const res = await fetch(url);
return await res.json();
};
// 34. Optional Function Params
function log(message, level = "info") {
console[level](message);
}
// 35. Number Conversion with +
const num = +"42";
// 36. Boolean Conversion with !!
const isValid = !!userInput;
// 37. Swap Values
[a, b] = [b, a];
// 38. String to Array
const chars = [..."dev"];
// 39. Clone Object
const copy = { ...original };
// 40. Debounce
const debounce = (fn, delay) => {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
};
// 41. Named Capture Groups in Regex
const url = "https://dev.to";
const match = url.match(/(?<protocol>https?):\/\/(?<host>.+)/);
console.log(match.groups);
// 42. ??= Operator
data.username ??= "guest";
// 43. Numeric Separators
const big = 1_000_000_000;
// 44. Top-Level await (in modules)
const user = await fetchUser();
// 45. Array.from with Map
const numbers = Array.from(new Set([1, 2, 2, 3]));
// 46. Group Array by Property
const grouped = data.reduce((acc, obj) => {
acc[obj.type] = acc[obj.type] || [];
acc[obj.type].push(obj);
return acc;
}, {});
// 47. isFinite()
if (isFinite(num)) { /* safe to use */ }
// 48. Abort Fetch Request
const controller = new AbortController();
fetch(url, { signal: controller.signal });
controller.abort();
// 49. toLocaleString()
(1234567.89).toLocaleString("en-US", {
style: "currency",
currency: "USD"
});
// 50. StructuredClone
const clone = structuredClone(myObj);
const user = { name: "Alice", age: 30 };
// 1. for...in loop - iteruje přes všechny enumerable vlastnosti
console.log("1. for...in loop:");
for (let key in user) {
console.log(`${key}: ${user[key]}`);
}
// 2. Object.keys() - vrací pole klíčů
console.log("\n2. Object.keys():");
Object.keys(user).forEach(key => {
console.log(`${key}: ${user[key]}`);
});
// 3. Object.values() - vrací pole hodnot
console.log("\n3. Object.values():");
Object.values(user).forEach(value => {
console.log(value);
});
// 4. Object.entries() - vrací pole párů [klíč, hodnota]
console.log("\n4. Object.entries():");
Object.entries(user).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
// 5. Object.entries() s for...of
console.log("\n5. Object.entries() s for...of:");
for (let [key, value] of Object.entries(user)) {
console.log(`${key}: ${value}`);
}
// 6. Object.keys() s for...of
console.log("\n6. Object.keys() s for...of:");
for (let key of Object.keys(user)) {
console.log(`${key}: ${user[key]}`);
}
// 7. Object.getOwnPropertyNames() - včetně non-enumerable vlastností
console.log("\n7. Object.getOwnPropertyNames():");
Object.getOwnPropertyNames(user).forEach(key => {
console.log(`${key}: ${user[key]}`);
});
// 8. Reflect.ownKeys() - všechny vlastnosti včetně Symbolů
console.log("\n8. Reflect.ownKeys():");
Reflect.ownKeys(user).forEach(key => {
console.log(`${key}: ${user[key]}`);
});
// 9. Map() pro transformaci
console.log("\n9. Map() pro transformaci:");
const transformed = Object.entries(user).map(([key, value]) => `${key.toUpperCase()}: ${value}`);
console.log(transformed);
// 10. Reduce() pro akumulaci
console.log("\n10. Reduce() pro akumulaci:");
const result = Object.entries(user).reduce((acc, [key, value]) => {
acc[key.toUpperCase()] = value;
return acc;
}, {});
console.log(result);
// 11. Filter() pro filtrování
console.log("\n11. Filter() pro filtrování:");
const filtered = Object.entries(user).filter(([key, value]) => typeof value === 'string');
console.log(filtered);
// 12. Some() a Every() pro testování
console.log("\n12. Some() a Every():");
const hasString = Object.values(user).some(value => typeof value === 'string');
const allStrings = Object.values(user).every(value => typeof value === 'string');
console.log(`Obsahuje string: ${hasString}`);
console.log(`Všechny jsou stringy: ${allStrings}`);
// 13. JSON.stringify() s replacer funkcí
console.log("\n13. JSON.stringify() s replacer:");
JSON.stringify(user, (key, value) => {
if (key !== '') console.log(`${key}: ${value}`);
return value;
});
// 14. Object.hasOwnProperty() check
console.log("\n14. for...in s hasOwnProperty:");
for (let key in user) {
if (user.hasOwnProperty(key)) {
console.log(`${key}: ${user[key]}`);
}
}
// 15. Destrukturování s rest operátorem
console.log("\n15. Destrukturování:");
const { name, ...rest } = user;
console.log(`name: ${name}`);
console.log('zbytek:', rest);
// 16. Použití s async/await (pokud by byly hodnoty Promise)
console.log("\n16. Async iterace (příklad):");
async function asyncIteration() {
for (let [key, value] of Object.entries(user)) {
// Simulace async operace
await new Promise(resolve => setTimeout(resolve, 100));
console.log(`Async: ${key}: ${value}`);
}
}
// asyncIteration(); // odkomentuj pro spuštění
<!--
https://jsbin.com/bihofirugo/2/edit?html,css,output
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="container">
<img src="https://picsum.photos/id/237/200/300" alt="Foto 1">
<img src="https://picsum.photos/id/237/200/300" alt="Foto 1">
<img src="https://picsum.photos/id/237/200/300" alt="Foto 1">
<img src="https://picsum.photos/id/237/200/300" alt="Foto 1">
<img src="https://picsum.photos/id/237/200/300" alt="Foto 1">
<img src="https://picsum.photos/id/237/200/300" alt="Foto 1">
<img src="https://picsum.photos/id/237/200/300" alt="Foto 1">
<img src="https://picsum.photos/id/237/200/300" alt="Foto 1">
</div>
<style>
.container {
white-space: nowrap;
overflow-x: auto;
cursor: grab;
user-select: none; /* Zabrání výběru textu nebo obrázků při tažení */
}
.container img {
display: inline-block;
width: 200px;
height: 150px;
pointer-events: none; /* Zabrání interakci s obrázky (např. drag-and-drop obrázků) */
}
.container.grabbing {
cursor: grabbing;
}
</style>
<script>
const container = document.querySelector('.container');
let isDragging = false;
let startX;
let scrollLeft;
container.addEventListener('mousedown', (e) => {
isDragging = true;
container.classList.add('grabbing');
startX = e.pageX - container.offsetLeft;
scrollLeft = container.scrollLeft;
e.preventDefault(); // Zabrání výchozímu chování (např. výběr textu)
});
container.addEventListener('mousemove', (e) => {
if (!isDragging) return;
e.preventDefault(); // Zabrání výchozímu chování při pohybu
const x = e.pageX - container.offsetLeft;
const walk = (x - startX) / 0.5; // Rychlost scrollování
container.scrollLeft = scrollLeft - walk;
});
container.addEventListener('mouseup', () => {
isDragging = false;
container.classList.remove('grabbing');
});
container.addEventListener('mouseleave', () => {
if (isDragging) {
isDragging = false;
container.classList.remove('grabbing');
}
});
// Pro jistotu přidáme globální posluchač na mouseup, aby se tažení ukončilo i mimo kontejner
document.addEventListener('mouseup', () => {
if (isDragging) {
isDragging = false;
container.classList.remove('grabbing');
}
});
</script>
</body>
</html>
// Noob
const eventHandler = e => {
if (e.key === 'Escape') {
this.closeGallery()
}
if (e.key === 'ArrowLeft') {
this.prevMedia()
}
if (e.key === 'ArrowRight') {
this.nextMedia()
}
}
// Profi
const eventHandler = e => {
const keyActions = {
Escape: closeGallery,
ArrowLeft: prevMedia,
ArrowRight: nextMedia
}
keyActions[e.key]?.()
}
Object.keys(window).forEach(key => {
if (/^on/.test(key)) {
window.addEventListener(key.slice(2), event => {
console.log(event);
});
}
});
/*
https://javascript.plainenglish.io/3-powerful-ways-to-share-data-across-browser-tabs-in-javascript-a6a98dffa1a3
*/
// 1. local storage
// Sender
localStorage.setItem('sharedData', JSON.stringify({
message: 'Hello from Tab1!',
timestamp: Date.now()
}));
// Receiver
window.addEventListener('storage', (e) => {
if(e.key === 'sharedData') {
const data = JSON.parse(e.newValue);
console.log('Received data:', data);
}
});
// 2. BroadcastChannel API
// Create a channel (use the same channel name across all tabs)
const channel = new BroadcastChannel('app-channel');
// Send a message
channel.postMessage({
type: 'USER_UPDATE',
payload: { name: 'John' }
});
// Receive messages
channel.onmessage = (e) => {
console.log('Received broadcast:', e.data);
};
// Close the connection
window.onunload = () => channel.close();
// 3.SharedWorker Shared Thread
// shared-worker.js
let ports = [];
onconnect = (e) => {
const port = e.ports[0];
ports.push(port);
port.onmessage = (e) => {
// Broadcast to all connected pages
ports.forEach(p => {
if(p !== port) p.postMessage(e.data);
});
};
};
// Page code
const worker = new SharedWorker('shared-worker.js');
worker.port.start();
// Send a message
worker.port.postMessage('Message from Tab A');
// Receive messages
worker.port.onmessage = (e) => {
console.log('Shared thread message:', e.data);
};