repo
stringlengths
5
106
file_url
stringlengths
78
301
file_path
stringlengths
4
211
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:56:49
2026-01-05 02:23:25
truncated
bool
2 classes
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/index.js
index.js
/* 33 JavaScript Concepts is a project created to help JavaScript developers master their skills. It is a compilation of fundamental JavaScript concepts that are important and fundamental. This project was inspired by an article written by Stephen Curtis. Any kind of contribution is welcome. Feel free to contribute. */
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/vitest.config.js
vitest.config.js
import { defineConfig } from 'vitest/config' export default defineConfig({ test: { include: ['tests/**/*.test.js'], globals: false, environment: 'node' } })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/async-javascript/callbacks/callbacks.test.js
tests/async-javascript/callbacks/callbacks.test.js
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' describe('Callbacks', () => { // ============================================================ // OPENING EXAMPLES // From callbacks.mdx lines 9-22, 139-155 // ============================================================ describe('Opening Examples', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) // From lines 9-22: Why doesn't JavaScript wait? it('should demonstrate setTimeout non-blocking behavior', async () => { const output = [] output.push('Before timer') setTimeout(function() { output.push('Timer fired!') }, 1000) output.push('After timer') // Before timer advances, only sync code has run expect(output).toEqual(['Before timer', 'After timer']) // After 1 second await vi.advanceTimersByTimeAsync(1000) // Output: // Before timer // After timer // Timer fired! (1 second later) expect(output).toEqual(['Before timer', 'After timer', 'Timer fired!']) }) // From lines 139-155: Restaurant buzzer analogy it('should demonstrate restaurant buzzer analogy with eatBurger callback', async () => { const output = [] // You place your order (start async operation) setTimeout(function eatBurger() { output.push('Eating my burger!') // This is the callback }, 5000) // You go sit down (your code continues) output.push('Sitting down, checking my phone...') output.push('Chatting with friends...') output.push('Reading the menu...') // Before timer fires expect(output).toEqual([ 'Sitting down, checking my phone...', 'Chatting with friends...', 'Reading the menu...' ]) // After 5 seconds await vi.advanceTimersByTimeAsync(5000) // Output: // Sitting down, checking my phone... // Chatting with friends... // Reading the menu... // Eating my burger! (5 seconds later) expect(output).toEqual([ 'Sitting down, checking my phone...', 'Chatting with friends...', 'Reading the menu...', 'Eating my burger!' ]) }) }) // ============================================================ // WHAT IS A CALLBACK // From callbacks.mdx lines 48-91 // ============================================================ describe('What is a Callback', () => { // From lines 48-61: greet and processUserInput example it('should execute greet callback passed to processUserInput', () => { const output = [] // greet is a callback function function greet(name) { output.push(`Hello, ${name}!`) } // processUserInput accepts a callback function processUserInput(callback) { const name = 'Alice' callback(name) // "calling back" the function we received } processUserInput(greet) // "Hello, Alice!" expect(output).toEqual(['Hello, Alice!']) }) // From lines 73-91: Callbacks can be anonymous it('should work with anonymous function callbacks', () => { const output = [] // Simulating addEventListener behavior for testing function simulateAddEventListener(event, callback) { callback() } // Named function as callback function handleClick() { output.push('Clicked!') } simulateAddEventListener('click', handleClick) // Anonymous function as callback simulateAddEventListener('click', function() { output.push('Clicked!') }) // Arrow function as callback simulateAddEventListener('click', () => { output.push('Clicked!') }) // All three do the same thing expect(output).toEqual(['Clicked!', 'Clicked!', 'Clicked!']) }) }) // ============================================================ // CALLBACKS AND HIGHER-ORDER FUNCTIONS // From callbacks.mdx lines 166-198 // ============================================================ describe('Callbacks and Higher-Order Functions', () => { // From lines 166-176: forEach is a higher-order function it('should demonstrate forEach as a higher-order function', () => { const output = [] // forEach is a HIGHER-ORDER FUNCTION (it accepts a function) // The arrow function is the CALLBACK (it's being passed in) const numbers = [1, 2, 3] numbers.forEach((num) => { // <- This is the callback output.push(num * 2) }) // 2, 4, 6 expect(output).toEqual([2, 4, 6]) }) // From lines 180-198: filter, map, find, sort with users array it('should demonstrate filter, map, find, sort with users array', () => { const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 17 }, { name: 'Charlie', age: 30 } ] // filter accepts a callback that returns true/false const adults = users.filter(user => user.age >= 18) expect(adults).toEqual([ { name: 'Alice', age: 25 }, { name: 'Charlie', age: 30 } ]) // map accepts a callback that transforms each element const names = users.map(user => user.name) expect(names).toEqual(['Alice', 'Bob', 'Charlie']) // find accepts a callback that returns true when found const bob = users.find(user => user.name === 'Bob') expect(bob).toEqual({ name: 'Bob', age: 17 }) // sort accepts a callback that compares two elements const byAge = [...users].sort((a, b) => a.age - b.age) expect(byAge).toEqual([ { name: 'Bob', age: 17 }, { name: 'Alice', age: 25 }, { name: 'Charlie', age: 30 } ]) }) }) // ============================================================ // SYNCHRONOUS VS ASYNCHRONOUS CALLBACKS // From callbacks.mdx lines 214-310 // ============================================================ describe('Synchronous Callbacks', () => { // From lines 214-236: Synchronous callbacks execute immediately it('should execute map callbacks synchronously and in order', () => { const output = [] const numbers = [1, 2, 3, 4, 5] output.push('Before map') const doubled = numbers.map(num => { output.push(`Doubling ${num}`) return num * 2 }) output.push('After map') output.push(JSON.stringify(doubled)) // Output (all synchronous, in order): // Before map // Doubling 1 // Doubling 2 // Doubling 3 // Doubling 4 // Doubling 5 // After map // [2, 4, 6, 8, 10] expect(output).toEqual([ 'Before map', 'Doubling 1', 'Doubling 2', 'Doubling 3', 'Doubling 4', 'Doubling 5', 'After map', '[2,4,6,8,10]' ]) expect(doubled).toEqual([2, 4, 6, 8, 10]) }) // From lines 287-295: Synchronous callback - try/catch WORKS it('should catch errors in synchronous callbacks with try/catch', () => { let caughtMessage = null // Synchronous callback - try/catch WORKS try { [1, 2, 3].forEach(num => { if (num === 2) throw new Error('Found 2!') }) } catch (error) { caughtMessage = error.message // "Caught: Found 2!" } expect(caughtMessage).toBe('Found 2!') }) }) describe('Asynchronous Callbacks', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) // From lines 249-262: Even with 0ms delay, callback runs after sync code it('should execute setTimeout callbacks after synchronous code even with 0ms delay', async () => { const output = [] output.push('Before setTimeout') setTimeout(() => { output.push('Inside setTimeout') }, 0) // Even with 0ms delay! output.push('After setTimeout') // Before timer fires expect(output).toEqual(['Before setTimeout', 'After setTimeout']) await vi.advanceTimersByTimeAsync(0) // Output: // Before setTimeout // After setTimeout // Inside setTimeout (runs AFTER all sync code) expect(output).toEqual([ 'Before setTimeout', 'After setTimeout', 'Inside setTimeout' ]) }) // From lines 297-306: Asynchronous callback - try/catch DOES NOT WORK! it('should demonstrate that try/catch cannot catch async callback errors', async () => { // This test verifies the concept that try/catch doesn't work for async callbacks // In real code, the error would crash the program let tryCatchRan = false const asyncCallback = vi.fn() // Asynchronous callback - try/catch DOES NOT WORK! try { setTimeout(() => { asyncCallback() // throw new Error('Async error!') // This error escapes! }, 100) } catch (error) { // This will NEVER run tryCatchRan = true } // The try/catch completes immediately, before the callback even runs expect(tryCatchRan).toBe(false) expect(asyncCallback).not.toHaveBeenCalled() await vi.advanceTimersByTimeAsync(100) // Now the callback has run, but the try/catch is long gone expect(asyncCallback).toHaveBeenCalled() }) }) // ============================================================ // HOW CALLBACKS WORK WITH THE EVENT LOOP // From callbacks.mdx lines 355-393 // ============================================================ describe('Event Loop Examples', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) // From lines 355-387: Event loop trace example it('should demonstrate event loop execution order', async () => { const output = [] output.push('1: Script start') setTimeout(function first() { output.push('2: First timeout') }, 0) setTimeout(function second() { output.push('3: Second timeout') }, 0) output.push('4: Script end') // Execution order: // 1. console.log('1: Script start') - runs immediately // 2. setTimeout(first, 0) - registers first callback with Web APIs // 3. setTimeout(second, 0) - registers second callback with Web APIs // 4. console.log('4: Script end') - runs immediately // 5. Call stack is now empty // 6. Event Loop checks Task Queue - finds first // 7. first() runs -> "2: First timeout" // 8. Event Loop checks Task Queue - finds second // 9. second() runs -> "3: Second timeout" // Before timers fire - only sync code has run expect(output).toEqual(['1: Script start', '4: Script end']) await vi.advanceTimersByTimeAsync(0) // Output: // 1: Script start // 4: Script end // 2: First timeout // 3: Second timeout expect(output).toEqual([ '1: Script start', '4: Script end', '2: First timeout', '3: Second timeout' ]) }) }) // ============================================================ // COMMON CALLBACK PATTERNS // From callbacks.mdx lines 397-537 // ============================================================ describe('Common Callback Patterns', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) // Pattern 2: Timers (lines 436-479) // From lines 440-447: setTimeout runs once after delay it('should run setTimeout callback once after delay', async () => { const output = [] // setTimeout - runs once after delay const timeoutId = setTimeout(function() { output.push('This runs once after 2 seconds') }, 2000) expect(output).toEqual([]) await vi.advanceTimersByTimeAsync(2000) expect(output).toEqual(['This runs once after 2 seconds']) }) // From lines 447: Cancel timeout before it runs it('should cancel setTimeout with clearTimeout', async () => { const callback = vi.fn() // Cancel it before it runs const timeoutId = setTimeout(function() { callback() }, 2000) clearTimeout(timeoutId) await vi.advanceTimersByTimeAsync(2000) expect(callback).not.toHaveBeenCalled() }) // From lines 449-459: setInterval runs repeatedly it('should run setInterval callback repeatedly until cleared', async () => { const output = [] // setInterval - runs repeatedly let count = 0 const intervalId = setInterval(function() { count++ output.push(`Count: ${count}`) if (count >= 5) { clearInterval(intervalId) // Stop after 5 times output.push('Done!') } }, 1000) await vi.advanceTimersByTimeAsync(5000) expect(output).toEqual([ 'Count: 1', 'Count: 2', 'Count: 3', 'Count: 4', 'Count: 5', 'Done!' ]) }) // From lines 464-479: Passing arguments to timer callbacks it('should pass arguments to setTimeout callbacks using closure', async () => { const output = [] // Method 1: Closure (most common) const name = 'Alice' setTimeout(function() { output.push(`Hello, ${name}!`) }, 1000) await vi.advanceTimersByTimeAsync(1000) expect(output).toEqual(['Hello, Alice!']) }) it('should pass arguments to setTimeout callbacks using extra arguments', async () => { const output = [] // Method 2: setTimeout's extra arguments setTimeout(function(greeting, name) { output.push(`${greeting}, ${name}!`) }, 1000, 'Hello', 'Bob') // Extra args passed to callback await vi.advanceTimersByTimeAsync(1000) expect(output).toEqual(['Hello, Bob!']) }) it('should pass arguments to setTimeout callbacks using arrow function with closure', async () => { const output = [] // Method 3: Arrow function with closure const user = { name: 'Charlie' } setTimeout(() => output.push(`Hi, ${user.name}!`), 1000) await vi.advanceTimersByTimeAsync(1000) expect(output).toEqual(['Hi, Charlie!']) }) // Pattern 3: Array Iteration (lines 481-512) // From lines 485-512: products array examples it('should demonstrate array iteration callbacks with products array', () => { const products = [ { name: 'Laptop', price: 999, inStock: true }, { name: 'Phone', price: 699, inStock: false }, { name: 'Tablet', price: 499, inStock: true } ] // forEach - do something with each item const forEachOutput = [] products.forEach(product => { forEachOutput.push(`${product.name}: $${product.price}`) }) expect(forEachOutput).toEqual([ 'Laptop: $999', 'Phone: $699', 'Tablet: $499' ]) // map - transform each item into something new const productNames = products.map(product => product.name) // ['Laptop', 'Phone', 'Tablet'] expect(productNames).toEqual(['Laptop', 'Phone', 'Tablet']) // filter - keep only items that pass a test const available = products.filter(product => product.inStock) // [{ name: 'Laptop', ... }, { name: 'Tablet', ... }] expect(available).toEqual([ { name: 'Laptop', price: 999, inStock: true }, { name: 'Tablet', price: 499, inStock: true } ]) // find - get the first item that passes a test const phone = products.find(product => product.name === 'Phone') // { name: 'Phone', price: 699, inStock: false } expect(phone).toEqual({ name: 'Phone', price: 699, inStock: false }) // reduce - combine all items into a single value const totalValue = products.reduce((sum, product) => sum + product.price, 0) // 2197 expect(totalValue).toBe(2197) }) // Pattern 4: Custom Callbacks (lines 514-537) // From lines 518-537: fetchUserData custom callback it('should demonstrate custom callback pattern with fetchUserData', async () => { const output = [] // A function that does something and then calls you back function fetchUserData(userId, callback) { // Simulate async operation setTimeout(function() { const user = { id: userId, name: 'Alice', email: 'alice@example.com' } callback(user) }, 1000) } // Using the function fetchUserData(123, function(user) { output.push(`Got user: ${user.name}`) }) output.push('Fetching user...') // Before timer fires expect(output).toEqual(['Fetching user...']) await vi.advanceTimersByTimeAsync(1000) // Output: // Fetching user... // Got user: Alice (1 second later) expect(output).toEqual(['Fetching user...', 'Got user: Alice']) }) }) // ============================================================ // THE ERROR-FIRST CALLBACK PATTERN // From callbacks.mdx lines 541-654 // ============================================================ describe('Error-First Callback Pattern', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) // From lines 547-553: Error-first callback signature it('should demonstrate error-first callback signature', () => { // Error-first callback signature // function callback(error, result) { // // error: null/undefined if success, Error object if failure // // result: the data if success, usually undefined if failure // } let receivedError = 'not called' let receivedResult = 'not called' function callback(error, result) { receivedError = error receivedResult = result } // Success case callback(null, 'success data') expect(receivedError).toBeNull() expect(receivedResult).toBe('success data') // Error case callback(new Error('something failed'), undefined) expect(receivedError).toBeInstanceOf(Error) expect(receivedError.message).toBe('something failed') expect(receivedResult).toBeUndefined() }) // From lines 586-622: divideAsync error-first example it('should demonstrate divideAsync error-first callback pattern', async () => { function divideAsync(a, b, callback) { // Simulate async operation setTimeout(function() { // Check for errors if (typeof a !== 'number' || typeof b !== 'number') { callback(new Error('Both arguments must be numbers')) return } if (b === 0) { callback(new Error('Cannot divide by zero')) return } // Success! Error is null, result is the value const result = a / b callback(null, result) }, 100) } // Test success case let successError = 'not called' let successResult = 'not called' divideAsync(10, 2, function(error, result) { successError = error successResult = result }) await vi.advanceTimersByTimeAsync(100) expect(successError).toBeNull() expect(successResult).toBe(5) // Result: 5 // Test error case - divide by zero let errorError = 'not called' let errorResult = 'not called' divideAsync(10, 0, function(error, result) { errorError = error errorResult = result }) await vi.advanceTimersByTimeAsync(100) expect(errorError).toBeInstanceOf(Error) expect(errorError.message).toBe('Cannot divide by zero') }) // From lines 627-650: Common Mistake - Forgetting to Return it('should demonstrate the importance of returning after error callback', () => { const results = [] // Wrong - doesn't return after error function processDataWrong(data, callback) { if (!data) { callback(new Error('No data provided')) // Oops! Execution continues... } // This runs even when there's an error! results.push('This should not run if error') callback(null, 'processed') } // Correct - return after error callback function processDataCorrect(data, callback) { if (!data) { return callback(new Error('No data provided')) // Or: callback(new Error(...)); return; } // This only runs if data exists results.push('This only runs on success') callback(null, 'processed') } // Test wrong way processDataWrong(null, () => {}) expect(results).toContain('This should not run if error') // Bug! results.length = 0 // Clear results // Test correct way processDataCorrect(null, () => {}) expect(results).not.toContain('This only runs on success') // Correct! }) }) // ============================================================ // CALLBACK HELL: THE PYRAMID OF DOOM // From callbacks.mdx lines 658-757 // ============================================================ describe('Callback Hell', () => { // From lines 674-715: Nested callback example it('should demonstrate the pyramid of doom pattern', () => { return new Promise((resolve) => { const steps = [] // Simulated async operations function getUser(userId, callback) { setTimeout(() => { steps.push('getUser') callback(null, { id: userId, name: 'Alice' }) }, 0) } function verifyPassword(user, password, callback) { setTimeout(() => { steps.push('verifyPassword') callback(null, password === 'correct') }, 0) } function getProfile(userId, callback) { setTimeout(() => { steps.push('getProfile') callback(null, { bio: 'Developer' }) }, 0) } function getSettings(userId, callback) { setTimeout(() => { steps.push('getSettings') callback(null, { theme: 'dark' }) }, 0) } function renderDashboard(user, profile, settings, callback) { setTimeout(() => { steps.push('renderDashboard') callback(null) }, 0) } function handleError(error) { steps.push(`Error: ${error.message}`) } const userId = 123 const password = 'correct' // Callback hell - nested callbacks (pyramid of doom) getUser(userId, function(error, user) { if (error) { handleError(error) return } verifyPassword(user, password, function(error, isValid) { if (error) { handleError(error) return } if (!isValid) { handleError(new Error('Invalid password')) return } getProfile(user.id, function(error, profile) { if (error) { handleError(error) return } getSettings(user.id, function(error, settings) { if (error) { handleError(error) return } renderDashboard(user, profile, settings, function(error) { if (error) { handleError(error) return } steps.push('Dashboard rendered!') expect(steps).toEqual([ 'getUser', 'verifyPassword', 'getProfile', 'getSettings', 'renderDashboard', 'Dashboard rendered!' ]) resolve() }) }) }) }) }) }) }) }) // ============================================================ // ESCAPING CALLBACK HELL // From callbacks.mdx lines 761-970 // ============================================================ describe('Escaping Callback Hell', () => { // From lines 769-801: Strategy 1 - Named Functions it('should demonstrate named functions to escape callback hell', () => { return new Promise((resolve) => { const steps = [] let rejected = false function getData(callback) { setTimeout(() => { steps.push('getData') callback(null, 'data') }, 0) } function processData(data, callback) { setTimeout(() => { steps.push(`processData: ${data}`) callback(null, 'processed') }, 0) } function saveData(processed, callback) { setTimeout(() => { steps.push(`saveData: ${processed}`) callback(null) }, 0) } function handleError(err) { steps.push(`Error: ${err.message}`) rejected = true } // After: Named functions function handleData(err, data) { if (err) return handleError(err) processData(data, handleProcessed) } function handleProcessed(err, processed) { if (err) return handleError(err) saveData(processed, handleSaved) } function handleSaved(err) { if (err) return handleError(err) steps.push('Done!') expect(steps).toEqual([ 'getData', 'processData: data', 'saveData: processed', 'Done!' ]) resolve() } // Start the chain getData(handleData) }) }) // From lines 813-847: Strategy 2 - Early Returns it('should demonstrate early returns to reduce nesting', () => { return new Promise((resolve) => { const results = [] function validateUser(user, callback) { setTimeout(() => { callback(null, user.name !== '') }, 0) } function saveUser(user, callback) { setTimeout(() => { callback(null, { ...user, saved: true }) }, 0) } // Use early returns function processUser(user, callback) { validateUser(user, function(err, isValid) { if (err) return callback(err) if (!isValid) return callback(new Error('Invalid user')) saveUser(user, function(err, savedUser) { if (err) return callback(err) callback(null, savedUser) }) }) } processUser({ name: 'Alice' }, function(err, result) { expect(err).toBeNull() expect(result).toEqual({ name: 'Alice', saved: true }) // Test invalid user processUser({ name: '' }, function(err, result) { expect(err).toBeInstanceOf(Error) expect(err.message).toBe('Invalid user') resolve() }) }) }) }) // From lines 853-888: Strategy 3 - Modularization it('should demonstrate modularization to break up callback hell', () => { return new Promise((resolve) => { const steps = [] // auth.js function getUser(email, callback) { setTimeout(() => callback(null, { id: 1, email }), 0) } function verifyPassword(user, password, callback) { setTimeout(() => callback(null, password === 'secret'), 0) } function authenticateUser(credentials, callback) { getUser(credentials.email, function(err, user) { if (err) return callback(err) verifyPassword(user, credentials.password, function(err, isValid) { if (err) return callback(err) if (!isValid) return callback(new Error('Invalid password')) callback(null, user) }) }) } // profile.js function getProfile(userId, callback) { setTimeout(() => callback(null, { bio: 'Developer' }), 0) } function getSettings(userId, callback) { setTimeout(() => callback(null, { theme: 'dark' }), 0) } function loadUserProfile(userId, callback) { getProfile(userId, function(err, profile) { if (err) return callback(err) getSettings(userId, function(err, settings) { if (err) return callback(err) callback(null, { profile, settings }) }) }) } function handleError(err) { steps.push(`Error: ${err.message}`) } function renderDashboard(user, profile, settings) { steps.push(`Rendered dashboard for ${user.email}`) } // main.js const credentials = { email: 'alice@example.com', password: 'secret' } authenticateUser(credentials, function(err, user) { if (err) return handleError(err) loadUserProfile(user.id, function(err, data) { if (err) return handleError(err) renderDashboard(user, data.profile, data.settings) expect(steps).toEqual(['Rendered dashboard for alice@example.com']) resolve() }) }) }) }) }) // ============================================================ // COMMON CALLBACK MISTAKES // From callbacks.mdx lines 974-1121 // ============================================================ describe('Common Callback Mistakes', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) // From lines 981-1001: Mistake 1 - Calling a Callback Multiple Times it('should demonstrate the problem of calling callbacks multiple times', () => { const results = [] // Wrong - callback called multiple times! function fetchDataWrong(url, callback) { // Simulating the wrong pattern from the docs callback(null, 'response') // Called on success // In the wrong code, .finally() would also call callback callback(null, 'done') // Called ALWAYS - even after success or error! } fetchDataWrong('http://example.com', (err, data) => { results.push(data) }) // Bug: callback was called twice! expect(results).toEqual(['response', 'done']) expect(results.length).toBe(2) }) // From lines 1003-1041: Mistake 2 - Zalgo (sync/async inconsistency) it('should demonstrate the Zalgo problem (inconsistent sync/async)', async () => { const cache = new Map() const order = [] // Wrong - sometimes sync, sometimes async (Zalgo!) function getData(key, callback) { if (cache.has(key)) { callback(null, cache.get(key)) // Sync! return } setTimeout(() => { const data = `data for ${key}` cache.set(key, data) callback(null, data) // Async! }, 0) } // This causes unpredictable behavior: let value = 'initial' getData('key1', function(err, data) { value = data })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
true
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/async-javascript/callbacks/callbacks.dom.test.js
tests/async-javascript/callbacks/callbacks.dom.test.js
/** * @vitest-environment jsdom */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' // ============================================================ // DOM EVENT HANDLER CALLBACKS // From callbacks.mdx lines 401-434 // Pattern 1: Event Handlers // ============================================================ describe('DOM Event Handler Callbacks', () => { let button beforeEach(() => { // Create a fresh button element for each test button = document.createElement('button') button.id = 'myButton' document.body.appendChild(button) }) afterEach(() => { // Clean up document.body.innerHTML = '' }) // From lines 405-416: DOM events with addEventListener it('should execute callback when button is clicked', () => { const output = [] // DOM events const button = document.getElementById('myButton') button.addEventListener('click', function handleClick(event) { output.push('Button clicked!') output.push(`Event type: ${event.type}`) // "click" output.push(`Target id: ${event.target.id}`) // "myButton" }) // The callback receives an Event object with details about what happened // Simulate click button.click() expect(output).toEqual([ 'Button clicked!', 'Event type: click', 'Target id: myButton' ]) }) // From lines 420-434: Named functions for reusability and removal it('should use named functions for reusability', () => { const output = [] function handleClick(event) { output.push(`Clicked: ${event.target.id}`) } function handleMouseOver(event) { output.push(`Mouseover: ${event.target.id}`) } button.addEventListener('click', handleClick) button.addEventListener('mouseover', handleMouseOver) // Simulate events button.click() button.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })) expect(output).toEqual([ 'Clicked: myButton', 'Mouseover: myButton' ]) }) it('should remove event listeners with removeEventListener', () => { const output = [] function handleClick(event) { output.push('Clicked!') } button.addEventListener('click', handleClick) // First click - handler is attached button.click() expect(output).toEqual(['Clicked!']) // Later, you can remove them: button.removeEventListener('click', handleClick) // Second click - handler is removed button.click() expect(output).toEqual(['Clicked!']) // Still just one, handler was removed }) it('should demonstrate multiple event listeners on same element', () => { const output = [] button.addEventListener('click', () => output.push('Handler 1')) button.addEventListener('click', () => output.push('Handler 2')) button.addEventListener('click', () => output.push('Handler 3')) button.click() // All handlers execute in order of registration expect(output).toEqual(['Handler 1', 'Handler 2', 'Handler 3']) }) it('should demonstrate event object properties in callback', () => { const eventData = {} button.addEventListener('click', function(event) { eventData.type = event.type eventData.target = event.target eventData.currentTarget = event.currentTarget eventData.bubbles = event.bubbles eventData.cancelable = event.cancelable }) button.click() expect(eventData.type).toBe('click') expect(eventData.target).toBe(button) expect(eventData.currentTarget).toBe(button) expect(eventData.bubbles).toBe(true) expect(eventData.cancelable).toBe(true) }) it('should demonstrate event delegation pattern with callbacks', () => { // Create a list with items const list = document.createElement('ul') list.id = 'myList' const item1 = document.createElement('li') item1.textContent = 'Item 1' item1.dataset.id = '1' const item2 = document.createElement('li') item2.textContent = 'Item 2' item2.dataset.id = '2' list.appendChild(item1) list.appendChild(item2) document.body.appendChild(list) const clickedItems = [] // Event delegation - single handler on parent list.addEventListener('click', function(event) { if (event.target.tagName === 'LI') { clickedItems.push(event.target.dataset.id) } }) item1.click() item2.click() expect(clickedItems).toEqual(['1', '2']) }) it('should demonstrate this context in event handler callbacks', () => { const results = [] // Regular function - 'this' is the element button.addEventListener('click', function(event) { results.push(`Regular: ${this.id}`) }) // Arrow function - 'this' is NOT the element (inherited from outer scope) button.addEventListener('click', (event) => { // In this context, 'this' would be the module/global scope results.push(`Arrow target: ${event.target.id}`) }) button.click() expect(results).toEqual([ 'Regular: myButton', 'Arrow target: myButton' ]) }) it('should demonstrate once option for single-fire callbacks', () => { const output = [] button.addEventListener('click', () => { output.push('Clicked!') }, { once: true }) button.click() button.click() button.click() // Handler only fires once expect(output).toEqual(['Clicked!']) }) it('should demonstrate preventing default with callbacks', () => { const form = document.createElement('form') const submitEvents = [] let defaultPrevented = false form.addEventListener('submit', function(event) { event.preventDefault() defaultPrevented = event.defaultPrevented submitEvents.push('Form submitted') }) // Dispatch a submit event const submitEvent = new Event('submit', { cancelable: true }) form.dispatchEvent(submitEvent) expect(submitEvents).toEqual(['Form submitted']) expect(defaultPrevented).toBe(true) }) it('should demonstrate stopping propagation in callbacks', () => { const output = [] // Create nested elements const outer = document.createElement('div') const inner = document.createElement('div') outer.appendChild(inner) document.body.appendChild(outer) outer.addEventListener('click', () => output.push('Outer clicked')) inner.addEventListener('click', (event) => { event.stopPropagation() output.push('Inner clicked') }) inner.click() // Only inner handler fires due to stopPropagation expect(output).toEqual(['Inner clicked']) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/functional-programming/higher-order-functions/higher-order-functions.test.js
tests/functional-programming/higher-order-functions/higher-order-functions.test.js
import { describe, it, expect, vi } from 'vitest' describe('Higher-Order Functions', () => { describe('Functions that accept functions as arguments', () => { it('should execute the passed function', () => { const mockFn = vi.fn() function doTwice(action) { action() action() } doTwice(mockFn) expect(mockFn).toHaveBeenCalledTimes(2) }) it('should repeat an action n times', () => { const results = [] function repeat(times, action) { for (let i = 0; i < times; i++) { action(i) } } repeat(5, i => results.push(i)) expect(results).toEqual([0, 1, 2, 3, 4]) }) it('should apply different logic with the same structure', () => { function calculate(numbers, operation) { const result = [] for (const num of numbers) { result.push(operation(num)) } return result } const numbers = [1, 2, 3, 4, 5] const doubled = calculate(numbers, n => n * 2) const squared = calculate(numbers, n => n * n) const incremented = calculate(numbers, n => n + 1) expect(doubled).toEqual([2, 4, 6, 8, 10]) expect(squared).toEqual([1, 4, 9, 16, 25]) expect(incremented).toEqual([2, 3, 4, 5, 6]) }) it('should implement unless as a control flow abstraction', () => { const results = [] function unless(condition, action) { if (!condition) { action() } } for (let i = 0; i < 5; i++) { unless(i % 2 === 1, () => results.push(i)) } expect(results).toEqual([0, 2, 4]) }) it('should calculate circle properties using formulas', () => { function calculate(radii, formula) { const result = [] for (const radius of radii) { result.push(formula(radius)) } return result } const area = r => Math.PI * r * r const circumference = r => 2 * Math.PI * r const diameter = r => 2 * r const volume = r => (4/3) * Math.PI * r * r * r const radii = [1, 2, 3] // Test area: π * r² const areas = calculate(radii, area) expect(areas[0]).toBeCloseTo(Math.PI, 5) // π * 1² = π expect(areas[1]).toBeCloseTo(4 * Math.PI, 5) // π * 2² = 4π expect(areas[2]).toBeCloseTo(9 * Math.PI, 5) // π * 3² = 9π // Test circumference: 2πr const circumferences = calculate(radii, circumference) expect(circumferences[0]).toBeCloseTo(2 * Math.PI, 5) // 2π * 1 expect(circumferences[1]).toBeCloseTo(4 * Math.PI, 5) // 2π * 2 expect(circumferences[2]).toBeCloseTo(6 * Math.PI, 5) // 2π * 3 // Test diameter: 2r const diameters = calculate(radii, diameter) expect(diameters).toEqual([2, 4, 6]) // Test volume: (4/3)πr³ const volumes = calculate(radii, volume) expect(volumes[0]).toBeCloseTo((4/3) * Math.PI, 5) // (4/3)π * 1³ expect(volumes[1]).toBeCloseTo((4/3) * Math.PI * 8, 5) // (4/3)π * 2³ expect(volumes[2]).toBeCloseTo((4/3) * Math.PI * 27, 5) // (4/3)π * 3³ }) }) describe('Functions that return functions', () => { it('should create a greaterThan comparator', () => { function greaterThan(n) { return function(m) { return m > n } } const greaterThan10 = greaterThan(10) const greaterThan100 = greaterThan(100) expect(greaterThan10(11)).toBe(true) expect(greaterThan10(5)).toBe(false) expect(greaterThan10(10)).toBe(false) expect(greaterThan100(150)).toBe(true) expect(greaterThan100(50)).toBe(false) }) it('should create multiplier functions', () => { function multiplier(factor) { return number => number * factor } const double = multiplier(2) const triple = multiplier(3) const tenX = multiplier(10) expect(double(5)).toBe(10) expect(triple(5)).toBe(15) expect(tenX(5)).toBe(50) expect(double(0)).toBe(0) expect(triple(-3)).toBe(-9) }) it('should wrap functions with logging behavior', () => { const logs = [] function noisy(fn) { return function(...args) { logs.push({ type: 'call', args }) const result = fn(...args) logs.push({ type: 'return', result }) return result } } const noisyMax = noisy(Math.max) const result = noisyMax(3, 1, 4, 1, 5) expect(result).toBe(5) expect(logs).toEqual([ { type: 'call', args: [3, 1, 4, 1, 5] }, { type: 'return', result: 5 } ]) }) it('should wrap Math.floor with noisy', () => { const logs = [] function noisy(fn) { return function(...args) { logs.push({ type: 'call', args }) const result = fn(...args) logs.push({ type: 'return', result }) return result } } const noisyFloor = noisy(Math.floor) const result = noisyFloor(4.7) expect(result).toBe(4) expect(logs).toEqual([ { type: 'call', args: [4.7] }, { type: 'return', result: 4 } ]) }) it('should create greeting functions with createGreeter', () => { function createGreeter(greeting) { return function(name) { return `${greeting}, ${name}!` } } const sayHello = createGreeter('Hello') const sayGoodbye = createGreeter('Goodbye') expect(sayHello('Alice')).toBe('Hello, Alice!') expect(sayHello('Bob')).toBe('Hello, Bob!') expect(sayGoodbye('Alice')).toBe('Goodbye, Alice!') }) it('should allow direct factory invocation', () => { function multiplier(factor) { return number => number * factor } // Direct invocation without storing intermediate function expect(multiplier(7)(3)).toBe(21) expect(multiplier(2)(10)).toBe(20) expect(multiplier(0.5)(100)).toBe(50) }) }) describe('Function factories', () => { it('should create validator functions', () => { function createValidator(min, max) { return function(value) { return value >= min && value <= max } } const isValidAge = createValidator(0, 120) const isValidPercentage = createValidator(0, 100) expect(isValidAge(25)).toBe(true) expect(isValidAge(150)).toBe(false) expect(isValidAge(-5)).toBe(false) expect(isValidPercentage(50)).toBe(true) expect(isValidPercentage(101)).toBe(false) }) it('should create formatter functions', () => { function createFormatter(prefix, suffix) { return function(value) { return `${prefix}${value}${suffix}` } } const formatDollars = createFormatter('$', '') const formatPercent = createFormatter('', '%') const formatParens = createFormatter('(', ')') expect(formatDollars(99.99)).toBe('$99.99') expect(formatPercent(75)).toBe('75%') expect(formatParens('aside')).toBe('(aside)') }) it('should implement partial application', () => { function partial(fn, ...presetArgs) { return function(...laterArgs) { return fn(...presetArgs, ...laterArgs) } } function greet(greeting, punctuation, name) { return `${greeting}, ${name}${punctuation}` } const sayHello = partial(greet, 'Hello', '!') const askHowAreYou = partial(greet, 'How are you', '?') expect(sayHello('Alice')).toBe('Hello, Alice!') expect(sayHello('Bob')).toBe('Hello, Bob!') expect(askHowAreYou('Charlie')).toBe('How are you, Charlie?') }) it('should create rating validator', () => { function createValidator(min, max) { return function(value) { return value >= min && value <= max } } // Rating from 1 to 5 stars const isValidRating = createValidator(1, 5) expect(isValidRating(3)).toBe(true) expect(isValidRating(1)).toBe(true) // At min expect(isValidRating(5)).toBe(true) // At max expect(isValidRating(0)).toBe(false) // Below min expect(isValidRating(6)).toBe(false) // Above max }) }) describe('Closures with higher-order functions', () => { it('should create independent counters', () => { function createCounter(start = 0) { let count = start return function() { count++ return count } } const counter1 = createCounter() const counter2 = createCounter(100) expect(counter1()).toBe(1) expect(counter1()).toBe(2) expect(counter1()).toBe(3) expect(counter2()).toBe(101) expect(counter2()).toBe(102) // counter1 should not be affected by counter2 expect(counter1()).toBe(4) }) it('should create private state with closures', () => { function createBankAccount(initialBalance) { let balance = initialBalance return { deposit(amount) { if (amount > 0) { balance += amount return balance } return balance }, withdraw(amount) { if (amount > 0 && amount <= balance) { balance -= amount return balance } return 'Insufficient funds' }, getBalance() { return balance } } } const account = createBankAccount(100) expect(account.getBalance()).toBe(100) expect(account.deposit(50)).toBe(150) expect(account.withdraw(30)).toBe(120) expect(account.withdraw(200)).toBe('Insufficient funds') expect(account.getBalance()).toBe(120) // balance is not directly accessible expect(account.balance).toBeUndefined() }) }) describe('Common mistakes', () => { it('should demonstrate the parseInt gotcha with map', () => { // This is the WRONG way - demonstrates the bug const buggyResult = ['1', '2', '3'].map(parseInt) // parseInt receives (string, index) from map // parseInt('1', 0) → 1 (radix 0 is treated as 10) // parseInt('2', 1) → NaN (radix 1 is invalid) // parseInt('3', 2) → NaN (3 is not valid in binary) expect(buggyResult).toEqual([1, NaN, NaN]) // The CORRECT way const correctResult = ['1', '2', '3'].map(str => parseInt(str, 10)) expect(correctResult).toEqual([1, 2, 3]) // Alternative correct way using Number const alternativeResult = ['1', '2', '3'].map(Number) expect(alternativeResult).toEqual([1, 2, 3]) }) it('should demonstrate losing this context', () => { const user = { name: 'Alice', greet() { // Using optional chaining to handle undefined 'this' safely return `Hello, I'm ${this?.name ?? 'undefined'}` } } // Direct call works expect(user.greet()).toBe("Hello, I'm Alice") // Passing as callback loses 'this' function callLater(fn) { return fn() } // This fails because 'this' is lost (undefined in strict mode) const lostThis = callLater(user.greet) expect(lostThis).toBe("Hello, I'm undefined") // Fix with bind const boundGreet = callLater(user.greet.bind(user)) expect(boundGreet).toBe("Hello, I'm Alice") // Fix with arrow function wrapper const wrappedGreet = callLater(() => user.greet()) expect(wrappedGreet).toBe("Hello, I'm Alice") }) it('should show difference between map and forEach return values', () => { const numbers = [1, 2, 3] // map returns a new array const mapResult = numbers.map(n => n * 2) expect(mapResult).toEqual([2, 4, 6]) // forEach returns undefined const forEachResult = numbers.forEach(n => n * 2) expect(forEachResult).toBeUndefined() }) }) describe('First-class functions', () => { it('should allow assigning functions to variables', () => { const greet = function(name) { return `Hello, ${name}!` } const add = (a, b) => a + b expect(greet('Alice')).toBe('Hello, Alice!') expect(add(2, 3)).toBe(5) }) it('should allow passing functions as arguments', () => { function callWith5(fn) { return fn(5) } expect(callWith5(n => n * 2)).toBe(10) expect(callWith5(n => n + 3)).toBe(8) expect(callWith5(Math.sqrt)).toBeCloseTo(2.236, 2) }) it('should allow returning functions from functions', () => { function createAdder(x) { return function(y) { return x + y } } const add5 = createAdder(5) const add10 = createAdder(10) expect(add5(3)).toBe(8) expect(add10(3)).toBe(13) }) }) describe('Built-in higher-order functions (overview)', () => { const numbers = [1, 2, 3, 4, 5] it('should use forEach for side effects', () => { const results = [] const returnValue = numbers.forEach(n => results.push(n * 2)) expect(results).toEqual([2, 4, 6, 8, 10]) expect(returnValue).toBeUndefined() }) it('should use map for transformations', () => { const doubled = numbers.map(n => n * 2) expect(doubled).toEqual([2, 4, 6, 8, 10]) expect(numbers).toEqual([1, 2, 3, 4, 5]) // Original unchanged }) it('should use filter for selection', () => { const evens = numbers.filter(n => n % 2 === 0) const greaterThan3 = numbers.filter(n => n > 3) expect(evens).toEqual([2, 4]) expect(greaterThan3).toEqual([4, 5]) }) it('should use reduce for accumulation', () => { const sum = numbers.reduce((acc, n) => acc + n, 0) const product = numbers.reduce((acc, n) => acc * n, 1) expect(sum).toBe(15) expect(product).toBe(120) }) it('should use find to get first matching element', () => { const firstEven = numbers.find(n => n % 2 === 0) const firstGreaterThan10 = numbers.find(n => n > 10) expect(firstEven).toBe(2) expect(firstGreaterThan10).toBeUndefined() }) it('should use some to test if any element matches', () => { const hasEven = numbers.some(n => n % 2 === 0) const hasNegative = numbers.some(n => n < 0) expect(hasEven).toBe(true) expect(hasNegative).toBe(false) }) it('should use every to test if all elements match', () => { const allPositive = numbers.every(n => n > 0) const allEven = numbers.every(n => n % 2 === 0) expect(allPositive).toBe(true) expect(allEven).toBe(false) }) it('should use sort with a comparator function', () => { const unsorted = [3, 1, 4, 1, 5, 9, 2, 6] // Ascending order const ascending = [...unsorted].sort((a, b) => a - b) expect(ascending).toEqual([1, 1, 2, 3, 4, 5, 6, 9]) // Descending order const descending = [...unsorted].sort((a, b) => b - a) expect(descending).toEqual([9, 6, 5, 4, 3, 2, 1, 1]) }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/functional-programming/map-reduce-filter/map-reduce-filter.test.js
tests/functional-programming/map-reduce-filter/map-reduce-filter.test.js
import { describe, it, expect } from 'vitest' describe('map, reduce, filter', () => { describe('map()', () => { it('should transform every element in the array', () => { const numbers = [1, 2, 3, 4] const doubled = numbers.map(n => n * 2) expect(doubled).toEqual([2, 4, 6, 8]) }) it('should not mutate the original array', () => { const original = [1, 2, 3] const mapped = original.map(n => n * 10) expect(original).toEqual([1, 2, 3]) expect(mapped).toEqual([10, 20, 30]) }) it('should pass element, index, and array to callback', () => { const letters = ['a', 'b', 'c'] const result = letters.map((letter, index, arr) => ({ letter, index, arrayLength: arr.length })) expect(result).toEqual([ { letter: 'a', index: 0, arrayLength: 3 }, { letter: 'b', index: 1, arrayLength: 3 }, { letter: 'c', index: 2, arrayLength: 3 } ]) }) it('should return undefined for elements when callback has no return', () => { const numbers = [1, 2, 3] const result = numbers.map(n => { n * 2 // No return statement }) expect(result).toEqual([undefined, undefined, undefined]) }) it('demonstrates the parseInt pitfall', () => { const strings = ['1', '2', '3'] // The pitfall: parseInt receives (element, index, array) // So it becomes parseInt('1', 0), parseInt('2', 1), parseInt('3', 2) const wrongResult = strings.map(parseInt) expect(wrongResult).toEqual([1, NaN, NaN]) // The fix: wrap in arrow function or use Number const correctResult1 = strings.map(str => parseInt(str, 10)) expect(correctResult1).toEqual([1, 2, 3]) const correctResult2 = strings.map(Number) expect(correctResult2).toEqual([1, 2, 3]) }) it('should extract properties from objects', () => { const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ] const names = users.map(user => user.name) expect(names).toEqual(['Alice', 'Bob']) }) it('should transform object shapes', () => { const users = [ { firstName: 'Alice', lastName: 'Smith' }, { firstName: 'Bob', lastName: 'Jones' } ] const fullNames = users.map(user => ({ fullName: `${user.firstName} ${user.lastName}` })) expect(fullNames).toEqual([ { fullName: 'Alice Smith' }, { fullName: 'Bob Jones' } ]) }) it('should convert strings to uppercase', () => { const words = ['hello', 'world'] const shouting = words.map(word => word.toUpperCase()) expect(shouting).toEqual(['HELLO', 'WORLD']) }) it('should square each number', () => { const numbers = [1, 2, 3, 4, 5] const squares = numbers.map(n => n * n) expect(squares).toEqual([1, 4, 9, 16, 25]) }) it('should add index prefix to each letter', () => { const letters = ['a', 'b', 'c', 'd'] const indexed = letters.map((letter, index) => `${index}: ${letter}`) expect(indexed).toEqual(['0: a', '1: b', '2: c', '3: d']) }) it('should create objects with sequential IDs from items', () => { const items = ['apple', 'banana', 'cherry'] const products = items.map((name, index) => ({ id: index + 1, name })) expect(products).toEqual([ { id: 1, name: 'apple' }, { id: 2, name: 'banana' }, { id: 3, name: 'cherry' } ]) }) }) describe('filter()', () => { it('should keep elements that pass the test', () => { const numbers = [1, 2, 3, 4, 5, 6] const evens = numbers.filter(n => n % 2 === 0) expect(evens).toEqual([2, 4, 6]) }) it('should return empty array when no elements match', () => { const numbers = [1, 3, 5, 7] const evens = numbers.filter(n => n % 2 === 0) expect(evens).toEqual([]) }) it('should not mutate the original array', () => { const original = [1, 2, 3, 4, 5] const filtered = original.filter(n => n > 3) expect(original).toEqual([1, 2, 3, 4, 5]) expect(filtered).toEqual([4, 5]) }) it('should evaluate truthy/falsy values correctly', () => { const mixed = [0, 1, '', 'hello', null, undefined, false, true] const truthy = mixed.filter(Boolean) expect(truthy).toEqual([1, 'hello', true]) }) it('should filter objects by property', () => { const users = [ { name: 'Alice', active: true }, { name: 'Bob', active: false }, { name: 'Charlie', active: true } ] const activeUsers = users.filter(user => user.active) expect(activeUsers).toEqual([ { name: 'Alice', active: true }, { name: 'Charlie', active: true } ]) }) it('demonstrates filter vs find', () => { const numbers = [1, 2, 3, 4, 5, 6] // filter returns ALL matches as an array const allEvens = numbers.filter(n => n % 2 === 0) expect(allEvens).toEqual([2, 4, 6]) // find returns the FIRST match (not an array) const firstEven = numbers.find(n => n % 2 === 0) expect(firstEven).toBe(2) }) it('should support multiple conditions', () => { const products = [ { name: 'Laptop', price: 1000, inStock: true }, { name: 'Phone', price: 500, inStock: false }, { name: 'Tablet', price: 300, inStock: true } ] const affordableInStock = products.filter( p => p.inStock && p.price < 500 ) expect(affordableInStock).toEqual([ { name: 'Tablet', price: 300, inStock: true } ]) }) it('should keep only odd numbers', () => { const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const odds = numbers.filter(n => n % 2 !== 0) expect(odds).toEqual([1, 3, 5, 7, 9]) }) it('should keep numbers greater than threshold', () => { const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const big = numbers.filter(n => n > 5) expect(big).toEqual([6, 7, 8, 9, 10]) }) it('should keep numbers in a range', () => { const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const middle = numbers.filter(n => n >= 3 && n <= 7) expect(middle).toEqual([3, 4, 5, 6, 7]) }) it('should search products by name case-insensitively', () => { const products = [ { name: 'MacBook Pro', category: 'laptops', price: 2000 }, { name: 'iPhone', category: 'phones', price: 1000 }, { name: 'iPad', category: 'tablets', price: 800 }, { name: 'Dell XPS', category: 'laptops', price: 1500 } ] const searchTerm = 'mac' const results = products.filter(p => p.name.toLowerCase().includes(searchTerm.toLowerCase()) ) expect(results).toEqual([ { name: 'MacBook Pro', category: 'laptops', price: 2000 } ]) }) it('should filter products by category', () => { const products = [ { name: 'MacBook Pro', category: 'laptops', price: 2000 }, { name: 'iPhone', category: 'phones', price: 1000 }, { name: 'iPad', category: 'tablets', price: 800 }, { name: 'Dell XPS', category: 'laptops', price: 1500 } ] const laptops = products.filter(p => p.category === 'laptops') expect(laptops).toEqual([ { name: 'MacBook Pro', category: 'laptops', price: 2000 }, { name: 'Dell XPS', category: 'laptops', price: 1500 } ]) }) it('should filter products by price range', () => { const products = [ { name: 'MacBook Pro', category: 'laptops', price: 2000 }, { name: 'iPhone', category: 'phones', price: 1000 }, { name: 'iPad', category: 'tablets', price: 800 }, { name: 'Dell XPS', category: 'laptops', price: 1500 } ] const affordable = products.filter(p => p.price <= 1000) expect(affordable).toEqual([ { name: 'iPhone', category: 'phones', price: 1000 }, { name: 'iPad', category: 'tablets', price: 800 } ]) }) }) describe('reduce()', () => { it('should combine array elements into a single value', () => { const numbers = [1, 2, 3, 4, 5] const sum = numbers.reduce((acc, n) => acc + n, 0) expect(sum).toBe(15) }) it('should use initial value as starting accumulator', () => { const numbers = [1, 2, 3] const sumStartingAt10 = numbers.reduce((acc, n) => acc + n, 10) expect(sumStartingAt10).toBe(16) // 10 + 1 + 2 + 3 }) it('should throw on empty array without initial value', () => { const empty = [] expect(() => { empty.reduce((acc, n) => acc + n) }).toThrow(TypeError) }) it('should return initial value for empty array', () => { const empty = [] const result = empty.reduce((acc, n) => acc + n, 0) expect(result).toBe(0) }) it('should count occurrences', () => { const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'] const count = fruits.reduce((acc, fruit) => { acc[fruit] = (acc[fruit] || 0) + 1 return acc }, {}) expect(count).toEqual({ apple: 3, banana: 2, orange: 1 }) }) it('should group by property', () => { const people = [ { name: 'Alice', department: 'Engineering' }, { name: 'Bob', department: 'Marketing' }, { name: 'Charlie', department: 'Engineering' } ] const byDepartment = people.reduce((acc, person) => { const dept = person.department if (!acc[dept]) { acc[dept] = [] } acc[dept].push(person.name) return acc }, {}) expect(byDepartment).toEqual({ Engineering: ['Alice', 'Charlie'], Marketing: ['Bob'] }) }) it('should build objects from arrays', () => { const pairs = [['a', 1], ['b', 2], ['c', 3]] const obj = pairs.reduce((acc, [key, value]) => { acc[key] = value return acc }, {}) expect(obj).toEqual({ a: 1, b: 2, c: 3 }) }) it('can implement map with reduce', () => { const numbers = [1, 2, 3, 4] const doubled = numbers.reduce((acc, n) => { acc.push(n * 2) return acc }, []) expect(doubled).toEqual([2, 4, 6, 8]) }) it('can implement filter with reduce', () => { const numbers = [1, 2, 3, 4, 5, 6] const evens = numbers.reduce((acc, n) => { if (n % 2 === 0) { acc.push(n) } return acc }, []) expect(evens).toEqual([2, 4, 6]) }) it('should calculate average', () => { const numbers = [10, 20, 30, 40, 50] const sum = numbers.reduce((acc, n) => acc + n, 0) const average = sum / numbers.length expect(average).toBe(30) }) it('should find max value', () => { const numbers = [5, 2, 9, 1, 7] const max = numbers.reduce((acc, n) => n > acc ? n : acc, numbers[0]) expect(max).toBe(9) }) it('should find minimum value', () => { const numbers = [5, 2, 9, 1, 7] const min = numbers.reduce((acc, n) => n < acc ? n : acc, numbers[0]) expect(min).toBe(1) }) it('should flatten nested arrays with reduce', () => { const nested = [[1, 2], [3, 4], [5, 6]] const flat = nested.reduce((acc, arr) => acc.concat(arr), []) expect(flat).toEqual([1, 2, 3, 4, 5, 6]) }) it('should implement myMap using reduce inline', () => { const array = [1, 2, 3] const callback = n => n * 2 // myMap implementation from concept page const result = array.reduce((acc, element, index) => { acc.push(callback(element, index, array)) return acc }, []) expect(result).toEqual([2, 4, 6]) }) }) describe('Method Chaining', () => { it('should chain filter → map → reduce', () => { const products = [ { name: 'Laptop', price: 1000, inStock: true }, { name: 'Phone', price: 500, inStock: false }, { name: 'Tablet', price: 300, inStock: true }, { name: 'Watch', price: 200, inStock: true } ] const totalInStock = products .filter(p => p.inStock) .map(p => p.price) .reduce((sum, price) => sum + price, 0) expect(totalInStock).toBe(1500) }) it('demonstrates real-world data pipeline', () => { const transactions = [ { type: 'sale', amount: 100 }, { type: 'refund', amount: 30 }, { type: 'sale', amount: 200 }, { type: 'sale', amount: 150 }, { type: 'refund', amount: 50 } ] // Calculate total sales (not refunds) const totalSales = transactions .filter(t => t.type === 'sale') .map(t => t.amount) .reduce((sum, amount) => sum + amount, 0) expect(totalSales).toBe(450) // Calculate net (sales - refunds) const net = transactions.reduce((acc, t) => { return t.type === 'sale' ? acc + t.amount : acc - t.amount }, 0) expect(net).toBe(370) // 450 - 80 }) it('should get active premium users emails', () => { const users = [ { email: 'alice@example.com', active: true, plan: 'premium' }, { email: 'bob@example.com', active: false, plan: 'premium' }, { email: 'charlie@example.com', active: true, plan: 'free' }, { email: 'diana@example.com', active: true, plan: 'premium' } ] const premiumEmails = users .filter(u => u.active) .filter(u => u.plan === 'premium') .map(u => u.email) expect(premiumEmails).toEqual([ 'alice@example.com', 'diana@example.com' ]) }) it('should calculate cart total with discounts', () => { const cart = [ { name: 'Laptop', price: 1000, quantity: 1, discountPercent: 10 }, { name: 'Mouse', price: 50, quantity: 2, discountPercent: 0 }, { name: 'Keyboard', price: 100, quantity: 1, discountPercent: 20 } ] const total = cart .map(item => { const subtotal = item.price * item.quantity const discount = subtotal * (item.discountPercent / 100) return subtotal - discount }) .reduce((sum, price) => sum + price, 0) // Laptop: 1000 * 1 - 10% = 900 // Mouse: 50 * 2 - 0% = 100 // Keyboard: 100 * 1 - 20% = 80 // Total: 900 + 100 + 80 = 1080 expect(total).toBe(1080) }) it('should get top 3 performers sorted by sales', () => { const salespeople = [ { name: 'Alice', sales: 50000 }, { name: 'Bob', sales: 75000 }, { name: 'Charlie', sales: 45000 }, { name: 'Diana', sales: 90000 }, { name: 'Eve', sales: 60000 } ] const top3 = salespeople .filter(p => p.sales >= 50000) .sort((a, b) => b.sales - a.sales) .slice(0, 3) .map(p => p.name) expect(top3).toEqual(['Diana', 'Bob', 'Eve']) }) }) describe('Other Array Methods', () => { it('find() returns first matching element', () => { const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' } ] const bob = users.find(u => u.id === 2) expect(bob).toEqual({ id: 2, name: 'Bob' }) const notFound = users.find(u => u.id === 999) expect(notFound).toBeUndefined() }) it('some() returns true if any element matches', () => { const numbers = [1, 2, 3, 4, 5] expect(numbers.some(n => n > 4)).toBe(true) expect(numbers.some(n => n > 10)).toBe(false) }) it('every() returns true if all elements match', () => { const numbers = [2, 4, 6, 8] expect(numbers.every(n => n % 2 === 0)).toBe(true) expect(numbers.every(n => n > 5)).toBe(false) }) it('includes() checks for value membership', () => { const fruits = ['apple', 'banana', 'orange'] expect(fruits.includes('banana')).toBe(true) expect(fruits.includes('grape')).toBe(false) }) it('findIndex() returns index of first match', () => { const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ] const bobIndex = users.findIndex(u => u.name === 'Bob') expect(bobIndex).toBe(1) const notFoundIndex = users.findIndex(u => u.name === 'Eve') expect(notFoundIndex).toBe(-1) }) it('flat() flattens nested arrays', () => { const nested = [[1, 2], [3, 4], [5, 6]] expect(nested.flat()).toEqual([1, 2, 3, 4, 5, 6]) const deepNested = [1, [2, [3, [4]]]] expect(deepNested.flat(2)).toEqual([1, 2, 3, [4]]) expect(deepNested.flat(Infinity)).toEqual([1, 2, 3, 4]) }) it('flatMap() maps then flattens', () => { const sentences = ['hello world', 'foo bar'] const words = sentences.flatMap(s => s.split(' ')) expect(words).toEqual(['hello', 'world', 'foo', 'bar']) }) }) describe('Common Mistakes', () => { it('demonstrates mutation issue in map', () => { const users = [ { name: 'Alice', score: 85 }, { name: 'Bob', score: 92 } ] // ❌ WRONG: This mutates the original objects const mutated = users.map(user => { user.score += 5 // Mutates original! return user }) expect(users[0].score).toBe(90) // Original was mutated! // Reset for next test const users2 = [ { name: 'Alice', score: 85 }, { name: 'Bob', score: 92 } ] // ✓ CORRECT: Create new objects const notMutated = users2.map(user => ({ ...user, score: user.score + 5 })) expect(users2[0].score).toBe(85) // Original unchanged expect(notMutated[0].score).toBe(90) }) it('demonstrates reduce without initial value type issues', () => { const products = [ { name: 'Laptop', price: 1000 }, { name: 'Phone', price: 500 } ] // ❌ WRONG: Without initial value, first element becomes accumulator // This would try to add 500 to an object, resulting in string concatenation const wrongTotal = products.reduce((acc, p) => acc + p.price) expect(typeof wrongTotal).toBe('string') // "[object Object]500" // ✓ CORRECT: Provide initial value const correctTotal = products.reduce((acc, p) => acc + p.price, 0) expect(correctTotal).toBe(1500) }) it('demonstrates forgetting to return accumulator in reduce', () => { const numbers = [1, 2, 3, 4] // ❌ WRONG: No return const wrong = numbers.reduce((acc, n) => { acc + n // Missing return! }, 0) expect(wrong).toBeUndefined() // ✓ CORRECT: Return accumulator const correct = numbers.reduce((acc, n) => { return acc + n }, 0) expect(correct).toBe(10) }) it('shows filter+map is clearer than complex reduce', () => { const users = [ { name: 'Alice', active: true }, { name: 'Bob', active: false }, { name: 'Charlie', active: true } ] // Complex reduce approach const resultReduce = users.reduce((acc, user) => { if (user.active) { acc.push(user.name.toUpperCase()) } return acc }, []) // Clearer filter + map approach const resultFilterMap = users .filter(u => u.active) .map(u => u.name.toUpperCase()) // Both should produce the same result expect(resultReduce).toEqual(['ALICE', 'CHARLIE']) expect(resultFilterMap).toEqual(['ALICE', 'CHARLIE']) }) }) describe('Test Your Knowledge Examples', () => { it('Q6: filter evens, triple, sum equals 18', () => { const result = [1, 2, 3, 4, 5] .filter(n => n % 2 === 0) .map(n => n * 3) .reduce((sum, n) => sum + n, 0) // filter: [2, 4] // map: [6, 12] // reduce: 6 + 12 = 18 expect(result).toBe(18) }) }) describe('ES2023+ Array Methods', () => { it('reduceRight() reduces from right to left', () => { const letters = ['a', 'b', 'c'] const result = letters.reduceRight((acc, s) => acc + s, '') expect(result).toBe('cba') }) it('toSorted() returns sorted copy without mutating original', () => { const nums = [3, 1, 2] const sorted = nums.toSorted() expect(sorted).toEqual([1, 2, 3]) expect(nums).toEqual([3, 1, 2]) // Original unchanged }) it('toReversed() returns reversed copy without mutating original', () => { const nums = [1, 2, 3] const reversed = nums.toReversed() expect(reversed).toEqual([3, 2, 1]) expect(nums).toEqual([1, 2, 3]) // Original unchanged }) it('toSpliced() returns modified copy without mutating original', () => { const nums = [1, 2, 3, 4, 5] const spliced = nums.toSpliced(1, 2, 'a', 'b') expect(spliced).toEqual([1, 'a', 'b', 4, 5]) expect(nums).toEqual([1, 2, 3, 4, 5]) // Original unchanged }) it('Object.groupBy() groups elements by key (ES2024, Node 21+)', () => { // Skip test if Object.groupBy is not available (requires Node 21+) if (typeof Object.groupBy !== 'function') { console.log('Skipping: Object.groupBy not available in this Node version') return } const people = [ { name: 'Alice', department: 'Engineering' }, { name: 'Bob', department: 'Marketing' }, { name: 'Charlie', department: 'Engineering' } ] const byDepartment = Object.groupBy(people, person => person.department) expect(byDepartment.Engineering).toEqual([ { name: 'Alice', department: 'Engineering' }, { name: 'Charlie', department: 'Engineering' } ]) expect(byDepartment.Marketing).toEqual([ { name: 'Bob', department: 'Marketing' } ]) }) }) describe('Async Callbacks', () => { it('map with async returns array of Promises', async () => { const ids = [1, 2, 3] // Simulate async operation const asyncDouble = async (n) => n * 2 // Without Promise.all, you get Promises const promiseArray = ids.map(id => asyncDouble(id)) expect(promiseArray[0]).toBeInstanceOf(Promise) // With Promise.all, you get resolved values const results = await Promise.all(promiseArray) expect(results).toEqual([2, 4, 6]) }) it('async filter workaround using map then filter', async () => { const numbers = [1, 2, 3, 4, 5] // Simulate async predicate const asyncIsEven = async (n) => n % 2 === 0 // Step 1: Get boolean results for each element const checks = await Promise.all(numbers.map(n => asyncIsEven(n))) // Step 2: Filter using the boolean results const evens = numbers.filter((_, index) => checks[index]) expect(evens).toEqual([2, 4]) }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/functional-programming/pure-functions/pure-functions.test.js
tests/functional-programming/pure-functions/pure-functions.test.js
import { describe, it, expect } from 'vitest' describe('Pure Functions', () => { describe('Rule 1: Same Input → Same Output', () => { it('should always return the same result for the same inputs', () => { // Pure function: deterministic function add(a, b) { return a + b } expect(add(2, 3)).toBe(5) expect(add(2, 3)).toBe(5) expect(add(2, 3)).toBe(5) // Always 5, no matter how many times we call it }) it('should demonstrate Math.max as a pure function', () => { // Math.max is pure: same inputs always give same output expect(Math.max(2, 8, 5)).toBe(8) expect(Math.max(2, 8, 5)).toBe(8) expect(Math.max(-1, -5, -2)).toBe(-1) }) it('should show how external state breaks purity', () => { // Impure: depends on external state let taxRate = 0.08 function calculateTotalImpure(price) { return price + price * taxRate } expect(calculateTotalImpure(100)).toBe(108) // Changing external state changes the result taxRate = 0.10 expect(calculateTotalImpure(100)).toBe(110) // Different! // Pure version: all dependencies are parameters function calculateTotalPure(price, rate) { return price + price * rate } expect(calculateTotalPure(100, 0.08)).toBe(108) expect(calculateTotalPure(100, 0.08)).toBe(108) // Always the same expect(calculateTotalPure(100, 0.10)).toBe(110) // Different input = different output (that's fine) }) it('should demonstrate that Math.random makes functions impure', () => { // ❌ IMPURE: Output depends on randomness function randomDouble(x) { return x * Math.random() } // Same input but (almost certainly) different outputs const results = new Set() for (let i = 0; i < 10; i++) { results.add(randomDouble(5)) } // With random, we get multiple different results for the same input expect(results.size).toBeGreaterThan(1) }) it('should demonstrate that Date makes functions impure', () => { // ❌ IMPURE: Output depends on when you call it function getGreeting(name) { const hour = new Date().getHours() if (hour < 12) return `Good morning, ${name}` return `Good afternoon, ${name}` } // The function works, but its output depends on external state (time) const result = getGreeting('Alice') expect(result).toMatch(/Good (morning|afternoon), Alice/) // To make it pure, pass the hour as a parameter function getGreetingPure(name, hour) { if (hour < 12) return `Good morning, ${name}` return `Good afternoon, ${name}` } // Now it's deterministic expect(getGreetingPure('Alice', 9)).toBe('Good morning, Alice') expect(getGreetingPure('Alice', 9)).toBe('Good morning, Alice') // Always same expect(getGreetingPure('Alice', 14)).toBe('Good afternoon, Alice') }) }) describe('Rule 2: No Side Effects', () => { it('should demonstrate addToTotal impure pattern from docs', () => { // ❌ IMPURE: Breaks rule 2 (has a side effect) let total = 0 function addToTotal(x) { total += x // Modifies external variable! return total } expect(addToTotal(5)).toBe(5) expect(addToTotal(5)).toBe(10) // Different result because total changed expect(addToTotal(5)).toBe(15) // Keeps changing! // The function modifies external state, making it impure expect(total).toBe(15) }) it('should demonstrate mutation as a side effect', () => { // Impure: mutates the input function addItemImpure(cart, item) { cart.push(item) return cart } const myCart = ['apple', 'banana'] const result = addItemImpure(myCart, 'orange') expect(myCart).toEqual(['apple', 'banana', 'orange']) // Original mutated! expect(result).toBe(myCart) // Same reference }) it('should show pure alternative that returns new array', () => { // Pure: returns new array, original unchanged function addItemPure(cart, item) { return [...cart, item] } const myCart = ['apple', 'banana'] const newCart = addItemPure(myCart, 'orange') expect(myCart).toEqual(['apple', 'banana']) // Original unchanged! expect(newCart).toEqual(['apple', 'banana', 'orange']) expect(myCart).not.toBe(newCart) // Different references }) it('should demonstrate external variable modification as a side effect', () => { let counter = 0 // Impure: modifies external variable function incrementImpure() { counter++ return counter } expect(incrementImpure()).toBe(1) expect(incrementImpure()).toBe(2) // Different result for same (no) input! expect(incrementImpure()).toBe(3) // Pure alternative function incrementPure(value) { return value + 1 } expect(incrementPure(0)).toBe(1) expect(incrementPure(0)).toBe(1) // Always the same expect(incrementPure(5)).toBe(6) }) it('should demonstrate processUser impure vs pure from docs', () => { // ❌ IMPURE: Multiple side effects let userCount = 0 const loginTime = new Date('2025-01-01T10:00:00') function processUserImpure(user) { user.lastLogin = loginTime // Side effect: mutates input userCount++ // Side effect: modifies external variable return user } const user1 = { name: 'Alice' } const result1 = processUserImpure(user1) expect(user1.lastLogin).toEqual(loginTime) // Original mutated! expect(userCount).toBe(1) // External state changed! expect(result1).toBe(user1) // Same reference // ✓ PURE: Returns new data, no side effects function processUserPure(user, loginTime) { return { ...user, lastLogin: loginTime } } const user2 = { name: 'Bob' } const result2 = processUserPure(user2, loginTime) expect(user2.lastLogin).toBe(undefined) // Original unchanged! expect(result2.lastLogin).toEqual(loginTime) expect(result2).not.toBe(user2) // Different reference expect(result2.name).toBe('Bob') }) }) describe('Identifying Pure vs Impure Functions', () => { it('should identify pure mathematical functions', () => { function double(x) { return x * 2 } function square(x) { return x * x } function hypotenuse(a, b) { return Math.sqrt(a * a + b * b) } // All pure: same inputs always give same outputs expect(double(5)).toBe(10) expect(square(4)).toBe(16) expect(hypotenuse(3, 4)).toBe(5) }) it('should identify pure string functions', () => { function formatName(name) { return name.trim().toLowerCase() } function greet(name, greeting) { return `${greeting}, ${name}!` } expect(formatName(' ALICE ')).toBe('alice') expect(formatName(' ALICE ')).toBe('alice') // Same result expect(greet('Bob', 'Hello')).toBe('Hello, Bob!') }) it('should identify pure validation functions', () => { function isValidEmail(email) { return email.includes('@') && email.includes('.') } function isPositive(num) { return num > 0 } expect(isValidEmail('test@example.com')).toBe(true) expect(isValidEmail('invalid')).toBe(false) expect(isPositive(5)).toBe(true) expect(isPositive(-3)).toBe(false) }) }) describe('Immutable Object Patterns', () => { it('should update object properties without mutation', () => { const user = { name: 'Alice', age: 25 } // Pure: returns new object function updateAge(user, newAge) { return { ...user, age: newAge } } const updatedUser = updateAge(user, 26) expect(user.age).toBe(25) // Original unchanged expect(updatedUser.age).toBe(26) expect(user).not.toBe(updatedUser) }) it('should add properties without mutation', () => { const product = { name: 'Widget', price: 10 } function addDiscount(product, discount) { return { ...product, discount } } const discountedProduct = addDiscount(product, 0.1) expect(product.discount).toBe(undefined) // Original unchanged expect(discountedProduct.discount).toBe(0.1) }) it('should remove properties without mutation', () => { const user = { name: 'Alice', age: 25, password: 'secret' } function removePassword(user) { const { password, ...rest } = user return rest } const safeUser = removePassword(user) expect(user.password).toBe('secret') // Original unchanged expect(safeUser.password).toBe(undefined) expect(safeUser).toEqual({ name: 'Alice', age: 25 }) }) }) describe('Immutable Array Patterns', () => { it('should add items without mutation', () => { const todos = ['Learn JS', 'Build app'] // Pure: returns new array function addTodo(todos, newTodo) { return [...todos, newTodo] } const newTodos = addTodo(todos, 'Deploy') expect(todos).toEqual(['Learn JS', 'Build app']) // Original unchanged expect(newTodos).toEqual(['Learn JS', 'Build app', 'Deploy']) }) it('should remove items without mutation', () => { const numbers = [1, 2, 3, 4, 5] // Pure: filter creates new array function removeItem(arr, index) { return arr.filter((_, i) => i !== index) } const result = removeItem(numbers, 2) // Remove item at index 2 expect(numbers).toEqual([1, 2, 3, 4, 5]) // Original unchanged expect(result).toEqual([1, 2, 4, 5]) }) it('should update items without mutation', () => { const todos = [ { id: 1, text: 'Learn JS', done: false }, { id: 2, text: 'Build app', done: false } ] function completeTodo(todos, id) { return todos.map((todo) => (todo.id === id ? { ...todo, done: true } : todo)) } const updated = completeTodo(todos, 1) expect(todos[0].done).toBe(false) // Original unchanged expect(updated[0].done).toBe(true) expect(updated[1].done).toBe(false) }) it('should sort without mutation using spread', () => { const numbers = [3, 1, 4, 1, 5, 9, 2, 6] // Impure: sort mutates the original function sortImpure(arr) { return arr.sort((a, b) => a - b) } // Pure: copy first function sortPure(arr) { return [...arr].sort((a, b) => a - b) } const sorted = sortPure(numbers) expect(numbers).toEqual([3, 1, 4, 1, 5, 9, 2, 6]) // Original unchanged expect(sorted).toEqual([1, 1, 2, 3, 4, 5, 6, 9]) }) it('should use toSorted for non-mutating sort (ES2023)', () => { const numbers = [3, 1, 4, 1, 5] const sorted = numbers.toSorted((a, b) => a - b) expect(numbers).toEqual([3, 1, 4, 1, 5]) // Original unchanged expect(sorted).toEqual([1, 1, 3, 4, 5]) }) it('should use toReversed for non-mutating reverse (ES2023)', () => { const letters = ['a', 'b', 'c', 'd'] const reversed = letters.toReversed() expect(letters).toEqual(['a', 'b', 'c', 'd']) // Original unchanged expect(reversed).toEqual(['d', 'c', 'b', 'a']) }) }) describe('Deep Copy for Nested Objects', () => { it('should demonstrate shallow copy problem with nested objects', () => { const user = { name: 'Alice', address: { city: 'NYC', zip: '10001' } } // Shallow copy - nested object is shared! const shallowCopy = { ...user } shallowCopy.address.city = 'LA' expect(user.address.city).toBe('LA') // Original changed! }) it('should use structuredClone for deep copy', () => { const user = { name: 'Alice', address: { city: 'NYC', zip: '10001' } } const deepCopy = structuredClone(user) deepCopy.address.city = 'LA' expect(user.address.city).toBe('NYC') // Original unchanged! expect(deepCopy.address.city).toBe('LA') }) it('should safely update nested properties in pure function', () => { const user = { name: 'Alice', address: { city: 'NYC', zip: '10001' } } // Pure function using structuredClone function updateCity(user, newCity) { const copy = structuredClone(user) copy.address.city = newCity return copy } // Alternative: spread at each level function updateCitySpread(user, newCity) { return { ...user, address: { ...user.address, city: newCity } } } const updated1 = updateCity(user, 'LA') const updated2 = updateCitySpread(user, 'Boston') expect(user.address.city).toBe('NYC') // Original unchanged expect(updated1.address.city).toBe('LA') expect(updated2.address.city).toBe('Boston') }) }) describe('Common Mistakes', () => { it('should avoid mutating function parameters', () => { // Bad: mutates the parameter function processUserBad(user) { user.processed = true user.name = user.name.toUpperCase() return user } // Good: returns new object function processUserGood(user) { return { ...user, processed: true, name: user.name.toUpperCase() } } const user = { name: 'alice', age: 25 } const result = processUserGood(user) expect(user.processed).toBe(undefined) // Original unchanged expect(user.name).toBe('alice') expect(result.processed).toBe(true) expect(result.name).toBe('ALICE') }) it('should avoid relying on external mutable state', () => { // Bad: relies on external config const config = { multiplier: 2 } function calculateBad(value) { return value * config.multiplier } // Good: config passed as parameter function calculateGood(value, multiplier) { return value * multiplier } expect(calculateGood(5, 2)).toBe(10) expect(calculateGood(5, 2)).toBe(10) // Always predictable }) it('should be careful with array methods that mutate', () => { const numbers = [3, 1, 2] // These methods MUTATE the original array: // sort(), reverse(), splice(), push(), pop(), shift(), unshift(), fill() // Safe alternatives: const sorted = [...numbers].sort((a, b) => a - b) // Copy first const reversed = [...numbers].reverse() // Copy first const withNew = [...numbers, 4] // Spread instead of push expect(numbers).toEqual([3, 1, 2]) // Original unchanged expect(sorted).toEqual([1, 2, 3]) expect(reversed).toEqual([2, 1, 3]) expect(withNew).toEqual([3, 1, 2, 4]) }) }) describe('Practical Pure Function Examples', () => { it('should calculate shopping cart total purely', () => { function calculateTotal(items, taxRate) { const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0) const tax = subtotal * taxRate return { subtotal, tax, total: subtotal + tax } } const items = [ { name: 'Widget', price: 10, quantity: 2 }, { name: 'Gadget', price: 25, quantity: 1 } ] const result = calculateTotal(items, 0.08) expect(result.subtotal).toBe(45) expect(result.tax).toBeCloseTo(3.6) expect(result.total).toBeCloseTo(48.6) // Original items unchanged expect(items[0].name).toBe('Widget') }) it('should filter and transform data purely', () => { function getActiveUserNames(users) { return users.filter((user) => user.active).map((user) => user.name.toLowerCase()) } const users = [ { name: 'ALICE', active: true }, { name: 'BOB', active: false }, { name: 'CHARLIE', active: true } ] const result = getActiveUserNames(users) expect(result).toEqual(['alice', 'charlie']) expect(users[0].name).toBe('ALICE') // Original unchanged }) it('should compose pure functions', () => { const trim = (str) => str.trim() const toLowerCase = (str) => str.toLowerCase() const removeSpaces = (str) => str.replace(/\s+/g, '-') function slugify(title) { return removeSpaces(toLowerCase(trim(title))) } expect(slugify(' Hello World ')).toBe('hello-world') expect(slugify(' JavaScript Is Fun ')).toBe('javascript-is-fun') }) it('should validate data purely', () => { function validateUser(user) { const errors = [] if (!user.name || user.name.length < 2) { errors.push('Name must be at least 2 characters') } if (!user.email || !user.email.includes('@')) { errors.push('Valid email is required') } if (!user.age || user.age < 0) { errors.push('Age must be a positive number') } return { isValid: errors.length === 0, errors } } const validUser = { name: 'Alice', email: 'alice@example.com', age: 25 } const invalidUser = { name: 'A', email: 'invalid', age: -5 } expect(validateUser(validUser).isValid).toBe(true) expect(validateUser(validUser).errors).toEqual([]) expect(validateUser(invalidUser).isValid).toBe(false) expect(validateUser(invalidUser).errors).toHaveLength(3) }) }) describe('Benefits of Pure Functions', () => { it('should be easy to test (no setup needed)', () => { // Pure functions are trivial to test function add(a, b) { return a + b } // No mocking, no setup, no cleanup expect(add(1, 2)).toBe(3) expect(add(-1, 1)).toBe(0) expect(add(0.1, 0.2)).toBeCloseTo(0.3) }) it('should be safe to memoize', () => { let callCount = 0 // Pure function - safe to cache function expensiveCalculation(n) { callCount++ let result = 0 for (let i = 0; i < n; i++) { result += i } return result } // Simple memoization function memoize(fn) { const cache = new Map() return function (arg) { if (cache.has(arg)) { return cache.get(arg) } const result = fn(arg) cache.set(arg, result) return result } } const memoizedCalc = memoize(expensiveCalculation) // First call computes expect(memoizedCalc(1000)).toBe(499500) expect(callCount).toBe(1) // Second call returns cached result expect(memoizedCalc(1000)).toBe(499500) expect(callCount).toBe(1) // Not called again! // Different input computes again expect(memoizedCalc(500)).toBe(124750) expect(callCount).toBe(2) }) it('should demonstrate fibonacci as a pure function safe for memoization', () => { // Expensive calculation - safe to cache because it's pure function fibonacci(n) { if (n <= 1) return n return fibonacci(n - 1) + fibonacci(n - 2) } // Pure: same input always gives same output expect(fibonacci(0)).toBe(0) expect(fibonacci(1)).toBe(1) expect(fibonacci(2)).toBe(1) expect(fibonacci(3)).toBe(2) expect(fibonacci(4)).toBe(3) expect(fibonacci(5)).toBe(5) expect(fibonacci(10)).toBe(55) // Call multiple times - always same result expect(fibonacci(10)).toBe(55) expect(fibonacci(10)).toBe(55) }) }) describe('Examples from Q&A Section', () => { it('should demonstrate multiply as a pure function', () => { // Pure: follows both rules function multiply(a, b) { return a * b } expect(multiply(3, 4)).toBe(12) expect(multiply(3, 4)).toBe(12) // Always the same expect(multiply(-2, 5)).toBe(-10) expect(multiply(0, 100)).toBe(0) }) it('should demonstrate greet impure vs pure', () => { // ❌ IMPURE: Uses new Date() - output varies with time function greetImpure(name) { return `Hello, ${name}! The time is ${new Date().toLocaleTimeString()}` } // The impure version includes time, making results unpredictable const result1 = greetImpure('Alice') expect(result1).toContain('Hello, Alice!') expect(result1).toContain('The time is') // ✓ PURE: Pass time as a parameter function greetPure(name, time) { return `Hello, ${name}! The time is ${time}` } expect(greetPure('Alice', '10:00:00 AM')).toBe('Hello, Alice! The time is 10:00:00 AM') expect(greetPure('Alice', '10:00:00 AM')).toBe('Hello, Alice! The time is 10:00:00 AM') // Always same expect(greetPure('Bob', '3:00:00 PM')).toBe('Hello, Bob! The time is 3:00:00 PM') }) it('should demonstrate calculateTax as a pure function', () => { // If calculateTax(100, 0.08) returns the wrong value, // the bug MUST be inside calculateTax. // No need to check what other code ran before it. function calculateTax(amount, rate) { return amount * rate } expect(calculateTax(100, 0.08)).toBe(8) expect(calculateTax(100, 0.08)).toBe(8) // Always the same expect(calculateTax(250, 0.1)).toBe(25) expect(calculateTax(0, 0.08)).toBe(0) }) it('should demonstrate formatPrice as a pure function', () => { // You can understand this function completely by reading it function formatPrice(cents, currency = 'USD') { const dollars = cents / 100 return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(dollars) } expect(formatPrice(1999)).toBe('$19.99') expect(formatPrice(1999)).toBe('$19.99') // Always the same expect(formatPrice(500)).toBe('$5.00') expect(formatPrice(9999, 'USD')).toBe('$99.99') expect(formatPrice(1000, 'EUR')).toBe('€10.00') }) it('should demonstrate addToCart fix from Q&A', () => { // ❌ WRONG: This function mutates its input function addToCartBad(cart, item) { cart.push(item) return cart } const cart1 = ['apple'] const result1 = addToCartBad(cart1, 'banana') expect(cart1).toEqual(['apple', 'banana']) // Original mutated! expect(result1).toBe(cart1) // Same reference // ✓ CORRECT: Fix it by returning a new array function addToCartGood(cart, item) { return [...cart, item] } const cart2 = ['apple'] const result2 = addToCartGood(cart2, 'banana') expect(cart2).toEqual(['apple']) // Original unchanged! expect(result2).toEqual(['apple', 'banana']) expect(result2).not.toBe(cart2) // Different reference }) it('should demonstrate updateCity with structuredClone from Q&A', () => { const user = { name: 'Alice', address: { city: 'NYC', zip: '10001' } } // Option 1: structuredClone (simplest) function updateCityClone(user, newCity) { const copy = structuredClone(user) copy.address.city = newCity return copy } const updated1 = updateCityClone(user, 'LA') expect(user.address.city).toBe('NYC') // Original unchanged expect(updated1.address.city).toBe('LA') // Option 2: Spread at each level function updateCitySpread(user, newCity) { return { ...user, address: { ...user.address, city: newCity } } } const updated2 = updateCitySpread(user, 'Boston') expect(user.address.city).toBe('NYC') // Original still unchanged expect(updated2.address.city).toBe('Boston') }) }) describe('Examples from Accordion Sections', () => { it('should demonstrate testing pure functions is trivial', () => { // Testing a pure function - simple and straightforward function add(a, b) { return a + b } function formatName(name) { return name.trim().toLowerCase() } function isValidEmail(email) { return email.includes('@') && email.includes('.') } // No mocking, no setup - just input and expected output expect(add(2, 3)).toBe(5) expect(formatName(' ALICE ')).toBe('alice') expect(isValidEmail('test@example.com')).toBe(true) expect(isValidEmail('invalid')).toBe(false) }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/functional-programming/recursion/recursion.test.js
tests/functional-programming/recursion/recursion.test.js
import { describe, it, expect } from 'vitest' import { JSDOM } from 'jsdom' describe('Recursion', () => { describe('Base Case Handling', () => { it('should return immediately when base case is met', () => { function countdown(n) { if (n <= 0) return 'done' return countdown(n - 1) } expect(countdown(0)).toBe('done') expect(countdown(-1)).toBe('done') }) it('should demonstrate countdown pattern from MDX opening example', () => { // Exact implementation from MDX lines 9-17 (modified to collect output) // Original uses console.log, we collect to array for testing function countdown(n, output = []) { if (n === 0) { output.push('Done!') return output } output.push(n) return countdown(n - 1, output) } // MDX example: countdown(3) outputs 3, 2, 1, Done! expect(countdown(3)).toEqual([3, 2, 1, 'Done!']) expect(countdown(1)).toEqual([1, 'Done!']) expect(countdown(0)).toEqual(['Done!']) }) it('should throw RangeError for infinite recursion (missing base case)', () => { function infiniteRecursion(n) { // No base case - will crash return infiniteRecursion(n - 1) } expect(() => infiniteRecursion(5)).toThrow(RangeError) }) it('should handle base case that returns a value', () => { function sumTo(n) { if (n === 1) return 1 return n + sumTo(n - 1) } expect(sumTo(1)).toBe(1) }) }) describe('Classic Algorithms', () => { describe('Factorial', () => { function factorial(n) { if (n <= 1) return 1 return n * factorial(n - 1) } it('should calculate factorial correctly', () => { expect(factorial(5)).toBe(120) expect(factorial(4)).toBe(24) expect(factorial(3)).toBe(6) }) it('should handle edge cases (0! = 1, 1! = 1)', () => { expect(factorial(0)).toBe(1) expect(factorial(1)).toBe(1) }) it('should handle larger numbers', () => { expect(factorial(10)).toBe(3628800) }) }) describe('Fibonacci', () => { // Memoized version for efficiency function fibonacci(n, memo = {}) { if (n in memo) return memo[n] if (n <= 1) return n memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo) return memo[n] } it('should return correct Fibonacci numbers', () => { expect(fibonacci(6)).toBe(8) expect(fibonacci(7)).toBe(13) expect(fibonacci(10)).toBe(55) }) it('should handle base cases (fib(0) = 0, fib(1) = 1)', () => { expect(fibonacci(0)).toBe(0) expect(fibonacci(1)).toBe(1) }) it('should handle larger numbers efficiently with memoization', () => { expect(fibonacci(50)).toBe(12586269025) }) it('should follow the Fibonacci sequence pattern', () => { // Each number is sum of two preceding ones const sequence = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] sequence.forEach((expected, index) => { expect(fibonacci(index)).toBe(expected) }) }) }) describe('Sum to N', () => { function sumTo(n) { if (n <= 1) return n return n + sumTo(n - 1) } it('should sum numbers from 1 to n', () => { expect(sumTo(5)).toBe(15) // 1+2+3+4+5 expect(sumTo(10)).toBe(55) expect(sumTo(100)).toBe(5050) }) it('should handle base cases', () => { expect(sumTo(1)).toBe(1) expect(sumTo(0)).toBe(0) }) }) describe('Power Function', () => { function power(x, n) { if (n === 0) return 1 return x * power(x, n - 1) } it('should calculate x^n correctly', () => { expect(power(2, 3)).toBe(8) expect(power(2, 10)).toBe(1024) expect(power(3, 4)).toBe(81) }) it('should handle power of 0', () => { expect(power(5, 0)).toBe(1) expect(power(100, 0)).toBe(1) }) it('should handle power of 1', () => { expect(power(7, 1)).toBe(7) }) }) describe('Power Function (Optimized O(log n))', () => { function powerFast(x, n) { if (n === 0) return 1 if (n % 2 === 0) { // Even exponent: x^n = (x^(n/2))^2 const half = powerFast(x, n / 2) return half * half } else { // Odd exponent: x^n = x * x^(n-1) return x * powerFast(x, n - 1) } } it('should calculate x^n correctly with O(log n) complexity', () => { expect(powerFast(2, 10)).toBe(1024) expect(powerFast(3, 4)).toBe(81) expect(powerFast(2, 3)).toBe(8) }) it('should handle even exponents efficiently', () => { expect(powerFast(2, 8)).toBe(256) expect(powerFast(2, 16)).toBe(65536) expect(powerFast(5, 4)).toBe(625) }) it('should handle odd exponents', () => { expect(powerFast(3, 5)).toBe(243) expect(powerFast(2, 7)).toBe(128) }) it('should handle edge cases', () => { expect(powerFast(5, 0)).toBe(1) expect(powerFast(7, 1)).toBe(7) expect(powerFast(100, 0)).toBe(1) }) it('should produce same results as naive power function', () => { function powerNaive(x, n) { if (n === 0) return 1 return x * powerNaive(x, n - 1) } // Test that both implementations produce identical results for (let x = 1; x <= 5; x++) { for (let n = 0; n <= 10; n++) { expect(powerFast(x, n)).toBe(powerNaive(x, n)) } } }) }) describe('String Reversal', () => { function reverse(str) { if (str.length <= 1) return str return str[str.length - 1] + reverse(str.slice(0, -1)) } it('should reverse a string', () => { expect(reverse('hello')).toBe('olleh') expect(reverse('world')).toBe('dlrow') expect(reverse('recursion')).toBe('noisrucer') }) it('should handle edge cases', () => { expect(reverse('')).toBe('') expect(reverse('a')).toBe('a') }) }) }) describe('Practical Patterns', () => { describe('Array Flattening', () => { function flatten(arr) { let result = [] for (const item of arr) { if (Array.isArray(item)) { result = result.concat(flatten(item)) } else { result.push(item) } } return result } it('should flatten nested arrays', () => { expect(flatten([1, [2, [3, 4]], 5])).toEqual([1, 2, 3, 4, 5]) expect(flatten([1, [2, [3, [4, [5]]]]])).toEqual([1, 2, 3, 4, 5]) }) it('should handle already flat arrays', () => { expect(flatten([1, 2, 3])).toEqual([1, 2, 3]) }) it('should handle empty arrays', () => { expect(flatten([])).toEqual([]) expect(flatten([[], []])).toEqual([]) }) }) describe('Nested Object Traversal', () => { function findAllValues(obj, key) { let results = [] for (const k in obj) { if (k === key) { results.push(obj[k]) } else if (typeof obj[k] === 'object' && obj[k] !== null) { results = results.concat(findAllValues(obj[k], key)) } } return results } it('should find all values for a given key in nested objects', () => { const data = { name: 'root', children: { a: { name: 'a', value: 1 }, b: { name: 'b', value: 2 } } } expect(findAllValues(data, 'name')).toEqual(['root', 'a', 'b']) expect(findAllValues(data, 'value')).toEqual([1, 2]) }) it('should return empty array if key not found', () => { const data = { a: 1, b: 2 } expect(findAllValues(data, 'notfound')).toEqual([]) }) }) describe('Finding All Counts (MDX Example)', () => { // Exact implementation from MDX lines 410-423 function findAllCounts(obj) { let total = 0 for (const key in obj) { if (key === 'count') { total += obj[key] } else if (typeof obj[key] === 'object' && obj[key] !== null) { // Recurse into nested objects total += findAllCounts(obj[key]) } } return total } it('should find and sum all count values in nested object (MDX example)', () => { const data = { name: 'Company', departments: { engineering: { frontend: { count: 5 }, backend: { count: 8 } }, sales: { count: 12 } } } expect(findAllCounts(data)).toBe(25) // 5 + 8 + 12 }) it('should return 0 for empty object', () => { expect(findAllCounts({})).toBe(0) }) it('should return 0 when no count keys exist', () => { const data = { name: 'Test', nested: { value: 10, deeper: { something: 'else' } } } expect(findAllCounts(data)).toBe(0) }) it('should handle flat object with count', () => { expect(findAllCounts({ count: 42 })).toBe(42) }) it('should handle deeply nested counts', () => { const data = { level1: { level2: { level3: { level4: { count: 100 } } } } } expect(findAllCounts(data)).toBe(100) }) }) describe('Linked List Operations', () => { function sumList(node) { if (node === null) return 0 return node.value + sumList(node.next) } function listLength(node) { if (node === null) return 0 return 1 + listLength(node.next) } // Modified version of MDX printReverse that collects results instead of console.log // MDX implementation (lines 505-509): // function printReverse(node) { // if (node === null) return // printReverse(node.next) // First, go to the end // console.log(node.value) // Then print on the way back // } function collectReverse(node, results = []) { if (node === null) return results collectReverse(node.next, results) // First, go to the end results.push(node.value) // Then collect on the way back return results } const list = { value: 1, next: { value: 2, next: { value: 3, next: null } } } it('should sum all values in a linked list', () => { expect(sumList(list)).toBe(6) }) it('should count nodes in a linked list', () => { expect(listLength(list)).toBe(3) }) it('should handle empty list (null)', () => { expect(sumList(null)).toBe(0) expect(listLength(null)).toBe(0) }) it('should handle single node list', () => { const single = { value: 5, next: null } expect(sumList(single)).toBe(5) expect(listLength(single)).toBe(1) }) it('should collect values in reverse order (printReverse pattern)', () => { // MDX shows: printReverse(list) outputs 3, 2, 1 expect(collectReverse(list)).toEqual([3, 2, 1]) }) it('should return empty array for null list (printReverse pattern)', () => { expect(collectReverse(null)).toEqual([]) }) it('should handle single node for reverse collection', () => { const single = { value: 42, next: null } expect(collectReverse(single)).toEqual([42]) }) }) describe('Tree Node Counting', () => { function countNodes(node) { if (node === null) return 0 return 1 + countNodes(node.left) + countNodes(node.right) } function sumTree(node) { if (node === null) return 0 return node.value + sumTree(node.left) + sumTree(node.right) } const tree = { value: 1, left: { value: 2, left: { value: 4, left: null, right: null }, right: { value: 5, left: null, right: null } }, right: { value: 3, left: null, right: null } } it('should count all nodes in a tree', () => { expect(countNodes(tree)).toBe(5) }) it('should sum all values in a tree', () => { expect(sumTree(tree)).toBe(15) // 1+2+3+4+5 }) it('should handle empty tree', () => { expect(countNodes(null)).toBe(0) expect(sumTree(null)).toBe(0) }) }) describe('File System Traversal (getTotalSize)', () => { // Exact implementation from MDX lines 539-550 function getTotalSize(node) { if (node.type === 'file') { return node.size } // Folder: sum sizes of all children let total = 0 for (const child of node.children) { total += getTotalSize(child) } return total } it('should calculate total size of file system (MDX example)', () => { // Exact data structure from MDX lines 522-537 const fileSystem = { name: 'root', type: 'folder', children: [ { name: 'file1.txt', type: 'file', size: 100 }, { name: 'docs', type: 'folder', children: [ { name: 'readme.md', type: 'file', size: 50 }, { name: 'notes.txt', type: 'file', size: 25 } ] } ] } expect(getTotalSize(fileSystem)).toBe(175) // 100 + 50 + 25 }) it('should return size of single file', () => { const singleFile = { name: 'test.js', type: 'file', size: 42 } expect(getTotalSize(singleFile)).toBe(42) }) it('should return 0 for empty folder', () => { const emptyFolder = { name: 'empty', type: 'folder', children: [] } expect(getTotalSize(emptyFolder)).toBe(0) }) it('should handle deeply nested folders', () => { const deepStructure = { name: 'level0', type: 'folder', children: [ { name: 'level1', type: 'folder', children: [ { name: 'level2', type: 'folder', children: [{ name: 'deep.txt', type: 'file', size: 999 }] } ] } ] } expect(getTotalSize(deepStructure)).toBe(999) }) it('should sum files across multiple nested folders', () => { const multiFolder = { name: 'root', type: 'folder', children: [ { name: 'a.txt', type: 'file', size: 10 }, { name: 'sub1', type: 'folder', children: [ { name: 'b.txt', type: 'file', size: 20 }, { name: 'c.txt', type: 'file', size: 30 } ] }, { name: 'sub2', type: 'folder', children: [{ name: 'd.txt', type: 'file', size: 40 }] } ] } expect(getTotalSize(multiFolder)).toBe(100) // 10 + 20 + 30 + 40 }) }) describe('DOM Traversal (walkDOM)', () => { // Exact implementation from MDX lines 461-470 function walkDOM(node, callback) { // Process this node callback(node) // Recurse into child nodes for (const child of node.children) { walkDOM(child, callback) } } it('should collect all tag names in document order (MDX example)', () => { const dom = new JSDOM(` <body> <div> <p></p> <span></span> </div> <footer></footer> </body> `) const tagNames = [] walkDOM(dom.window.document.body, (node) => { tagNames.push(node.tagName) }) expect(tagNames).toEqual(['BODY', 'DIV', 'P', 'SPAN', 'FOOTER']) }) it('should handle single element with no children', () => { const dom = new JSDOM(`<body></body>`) const tagNames = [] walkDOM(dom.window.document.body, (node) => { tagNames.push(node.tagName) }) expect(tagNames).toEqual(['BODY']) }) it('should handle deeply nested structure', () => { const dom = new JSDOM(` <body> <div> <div> <div> <p></p> </div> </div> </div> </body> `) const tagNames = [] walkDOM(dom.window.document.body, (node) => { tagNames.push(node.tagName) }) expect(tagNames).toEqual(['BODY', 'DIV', 'DIV', 'DIV', 'P']) }) it('should process nodes in depth-first order', () => { const dom = new JSDOM(` <body> <nav> <a></a> </nav> <main> <article> <h1></h1> <p></p> </article> </main> </body> `) const tagNames = [] walkDOM(dom.window.document.body, (node) => { tagNames.push(node.tagName) }) expect(tagNames).toEqual(['BODY', 'NAV', 'A', 'MAIN', 'ARTICLE', 'H1', 'P']) }) it('should allow custom callbacks', () => { const dom = new JSDOM(` <body> <div id="first"></div> <div id="second"></div> </body> `) const ids = [] walkDOM(dom.window.document.body, (node) => { if (node.id) { ids.push(node.id) } }) expect(ids).toEqual(['first', 'second']) }) }) }) describe('Common Mistakes', () => { it('should demonstrate stack overflow without proper base case', () => { function badRecursion(n) { // Base case uses === instead of <=, causing overflow for negative inputs if (n === 0) return 0 return badRecursion(n - 2) // Skips 0 when starting with odd number } // Odd number will skip past 0 and cause stack overflow expect(() => badRecursion(5)).toThrow(RangeError) }) it('should show difference between returning and not returning recursive call', () => { function withReturn(n) { if (n === 1) return 1 return n + withReturn(n - 1) } function withoutReturn(n) { if (n === 1) return 1 n + withoutReturn(n - 1) // Missing return! } expect(withReturn(5)).toBe(15) expect(withoutReturn(5)).toBeUndefined() }) }) describe('Optimization', () => { it('should demonstrate memoized fibonacci is much faster than naive', () => { // Naive implementation (would be very slow for large n) function fibNaive(n) { if (n <= 1) return n return fibNaive(n - 1) + fibNaive(n - 2) } // Memoized implementation function fibMemo(n, memo = {}) { if (n in memo) return memo[n] if (n <= 1) return n memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo) return memo[n] } // Both should return the same result expect(fibNaive(10)).toBe(55) expect(fibMemo(10)).toBe(55) // But memoized can handle much larger numbers expect(fibMemo(50)).toBe(12586269025) // fibNaive(50) would take minutes or crash }) it('should demonstrate tail recursive vs non-tail recursive', () => { // Non-tail recursive: multiplication happens AFTER recursive call returns function factorialNonTail(n) { if (n <= 1) return 1 return n * factorialNonTail(n - 1) } // Tail recursive: recursive call is the LAST operation function factorialTail(n, acc = 1) { if (n <= 1) return acc return factorialTail(n - 1, acc * n) } // Both produce the same result expect(factorialNonTail(5)).toBe(120) expect(factorialTail(5)).toBe(120) expect(factorialNonTail(10)).toBe(3628800) expect(factorialTail(10)).toBe(3628800) }) }) describe('Edge Cases', () => { it('should handle recursive function with multiple base cases', () => { function fibonacci(n) { if (n === 0) return 0 // First base case if (n === 1) return 1 // Second base case return fibonacci(n - 1) + fibonacci(n - 2) } expect(fibonacci(0)).toBe(0) expect(fibonacci(1)).toBe(1) expect(fibonacci(2)).toBe(1) }) it('should handle recursion with multiple recursive calls', () => { function sumTree(node) { if (node === null) return 0 // Two recursive calls return node.value + sumTree(node.left) + sumTree(node.right) } const tree = { value: 10, left: { value: 5, left: null, right: null }, right: { value: 15, left: null, right: null } } expect(sumTree(tree)).toBe(30) }) it('should handle mutual recursion', () => { function isEven(n) { if (n === 0) return true return isOdd(n - 1) } function isOdd(n) { if (n === 0) return false return isEven(n - 1) } expect(isEven(4)).toBe(true) expect(isEven(5)).toBe(false) expect(isOdd(3)).toBe(true) expect(isOdd(4)).toBe(false) }) }) describe('Recursion vs Iteration', () => { describe('Factorial (Iterative vs Recursive)', () => { // Recursive version (from Classic Algorithms) function factorialRecursive(n) { if (n <= 1) return 1 return n * factorialRecursive(n - 1) } // Exact iterative implementation from MDX lines 585-592 function factorialIterative(n) { let result = 1 for (let i = 2; i <= n; i++) { result *= i } return result } it('should produce same results as recursive version', () => { expect(factorialIterative(5)).toBe(factorialRecursive(5)) expect(factorialIterative(10)).toBe(factorialRecursive(10)) }) it('should calculate factorial correctly', () => { expect(factorialIterative(5)).toBe(120) expect(factorialIterative(10)).toBe(3628800) }) it('should handle edge cases (0! = 1, 1! = 1)', () => { expect(factorialIterative(0)).toBe(1) expect(factorialIterative(1)).toBe(1) }) it('should handle larger numbers without stack overflow', () => { // Iterative can handle larger numbers without stack concerns expect(factorialIterative(20)).toBe(2432902008176640000) }) }) describe('Sum Tree (Iterative with Explicit Stack)', () => { // Recursive version function sumTreeRecursive(node) { if (node === null) return 0 return node.value + sumTreeRecursive(node.left) + sumTreeRecursive(node.right) } // Exact iterative implementation from MDX lines 814-829 function sumTreeIterative(root) { if (root === null) return 0 let sum = 0 const stack = [root] while (stack.length > 0) { const node = stack.pop() sum += node.value if (node.right) stack.push(node.right) if (node.left) stack.push(node.left) } return sum } const tree = { value: 1, left: { value: 2, left: { value: 4, left: null, right: null }, right: { value: 5, left: null, right: null } }, right: { value: 3, left: null, right: null } } it('should produce same results as recursive version', () => { expect(sumTreeIterative(tree)).toBe(sumTreeRecursive(tree)) }) it('should sum all values in a tree', () => { expect(sumTreeIterative(tree)).toBe(15) // 1+2+3+4+5 }) it('should handle empty tree (null)', () => { expect(sumTreeIterative(null)).toBe(0) }) it('should handle single node tree', () => { const single = { value: 42, left: null, right: null } expect(sumTreeIterative(single)).toBe(42) }) it('should handle left-only tree', () => { const leftOnly = { value: 1, left: { value: 2, left: { value: 3, left: null, right: null }, right: null }, right: null } expect(sumTreeIterative(leftOnly)).toBe(6) }) it('should handle right-only tree', () => { const rightOnly = { value: 1, left: null, right: { value: 2, left: null, right: { value: 3, left: null, right: null } } } expect(sumTreeIterative(rightOnly)).toBe(6) }) }) }) describe('Q&A Examples', () => { describe('Array Length (Recursive)', () => { // Exact implementation from MDX lines 899-910 function arrayLength(arr) { // Base case: empty array has length 0 if (arr.length === 0) return 0 // Recursive case: 1 + length of the rest return 1 + arrayLength(arr.slice(1)) } it('should calculate array length recursively (MDX example)', () => { expect(arrayLength([1, 2, 3, 4])).toBe(4) }) it('should return 0 for empty array', () => { expect(arrayLength([])).toBe(0) }) it('should handle single element array', () => { expect(arrayLength([42])).toBe(1) }) it('should work with arrays of different types', () => { expect(arrayLength(['a', 'b', 'c'])).toBe(3) expect(arrayLength([{ a: 1 }, { b: 2 }])).toBe(2) expect(arrayLength([1, 'two', { three: 3 }, [4]])).toBe(4) }) it('should handle longer arrays', () => { const longArray = Array.from({ length: 100 }, (_, i) => i) expect(arrayLength(longArray)).toBe(100) }) }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/functional-programming/currying-composition/currying-composition.test.js
tests/functional-programming/currying-composition/currying-composition.test.js
import { describe, it, expect } from 'vitest' describe('Currying & Composition', () => { describe('Basic Currying', () => { describe('Manual Currying with Arrow Functions', () => { it('should create a curried function with arrow syntax', () => { const add = a => b => c => a + b + c expect(add(1)(2)(3)).toBe(6) }) it('should allow partial application at each step', () => { const add = a => b => c => a + b + c const add1 = add(1) // Returns b => c => 1 + b + c const add1and2 = add1(2) // Returns c => 1 + 2 + c const result = add1and2(3) // Returns 6 expect(typeof add1).toBe('function') expect(typeof add1and2).toBe('function') expect(result).toBe(6) }) it('should demonstrate closures preserving arguments', () => { const multiply = a => b => a * b const double = multiply(2) const triple = multiply(3) expect(double(5)).toBe(10) expect(triple(5)).toBe(15) expect(double(10)).toBe(20) expect(triple(10)).toBe(30) }) }) describe('Traditional Function Currying', () => { it('should work with traditional function syntax', () => { function curriedAdd(a) { return function(b) { return function(c) { return a + b + c } } } expect(curriedAdd(1)(2)(3)).toBe(6) }) }) describe('Pizza Restaurant Example', () => { it('should demonstrate the pizza ordering pattern', () => { const orderPizza = size => crust => topping => { return `${size} ${crust}-crust ${topping} pizza` } expect(orderPizza("Large")("Thin")("Pepperoni")) .toBe("Large Thin-crust Pepperoni pizza") }) it('should allow creating reusable order templates', () => { const orderPizza = size => crust => topping => { return `${size} ${crust}-crust ${topping} pizza` } const orderLarge = orderPizza("Large") const orderLargeThin = orderLarge("Thin") expect(orderLargeThin("Mushroom")).toBe("Large Thin-crust Mushroom pizza") expect(orderLargeThin("Hawaiian")).toBe("Large Thin-crust Hawaiian pizza") }) }) }) describe('Curry Helper Implementation', () => { describe('Basic Two-Argument Curry', () => { it('should curry a two-argument function', () => { function curry(fn) { return function(a) { return function(b) { return fn(a, b) } } } const add = (a, b) => a + b const curriedAdd = curry(add) expect(curriedAdd(1)(2)).toBe(3) }) }) describe('Advanced Curry (Any Number of Arguments)', () => { const curry = fn => { return function curried(...args) { if (args.length >= fn.length) { return fn.apply(this, args) } return (...nextArgs) => curried.apply(this, args.concat(nextArgs)) } } it('should support full currying', () => { const sum = (a, b, c) => a + b + c const curriedSum = curry(sum) expect(curriedSum(1)(2)(3)).toBe(6) }) it('should support normal function calls', () => { const sum = (a, b, c) => a + b + c const curriedSum = curry(sum) expect(curriedSum(1, 2, 3)).toBe(6) }) it('should support mixed calling styles', () => { const sum = (a, b, c) => a + b + c const curriedSum = curry(sum) expect(curriedSum(1, 2)(3)).toBe(6) expect(curriedSum(1)(2, 3)).toBe(6) }) it('should work with functions of different arities', () => { const add2 = (a, b) => a + b const add4 = (a, b, c, d) => a + b + c + d const curriedAdd2 = curry(add2) const curriedAdd4 = curry(add4) expect(curriedAdd2(1)(2)).toBe(3) expect(curriedAdd4(1)(2)(3)(4)).toBe(10) expect(curriedAdd4(1, 2)(3, 4)).toBe(10) }) }) describe('curryN (Explicit Arity)', () => { const curryN = (fn, arity) => { return function curried(...args) { if (args.length >= arity) { return fn(...args) } return (...nextArgs) => curried(...args, ...nextArgs) } } it('should curry variadic functions with explicit arity', () => { const sum = (...nums) => nums.reduce((a, b) => a + b, 0) const curriedSum3 = curryN(sum, 3) const curriedSum5 = curryN(sum, 5) expect(curriedSum3(1)(2)(3)).toBe(6) expect(curriedSum5(1)(2)(3)(4)(5)).toBe(15) }) }) }) describe('Currying vs Partial Application', () => { describe('Currying (One Argument at a Time)', () => { it('should demonstrate currying with unary functions', () => { const curriedAdd = a => b => c => a + b + c // Each call takes exactly ONE argument const step1 = curriedAdd(1) // Returns function const step2 = step1(2) // Returns function const step3 = step2(3) // Returns 6 expect(typeof step1).toBe('function') expect(typeof step2).toBe('function') expect(step3).toBe(6) }) }) describe('Partial Application (Fix Some Args)', () => { const partial = (fn, ...presetArgs) => { return (...laterArgs) => fn(...presetArgs, ...laterArgs) } it('should fix some arguments upfront', () => { const greet = (greeting, punctuation, name) => { return `${greeting}, ${name}${punctuation}` } const greetExcitedly = partial(greet, "Hello", "!") expect(greetExcitedly("Alice")).toBe("Hello, Alice!") expect(greetExcitedly("Bob")).toBe("Hello, Bob!") }) it('should take remaining arguments together, not one at a time', () => { const add = (a, b, c, d) => a + b + c + d const add10 = partial(add, 10) // Takes remaining 3 args at once expect(add10(1, 2, 3)).toBe(16) }) it('should differ from currying in how arguments are collected', () => { const add = (a, b, c) => a + b + c // Curried: takes args one at a time const curriedAdd = a => b => c => a + b + c // Partial: fixes some args, takes rest together const add1 = partial(add, 1) // Curried needs 3 calls expect(curriedAdd(1)(2)(3)).toBe(6) // Partial takes remaining in one call expect(add1(2, 3)).toBe(6) }) }) }) describe('Real-World Currying Patterns', () => { describe('Configurable Logger', () => { it('should create specialized loggers', () => { const logs = [] const createLogger = level => prefix => message => { const logEntry = `[${level}] ${prefix}: ${message}` logs.push(logEntry) return logEntry } const infoLogger = createLogger('INFO')('App') const errorLogger = createLogger('ERROR')('App') expect(infoLogger('Started')).toBe('[INFO] App: Started') expect(errorLogger('Failed')).toBe('[ERROR] App: Failed') }) }) describe('API Client Factory', () => { it('should create specialized API clients', () => { const createApiUrl = baseUrl => endpoint => params => { const queryString = new URLSearchParams(params).toString() return `${baseUrl}${endpoint}${queryString ? '?' + queryString : ''}` } const githubApi = createApiUrl('https://api.github.com') const getUsers = githubApi('/users') expect(getUsers({})).toBe('https://api.github.com/users') expect(getUsers({ per_page: 10 })).toBe('https://api.github.com/users?per_page=10') }) }) describe('Validation Functions', () => { it('should create reusable validators', () => { const isGreaterThan = min => value => value > min const isLessThan = max => value => value < max const hasLength = length => str => str.length === length const isAdult = isGreaterThan(17) const isValidAge = isLessThan(120) const isValidZipCode = hasLength(5) expect(isAdult(18)).toBe(true) expect(isAdult(15)).toBe(false) expect(isValidAge(50)).toBe(true) expect(isValidAge(150)).toBe(false) expect(isValidZipCode('12345')).toBe(true) expect(isValidZipCode('1234')).toBe(false) }) it('should work with array methods', () => { const isGreaterThan = min => value => value > min const isAdult = isGreaterThan(17) const ages = [15, 22, 45, 8, 67] const adults = ages.filter(isAdult) expect(adults).toEqual([22, 45, 67]) }) }) describe('Discount Calculator', () => { it('should create specialized discount functions', () => { const applyDiscount = discountPercent => price => { return price * (1 - discountPercent / 100) } const tenPercentOff = applyDiscount(10) const twentyPercentOff = applyDiscount(20) const blackFridayDeal = applyDiscount(50) expect(tenPercentOff(100)).toBe(90) expect(twentyPercentOff(100)).toBe(80) expect(blackFridayDeal(100)).toBe(50) }) it('should work with array map', () => { const applyDiscount = discountPercent => price => { return price * (1 - discountPercent / 100) } const tenPercentOff = applyDiscount(10) const prices = [100, 200, 50, 75] const discountedPrices = prices.map(tenPercentOff) expect(discountedPrices).toEqual([90, 180, 45, 67.5]) }) }) describe('Event Handler Configuration', () => { it('should configure event handlers step by step', () => { const handlers = [] const handleEvent = eventType => elementId => callback => { const handler = { eventType, elementId, callback } handlers.push(handler) return handler } const onClick = handleEvent('click') const onClickButton = onClick('myButton') const handler = onClickButton(() => 'clicked!') expect(handler.eventType).toBe('click') expect(handler.elementId).toBe('myButton') expect(handler.callback()).toBe('clicked!') }) }) }) describe('Function Composition', () => { describe('pipe() Implementation', () => { const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x) it('should compose functions left-to-right', () => { const add1 = x => x + 1 const double = x => x * 2 const square = x => x * x const process = pipe(add1, double, square) // 5 → 6 → 12 → 144 expect(process(5)).toBe(144) }) it('should process single functions', () => { const double = x => x * 2 const process = pipe(double) expect(process(5)).toBe(10) }) it('should handle identity when empty', () => { const pipe = (...fns) => x => fns.length ? fns.reduce((acc, fn) => fn(acc), x) : x const identity = pipe() expect(identity(5)).toBe(5) }) }) describe('compose() Implementation', () => { const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x) it('should compose functions right-to-left', () => { const add1 = x => x + 1 const double = x => x * 2 const square = x => x * x // Functions listed in reverse execution order const process = compose(square, double, add1) // 5 → 6 → 12 → 144 (same result as pipe(add1, double, square)) expect(process(5)).toBe(144) }) it('should be equivalent to pipe with reversed arguments', () => { const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x) const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x) const add1 = x => x + 1 const double = x => x * 2 const piped = pipe(add1, double) const composed = compose(double, add1) expect(piped(5)).toBe(composed(5)) }) }) describe('String Transformation Pipeline', () => { const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x) it('should transform strings through a pipeline', () => { const getName = obj => obj.name const trim = str => str.trim() const toUpperCase = str => str.toUpperCase() const addExclaim = str => str + '!' const shout = pipe(getName, trim, toUpperCase, addExclaim) expect(shout({ name: ' alice ' })).toBe('ALICE!') }) it('should convert to camelCase', () => { const trim = str => str.trim() const toLowerCase = str => str.toLowerCase() const splitWords = str => str.split(' ') const capitalizeFirst = words => words.map((w, i) => i === 0 ? w : w[0].toUpperCase() + w.slice(1) ) const joinWords = words => words.join('') const toCamelCase = pipe( trim, toLowerCase, splitWords, capitalizeFirst, joinWords ) expect(toCamelCase(' HELLO WORLD ')).toBe('helloWorld') expect(toCamelCase('my variable name')).toBe('myVariableName') }) }) describe('Data Transformation Pipeline', () => { const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x) it('should process array data through pipeline', () => { const users = [ { name: 'Alice', age: 25, active: true }, { name: 'Bob', age: 17, active: true }, { name: 'Charlie', age: 30, active: false }, { name: 'Diana', age: 22, active: true } ] const processUsers = pipe( users => users.filter(u => u.active), users => users.filter(u => u.age >= 18), users => users.map(u => u.name), names => names.sort() ) expect(processUsers(users)).toEqual(['Alice', 'Diana']) }) }) }) describe('Currying + Composition Together', () => { const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x) describe('Data-Last Parameter Order', () => { it('should enable composition with data-last curried functions', () => { const map = fn => arr => arr.map(fn) const filter = fn => arr => arr.filter(fn) const double = x => x * 2 const isEven = x => x % 2 === 0 const doubleEvens = pipe( filter(isEven), map(double) ) expect(doubleEvens([1, 2, 3, 4, 5, 6])).toEqual([4, 8, 12]) }) it('should show why data-first is harder to compose', () => { // Data-first: harder to compose const mapFirst = (arr, fn) => arr.map(fn) const filterFirst = (arr, fn) => arr.filter(fn) // Can't easily pipe these without wrapping const double = x => x * 2 const isEven = x => x % 2 === 0 // Would need manual wrapping: const result = mapFirst(filterFirst([1, 2, 3, 4, 5, 6], isEven), double) expect(result).toEqual([4, 8, 12]) }) }) describe('Curried Functions in Pipelines', () => { it('should compose curried arithmetic functions', () => { const add = a => b => a + b const multiply = a => b => a * b const subtract = a => b => b - a const add5 = add(5) const double = multiply(2) const subtract3 = subtract(3) const process = pipe(add5, double, subtract3) // 10 → 15 → 30 → 27 expect(process(10)).toBe(27) }) it('should demonstrate point-free style', () => { const prop = key => obj => obj[key] const toUpper = str => str.toUpperCase() // Point-free: no explicit data parameter const getUpperName = pipe( prop('name'), toUpper ) expect(getUpperName({ name: 'alice' })).toBe('ALICE') expect(getUpperName({ name: 'bob' })).toBe('BOB') }) }) describe('Complex Pipeline with Currying', () => { it('should process user data through curried pipeline', () => { const prop = key => obj => obj[key] const map = fn => arr => arr.map(fn) const filter = pred => arr => arr.filter(pred) const sort = compareFn => arr => [...arr].sort(compareFn) const take = n => arr => arr.slice(0, n) const users = [ { id: 1, name: 'Zara', score: 85 }, { id: 2, name: 'Alice', score: 92 }, { id: 3, name: 'Bob', score: 78 }, { id: 4, name: 'Charlie', score: 95 } ] const getTopScorers = pipe( filter(u => u.score >= 80), sort((a, b) => b.score - a.score), take(2), map(prop('name')) ) expect(getTopScorers(users)).toEqual(['Charlie', 'Alice']) }) }) }) describe('Interview Questions', () => { describe('Implement sum(1)(2)(3)...(n)()', () => { it('should return sum when called with no arguments', () => { function sum(a) { return function next(b) { if (b === undefined) { return a } return sum(a + b) } } expect(sum(1)(2)(3)()).toBe(6) expect(sum(1)(2)(3)(4)(5)()).toBe(15) expect(sum(10)()).toBe(10) }) }) describe('Infinite Currying with valueOf', () => { it('should return sum when coerced to number', () => { function sum(a) { const fn = b => sum(a + b) fn.valueOf = () => a return fn } expect(+sum(1)(2)(3)).toBe(6) expect(+sum(1)(2)(3)(4)(5)).toBe(15) }) }) describe('Fix map + parseInt Issue', () => { it('should demonstrate the problem', () => { const result = ['1', '2', '3'].map(parseInt) // parseInt receives (value, index, array) // parseInt('1', 0) → 1 // parseInt('2', 1) → NaN (base 1 is invalid) // parseInt('3', 2) → NaN (3 is not valid in base 2) expect(result).toEqual([1, NaN, NaN]) }) it('should fix with unary wrapper', () => { const unary = fn => arg => fn(arg) const result = ['1', '2', '3'].map(unary(parseInt)) expect(result).toEqual([1, 2, 3]) }) }) }) describe('Common Mistakes', () => { describe('Forgetting Curried Functions Return Functions', () => { it('should demonstrate the mistake', () => { const add = a => b => a + b // Mistake: forgot second call const result = add(1) expect(typeof result).toBe('function') expect(result).not.toBe(1) // Not a number! // Correct expect(add(1)(2)).toBe(3) }) }) describe('fn.length with Rest Parameters', () => { it('should show fn.length is 0 for rest parameters', () => { function withRest(...args) { return args.reduce((a, b) => a + b, 0) } function withDefault(a, b = 2) { return a + b } expect(withRest.length).toBe(0) expect(withDefault.length).toBe(1) // Only counts params before default }) }) describe('Type Mismatches in Pipelines', () => { const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x) it('should show type mismatch issues', () => { const getAge = obj => obj.age // Returns number const getLength = arr => arr.length // Expects array // This would cause issues const broken = pipe(getAge, getLength) // Numbers have no .length property expect(broken({ age: 25 })).toBe(undefined) }) }) }) describe('Vanilla JS Utility Functions', () => { describe('Complete Utility Set', () => { // Curry const curry = fn => { return function curried(...args) { return args.length >= fn.length ? fn(...args) : (...next) => curried(...args, ...next) } } // Pipe and Compose const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x) const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x) // Partial Application const partial = (fn, ...presetArgs) => (...laterArgs) => fn(...presetArgs, ...laterArgs) // Data-last utilities const map = fn => arr => arr.map(fn) const filter = fn => arr => arr.filter(fn) const reduce = (fn, initial) => arr => arr.reduce(fn, initial) it('should demonstrate all utilities working together', () => { const sum = (a, b, c) => a + b + c const curriedSum = curry(sum) expect(curriedSum(1)(2)(3)).toBe(6) expect(curriedSum(1, 2)(3)).toBe(6) const double = x => x * 2 const add1 = x => x + 1 const process = pipe(add1, double) expect(process(5)).toBe(12) const processReverse = compose(add1, double) expect(processReverse(5)).toBe(11) // double first, then add1 const greet = (greeting, name) => `${greeting}, ${name}!` const sayHello = partial(greet, 'Hello') expect(sayHello('Alice')).toBe('Hello, Alice!') const nums = [1, 2, 3, 4, 5] const isEven = x => x % 2 === 0 const sumOfDoubledEvens = pipe( filter(isEven), map(double), reduce((a, b) => a + b, 0) ) expect(sumOfDoubledEvens(nums)).toBe(12) // [2,4] → [4,8] → 12 }) }) }) describe('Practical Examples from Documentation', () => { const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x) describe('Logging Factory', () => { it('should create specialized loggers from documentation example', () => { const logs = [] const createLogger = level => withTimestamp => message => { const timestamp = withTimestamp ? '2024-01-15T10:30:00Z' : '' const logEntry = `[${level}]${timestamp ? ' ' + timestamp : ''} ${message}` logs.push(logEntry) return logEntry } const info = createLogger('INFO')(true) const quickLog = createLogger('LOG')(false) expect(info('Application started')).toBe('[INFO] 2024-01-15T10:30:00Z Application started') expect(quickLog('Quick debug')).toBe('[LOG] Quick debug') }) }) describe('Assembly Line Pipeline', () => { it('should transform user data as shown in documentation', () => { const getName = obj => obj.name const trim = str => str.trim() const toLowerCase = str => str.toLowerCase() const processUser = pipe(getName, trim, toLowerCase) expect(processUser({ name: ' ALICE ' })).toBe('alice') }) }) }) describe('Additional Documentation Examples', () => { const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x) const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x) describe('Real-World Pipeline: Processing API Data (doc lines 729-756)', () => { it('should process API response through complete pipeline', () => { // Mock API response matching documentation example const apiResponse = { data: [ { id: 1, firstName: 'Charlie', lastName: 'Brown', email: 'charlie@test.com', isActive: true }, { id: 2, firstName: 'Alice', lastName: 'Smith', email: 'alice@test.com', isActive: false }, { id: 3, firstName: 'Bob', lastName: 'Jones', email: 'bob@test.com', isActive: true }, { id: 4, firstName: 'Diana', lastName: 'Prince', email: 'diana@test.com', isActive: true }, { id: 5, firstName: 'Eve', lastName: 'Wilson', email: 'eve@test.com', isActive: true }, { id: 6, firstName: 'Frank', lastName: 'Miller', email: 'frank@test.com', isActive: true }, { id: 7, firstName: 'Grace', lastName: 'Lee', email: 'grace@test.com', isActive: true }, { id: 8, firstName: 'Henry', lastName: 'Taylor', email: 'henry@test.com', isActive: true }, { id: 9, firstName: 'Ivy', lastName: 'Chen', email: 'ivy@test.com', isActive: true }, { id: 10, firstName: 'Jack', lastName: 'Davis', email: 'jack@test.com', isActive: true }, { id: 11, firstName: 'Kate', lastName: 'Moore', email: 'kate@test.com', isActive: true }, { id: 12, firstName: 'Leo', lastName: 'Garcia', email: 'leo@test.com', isActive: true } ] } // Transform API response into display format (matching doc example) const processApiResponse = pipe( // Extract data from response response => response.data, // Filter active users only users => users.filter(u => u.isActive), // Sort by name (using lastName for sorting) users => users.sort((a, b) => a.firstName.localeCompare(b.firstName)), // Transform to display format users => users.map(u => ({ id: u.id, displayName: `${u.firstName} ${u.lastName}`, email: u.email })), // Take first 10 users => users.slice(0, 10) ) const result = processApiResponse(apiResponse) // Verify pipeline worked correctly expect(result).toHaveLength(10) // Alice was filtered out (isActive: false) expect(result.find(u => u.displayName === 'Alice Smith')).toBeUndefined() // First user should be Bob (alphabetically first among active users) expect(result[0].displayName).toBe('Bob Jones') // Verify display format expect(result[0]).toHaveProperty('id') expect(result[0]).toHaveProperty('displayName') expect(result[0]).toHaveProperty('email') // Verify sorting (alphabetical by firstName) const names = result.map(u => u.displayName.split(' ')[0]) const sortedNames = [...names].sort() expect(names).toEqual(sortedNames) }) }) describe('compose() Direction Example (doc lines 658-664)', () => { it('should process right-to-left with getName/toUpperCase/addExclaim', () => { const getName = obj => obj.name const toUpperCase = str => str.toUpperCase() const addExclaim = str => str + '!' // compose processes right-to-left const shout = compose(addExclaim, toUpperCase, getName) expect(shout({ name: 'alice' })).toBe('ALICE!') // This is equivalent to nested calls: const manualResult = addExclaim(toUpperCase(getName({ name: 'alice' }))) expect(shout({ name: 'alice' })).toBe(manualResult) }) }) describe('pipe/compose Equivalence (doc lines 669-672)', () => { it('should produce same result: pipe(a, b, c)(x) === compose(c, b, a)(x)', () => { const a = x => x + 1 const b = x => x * 2 const c = x => x - 3 const input = 10 // pipe: a first, then b, then c const pipedResult = pipe(a, b, c)(input) // compose: c(b(a(x))) - reversed argument order const composedResult = compose(c, b, a)(input) expect(pipedResult).toBe(composedResult) // Verify the actual value: (10 + 1) * 2 - 3 = 19 expect(pipedResult).toBe(19) }) it('should demonstrate both directions with same functions', () => { const add5 = x => x + 5 const double = x => x * 2 const square = x => x * x const input = 3 // pipe(add5, double, square)(3) = ((3 + 5) * 2)² = 256 expect(pipe(add5, double, square)(input)).toBe(256) // compose(add5, double, square)(3) = (3² * 2) + 5 = 23 expect(compose(add5, double, square)(input)).toBe(23) // To get same result with compose, reverse the order expect(compose(square, double, add5)(input)).toBe(256) }) }) describe('Why Multi-Argument Functions Do Not Compose (doc lines 769-775)', () => { it('should demonstrate NaN problem with non-curried functions', () => { const add = (a, b) => a + b const multiply = (a, b) => a * b // This doesn't work as expected! const addThenMultiply = pipe(add, multiply) // When called: add(1, 2) returns 3 // Then multiply(3) is called with only one argument // multiply(3, undefined) = 3 * undefined = NaN const result = addThenMultiply(1, 2) expect(result).toBeNaN() }) it('should work correctly with curried versions', () => { // Curried versions const add = a => b => a + b const multiply = a => b => a * b // Now we can compose! const add5 = add(5) // x => 5 + x const double = multiply(2) // x => 2 * x const add5ThenDouble = pipe(add5, double) // (10 + 5) * 2 = 30 expect(add5ThenDouble(10)).toBe(30) }) }) describe('Data-First vs Data-Last Argument Order (doc lines 984-994)', () => { it('should show data-first makes composition harder', () => { // Data-first: hard to compose const multiplyFirst = (value, factor) => value * factor // Can't easily create a reusable "double" function for pipelines // Would need to wrap it: const doubleFirst = value => multiplyFirst(value, 2) const tripleFirst = value => multiplyFirst(value, 3) // Works, but requires manual wrapping each time expect(pipe(doubleFirst, tripleFirst)(5)).toBe(30) }) it('should show data-last composes naturally', () => { // Data-last: composes well const multiply = factor => value => value * factor const double = multiply(2) const triple = multiply(3) // Composes naturally without any wrapping expect(pipe(double, triple)(5)).toBe(30) // Can easily create new specialized functions const quadruple = multiply(4) expect(pipe(double, quadruple)(5)).toBe(40) }) }) describe('Manual Composition with Nested Calls (doc lines 526-538)', () => { it('should work with nested function calls', () => { const add10 = x => x + 10 const multiply2 = x => x * 2 const subtract5 = x => x - 5 // Manual composition (nested calls) // Step by step: 5 → 15 → 30 → 25 const result = subtract5(multiply2(add10(5))) expect(result).toBe(25) }) it('should produce same result with compose function', () => { const add10 = x => x + 10 const multiply2 = x => x * 2 const subtract5 = x => x - 5 // With a compose function const composed = compose(subtract5, multiply2, add10) expect(composed(5)).toBe(25) // Verify it matches manual nesting const manual = subtract5(multiply2(add10(5))) expect(composed(5)).toBe(manual) }) it('should be more readable with pipe', () => { const add10 = x => x + 10 const multiply2 = x => x * 2 const subtract5 = x => x - 5 // With pipe (reads in execution order) const piped = pipe(add10, multiply2, subtract5) expect(piped(5)).toBe(25) }) }) describe('Opening Example from Documentation (doc lines 9-20)', () => { it('should demonstrate the opening currying example', () => { // Currying: one argument at a time const add = a => b => c => a + b + c expect(add(1)(2)(3)).toBe(6)
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
true
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/web-platform/http-fetch/http-fetch.test.js
tests/web-platform/http-fetch/http-fetch.test.js
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' // ============================================================================= // HTTP & FETCH - TEST SUITE // Tests for code examples from docs/concepts/http-fetch.mdx // Uses Node 20+ native fetch with Vitest mocking // ============================================================================= describe('HTTP & Fetch', () => { // Store original fetch const originalFetch = global.fetch beforeEach(() => { // Reset fetch mock before each test vi.restoreAllMocks() }) afterEach(() => { // Restore original fetch after each test global.fetch = originalFetch }) // =========================================================================== // RESPONSE OBJECT BASICS // =========================================================================== describe('Response Object', () => { it('should have status property', () => { const response = new Response('OK', { status: 200 }) expect(response.status).toBe(200) }) it('should have statusText property', () => { const response = new Response('OK', { status: 200, statusText: 'OK' }) expect(response.statusText).toBe('OK') }) it('should have ok property true for 2xx status', () => { const response200 = new Response('OK', { status: 200 }) const response201 = new Response('Created', { status: 201 }) const response204 = new Response(null, { status: 204 }) expect(response200.ok).toBe(true) expect(response201.ok).toBe(true) expect(response204.ok).toBe(true) }) it('should have ok property false for non-2xx status', () => { const response400 = new Response('Bad Request', { status: 400 }) const response404 = new Response('Not Found', { status: 404 }) const response500 = new Response('Server Error', { status: 500 }) expect(response400.ok).toBe(false) expect(response404.ok).toBe(false) expect(response500.ok).toBe(false) }) it('should have headers object', () => { const response = new Response('OK', { headers: { 'Content-Type': 'application/json', 'X-Custom-Header': 'custom-value' } }) expect(response.headers.get('Content-Type')).toBe('application/json') expect(response.headers.get('X-Custom-Header')).toBe('custom-value') }) it('should parse JSON body', async () => { const data = { name: 'Alice', age: 30 } const response = new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } }) const parsed = await response.json() expect(parsed).toEqual(data) }) it('should parse text body', async () => { const response = new Response('Hello, World!') const text = await response.text() expect(text).toBe('Hello, World!') }) it('should only allow body to be read once', async () => { const response = new Response('Hello') await response.text() // First read // Second read should throw await expect(response.text()).rejects.toThrow() }) it('should clone response for multiple reads', async () => { const response = new Response('Hello') const clone = response.clone() const text1 = await response.text() const text2 = await clone.text() expect(text1).toBe('Hello') expect(text2).toBe('Hello') }) }) // =========================================================================== // RESPONSE BODY METHODS (blob, arrayBuffer) // =========================================================================== describe('Response Body Methods', () => { it('should parse body as Blob', async () => { const textContent = 'Hello, World!' const response = new Response(textContent) const blob = await response.blob() expect(blob).toBeInstanceOf(Blob) expect(blob.size).toBe(textContent.length) }) it('should parse body as ArrayBuffer', async () => { const textContent = 'Hello' const response = new Response(textContent) const buffer = await response.arrayBuffer() expect(buffer).toBeInstanceOf(ArrayBuffer) expect(buffer.byteLength).toBe(textContent.length) }) it('should parse binary data as Blob', async () => { const binaryData = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f]) // "Hello" const response = new Response(binaryData) const blob = await response.blob() expect(blob.size).toBe(5) }) it('should parse binary data as ArrayBuffer', async () => { const binaryData = new Uint8Array([1, 2, 3, 4, 5]) const response = new Response(binaryData) const buffer = await response.arrayBuffer() const view = new Uint8Array(buffer) expect(view[0]).toBe(1) expect(view[4]).toBe(5) }) }) // =========================================================================== // RESPONSE METADATA PROPERTIES // =========================================================================== describe('Response Metadata', () => { it('should have url property', () => { // Note: In real fetch, url reflects the final URL after redirects // For Response constructor, we can't set URL directly const response = new Response('OK', { status: 200 }) expect(response.url).toBe('') // Empty for constructed responses }) it('should have type property', () => { const response = new Response('OK', { status: 200 }) // Constructed responses have type "default" expect(response.type).toBe('default') }) it('should have redirected property', () => { const response = new Response('OK', { status: 200 }) // Constructed responses are not redirected expect(response.redirected).toBe(false) }) it('should have bodyUsed property', async () => { const response = new Response('Hello') expect(response.bodyUsed).toBe(false) await response.text() expect(response.bodyUsed).toBe(true) }) }) // =========================================================================== // STATUS CODE RANGES // =========================================================================== describe('HTTP Status Codes', () => { describe('2xx Success', () => { it('200 OK should be successful', () => { const response = new Response('OK', { status: 200 }) expect(response.ok).toBe(true) expect(response.status).toBe(200) }) it('201 Created should be successful', () => { const response = new Response('Created', { status: 201 }) expect(response.ok).toBe(true) expect(response.status).toBe(201) }) it('204 No Content should be successful', () => { const response = new Response(null, { status: 204 }) expect(response.ok).toBe(true) expect(response.status).toBe(204) }) it('299 should still be ok', () => { const response = new Response('OK', { status: 299 }) expect(response.ok).toBe(true) }) }) describe('3xx Redirection', () => { it('301 Moved Permanently should not be ok', () => { const response = new Response('Moved', { status: 301 }) expect(response.ok).toBe(false) }) it('302 Found should not be ok', () => { const response = new Response('Found', { status: 302 }) expect(response.ok).toBe(false) }) it('304 Not Modified should not be ok', () => { // 304 is a "null body status" so we use null body const response = new Response(null, { status: 304 }) expect(response.ok).toBe(false) }) }) describe('4xx Client Errors', () => { it('400 Bad Request should not be ok', () => { const response = new Response('Bad Request', { status: 400 }) expect(response.ok).toBe(false) expect(response.status).toBe(400) }) it('401 Unauthorized should not be ok', () => { const response = new Response('Unauthorized', { status: 401 }) expect(response.ok).toBe(false) expect(response.status).toBe(401) }) it('403 Forbidden should not be ok', () => { const response = new Response('Forbidden', { status: 403 }) expect(response.ok).toBe(false) expect(response.status).toBe(403) }) it('404 Not Found should not be ok', () => { const response = new Response('Not Found', { status: 404 }) expect(response.ok).toBe(false) expect(response.status).toBe(404) }) it('422 Unprocessable Entity should not be ok', () => { const response = new Response('Unprocessable Entity', { status: 422 }) expect(response.ok).toBe(false) expect(response.status).toBe(422) }) }) describe('5xx Server Errors', () => { it('500 Internal Server Error should not be ok', () => { const response = new Response('Internal Server Error', { status: 500 }) expect(response.ok).toBe(false) expect(response.status).toBe(500) }) it('502 Bad Gateway should not be ok', () => { const response = new Response('Bad Gateway', { status: 502 }) expect(response.ok).toBe(false) expect(response.status).toBe(502) }) it('503 Service Unavailable should not be ok', () => { const response = new Response('Service Unavailable', { status: 503 }) expect(response.ok).toBe(false) expect(response.status).toBe(503) }) }) }) // =========================================================================== // HEADERS API // =========================================================================== describe('Headers API', () => { it('should create headers from object', () => { const headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json' }) expect(headers.get('Content-Type')).toBe('application/json') expect(headers.get('Accept')).toBe('application/json') }) it('should append headers', () => { const headers = new Headers() headers.append('Accept', 'application/json') headers.append('Accept', 'text/plain') expect(headers.get('Accept')).toBe('application/json, text/plain') }) it('should set headers (overwrite)', () => { const headers = new Headers() headers.set('Accept', 'application/json') headers.set('Accept', 'text/plain') expect(headers.get('Accept')).toBe('text/plain') }) it('should check if header exists', () => { const headers = new Headers({ 'Content-Type': 'application/json' }) expect(headers.has('Content-Type')).toBe(true) expect(headers.has('Authorization')).toBe(false) }) it('should delete headers', () => { const headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json' }) headers.delete('Accept') expect(headers.has('Accept')).toBe(false) expect(headers.has('Content-Type')).toBe(true) }) it('should iterate over headers', () => { const headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json' }) const entries = [] for (const [key, value] of headers) { entries.push([key, value]) } expect(entries).toContainEqual(['content-type', 'application/json']) expect(entries).toContainEqual(['accept', 'application/json']) }) it('should be case-insensitive for header names', () => { const headers = new Headers({ 'Content-Type': 'application/json' }) expect(headers.get('content-type')).toBe('application/json') expect(headers.get('CONTENT-TYPE')).toBe('application/json') expect(headers.get('Content-Type')).toBe('application/json') }) }) // =========================================================================== // REQUEST OBJECT // =========================================================================== describe('Request Object', () => { it('should create a basic request', () => { const request = new Request('https://api.example.com/users') expect(request.url).toBe('https://api.example.com/users') expect(request.method).toBe('GET') }) it('should create request with method', () => { const request = new Request('https://api.example.com/users', { method: 'POST' }) expect(request.method).toBe('POST') }) it('should create request with headers', () => { const request = new Request('https://api.example.com/users', { headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer token123' } }) expect(request.headers.get('Content-Type')).toBe('application/json') expect(request.headers.get('Authorization')).toBe('Bearer token123') }) it('should create request with body', async () => { const body = JSON.stringify({ name: 'Alice' }) const request = new Request('https://api.example.com/users', { method: 'POST', body: body }) const requestBody = await request.text() expect(requestBody).toBe(body) }) it('should clone request', () => { const request = new Request('https://api.example.com/users', { method: 'POST', headers: { 'Content-Type': 'application/json' } }) const clone = request.clone() expect(clone.url).toBe(request.url) expect(clone.method).toBe(request.method) expect(clone.headers.get('Content-Type')).toBe('application/json') }) }) // =========================================================================== // FETCH WITH MOCKING // =========================================================================== describe('Fetch API (Mocked)', () => { it('should make a GET request', async () => { const mockData = { id: 1, name: 'Alice' } global.fetch = vi.fn().mockResolvedValue( new Response(JSON.stringify(mockData), { status: 200, headers: { 'Content-Type': 'application/json' } }) ) const response = await fetch('https://api.example.com/users/1') const data = await response.json() expect(fetch).toHaveBeenCalledWith('https://api.example.com/users/1') expect(data).toEqual(mockData) }) it('should make a POST request with body', async () => { const mockResponse = { id: 1, name: 'Alice' } global.fetch = vi.fn().mockResolvedValue( new Response(JSON.stringify(mockResponse), { status: 201, headers: { 'Content-Type': 'application/json' } }) ) const userData = { name: 'Alice', email: 'alice@example.com' } const response = await fetch('https://api.example.com/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(userData) }) expect(fetch).toHaveBeenCalledWith('https://api.example.com/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(userData) }) expect(response.status).toBe(201) }) it('should handle 404 response (not rejection)', async () => { global.fetch = vi.fn().mockResolvedValue( new Response('Not Found', { status: 404 }) ) // Fetch resolves even for 404! const response = await fetch('https://api.example.com/users/999') expect(response.ok).toBe(false) expect(response.status).toBe(404) }) it('should handle 500 response (not rejection)', async () => { global.fetch = vi.fn().mockResolvedValue( new Response('Internal Server Error', { status: 500 }) ) // Fetch resolves even for 500! const response = await fetch('https://api.example.com/broken') expect(response.ok).toBe(false) expect(response.status).toBe(500) }) it('should reject on network error', async () => { global.fetch = vi.fn().mockRejectedValue( new TypeError('Failed to fetch') ) await expect(fetch('https://api.example.com/unreachable')) .rejects.toThrow('Failed to fetch') }) }) // =========================================================================== // ERROR HANDLING PATTERNS // =========================================================================== describe('Error Handling Patterns', () => { it('should properly check response.ok', async () => { global.fetch = vi.fn().mockResolvedValue( new Response('Not Found', { status: 404 }) ) const response = await fetch('/api/users/999') // The correct pattern if (!response.ok) { const error = new Error(`HTTP ${response.status}`) expect(error.message).toBe('HTTP 404') } }) it('should demonstrate fetchJSON wrapper pattern', async () => { // Reusable fetch wrapper async function fetchJSON(url, options = {}) { const response = await fetch(url, options) if (!response.ok) { const error = new Error(`HTTP ${response.status}`) error.status = response.status throw error } if (response.status === 204) { return null } return response.json() } // Test successful response global.fetch = vi.fn().mockResolvedValue( new Response(JSON.stringify({ id: 1 }), { status: 200 }) ) const data = await fetchJSON('/api/users/1') expect(data).toEqual({ id: 1 }) // Test 404 error global.fetch = vi.fn().mockResolvedValue( new Response('Not Found', { status: 404 }) ) try { await fetchJSON('/api/users/999') expect.fail('Should have thrown') } catch (error) { expect(error.message).toBe('HTTP 404') expect(error.status).toBe(404) } // Test 204 No Content global.fetch = vi.fn().mockResolvedValue( new Response(null, { status: 204 }) ) const noContent = await fetchJSON('/api/users/1', { method: 'DELETE' }) expect(noContent).toBeNull() }) it('should differentiate network vs HTTP errors', async () => { let errorType = null async function safeFetch(url) { try { const response = await fetch(url) if (!response.ok) { errorType = 'http' throw new Error(`HTTP ${response.status}`) } return await response.json() } catch (error) { if (error.message.startsWith('HTTP')) { // Already handled HTTP error throw error } // Network error errorType = 'network' throw new Error('Network error: ' + error.message) } } // Test HTTP error (404) global.fetch = vi.fn().mockResolvedValue( new Response('Not Found', { status: 404 }) ) try { await safeFetch('/api/missing') } catch (e) { expect(errorType).toBe('http') } // Test network error global.fetch = vi.fn().mockRejectedValue( new TypeError('Failed to fetch') ) try { await safeFetch('/api/unreachable') } catch (e) { expect(errorType).toBe('network') } }) }) // =========================================================================== // ABORT CONTROLLER // =========================================================================== describe('AbortController', () => { it('should create an AbortController', () => { const controller = new AbortController() expect(controller).toBeDefined() expect(controller.signal).toBeDefined() expect(controller.signal.aborted).toBe(false) }) it('should abort and update signal', () => { const controller = new AbortController() expect(controller.signal.aborted).toBe(false) controller.abort() expect(controller.signal.aborted).toBe(true) }) it('should abort with reason', () => { const controller = new AbortController() controller.abort('User cancelled') expect(controller.signal.aborted).toBe(true) expect(controller.signal.reason).toBe('User cancelled') }) it('should reject fetch when aborted', async () => { const controller = new AbortController() // Mock fetch to respect abort signal global.fetch = vi.fn().mockImplementation((url, options) => { return new Promise((resolve, reject) => { if (options?.signal?.aborted) { const error = new DOMException('The operation was aborted.', 'AbortError') reject(error) return } options?.signal?.addEventListener('abort', () => { const error = new DOMException('The operation was aborted.', 'AbortError') reject(error) }) // Simulate slow request setTimeout(() => { resolve(new Response('OK')) }, 1000) }) }) const fetchPromise = fetch('/api/slow', { signal: controller.signal }) // Abort immediately controller.abort() await expect(fetchPromise).rejects.toThrow() try { await fetchPromise } catch (error) { expect(error.name).toBe('AbortError') } }) it('should handle abort in try/catch', async () => { const controller = new AbortController() controller.abort() global.fetch = vi.fn().mockRejectedValue( new DOMException('The operation was aborted.', 'AbortError') ) try { await fetch('/api/data', { signal: controller.signal }) expect.fail('Should have thrown') } catch (error) { if (error.name === 'AbortError') { // Expected - request was cancelled expect(true).toBe(true) } else { throw error } } }) it('should implement timeout pattern', async () => { async function fetchWithTimeout(url, timeout = 5000) { const controller = new AbortController() const timeoutId = setTimeout(() => controller.abort(), timeout) try { const response = await fetch(url, { signal: controller.signal }) clearTimeout(timeoutId) return response } catch (error) { clearTimeout(timeoutId) if (error.name === 'AbortError') { throw new Error(`Request timed out after ${timeout}ms`) } throw error } } // Mock slow request that will be aborted global.fetch = vi.fn().mockImplementation((url, options) => { return new Promise((resolve, reject) => { const timeout = setTimeout(() => { resolve(new Response('OK')) }, 10000) // Very slow options?.signal?.addEventListener('abort', () => { clearTimeout(timeout) reject(new DOMException('The operation was aborted.', 'AbortError')) }) }) }) // Should timeout after 100ms await expect(fetchWithTimeout('/api/slow', 100)) .rejects.toThrow('Request timed out after 100ms') }) }) // =========================================================================== // PARALLEL REQUESTS // =========================================================================== describe('Parallel Requests with Promise.all', () => { it('should fetch multiple resources in parallel', async () => { global.fetch = vi.fn() .mockResolvedValueOnce(new Response(JSON.stringify({ id: 1, name: 'User' }))) .mockResolvedValueOnce(new Response(JSON.stringify([{ id: 1, title: 'Post' }]))) .mockResolvedValueOnce(new Response(JSON.stringify([{ id: 1, body: 'Comment' }]))) const [user, posts, comments] = await Promise.all([ fetch('/api/user').then(r => r.json()), fetch('/api/posts').then(r => r.json()), fetch('/api/comments').then(r => r.json()) ]) expect(user).toEqual({ id: 1, name: 'User' }) expect(posts).toEqual([{ id: 1, title: 'Post' }]) expect(comments).toEqual([{ id: 1, body: 'Comment' }]) expect(fetch).toHaveBeenCalledTimes(3) }) it('should fail fast if any request fails', async () => { global.fetch = vi.fn() .mockResolvedValueOnce(new Response(JSON.stringify({ id: 1 }))) .mockRejectedValueOnce(new Error('Network error')) .mockResolvedValueOnce(new Response(JSON.stringify({ id: 3 }))) await expect(Promise.all([ fetch('/api/1').then(r => r.json()), fetch('/api/2').then(r => r.json()), fetch('/api/3').then(r => r.json()) ])).rejects.toThrow('Network error') }) it('should use Promise.allSettled for graceful handling', async () => { global.fetch = vi.fn() .mockResolvedValueOnce(new Response(JSON.stringify({ id: 1 }))) .mockRejectedValueOnce(new Error('Failed')) .mockResolvedValueOnce(new Response(JSON.stringify({ id: 3 }))) const results = await Promise.allSettled([ fetch('/api/1').then(r => r.json()), fetch('/api/2').then(r => r.json()), fetch('/api/3').then(r => r.json()) ]) expect(results[0].status).toBe('fulfilled') expect(results[0].value).toEqual({ id: 1 }) expect(results[1].status).toBe('rejected') expect(results[1].reason.message).toBe('Failed') expect(results[2].status).toBe('fulfilled') expect(results[2].value).toEqual({ id: 3 }) }) }) // =========================================================================== // LOADING STATE PATTERN // =========================================================================== describe('Loading State Pattern', () => { it('should track loading, data, and error states', async () => { async function fetchWithState(url) { const state = { data: null, loading: true, error: null } try { const response = await fetch(url) if (!response.ok) { throw new Error(`HTTP ${response.status}`) } state.data = await response.json() } catch (error) { state.error = error.message } finally { state.loading = false } return state } // Test successful fetch global.fetch = vi.fn().mockResolvedValue( new Response(JSON.stringify({ name: 'Alice' }), { status: 200 }) ) const successState = await fetchWithState('/api/user') expect(successState.loading).toBe(false) expect(successState.data).toEqual({ name: 'Alice' }) expect(successState.error).toBeNull() // Test error fetch global.fetch = vi.fn().mockResolvedValue( new Response('Not Found', { status: 404 }) ) const errorState = await fetchWithState('/api/missing') expect(errorState.loading).toBe(false) expect(errorState.data).toBeNull() expect(errorState.error).toBe('HTTP 404') // Test network error global.fetch = vi.fn().mockRejectedValue(new Error('Network error')) const networkErrorState = await fetchWithState('/api/unreachable') expect(networkErrorState.loading).toBe(false) expect(networkErrorState.data).toBeNull() expect(networkErrorState.error).toBe('Network error') }) }) // =========================================================================== // JSON PARSING // =========================================================================== describe('JSON Parsing', () => { it('should parse valid JSON', async () => { const response = new Response('{"name": "Alice", "age": 30}') const data = await response.json() expect(data).toEqual({ name: 'Alice', age: 30 }) }) it('should parse JSON arrays', async () => { const response = new Response('[1, 2, 3, 4, 5]') const data = await response.json() expect(data).toEqual([1, 2, 3, 4, 5]) }) it('should parse nested JSON', async () => { const nested = { user: { name: 'Alice', address: { city: 'Wonderland' } }, posts: [ { id: 1, title: 'First' }, { id: 2, title: 'Second' } ] } const response = new Response(JSON.stringify(nested)) const data = await response.json() expect(data.user.address.city).toBe('Wonderland') expect(data.posts[1].title).toBe('Second') }) it('should throw on invalid JSON', async () => { const response = new Response('not valid json {') await expect(response.json()).rejects.toThrow() }) it('should throw on empty body when expecting JSON', async () => { const response = new Response('') await expect(response.json()).rejects.toThrow() }) }) // =========================================================================== // HTTP METHODS // =========================================================================== describe('HTTP Methods', () => { beforeEach(() => { global.fetch = vi.fn().mockResolvedValue( new Response(JSON.stringify({ success: true }), { status: 200 }) ) }) it('should default to GET method', async () => { await fetch('/api/users') expect(fetch).toHaveBeenCalledWith('/api/users') }) it('should make POST request', async () => { await fetch('/api/users', { method: 'POST', body: JSON.stringify({ name: 'Alice' }) }) expect(fetch).toHaveBeenCalledWith('/api/users', expect.objectContaining({ method: 'POST' })) }) it('should make PUT request', async () => { await fetch('/api/users/1', { method: 'PUT', body: JSON.stringify({ name: 'Alice Updated' }) }) expect(fetch).toHaveBeenCalledWith('/api/users/1', expect.objectContaining({ method: 'PUT' })) }) it('should make PATCH request', async () => { await fetch('/api/users/1', { method: 'PATCH', body: JSON.stringify({ name: 'New Name' }) }) expect(fetch).toHaveBeenCalledWith('/api/users/1', expect.objectContaining({ method: 'PATCH' })) }) it('should make DELETE request', async () => { await fetch('/api/users/1', { method: 'DELETE' }) expect(fetch).toHaveBeenCalledWith('/api/users/1', expect.objectContaining({ method: 'DELETE' })) }) }) // =========================================================================== // URL AND QUERY PARAMETERS // =========================================================================== describe('URL and Query Parameters', () => { it('should construct URL with search params', () => { const url = new URL('https://api.example.com/search') url.searchParams.set('q', 'javascript') url.searchParams.set('page', '1') url.searchParams.set('limit', '10') expect(url.toString()).toBe('https://api.example.com/search?q=javascript&page=1&limit=10') }) it('should append multiple values for same param', () => { const url = new URL('https://api.example.com/filter') url.searchParams.append('tag', 'javascript') url.searchParams.append('tag', 'nodejs') expect(url.toString()).toBe('https://api.example.com/filter?tag=javascript&tag=nodejs') }) it('should get search params', () => { const url = new URL('https://api.example.com/search?q=javascript&page=2') expect(url.searchParams.get('q')).toBe('javascript') expect(url.searchParams.get('page')).toBe('2') expect(url.searchParams.get('missing')).toBeNull() }) it('should delete search params', () => { const url = new URL('https://api.example.com/search?q=javascript&page=2') url.searchParams.delete('page') expect(url.toString()).toBe('https://api.example.com/search?q=javascript') }) it('should check if param exists', () => { const url = new URL('https://api.example.com/search?q=javascript') expect(url.searchParams.has('q')).toBe(true) expect(url.searchParams.has('page')).toBe(false) }) it('should use URLSearchParams with fetch', async () => { global.fetch = vi.fn().mockResolvedValue( new Response(JSON.stringify([]), { status: 200 }) )
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
true
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/web-platform/dom/dom.test.js
tests/web-platform/dom/dom.test.js
/** * @vitest-environment jsdom */ import { describe, it, expect, beforeEach } from 'vitest' // ============================================================================= // DOM AND LAYOUT TREES - TEST SUITE // Tests for code examples from docs/concepts/dom.mdx // ============================================================================= describe('DOM and Layout Trees', () => { // Reset document body before each test beforeEach(() => { document.body.innerHTML = '' document.head.innerHTML = '' }) // =========================================================================== // NODE TYPES AND STRUCTURE // =========================================================================== describe('Node Types and Structure', () => { it('should identify element node type', () => { const div = document.createElement('div') expect(div.nodeType).toBe(1) expect(div.nodeType).toBe(Node.ELEMENT_NODE) expect(div.nodeName).toBe('DIV') }) it('should identify text node type', () => { const text = document.createTextNode('Hello') expect(text.nodeType).toBe(3) expect(text.nodeType).toBe(Node.TEXT_NODE) expect(text.nodeName).toBe('#text') }) it('should identify comment node type', () => { const comment = document.createComment('This is a comment') expect(comment.nodeType).toBe(8) expect(comment.nodeType).toBe(Node.COMMENT_NODE) expect(comment.nodeName).toBe('#comment') }) it('should identify document node type', () => { expect(document.nodeType).toBe(9) expect(document.nodeType).toBe(Node.DOCUMENT_NODE) expect(document.nodeName).toBe('#document') }) it('should identify document fragment node type', () => { const fragment = document.createDocumentFragment() expect(fragment.nodeType).toBe(11) expect(fragment.nodeType).toBe(Node.DOCUMENT_FRAGMENT_NODE) expect(fragment.nodeName).toBe('#document-fragment') }) it('should have correct node type constants', () => { expect(Node.ELEMENT_NODE).toBe(1) expect(Node.TEXT_NODE).toBe(3) expect(Node.COMMENT_NODE).toBe(8) expect(Node.DOCUMENT_NODE).toBe(9) expect(Node.DOCUMENT_FRAGMENT_NODE).toBe(11) }) it('should access document properties', () => { expect(document.documentElement.tagName).toBe('HTML') expect(document.head).toBeTruthy() expect(document.body).toBeTruthy() }) it('should be able to set document title', () => { document.title = 'New Title' expect(document.title).toBe('New Title') }) }) // =========================================================================== // SELECTING ELEMENTS // =========================================================================== describe('Selecting Elements', () => { beforeEach(() => { document.body.innerHTML = ` <div id="hero">Welcome!</div> <p class="intro">First</p> <p class="intro">Second</p> <p>Third</p> <nav> <a href="#" class="active">Home</a> <a href="#">About</a> </nav> <input type="text" data-id="123"> ` }) describe('getElementById', () => { it('should select element by id', () => { const hero = document.getElementById('hero') expect(hero).toBeTruthy() expect(hero.textContent).toBe('Welcome!') }) it('should return null for non-existent id', () => { const ghost = document.getElementById('nonexistent') expect(ghost).toBeNull() }) }) describe('getElementsByClassName', () => { it('should select elements by class name', () => { const intros = document.getElementsByClassName('intro') expect(intros.length).toBe(2) expect(intros[0].textContent).toBe('First') }) it('should return empty collection for non-existent class', () => { const ghosts = document.getElementsByClassName('nonexistent') expect(ghosts.length).toBe(0) }) }) describe('getElementsByTagName', () => { it('should select elements by tag name', () => { const allParagraphs = document.getElementsByTagName('p') expect(allParagraphs.length).toBe(3) }) }) describe('querySelector', () => { it('should select first matching element', () => { const firstButton = document.querySelector('a') expect(firstButton.textContent).toBe('Home') }) it('should select by id', () => { const hero = document.querySelector('#hero') expect(hero.textContent).toBe('Welcome!') }) it('should select by class', () => { const firstIntro = document.querySelector('.intro') expect(firstIntro.textContent).toBe('First') }) it('should select by complex selector', () => { const navLink = document.querySelector('nav a.active') expect(navLink.textContent).toBe('Home') }) it('should select by attribute', () => { const dataItem = document.querySelector('[data-id="123"]') expect(dataItem.tagName).toBe('INPUT') }) it('should return null for no match', () => { const ghost = document.querySelector('.nonexistent') expect(ghost).toBeNull() }) }) describe('querySelectorAll', () => { it('should select all matching elements', () => { const allCards = document.querySelectorAll('.intro') expect(allCards.length).toBe(2) }) it('should return empty NodeList for no matches', () => { const ghosts = document.querySelectorAll('.nonexistent') expect(ghosts.length).toBe(0) }) it('should support complex selectors', () => { const links = document.querySelectorAll('nav a') expect(links.length).toBe(2) }) }) describe('Scoped Selection', () => { it('should select within a parent element', () => { const nav = document.querySelector('nav') const navLinks = nav.querySelectorAll('a') expect(navLinks.length).toBe(2) }) it('should find specific child in parent', () => { const nav = document.querySelector('nav') const activeLink = nav.querySelector('.active') expect(activeLink.textContent).toBe('Home') }) }) }) // =========================================================================== // LIVE VS STATIC COLLECTIONS // =========================================================================== describe('Live vs Static Collections', () => { beforeEach(() => { document.body.innerHTML = ` <div class="item">One</div> <div class="item">Two</div> <div class="item">Three</div> ` }) it('should demonstrate live HTMLCollection updates', () => { const liveList = document.getElementsByClassName('item') expect(liveList.length).toBe(3) // Add a new item const newItem = document.createElement('div') newItem.className = 'item' document.body.appendChild(newItem) // Live collection is automatically updated expect(liveList.length).toBe(4) }) it('should demonstrate static NodeList does not update', () => { const staticList = document.querySelectorAll('.item') expect(staticList.length).toBe(3) // Add a new item const newItem = document.createElement('div') newItem.className = 'item' document.body.appendChild(newItem) // Static list is still the old snapshot expect(staticList.length).toBe(3) }) }) // =========================================================================== // DOM TRAVERSAL // =========================================================================== describe('DOM Traversal', () => { beforeEach(() => { document.body.innerHTML = ` <ul id="list"> <li id="first">One</li> <li id="second">Two</li> <li id="third">Three</li> </ul> ` }) describe('Traversing Downwards', () => { it('should get child nodes including text nodes', () => { const ul = document.querySelector('ul') // childNodes includes text nodes from whitespace expect(ul.childNodes.length).toBeGreaterThan(3) }) it('should get only element children', () => { const ul = document.querySelector('ul') expect(ul.children.length).toBe(3) expect(ul.children[0].textContent).toBe('One') }) it('should get first and last element children', () => { const ul = document.querySelector('ul') expect(ul.firstElementChild.textContent).toBe('One') expect(ul.lastElementChild.textContent).toBe('Three') }) it('should demonstrate firstChild vs firstElementChild', () => { const ul = document.querySelector('ul') // firstChild might be a text node (whitespace) const firstChild = ul.firstChild const firstElementChild = ul.firstElementChild // firstElementChild is always an element expect(firstElementChild.tagName).toBe('LI') // firstChild might be text node expect(firstChild.nodeType === Node.TEXT_NODE || firstChild.nodeType === Node.ELEMENT_NODE).toBe(true) }) }) describe('Traversing Upwards', () => { it('should get parent node', () => { const li = document.querySelector('li') expect(li.parentNode.tagName).toBe('UL') }) it('should get parent element', () => { const li = document.querySelector('li') expect(li.parentElement.tagName).toBe('UL') }) it('should find ancestor with closest()', () => { const li = document.querySelector('li') const ul = li.closest('ul') expect(ul.id).toBe('list') }) it('should return element itself if it matches closest()', () => { const li = document.querySelector('li') const self = li.closest('li') expect(self).toBe(li) }) it('should return null if no ancestor matches closest()', () => { const li = document.querySelector('li') const result = li.closest('.nonexistent') expect(result).toBeNull() }) }) describe('Traversing Sideways', () => { it('should get next element sibling', () => { const first = document.querySelector('#first') const second = first.nextElementSibling expect(second.id).toBe('second') }) it('should get previous element sibling', () => { const second = document.querySelector('#second') const first = second.previousElementSibling expect(first.id).toBe('first') }) it('should return null at boundaries', () => { const first = document.querySelector('#first') const third = document.querySelector('#third') expect(first.previousElementSibling).toBeNull() expect(third.nextElementSibling).toBeNull() }) }) describe('Building Ancestor Trail', () => { it('should get all ancestors of an element', () => { document.body.innerHTML = ` <main> <section> <div class="deeply-nested">Content</div> </section> </main> ` function getAncestors(element) { const ancestors = [] let current = element.parentElement while (current && current !== document.body) { ancestors.push(current) current = current.parentElement } return ancestors } const deepElement = document.querySelector('.deeply-nested') const ancestors = getAncestors(deepElement) expect(ancestors.length).toBe(2) expect(ancestors[0].tagName).toBe('SECTION') expect(ancestors[1].tagName).toBe('MAIN') }) }) }) // =========================================================================== // CREATING AND MANIPULATING ELEMENTS // =========================================================================== describe('Creating and Manipulating Elements', () => { describe('Creating Elements', () => { it('should create a new element', () => { const div = document.createElement('div') expect(div.tagName).toBe('DIV') expect(div.parentNode).toBeNull() // Not yet in DOM }) it('should create a text node', () => { const text = document.createTextNode('Hello, world!') expect(text.nodeType).toBe(Node.TEXT_NODE) expect(text.textContent).toBe('Hello, world!') }) it('should create a comment node', () => { const comment = document.createComment('This is a comment') expect(comment.nodeType).toBe(Node.COMMENT_NODE) expect(comment.textContent).toBe('This is a comment') }) }) describe('appendChild', () => { it('should add element as last child', () => { document.body.innerHTML = '<ul><li>Existing</li></ul>' const ul = document.querySelector('ul') const li = document.createElement('li') li.textContent = 'New item' ul.appendChild(li) expect(ul.lastElementChild.textContent).toBe('New item') expect(ul.children.length).toBe(2) }) }) describe('insertBefore', () => { it('should insert element before reference node', () => { document.body.innerHTML = '<ul><li>Existing</li></ul>' const ul = document.querySelector('ul') const existingLi = ul.querySelector('li') const newLi = document.createElement('li') newLi.textContent = 'First!' ul.insertBefore(newLi, existingLi) expect(ul.firstElementChild.textContent).toBe('First!') expect(ul.children.length).toBe(2) }) }) describe('append and prepend', () => { it('should append multiple items including strings', () => { const div = document.createElement('div') const span = document.createElement('span') div.append('Text', span, 'More text') expect(div.childNodes.length).toBe(3) expect(div.textContent).toBe('TextMore text') }) it('should prepend element to start', () => { document.body.innerHTML = '<div>Existing</div>' const div = document.querySelector('div') const strong = document.createElement('strong') strong.textContent = 'New' div.prepend(strong) expect(div.firstElementChild.tagName).toBe('STRONG') }) }) describe('before and after', () => { it('should insert as previous sibling with before()', () => { document.body.innerHTML = '<h1>Title</h1>' const h1 = document.querySelector('h1') const nav = document.createElement('nav') h1.before(nav) expect(h1.previousElementSibling.tagName).toBe('NAV') }) it('should insert as next sibling with after()', () => { document.body.innerHTML = '<h1>Title</h1>' const h1 = document.querySelector('h1') const p = document.createElement('p') h1.after(p) expect(h1.nextElementSibling.tagName).toBe('P') }) }) describe('insertAdjacentHTML', () => { it('should insert at all four positions', () => { document.body.innerHTML = '<div id="target">Content</div>' const div = document.querySelector('#target') div.insertAdjacentHTML('beforebegin', '<p id="before">Before</p>') div.insertAdjacentHTML('afterbegin', '<span id="first">First</span>') div.insertAdjacentHTML('beforeend', '<span id="last">Last</span>') div.insertAdjacentHTML('afterend', '<p id="after">After</p>') expect(div.previousElementSibling.id).toBe('before') expect(div.firstElementChild.id).toBe('first') expect(div.lastElementChild.id).toBe('last') expect(div.nextElementSibling.id).toBe('after') }) }) describe('Removing Elements', () => { it('should remove element with remove()', () => { document.body.innerHTML = '<div class="to-remove">Gone</div>' const element = document.querySelector('.to-remove') element.remove() expect(document.querySelector('.to-remove')).toBeNull() }) it('should remove child with removeChild()', () => { document.body.innerHTML = '<ul><li>Keep</li><li class="remove">Remove</li></ul>' const ul = document.querySelector('ul') const toRemove = ul.querySelector('.remove') ul.removeChild(toRemove) expect(ul.children.length).toBe(1) expect(ul.querySelector('.remove')).toBeNull() }) }) describe('Cloning Elements', () => { it('should shallow clone element only', () => { document.body.innerHTML = '<div class="card"><p>Content</p></div>' const original = document.querySelector('.card') const shallow = original.cloneNode(false) expect(shallow.className).toBe('card') expect(shallow.children.length).toBe(0) // No children }) it('should deep clone element with descendants', () => { document.body.innerHTML = '<div class="card"><p>Content</p></div>' const original = document.querySelector('.card') const deep = original.cloneNode(true) expect(deep.className).toBe('card') expect(deep.children.length).toBe(1) expect(deep.querySelector('p').textContent).toBe('Content') }) it('should create detached clone', () => { document.body.innerHTML = '<div class="card">Content</div>' const original = document.querySelector('.card') const clone = original.cloneNode(true) expect(clone.parentNode).toBeNull() }) }) describe('DocumentFragment', () => { it('should batch add elements with fragment', () => { document.body.innerHTML = '<ul></ul>' const ul = document.querySelector('ul') const fragment = document.createDocumentFragment() for (let i = 0; i < 5; i++) { const li = document.createElement('li') li.textContent = `Item ${i}` fragment.appendChild(li) } ul.appendChild(fragment) expect(ul.children.length).toBe(5) expect(ul.firstElementChild.textContent).toBe('Item 0') expect(ul.lastElementChild.textContent).toBe('Item 4') }) it('should have no parent', () => { const fragment = document.createDocumentFragment() expect(fragment.parentNode).toBeNull() }) }) }) // =========================================================================== // MODIFYING CONTENT // =========================================================================== describe('Modifying Content', () => { describe('innerHTML', () => { it('should read HTML content', () => { document.body.innerHTML = '<div><p>Hello</p><span>World</span></div>' const div = document.querySelector('div') expect(div.innerHTML).toBe('<p>Hello</p><span>World</span>') }) it('should set HTML content', () => { document.body.innerHTML = '<div></div>' const div = document.querySelector('div') div.innerHTML = '<h1>New Title</h1><p>New paragraph</p>' expect(div.children.length).toBe(2) expect(div.querySelector('h1').textContent).toBe('New Title') }) it('should clear content with empty string', () => { document.body.innerHTML = '<div><p>Content</p></div>' const div = document.querySelector('div') div.innerHTML = '' expect(div.children.length).toBe(0) }) }) describe('textContent', () => { it('should read text content ignoring HTML', () => { document.body.innerHTML = '<div><p>Hello</p><span>World</span></div>' const div = document.querySelector('div') expect(div.textContent).toBe('HelloWorld') }) it('should set text content escaping HTML', () => { document.body.innerHTML = '<div></div>' const div = document.querySelector('div') div.textContent = '<script>alert("XSS")</script>' // HTML is escaped, not parsed expect(div.children.length).toBe(0) expect(div.textContent).toBe('<script>alert("XSS")</script>') }) }) describe('innerText vs textContent', () => { it('textContent includes hidden text, innerText may not', () => { document.body.innerHTML = '<div>Hello <span style="display:none">Hidden</span> World</div>' const div = document.querySelector('div') // textContent includes all text expect(div.textContent).toContain('Hidden') // Note: In jsdom, innerText may behave like textContent // In real browsers, innerText would exclude display:none text }) }) }) // =========================================================================== // WORKING WITH ATTRIBUTES // =========================================================================== describe('Working with Attributes', () => { describe('Standard Attribute Methods', () => { it('should get attribute value', () => { document.body.innerHTML = '<a href="https://example.com" target="_blank">Link</a>' const link = document.querySelector('a') expect(link.getAttribute('href')).toBe('https://example.com') expect(link.getAttribute('target')).toBe('_blank') }) it('should set attribute value', () => { document.body.innerHTML = '<a href="#">Link</a>' const link = document.querySelector('a') link.setAttribute('href', 'https://newurl.com') link.setAttribute('target', '_blank') expect(link.getAttribute('href')).toBe('https://newurl.com') expect(link.getAttribute('target')).toBe('_blank') }) it('should check if attribute exists', () => { document.body.innerHTML = '<a href="#" target="_blank">Link</a>' const link = document.querySelector('a') expect(link.hasAttribute('target')).toBe(true) expect(link.hasAttribute('rel')).toBe(false) }) it('should remove attribute', () => { document.body.innerHTML = '<a href="#" target="_blank">Link</a>' const link = document.querySelector('a') link.removeAttribute('target') expect(link.hasAttribute('target')).toBe(false) }) }) describe('Properties vs Attributes', () => { it('should show difference between attribute and property', () => { document.body.innerHTML = '<input type="text" value="initial">' const input = document.querySelector('input') // Both start the same expect(input.getAttribute('value')).toBe('initial') expect(input.value).toBe('initial') // Change the property (simulating user input) input.value = 'new text' // Attribute stays the same, property changes expect(input.getAttribute('value')).toBe('initial') expect(input.value).toBe('new text') }) it('should show checkbox property vs attribute', () => { document.body.innerHTML = '<input type="checkbox" checked>' const checkbox = document.querySelector('input') // Attribute is string or null expect(checkbox.getAttribute('checked')).toBe('') // Property is boolean expect(checkbox.checked).toBe(true) // Toggle the property checkbox.checked = false expect(checkbox.checked).toBe(false) // Attribute may still exist }) }) describe('Data Attributes and dataset API', () => { it('should read data attributes via dataset', () => { document.body.innerHTML = '<div id="user" data-user-id="123" data-role="admin"></div>' const user = document.querySelector('#user') expect(user.dataset.userId).toBe('123') expect(user.dataset.role).toBe('admin') }) it('should write data attributes via dataset', () => { document.body.innerHTML = '<div id="user"></div>' const user = document.querySelector('#user') user.dataset.lastLogin = '2024-01-15' expect(user.getAttribute('data-last-login')).toBe('2024-01-15') }) it('should delete data attributes', () => { document.body.innerHTML = '<div data-role="admin"></div>' const div = document.querySelector('div') delete div.dataset.role expect(div.hasAttribute('data-role')).toBe(false) }) it('should check if data attribute exists', () => { document.body.innerHTML = '<div data-user-id="123"></div>' const div = document.querySelector('div') expect('userId' in div.dataset).toBe(true) expect('role' in div.dataset).toBe(false) }) }) }) // =========================================================================== // STYLING ELEMENTS // =========================================================================== describe('Styling Elements', () => { describe('style Property', () => { it('should set inline styles', () => { document.body.innerHTML = '<div></div>' const box = document.querySelector('div') box.style.backgroundColor = 'blue' box.style.fontSize = '20px' expect(box.style.backgroundColor).toBe('blue') expect(box.style.fontSize).toBe('20px') }) it('should remove inline style with empty string', () => { document.body.innerHTML = '<div style="color: red;"></div>' const box = document.querySelector('div') box.style.color = '' expect(box.style.color).toBe('') }) it('should set multiple styles with cssText', () => { document.body.innerHTML = '<div></div>' const box = document.querySelector('div') box.style.cssText = 'background: red; font-size: 16px; padding: 10px;' expect(box.style.background).toContain('red') expect(box.style.fontSize).toBe('16px') expect(box.style.padding).toBe('10px') }) }) describe('getComputedStyle', () => { it('should get computed styles', () => { document.body.innerHTML = '<div style="display: block;"></div>' const box = document.querySelector('div') const styles = getComputedStyle(box) expect(styles.display).toBe('block') }) }) describe('classList API', () => { it('should add classes', () => { document.body.innerHTML = '<button></button>' const button = document.querySelector('button') button.classList.add('active') button.classList.add('btn', 'btn-primary') expect(button.classList.contains('active')).toBe(true) expect(button.classList.contains('btn')).toBe(true) expect(button.classList.contains('btn-primary')).toBe(true) }) it('should remove classes', () => { document.body.innerHTML = '<button class="active btn btn-primary"></button>' const button = document.querySelector('button') button.classList.remove('active') button.classList.remove('btn', 'btn-primary') expect(button.classList.contains('active')).toBe(false) expect(button.classList.contains('btn')).toBe(false) }) it('should toggle classes', () => { document.body.innerHTML = '<button></button>' const button = document.querySelector('button') button.classList.toggle('active') expect(button.classList.contains('active')).toBe(true) button.classList.toggle('active') expect(button.classList.contains('active')).toBe(false) }) it('should toggle with condition', () => { document.body.innerHTML = '<button></button>' const button = document.querySelector('button') button.classList.toggle('active', true) expect(button.classList.contains('active')).toBe(true) button.classList.toggle('active', false) expect(button.classList.contains('active')).toBe(false) }) it('should replace class', () => { document.body.innerHTML = '<button class="btn-primary"></button>' const button = document.querySelector('button') button.classList.replace('btn-primary', 'btn-secondary') expect(button.classList.contains('btn-primary')).toBe(false) expect(button.classList.contains('btn-secondary')).toBe(true) }) it('should get class count', () => { document.body.innerHTML = '<button class="btn btn-primary active"></button>' const button = document.querySelector('button') expect(button.classList.length).toBe(3) }) }) }) // =========================================================================== // COMMON PATTERNS // =========================================================================== describe('Common Patterns', () => { describe('Checking Element Existence', () => { it('should check if element exists with querySelector', () => { document.body.innerHTML = '<div class="exists">Found</div>' const element = document.querySelector('.exists') if (element) { element.textContent = 'Updated!' } expect(document.querySelector('.exists').textContent).toBe('Updated!') }) it('should handle non-existent element safely', () => { document.body.innerHTML = '' const element = document.querySelector('.maybe-exists') // Using optional chaining (no error) element?.classList.add('active') expect(element).toBeNull() }) }) describe('Event Delegation Pattern', () => { it('should use closest() for event delegation', () => { document.body.innerHTML = ` <div class="card-container"> <div class="card"> <button class="btn">Click</button> </div> </div> ` let clickedCard = null const container = document.querySelector('.card-container') // Simulate event delegation const btn = document.querySelector('.btn') const card = btn.closest('.card') if (card) { clickedCard = card } expect(clickedCard).not.toBeNull() expect(clickedCard.classList.contains('card')).toBe(true) }) }) describe('Security Patterns - XSS Prevention', () => { it('should demonstrate innerHTML vulnerability with script-like content', () => { document.body.innerHTML = '<div id="output"></div>' const output = document.getElementById('output') // innerHTML can render HTML - potential XSS vector const maliciousInput = '<img src="x" onerror="alert(1)">' output.innerHTML = maliciousInput // The img tag is actually created const img = output.querySelector('img') expect(img).not.toBeNull() expect(img.getAttribute('onerror')).toBe('alert(1)') }) it('should use textContent to safely render user input', () => { document.body.innerHTML = '<div id="output"></div>' const output = document.getElementById('output') // textContent escapes HTML - safe from XSS const maliciousInput = '<img src="x" onerror="alert(1)">' output.textContent = maliciousInput // No img tag created - text is escaped const img = output.querySelector('img') expect(img).toBeNull() expect(output.textContent).toBe('<img src="x" onerror="alert(1)">') }) it('should show difference between innerHTML and textContent with HTML entities', () => { document.body.innerHTML = '<div id="html-output"></div><div id="text-output"></div>' const htmlOutput = document.getElementById('html-output') const textOutput = document.getElementById('text-output') const userInput = '<script>steal(cookies)</script>' htmlOutput.innerHTML = userInput textOutput.textContent = userInput // innerHTML parses the HTML (script won't execute in modern browsers but DOM is modified) expect(htmlOutput.children.length).toBeGreaterThanOrEqual(0) // textContent treats it as plain text expect(textOutput.textContent).toBe('<script>steal(cookies)</script>') expect(textOutput.children.length).toBe(0) }) }) describe('Attribute Shortcuts', () => { it('should access id directly on element', () => { document.body.innerHTML = '<div id="myElement"></div>'
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
true
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/advanced-topics/data-structures/data-structures.test.js
tests/advanced-topics/data-structures/data-structures.test.js
import { describe, it, expect } from 'vitest' describe('Data Structures', () => { describe('Arrays', () => { it('should access elements by index in O(1)', () => { const arr = ['a', 'b', 'c', 'd', 'e'] expect(arr[0]).toBe('a') expect(arr[2]).toBe('c') expect(arr[4]).toBe('e') }) it('should add and remove from end with push/pop in O(1)', () => { const arr = [1, 2, 3] arr.push(4) expect(arr).toEqual([1, 2, 3, 4]) const popped = arr.pop() expect(popped).toBe(4) expect(arr).toEqual([1, 2, 3]) }) it('should add and remove from beginning with unshift/shift (O(n))', () => { const arr = [1, 2, 3] arr.unshift(0) expect(arr).toEqual([0, 1, 2, 3]) const shifted = arr.shift() expect(shifted).toBe(0) expect(arr).toEqual([1, 2, 3]) }) it('should search with indexOf and includes in O(n)', () => { const arr = ['apple', 'banana', 'cherry'] expect(arr.indexOf('banana')).toBe(1) expect(arr.indexOf('mango')).toBe(-1) expect(arr.includes('cherry')).toBe(true) expect(arr.includes('grape')).toBe(false) }) it('should insert in middle with splice in O(n)', () => { const arr = [1, 2, 4, 5] // Insert 3 at index 2 arr.splice(2, 0, 3) expect(arr).toEqual([1, 2, 3, 4, 5]) // Remove element at index 2 arr.splice(2, 1) expect(arr).toEqual([1, 2, 4, 5]) }) }) describe('Objects', () => { it('should access, add, and delete properties in O(1)', () => { const user = { name: 'Alice', age: 30 } // Access expect(user.name).toBe('Alice') expect(user['age']).toBe(30) // Add user.email = 'alice@example.com' expect(user.email).toBe('alice@example.com') // Delete delete user.email expect(user.email).toBe(undefined) }) it('should check for key existence', () => { const user = { name: 'Alice' } expect('name' in user).toBe(true) expect('age' in user).toBe(false) expect(user.hasOwnProperty('name')).toBe(true) }) it('should convert numeric keys to strings', () => { const obj = {} obj[1] = 'one' obj['1'] = 'one as string' // Both are the same key! expect(Object.keys(obj)).toEqual(['1']) expect(obj[1]).toBe('one as string') expect(obj['1']).toBe('one as string') }) }) describe('Map', () => { it('should use any value type as key', () => { const map = new Map() const objKey = { id: 1 } const funcKey = () => {} map.set('string', 'string key') map.set(123, 'number key') map.set(objKey, 'object key') map.set(funcKey, 'function key') map.set(true, 'boolean key') expect(map.get('string')).toBe('string key') expect(map.get(123)).toBe('number key') expect(map.get(objKey)).toBe('object key') expect(map.get(funcKey)).toBe('function key') expect(map.get(true)).toBe('boolean key') }) it('should have a size property', () => { const map = new Map() map.set('a', 1) map.set('b', 2) map.set('c', 3) expect(map.size).toBe(3) }) it('should check existence with has()', () => { const map = new Map([['key', 'value']]) expect(map.has('key')).toBe(true) expect(map.has('nonexistent')).toBe(false) }) it('should delete entries', () => { const map = new Map([['a', 1], ['b', 2]]) map.delete('a') expect(map.has('a')).toBe(false) expect(map.size).toBe(1) }) it('should maintain insertion order', () => { const map = new Map() map.set('first', 1) map.set('second', 2) map.set('third', 3) const keys = [...map.keys()] expect(keys).toEqual(['first', 'second', 'third']) }) it('should iterate with for...of', () => { const map = new Map([['a', 1], ['b', 2]]) const entries = [] for (const [key, value] of map) { entries.push([key, value]) } expect(entries).toEqual([['a', 1], ['b', 2]]) }) it('should be useful for counting occurrences', () => { function countWords(text) { const words = text.toLowerCase().split(/\s+/) const counts = new Map() for (const word of words) { counts.set(word, (counts.get(word) || 0) + 1) } return counts } const result = countWords('the cat and the dog') expect(result.get('the')).toBe(2) expect(result.get('cat')).toBe(1) expect(result.get('and')).toBe(1) }) }) describe('Set', () => { it('should store only unique values', () => { const set = new Set() set.add(1) set.add(2) set.add(2) // Duplicate - ignored set.add(3) set.add(3) // Duplicate - ignored expect(set.size).toBe(3) expect([...set]).toEqual([1, 2, 3]) }) it('should check existence with has()', () => { const set = new Set([1, 2, 3]) expect(set.has(2)).toBe(true) expect(set.has(5)).toBe(false) }) it('should remove duplicates from array', () => { const numbers = [1, 2, 2, 3, 3, 3, 4] const unique = [...new Set(numbers)] expect(unique).toEqual([1, 2, 3, 4]) }) it('should delete values', () => { const set = new Set([1, 2, 3]) set.delete(2) expect(set.has(2)).toBe(false) expect(set.size).toBe(2) }) it('should iterate in insertion order', () => { const set = new Set() set.add('first') set.add('second') set.add('third') expect([...set]).toEqual(['first', 'second', 'third']) }) it('should perform set operations (ES2024+)', () => { const a = new Set([1, 2, 3]) const b = new Set([2, 3, 4]) // Skip if ES2024 Set methods not available if (typeof a.union !== 'function') { // Manual implementation for older environments const union = new Set([...a, ...b]) expect([...union].sort()).toEqual([1, 2, 3, 4]) const intersection = new Set([...a].filter(x => b.has(x))) expect([...intersection].sort()).toEqual([2, 3]) const difference = new Set([...a].filter(x => !b.has(x))) expect([...difference]).toEqual([1]) return } // Union: elements in either set expect([...a.union(b)].sort()).toEqual([1, 2, 3, 4]) // Intersection: elements in both sets expect([...a.intersection(b)].sort()).toEqual([2, 3]) // Difference: elements in a but not in b expect([...a.difference(b)]).toEqual([1]) // Symmetric difference: elements in either but not both expect([...a.symmetricDifference(b)].sort()).toEqual([1, 4]) }) it('should check subset relationships (ES2024+)', () => { const small = new Set([1, 2]) const large = new Set([1, 2, 3, 4]) // Skip if ES2024 Set methods not available if (typeof small.isSubsetOf !== 'function') { // Manual implementation for older environments const isSubset = [...small].every(x => large.has(x)) expect(isSubset).toBe(true) const isSuperset = [...small].every(x => large.has(x)) expect(isSuperset).toBe(true) const largeIsSubsetOfSmall = [...large].every(x => small.has(x)) expect(largeIsSubsetOfSmall).toBe(false) return } expect(small.isSubsetOf(large)).toBe(true) expect(large.isSupersetOf(small)).toBe(true) expect(large.isSubsetOf(small)).toBe(false) }) }) describe('WeakMap', () => { it('should only accept objects as keys', () => { const weakMap = new WeakMap() const obj = { id: 1 } weakMap.set(obj, 'value') expect(weakMap.get(obj)).toBe('value') // Cannot use primitives as keys expect(() => weakMap.set('string', 'value')).toThrow(TypeError) }) it('should support get, set, has, delete operations', () => { const weakMap = new WeakMap() const obj = { id: 1 } weakMap.set(obj, 'data') expect(weakMap.has(obj)).toBe(true) expect(weakMap.get(obj)).toBe('data') weakMap.delete(obj) expect(weakMap.has(obj)).toBe(false) }) it('should be useful for private data pattern', () => { const privateData = new WeakMap() class User { constructor(name, password) { this.name = name privateData.set(this, { password }) } checkPassword(input) { return privateData.get(this).password === input } } const user = new User('Alice', 'secret123') expect(user.name).toBe('Alice') expect(user.password).toBe(undefined) // Not accessible expect(user.checkPassword('secret123')).toBe(true) expect(user.checkPassword('wrong')).toBe(false) }) }) describe('WeakSet', () => { it('should only accept objects as values', () => { const weakSet = new WeakSet() const obj = { id: 1 } weakSet.add(obj) expect(weakSet.has(obj)).toBe(true) // Cannot use primitives expect(() => weakSet.add('string')).toThrow(TypeError) }) it('should be useful for tracking processed objects', () => { const processed = new WeakSet() function processOnce(obj) { if (processed.has(obj)) { return 'already processed' } processed.add(obj) return 'processed' } const obj = { data: 'test' } expect(processOnce(obj)).toBe('processed') expect(processOnce(obj)).toBe('already processed') }) }) describe('Stack Implementation', () => { class Stack { constructor() { this.items = [] } push(item) { this.items.push(item) } pop() { return this.items.pop() } peek() { return this.items[this.items.length - 1] } isEmpty() { return this.items.length === 0 } size() { return this.items.length } } it('should follow LIFO (Last In, First Out)', () => { const stack = new Stack() stack.push(1) stack.push(2) stack.push(3) expect(stack.pop()).toBe(3) // Last in expect(stack.pop()).toBe(2) expect(stack.pop()).toBe(1) // First in }) it('should peek without removing', () => { const stack = new Stack() stack.push('a') stack.push('b') expect(stack.peek()).toBe('b') expect(stack.size()).toBe(2) // Still 2 items }) it('should report isEmpty correctly', () => { const stack = new Stack() expect(stack.isEmpty()).toBe(true) stack.push(1) expect(stack.isEmpty()).toBe(false) stack.pop() expect(stack.isEmpty()).toBe(true) }) it('should handle pop and peek on empty stack', () => { const stack = new Stack() expect(stack.pop()).toBe(undefined) expect(stack.peek()).toBe(undefined) expect(stack.size()).toBe(0) }) it('should solve valid parentheses problem', () => { function isValid(s) { const stack = [] const pairs = { ')': '(', ']': '[', '}': '{' } for (const char of s) { if (char in pairs) { if (stack.pop() !== pairs[char]) { return false } } else { stack.push(char) } } return stack.length === 0 } expect(isValid('()')).toBe(true) expect(isValid('()[]{}')).toBe(true) expect(isValid('([{}])')).toBe(true) expect(isValid('(]')).toBe(false) expect(isValid('([)]')).toBe(false) expect(isValid('(((')).toBe(false) }) }) describe('Queue Implementation', () => { class Queue { constructor() { this.items = [] } enqueue(item) { this.items.push(item) } dequeue() { return this.items.shift() } front() { return this.items[0] } isEmpty() { return this.items.length === 0 } size() { return this.items.length } } it('should follow FIFO (First In, First Out)', () => { const queue = new Queue() queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) expect(queue.dequeue()).toBe(1) // First in expect(queue.dequeue()).toBe(2) expect(queue.dequeue()).toBe(3) // Last in }) it('should peek at front without removing', () => { const queue = new Queue() queue.enqueue('first') queue.enqueue('second') expect(queue.front()).toBe('first') expect(queue.size()).toBe(2) // Still 2 items }) it('should report isEmpty correctly', () => { const queue = new Queue() expect(queue.isEmpty()).toBe(true) queue.enqueue(1) expect(queue.isEmpty()).toBe(false) queue.dequeue() expect(queue.isEmpty()).toBe(true) }) it('should handle dequeue and front on empty queue', () => { const queue = new Queue() expect(queue.dequeue()).toBe(undefined) expect(queue.front()).toBe(undefined) expect(queue.size()).toBe(0) }) }) describe('Linked List Implementation', () => { class Node { constructor(value) { this.value = value this.next = null } } class LinkedList { constructor() { this.head = null this.size = 0 } prepend(value) { const node = new Node(value) node.next = this.head this.head = node this.size++ } append(value) { const node = new Node(value) if (!this.head) { this.head = node } else { let current = this.head while (current.next) { current = current.next } current.next = node } this.size++ } find(value) { let current = this.head while (current) { if (current.value === value) { return current } current = current.next } return null } toArray() { const result = [] let current = this.head while (current) { result.push(current.value) current = current.next } return result } } it('should prepend elements in O(1)', () => { const list = new LinkedList() list.prepend(3) list.prepend(2) list.prepend(1) expect(list.toArray()).toEqual([1, 2, 3]) }) it('should append elements', () => { const list = new LinkedList() list.append(1) list.append(2) list.append(3) expect(list.toArray()).toEqual([1, 2, 3]) }) it('should find elements', () => { const list = new LinkedList() list.append(1) list.append(2) list.append(3) const found = list.find(2) expect(found.value).toBe(2) expect(found.next.value).toBe(3) expect(list.find(5)).toBe(null) }) it('should track size correctly', () => { const list = new LinkedList() expect(list.size).toBe(0) list.append(1) list.append(2) list.prepend(0) expect(list.size).toBe(3) }) it('should handle operations on empty list', () => { const list = new LinkedList() expect(list.head).toBe(null) expect(list.find(1)).toBe(null) expect(list.toArray()).toEqual([]) }) it('should reverse a linked list', () => { function reverseList(head) { let prev = null let current = head while (current) { const next = current.next current.next = prev prev = current current = next } return prev } const list = new LinkedList() list.append(1) list.append(2) list.append(3) list.head = reverseList(list.head) expect(list.toArray()).toEqual([3, 2, 1]) }) }) describe('Binary Search Tree Implementation', () => { class TreeNode { constructor(value) { this.value = value this.left = null this.right = null } } class BinarySearchTree { constructor() { this.root = null } insert(value) { const node = new TreeNode(value) if (!this.root) { this.root = node return } let current = this.root while (true) { if (value < current.value) { if (!current.left) { current.left = node return } current = current.left } else { if (!current.right) { current.right = node return } current = current.right } } } search(value) { let current = this.root while (current) { if (value === current.value) { return current } current = value < current.value ? current.left : current.right } return null } inOrder(node = this.root, result = []) { if (node) { this.inOrder(node.left, result) result.push(node.value) this.inOrder(node.right, result) } return result } } it('should insert values following BST property', () => { const bst = new BinarySearchTree() bst.insert(10) bst.insert(5) bst.insert(15) expect(bst.root.value).toBe(10) expect(bst.root.left.value).toBe(5) expect(bst.root.right.value).toBe(15) }) it('should search for values', () => { const bst = new BinarySearchTree() bst.insert(10) bst.insert(5) bst.insert(15) bst.insert(3) bst.insert(7) expect(bst.search(7).value).toBe(7) expect(bst.search(15).value).toBe(15) expect(bst.search(100)).toBe(null) }) it('should return sorted values with in-order traversal', () => { const bst = new BinarySearchTree() bst.insert(10) bst.insert(5) bst.insert(15) bst.insert(3) bst.insert(7) bst.insert(20) expect(bst.inOrder()).toEqual([3, 5, 7, 10, 15, 20]) }) it('should find max depth of tree', () => { function maxDepth(root) { if (!root) return 0 const leftDepth = maxDepth(root.left) const rightDepth = maxDepth(root.right) return Math.max(leftDepth, rightDepth) + 1 } const bst = new BinarySearchTree() bst.insert(10) bst.insert(5) bst.insert(15) bst.insert(3) expect(maxDepth(bst.root)).toBe(3) }) it('should handle empty tree operations', () => { const bst = new BinarySearchTree() expect(bst.root).toBe(null) expect(bst.search(10)).toBe(null) expect(bst.inOrder()).toEqual([]) }) it('should handle duplicate values (goes to right subtree)', () => { const bst = new BinarySearchTree() bst.insert(10) bst.insert(10) // Duplicate bst.insert(10) // Another duplicate // Duplicates go to the right (based on our implementation: else branch) expect(bst.root.value).toBe(10) expect(bst.root.right.value).toBe(10) expect(bst.root.right.right.value).toBe(10) expect(bst.inOrder()).toEqual([10, 10, 10]) }) }) describe('Graph Implementation', () => { class Graph { constructor() { this.adjacencyList = new Map() } addVertex(vertex) { if (!this.adjacencyList.has(vertex)) { this.adjacencyList.set(vertex, []) } } addEdge(v1, v2) { this.adjacencyList.get(v1).push(v2) this.adjacencyList.get(v2).push(v1) } bfs(start) { const visited = new Set() const queue = [start] const result = [] while (queue.length) { const vertex = queue.shift() if (visited.has(vertex)) continue visited.add(vertex) result.push(vertex) for (const neighbor of this.adjacencyList.get(vertex)) { if (!visited.has(neighbor)) { queue.push(neighbor) } } } return result } dfs(start, visited = new Set(), result = []) { if (visited.has(start)) return result visited.add(start) result.push(start) for (const neighbor of this.adjacencyList.get(start)) { this.dfs(neighbor, visited, result) } return result } } it('should add vertices and edges', () => { const graph = new Graph() graph.addVertex('A') graph.addVertex('B') graph.addVertex('C') graph.addEdge('A', 'B') graph.addEdge('A', 'C') expect(graph.adjacencyList.get('A')).toContain('B') expect(graph.adjacencyList.get('A')).toContain('C') expect(graph.adjacencyList.get('B')).toContain('A') }) it('should perform breadth-first search', () => { const graph = new Graph() graph.addVertex('A') graph.addVertex('B') graph.addVertex('C') graph.addVertex('D') graph.addEdge('A', 'B') graph.addEdge('A', 'C') graph.addEdge('B', 'D') const result = graph.bfs('A') // BFS visits level by level expect(result[0]).toBe('A') expect(result.includes('B')).toBe(true) expect(result.includes('C')).toBe(true) expect(result.includes('D')).toBe(true) }) it('should perform depth-first search', () => { const graph = new Graph() graph.addVertex('A') graph.addVertex('B') graph.addVertex('C') graph.addVertex('D') graph.addEdge('A', 'B') graph.addEdge('A', 'C') graph.addEdge('B', 'D') const result = graph.dfs('A') // DFS goes deep before wide expect(result[0]).toBe('A') expect(result.length).toBe(4) }) }) describe('Common Interview Patterns', () => { it('Two Sum - using Map for O(n) lookup', () => { function twoSum(nums, target) { const seen = new Map() for (let i = 0; i < nums.length; i++) { const complement = target - nums[i] if (seen.has(complement)) { return [seen.get(complement), i] } seen.set(nums[i], i) } return [] } expect(twoSum([2, 7, 11, 15], 9)).toEqual([0, 1]) expect(twoSum([3, 2, 4], 6)).toEqual([1, 2]) expect(twoSum([3, 3], 6)).toEqual([0, 1]) }) it('Detect cycle in linked list - Floyd\'s algorithm', () => { function hasCycle(head) { let slow = head let fast = head while (fast && fast.next) { slow = slow.next fast = fast.next.next if (slow === fast) { return true } } return false } // Create a list with cycle const node1 = { val: 1, next: null } const node2 = { val: 2, next: null } const node3 = { val: 3, next: null } node1.next = node2 node2.next = node3 node3.next = node1 // Cycle back to node1 expect(hasCycle(node1)).toBe(true) // List without cycle const a = { val: 1, next: null } const b = { val: 2, next: null } a.next = b expect(hasCycle(a)).toBe(false) }) it('Queue using two stacks', () => { class QueueFromStacks { constructor() { this.stack1 = [] this.stack2 = [] } enqueue(item) { this.stack1.push(item) } dequeue() { if (this.stack2.length === 0) { while (this.stack1.length) { this.stack2.push(this.stack1.pop()) } } return this.stack2.pop() } } const queue = new QueueFromStacks() queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) expect(queue.dequeue()).toBe(1) // FIFO expect(queue.dequeue()).toBe(2) queue.enqueue(4) expect(queue.dequeue()).toBe(3) expect(queue.dequeue()).toBe(4) }) }) describe('Choosing the Right Data Structure', () => { it('should use Array for ordered data with index access', () => { const todos = ['Buy milk', 'Walk dog', 'Write code'] // O(1) access by index expect(todos[1]).toBe('Walk dog') // Easy to iterate expect(todos.map(t => t.toUpperCase())).toEqual([ 'BUY MILK', 'WALK DOG', 'WRITE CODE' ]) }) it('should use Set for unique values and fast lookup', () => { const visited = new Set() // Track unique visitors visited.add('user1') visited.add('user2') visited.add('user1') // Duplicate ignored expect(visited.size).toBe(2) expect(visited.has('user1')).toBe(true) // O(1) lookup }) it('should use Map for non-string keys or frequent updates', () => { // Using objects as keys const cache = new Map() const request1 = { url: '/api/users', method: 'GET' } const request2 = { url: '/api/posts', method: 'GET' } cache.set(request1, { data: ['user1', 'user2'] }) cache.set(request2, { data: ['post1', 'post2'] }) expect(cache.get(request1).data).toEqual(['user1', 'user2']) }) it('should use Stack for undo/redo or backtracking', () => { const history = [] // Record actions history.push('action1') history.push('action2') history.push('action3') // Undo - pop most recent const undone = history.pop() expect(undone).toBe('action3') }) it('should use Queue for task scheduling', () => { const taskQueue = [] // Add tasks taskQueue.push('task1') taskQueue.push('task2') taskQueue.push('task3') // Process in order expect(taskQueue.shift()).toBe('task1') // First added expect(taskQueue.shift()).toBe('task2') }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/advanced-topics/modern-js-syntax/modern-js-syntax.test.js
tests/advanced-topics/modern-js-syntax/modern-js-syntax.test.js
import { describe, it, expect } from 'vitest' describe('Modern JavaScript Syntax (ES6+)', () => { // =========================================== // ARROW FUNCTIONS // =========================================== describe('Arrow Functions', () => { it('should have concise syntax for single expressions', () => { const add = (a, b) => a + b const square = x => x * x const greet = () => 'Hello!' expect(add(2, 3)).toBe(5) expect(square(4)).toBe(16) expect(greet()).toBe('Hello!') }) it('should require explicit return in block body', () => { const withBlock = (a, b) => { return a + b } const withoutReturn = (a, b) => { a + b } // Returns undefined expect(withBlock(2, 3)).toBe(5) expect(withoutReturn(2, 3)).toBe(undefined) }) it('should require parentheses when returning object literal', () => { // Without parentheses, braces are interpreted as function body (labeled statement) const wrong = name => { name: name } // This is a labeled statement, returns undefined const correct = name => ({ name: name }) // Parentheses make it an object literal expect(wrong('Alice')).toBe(undefined) expect(correct('Alice')).toEqual({ name: 'Alice' }) // Note: Adding a comma like { name: name, active: true } would be a SyntaxError }) it('should inherit this from enclosing scope', () => { const obj = { value: 42, getValueArrow: function() { const arrow = () => this.value return arrow() }, getValueRegular: function() { // In strict mode, 'this' inside a plain function call is undefined // This would throw an error if we try to access this.value const regular = function() { return this } return regular() } } expect(obj.getValueArrow()).toBe(42) // Arrow function correctly inherits 'this' from getValueArrow // Regular function loses 'this' binding (undefined in strict mode) expect(obj.getValueRegular()).toBe(undefined) }) }) // =========================================== // DESTRUCTURING // =========================================== describe('Destructuring', () => { describe('Array Destructuring', () => { it('should extract values by position', () => { const colors = ['red', 'green', 'blue'] const [first, second, third] = colors expect(first).toBe('red') expect(second).toBe('green') expect(third).toBe('blue') }) it('should skip elements with empty slots', () => { const numbers = [1, 2, 3, 4, 5] const [first, , third, , fifth] = numbers expect(first).toBe(1) expect(third).toBe(3) expect(fifth).toBe(5) }) it('should support default values', () => { const [a, b, c = 'default'] = [1, 2] expect(a).toBe(1) expect(b).toBe(2) expect(c).toBe('default') }) it('should support rest pattern', () => { const [head, ...tail] = [1, 2, 3, 4, 5] expect(head).toBe(1) expect(tail).toEqual([2, 3, 4, 5]) }) it('should swap variables without temp', () => { let x = 1 let y = 2 ;[x, y] = [y, x] expect(x).toBe(2) expect(y).toBe(1) }) }) describe('Object Destructuring', () => { it('should extract properties by name', () => { const user = { name: 'Alice', age: 25 } const { name, age } = user expect(name).toBe('Alice') expect(age).toBe(25) }) it('should support renaming', () => { const user = { name: 'Alice', age: 25 } const { name: userName, age: userAge } = user expect(userName).toBe('Alice') expect(userAge).toBe(25) }) it('should support default values', () => { const user = { name: 'Alice' } const { name, role = 'guest' } = user expect(name).toBe('Alice') expect(role).toBe('guest') }) it('should support nested destructuring', () => { const user = { name: 'Alice', address: { city: 'Portland', country: 'USA' } } const { address: { city } } = user expect(city).toBe('Portland') }) it('should support rest pattern', () => { const user = { id: 1, name: 'Alice', age: 25 } const { id, ...rest } = user expect(id).toBe(1) expect(rest).toEqual({ name: 'Alice', age: 25 }) }) }) describe('Function Parameter Destructuring', () => { it('should destructure parameters', () => { function greet({ name, greeting = 'Hello' }) { return `${greeting}, ${name}!` } expect(greet({ name: 'Alice' })).toBe('Hello, Alice!') expect(greet({ name: 'Bob', greeting: 'Hi' })).toBe('Hi, Bob!') }) it('should handle empty parameter with default', () => { function greet({ name = 'Guest' } = {}) { return `Hello, ${name}!` } expect(greet()).toBe('Hello, Guest!') expect(greet({})).toBe('Hello, Guest!') expect(greet({ name: 'Alice' })).toBe('Hello, Alice!') }) }) }) // =========================================== // SPREAD AND REST OPERATORS // =========================================== describe('Spread and Rest Operators', () => { describe('Spread Operator', () => { it('should spread arrays', () => { const arr1 = [1, 2, 3] const arr2 = [4, 5, 6] expect([...arr1, ...arr2]).toEqual([1, 2, 3, 4, 5, 6]) expect([0, ...arr1, 4]).toEqual([0, 1, 2, 3, 4]) }) it('should copy arrays (shallow)', () => { const original = [1, 2, 3] const copy = [...original] expect(copy).toEqual(original) expect(copy).not.toBe(original) }) it('should spread objects', () => { const defaults = { theme: 'light', fontSize: 14 } const userPrefs = { theme: 'dark' } const merged = { ...defaults, ...userPrefs } expect(merged).toEqual({ theme: 'dark', fontSize: 14 }) }) it('should spread function arguments', () => { const numbers = [1, 5, 3, 9, 2] expect(Math.max(...numbers)).toBe(9) expect(Math.min(...numbers)).toBe(1) }) it('should create shallow copies only', () => { const original = { nested: { value: 1 } } const copy = { ...original } copy.nested.value = 2 // Both are affected because nested object is shared expect(original.nested.value).toBe(2) expect(copy.nested.value).toBe(2) }) }) describe('Rest Parameters', () => { it('should collect remaining arguments', () => { function sum(...numbers) { return numbers.reduce((total, n) => total + n, 0) } expect(sum(1, 2, 3)).toBe(6) expect(sum(1, 2, 3, 4, 5)).toBe(15) expect(sum()).toBe(0) }) it('should work with named parameters', () => { function log(first, ...rest) { return { first, rest } } expect(log('a', 'b', 'c', 'd')).toEqual({ first: 'a', rest: ['b', 'c', 'd'] }) }) }) }) // =========================================== // TEMPLATE LITERALS // =========================================== describe('Template Literals', () => { it('should interpolate expressions', () => { const name = 'Alice' const age = 25 expect(`Hello, ${name}!`).toBe('Hello, Alice!') expect(`Age: ${age}`).toBe('Age: 25') expect(`Next year: ${age + 1}`).toBe('Next year: 26') }) it('should support multi-line strings', () => { const multiLine = `line 1 line 2 line 3` expect(multiLine).toContain('line 1') expect(multiLine).toContain('\n') expect(multiLine.split('\n').length).toBe(3) }) it('should work with tagged templates', () => { function upper(strings, ...values) { return strings.reduce((result, str, i) => { const value = values[i] ? values[i].toString().toUpperCase() : '' return result + str + value }, '') } const name = 'alice' expect(upper`Hello, ${name}!`).toBe('Hello, ALICE!') }) }) // =========================================== // OPTIONAL CHAINING // =========================================== describe('Optional Chaining', () => { it('should safely access nested properties', () => { const user = { name: 'Alice' } const userWithAddress = { name: 'Bob', address: { city: 'Portland' } } expect(user?.address?.city).toBe(undefined) expect(userWithAddress?.address?.city).toBe('Portland') }) it('should short-circuit on null/undefined', () => { const user = null expect(user?.name).toBe(undefined) expect(user?.address?.city).toBe(undefined) }) it('should work with bracket notation', () => { const user = { profile: { name: 'Alice' } } const prop = 'profile' expect(user?.[prop]?.name).toBe('Alice') expect(user?.['nonexistent']?.name).toBe(undefined) }) it('should work with function calls', () => { const obj = { greet: () => 'Hello!' } expect(obj.greet?.()).toBe('Hello!') expect(obj.nonexistent?.()).toBe(undefined) }) }) // =========================================== // NULLISH COALESCING // =========================================== describe('Nullish Coalescing', () => { it('should return right side only for null/undefined', () => { expect(null ?? 'default').toBe('default') expect(undefined ?? 'default').toBe('default') expect(0 ?? 'default').toBe(0) expect('' ?? 'default').toBe('') expect(false ?? 'default').toBe(false) expect(NaN ?? 'default').toBeNaN() }) it('should differ from logical OR', () => { // || returns right side for any falsy value expect(0 || 'default').toBe('default') expect('' || 'default').toBe('default') expect(false || 'default').toBe('default') // ?? only returns right side for null/undefined expect(0 ?? 'default').toBe(0) expect('' ?? 'default').toBe('') expect(false ?? 'default').toBe(false) }) it('should combine with optional chaining', () => { const user = null expect(user?.name ?? 'Anonymous').toBe('Anonymous') const userWithName = { name: 'Alice' } expect(userWithName?.name ?? 'Anonymous').toBe('Alice') }) }) // =========================================== // LOGICAL ASSIGNMENT OPERATORS // =========================================== describe('Logical Assignment Operators', () => { it('should support nullish coalescing assignment (??=)', () => { let a = null let b = 'value' let c = 0 a ??= 'default' b ??= 'default' c ??= 'default' expect(a).toBe('default') expect(b).toBe('value') expect(c).toBe(0) }) it('should support logical OR assignment (||=)', () => { let a = null let b = 'value' let c = 0 a ||= 'default' b ||= 'default' c ||= 'default' expect(a).toBe('default') expect(b).toBe('value') expect(c).toBe('default') // 0 is falsy }) it('should support logical AND assignment (&&=)', () => { let a = null let b = 'value' a &&= 'updated' b &&= 'updated' expect(a).toBe(null) // null is falsy, so no assignment expect(b).toBe('updated') // 'value' is truthy, so assign }) }) // =========================================== // DEFAULT PARAMETERS // =========================================== describe('Default Parameters', () => { it('should provide default values', () => { function greet(name = 'Guest', greeting = 'Hello') { return `${greeting}, ${name}!` } expect(greet()).toBe('Hello, Guest!') expect(greet('Alice')).toBe('Hello, Alice!') expect(greet('Bob', 'Hi')).toBe('Hi, Bob!') }) it('should only trigger on undefined, not null', () => { function example(value = 'default') { return value } expect(example(undefined)).toBe('default') expect(example(null)).toBe(null) expect(example(0)).toBe(0) expect(example('')).toBe('') expect(example(false)).toBe(false) }) it('should allow earlier parameters as defaults', () => { function createRect(width, height = width) { return { width, height } } expect(createRect(10)).toEqual({ width: 10, height: 10 }) expect(createRect(10, 20)).toEqual({ width: 10, height: 20 }) }) it('should evaluate default expressions each time', () => { let counter = 0 function getDefault() { return ++counter } function example(value = getDefault()) { return value } expect(example()).toBe(1) expect(example()).toBe(2) expect(example()).toBe(3) expect(example(100)).toBe(100) // getDefault not called expect(example()).toBe(4) }) }) // =========================================== // ENHANCED OBJECT LITERALS // =========================================== describe('Enhanced Object Literals', () => { it('should support property shorthand', () => { const name = 'Alice' const age = 25 const user = { name, age } expect(user).toEqual({ name: 'Alice', age: 25 }) }) it('should support method shorthand', () => { const calculator = { add(a, b) { return a + b }, subtract(a, b) { return a - b } } expect(calculator.add(5, 3)).toBe(8) expect(calculator.subtract(5, 3)).toBe(2) }) it('should support computed property names', () => { const key = 'dynamicKey' const index = 0 const obj = { [key]: 'value', [`item_${index}`]: 'first' } expect(obj.dynamicKey).toBe('value') expect(obj.item_0).toBe('first') }) }) // =========================================== // MAP, SET, AND SYMBOL // =========================================== describe('Map', () => { it('should store key-value pairs with any key type', () => { const map = new Map() const objKey = { id: 1 } map.set('string', 'value1') map.set(42, 'value2') map.set(objKey, 'value3') expect(map.get('string')).toBe('value1') expect(map.get(42)).toBe('value2') expect(map.get(objKey)).toBe('value3') expect(map.size).toBe(3) }) it('should maintain insertion order', () => { const map = new Map([['c', 3], ['a', 1], ['b', 2]]) const keys = [...map.keys()] expect(keys).toEqual(['c', 'a', 'b']) }) it('should be iterable', () => { const map = new Map([['a', 1], ['b', 2]]) const entries = [] for (const [key, value] of map) { entries.push([key, value]) } expect(entries).toEqual([['a', 1], ['b', 2]]) }) }) describe('Set', () => { it('should store unique values', () => { const set = new Set([1, 2, 2, 3, 3, 3]) expect(set.size).toBe(3) expect([...set]).toEqual([1, 2, 3]) }) it('should remove duplicates from arrays', () => { const numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] const unique = [...new Set(numbers)] expect(unique).toEqual([1, 2, 3, 4]) }) it('should support set operations', () => { const a = new Set([1, 2, 3]) const b = new Set([2, 3, 4]) const union = new Set([...a, ...b]) const intersection = [...a].filter(x => b.has(x)) const difference = [...a].filter(x => !b.has(x)) expect([...union]).toEqual([1, 2, 3, 4]) expect(intersection).toEqual([2, 3]) expect(difference).toEqual([1]) }) }) describe('Symbol', () => { it('should create unique values', () => { const sym1 = Symbol('description') const sym2 = Symbol('description') expect(sym1).not.toBe(sym2) }) it('should work as object keys', () => { const ID = Symbol('id') const user = { name: 'Alice', [ID]: 12345 } expect(user[ID]).toBe(12345) expect(Object.keys(user)).toEqual(['name']) // Symbol not included }) it('should support global registry with Symbol.for', () => { const sym1 = Symbol.for('shared') const sym2 = Symbol.for('shared') expect(sym1).toBe(sym2) expect(Symbol.keyFor(sym1)).toBe('shared') }) }) // =========================================== // FOR...OF LOOP // =========================================== describe('for...of Loop', () => { it('should iterate over array values', () => { const arr = ['a', 'b', 'c'] const values = [] for (const value of arr) { values.push(value) } expect(values).toEqual(['a', 'b', 'c']) }) it('should iterate over string characters', () => { const chars = [] for (const char of 'hello') { chars.push(char) } expect(chars).toEqual(['h', 'e', 'l', 'l', 'o']) }) it('should iterate over Map entries', () => { const map = new Map([['a', 1], ['b', 2]]) const entries = [] for (const [key, value] of map) { entries.push({ key, value }) } expect(entries).toEqual([ { key: 'a', value: 1 }, { key: 'b', value: 2 } ]) }) it('should iterate over Set values', () => { const set = new Set([1, 2, 3]) const values = [] for (const value of set) { values.push(value) } expect(values).toEqual([1, 2, 3]) }) it('should work with destructuring', () => { const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 } ] const names = [] for (const { name } of users) { names.push(name) } expect(names).toEqual(['Alice', 'Bob']) }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/advanced-topics/regular-expressions/regular-expressions.test.js
tests/advanced-topics/regular-expressions/regular-expressions.test.js
import { describe, it, expect } from 'vitest' describe('Regular Expressions', () => { describe('Creating Regex', () => { it('should create regex with literal syntax', () => { const pattern = /hello/ expect(pattern.test('hello world')).toBe(true) expect(pattern.test('world')).toBe(false) }) it('should create regex with RegExp constructor', () => { const pattern = new RegExp('hello') expect(pattern.test('hello world')).toBe(true) expect(pattern.test('world')).toBe(false) }) it('should create dynamic patterns with RegExp constructor', () => { const searchTerm = 'cat' const pattern = new RegExp(searchTerm, 'gi') expect('Cat CAT cat'.match(pattern)).toEqual(['Cat', 'CAT', 'cat']) }) }) describe('Character Classes', () => { it('should match digits with \\d', () => { const pattern = /\d+/ expect(pattern.test('123')).toBe(true) expect(pattern.test('abc')).toBe(false) expect('abc123def'.match(pattern)[0]).toBe('123') }) it('should match word characters with \\w', () => { const pattern = /\w+/g expect('hello_world 123'.match(pattern)).toEqual(['hello_world', '123']) }) it('should match whitespace with \\s', () => { const pattern = /\s+/ expect(pattern.test('hello world')).toBe(true) expect(pattern.test('helloworld')).toBe(false) }) it('should match any character with .', () => { const pattern = /a.c/ expect(pattern.test('abc')).toBe(true) expect(pattern.test('a1c')).toBe(true) expect(pattern.test('ac')).toBe(false) }) it('should match character sets with []', () => { const vowelPattern = /[aeiou]/g expect('hello'.match(vowelPattern)).toEqual(['e', 'o']) }) it('should match negated character sets with [^]', () => { const nonDigitPattern = /[^0-9]+/g expect('abc123def'.match(nonDigitPattern)).toEqual(['abc', 'def']) }) it('should match character ranges', () => { const lowercasePattern = /[a-z]+/g expect('Hello World'.match(lowercasePattern)).toEqual(['ello', 'orld']) }) }) describe('Quantifiers', () => { it('should match 0 or more with *', () => { const pattern = /ab*c/ expect(pattern.test('ac')).toBe(true) expect(pattern.test('abc')).toBe(true) expect(pattern.test('abbbbc')).toBe(true) }) it('should match 1 or more with +', () => { const pattern = /ab+c/ expect(pattern.test('ac')).toBe(false) expect(pattern.test('abc')).toBe(true) expect(pattern.test('abbbbc')).toBe(true) }) it('should match 0 or 1 with ?', () => { const pattern = /colou?r/ expect(pattern.test('color')).toBe(true) expect(pattern.test('colour')).toBe(true) expect(pattern.test('colouur')).toBe(false) }) it('should match exact count with {n}', () => { const pattern = /\d{4}/ expect(pattern.test('2024')).toBe(true) expect(pattern.test('123')).toBe(false) }) it('should match range with {n,m}', () => { const pattern = /\d{2,4}/ expect('1'.match(pattern)).toBe(null) expect('12'.match(pattern)[0]).toBe('12') expect('12345'.match(pattern)[0]).toBe('1234') }) it('should match n or more with {n,}', () => { const pattern = /\d{2,}/ expect(pattern.test('1')).toBe(false) expect(pattern.test('12')).toBe(true) expect(pattern.test('12345')).toBe(true) }) }) describe('Anchors', () => { it('should match start of string with ^', () => { const pattern = /^Hello/ expect(pattern.test('Hello World')).toBe(true) expect(pattern.test('Say Hello')).toBe(false) }) it('should match end of string with $', () => { const pattern = /World$/ expect(pattern.test('Hello World')).toBe(true) expect(pattern.test('World Hello')).toBe(false) }) it('should match entire string with ^ and $', () => { const pattern = /^\d+$/ expect(pattern.test('12345')).toBe(true) expect(pattern.test('123abc')).toBe(false) expect(pattern.test('abc123')).toBe(false) }) it('should match word boundaries with \\b', () => { const pattern = /\bcat\b/ expect(pattern.test('cat')).toBe(true) expect(pattern.test('the cat sat')).toBe(true) expect(pattern.test('category')).toBe(false) expect(pattern.test('concatenate')).toBe(false) }) }) describe('Methods', () => { describe('test()', () => { it('should return true for matches', () => { expect(/\d+/.test('123')).toBe(true) }) it('should return false for non-matches', () => { expect(/\d+/.test('abc')).toBe(false) }) }) describe('match()', () => { it('should return first match without g flag', () => { const result = 'cat and cat'.match(/cat/) expect(result[0]).toBe('cat') expect(result.index).toBe(0) }) it('should return all matches with g flag', () => { const result = 'cat and cat'.match(/cat/g) expect(result).toEqual(['cat', 'cat']) }) it('should return null when no match', () => { expect('hello'.match(/\d+/)).toBe(null) }) }) describe('replace()', () => { it('should replace first match without g flag', () => { expect('hello world'.replace(/o/, '0')).toBe('hell0 world') }) it('should replace all matches with g flag', () => { expect('hello world'.replace(/o/g, '0')).toBe('hell0 w0rld') }) it('should use captured groups in replacement', () => { expect('John Smith'.replace(/(\w+) (\w+)/, '$2, $1')).toBe('Smith, John') }) }) describe('split()', () => { it('should split by regex pattern', () => { expect('a, b, c'.split(/,\s*/)).toEqual(['a', 'b', 'c']) }) it('should split on whitespace', () => { expect('hello world foo'.split(/\s+/)).toEqual(['hello', 'world', 'foo']) }) }) describe('exec()', () => { it('should return match with details', () => { const result = /\d+/.exec('abc123def') expect(result[0]).toBe('123') expect(result.index).toBe(3) }) it('should return null for no match', () => { expect(/\d+/.exec('abc')).toBe(null) }) }) }) describe('Flags', () => { it('should match case-insensitively with i flag', () => { const pattern = /hello/i expect(pattern.test('HELLO')).toBe(true) expect(pattern.test('Hello')).toBe(true) expect(pattern.test('hello')).toBe(true) }) it('should find all matches with g flag', () => { const pattern = /a/g expect('banana'.match(pattern)).toEqual(['a', 'a', 'a']) }) it('should match line boundaries with m flag', () => { const text = 'line1\nline2\nline3' const pattern = /^line\d/gm expect(text.match(pattern)).toEqual(['line1', 'line2', 'line3']) }) it('should combine multiple flags', () => { const pattern = /hello/gi expect('Hello HELLO hello'.match(pattern)).toEqual(['Hello', 'HELLO', 'hello']) }) }) describe('Capturing Groups', () => { it('should capture groups with parentheses', () => { const pattern = /(\d{3})-(\d{4})/ const match = '555-1234'.match(pattern) expect(match[0]).toBe('555-1234') expect(match[1]).toBe('555') expect(match[2]).toBe('1234') }) it('should support named groups', () => { const pattern = /(?<area>\d{3})-(?<number>\d{4})/ const match = '555-1234'.match(pattern) expect(match.groups.area).toBe('555') expect(match.groups.number).toBe('1234') }) it('should use groups in replace with $n', () => { const result = '12-25-2024'.replace( /(\d{2})-(\d{2})-(\d{4})/, '$3/$1/$2' ) expect(result).toBe('2024/12/25') }) it('should use named groups in replace', () => { const result = '12-25-2024'.replace( /(?<month>\d{2})-(?<day>\d{2})-(?<year>\d{4})/, '$<year>/$<month>/$<day>' ) expect(result).toBe('2024/12/25') }) it('should support non-capturing groups with (?:)', () => { const pattern = /(?:ab)+/ const match = 'ababab'.match(pattern) expect(match[0]).toBe('ababab') expect(match[1]).toBeUndefined() }) }) describe('Greedy vs Lazy', () => { it('should match greedily by default', () => { const html = '<div>Hello</div><div>World</div>' const greedy = /<div>.*<\/div>/ expect(html.match(greedy)[0]).toBe('<div>Hello</div><div>World</div>') }) it('should match lazily with ?', () => { const html = '<div>Hello</div><div>World</div>' const lazy = /<div>.*?<\/div>/ expect(html.match(lazy)[0]).toBe('<div>Hello</div>') }) it('should find all lazy matches with g flag', () => { const html = '<div>Hello</div><div>World</div>' const lazy = /<div>.*?<\/div>/g expect(html.match(lazy)).toEqual(['<div>Hello</div>', '<div>World</div>']) }) }) describe('Common Patterns', () => { it('should validate basic email format', () => { const email = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ expect(email.test('user@example.com')).toBe(true) expect(email.test('user.name@example.co.uk')).toBe(true) expect(email.test('invalid-email')).toBe(false) expect(email.test('missing@domain')).toBe(false) expect(email.test('@missing-local.com')).toBe(false) }) it('should validate URL format', () => { const url = /^https?:\/\/[^\s]+$/ expect(url.test('https://example.com')).toBe(true) expect(url.test('http://example.com/path')).toBe(true) expect(url.test('ftp://example.com')).toBe(false) expect(url.test('not a url')).toBe(false) }) it('should validate US phone number formats', () => { const phone = /^(\(\d{3}\)|\d{3})[-.\s]?\d{3}[-.\s]?\d{4}$/ expect(phone.test('555-123-4567')).toBe(true) expect(phone.test('(555) 123-4567')).toBe(true) expect(phone.test('555.123.4567')).toBe(true) expect(phone.test('5551234567')).toBe(true) expect(phone.test('55-123-4567')).toBe(false) }) it('should validate username format', () => { const username = /^[a-zA-Z0-9_]{3,16}$/ expect(username.test('john_doe')).toBe(true) expect(username.test('user123')).toBe(true) expect(username.test('ab')).toBe(false) // too short expect(username.test('this_is_way_too_long_username')).toBe(false) // too long expect(username.test('invalid-user')).toBe(false) // hyphen not allowed }) it('should extract hashtags from text', () => { const hashtags = /#\w+/g const text = 'Learning #JavaScript and #regex is fun! #coding' expect(text.match(hashtags)).toEqual(['#JavaScript', '#regex', '#coding']) }) it('should extract numbers from text', () => { const numbers = /\d+/g const text = 'I have 42 apples and 7 oranges' expect(text.match(numbers)).toEqual(['42', '7']) }) }) describe('Edge Cases', () => { it('should escape special characters in RegExp constructor', () => { const searchTerm = 'hello.world' const escaped = searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') const pattern = new RegExp(escaped) expect(pattern.test('hello.world')).toBe(true) expect(pattern.test('helloXworld')).toBe(false) }) it('should handle empty strings', () => { expect(/.*/.test('')).toBe(true) expect(/.+/.test('')).toBe(false) const emptyMatch = ''.match(/\d*/) expect(emptyMatch[0]).toBe('') }) it('should handle alternation with |', () => { const pattern = /cat|dog|bird/ expect(pattern.test('I have a cat')).toBe(true) expect(pattern.test('I have a dog')).toBe(true) expect(pattern.test('I have a fish')).toBe(false) }) it('should handle backreferences', () => { const pattern = /(\w+)\s+\1/ expect(pattern.test('hello hello')).toBe(true) expect(pattern.test('hello world')).toBe(false) }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/advanced-topics/es-modules/es-modules.test.js
tests/advanced-topics/es-modules/es-modules.test.js
import { describe, it, expect, vi } from 'vitest' describe('ES Modules', () => { // =========================================== // Part 1: Live Bindings // =========================================== describe('Part 1: Live Bindings', () => { describe('ESM Live Bindings vs CommonJS Value Copies', () => { it('should demonstrate CommonJS-style value copy behavior', () => { // CommonJS exports copies of primitive values at require time // Simulating: module.exports = { count, increment, getCount } function createCommonJSModule() { let count = 0 function increment() { count++ } function getCount() { return count } // CommonJS exports a snapshot (copy) of the value return { count, increment, getCount } } const { count, increment, getCount } = createCommonJSModule() expect(count).toBe(0) increment() expect(count).toBe(0) // Still 0! It's a copy from export time expect(getCount()).toBe(1) // Function reads the real internal value }) it('should demonstrate ESM-style live binding behavior', () => { // ESM exports live references - changes are visible to importers // Simulating with an object that acts as a module namespace function createESMModule() { const moduleNamespace = { count: 0, increment() { moduleNamespace.count++ } } return moduleNamespace } const mod = createESMModule() expect(mod.count).toBe(0) mod.increment() expect(mod.count).toBe(1) // Live binding reflects the change! mod.increment() expect(mod.count).toBe(2) // Still updating }) it('should show live bindings work with objects', () => { // Even with objects, ESM bindings are live references const moduleState = { user: null, setUser(u) { moduleState.user = u }, getUser() { return moduleState.user } } expect(moduleState.user).toBe(null) moduleState.setUser({ name: 'Alice' }) expect(moduleState.user).toEqual({ name: 'Alice' }) // Live! moduleState.setUser({ name: 'Bob' }) expect(moduleState.user).toEqual({ name: 'Bob' }) // Updated! }) it('should demonstrate singleton state via live bindings', () => { // All importers share the same module state const sharedModule = (() => { let state = { count: 0 } return { getState: () => state, increment: () => { state.count++ } } })() // Simulate two different "importers" const importer1 = sharedModule const importer2 = sharedModule importer1.increment() expect(importer1.getState().count).toBe(1) expect(importer2.getState().count).toBe(1) // Same state! importer2.increment() expect(importer1.getState().count).toBe(2) // Both see the update expect(importer2.getState().count).toBe(2) }) }) describe('Why Live Bindings Matter', () => { it('should enable proper state management across module boundaries', () => { // Auth module that multiple parts of an app might import const authModule = (() => { let currentUser = null let isAuthenticated = false return { get currentUser() { return currentUser }, get isAuthenticated() { return isAuthenticated }, login(user) { currentUser = user isAuthenticated = true }, logout() { currentUser = null isAuthenticated = false } } })() // Header component checks auth expect(authModule.isAuthenticated).toBe(false) // Login form logs in authModule.login({ name: 'Alice', email: 'alice@test.com' }) // Header immediately sees the change (live binding) expect(authModule.isAuthenticated).toBe(true) expect(authModule.currentUser.name).toBe('Alice') // Logout button logs out authModule.logout() // All components see the change expect(authModule.isAuthenticated).toBe(false) expect(authModule.currentUser).toBe(null) }) }) }) // =========================================== // Part 2: Read-Only Imports // =========================================== describe('Part 2: Read-Only Imports', () => { describe('Imported bindings cannot be reassigned', () => { it('should demonstrate that imports are read-only (simulated with Object.defineProperty)', () => { // ESM imports are read-only - you can't reassign them // We simulate this with a frozen/non-writable property const moduleExports = {} Object.defineProperty(moduleExports, 'count', { value: 0, writable: false, enumerable: true }) expect(moduleExports.count).toBe(0) // Attempting to reassign throws in strict mode expect(() => { 'use strict' moduleExports.count = 10 }).toThrow(TypeError) }) it('should show that const-like behavior applies to all imports', () => { // Even if the source uses `let`, importers can't reassign const createModule = () => { let value = 'original' // let in source module return { get value() { return value }, setValue(v) { value = v } // only module can change it } } const mod = createModule() // Importer can read expect(mod.value).toBe('original') // Importer can call methods that modify (module modifies itself) mod.setValue('updated') expect(mod.value).toBe('updated') // But direct assignment to the binding would fail in real ESM // import { value } from './mod.js' // value = 'hack' // TypeError: Assignment to constant variable }) it('should allow modification of imported object properties', () => { // You can't reassign the import, but you CAN modify object properties const configModule = { config: { theme: 'light', debug: false } } // Can't do: config = newObject (would throw) // But CAN do: config.theme = 'dark' configModule.config.theme = 'dark' expect(configModule.config.theme).toBe('dark') configModule.config.debug = true expect(configModule.config.debug).toBe(true) }) }) }) // =========================================== // Part 3: Circular Dependencies and TDZ // =========================================== describe('Part 3: Circular Dependencies and TDZ', () => { describe('Temporal Dead Zone (TDZ) with const/let', () => { it('should throw ReferenceError when accessing const before initialization', () => { expect(() => { // This simulates what happens in a circular dependency // when module B tries to access a const from module A // before A has finished executing const accessBeforeInit = () => { console.log(value) // Accessing before declaration const value = 'initialized' } accessBeforeInit() }).toThrow(ReferenceError) }) it('should throw ReferenceError when accessing let before initialization', () => { expect(() => { const accessBeforeInit = () => { console.log(value) // TDZ - ReferenceError let value = 'initialized' } accessBeforeInit() }).toThrow(ReferenceError) }) it('should NOT throw with var (hoisted with undefined)', () => { // var is hoisted and initialized to undefined // This is why old circular dependency examples showed 'undefined' let result const accessVarBeforeInit = () => { result = value // undefined, not an error var value = 'initialized' } accessVarBeforeInit() expect(result).toBe(undefined) // var is hoisted as undefined }) }) describe('Circular Dependency Patterns', () => { it('should demonstrate safe circular dependency with deferred access', () => { // Safe pattern: export functions that access values at call time const moduleA = { value: null, getValue: () => moduleA.value, init: () => { moduleA.value = 'A initialized' } } const moduleB = { value: null, getValue: () => moduleB.value, getAValue: () => moduleA.getValue(), // Deferred access init: () => { moduleB.value = 'B initialized' } } // Simulate circular initialization // B tries to access A.value before A.init() runs expect(moduleB.getAValue()).toBe(null) // A not initialized yet moduleA.init() expect(moduleB.getAValue()).toBe('A initialized') // Now it works moduleB.init() expect(moduleB.getValue()).toBe('B initialized') }) it('should show how to restructure to avoid circular deps', () => { // Instead of A importing B and B importing A, // create a shared module C that both import const sharedModule = { sharedConfig: { apiUrl: 'https://api.example.com' }, sharedUtil: (x) => x.toUpperCase() } const moduleA = { config: sharedModule.sharedConfig, formatName: (name) => sharedModule.sharedUtil(name) } const moduleB = { config: sharedModule.sharedConfig, formatTitle: (title) => sharedModule.sharedUtil(title) } // No circular dependency - both depend on shared module expect(moduleA.formatName('alice')).toBe('ALICE') expect(moduleB.formatTitle('hello')).toBe('HELLO') expect(moduleA.config).toBe(moduleB.config) // Same reference }) }) }) // =========================================== // Part 4: Module Singleton Behavior // =========================================== describe('Part 4: Module Singleton Behavior', () => { describe('Module code executes exactly once', () => { it('should only run initialization code once', () => { let initCount = 0 // Simulating a module that runs initialization code const createSingletonModule = (() => { initCount++ // This runs once when module loads return { getValue: () => 'module value', getInitCount: () => initCount } })() // Multiple "imports" all get the same instance const import1 = createSingletonModule const import2 = createSingletonModule const import3 = createSingletonModule expect(initCount).toBe(1) // Only ran once expect(import1).toBe(import2) expect(import2).toBe(import3) }) it('should share state across all importers', () => { const cacheModule = (() => { const cache = new Map() console.log('Cache module initialized') // Runs once return { set: (key, value) => cache.set(key, value), get: (key) => cache.get(key), size: () => cache.size } })() // Different "files" using the cache // file1.js cacheModule.set('user', { id: 1 }) // file2.js - sees the same cache expect(cacheModule.get('user')).toEqual({ id: 1 }) // file3.js - also same cache cacheModule.set('token', 'abc123') expect(cacheModule.size()).toBe(2) }) it('should maintain singleton even with different import styles', () => { // Whether you use named imports, default import, or namespace import, // you get the same module instance const mathModule = (() => { const moduleId = Math.random() // Generated once return { moduleId, PI: 3.14159, add: (a, b) => a + b, default: function Calculator() { this.result = 0 } } })() // import { add, PI } from './math.js' const { add, PI } = mathModule // import * as math from './math.js' const math = mathModule // import Calculator from './math.js' const Calculator = mathModule.default // All reference the same module expect(math.PI).toBe(PI) expect(math.add).toBe(add) expect(math.moduleId).toBe(mathModule.moduleId) }) }) }) // =========================================== // Part 5: Dynamic Imports // =========================================== describe('Part 5: Dynamic Imports', () => { describe('import() returns a Promise', () => { it('should resolve to module namespace object', async () => { // Simulating dynamic import behavior const mockModule = { namedExport: 'named value', anotherExport: 42, default: function DefaultExport() { return 'default' } } const dynamicImport = () => Promise.resolve(mockModule) const module = await dynamicImport() expect(module.namedExport).toBe('named value') expect(module.anotherExport).toBe(42) expect(module.default()).toBe('default') }) it('should allow destructuring named exports', async () => { const mockDateModule = { formatDate: (d) => d.toISOString(), parseDate: (s) => new Date(s) } const dynamicImport = () => Promise.resolve(mockDateModule) // Destructure directly from await const { formatDate, parseDate } = await dynamicImport() expect(typeof formatDate).toBe('function') expect(typeof parseDate).toBe('function') }) it('should access default export via .default property', async () => { const mockModule = { default: class Logger { log(msg) { return `[LOG] ${msg}` } } } const dynamicImport = () => Promise.resolve(mockModule) // Method 1: Destructure with rename const { default: Logger } = await dynamicImport() const logger1 = new Logger() expect(logger1.log('test')).toBe('[LOG] test') // Method 2: Access .default property const module = await dynamicImport() const Logger2 = module.default const logger2 = new Logger2() expect(logger2.log('hello')).toBe('[LOG] hello') }) }) describe('Dynamic Import Use Cases', () => { it('should enable conditional module loading', async () => { const modules = { light: { theme: 'light', bg: '#fff', text: '#000' }, dark: { theme: 'dark', bg: '#000', text: '#fff' } } async function loadTheme(themeName) { // Simulating: const theme = await import(`./themes/${themeName}.js`) return Promise.resolve(modules[themeName]) } const lightTheme = await loadTheme('light') expect(lightTheme.bg).toBe('#fff') const darkTheme = await loadTheme('dark') expect(darkTheme.bg).toBe('#000') }) it('should enable route-based code splitting', async () => { const pageModules = { home: { default: () => 'Home Page Content' }, about: { default: () => 'About Page Content' }, contact: { default: () => 'Contact Page Content' } } async function loadPage(pageName) { // Simulating route-based dynamic import const pageModule = await Promise.resolve(pageModules[pageName]) return pageModule.default } const HomePage = await loadPage('home') expect(HomePage()).toBe('Home Page Content') const AboutPage = await loadPage('about') expect(AboutPage()).toBe('About Page Content') }) it('should enable lazy loading of heavy features', async () => { let chartLibraryLoaded = false const heavyChartLibrary = { Chart: class { constructor(data) { chartLibraryLoaded = true this.data = data } render() { return `Chart with ${this.data.length} points` } } } async function showChart(data) { // Only load chart library when actually needed const { Chart } = await Promise.resolve(heavyChartLibrary) const chart = new Chart(data) return chart.render() } expect(chartLibraryLoaded).toBe(false) // Not loaded yet const result = await showChart([1, 2, 3, 4, 5]) expect(chartLibraryLoaded).toBe(true) // Now loaded expect(result).toBe('Chart with 5 points') }) it('should work with Promise.all for parallel loading', async () => { const modules = { header: { render: () => '<header>Header</header>' }, footer: { render: () => '<footer>Footer</footer>' }, sidebar: { render: () => '<aside>Sidebar</aside>' } } async function loadComponents() { const [header, footer, sidebar] = await Promise.all([ Promise.resolve(modules.header), Promise.resolve(modules.footer), Promise.resolve(modules.sidebar) ]) return { header, footer, sidebar } } const components = await loadComponents() expect(components.header.render()).toBe('<header>Header</header>') expect(components.footer.render()).toBe('<footer>Footer</footer>') expect(components.sidebar.render()).toBe('<aside>Sidebar</aside>') }) }) describe('Error Handling with Dynamic Imports', () => { it('should handle module not found errors', async () => { const loadModule = (name) => { if (name === 'nonexistent') { return Promise.reject(new Error('Module not found')) } return Promise.resolve({ value: 'found' }) } // Successful load const mod = await loadModule('existing') expect(mod.value).toBe('found') // Failed load await expect(loadModule('nonexistent')).rejects.toThrow('Module not found') }) it('should use try-catch for error handling', async () => { const loadModule = () => Promise.reject(new Error('Network error')) let errorHandled = false let fallbackUsed = false try { await loadModule() } catch (error) { errorHandled = true // Use fallback fallbackUsed = true } expect(errorHandled).toBe(true) expect(fallbackUsed).toBe(true) }) }) }) // =========================================== // Part 6: Export and Import Syntax Variations // =========================================== describe('Part 6: Export and Import Syntax Variations', () => { describe('Named Exports', () => { it('should support inline named exports', () => { // export const PI = 3.14159 // export function square(x) { return x * x } // export class Circle { } const moduleExports = {} moduleExports.PI = 3.14159 moduleExports.square = function(x) { return x * x } moduleExports.Circle = class { constructor(radius) { this.radius = radius } area() { return moduleExports.PI * this.radius ** 2 } } expect(moduleExports.PI).toBe(3.14159) expect(moduleExports.square(4)).toBe(16) const circle = new moduleExports.Circle(5) expect(circle.area()).toBeCloseTo(78.54, 1) }) it('should support grouped exports at bottom', () => { // const PI = 3.14159 // function square(x) { return x * x } // export { PI, square } const PI = 3.14159 function square(x) { return x * x } const exports = { PI, square } expect(exports.PI).toBe(3.14159) expect(exports.square(5)).toBe(25) }) it('should support renaming exports with as', () => { // function internalHelper() { } // export { internalHelper as helper } function internalHelper() { return 'helped' } function _privateUtil() { return 'util' } const exports = { helper: internalHelper, publicUtil: _privateUtil } expect(exports.helper()).toBe('helped') expect(exports.publicUtil()).toBe('util') expect(exports.internalHelper).toBe(undefined) // Not exported under original name }) }) describe('Default Exports', () => { it('should support default export of function', () => { // export default function greet(name) { } function greet(name) { return `Hello, ${name}!` } const moduleExports = { default: greet } // import greet from './greet.js' const importedGreet = moduleExports.default expect(importedGreet('World')).toBe('Hello, World!') }) it('should support default export of class', () => { // export default class User { } class User { constructor(name) { this.name = name } greet() { return `Hi, I'm ${this.name}` } } const moduleExports = { default: User } // import User from './user.js' const ImportedUser = moduleExports.default const user = new ImportedUser('Alice') expect(user.greet()).toBe("Hi, I'm Alice") }) it('should support default export of object/value', () => { // export default { name: 'Config', version: '1.0' } const moduleExports = { default: { name: 'Config', version: '1.0.0', debug: false } } // import config from './config.js' const config = moduleExports.default expect(config.name).toBe('Config') expect(config.version).toBe('1.0.0') }) }) describe('Mixed Named and Default Exports', () => { it('should support both default and named exports', () => { // export default function React() { } // export function useState() { } // export function useEffect() { } function React() { return 'React' } function useState(initial) { return [initial, () => {}] } function useEffect(fn) { fn() } const moduleExports = { default: React, useState, useEffect } // import React, { useState, useEffect } from 'react' const ImportedReact = moduleExports.default const { useState: importedUseState, useEffect: importedUseEffect } = moduleExports expect(ImportedReact()).toBe('React') expect(importedUseState(0)).toEqual([0, expect.any(Function)]) }) }) describe('Import Variations', () => { it('should support named imports with exact names', () => { // import { PI, square } from './math.js' const mathModule = { PI: 3.14159, square: (x) => x * x, cube: (x) => x * x * x } const { PI, square } = mathModule expect(PI).toBe(3.14159) expect(square(3)).toBe(9) }) it('should support renaming imports with as', () => { // import { formatDate as formatDateISO } from './date.js' const dateModule = { formatDate: (d) => d.toISOString() } const dateUSModule = { formatDate: (d) => d.toLocaleDateString('en-US') } const { formatDate: formatDateISO } = dateModule const { formatDate: formatDateUS } = dateUSModule const date = new Date('2024-01-15') expect(formatDateISO(date)).toContain('2024-01-15') expect(typeof formatDateUS(date)).toBe('string') }) it('should support namespace imports (import * as)', () => { // import * as math from './math.js' const mathModule = { PI: 3.14159, E: 2.71828, add: (a, b) => a + b, multiply: (a, b) => a * b, default: { name: 'Math Utils' } } // Namespace import gets all exports as properties const math = mathModule expect(math.PI).toBe(3.14159) expect(math.E).toBe(2.71828) expect(math.add(2, 3)).toBe(5) expect(math.multiply(4, 5)).toBe(20) expect(math.default.name).toBe('Math Utils') // default is also accessible }) it('should support side-effect only imports', () => { // import './polyfills.js' // import './analytics.js' let polyfillsLoaded = false let analyticsInitialized = false // Simulating side-effect modules const loadPolyfills = () => { polyfillsLoaded = true } const initAnalytics = () => { analyticsInitialized = true } loadPolyfills() initAnalytics() expect(polyfillsLoaded).toBe(true) expect(analyticsInitialized).toBe(true) }) }) describe('Re-exports (Barrel Files)', () => { it('should support re-exporting named exports', () => { // date.js const dateModule = { formatDate: (d) => d.toISOString(), parseDate: (s) => new Date(s) } // currency.js const currencyModule = { formatCurrency: (n) => `$${n.toFixed(2)}` } // utils/index.js (barrel file) // export { formatDate, parseDate } from './date.js' // export { formatCurrency } from './currency.js' const utilsBarrel = { ...dateModule, ...currencyModule } // Consumer imports from barrel const { formatDate, formatCurrency } = utilsBarrel expect(formatCurrency(19.99)).toBe('$19.99') expect(typeof formatDate(new Date())).toBe('string') }) it('should support re-exporting default as named', () => { // logger.js // export default class Logger { } const loggerModule = { default: class Logger { log(msg) { return msg } } } // utils/index.js // export { default as Logger } from './logger.js' const utilsBarrel = { Logger: loggerModule.default } const { Logger } = utilsBarrel const logger = new Logger() expect(logger.log('test')).toBe('test') }) it('should support re-exporting all (export *)', () => { // math.js exports multiple functions const mathModule = { add: (a, b) => a + b, subtract: (a, b) => a - b, multiply: (a, b) => a * b } // utils/index.js // export * from './math.js' const utilsBarrel = { ...mathModule } expect(utilsBarrel.add(1, 2)).toBe(3) expect(utilsBarrel.subtract(5, 3)).toBe(2) expect(utilsBarrel.multiply(4, 5)).toBe(20) }) }) }) // =========================================== // Part 7: Module Characteristics // =========================================== describe('Part 7: Module Characteristics', () => { describe('Automatic Strict Mode', () => { it('should demonstrate strict mode behaviors', () => { // ES Modules are always in strict mode // Assigning to undeclared variable throws expect(() => { 'use strict' undeclaredVar = 'oops' }).toThrow(ReferenceError) }) it('should prevent duplicate parameters in strict mode', () => { // In strict mode, duplicate parameter names are syntax errors // This would be caught at parse time in a real module: // function f(a, a) { } // SyntaxError // We can test that strict mode is enforced expect(() => { 'use strict' eval('function f(a, a) {}') }).toThrow(SyntaxError) }) it('should make this undefined in functions called without context', () => { 'use strict' function getThis() { return this } expect(getThis()).toBe(undefined) }) }) describe('Module Scope (not global)', () => { it('should keep module variables private by default', () => { // In a module, top-level variables are scoped to the module const createModule = () => { const privateValue = 'secret' const publicValue = 'visible' return { publicValue, getPrivate: () => privateValue } } const mod = createModule() expect(mod.publicValue).toBe('visible') expect(mod.getPrivate()).toBe('secret') expect(mod.privateValue).toBe(undefined) // Not exposed }) it('should not leak var to global scope in modules', () => { // In regular scripts, var leaks to window // In modules, var is module-scoped const createModule = () => { var moduleVar = 'module scoped' return { getVar: () => moduleVar } } const mod = createModule() expect(mod.getVar()).toBe('module scoped') expect(typeof moduleVar).toBe('undefined') // Not in outer scope }) }) describe('Top-level this is undefined', () => { it('should have undefined this at module top level', () => { // In ES Modules, top-level this is undefined // (not window or global) // Regular function in strict mode has undefined this when called without context function getThisInStrictMode() { 'use strict' return this } // Called without context, this is undefined (like module top-level) expect(getThisInStrictMode()).toBe(undefined) // Arrow functions capture this from enclosing scope // In a real ES module, this would be undefined at the top level const arrowThis = (() => this)() // Note: In test environment, the outer `this` may not be undefined // but in a real ES module file, top-level `this` IS undefined // This test demonstrates the concept via strict mode function }) }) describe('Import Hoisting', () => { it('should demonstrate that imports are hoisted', () => { // In ES Modules, import declarations are hoisted // The imported bindings are available throughout the module // This would work in a real module: // console.log(helper()) // Works! Imports are hoisted // import { helper } from './utils.js' // We simulate by showing the concept const moduleCode = () => { // Imports are processed first, before any code runs const imports = { helper: () => 'helped' } // Then code runs, with imports already available const result = imports.helper() // Can use before "import line" return result } expect(moduleCode()).toBe('helped') }) }) }) // =========================================== // Part 8: Common Mistakes // ===========================================
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
true
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/advanced-topics/algorithms-big-o/algorithms-big-o.test.js
tests/advanced-topics/algorithms-big-o/algorithms-big-o.test.js
import { describe, it, expect } from 'vitest' // ============================================ // SEARCHING ALGORITHMS // ============================================ // Linear Search - O(n) function linearSearch(arr, target) { for (let i = 0; i < arr.length; i++) { if (arr[i] === target) return i } return -1 } // Binary Search - O(log n) function binarySearch(arr, target) { let left = 0 let right = arr.length - 1 while (left <= right) { const mid = Math.floor((left + right) / 2) if (arr[mid] === target) return mid if (arr[mid] < target) left = mid + 1 else right = mid - 1 } return -1 } // ============================================ // SORTING ALGORITHMS // ============================================ // Bubble Sort - O(n²) average/worst, O(n) best with early termination function bubbleSort(arr) { const result = [...arr] const n = result.length for (let i = 0; i < n; i++) { let swapped = false for (let j = 0; j < n - i - 1; j++) { if (result[j] > result[j + 1]) { [result[j], result[j + 1]] = [result[j + 1], result[j]] swapped = true } } // If no swaps occurred, array is sorted if (!swapped) break } return result } // Merge Sort - O(n log n) function mergeSort(arr) { if (arr.length <= 1) return arr const mid = Math.floor(arr.length / 2) const left = mergeSort(arr.slice(0, mid)) const right = mergeSort(arr.slice(mid)) return merge(left, right) } function merge(left, right) { const result = [] let i = 0 let j = 0 while (i < left.length && j < right.length) { if (left[i] <= right[j]) { result.push(left[i]) i++ } else { result.push(right[j]) j++ } } return result.concat(left.slice(i)).concat(right.slice(j)) } // ============================================ // INTERVIEW PATTERNS // ============================================ // Two Pointers - Find pair that sums to target function twoSum(arr, target) { let left = 0 let right = arr.length - 1 while (left < right) { const sum = arr[left] + arr[right] if (sum === target) return [left, right] if (sum < target) left++ else right-- } return null } // Sliding Window - Maximum sum of k consecutive elements function maxSumSubarray(arr, k) { if (arr.length < k) return null let windowSum = 0 for (let i = 0; i < k; i++) { windowSum += arr[i] } let maxSum = windowSum for (let i = k; i < arr.length; i++) { windowSum = windowSum - arr[i - k] + arr[i] maxSum = Math.max(maxSum, windowSum) } return maxSum } // Frequency Counter - Check anagrams function isAnagram(str1, str2) { if (str1.length !== str2.length) return false const freq = {} for (const char of str1) { freq[char] = (freq[char] || 0) + 1 } for (const char of str2) { if (!freq[char]) return false freq[char]-- } return true } // Has Duplicates - O(n) with Set function hasDuplicates(arr) { const seen = new Set() for (const item of arr) { if (seen.has(item)) return true seen.add(item) } return false } // Longest Unique Substring - Sliding Window function longestUniqueSubstring(s) { const seen = new Set() let maxLen = 0 let left = 0 for (let right = 0; right < s.length; right++) { while (seen.has(s[right])) { seen.delete(s[left]) left++ } seen.add(s[right]) maxLen = Math.max(maxLen, right - left + 1) } return maxLen } // ============================================ // TESTS // ============================================ describe('Algorithms & Big O', () => { describe('Searching Algorithms', () => { describe('Linear Search', () => { it('should find element at beginning', () => { expect(linearSearch([1, 2, 3, 4, 5], 1)).toBe(0) }) it('should find element at end', () => { expect(linearSearch([1, 2, 3, 4, 5], 5)).toBe(4) }) it('should find element in middle', () => { expect(linearSearch([3, 7, 1, 9, 4], 9)).toBe(3) }) it('should return -1 when element not found', () => { expect(linearSearch([1, 2, 3, 4, 5], 10)).toBe(-1) }) it('should handle empty array', () => { expect(linearSearch([], 1)).toBe(-1) }) it('should find first occurrence of duplicates', () => { expect(linearSearch([1, 2, 3, 2, 5], 2)).toBe(1) }) }) describe('Binary Search', () => { it('should find element in sorted array', () => { expect(binarySearch([1, 3, 5, 7, 9, 11, 13], 9)).toBe(4) }) it('should find first element', () => { expect(binarySearch([1, 3, 5, 7, 9], 1)).toBe(0) }) it('should find last element', () => { expect(binarySearch([1, 3, 5, 7, 9], 9)).toBe(4) }) it('should return -1 when element not found', () => { expect(binarySearch([1, 3, 5, 7, 9], 6)).toBe(-1) }) it('should handle single element array - found', () => { expect(binarySearch([5], 5)).toBe(0) }) it('should handle single element array - not found', () => { expect(binarySearch([5], 3)).toBe(-1) }) it('should handle empty array', () => { expect(binarySearch([], 5)).toBe(-1) }) it('should work with large sorted array', () => { const arr = Array.from({ length: 1000 }, (_, i) => i * 2) // [0, 2, 4, ..., 1998] expect(binarySearch(arr, 500)).toBe(250) expect(binarySearch(arr, 501)).toBe(-1) }) }) }) describe('Sorting Algorithms', () => { describe('Bubble Sort', () => { it('should sort array in ascending order', () => { expect(bubbleSort([5, 3, 8, 4, 2])).toEqual([2, 3, 4, 5, 8]) }) it('should handle already sorted array', () => { expect(bubbleSort([1, 2, 3, 4, 5])).toEqual([1, 2, 3, 4, 5]) }) it('should handle reverse sorted array', () => { expect(bubbleSort([5, 4, 3, 2, 1])).toEqual([1, 2, 3, 4, 5]) }) it('should handle array with duplicates', () => { expect(bubbleSort([3, 1, 4, 1, 5, 9, 2, 6])).toEqual([1, 1, 2, 3, 4, 5, 6, 9]) }) it('should handle single element', () => { expect(bubbleSort([42])).toEqual([42]) }) it('should handle empty array', () => { expect(bubbleSort([])).toEqual([]) }) it('should not mutate original array', () => { const original = [3, 1, 4, 1, 5] bubbleSort(original) expect(original).toEqual([3, 1, 4, 1, 5]) }) it('should handle negative numbers', () => { expect(bubbleSort([-3, -1, -4, -1, -5])).toEqual([-5, -4, -3, -1, -1]) }) it('should terminate early on already sorted array (O(n) best case)', () => { // This test verifies the early termination optimization works // On an already sorted array, only one pass is needed const sorted = [1, 2, 3, 4, 5] expect(bubbleSort(sorted)).toEqual([1, 2, 3, 4, 5]) }) }) describe('Merge Sort', () => { it('should sort array in ascending order', () => { expect(mergeSort([38, 27, 43, 3, 9, 82, 10])).toEqual([3, 9, 10, 27, 38, 43, 82]) }) it('should handle already sorted array', () => { expect(mergeSort([1, 2, 3, 4, 5])).toEqual([1, 2, 3, 4, 5]) }) it('should handle reverse sorted array', () => { expect(mergeSort([5, 4, 3, 2, 1])).toEqual([1, 2, 3, 4, 5]) }) it('should handle array with duplicates', () => { expect(mergeSort([3, 1, 4, 1, 5, 9, 2, 6])).toEqual([1, 1, 2, 3, 4, 5, 6, 9]) }) it('should handle single element', () => { expect(mergeSort([42])).toEqual([42]) }) it('should handle empty array', () => { expect(mergeSort([])).toEqual([]) }) it('should handle negative numbers', () => { expect(mergeSort([-3, 1, -4, 1, -5, 9])).toEqual([-5, -4, -3, 1, 1, 9]) }) it('should maintain stability for equal elements', () => { // Merge sort is stable - equal elements maintain relative order const result = mergeSort([3, 1, 2, 1]) expect(result).toEqual([1, 1, 2, 3]) }) }) }) describe('Interview Patterns', () => { describe('Two Pointers - Two Sum', () => { it('should find pair that sums to target', () => { expect(twoSum([1, 3, 5, 7, 9], 12)).toEqual([1, 4]) // 3 + 9 = 12 }) it('should find pair at extremes', () => { expect(twoSum([1, 2, 3, 4, 5], 6)).toEqual([0, 4]) // 1 + 5 = 6 }) it('should find adjacent pair', () => { expect(twoSum([1, 2, 3, 4, 5], 9)).toEqual([3, 4]) // 4 + 5 = 9 }) it('should return null when no pair exists', () => { expect(twoSum([1, 2, 3, 4, 5], 100)).toBe(null) }) it('should handle minimum size array', () => { expect(twoSum([3, 7], 10)).toEqual([0, 1]) }) it('should return null for single element', () => { expect(twoSum([5], 10)).toBe(null) }) }) describe('Sliding Window - Max Sum Subarray', () => { it('should find maximum sum of k consecutive elements', () => { expect(maxSumSubarray([2, 1, 5, 1, 3, 2], 3)).toBe(9) // 5 + 1 + 3 }) it('should handle window at beginning', () => { expect(maxSumSubarray([9, 1, 1, 1, 1, 1], 2)).toBe(10) // 9 + 1 }) it('should handle window at end', () => { expect(maxSumSubarray([1, 1, 1, 1, 9, 8], 2)).toBe(17) // 9 + 8 }) it('should handle k equal to array length', () => { expect(maxSumSubarray([1, 2, 3], 3)).toBe(6) }) it('should return null if array shorter than k', () => { expect(maxSumSubarray([1, 2], 3)).toBe(null) }) it('should handle negative numbers', () => { expect(maxSumSubarray([-1, -2, 5, 6, -3], 2)).toBe(11) // 5 + 6 }) it('should handle all negative numbers', () => { expect(maxSumSubarray([-5, -3, -8, -2], 2)).toBe(-8) // -5 + -3 = -8 is max }) }) describe('Frequency Counter - Anagram Check', () => { it('should return true for valid anagrams', () => { expect(isAnagram('listen', 'silent')).toBe(true) }) it('should return true for same string', () => { expect(isAnagram('hello', 'hello')).toBe(true) }) it('should return false for different lengths', () => { expect(isAnagram('hello', 'helloo')).toBe(false) }) it('should return false for non-anagrams', () => { expect(isAnagram('hello', 'world')).toBe(false) }) it('should handle empty strings', () => { expect(isAnagram('', '')).toBe(true) }) it('should be case sensitive', () => { expect(isAnagram('Listen', 'Silent')).toBe(false) }) it('should handle repeated characters', () => { expect(isAnagram('aab', 'baa')).toBe(true) expect(isAnagram('aab', 'bba')).toBe(false) }) it('should handle single characters', () => { expect(isAnagram('a', 'a')).toBe(true) expect(isAnagram('a', 'b')).toBe(false) }) }) describe('Has Duplicates', () => { it('should return true when duplicates exist', () => { expect(hasDuplicates([1, 2, 3, 2, 5])).toBe(true) }) it('should return false when no duplicates', () => { expect(hasDuplicates([1, 2, 3, 4, 5])).toBe(false) }) it('should handle empty array', () => { expect(hasDuplicates([])).toBe(false) }) it('should handle single element', () => { expect(hasDuplicates([1])).toBe(false) }) it('should detect duplicates at beginning', () => { expect(hasDuplicates([1, 1, 2, 3, 4])).toBe(true) }) it('should detect duplicates at end', () => { expect(hasDuplicates([1, 2, 3, 4, 4])).toBe(true) }) it('should work with strings', () => { expect(hasDuplicates(['a', 'b', 'c', 'a'])).toBe(true) expect(hasDuplicates(['a', 'b', 'c', 'd'])).toBe(false) }) }) describe('Longest Unique Substring', () => { it('should find longest substring without repeating characters', () => { expect(longestUniqueSubstring('abcabcbb')).toBe(3) // "abc" }) it('should handle all same characters', () => { expect(longestUniqueSubstring('bbbbb')).toBe(1) }) it('should handle unique characters at end', () => { expect(longestUniqueSubstring('pwwkew')).toBe(3) // "wke" }) it('should handle empty string', () => { expect(longestUniqueSubstring('')).toBe(0) }) it('should handle single character', () => { expect(longestUniqueSubstring('a')).toBe(1) }) it('should handle all unique characters', () => { expect(longestUniqueSubstring('abcdef')).toBe(6) }) it('should handle repeating pattern', () => { expect(longestUniqueSubstring('abab')).toBe(2) }) }) }) describe('Big O Concepts', () => { describe('Array operations complexity', () => { it('should demonstrate O(1) array access', () => { const arr = [1, 2, 3, 4, 5] // Direct index access is O(1) expect(arr[0]).toBe(1) expect(arr[4]).toBe(5) expect(arr[2]).toBe(3) }) it('should demonstrate O(1) push and pop', () => { const arr = [1, 2, 3] arr.push(4) // O(1) expect(arr).toEqual([1, 2, 3, 4]) const popped = arr.pop() // O(1) expect(popped).toBe(4) expect(arr).toEqual([1, 2, 3]) }) it('should demonstrate O(n) shift and unshift', () => { const arr = [1, 2, 3] // These are O(n) because they require re-indexing all elements arr.unshift(0) expect(arr).toEqual([0, 1, 2, 3]) const shifted = arr.shift() expect(shifted).toBe(0) expect(arr).toEqual([1, 2, 3]) }) }) describe('Set vs Array for lookups', () => { it('should demonstrate Set.has() is faster than Array.includes() for repeated lookups', () => { const arr = Array.from({ length: 1000 }, (_, i) => i) const set = new Set(arr) // Both find the element, but Set.has() is O(1) vs Array.includes() O(n) expect(arr.includes(500)).toBe(true) expect(set.has(500)).toBe(true) expect(arr.includes(999)).toBe(true) expect(set.has(999)).toBe(true) expect(arr.includes(1001)).toBe(false) expect(set.has(1001)).toBe(false) }) }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/advanced-topics/design-patterns/design-patterns.test.js
tests/advanced-topics/design-patterns/design-patterns.test.js
import { describe, it, expect, vi, beforeEach } from 'vitest' describe('Design Patterns', () => { describe('Module Pattern', () => { it('should encapsulate private state using closures', () => { // IIFE-based module pattern const Counter = (function () { let count = 0 // Private variable return { increment() { count++ return count }, decrement() { count-- return count }, getCount() { return count } } })() expect(Counter.getCount()).toBe(0) expect(Counter.increment()).toBe(1) expect(Counter.increment()).toBe(2) expect(Counter.decrement()).toBe(1) // Private variable is not accessible expect(Counter.count).toBeUndefined() }) it('should only expose public methods', () => { const Module = (function () { // Private function function privateHelper(value) { return value * 2 } // Public API return { publicMethod(value) { return privateHelper(value) + 10 } } })() expect(Module.publicMethod(5)).toBe(20) // (5 * 2) + 10 expect(Module.privateHelper).toBeUndefined() }) }) describe('Singleton Pattern', () => { it('should return the same instance when created multiple times', () => { let instance = null class Singleton { constructor() { if (instance) { return instance } this.timestamp = Date.now() instance = this } } const instance1 = new Singleton() const instance2 = new Singleton() expect(instance1).toBe(instance2) expect(instance1.timestamp).toBe(instance2.timestamp) }) it('should prevent modification with Object.freeze', () => { const Config = { apiUrl: 'https://api.example.com', timeout: 5000 } Object.freeze(Config) // In strict mode (which Vitest uses), this throws an error expect(() => { Config.apiUrl = 'https://evil.com' }).toThrow(TypeError) expect(() => { Config.newProperty = 'test' }).toThrow(TypeError) // Original values remain unchanged expect(Config.apiUrl).toBe('https://api.example.com') expect(Config.newProperty).toBeUndefined() }) it('should demonstrate that ES modules behave like singletons', () => { // Simulating ES module behavior const createModule = () => { const cache = new Map() return function getModule(name) { if (!cache.has(name)) { cache.set(name, { name, timestamp: Date.now() }) } return cache.get(name) } } const requireModule = createModule() const module1 = requireModule('config') const module2 = requireModule('config') expect(module1).toBe(module2) }) }) describe('Factory Pattern', () => { it('should create objects without using the new keyword', () => { function createUser(name, role) { return { name, role, greet() { return `Hi, I'm ${this.name}` } } } const user = createUser('Alice', 'admin') expect(user.name).toBe('Alice') expect(user.role).toBe('admin') expect(user.greet()).toBe("Hi, I'm Alice") }) it('should return different object instances', () => { function createProduct(name) { return { name, id: Math.random() } } const product1 = createProduct('Widget') const product2 = createProduct('Widget') expect(product1).not.toBe(product2) expect(product1.id).not.toBe(product2.id) }) it('should create different types based on input', () => { function createNotification(type, message) { const base = { message, timestamp: Date.now() } switch (type) { case 'error': return { ...base, type: 'error', color: 'red', icon: '❌' } case 'success': return { ...base, type: 'success', color: 'green', icon: '✓' } case 'warning': return { ...base, type: 'warning', color: 'yellow', icon: '⚠' } default: return { ...base, type: 'info', color: 'blue', icon: 'ℹ' } } } const error = createNotification('error', 'Failed!') const success = createNotification('success', 'Done!') const info = createNotification('unknown', 'Info') expect(error.color).toBe('red') expect(success.color).toBe('green') expect(info.type).toBe('info') }) }) describe('Observer Pattern', () => { let observable beforeEach(() => { observable = { observers: [], subscribe(fn) { this.observers.push(fn) return () => { this.observers = this.observers.filter((o) => o !== fn) } }, notify(data) { this.observers.forEach((fn) => fn(data)) } } }) it('should allow subscribing to events', () => { const callback = vi.fn() observable.subscribe(callback) observable.notify('test data') expect(callback).toHaveBeenCalledWith('test data') expect(callback).toHaveBeenCalledTimes(1) }) it('should notify all subscribers', () => { const callback1 = vi.fn() const callback2 = vi.fn() const callback3 = vi.fn() observable.subscribe(callback1) observable.subscribe(callback2) observable.subscribe(callback3) observable.notify('event data') expect(callback1).toHaveBeenCalledWith('event data') expect(callback2).toHaveBeenCalledWith('event data') expect(callback3).toHaveBeenCalledWith('event data') }) it('should allow unsubscribing', () => { const callback = vi.fn() const unsubscribe = observable.subscribe(callback) observable.notify('first') expect(callback).toHaveBeenCalledTimes(1) unsubscribe() observable.notify('second') expect(callback).toHaveBeenCalledTimes(1) // Still 1, not called again }) it('should handle multiple subscriptions and unsubscriptions', () => { const callback1 = vi.fn() const callback2 = vi.fn() const unsub1 = observable.subscribe(callback1) observable.subscribe(callback2) observable.notify('test') expect(callback1).toHaveBeenCalledTimes(1) expect(callback2).toHaveBeenCalledTimes(1) unsub1() observable.notify('test2') expect(callback1).toHaveBeenCalledTimes(1) // Not called again expect(callback2).toHaveBeenCalledTimes(2) // Called again }) }) describe('Proxy Pattern', () => { it('should intercept property access (get)', () => { const target = { name: 'Alice', age: 25 } const accessLog = [] const proxy = new Proxy(target, { get(obj, prop) { accessLog.push(prop) return obj[prop] } }) expect(proxy.name).toBe('Alice') expect(proxy.age).toBe(25) expect(accessLog).toEqual(['name', 'age']) }) it('should intercept property assignment (set)', () => { const target = { count: 0 } const setLog = [] const proxy = new Proxy(target, { set(obj, prop, value) { setLog.push({ prop, value }) obj[prop] = value return true } }) proxy.count = 5 proxy.newProp = 'hello' expect(target.count).toBe(5) expect(target.newProp).toBe('hello') expect(setLog).toEqual([ { prop: 'count', value: 5 }, { prop: 'newProp', value: 'hello' } ]) }) it('should validate values on set', () => { const user = { name: 'Alice', age: 25 } const validatedUser = new Proxy(user, { set(obj, prop, value) { if (prop === 'age') { if (typeof value !== 'number') { throw new TypeError('Age must be a number') } if (value < 0 || value > 150) { throw new RangeError('Age must be between 0 and 150') } } obj[prop] = value return true } }) // Valid assignment validatedUser.age = 30 expect(validatedUser.age).toBe(30) // Invalid assignments expect(() => { validatedUser.age = 'thirty' }).toThrow(TypeError) expect(() => { validatedUser.age = -5 }).toThrow(RangeError) expect(() => { validatedUser.age = 200 }).toThrow(RangeError) }) it('should provide default values for missing properties', () => { const target = { name: 'Alice' } const withDefaults = new Proxy(target, { get(obj, prop) { if (prop in obj) { return obj[prop] } return `Default value for ${prop}` } }) expect(withDefaults.name).toBe('Alice') expect(withDefaults.missing).toBe('Default value for missing') }) }) describe('Decorator Pattern', () => { it('should add new methods to objects', () => { const createBird = (name) => ({ name, chirp() { return `${this.name} says chirp!` } }) const withFlying = (bird) => ({ ...bird, fly() { return `${bird.name} is flying!` } }) const sparrow = withFlying(createBird('Sparrow')) expect(sparrow.chirp()).toBe('Sparrow says chirp!') expect(sparrow.fly()).toBe('Sparrow is flying!') }) it('should preserve original object properties', () => { const original = { name: 'Widget', price: 100, getInfo() { return `${this.name}: $${this.price}` } } const withDiscount = (product, discountPercent) => ({ ...product, discount: discountPercent, getDiscountedPrice() { return product.price * (1 - discountPercent / 100) } }) const discounted = withDiscount(original, 20) expect(discounted.name).toBe('Widget') expect(discounted.price).toBe(100) expect(discounted.discount).toBe(20) expect(discounted.getDiscountedPrice()).toBe(80) }) it('should allow composing multiple decorators', () => { const createCharacter = (name) => ({ name, abilities: [], describe() { return `${this.name} can: ${this.abilities.join(', ') || 'nothing yet'}` } }) const withSwimming = (character) => ({ ...character, abilities: [...character.abilities, 'swim'], swim() { return `${character.name} swims!` } }) const withFlying = (character) => ({ ...character, abilities: [...character.abilities, 'fly'], fly() { return `${character.name} flies!` } }) const withFireBreathing = (character) => ({ ...character, abilities: [...character.abilities, 'breathe fire'], breatheFire() { return `${character.name} breathes fire!` } }) // Compose decorators const dragon = withFireBreathing(withFlying(createCharacter('Dragon'))) expect(dragon.abilities).toEqual(['fly', 'breathe fire']) expect(dragon.fly()).toBe('Dragon flies!') expect(dragon.breatheFire()).toBe('Dragon breathes fire!') // Different composition const duck = withSwimming(withFlying(createCharacter('Duck'))) expect(duck.abilities).toEqual(['fly', 'swim']) expect(duck.fly()).toBe('Duck flies!') expect(duck.swim()).toBe('Duck swims!') }) it('should work with function decorators', () => { // Logging decorator const withLogging = (fn) => { return function (...args) { const result = fn.apply(this, args) return result } } // Timing decorator const withTiming = (fn) => { return function (...args) { const start = Date.now() const result = fn.apply(this, args) const end = Date.now() return { result, duration: end - start } } } const add = (a, b) => a + b const timedAdd = withTiming(withLogging(add)) const output = timedAdd(2, 3) expect(output.result).toBe(5) expect(typeof output.duration).toBe('number') expect(output.duration).toBeGreaterThanOrEqual(0) }) it('should implement memoization decorator', () => { const withMemoization = (fn) => { const cache = new Map() return function (...args) { const key = JSON.stringify(args) if (cache.has(key)) { return { value: cache.get(key), cached: true } } const result = fn.apply(this, args) cache.set(key, result) return { value: result, cached: false } } } let callCount = 0 const expensiveOperation = (n) => { callCount++ return n * n } const memoized = withMemoization(expensiveOperation) const result1 = memoized(5) expect(result1).toEqual({ value: 25, cached: false }) expect(callCount).toBe(1) const result2 = memoized(5) expect(result2).toEqual({ value: 25, cached: true }) expect(callCount).toBe(1) // Not called again const result3 = memoized(10) expect(result3).toEqual({ value: 100, cached: false }) expect(callCount).toBe(2) // Called for new argument }) }) describe('Pattern Integration', () => { it('should combine Observer and Singleton for a global event bus', () => { // Singleton event bus using module pattern const EventBus = (function () { const events = new Map() return Object.freeze({ on(event, callback) { if (!events.has(event)) { events.set(event, []) } events.get(event).push(callback) }, off(event, callback) { if (events.has(event)) { const callbacks = events.get(event).filter((cb) => cb !== callback) events.set(event, callbacks) } }, emit(event, data) { if (events.has(event)) { events.get(event).forEach((callback) => callback(data)) } } }) })() const handler1 = vi.fn() const handler2 = vi.fn() EventBus.on('user:login', handler1) EventBus.on('user:login', handler2) EventBus.emit('user:login', { userId: 123 }) expect(handler1).toHaveBeenCalledWith({ userId: 123 }) expect(handler2).toHaveBeenCalledWith({ userId: 123 }) EventBus.off('user:login', handler1) EventBus.emit('user:login', { userId: 456 }) expect(handler1).toHaveBeenCalledTimes(1) expect(handler2).toHaveBeenCalledTimes(2) }) it('should combine Factory and Decorator patterns', () => { // Factory for creating base enemies const createEnemy = (type) => { const enemies = { goblin: { name: 'Goblin', health: 50, damage: 10 }, orc: { name: 'Orc', health: 100, damage: 20 }, troll: { name: 'Troll', health: 200, damage: 30 } } return { ...enemies[type] } } // Decorators for enemy modifiers const withArmor = (enemy, armor) => ({ ...enemy, armor, takeDamage(amount) { return Math.max(0, amount - armor) } }) const withPoison = (enemy) => ({ ...enemy, poisonDamage: 5, attack() { return `${enemy.name} attacks for ${enemy.damage} + ${this.poisonDamage} poison!` } }) // Create decorated enemies const armoredOrc = withArmor(createEnemy('orc'), 15) const poisonGoblin = withPoison(createEnemy('goblin')) const armoredPoisonTroll = withPoison(withArmor(createEnemy('troll'), 25)) expect(armoredOrc.armor).toBe(15) expect(armoredOrc.takeDamage(30)).toBe(15) expect(poisonGoblin.attack()).toBe('Goblin attacks for 10 + 5 poison!') expect(armoredPoisonTroll.armor).toBe(25) expect(armoredPoisonTroll.attack()).toBe('Troll attacks for 30 + 5 poison!') }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/advanced-topics/error-handling/error-handling.test.js
tests/advanced-topics/error-handling/error-handling.test.js
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' describe('Error Handling', () => { // ============================================================ // TRY/CATCH/FINALLY BASICS // ============================================================ describe('try/catch/finally Basics', () => { it('should catch errors thrown in try block', () => { // From: The try block contains code that might throw an error let caught = false try { throw new Error('Test error') } catch (error) { caught = true expect(error.message).toBe('Test error') } expect(caught).toBe(true) }) it('should skip catch block if no error occurs', () => { const order = [] try { order.push('try') } catch (error) { order.push('catch') } expect(order).toEqual(['try']) }) it('should stop try block execution at the error', () => { // From: If an error occurs, execution immediately jumps to the catch block const order = [] try { order.push('before error') throw new Error('stop') order.push('after error') // Never runs } catch (error) { order.push('catch') } expect(order).toEqual(['before error', 'catch']) }) it('should always run finally block - success case', () => { // From: The finally block always runs const order = [] try { order.push('try') } catch (error) { order.push('catch') } finally { order.push('finally') } expect(order).toEqual(['try', 'finally']) }) it('should always run finally block - error case', () => { const order = [] try { order.push('try') throw new Error('test') } catch (error) { order.push('catch') } finally { order.push('finally') } expect(order).toEqual(['try', 'catch', 'finally']) }) it('should run finally even with return in try', () => { // From: finally runs even with return const order = [] function example() { try { order.push('try') return 'from try' } finally { order.push('finally') } } const result = example() expect(result).toBe('from try') expect(order).toEqual(['try', 'finally']) }) it('should run finally even with return in catch', () => { const order = [] function example() { try { throw new Error('test') } catch (error) { order.push('catch') return 'from catch' } finally { order.push('finally') } } const result = example() expect(result).toBe('from catch') expect(order).toEqual(['catch', 'finally']) }) it('should support optional catch binding (ES2019+)', () => { // From: Optional catch binding let result = 'default' try { JSON.parse('{ invalid json }') } catch { // No error parameter needed result = 'caught' } expect(result).toBe('caught') }) }) // ============================================================ // THE ERROR OBJECT // ============================================================ describe('The Error Object', () => { it('should have name, message, and stack properties', () => { // From: Error Properties table try { undefinedVariable } catch (error) { expect(error.name).toBe('ReferenceError') expect(error.message).toContain('undefinedVariable') expect(typeof error.stack).toBe('string') expect(error.stack).toContain('ReferenceError') } }) it('should convert error to string as "name: message"', () => { const error = new Error('Something went wrong') expect(String(error)).toBe('Error: Something went wrong') }) it('should support error cause (ES2022+)', () => { // From: Error chaining with cause const originalError = new Error('Original error') const wrappedError = new Error('Wrapped error', { cause: originalError }) expect(wrappedError.message).toBe('Wrapped error') expect(wrappedError.cause).toBe(originalError) expect(wrappedError.cause.message).toBe('Original error') }) }) // ============================================================ // BUILT-IN ERROR TYPES // ============================================================ describe('Built-in Error Types', () => { it('should throw TypeError for wrong type operations', () => { // From: TypeError - calling method on null expect(() => { const obj = null obj.method() }).toThrow(TypeError) // Calling non-function expect(() => { const notAFunction = 42 notAFunction() }).toThrow(TypeError) }) it('should throw ReferenceError for undefined variables', () => { // From: ReferenceError - using undefined variable expect(() => { undefinedVariableName }).toThrow(ReferenceError) }) it('should throw SyntaxError for invalid JSON', () => { // From: SyntaxError - invalid JSON expect(() => { JSON.parse('{ name: "John" }') // Missing quotes around key }).toThrow(SyntaxError) expect(() => { JSON.parse('') // Empty string }).toThrow(SyntaxError) }) it('should throw RangeError for out-of-range values', () => { // From: RangeError - value out of range expect(() => { new Array(-1) }).toThrow(RangeError) expect(() => { (1.5).toFixed(200) // Max is 100 }).toThrow(RangeError) // From: 'x'.repeat(Infinity) example expect(() => { 'x'.repeat(Infinity) }).toThrow(RangeError) }) it('should use optional chaining to avoid TypeError', () => { // From: Fix for TypeError - Check if values exist before using them const user = null // Without optional chaining - throws TypeError expect(() => { user.name }).toThrow(TypeError) // With optional chaining - returns undefined (no error) expect(user?.name).toBeUndefined() }) it('should throw URIError for bad URI encoding', () => { // From: URIError - bad URI encoding expect(() => { decodeURIComponent('%') }).toThrow(URIError) }) it('should throw AggregateError when all promises reject', async () => { // From: AggregateError - Promise.any() all reject await expect( Promise.any([ Promise.reject(new Error('Error 1')), Promise.reject(new Error('Error 2')), Promise.reject(new Error('Error 3')) ]) ).rejects.toThrow(AggregateError) try { await Promise.any([ Promise.reject(new Error('Error 1')), Promise.reject(new Error('Error 2')) ]) } catch (error) { expect(error.name).toBe('AggregateError') expect(error.errors).toHaveLength(2) } }) }) // ============================================================ // THE THROW STATEMENT // ============================================================ describe('The throw Statement', () => { it('should throw and catch custom errors', () => { // From: The throw statement lets you create your own errors function divide(a, b) { if (b === 0) { throw new Error('Cannot divide by zero') } return a / b } expect(divide(10, 2)).toBe(5) expect(() => divide(10, 0)).toThrow('Cannot divide by zero') }) it('should demonstrate throwing non-Error types (bad practice)', () => { // From: Always Throw Error Objects - BAD examples // These all work but lack stack traces for debugging // Throwing a string - no stack trace try { throw 'Something went wrong' } catch (error) { expect(typeof error).toBe('string') expect(error).toBe('Something went wrong') expect(error.stack).toBeUndefined() } // Throwing a number - no stack trace try { throw 404 } catch (error) { expect(typeof error).toBe('number') expect(error).toBe(404) expect(error.stack).toBeUndefined() } // Throwing an object - no stack trace try { throw { message: 'Error' } } catch (error) { expect(typeof error).toBe('object') expect(error.message).toBe('Error') expect(error.stack).toBeUndefined() } }) it('should throw errors with proper type', () => { // From: Always throw Error objects function validateAge(age) { if (typeof age !== 'number') { throw new TypeError(`Expected number but got ${typeof age}`) } if (age < 0 || age > 150) { throw new RangeError(`Age must be between 0 and 150, got ${age}`) } return true } expect(validateAge(25)).toBe(true) expect(() => validateAge('25')).toThrow(TypeError) expect(() => validateAge(-5)).toThrow(RangeError) }) it('should include stack trace when throwing Error objects', () => { try { throw new Error('Test') } catch (error) { expect(error.stack).toBeDefined() expect(error.stack).toContain('Error: Test') } }) it('should create meaningful error messages with context', () => { // From: Creating Meaningful Error Messages // Specific error message with details const email = 'invalid-email' const emailError = new Error(`Email address is invalid: missing @ symbol`) expect(emailError.message).toBe('Email address is invalid: missing @ symbol') // TypeError with actual type in message const value = 42 const typeError = new TypeError(`Expected string but got ${typeof value}`) expect(typeError.message).toBe('Expected string but got number') expect(typeError.name).toBe('TypeError') // RangeError with actual value in message const age = 200 const rangeError = new RangeError(`Age must be between 0 and 150, got ${age}`) expect(rangeError.message).toBe('Age must be between 0 and 150, got 200') expect(rangeError.name).toBe('RangeError') }) }) // ============================================================ // CUSTOM ERROR CLASSES // ============================================================ describe('Custom Error Classes', () => { it('should create custom error classes', () => { // From: Custom error classes for better categorization class ValidationError extends Error { constructor(message) { super(message) this.name = 'ValidationError' } } const error = new ValidationError('Invalid email') expect(error.name).toBe('ValidationError') expect(error.message).toBe('Invalid email') expect(error instanceof ValidationError).toBe(true) expect(error instanceof Error).toBe(true) }) it('should support auto-naming pattern', () => { // From: The Auto-Naming Pattern class AppError extends Error { constructor(message, options) { super(message, options) this.name = this.constructor.name } } class ValidationError extends AppError {} class NetworkError extends AppError {} const validationError = new ValidationError('Bad input') const networkError = new NetworkError('Connection failed') expect(validationError.name).toBe('ValidationError') expect(networkError.name).toBe('NetworkError') }) it('should add custom properties to error classes', () => { class NetworkError extends Error { constructor(message, statusCode) { super(message) this.name = 'NetworkError' this.statusCode = statusCode } } const error = new NetworkError('Not found', 404) expect(error.message).toBe('Not found') expect(error.statusCode).toBe(404) }) it('should use instanceof for error type checking', () => { // From: Using instanceof for Error Handling class ValidationError extends Error { constructor(message) { super(message) this.name = 'ValidationError' } } class NetworkError extends Error { constructor(message) { super(message) this.name = 'NetworkError' } } const errors = [ new ValidationError('Bad input'), new NetworkError('Offline'), new Error('Unknown') ] const results = errors.map(error => { if (error instanceof ValidationError) return 'validation' if (error instanceof NetworkError) return 'network' return 'unknown' }) expect(results).toEqual(['validation', 'network', 'unknown']) }) it('should chain errors with cause', () => { // From: Error Chaining with cause class DataLoadError extends Error { constructor(message, options) { super(message, options) this.name = 'DataLoadError' } } const originalError = new Error('Network timeout') const wrappedError = new DataLoadError('Failed to load user data', { cause: originalError }) expect(wrappedError.cause).toBe(originalError) expect(wrappedError.cause.message).toBe('Network timeout') }) }) // ============================================================ // ASYNC ERROR HANDLING // ============================================================ describe('Async Error Handling', () => { it('should catch Promise rejections with .catch()', async () => { // From: With Promises: .catch() const result = await Promise.reject(new Error('Failed')) .catch(error => `Caught: ${error.message}`) expect(result).toBe('Caught: Failed') }) it('should catch async/await errors with try/catch', async () => { // From: With async/await: try/catch async function failingOperation() { throw new Error('Async failure') } let caught = null try { await failingOperation() } catch (error) { caught = error.message } expect(caught).toBe('Async failure') }) it('should run .finally() regardless of outcome', async () => { const order = [] // Success case await Promise.resolve('success') .then(v => { order.push('then') }) .finally(() => { order.push('finally-success') }) // Failure case await Promise.reject(new Error('fail')) .catch(e => { order.push('catch') }) .finally(() => { order.push('finally-fail') }) expect(order).toEqual(['then', 'finally-success', 'catch', 'finally-fail']) }) it('should demonstrate try/catch only catches synchronous errors', async () => { // From: try/catch Only Works Synchronously const order = [] try { setTimeout(() => { order.push('timeout executed') // If we threw here, try/catch wouldn't catch it }, 0) order.push('after setTimeout') } catch (error) { order.push('catch') } expect(order).toEqual(['after setTimeout']) // Let setTimeout execute await new Promise(resolve => setTimeout(resolve, 10)) expect(order).toEqual(['after setTimeout', 'timeout executed']) }) }) // ============================================================ // GLOBAL ERROR HANDLERS (Not Tested - Browser-Specific) // ============================================================ // // The following patterns from the concept page are browser-specific // and cannot be tested in a Node.js/Vitest environment: // // - window.onerror = function(message, source, lineno, colno, error) { ... } // Catches uncaught synchronous errors in the browser // // - window.addEventListener('unhandledrejection', event => { ... }) // Catches unhandled Promise rejections in the browser // // These are documented in the concept page (lines 531-557) for browser usage. // In production, these are typically used for: // - Logging errors to services like Sentry or LogRocket // - Showing generic "something went wrong" messages // - Tracking errors in production environments // // They should be used as a safety net, not as primary error handling. // ============================================================ // ============================================================ // COMMON MISTAKES // ============================================================ describe('Common Mistakes', () => { it('Mistake 1: Empty catch blocks swallow errors', () => { // From: Empty catch Blocks (Swallowing Errors) let errorLogged = false // Bad: error is silently swallowed try { throw new Error('Silent error') } catch (error) { // Empty - bad practice } // Good: at least log the error try { throw new Error('Logged error') } catch (error) { errorLogged = true // console.error('Error:', error) in real code } expect(errorLogged).toBe(true) }) it('Mistake 2: Catching too broadly hides bugs', () => { // From: Catching Too Broadly function parseWithBugHidden(input) { try { const result = JSON.parse(input) // Bug: typo in variable name would be hidden return result } catch (error) { return 'Something went wrong' } } function parseCorrectly(input) { try { return JSON.parse(input) } catch (error) { if (error instanceof SyntaxError) { return null // Expected case } throw error // Unexpected: re-throw } } expect(parseWithBugHidden('{ invalid }')).toBe('Something went wrong') expect(parseCorrectly('{ invalid }')).toBe(null) expect(parseCorrectly('{"valid": true}')).toEqual({ valid: true }) }) it('Mistake 3: Throwing strings instead of Error objects', () => { // From: Throwing Strings Instead of Errors // Bad: no stack trace try { throw 'String error' } catch (error) { expect(typeof error).toBe('string') expect(error.stack).toBeUndefined() } // Good: has stack trace try { throw new Error('Error object') } catch (error) { expect(error instanceof Error).toBe(true) expect(error.stack).toBeDefined() } }) it('Mistake 4: Not re-throwing when needed', async () => { // From: Not Re-throwing When Needed // Bad: returns undefined, caller thinks success async function badFetch() { try { throw new Error('Network error') } catch (error) { // Just logs, doesn't re-throw or return meaningful value } } // Good: re-throws for caller to handle async function goodFetch() { try { throw new Error('Network error') } catch (error) { throw error // Let caller decide what to do } } const badResult = await badFetch() expect(badResult).toBeUndefined() // Silent failure! await expect(goodFetch()).rejects.toThrow('Network error') }) it('Mistake 5: Expecting try/catch to catch async callback errors', async () => { // From: Forgetting try/catch is Synchronous let syncCaughtError = null let callbackError = null // This catch won't catch the setTimeout error try { setTimeout(() => { try { throw new Error('Callback error') } catch (e) { callbackError = e.message } }, 0) } catch (error) { syncCaughtError = error.message } expect(syncCaughtError).toBeNull() // Sync catch doesn't catch async await new Promise(resolve => setTimeout(resolve, 10)) expect(callbackError).toBe('Callback error') // Inner catch works }) }) // ============================================================ // REAL-WORLD PATTERNS // ============================================================ describe('Real-World Patterns', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) it('should implement retry pattern', async () => { // From: Retry Pattern let attempts = 0 async function flakyOperation() { attempts++ if (attempts < 3) { throw new Error('Temporary failure') } return 'success' } async function fetchWithRetry(operation, retries = 3) { for (let i = 0; i < retries; i++) { try { return await operation() } catch (error) { if (i === retries - 1) throw error await new Promise(r => setTimeout(r, 100 * Math.pow(2, i))) } } } const promise = fetchWithRetry(flakyOperation, 3) // First attempt fails await vi.advanceTimersByTimeAsync(0) expect(attempts).toBe(1) // Wait for first retry (100ms) await vi.advanceTimersByTimeAsync(100) expect(attempts).toBe(2) // Wait for second retry (200ms) await vi.advanceTimersByTimeAsync(200) expect(attempts).toBe(3) const result = await promise expect(result).toBe('success') }) it('should implement validation error pattern', () => { // From: Validation Error Pattern class ValidationError extends Error { constructor(errors) { super('Validation failed') this.name = 'ValidationError' this.errors = errors } } function validateUser(data) { const errors = {} if (!data.email?.includes('@')) { errors.email = 'Invalid email address' } if (data.age < 0) { errors.age = 'Age must be positive' } if (Object.keys(errors).length > 0) { throw new ValidationError(errors) } return true } // Valid data expect(validateUser({ email: 'test@example.com', age: 25 })).toBe(true) // Invalid data try { validateUser({ email: 'invalid', age: -5 }) } catch (error) { expect(error instanceof ValidationError).toBe(true) expect(error.errors.email).toBe('Invalid email address') expect(error.errors.age).toBe('Age must be positive') } }) it('should implement graceful degradation', async () => { // From: Graceful Degradation let apiCalled = false let cacheCalled = false async function fetchFromApi() { apiCalled = true throw new Error('API unavailable') } async function loadFromCache() { cacheCalled = true return { cached: true } } async function loadUserPreferences() { try { return await fetchFromApi() } catch (apiError) { try { return await loadFromCache() } catch (cacheError) { return { theme: 'light', language: 'en' } // Defaults } } } const result = await loadUserPreferences() expect(apiCalled).toBe(true) expect(cacheCalled).toBe(true) expect(result).toEqual({ cached: true }) }) }) // ============================================================ // RETHROWING ERRORS // ============================================================ describe('Rethrowing Errors', () => { it('should rethrow errors you cannot handle', () => { // From: Catch should only process errors that it knows function parseUserData(json) { try { return JSON.parse(json) } catch (error) { if (error instanceof SyntaxError) { // We know how to handle this return null } // Unknown error, rethrow throw error } } expect(parseUserData('{"name": "John"}')).toEqual({ name: 'John' }) expect(parseUserData('invalid')).toBeNull() }) it('should wrap errors with additional context', () => { function processOrder(order) { try { if (!order.items) { throw new Error('Order has no items') } return { processed: true } } catch (error) { throw new Error(`Failed to process order ${order.id}`, { cause: error }) } } try { processOrder({ id: '123' }) } catch (error) { expect(error.message).toBe('Failed to process order 123') expect(error.cause.message).toBe('Order has no items') } }) }) // ============================================================ // SCOPING IN TRY/CATCH // ============================================================ describe('Variable Scoping in try/catch', () => { it('should demonstrate variable scoping issue', () => { // From: Test Your Knowledge Question 6 // Wrong: result is scoped to try block let wrongResult try { const result = 'value' wrongResult = result } catch (e) { // handle error } // console.log(result) would throw ReferenceError // Correct: declare outside try block let correctResult try { correctResult = 'value' } catch (e) { correctResult = 'fallback' } expect(correctResult).toBe('value') }) it('should use fallback value when error occurs', () => { let result try { result = JSON.parse('invalid') } catch (e) { result = { fallback: true } } expect(result).toEqual({ fallback: true }) }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/functions-execution/event-loop/event-loop.test.js
tests/functions-execution/event-loop/event-loop.test.js
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' describe('Event Loop, Timers and Scheduling', () => { // ============================================================ // SYNCHRONOUS EXECUTION // ============================================================ describe('Synchronous Execution', () => { it('should execute code one line at a time in order', () => { // From lines 99-104: JavaScript executes these ONE AT A TIME, in order const order = [] order.push('First') // 1. This runs order.push('Second') // 2. Then this order.push('Third') // 3. Then this expect(order).toEqual(['First', 'Second', 'Third']) }) it('should execute nested function calls correctly (multiply, square, printSquare)', () => { // From lines 210-224: Call Stack example function multiply(a, b) { return a * b } function square(n) { return multiply(n, n) } function printSquare(n) { const result = square(n) return result } expect(printSquare(4)).toBe(16) expect(square(5)).toBe(25) expect(multiply(3, 4)).toBe(12) }) it('should store objects and arrays in the heap', () => { // From lines 243-245: Heap example const user = { name: 'Alice' } // Object stored in heap const numbers = [1, 2, 3] // Array stored in heap expect(user).toEqual({ name: 'Alice' }) expect(numbers).toEqual([1, 2, 3]) }) }) // ============================================================ // setTimeout BASICS // ============================================================ describe('setTimeout Basics', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) it('should run callback after specified delay', async () => { const callback = vi.fn() setTimeout(callback, 2000) expect(callback).not.toHaveBeenCalled() await vi.advanceTimersByTimeAsync(2000) expect(callback).toHaveBeenCalledTimes(1) }) it('should pass arguments to the callback', async () => { // From lines 562-566: Pass arguments to the callback let result = '' setTimeout((name, greeting) => { result = `${greeting}, ${name}!` }, 1000, 'Alice', 'Hello') await vi.advanceTimersByTimeAsync(1000) expect(result).toBe('Hello, Alice!') }) it('should cancel timeout with clearTimeout', async () => { // From lines 569-577: Canceling a timeout const callback = vi.fn() const timerId = setTimeout(callback, 5000) // Cancel it before it fires clearTimeout(timerId) await vi.advanceTimersByTimeAsync(5000) expect(callback).not.toHaveBeenCalled() }) it('should demonstrate the zero delay myth - setTimeout(fn, 0) does NOT run immediately', async () => { // From lines 580-589: Zero delay myth const order = [] order.push('A') setTimeout(() => order.push('B'), 0) order.push('C') // Before advancing timers, only sync code has run expect(order).toEqual(['A', 'C']) await vi.advanceTimersByTimeAsync(0) // Output: A, C, B (NOT A, B, C!) expect(order).toEqual(['A', 'C', 'B']) }) it('should run synchronous code first, then setTimeout callback', async () => { // From lines 313-323: Basic setTimeout example const order = [] order.push('Start') setTimeout(() => { order.push('Timeout') }, 0) order.push('End') // Before microtasks/timers run expect(order).toEqual(['Start', 'End']) await vi.advanceTimersByTimeAsync(0) // Output: Start, End, Timeout expect(order).toEqual(['Start', 'End', 'Timeout']) }) it('should run multiple setTimeout callbacks in order of their delays', async () => { const order = [] setTimeout(() => order.push('200ms'), 200) setTimeout(() => order.push('100ms'), 100) setTimeout(() => order.push('300ms'), 300) await vi.advanceTimersByTimeAsync(300) expect(order).toEqual(['100ms', '200ms', '300ms']) }) it('should run setTimeout callbacks with same delay in registration order', async () => { const order = [] setTimeout(() => order.push('first'), 100) setTimeout(() => order.push('second'), 100) setTimeout(() => order.push('third'), 100) await vi.advanceTimersByTimeAsync(100) expect(order).toEqual(['first', 'second', 'third']) }) it('should demonstrate the 4ms minimum delay after nested timeouts', async () => { // From lines 601-615: After 5 nested timeouts, browsers enforce a minimum 4ms delay // Note: Vitest fake timers don't enforce the 4ms minimum, so we test the pattern const times = [] let start = Date.now() function run() { times.push(Date.now() - start) if (times.length < 10) { setTimeout(run, 0) } } setTimeout(run, 0) // Run all nested timeouts await vi.runAllTimersAsync() // Should have 10 timestamps recorded expect(times.length).toBe(10) // In fake timers, all execute at 0ms intervals // In real browsers, after 5 nested calls, minimum becomes 4ms // Pattern: [1, 1, 1, 1, 4, 9, 14, 19, 24, 29] approximately }) }) // ============================================================ // DEBOUNCE PATTERN // ============================================================ describe('Debounce Pattern', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) it('should cancel previous timeout when implementing debounce', async () => { // From lines 1341-1349: Cancel previous timeout (debounce) const searchResults = [] let timeoutId function handleInput(value) { clearTimeout(timeoutId) timeoutId = setTimeout(() => { searchResults.push(`search: ${value}`) }, 300) } // Simulate rapid typing handleInput('a') await vi.advanceTimersByTimeAsync(100) handleInput('ab') await vi.advanceTimersByTimeAsync(100) handleInput('abc') await vi.advanceTimersByTimeAsync(100) // At this point, 300ms hasn't passed since last input expect(searchResults).toEqual([]) // Wait for debounce delay await vi.advanceTimersByTimeAsync(300) // Only the last input should trigger a search expect(searchResults).toEqual(['search: abc']) }) it('should execute immediately if enough time passes between inputs', async () => { const searchResults = [] let timeoutId function handleInput(value) { clearTimeout(timeoutId) timeoutId = setTimeout(() => { searchResults.push(`search: ${value}`) }, 300) } handleInput('first') await vi.advanceTimersByTimeAsync(300) expect(searchResults).toEqual(['search: first']) handleInput('second') await vi.advanceTimersByTimeAsync(300) expect(searchResults).toEqual(['search: first', 'search: second']) }) }) // ============================================================ // SETINTERVAL WITH ASYNC PROBLEM // ============================================================ describe('setInterval with Async Problem', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) it('should demonstrate overlapping requests with setInterval and async', async () => { // From lines 1521-1526: If fetch takes longer than interval, multiple requests overlap const requestsStarted = [] const requestsCompleted = [] let requestCount = 0 // Simulate a slow fetch that takes 1500ms async function slowFetch() { const id = ++requestCount requestsStarted.push(`request ${id} started`) await new Promise(resolve => setTimeout(resolve, 1500)) requestsCompleted.push(`request ${id} completed`) } // Start interval that fires every 1000ms const intervalId = setInterval(async () => { await slowFetch() }, 1000) // After 1000ms: first request starts await vi.advanceTimersByTimeAsync(1000) await Promise.resolve() expect(requestsStarted).toEqual(['request 1 started']) expect(requestsCompleted).toEqual([]) // After 2000ms: second request starts (first still pending!) await vi.advanceTimersByTimeAsync(1000) await Promise.resolve() expect(requestsStarted).toEqual(['request 1 started', 'request 2 started']) expect(requestsCompleted).toEqual([]) // First request still not done // After 2500ms: first request completes await vi.advanceTimersByTimeAsync(500) await Promise.resolve() expect(requestsCompleted).toEqual(['request 1 completed']) // Clean up clearInterval(intervalId) }) it('should demonstrate the fix using nested setTimeout for polling', async () => { // From lines 1532-1539: Schedule next AFTER completion const requestsStarted = [] const requestsCompleted = [] let requestCount = 0 let isPolling = true // Simulate a slow fetch that takes 1500ms async function slowFetch() { const id = ++requestCount requestsStarted.push(`request ${id} started`) await new Promise(resolve => setTimeout(resolve, 1500)) requestsCompleted.push(`request ${id} completed`) } // Fixed polling pattern async function poll() { await slowFetch() if (isPolling && requestCount < 3) { setTimeout(poll, 1000) // Schedule next AFTER completion } } poll() // Request 1 starts immediately await Promise.resolve() expect(requestsStarted).toEqual(['request 1 started']) // After 1500ms: request 1 completes, then waits 1000ms before next await vi.advanceTimersByTimeAsync(1500) await Promise.resolve() expect(requestsCompleted).toEqual(['request 1 completed']) expect(requestsStarted.length).toBe(1) // No overlapping request! // After 2500ms (1500 + 1000): request 2 starts await vi.advanceTimersByTimeAsync(1000) await Promise.resolve() expect(requestsStarted).toEqual(['request 1 started', 'request 2 started']) // After 4000ms (1500 + 1000 + 1500): request 2 completes await vi.advanceTimersByTimeAsync(1500) await Promise.resolve() expect(requestsCompleted).toEqual(['request 1 completed', 'request 2 completed']) isPolling = false }) }) // ============================================================ // PROMISES AND MICROTASKS // ============================================================ describe('Promises and Microtasks', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) it('should run Promise.then() as a microtask', async () => { const order = [] order.push('sync 1') Promise.resolve().then(() => order.push('promise')) order.push('sync 2') // Microtask hasn't run yet expect(order).toEqual(['sync 1', 'sync 2']) // Let microtasks drain await Promise.resolve() expect(order).toEqual(['sync 1', 'sync 2', 'promise']) }) it('should run Promises BEFORE setTimeout (microtasks before macrotasks)', async () => { // From lines 391-401: Promises vs setTimeout const order = [] order.push('1') setTimeout(() => order.push('2'), 0) Promise.resolve().then(() => order.push('3')) order.push('4') // Let microtasks drain first await Promise.resolve() // At this point: ['1', '4', '3'] expect(order).toEqual(['1', '4', '3']) // Now let timers run await vi.advanceTimersByTimeAsync(0) // Output: 1, 4, 3, 2 expect(order).toEqual(['1', '4', '3', '2']) }) it('should drain entire microtask queue before any macrotask', async () => { // From lines 449-467: Nested Microtasks const order = [] order.push('Start') Promise.resolve() .then(() => { order.push('Promise 1') Promise.resolve().then(() => order.push('Promise 2')) }) setTimeout(() => order.push('Timeout'), 0) order.push('End') // Let all microtasks drain await Promise.resolve() await Promise.resolve() // Need two ticks for nested promise expect(order).toEqual(['Start', 'End', 'Promise 1', 'Promise 2']) // Now let timers run await vi.advanceTimersByTimeAsync(0) // Output: Start, End, Promise 1, Promise 2, Timeout expect(order).toEqual(['Start', 'End', 'Promise 1', 'Promise 2', 'Timeout']) }) it('should process newly added microtasks during microtask processing', async () => { const order = [] Promise.resolve().then(() => { order.push('first') Promise.resolve().then(() => { order.push('second') Promise.resolve().then(() => { order.push('third') }) }) }) // Drain all microtasks - need multiple ticks for nested promises await Promise.resolve() await Promise.resolve() await Promise.resolve() await Promise.resolve() expect(order).toEqual(['first', 'second', 'third']) }) it('should run queueMicrotask as a microtask', async () => { const order = [] order.push('sync 1') queueMicrotask(() => order.push('microtask')) order.push('sync 2') await Promise.resolve() expect(order).toEqual(['sync 1', 'sync 2', 'microtask']) }) it('should interleave Promise.resolve() and queueMicrotask in order', async () => { const order = [] Promise.resolve().then(() => order.push('promise 1')) queueMicrotask(() => order.push('queueMicrotask 1')) Promise.resolve().then(() => order.push('promise 2')) queueMicrotask(() => order.push('queueMicrotask 2')) await Promise.resolve() await Promise.resolve() // Microtasks run in order they were queued expect(order).toEqual(['promise 1', 'queueMicrotask 1', 'promise 2', 'queueMicrotask 2']) }) it('should demonstrate that Promise.resolve() creates a microtask, not synchronous execution', async () => { const order = [] const promise = Promise.resolve('value') order.push('after Promise.resolve()') promise.then(value => order.push(`then: ${value}`)) order.push('after .then()') await Promise.resolve() expect(order).toEqual([ 'after Promise.resolve()', 'after .then()', 'then: value' ]) }) }) // ============================================================ // setInterval // ============================================================ describe('setInterval', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) it('should run callback repeatedly at specified interval', async () => { // From lines 649-662: Basic setInterval usage let count = 0 const results = [] const intervalId = setInterval(() => { count++ results.push(`Count: ${count}`) if (count >= 5) { clearInterval(intervalId) results.push('Done!') } }, 1000) // Advance through 5 intervals await vi.advanceTimersByTimeAsync(5000) expect(results).toEqual([ 'Count: 1', 'Count: 2', 'Count: 3', 'Count: 4', 'Count: 5', 'Done!' ]) expect(count).toBe(5) }) it('should stop running when clearInterval is called', async () => { const callback = vi.fn() const intervalId = setInterval(callback, 100) await vi.advanceTimersByTimeAsync(250) expect(callback).toHaveBeenCalledTimes(2) clearInterval(intervalId) await vi.advanceTimersByTimeAsync(500) // Should still be 2, not more expect(callback).toHaveBeenCalledTimes(2) }) it('should pass arguments to the interval callback', async () => { const results = [] const intervalId = setInterval((prefix, suffix) => { results.push(`${prefix}test${suffix}`) }, 100, '[', ']') await vi.advanceTimersByTimeAsync(300) clearInterval(intervalId) expect(results).toEqual(['[test]', '[test]', '[test]']) }) }) // ============================================================ // NESTED setTimeout (preciseInterval pattern) // ============================================================ describe('Nested setTimeout (preciseInterval pattern)', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) it('should implement preciseInterval with nested setTimeout', async () => { // From lines 695-706: Nested setTimeout guarantees delay BETWEEN executions const results = [] let callCount = 0 function preciseInterval(callback, delay) { function tick() { callback() if (callCount < 3) { setTimeout(tick, delay) } } setTimeout(tick, delay) } preciseInterval(() => { callCount++ results.push(`tick ${callCount}`) }, 1000) await vi.advanceTimersByTimeAsync(3000) expect(results).toEqual(['tick 1', 'tick 2', 'tick 3']) }) it('should schedule next timeout only after callback completes', async () => { const timestamps = [] let count = 0 function recursiveTimeout() { timestamps.push(Date.now()) count++ if (count < 3) { setTimeout(recursiveTimeout, 100) } } setTimeout(recursiveTimeout, 100) await vi.advanceTimersByTimeAsync(300) expect(timestamps.length).toBe(3) // Each timestamp should be 100ms apart expect(timestamps[1] - timestamps[0]).toBe(100) expect(timestamps[2] - timestamps[1]).toBe(100) }) }) // ============================================================ // async/await // ============================================================ describe('async/await', () => { it('should run code before await synchronously', async () => { // From lines 955-964: async/await ordering const order = [] async function foo() { order.push('foo start') await Promise.resolve() order.push('foo end') } order.push('script start') foo() order.push('script end') // At this point, foo has paused at await expect(order).toEqual(['script start', 'foo start', 'script end']) // Let microtasks drain await Promise.resolve() // Output: script start, foo start, script end, foo end expect(order).toEqual(['script start', 'foo start', 'script end', 'foo end']) }) it('should treat code after await as a microtask', async () => { const order = [] async function asyncFn() { order.push('async start') await Promise.resolve() order.push('async after await') } order.push('before call') asyncFn() order.push('after call') // Await hasn't resolved yet expect(order).toEqual(['before call', 'async start', 'after call']) await Promise.resolve() expect(order).toEqual(['before call', 'async start', 'after call', 'async after await']) }) it('should handle multiple await statements', async () => { const order = [] async function multipleAwaits() { order.push('start') await Promise.resolve() order.push('after first await') await Promise.resolve() order.push('after second await') } multipleAwaits() order.push('sync after call') expect(order).toEqual(['start', 'sync after call']) await Promise.resolve() expect(order).toEqual(['start', 'sync after call', 'after first await']) await Promise.resolve() expect(order).toEqual(['start', 'sync after call', 'after first await', 'after second await']) }) it('should handle async functions returning values', async () => { async function getValue() { await Promise.resolve() return 42 } const result = await getValue() expect(result).toBe(42) }) it('should handle async functions with try/catch', async () => { async function mightFail(shouldFail) { await Promise.resolve() if (shouldFail) { throw new Error('Failed!') } return 'Success' } await expect(mightFail(false)).resolves.toBe('Success') await expect(mightFail(true)).rejects.toThrow('Failed!') }) }) // ============================================================ // INTERVIEW QUESTIONS // ============================================================ describe('Interview Questions', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) it('Question 1: Basic Output Order - should output 1, 4, 3, 2', async () => { // From lines 900-918 const order = [] order.push('1') setTimeout(() => order.push('2'), 0) Promise.resolve().then(() => order.push('3')) order.push('4') // Drain microtasks await Promise.resolve() expect(order).toEqual(['1', '4', '3']) // Drain macrotasks await vi.advanceTimersByTimeAsync(0) expect(order).toEqual(['1', '4', '3', '2']) }) it('Question 2: Nested Promises and Timeouts - should output sync, promise 1, promise 2, timeout 1, timeout 2', async () => { // From lines 921-951 const order = [] setTimeout(() => order.push('timeout 1'), 0) Promise.resolve().then(() => { order.push('promise 1') Promise.resolve().then(() => order.push('promise 2')) }) setTimeout(() => order.push('timeout 2'), 0) order.push('sync') // Sync done expect(order).toEqual(['sync']) // Drain microtasks (including nested ones) await Promise.resolve() await Promise.resolve() expect(order).toEqual(['sync', 'promise 1', 'promise 2']) // Drain macrotasks await vi.advanceTimersByTimeAsync(0) expect(order).toEqual(['sync', 'promise 1', 'promise 2', 'timeout 1', 'timeout 2']) }) it('Question 3: async/await Ordering - should output script start, foo start, script end, foo end', async () => { // From lines 953-981 const order = [] async function foo() { order.push('foo start') await Promise.resolve() order.push('foo end') } order.push('script start') foo() order.push('script end') await Promise.resolve() expect(order).toEqual(['script start', 'foo start', 'script end', 'foo end']) }) it('Question 4a: setTimeout in a loop with var - should output 3, 3, 3', async () => { // From lines 985-997 const order = [] for (var i = 0; i < 3; i++) { setTimeout(() => order.push(i), 0) } await vi.advanceTimersByTimeAsync(0) // All callbacks see i = 3 because var is function-scoped expect(order).toEqual([3, 3, 3]) }) it('Question 4b: setTimeout in a loop with let - should output 0, 1, 2', async () => { // From lines 999-1004 const order = [] for (let i = 0; i < 3; i++) { setTimeout(() => order.push(i), 0) } await vi.advanceTimersByTimeAsync(0) // Each callback has its own i because let is block-scoped expect(order).toEqual([0, 1, 2]) }) it('Question 4c: setTimeout in a loop with closure fix - should output 0, 1, 2', async () => { // From lines 1007-1015 const order = [] for (var i = 0; i < 3; i++) { ((j) => { setTimeout(() => order.push(j), 0) })(i) } await vi.advanceTimersByTimeAsync(0) // Each IIFE captures the current value of i expect(order).toEqual([0, 1, 2]) }) it('Question 6: Microtask scheduling - microtask should run', async () => { // From lines 1051-1077 (simplified - not infinite) const order = [] let count = 0 function scheduleMicrotask() { Promise.resolve().then(() => { count++ order.push(`microtask ${count}`) if (count < 3) { scheduleMicrotask() } }) } scheduleMicrotask() // Drain all microtasks await Promise.resolve() await Promise.resolve() await Promise.resolve() expect(order).toEqual(['microtask 1', 'microtask 2', 'microtask 3']) }) it('Misconception 1: setTimeout(fn, 0) does NOT run immediately - should output sync, promise, timeout', async () => { // From lines 1084-1096 const order = [] setTimeout(() => order.push('timeout'), 0) Promise.resolve().then(() => order.push('promise')) order.push('sync') await Promise.resolve() await vi.advanceTimersByTimeAsync(0) // Output: sync, promise, timeout (NOT sync, timeout, promise) expect(order).toEqual(['sync', 'promise', 'timeout']) }) it('Test Your Knowledge Q3: Complex ordering - should output E, B, C, A, D', async () => { // From lines 1487-1504 const order = [] setTimeout(() => order.push('A'), 0) Promise.resolve().then(() => order.push('B')) Promise.resolve().then(() => { order.push('C') setTimeout(() => order.push('D'), 0) }) order.push('E') // Drain microtasks await Promise.resolve() await Promise.resolve() expect(order).toEqual(['E', 'B', 'C']) // Drain macrotasks await vi.advanceTimersByTimeAsync(0) expect(order).toEqual(['E', 'B', 'C', 'A', 'D']) }) }) // ============================================================ // COMMON PATTERNS // ============================================================ describe('Common Patterns', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) it('this binding: regular function loses this context', async () => { // From lines 1354-1363 const obj = { name: 'Alice', greet() { return new Promise(resolve => { setTimeout(function() { // 'this' is undefined in strict mode (or global in non-strict) resolve(this?.name) }, 100) }) } } const resultPromise = obj.greet() await vi.advanceTimersByTimeAsync(100) const result = await resultPromise expect(result).toBeUndefined() }) it('this binding: arrow function preserves this context', async () => { // From lines 1365-1373 const obj = { name: 'Alice', greet() { return new Promise(resolve => { setTimeout(() => { resolve(this.name) }, 100) }) } } const resultPromise = obj.greet() await vi.advanceTimersByTimeAsync(100) const result = await resultPromise expect(result).toBe('Alice') }) it('this binding: bind() preserves this context', async () => { // From lines 1375-1383 const obj = { name: 'Alice', greet() { return new Promise(resolve => { setTimeout(function() { resolve(this.name) }.bind(this), 100) }) } } const resultPromise = obj.greet() await vi.advanceTimersByTimeAsync(100) const result = await resultPromise expect(result).toBe('Alice') }) it('closure in loop: var creates shared reference', async () => { // From lines 1388-1393 const results = [] for (var i = 0; i < 3; i++) { setTimeout(() => results.push(i), 100) } await vi.advanceTimersByTimeAsync(100) // Output: 3, 3, 3 expect(results).toEqual([3, 3, 3]) }) it('closure in loop: let creates new binding per iteration', async () => { // From lines 1395-1399 const results = [] for (let i = 0; i < 3; i++) { setTimeout(() => results.push(i), 100) } await vi.advanceTimersByTimeAsync(100) // Output: 0, 1, 2 expect(results).toEqual([0, 1, 2]) }) it('closure in loop: setTimeout third argument passes value', async () => { // From lines 1401-1405 const results = [] for (var i = 0; i < 3; i++) { setTimeout((j) => results.push(j), 100, i) } await vi.advanceTimersByTimeAsync(100) // Output: 0, 1, 2 expect(results).toEqual([0, 1, 2]) }) it('should implement chunking with setTimeout', async () => { // From lines 1196-1215 const processed = [] const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] function processInChunks(items, process, chunkSize = 3) { let index = 0 function doChunk() { const end = Math.min(index + chunkSize, items.length) for (; index < end; index++) { process(items[index]) } if (index < items.length) { setTimeout(doChunk, 0) } } doChunk() } processInChunks(items, item => processed.push(item), 3) // First chunk runs synchronously expect(processed).toEqual([1, 2, 3]) // Run all remaining timers await vi.runAllTimersAsync() expect(processed).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) }) it('should implement async polling with nested setTimeout', async () => { // From lines 1532-1540 const results = [] let pollCount = 0 async function poll() { // Simulate async fetch const data = await Promise.resolve(`data ${++pollCount}`) results.push(data) if (pollCount < 3) { setTimeout(poll, 1000) } } poll() // First poll completes immediately (Promise.resolve) await Promise.resolve() expect(results).toEqual(['data 1']) // Second poll after 1000ms await vi.advanceTimersByTimeAsync(1000) await Promise.resolve() expect(results).toEqual(['data 1', 'data 2']) // Third poll after another 1000ms await vi.advanceTimersByTimeAsync(1000) await Promise.resolve() expect(results).toEqual(['data 1', 'data 2', 'data 3']) }) }) // ============================================================ // YIELDING TO EVENT LOOP // ============================================================ describe('Yielding to Event Loop', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
true
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/functions-execution/async-await/async-await.test.js
tests/functions-execution/async-await/async-await.test.js
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' describe('async/await', () => { // ============================================================ // THE async KEYWORD // ============================================================ describe('The async Keyword', () => { it('should make a function return a Promise', () => { // From: async function always returns a Promise async function getValue() { return 42 } const result = getValue() expect(result).toBeInstanceOf(Promise) }) it('should wrap return values in Promise.resolve()', async () => { // From: return values are wrapped in Promise.resolve() async function getValue() { return 42 } const result = await getValue() expect(result).toBe(42) }) it('should convert thrown errors to rejected Promises', async () => { // From: when you throw in an async function, it becomes a rejected Promise async function failingFunction() { throw new Error('Something went wrong!') } await expect(failingFunction()).rejects.toThrow('Something went wrong!') }) it('should not double-wrap returned Promises', async () => { // From: return a Promise? No double-wrapping async function getPromise() { return Promise.resolve(42) } const result = await getPromise() // If it double-wrapped, result would be a Promise, not 42 expect(result).toBe(42) expect(typeof result).toBe('number') }) it('should work with async arrow functions', async () => { // From: async arrow function const getData = async () => { return 'data' } expect(await getData()).toBe('data') }) it('should work with async methods in objects', async () => { // From: async method in an object const api = { async fetchData() { return 'fetched' } } expect(await api.fetchData()).toBe('fetched') }) it('should work with async methods in classes', async () => { // From: async method in a class class DataService { async getData() { return 'class data' } } const service = new DataService() expect(await service.getData()).toBe('class data') }) }) // ============================================================ // THE await KEYWORD // ============================================================ describe('The await Keyword', () => { it('should pause execution until Promise resolves', async () => { const order = [] async function example() { order.push('before await') await Promise.resolve() order.push('after await') } await example() expect(order).toEqual(['before await', 'after await']) }) it('should return the resolved value of a Promise', async () => { async function example() { const value = await Promise.resolve(42) return value } expect(await example()).toBe(42) }) it('should work with non-Promise values (though pointless)', async () => { // From: awaiting a non-Promise value async function example() { const num = await 42 return num } expect(await example()).toBe(42) }) it('should work with thenable objects', async () => { // From: awaiting a thenable const thenable = { then(resolve) { resolve('thenable value') } } async function example() { return await thenable } expect(await example()).toBe('thenable value') }) it('should not block the main thread - other code runs while waiting', async () => { // From: await pauses the function, not the thread const order = [] async function slowOperation() { order.push('Starting slow operation') await Promise.resolve() order.push('Slow operation complete') } order.push('Before calling slowOperation') const promise = slowOperation() order.push('After calling slowOperation') // At this point, slowOperation is paused at await expect(order).toEqual([ 'Before calling slowOperation', 'Starting slow operation', 'After calling slowOperation' ]) await promise expect(order).toEqual([ 'Before calling slowOperation', 'Starting slow operation', 'After calling slowOperation', 'Slow operation complete' ]) }) }) // ============================================================ // HOW await WORKS UNDER THE HOOD // ============================================================ describe('How await Works Under the Hood', () => { it('should run code before await synchronously', async () => { // From: code before await is synchronous const order = [] async function example() { order.push('1. Before await') await Promise.resolve() order.push('2. After await') } order.push('A. Before call') example() order.push('B. After call') // Before microtasks run expect(order).toEqual([ 'A. Before call', '1. Before await', 'B. After call' ]) // Let microtasks run await Promise.resolve() expect(order).toEqual([ 'A. Before call', '1. Before await', 'B. After call', '2. After await' ]) }) it('should treat code after await as a microtask', async () => { // From: await splits the function diagram const order = [] async function asyncFn() { order.push('async start') await Promise.resolve() order.push('async after await') } order.push('script start') asyncFn() order.push('script end') // Await hasn't resolved yet expect(order).toEqual(['script start', 'async start', 'script end']) await Promise.resolve() expect(order).toEqual(['script start', 'async start', 'script end', 'async after await']) }) it('should handle multiple await statements', async () => { const order = [] async function multipleAwaits() { order.push('start') await Promise.resolve() order.push('after first await') await Promise.resolve() order.push('after second await') } multipleAwaits() order.push('sync after call') expect(order).toEqual(['start', 'sync after call']) await Promise.resolve() expect(order).toEqual(['start', 'sync after call', 'after first await']) await Promise.resolve() expect(order).toEqual(['start', 'sync after call', 'after first await', 'after second await']) }) }) // ============================================================ // ERROR HANDLING WITH try/catch // ============================================================ describe('Error Handling with try/catch', () => { it('should catch rejected Promises with try/catch', async () => { // From: Basic try/catch pattern async function fetchData() { try { await Promise.reject(new Error('Network error')) return 'success' } catch (error) { return `caught: ${error.message}` } } expect(await fetchData()).toBe('caught: Network error') }) it('should catch errors thrown in async functions', async () => { async function mightFail(shouldFail) { if (shouldFail) { throw new Error('Failed!') } return 'Success' } expect(await mightFail(false)).toBe('Success') await expect(mightFail(true)).rejects.toThrow('Failed!') }) it('should run finally block regardless of success or failure', async () => { // From: The finally block const results = [] async function withFinally(shouldFail) { try { if (shouldFail) { throw new Error('error') } results.push('success') } catch (error) { results.push('caught') } finally { results.push('finally') } } await withFinally(false) expect(results).toEqual(['success', 'finally']) results.length = 0 await withFinally(true) expect(results).toEqual(['caught', 'finally']) }) it('should demonstrate the swallowed error mistake', async () => { // From: The Trap - if you catch but don't re-throw, Promise resolves with undefined async function swallowsError() { try { throw new Error('Oops') } catch (error) { console.error('Error:', error) // Missing: throw error } } // This resolves (not rejects!) with undefined const result = await swallowsError() expect(result).toBeUndefined() }) it('should propagate errors when re-thrown', async () => { async function rethrowsError() { try { throw new Error('Oops') } catch (error) { throw error // Re-throw } } await expect(rethrowsError()).rejects.toThrow('Oops') }) it('should catch errors from nested async calls', async () => { // From: Interview Question 3 - Error Handling async function inner() { throw new Error('Oops!') } async function outer() { try { await inner() return 'success' } catch (e) { return `caught: ${e.message}` } } expect(await outer()).toBe('caught: Oops!') }) }) // ============================================================ // SEQUENTIAL VS PARALLEL EXECUTION // ============================================================ describe('Sequential vs Parallel Execution', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) it('should demonstrate slow sequential execution', async () => { // From: The Problem - Unnecessary Sequential Execution const delay = (ms, value) => new Promise(resolve => setTimeout(() => resolve(value), ms) ) async function sequential() { const start = Date.now() const a = await delay(100, 'a') const b = await delay(100, 'b') const c = await delay(100, 'c') return { a, b, c, time: Date.now() - start } } const promise = sequential() // Advance through all three delays await vi.advanceTimersByTimeAsync(100) await vi.advanceTimersByTimeAsync(100) await vi.advanceTimersByTimeAsync(100) const result = await promise expect(result.a).toBe('a') expect(result.b).toBe('b') expect(result.c).toBe('c') expect(result.time).toBeGreaterThanOrEqual(300) // Sequential: 100+100+100 }) it('should demonstrate fast parallel execution with Promise.all', async () => { // From: The Solution - Promise.all for Parallel Execution const delay = (ms, value) => new Promise(resolve => setTimeout(() => resolve(value), ms) ) async function parallel() { const start = Date.now() const [a, b, c] = await Promise.all([ delay(100, 'a'), delay(100, 'b'), delay(100, 'c') ]) return { a, b, c, time: Date.now() - start } } const promise = parallel() // All three start at once, so only need 100ms total await vi.advanceTimersByTimeAsync(100) const result = await promise expect(result.a).toBe('a') expect(result.b).toBe('b') expect(result.c).toBe('c') expect(result.time).toBe(100) // Parallel: max(100,100,100) = 100 }) it('should fail fast with Promise.all when any Promise rejects', async () => { // From: Promise.all - fails fast const results = await Promise.allSettled([ Promise.resolve('success'), Promise.reject(new Error('fail')), Promise.resolve('also success') ]) expect(results[0]).toEqual({ status: 'fulfilled', value: 'success' }) expect(results[1].status).toBe('rejected') expect(results[1].reason.message).toBe('fail') expect(results[2]).toEqual({ status: 'fulfilled', value: 'also success' }) }) it('should get all results with Promise.allSettled', async () => { // From: Promise.allSettled - waits for all const results = await Promise.allSettled([ Promise.resolve('a'), Promise.reject(new Error('b failed')), Promise.resolve('c') ]) const successful = results .filter(r => r.status === 'fulfilled') .map(r => r.value) const failed = results .filter(r => r.status === 'rejected') .map(r => r.reason.message) expect(successful).toEqual(['a', 'c']) expect(failed).toEqual(['b failed']) }) }) // ============================================================ // COMMON MISTAKES // ============================================================ describe('Common Mistakes', () => { it('Mistake #1: Forgetting await gives Promise instead of value', async () => { // From: Without await, you get a Promise object instead of the resolved value async function withoutAwait() { const value = Promise.resolve(42) // Missing await! return value } async function withAwait() { const value = await Promise.resolve(42) return value } const withoutResult = await withoutAwait() const withResult = await withAwait() // Both eventually resolve to 42, but withoutAwait returns a Promise expect(withoutResult).toBe(42) // Works because we await the function expect(withResult).toBe(42) }) it('Mistake #2: forEach does not wait for async callbacks', async () => { // From: forEach doesn't wait for async callbacks const order = [] const items = [1, 2, 3] // This is the WRONG way async function wrongWay() { items.forEach(async (item) => { await Promise.resolve() order.push(item) }) order.push('done') } await wrongWay() // 'done' appears before the items because forEach doesn't wait expect(order[0]).toBe('done') // Let microtasks complete await Promise.resolve() await Promise.resolve() await Promise.resolve() expect(order).toEqual(['done', 1, 2, 3]) }) it('Mistake #2 Fix: Use for...of for sequential processing', async () => { // From: Use for...of for sequential const order = [] const items = [1, 2, 3] async function rightWay() { for (const item of items) { await Promise.resolve() order.push(item) } order.push('done') } await rightWay() expect(order).toEqual([1, 2, 3, 'done']) }) it('Mistake #2 Fix: Use Promise.all with map for parallel processing', async () => { // From: Use Promise.all for parallel const results = [] const items = [1, 2, 3] async function parallelWay() { await Promise.all( items.map(async (item) => { await Promise.resolve() results.push(item) }) ) results.push('done') } await parallelWay() // Items may be in any order (parallel), but 'done' is always last expect(results).toContain(1) expect(results).toContain(2) expect(results).toContain(3) expect(results[results.length - 1]).toBe('done') }) it('Mistake #4: Not handling errors leads to unhandled rejections', async () => { // From: Not Handling Errors async function riskyOperation() { throw new Error('Unhandled!') } // Without error handling, this would be an unhandled rejection await expect(riskyOperation()).rejects.toThrow('Unhandled!') }) }) // ============================================================ // ADVANCED PATTERNS // ============================================================ describe('Advanced Patterns', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) it('should implement retry with exponential backoff', async () => { // From: Retry with Exponential Backoff let attempts = 0 async function flakyOperation() { attempts++ if (attempts < 3) { throw new Error('Temporary failure') } return 'success' } async function withRetry(operation, retries = 3, backoff = 100) { for (let attempt = 0; attempt < retries; attempt++) { try { return await operation() } catch (error) { if (attempt === retries - 1) throw error await new Promise(resolve => setTimeout(resolve, backoff * Math.pow(2, attempt))) } } } const promise = withRetry(flakyOperation, 3, 100) // First attempt fails, wait 100ms await vi.advanceTimersByTimeAsync(0) expect(attempts).toBe(1) // Second attempt after 100ms, fails, wait 200ms await vi.advanceTimersByTimeAsync(100) expect(attempts).toBe(2) // Third attempt after 200ms, succeeds await vi.advanceTimersByTimeAsync(200) const result = await promise expect(result).toBe('success') expect(attempts).toBe(3) }) it('should implement timeout wrapper', async () => { // From: Timeout Wrapper async function withTimeout(promise, ms) { const timeout = new Promise((_, reject) => { setTimeout(() => reject(new Error(`Timeout after ${ms}ms`)), ms) }) return Promise.race([promise, timeout]) } // Test successful case const fastPromise = withTimeout(Promise.resolve('fast'), 1000) expect(await fastPromise).toBe('fast') // Test timeout case const slowPromise = new Promise(resolve => setTimeout(() => resolve('slow'), 2000)) const timeoutPromise = withTimeout(slowPromise, 100) // Advance time to trigger timeout vi.advanceTimersByTime(100) await expect(timeoutPromise).rejects.toThrow('Timeout after 100ms') }) it('should implement cancellation with AbortController', async () => { // From: Cancellation with AbortController async function fetchWithCancellation(signal) { return new Promise((resolve, reject) => { const timeoutId = setTimeout(() => resolve('data'), 1000) signal.addEventListener('abort', () => { clearTimeout(timeoutId) reject(new DOMException('Aborted', 'AbortError')) }) }) } const controller = new AbortController() const promise = fetchWithCancellation(controller.signal) // Cancel before it completes controller.abort() await expect(promise).rejects.toThrow('Aborted') }) it('should convert callback API to async/await', async () => { // From: Converting Callback APIs to async/await function callbackApi(value, callback) { setTimeout(() => { if (value < 0) { callback(new Error('Negative value')) } else { callback(null, value * 2) } }, 100) } // Promisified version function asyncApi(value) { return new Promise((resolve, reject) => { callbackApi(value, (err, result) => { if (err) reject(err) else resolve(result) }) }) } // Test success const successPromise = asyncApi(21) await vi.advanceTimersByTimeAsync(100) expect(await successPromise).toBe(42) // Test failure - must attach handler BEFORE advancing time const failPromise = asyncApi(-1) const failHandler = expect(failPromise).rejects.toThrow('Negative value') await vi.advanceTimersByTimeAsync(100) await failHandler }) }) // ============================================================ // INTERVIEW QUESTIONS // ============================================================ describe('Interview Questions', () => { it('Question 1: What is the output order?', async () => { // From: Interview Question 1 const order = [] async function test() { order.push('1') await Promise.resolve() order.push('2') } order.push('A') test() order.push('B') // Before microtasks expect(order).toEqual(['A', '1', 'B']) await Promise.resolve() // After microtasks expect(order).toEqual(['A', '1', 'B', '2']) }) it('Question 2: Sequential vs Parallel timing', async () => { // From: Interview Question 2 vi.useFakeTimers() function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)) } // Version A - Sequential async function versionA() { const start = Date.now() await delay(100) await delay(100) return Date.now() - start } // Version B - Parallel async function versionB() { const start = Date.now() await Promise.all([delay(100), delay(100)]) return Date.now() - start } const promiseA = versionA() await vi.advanceTimersByTimeAsync(200) const timeA = await promiseA const promiseB = versionB() await vi.advanceTimersByTimeAsync(100) const timeB = await promiseB expect(timeA).toBe(200) // Sequential: 100 + 100 expect(timeB).toBe(100) // Parallel: max(100, 100) vi.useRealTimers() }) it('Question 4: The forEach trap', async () => { // From: Interview Question 4 - The forEach Trap vi.useFakeTimers() const order = [] async function processItems() { const items = [1, 2, 3] items.forEach(async (item) => { await new Promise(resolve => setTimeout(resolve, 100)) order.push(item) }) order.push('Done') } processItems() // 'Done' appears immediately because forEach doesn't wait expect(order).toEqual(['Done']) // After delays complete await vi.advanceTimersByTimeAsync(100) await Promise.resolve() await Promise.resolve() await Promise.resolve() expect(order).toEqual(['Done', 1, 2, 3]) vi.useRealTimers() }) it('Question 5: Unnecessary await before return', async () => { // From: Interview Question 5 - What is wrong here? // This await is unnecessary (but not wrong) async function unnecessaryAwait() { return await Promise.resolve(42) } // This is equivalent and cleaner async function noAwait() { return Promise.resolve(42) } expect(await unnecessaryAwait()).toBe(42) expect(await noAwait()).toBe(42) }) it('Question 6: Complex output order with async/await, Promises, and setTimeout', async () => { // From: Test Your Knowledge Question 6 vi.useFakeTimers() const order = [] order.push('1') setTimeout(() => order.push('2'), 0) Promise.resolve().then(() => order.push('3')) async function test() { order.push('4') await Promise.resolve() order.push('5') } test() order.push('6') // Synchronous code completes: 1, 4, 6 expect(order).toEqual(['1', '4', '6']) // Microtasks run: 3, 5 await Promise.resolve() await Promise.resolve() expect(order).toEqual(['1', '4', '6', '3', '5']) // Macrotask runs: 2 await vi.advanceTimersByTimeAsync(0) expect(order).toEqual(['1', '4', '6', '3', '5', '2']) vi.useRealTimers() }) }) // ============================================================ // ASYNC/AWAIT WITH PROMISES INTEROPERABILITY // ============================================================ describe('async/await and Promises Interoperability', () => { it('should work with .then() on async function results', async () => { async function getData() { return 42 } const result = await getData().then(x => x * 2) expect(result).toBe(84) }) it('should work with .catch() on async function results', async () => { async function failingFn() { throw new Error('failed') } const result = await failingFn().catch(err => `caught: ${err.message}`) expect(result).toBe('caught: failed') }) it('should allow mixing async/await and Promise chains', async () => { async function step1() { return 'step1' } function step2(prev) { return Promise.resolve(`${prev} -> step2`) } async function step3(prev) { return `${prev} -> step3` } const result = await step1() .then(step2) .then(step3) expect(result).toBe('step1 -> step2 -> step3') }) it('should handle Promise.race with async functions', async () => { vi.useFakeTimers() async function fast() { await new Promise(resolve => setTimeout(resolve, 50)) return 'fast' } async function slow() { await new Promise(resolve => setTimeout(resolve, 200)) return 'slow' } const racePromise = Promise.race([fast(), slow()]) await vi.advanceTimersByTimeAsync(50) expect(await racePromise).toBe('fast') vi.useRealTimers() }) }) // ============================================================ // EDGE CASES // ============================================================ describe('Edge Cases', () => { it('should handle async function that returns undefined', async () => { async function returnsNothing() { await Promise.resolve() // No return statement } const result = await returnsNothing() expect(result).toBeUndefined() }) it('should handle async function that returns null', async () => { async function returnsNull() { return null } const result = await returnsNull() expect(result).toBeNull() }) it('should handle nested async functions', async () => { async function outer() { async function inner() { return await Promise.resolve('inner value') } return await inner() } expect(await outer()).toBe('inner value') }) it('should handle async IIFE', async () => { const result = await (async () => { return 'IIFE result' })() expect(result).toBe('IIFE result') }) it('should handle await in conditional', async () => { async function conditionalAwait(condition) { if (condition) { return await Promise.resolve('true branch') } else { return await Promise.resolve('false branch') } } expect(await conditionalAwait(true)).toBe('true branch') expect(await conditionalAwait(false)).toBe('false branch') }) it('should handle await in try-catch-finally', async () => { const order = [] async function withTryCatchFinally() { try { order.push('try start') await Promise.resolve() order.push('try end') throw new Error('test') } catch (e) { order.push('catch') await Promise.resolve() order.push('catch after await') } finally { order.push('finally') await Promise.resolve() order.push('finally after await') } } await withTryCatchFinally() expect(order).toEqual([ 'try start', 'try end', 'catch', 'catch after await', 'finally', 'finally after await' ]) }) it('should handle await in loop', async () => { async function loopWithAwait() { const results = [] for (let i = 0; i < 3; i++) { results.push(await Promise.resolve(i)) } return results } expect(await loopWithAwait()).toEqual([0, 1, 2]) }) it('should handle rejected Promise without await in try block', async () => { // This is a subtle bug - the catch won't catch the rejection // because the Promise is returned, not awaited async function subtleBug() { try { return Promise.reject(new Error('not caught')) } catch (e) { return 'caught' } } // The error is NOT caught by the try-catch await expect(subtleBug()).rejects.toThrow('not caught') }) it('should catch rejected Promise when awaited in try block', async () => { async function fixedVersion() { try { return await Promise.reject(new Error('is caught')) } catch (e) { return 'caught' } } // Now the error IS caught expect(await fixedVersion()).toBe('caught') }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/functions-execution/promises/promises.test.js
tests/functions-execution/promises/promises.test.js
import { describe, it, expect, vi } from 'vitest' describe('Promises', () => { describe('Basic Promise Creation', () => { it('should create a fulfilled Promise with resolve()', async () => { const promise = new Promise((resolve) => { resolve('success') }) const result = await promise expect(result).toBe('success') }) it('should create a rejected Promise with reject()', async () => { const promise = new Promise((_, reject) => { reject(new Error('failure')) }) await expect(promise).rejects.toThrow('failure') }) it('should execute the executor function synchronously', () => { const order = [] order.push('before') new Promise((resolve) => { order.push('inside executor') resolve('done') }) order.push('after') expect(order).toEqual(['before', 'inside executor', 'after']) }) it('should ignore subsequent resolve/reject calls after first settlement', async () => { const promise = new Promise((resolve, reject) => { resolve('first') resolve('second') // Ignored reject(new Error('error')) // Ignored }) const result = await promise expect(result).toBe('first') }) it('should automatically reject if executor throws', async () => { const promise = new Promise(() => { throw new Error('thrown error') }) await expect(promise).rejects.toThrow('thrown error') }) }) describe('Promise.resolve() and Promise.reject()', () => { it('should create fulfilled Promise with Promise.resolve()', async () => { const promise = Promise.resolve(42) expect(await promise).toBe(42) }) it('should create rejected Promise with Promise.reject()', async () => { const promise = Promise.reject(new Error('rejected')) await expect(promise).rejects.toThrow('rejected') }) it('should return the same Promise if resolving with a Promise', async () => { const original = Promise.resolve('original') const wrapped = Promise.resolve(original) // Promise.resolve returns the same Promise if given a native Promise expect(wrapped).toBe(original) }) }) describe('.then() method', () => { it('should receive the fulfilled value', async () => { const result = await Promise.resolve(10).then(x => x * 2) expect(result).toBe(20) }) it('should return a new Promise', () => { const p1 = Promise.resolve(1) const p2 = p1.then(x => x) expect(p2).toBeInstanceOf(Promise) expect(p1).not.toBe(p2) }) it('should chain values through multiple .then() calls', async () => { const result = await Promise.resolve(1) .then(x => x + 1) .then(x => x * 2) .then(x => x + 10) expect(result).toBe(14) // ((1 + 1) * 2) + 10 }) it('should unwrap returned Promises', async () => { const result = await Promise.resolve(1) .then(x => Promise.resolve(x + 1)) .then(x => x * 2) expect(result).toBe(4) // (1 + 1) * 2 }) it('should skip .then() when Promise is rejected', async () => { const thenCallback = vi.fn() await Promise.reject(new Error('error')) .then(thenCallback) .catch(() => {}) // Handle the rejection expect(thenCallback).not.toHaveBeenCalled() }) }) describe('.catch() method', () => { it('should catch rejected Promises', async () => { const result = await Promise.reject(new Error('error')) .catch(error => `caught: ${error.message}`) expect(result).toBe('caught: error') }) it('should catch errors thrown in .then()', async () => { const result = await Promise.resolve('ok') .then(() => { throw new Error('thrown') }) .catch(error => `caught: ${error.message}`) expect(result).toBe('caught: thrown') }) it('should allow chain to continue after catching', async () => { const result = await Promise.reject(new Error('error')) .catch(() => 'recovered') .then(value => value.toUpperCase()) expect(result).toBe('RECOVERED') }) it('should propagate errors through the chain until caught', async () => { const thenCallback1 = vi.fn() const thenCallback2 = vi.fn() const catchCallback = vi.fn(e => e.message) await Promise.reject(new Error('original error')) .then(thenCallback1) .then(thenCallback2) .catch(catchCallback) expect(thenCallback1).not.toHaveBeenCalled() expect(thenCallback2).not.toHaveBeenCalled() expect(catchCallback).toHaveBeenCalledWith(expect.any(Error)) }) }) describe('.finally() method', () => { it('should run on fulfillment', async () => { const finallyCallback = vi.fn() await Promise.resolve('value').finally(finallyCallback) expect(finallyCallback).toHaveBeenCalled() }) it('should run on rejection', async () => { const finallyCallback = vi.fn() await Promise.reject(new Error('error')) .catch(() => {}) // Handle rejection .finally(finallyCallback) expect(finallyCallback).toHaveBeenCalled() }) it('should not receive any arguments', async () => { const finallyCallback = vi.fn() await Promise.resolve('value').finally(finallyCallback) expect(finallyCallback).toHaveBeenCalledWith() // No arguments }) it('should pass through the original value', async () => { const result = await Promise.resolve('original') .finally(() => 'ignored') expect(result).toBe('original') }) it('should pass through the original error', async () => { await expect( Promise.reject(new Error('original')) .finally(() => 'ignored') ).rejects.toThrow('original') }) }) describe('Promise Chaining', () => { it('should maintain chain with undefined return', async () => { const result = await Promise.resolve('start') .then(() => { // No explicit return = undefined }) .then(value => value) expect(result).toBeUndefined() }) it('should handle async operations in sequence', async () => { const delay = (ms, value) => new Promise(resolve => setTimeout(() => resolve(value), ms)) const result = await delay(10, 'first') .then(value => delay(10, value + ' second')) .then(value => delay(10, value + ' third')) expect(result).toBe('first second third') }) }) describe('Promise.all()', () => { it('should resolve with array of values when all fulfill', async () => { const result = await Promise.all([ Promise.resolve(1), Promise.resolve(2), Promise.resolve(3) ]) expect(result).toEqual([1, 2, 3]) }) it('should maintain order regardless of resolution order', async () => { const result = await Promise.all([ new Promise(resolve => setTimeout(() => resolve('slow'), 30)), new Promise(resolve => setTimeout(() => resolve('fast'), 10)), Promise.resolve('instant') ]) expect(result).toEqual(['slow', 'fast', 'instant']) }) it('should reject immediately if any Promise rejects', async () => { await expect( Promise.all([ Promise.resolve('A'), Promise.reject(new Error('B failed')), Promise.resolve('C') ]) ).rejects.toThrow('B failed') }) it('should work with non-Promise values', async () => { const result = await Promise.all([1, 'two', Promise.resolve(3)]) expect(result).toEqual([1, 'two', 3]) }) it('should resolve immediately with empty array', async () => { const result = await Promise.all([]) expect(result).toEqual([]) }) }) describe('Promise.allSettled()', () => { it('should return status objects for all Promises', async () => { const results = await Promise.allSettled([ Promise.resolve('success'), Promise.reject(new Error('failure')), Promise.resolve(42) ]) expect(results).toEqual([ { status: 'fulfilled', value: 'success' }, { status: 'rejected', reason: expect.any(Error) }, { status: 'fulfilled', value: 42 } ]) }) it('should never reject', async () => { const results = await Promise.allSettled([ Promise.reject(new Error('error 1')), Promise.reject(new Error('error 2')) ]) expect(results).toHaveLength(2) expect(results[0].status).toBe('rejected') expect(results[1].status).toBe('rejected') }) it('should wait for all to settle', async () => { const start = Date.now() await Promise.allSettled([ new Promise(resolve => setTimeout(resolve, 50)), new Promise((_, reject) => setTimeout(() => reject(new Error()), 30)), new Promise(resolve => setTimeout(resolve, 40)) ]) const elapsed = Date.now() - start expect(elapsed).toBeGreaterThanOrEqual(45) // Waited for slowest }) }) describe('Promise.race()', () => { it('should resolve with first settled value', async () => { const result = await Promise.race([ new Promise(resolve => setTimeout(() => resolve('slow'), 50)), new Promise(resolve => setTimeout(() => resolve('fast'), 10)) ]) expect(result).toBe('fast') }) it('should reject if first settled is rejection', async () => { await expect( Promise.race([ new Promise((_, reject) => setTimeout(() => reject(new Error('fast error')), 10)), new Promise(resolve => setTimeout(() => resolve('slow success'), 50)) ]) ).rejects.toThrow('fast error') }) it('should never settle with empty array', () => { // Promise.race([]) returns a forever-pending Promise const promise = Promise.race([]) // We can't really test this without timing out, // but we can verify it returns a Promise expect(promise).toBeInstanceOf(Promise) }) }) describe('Promise.any()', () => { it('should resolve with first fulfilled value', async () => { const result = await Promise.any([ Promise.reject(new Error('error 1')), Promise.resolve('success'), Promise.reject(new Error('error 2')) ]) expect(result).toBe('success') }) it('should wait for first fulfillment, ignoring rejections', async () => { const result = await Promise.any([ new Promise((_, reject) => setTimeout(() => reject(new Error()), 10)), new Promise(resolve => setTimeout(() => resolve('winner'), 30)), new Promise((_, reject) => setTimeout(() => reject(new Error()), 20)) ]) expect(result).toBe('winner') }) it('should reject with AggregateError if all reject', async () => { try { await Promise.any([ Promise.reject(new Error('error 1')), Promise.reject(new Error('error 2')), Promise.reject(new Error('error 3')) ]) expect.fail('Should have rejected') } catch (error) { expect(error.name).toBe('AggregateError') expect(error.errors).toHaveLength(3) } }) }) describe('Microtask Queue Timing', () => { it('should run .then() callbacks asynchronously', () => { const order = [] order.push('1') Promise.resolve().then(() => { order.push('3') }) order.push('2') // Synchronously, only 1 and 2 are in the array expect(order).toEqual(['1', '2']) }) it('should demonstrate microtask priority over macrotasks', async () => { const order = [] // Macrotask (setTimeout) setTimeout(() => order.push('timeout'), 0) // Microtask (Promise) Promise.resolve().then(() => order.push('promise')) // Wait for both to complete await new Promise(resolve => setTimeout(resolve, 10)) // Promise (microtask) runs before setTimeout (macrotask) expect(order).toEqual(['promise', 'timeout']) }) it('should process nested microtasks before macrotasks', async () => { const order = [] setTimeout(() => order.push('timeout'), 0) Promise.resolve().then(() => { order.push('promise 1') Promise.resolve().then(() => { order.push('promise 2') }) }) await new Promise(resolve => setTimeout(resolve, 10)) expect(order).toEqual(['promise 1', 'promise 2', 'timeout']) }) }) describe('Common Patterns', () => { it('should wrap setTimeout in a Promise (delay pattern)', async () => { const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms)) const start = Date.now() await delay(50) const elapsed = Date.now() - start expect(elapsed).toBeGreaterThanOrEqual(45) }) it('should handle sequential execution', async () => { const results = [] const items = [1, 2, 3] for (const item of items) { const result = await Promise.resolve(item * 2) results.push(result) } expect(results).toEqual([2, 4, 6]) }) it('should handle parallel execution', async () => { const items = [1, 2, 3] const results = await Promise.all( items.map(item => Promise.resolve(item * 2)) ) expect(results).toEqual([2, 4, 6]) }) }) describe('Common Mistakes', () => { it('should demonstrate forgotten return issue', async () => { // This is what happens when you forget to return const result = await Promise.resolve('start') .then(value => { Promise.resolve(value + ' middle') // Forgot return! }) .then(value => value) expect(result).toBeUndefined() // Lost the value! }) it('should demonstrate correct return', async () => { const result = await Promise.resolve('start') .then(value => { return Promise.resolve(value + ' middle') // Correct! }) .then(value => value) expect(result).toBe('start middle') }) it('should demonstrate Promise constructor anti-pattern', async () => { // Anti-pattern: unnecessary wrapper const antiPattern = () => { return new Promise((resolve, reject) => { Promise.resolve('data') .then(data => resolve(data)) .catch(error => reject(error)) }) } // Correct: just return the Promise const correct = () => { return Promise.resolve('data') } // Both work, but correct is cleaner expect(await antiPattern()).toBe('data') expect(await correct()).toBe('data') }) }) describe('Error Handling Patterns', () => { it('should catch errors anywhere in the chain', async () => { const error = await Promise.resolve('start') .then(() => { throw new Error('middle error') }) .then(() => 'never reached') .catch(e => e.message) expect(error).toBe('middle error') }) it('should allow recovery from errors', async () => { const result = await Promise.reject(new Error('initial error')) .catch(() => 'recovered value') .then(value => value.toUpperCase()) expect(result).toBe('RECOVERED VALUE') }) it('should allow re-throwing errors', async () => { await expect( Promise.reject(new Error('original')) .catch(error => { // Log it, then re-throw throw error }) ).rejects.toThrow('original') }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/functions-execution/generators-iterators/generators-iterators.test.js
tests/functions-execution/generators-iterators/generators-iterators.test.js
import { describe, it, expect } from 'vitest' describe('Generators & Iterators', () => { describe('Basic Iterator Protocol', () => { it('should follow the iterator protocol with { value, done }', () => { function createIterator(arr) { let index = 0 return { next() { if (index < arr.length) { return { value: arr[index++], done: false } } return { value: undefined, done: true } } } } const iterator = createIterator([1, 2, 3]) expect(iterator.next()).toEqual({ value: 1, done: false }) expect(iterator.next()).toEqual({ value: 2, done: false }) expect(iterator.next()).toEqual({ value: 3, done: false }) expect(iterator.next()).toEqual({ value: undefined, done: true }) }) it('should allow accessing array iterator via Symbol.iterator', () => { const arr = [10, 20, 30] const iterator = arr[Symbol.iterator]() expect(iterator.next()).toEqual({ value: 10, done: false }) expect(iterator.next()).toEqual({ value: 20, done: false }) expect(iterator.next()).toEqual({ value: 30, done: false }) expect(iterator.next()).toEqual({ value: undefined, done: true }) }) }) describe('Basic Generator Syntax', () => { it('should create a generator function with function*', () => { function* simpleGenerator() { yield 1 yield 2 yield 3 } const gen = simpleGenerator() expect(gen.next()).toEqual({ value: 1, done: false }) expect(gen.next()).toEqual({ value: 2, done: false }) expect(gen.next()).toEqual({ value: 3, done: false }) expect(gen.next()).toEqual({ value: undefined, done: true }) }) it('should not execute until .next() is called', () => { let executed = false function* trackExecution() { executed = true yield 'done' } const gen = trackExecution() expect(executed).toBe(false) // Not executed yet! gen.next() expect(executed).toBe(true) // Now it's executed }) it('should work with for...of loops', () => { function* colors() { yield 'red' yield 'green' yield 'blue' } const result = [] for (const color of colors()) { result.push(color) } expect(result).toEqual(['red', 'green', 'blue']) }) it('should work with spread operator', () => { function* numbers() { yield 1 yield 2 yield 3 } expect([...numbers()]).toEqual([1, 2, 3]) }) }) describe('yield vs return', () => { it('should pause execution at yield and allow resuming', () => { const executionOrder = [] function* trackOrder() { executionOrder.push('before first yield') yield 'A' executionOrder.push('after first yield') yield 'B' executionOrder.push('after second yield') } const gen = trackOrder() expect(executionOrder).toEqual([]) gen.next() expect(executionOrder).toEqual(['before first yield']) gen.next() expect(executionOrder).toEqual(['before first yield', 'after first yield']) gen.next() expect(executionOrder).toEqual([ 'before first yield', 'after first yield', 'after second yield' ]) }) it('should mark done: true on return', () => { function* withReturn() { yield 'A' return 'B' yield 'C' // This never executes } const gen = withReturn() expect(gen.next()).toEqual({ value: 'A', done: false }) expect(gen.next()).toEqual({ value: 'B', done: true }) expect(gen.next()).toEqual({ value: undefined, done: true }) }) it('should NOT include return value in for...of', () => { function* withReturn() { yield 'A' yield 'B' return 'C' // Not included in iteration! } expect([...withReturn()]).toEqual(['A', 'B']) // No 'C'! }) }) describe('yield* delegation', () => { it('should delegate to another iterable', () => { function* inner() { yield 'a' yield 'b' } function* outer() { yield 1 yield* inner() yield 2 } expect([...outer()]).toEqual([1, 'a', 'b', 2]) }) it('should delegate to arrays', () => { function* withArray() { yield 'start' yield* [1, 2, 3] yield 'end' } expect([...withArray()]).toEqual(['start', 1, 2, 3, 'end']) }) it('should flatten nested arrays recursively', () => { function* flatten(arr) { for (const item of arr) { if (Array.isArray(item)) { yield* flatten(item) } else { yield item } } } const nested = [1, [2, 3, [4, 5]], 6] expect([...flatten(nested)]).toEqual([1, 2, 3, 4, 5, 6]) }) }) describe('Passing values to generators', () => { it('should receive values via .next(value)', () => { function* adder() { const a = yield 'Enter first number' const b = yield 'Enter second number' yield a + b } const gen = adder() expect(gen.next().value).toBe('Enter first number') expect(gen.next(10).value).toBe('Enter second number') expect(gen.next(5).value).toBe(15) }) it('should ignore value passed to first .next()', () => { function* capture() { const first = yield 'ready' yield first } const gen = capture() // First .next() value is ignored because no yield is waiting gen.next('IGNORED') expect(gen.next('captured').value).toBe('captured') }) }) describe('Symbol.iterator - Custom Iterables', () => { it('should make object iterable with Symbol.iterator', () => { const myCollection = { items: ['apple', 'banana', 'cherry'], [Symbol.iterator]() { let index = 0 const items = this.items return { next() { if (index < items.length) { return { value: items[index++], done: false } } return { value: undefined, done: true } } } } } expect([...myCollection]).toEqual(['apple', 'banana', 'cherry']) }) it('should make object iterable with generator', () => { const myCollection = { items: [1, 2, 3], *[Symbol.iterator]() { yield* this.items } } const result = [] for (const item of myCollection) { result.push(item) } expect(result).toEqual([1, 2, 3]) }) it('should create an iterable Range class', () => { class Range { constructor(start, end, step = 1) { this.start = start this.end = end this.step = step } *[Symbol.iterator]() { for (let i = this.start; i <= this.end; i += this.step) { yield i } } } expect([...new Range(1, 5)]).toEqual([1, 2, 3, 4, 5]) expect([...new Range(0, 10, 2)]).toEqual([0, 2, 4, 6, 8, 10]) expect([...new Range(5, 1)]).toEqual([]) // Empty when start > end }) }) describe('Lazy Evaluation', () => { it('should compute values on demand', () => { let computeCount = 0 function* lazyComputation() { while (true) { computeCount++ yield computeCount } } const gen = lazyComputation() expect(computeCount).toBe(0) // Nothing computed yet gen.next() expect(computeCount).toBe(1) gen.next() expect(computeCount).toBe(2) // Only computed twice, not infinitely }) it('should handle infinite sequences safely with take()', () => { function* naturalNumbers() { let n = 1 while (true) { yield n++ } } function* take(n, iterable) { let count = 0 for (const item of iterable) { if (count >= n) return yield item count++ } } expect([...take(5, naturalNumbers())]).toEqual([1, 2, 3, 4, 5]) }) it('should generate Fibonacci sequence lazily', () => { function* fibonacci() { let prev = 0 let curr = 1 while (true) { yield curr const next = prev + curr prev = curr curr = next } } function* take(n, iterable) { let count = 0 for (const item of iterable) { if (count >= n) return yield item count++ } } expect([...take(10, fibonacci())]).toEqual([ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ]) }) }) describe('Common Patterns', () => { it('should create a unique ID generator', () => { function* createIdGenerator(prefix = 'id') { let id = 1 while (true) { yield `${prefix}_${id++}` } } const userIds = createIdGenerator('user') const orderIds = createIdGenerator('order') expect(userIds.next().value).toBe('user_1') expect(userIds.next().value).toBe('user_2') expect(orderIds.next().value).toBe('order_1') expect(userIds.next().value).toBe('user_3') expect(orderIds.next().value).toBe('order_2') }) it('should chunk arrays into batches', () => { function* chunk(array, size) { for (let i = 0; i < array.length; i += size) { yield array.slice(i, i + size) } } const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] expect([...chunk(data, 3)]).toEqual([ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10] ]) }) it('should implement filter and map with generators', () => { function* filter(iterable, predicate) { for (const item of iterable) { if (predicate(item)) { yield item } } } function* map(iterable, transform) { for (const item of iterable) { yield transform(item) } } function* range(start, end) { for (let i = start; i <= end; i++) { yield i } } // Pipeline: 1-10 -> filter evens -> double them const result = map( filter(range(1, 10), n => n % 2 === 0), n => n * 2 ) expect([...result]).toEqual([4, 8, 12, 16, 20]) }) it('should implement a simple state machine', () => { function* trafficLight() { while (true) { yield 'green' yield 'yellow' yield 'red' } } const light = trafficLight() expect(light.next().value).toBe('green') expect(light.next().value).toBe('yellow') expect(light.next().value).toBe('red') expect(light.next().value).toBe('green') // Cycles back expect(light.next().value).toBe('yellow') }) it('should traverse a tree structure', () => { function* traverseTree(node) { yield node.value if (node.children) { for (const child of node.children) { yield* traverseTree(child) } } } const tree = { value: 'root', children: [ { value: 'child1', children: [{ value: 'grandchild1' }, { value: 'grandchild2' }] }, { value: 'child2', children: [{ value: 'grandchild3' }] } ] } expect([...traverseTree(tree)]).toEqual([ 'root', 'child1', 'grandchild1', 'grandchild2', 'child2', 'grandchild3' ]) }) }) describe('Async Generators', () => { it('should create async generators with async function*', async () => { async function* asyncNumbers() { yield await Promise.resolve(1) yield await Promise.resolve(2) yield await Promise.resolve(3) } const results = [] for await (const num of asyncNumbers()) { results.push(num) } expect(results).toEqual([1, 2, 3]) }) it('should handle delayed async values', async () => { const delay = ms => new Promise(resolve => setTimeout(resolve, ms)) async function* delayedNumbers() { await delay(10) yield 1 await delay(10) yield 2 await delay(10) yield 3 } const results = [] for await (const num of delayedNumbers()) { results.push(num) } expect(results).toEqual([1, 2, 3]) }) it('should simulate paginated API fetching', async () => { // Mock paginated data const mockPages = [ { items: ['a', 'b'], hasNextPage: true }, { items: ['c', 'd'], hasNextPage: true }, { items: ['e'], hasNextPage: false } ] async function* fetchAllPages() { let page = 0 let hasMore = true while (hasMore) { // Simulate API call const data = await Promise.resolve(mockPages[page]) yield data.items hasMore = data.hasNextPage page++ } } const allItems = [] for await (const pageItems of fetchAllPages()) { allItems.push(...pageItems) } expect(allItems).toEqual(['a', 'b', 'c', 'd', 'e']) }) }) describe('Generator Exhaustion', () => { it('should only be iterable once', () => { function* nums() { yield 1 yield 2 } const gen = nums() expect([...gen]).toEqual([1, 2]) expect([...gen]).toEqual([]) // Exhausted! }) it('should create fresh generator for each iteration', () => { function* nums() { yield 1 yield 2 } expect([...nums()]).toEqual([1, 2]) expect([...nums()]).toEqual([1, 2]) // Fresh generator each time }) }) describe('Error Handling', () => { it('should allow throwing errors into generator with .throw()', () => { function* gen() { try { yield 'A' yield 'B' } catch (e) { yield `Error: ${e.message}` } } const g = gen() expect(g.next().value).toBe('A') expect(g.throw(new Error('Something went wrong')).value).toBe( 'Error: Something went wrong' ) }) it('should allow early termination with .return()', () => { function* gen() { yield 1 yield 2 yield 3 } const g = gen() expect(g.next().value).toBe(1) expect(g.return('early exit')).toEqual({ value: 'early exit', done: true }) expect(g.next()).toEqual({ value: undefined, done: true }) }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/functions-execution/iife-modules/iife-modules.test.js
tests/functions-execution/iife-modules/iife-modules.test.js
import { describe, it, expect, vi } from 'vitest' describe('IIFE, Modules and Namespaces', () => { // =========================================== // Part 1: IIFE — The Self-Running Function // =========================================== describe('Part 1: IIFE — The Self-Running Function', () => { describe('What is an IIFE?', () => { it('should require calling a normal function manually', () => { let called = false function greet() { called = true } // Function is defined but not called yet expect(called).toBe(false) greet() // You have to call it expect(called).toBe(true) }) it('should run IIFE immediately without manual call', () => { let called = false // An IIFE — it runs immediately, no calling needed ;(function () { called = true })() // Runs right away! expect(called).toBe(true) }) it('should demonstrate IIFE executes during definition', () => { const results = [] results.push('before IIFE') ;(function () { results.push('inside IIFE') })() results.push('after IIFE') expect(results).toEqual(['before IIFE', 'inside IIFE', 'after IIFE']) }) }) describe('IIFE Variations', () => { it('should work with classic style', () => { let executed = false // Classic style ;(function () { executed = true })() expect(executed).toBe(true) }) it('should work with alternative parentheses placement', () => { let executed = false // Alternative parentheses placement ;(function () { executed = true })() expect(executed).toBe(true) }) it('should work with arrow function IIFE (modern)', () => { let executed = false // Arrow function IIFE (modern) ;(() => { executed = true })() expect(executed).toBe(true) }) it('should work with parameters', () => { let greeting = '' // With parameters ;((name) => { greeting = `Hello, ${name}!` })('Alice') expect(greeting).toBe('Hello, Alice!') }) it('should work with named IIFE (useful for debugging)', () => { let executed = false // Named IIFE (useful for debugging) ;(function myIIFE() { executed = true })() expect(executed).toBe(true) }) it('should allow named IIFE to call itself recursively', () => { const result = (function factorial(n) { if (n <= 1) return 1 return n * factorial(n - 1) })(5) expect(result).toBe(120) }) }) describe('Why Were IIFEs Invented? (Global Scope Problem)', () => { it('should demonstrate var variables can be overwritten in same scope', () => { // Simulating file1.js var userName = 'Alice' var count = 0 // Simulating file2.js (loaded after file1.js) var userName = 'Bob' // Overwrites the first userName var count = 100 // Overwrites the first count // Now file1.js's code is broken because its variables were replaced expect(userName).toBe('Bob') expect(count).toBe(100) }) it('should demonstrate IIFE creates private scope', () => { let file1UserName let file2UserName // file1.js — wrapped in an IIFE ;(function () { var userName = 'Alice' // Private to this IIFE file1UserName = userName })() // file2.js — also wrapped in an IIFE ;(function () { var userName = 'Bob' // Different variable, no conflict! file2UserName = userName })() expect(file1UserName).toBe('Alice') expect(file2UserName).toBe('Bob') }) it('should keep IIFE variables inaccessible from outside', () => { ;(function () { var privateVar = 'secret' // privateVar exists here expect(privateVar).toBe('secret') })() // privateVar is not accessible here expect(typeof privateVar).toBe('undefined') }) }) describe('Practical Example: Creating Private Variables (Module Pattern)', () => { it('should create counter with private state', () => { const counter = (function () { // Private variable — can't be accessed directly let count = 0 // Return public interface return { increment() { count++ }, decrement() { count-- }, getCount() { return count } } })() // Using the counter counter.increment() expect(counter.getCount()).toBe(1) counter.increment() expect(counter.getCount()).toBe(2) counter.decrement() expect(counter.getCount()).toBe(1) }) it('should keep count private (not accessible directly)', () => { const counter = (function () { let count = 0 return { increment() { count++ }, getCount() { return count } } })() counter.increment() counter.increment() // Trying to access private variables expect(counter.count).toBe(undefined) // it's private! }) it('should throw TypeError when calling non-existent private function', () => { const counter = (function () { let count = 0 // Private function — also hidden function log(message) { return `[Counter] ${message}` } return { increment() { count++ return log(`Incremented to ${count}`) }, getCount() { return count } } })() // Private log function works internally expect(counter.increment()).toBe('[Counter] Incremented to 1') // But not accessible from outside expect(counter.log).toBe(undefined) expect(() => counter.log('test')).toThrow(TypeError) }) it('should create multiple independent counter instances', () => { function createCounter() { let count = 0 return { increment() { count++ }, getCount() { return count } } } const counter1 = createCounter() const counter2 = createCounter() counter1.increment() counter1.increment() counter1.increment() counter2.increment() expect(counter1.getCount()).toBe(3) expect(counter2.getCount()).toBe(1) }) }) describe('IIFE with Parameters', () => { it('should pass parameters into IIFE', () => { const result = (function (a, b) { return a + b })(10, 20) expect(result).toBe(30) }) it('should create local aliases for global objects', () => { const globalObj = { name: 'Global' } const result = (function (obj) { // Inside here, obj is a local reference return obj.name })(globalObj) expect(result).toBe('Global') }) it('should preserve parameter values even if outer variable changes', () => { let value = 'original' const getOriginalValue = (function (capturedValue) { return function () { return capturedValue } })(value) value = 'changed' expect(getOriginalValue()).toBe('original') expect(value).toBe('changed') }) }) describe('When to Use IIFEs Today', () => { describe('One-time initialization code', () => { it('should create config object with computed values', () => { const config = (() => { const env = 'production' // simulating process.env.NODE_ENV const apiUrl = env === 'production' ? 'https://api.example.com' : 'http://localhost:3000' return { env, apiUrl } })() expect(config.env).toBe('production') expect(config.apiUrl).toBe('https://api.example.com') }) it('should use development URL when not in production', () => { const config = (() => { const env = 'development' const apiUrl = env === 'production' ? 'https://api.example.com' : 'http://localhost:3000' return { env, apiUrl } })() expect(config.env).toBe('development') expect(config.apiUrl).toBe('http://localhost:3000') }) }) describe('Creating async IIFEs', () => { it('should execute async IIFE', async () => { let result = null await (async () => { result = await Promise.resolve('data loaded') })() expect(result).toBe('data loaded') }) it('should handle async operations in IIFE', async () => { const data = await (async () => { const response = await Promise.resolve({ json: () => ({ id: 1, name: 'Test' }) }) return response.json() })() expect(data).toEqual({ id: 1, name: 'Test' }) }) }) }) }) // =========================================== // Part 2: Namespaces — Organizing Under One Name // =========================================== describe('Part 2: Namespaces — Organizing Under One Name', () => { describe('What is a Namespace?', () => { it('should demonstrate variables without namespace can conflict', () => { // Without namespace — variables everywhere var userName = 'Alice' var userAge = 25 // These could easily conflict with other code var userName = 'Bob' // Overwrites! expect(userName).toBe('Bob') }) it('should organize data under one namespace object', () => { // With namespace — everything organized under one name const User = { name: 'Alice', age: 25, email: 'alice@example.com', login() { return `${this.name} logged in` }, logout() { return `${this.name} logged out` } } // Access with the namespace prefix expect(User.name).toBe('Alice') expect(User.age).toBe(25) expect(User.login()).toBe('Alice logged in') expect(User.logout()).toBe('Alice logged out') }) }) describe('Creating a Namespace', () => { it('should create simple namespace and add properties', () => { // Simple namespace const MyApp = {} // Add things to it MyApp.version = '1.0.0' MyApp.config = { apiUrl: 'https://api.example.com', timeout: 5000 } expect(MyApp.version).toBe('1.0.0') expect(MyApp.config.apiUrl).toBe('https://api.example.com') expect(MyApp.config.timeout).toBe(5000) }) it('should add utility methods to namespace', () => { const MyApp = {} MyApp.utils = { formatDate(date) { return date.toLocaleDateString() }, capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1) } } expect(MyApp.utils.capitalize('hello')).toBe('Hello') expect(MyApp.utils.capitalize('world')).toBe('World') const testDate = new Date('2024-01-15') expect(typeof MyApp.utils.formatDate(testDate)).toBe('string') }) }) describe('Nested Namespaces', () => { it('should create nested namespace structure', () => { // Create the main namespace const MyApp = { // Nested namespaces Models: {}, Views: {}, Controllers: {}, Utils: {} } expect(MyApp.Models).toEqual({}) expect(MyApp.Views).toEqual({}) expect(MyApp.Controllers).toEqual({}) expect(MyApp.Utils).toEqual({}) }) it('should add functionality to nested namespaces', () => { const MyApp = { Models: {}, Views: {}, Utils: {} } // Add to nested namespaces MyApp.Models.User = { create(name) { return { name, id: Date.now() } }, find(id) { return { id, name: 'Found User' } } } MyApp.Views.UserList = { render(users) { return users.map((u) => u.name).join(', ') } } MyApp.Utils.Validation = { isEmail(str) { return str.includes('@') } } // Use nested namespaces const user = MyApp.Models.User.create('Alice') expect(user.name).toBe('Alice') expect(typeof user.id).toBe('number') const found = MyApp.Models.User.find(123) expect(found.id).toBe(123) const rendered = MyApp.Views.UserList.render([{ name: 'Alice' }, { name: 'Bob' }]) expect(rendered).toBe('Alice, Bob') expect(MyApp.Utils.Validation.isEmail('test@example.com')).toBe(true) expect(MyApp.Utils.Validation.isEmail('invalid')).toBe(false) }) }) describe('Combining Namespaces with IIFEs', () => { it('should create namespace with IIFE for private variables', () => { const MyApp = {} // Use IIFE to add features with private variables MyApp.Counter = (function () { // Private let count = 0 // Public return { increment() { count++ }, decrement() { count-- }, getCount() { return count } } })() MyApp.Counter.increment() MyApp.Counter.increment() expect(MyApp.Counter.getCount()).toBe(2) MyApp.Counter.decrement() expect(MyApp.Counter.getCount()).toBe(1) // Private count is not accessible expect(MyApp.Counter.count).toBe(undefined) }) it('should create Logger with private logs array', () => { const MyApp = {} MyApp.Logger = (function () { // Private const logs = [] // Public return { log(message) { logs.push({ message, time: new Date() }) return message // Return for testing }, getLogs() { return [...logs] // Return a copy }, getLogCount() { return logs.length } } })() MyApp.Logger.log('First message') MyApp.Logger.log('Second message') expect(MyApp.Logger.getLogCount()).toBe(2) const allLogs = MyApp.Logger.getLogs() expect(allLogs[0].message).toBe('First message') expect(allLogs[1].message).toBe('Second message') // Returned array is a copy, modifying it doesn't affect internal logs allLogs.push({ message: 'Fake log' }) expect(MyApp.Logger.getLogCount()).toBe(2) }) it('should combine Counter and Logger in same namespace', () => { const MyApp = {} MyApp.Counter = (function () { let count = 0 return { increment() { count++ return count }, getCount() { return count } } })() MyApp.Logger = (function () { const logs = [] return { log(message) { logs.push(message) }, getLogs() { return [...logs] } } })() // Usage const newCount = MyApp.Counter.increment() MyApp.Logger.log(`Counter incremented to ${newCount}`) expect(MyApp.Counter.getCount()).toBe(1) expect(MyApp.Logger.getLogs()).toEqual(['Counter incremented to 1']) }) }) }) // =========================================== // Part 3: ES6 Modules — The Modern Solution (Patterns) // =========================================== describe('Part 3: ES6 Modules — Pattern Testing', () => { describe('Named Export Patterns', () => { it('should test function that would be named export', () => { // These functions would be: export function add(a, b) { ... } function add(a, b) { return a + b } function subtract(a, b) { return a - b } const PI = 3.14159 expect(add(2, 3)).toBe(5) expect(subtract(10, 4)).toBe(6) expect(PI).toBe(3.14159) }) it('should test square and cube functions', () => { // export function square(x) { return x * x; } function square(x) { return x * x } // function cube(x) { return x * x * x; } // export { cube }; function cube(x) { return x * x * x } expect(square(4)).toBe(16) expect(square(5)).toBe(25) expect(cube(3)).toBe(27) expect(cube(4)).toBe(64) }) it('should test Calculator class', () => { // export class Calculator { ... } class Calculator { add(a, b) { return a + b } subtract(a, b) { return a - b } multiply(a, b) { return a * b } divide(a, b) { return a / b } } const calc = new Calculator() expect(calc.add(5, 3)).toBe(8) expect(calc.subtract(10, 4)).toBe(6) expect(calc.multiply(3, 4)).toBe(12) expect(calc.divide(20, 5)).toBe(4) }) it('should test math constants', () => { const PI = 3.14159 const E = 2.71828 expect(PI).toBeCloseTo(3.14159, 5) expect(E).toBeCloseTo(2.71828, 5) }) }) describe('Default Export Patterns', () => { it('should test greet function (default export pattern)', () => { // export default function greet(name) { ... } function greet(name) { return `Hello, ${name}!` } expect(greet('World')).toBe('Hello, World!') expect(greet('Alice')).toBe('Hello, Alice!') }) it('should test User class (default export pattern)', () => { // export default class User { ... } class User { constructor(name) { this.name = name } greet() { return `Hi, I'm ${this.name}` } } const user = new User('Alice') expect(user.name).toBe('Alice') expect(user.greet()).toBe("Hi, I'm Alice") const bob = new User('Bob') expect(bob.greet()).toBe("Hi, I'm Bob") }) }) describe('Module Privacy Pattern', () => { it('should demonstrate unexported variables are private', () => { // In a real module: // let currentUser = null; // Private to this module // export function login() { currentUser = ... } // export function getCurrentUser() { return currentUser } // Simulating with closure const authModule = (function () { let currentUser = null // Private to this module return { login(email) { currentUser = { email, loggedInAt: new Date() } return currentUser }, getCurrentUser() { return currentUser }, logout() { currentUser = null } } })() expect(authModule.getCurrentUser()).toBe(null) authModule.login('user@example.com') expect(authModule.getCurrentUser().email).toBe('user@example.com') authModule.logout() expect(authModule.getCurrentUser()).toBe(null) // currentUser is not directly accessible expect(authModule.currentUser).toBe(undefined) }) }) describe('Re-export Pattern (Barrel Files)', () => { it('should demonstrate re-export concept', () => { // utils/format.js const formatModule = { formatDate(date) { return date.toLocaleDateString() }, formatCurrency(amount) { return `$${amount.toFixed(2)}` } } // utils/validate.js const validateModule = { isEmail(str) { return str.includes('@') }, isPhone(str) { return /^\d{10}$/.test(str) } } // utils/index.js — re-exports everything const Utils = { ...formatModule, ...validateModule } expect(Utils.formatCurrency(19.99)).toBe('$19.99') expect(Utils.isEmail('test@example.com')).toBe(true) expect(Utils.isPhone('1234567890')).toBe(true) expect(Utils.isPhone('123')).toBe(false) }) }) }) // =========================================== // The Evolution: From IIFEs to Modules // =========================================== describe('The Evolution: From IIFEs to Modules', () => { describe('Era 1: Global (Bad)', () => { it('should demonstrate global variable problem', () => { // Everything pollutes global scope var counter = 0 function increment() { counter++ } function getCount() { return counter } increment() expect(getCount()).toBe(1) // Problem: Anyone can do this counter = 999 // Oops, state corrupted! expect(getCount()).toBe(999) }) }) describe('Era 2: IIFE (Better)', () => { it('should demonstrate IIFE protects state', () => { // Uses closure to hide counter var Counter = (function () { var counter = 0 // Private! return { increment: function () { counter++ }, getCount: function () { return counter } } })() Counter.increment() expect(Counter.getCount()).toBe(1) expect(Counter.counter).toBe(undefined) // private! }) it('should prevent external modification of private state', () => { var Counter = (function () { var counter = 0 return { increment: function () { counter++ }, getCount: function () { return counter } } })() Counter.increment() Counter.increment() Counter.increment() // Cannot directly set counter Counter.counter = 999 expect(Counter.getCount()).toBe(3) // Still 3, not 999! }) }) describe('Era 3: ES6 Modules (Best) - Pattern', () => { it('should demonstrate module pattern (simulated)', () => { // Simulating: // counter.js // let counter = 0; // Private (not exported) // export function increment() { counter++; } // export function getCount() { return counter; } const counterModule = (function () { let counter = 0 // Private (not exported) return { increment() { counter++ }, getCount() { return counter } } })() // Simulating: import { increment, getCount } from './counter.js'; const { increment, getCount } = counterModule increment() expect(getCount()).toBe(1) // counter variable is not accessible at all expect(counterModule.counter).toBe(undefined) }) }) }) // =========================================== // Common Patterns and Best Practices // =========================================== describe('Common Patterns and Best Practices', () => { describe('Avoid Circular Dependencies', () => { it('should demonstrate shared module pattern to avoid circular deps', () => { // Instead of A importing B and B importing A... // Create a third module for shared code // shared.js const sharedModule = { sharedThing: 'shared', helperFunction() { return 'helper result' } } // a.js - imports from shared const moduleA = { fromA: 'A', useShared() { return sharedModule.sharedThing } } // b.js - also imports from shared const moduleB = { fromB: 'B', useShared() { return sharedModule.sharedThing } } // No circular dependency! expect(moduleA.useShared()).toBe('shared') expect(moduleB.useShared()).toBe('shared') }) }) }) // =========================================== // Test Your Knowledge Examples // =========================================== describe('Test Your Knowledge Examples', () => { describe('Question 1: What does IIFE stand for?', () => { it('should demonstrate Immediately Invoked Function Expression', () => { const results = [] // Immediately - runs right now // Invoked - called/executed // Function Expression - a function written as an expression results.push('before') ;(function () { results.push('immediately invoked') })() results.push('after') expect(results).toEqual(['before', 'immediately invoked', 'after']) }) }) describe('Question 3: How to create private variable in IIFE?', () => { it('should create private variable inside IIFE', () => { const module = (function () { // Private variable let privateCounter = 0 // Return public methods that can access it return { increment() { privateCounter++ }, getCount() { return privateCounter } } })() module.increment() expect(module.getCount()).toBe(1) expect(module.privateCounter).toBe(undefined) // private! }) }) describe('Question 4: Static vs Dynamic imports', () => { it('should demonstrate dynamic import returns a Promise', async () => { // Dynamic imports return Promises // const module = await import('./module.js') // Simulating dynamic import behavior const dynamicImport = () => Promise.resolve({ default: function () { return 'loaded' }, namedExport: 'value' }) const module = await dynamicImport() expect(module.default()).toBe('loaded') expect(module.namedExport).toBe('value') }) }) describe('Question 6: When to use IIFE today', () => { it('should use IIFE for async initialization', async () => { let data = null await (async () => { data = await Promise.resolve({ loaded: true }) })() expect(data).toEqual({ loaded: true }) }) it('should use IIFE for one-time calculations', () => { const config = (() => { // Complex setup that runs once const computed = 2 + 2 return { computed, ready: true } })() expect(config.computed).toBe(4) expect(config.ready).toBe(true) }) }) }) // =========================================== // Additional Edge Cases // =========================================== describe('Edge Cases and Additional Tests', () => { describe('IIFE Return Values', () => { it('should return primitive values from IIFE', () => { const number = (function () { return 42 })() const string = (function () { return 'hello' })() const boolean = (function () { return true })() expect(number).toBe(42) expect(string).toBe('hello') expect(boolean).toBe(true) }) it('should return undefined when no return statement', () => { const result = (function () { const x = 1 + 1 // no return })() expect(result).toBe(undefined) }) it('should return arrays and objects from IIFE', () => { const arr = (function () { return [1, 2, 3] })() const obj = (function () { return { a: 1, b: 2 } })() expect(arr).toEqual([1, 2, 3]) expect(obj).toEqual({ a: 1, b: 2 }) }) }) describe('Nested IIFEs', () => { it('should support nested IIFEs', () => { const result = (function () { const outer = 'outer' return (function () { const inner = 'inner' return outer + '-' + inner })() })() expect(result).toBe('outer-inner') }) }) describe('IIFE with this context', () => { it('should demonstrate arrow IIFE inherits this from enclosing scope', () => { // Arrow functions don't have their own this binding // They inherit this from the enclosing lexical scope const obj = { name: 'TestObject', getThisArrow: (() => { // In module scope, this may be undefined or global depending on environment return typeof this })(), getNameWithRegular: function() { return (function() { // Regular function IIFE in strict mode has undefined this return this })() } } // Arrow IIFE inherits this from module scope (not the object) expect(typeof obj.getThisArrow).toBe('string') // Regular function IIFE called without context has undefined this in strict mode expect(obj.getNameWithRegular()).toBe(undefined) }) it('should show regular function IIFE has undefined this in strict mode', () => { const result = (function() { 'use strict' return this })() expect(result).toBe(undefined) }) }) describe('Namespace Extension', () => { it('should extend existing namespace safely', () => { // Create or extend namespace const MyApp = {} // Safely extend (pattern used in large apps) MyApp.Utils = MyApp.Utils || {} MyApp.Utils.String = MyApp.Utils.String || {} MyApp.Utils.String.reverse = function (str) { return str.split('').reverse().join('') } expect(MyApp.Utils.String.reverse('hello')).toBe('olleh') // Extend again without overwriting MyApp.Utils.String = MyApp.Utils.String || {} MyApp.Utils.String.uppercase = function (str) { return str.toUpperCase() } // Both functions exist expect(MyApp.Utils.String.reverse('test')).toBe('tset') expect(MyApp.Utils.String.uppercase('test')).toBe('TEST') }) }) describe('Closure over Loop Variables', () => { it('should demonstrate IIFE fixing var loop problem', () => { const funcs = [] for (var i = 0; i < 3; i++) { ;(function (j) { funcs.push(function () { return j }) })(i) } expect(funcs[0]()).toBe(0) expect(funcs[1]()).toBe(1) expect(funcs[2]()).toBe(2) }) it('should show problem without IIFE', () => { const funcs = [] for (var i = 0; i < 3; i++) { funcs.push(function () { return i }) } // All return 3 because they share the same i expect(funcs[0]()).toBe(3) expect(funcs[1]()).toBe(3) expect(funcs[2]()).toBe(3) }) }) describe('Module Pattern Variations', () => { it('should implement revealing module pattern', () => { const RevealingModule = (function () { // Private variables and functions let privateVar = 'private' let publicVar = 'public' function privateFunction() { return privateVar }
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
true
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/fundamentals/primitive-types/primitive-types.test.js
tests/fundamentals/primitive-types/primitive-types.test.js
import { describe, it, expect } from 'vitest' describe('Primitive Types', () => { describe('String', () => { it('should create strings with single quotes, double quotes, and backticks', () => { let single = 'Hello' let double = "World" let backtick = `Hello World` expect(single).toBe('Hello') expect(double).toBe('World') expect(backtick).toBe('Hello World') }) it('should support template literal interpolation', () => { let name = "Alice" let age = 25 let greeting = `Hello, ${name}! You are ${age} years old.` expect(greeting).toBe("Hello, Alice! You are 25 years old.") }) it('should support multi-line strings with template literals', () => { let multiLine = ` This is line 1 This is line 2 ` expect(multiLine).toContain('This is line 1') expect(multiLine).toContain('This is line 2') }) it('should demonstrate string immutability - cannot change characters', () => { let str = "hello" // In strict mode, this throws TypeError // In non-strict mode, it silently fails expect(() => { "use strict" str[0] = "H" }).toThrow(TypeError) expect(str).toBe("hello") // Still "hello" }) it('should create new string when "changing" with concatenation', () => { let str = "hello" str = "H" + str.slice(1) expect(str).toBe("Hello") }) it('should not modify original string with toUpperCase', () => { let name = "Alice" name.toUpperCase() // Creates "ALICE" but doesn't change 'name' expect(name).toBe("Alice") // Still "Alice" }) }) describe('Number', () => { it('should handle integers, decimals, negatives, and scientific notation', () => { let integer = 42 let decimal = 3.14 let negative = -10 let scientific = 2.5e6 expect(integer).toBe(42) expect(decimal).toBe(3.14) expect(negative).toBe(-10) expect(scientific).toBe(2500000) }) it('should return Infinity for division by zero', () => { expect(1 / 0).toBe(Infinity) expect(-1 / 0).toBe(-Infinity) }) it('should return NaN for invalid operations', () => { expect(Number.isNaN("hello" * 2)).toBe(true) }) it('should demonstrate floating-point precision problem', () => { expect(0.1 + 0.2).not.toBe(0.3) expect(0.1 + 0.2).toBeCloseTo(0.3) expect(0.1 + 0.2 === 0.3).toBe(false) }) it('should have MAX_SAFE_INTEGER and MIN_SAFE_INTEGER', () => { expect(Number.MAX_SAFE_INTEGER).toBe(9007199254740991) expect(Number.MIN_SAFE_INTEGER).toBe(-9007199254740991) }) it('should lose precision beyond safe integer range', () => { // This demonstrates the precision loss expect(9007199254740992 === 9007199254740993).toBe(true) // Wrong but expected }) }) describe('BigInt', () => { it('should create BigInt with n suffix', () => { let big = 9007199254740993n expect(big).toBe(9007199254740993n) }) it('should create BigInt from string', () => { let alsoBig = BigInt("9007199254740993") expect(alsoBig).toBe(9007199254740993n) }) it('should perform accurate math with BigInt', () => { let big = 9007199254740993n expect(big + 1n).toBe(9007199254740994n) }) it('should require explicit conversion between BigInt and Number', () => { let big = 10n let regular = 5 expect(big + BigInt(regular)).toBe(15n) expect(Number(big) + regular).toBe(15) }) it('should throw TypeError when mixing BigInt and Number without conversion', () => { let big = 10n let regular = 5 expect(() => big + regular).toThrow(TypeError) }) }) describe('Boolean', () => { it('should have only two values: true and false', () => { let isLoggedIn = true let hasPermission = false expect(isLoggedIn).toBe(true) expect(hasPermission).toBe(false) }) it('should create boolean from comparisons', () => { let age = 25 let name = "Alice" let isAdult = age >= 18 let isEqual = name === "Alice" expect(isAdult).toBe(true) expect(isEqual).toBe(true) }) describe('Falsy Values', () => { it('should identify all 8 falsy values', () => { expect(Boolean(false)).toBe(false) expect(Boolean(0)).toBe(false) expect(Boolean(-0)).toBe(false) expect(Boolean(0n)).toBe(false) expect(Boolean("")).toBe(false) expect(Boolean(null)).toBe(false) expect(Boolean(undefined)).toBe(false) expect(Boolean(NaN)).toBe(false) }) }) describe('Truthy Values', () => { it('should identify truthy values including surprises', () => { expect(Boolean(true)).toBe(true) expect(Boolean(1)).toBe(true) expect(Boolean(-1)).toBe(true) expect(Boolean("hello")).toBe(true) expect(Boolean("0")).toBe(true) // Non-empty string is truthy! expect(Boolean("false")).toBe(true) // Non-empty string is truthy! expect(Boolean([])).toBe(true) // Empty array is truthy! expect(Boolean({})).toBe(true) // Empty object is truthy! expect(Boolean(function(){})).toBe(true) expect(Boolean(Infinity)).toBe(true) expect(Boolean(-Infinity)).toBe(true) }) }) it('should convert to boolean using Boolean() and double negation', () => { let value = "hello" let bool = Boolean(value) let shortcut = !!value expect(bool).toBe(true) expect(shortcut).toBe(true) }) }) describe('undefined', () => { it('should be the default value for uninitialized variables', () => { let x expect(x).toBe(undefined) }) it('should be the value for missing function parameters', () => { function greet(name) { return name } expect(greet()).toBe(undefined) }) it('should be the return value of functions without return statement', () => { function doNothing() { // no return } expect(doNothing()).toBe(undefined) }) it('should be the value for non-existent object properties', () => { let person = { name: "Alice" } expect(person.age).toBe(undefined) }) }) describe('null', () => { it('should represent intentional absence of value', () => { let user = { name: "Alice" } user = null expect(user).toBe(null) }) it('should be used to indicate no result from functions', () => { function findUser(id) { // Simulating user not found return null } expect(findUser(999)).toBe(null) }) it('should have typeof return "object" (famous bug)', () => { expect(typeof null).toBe("object") }) it('should be checked with strict equality', () => { let value = null expect(value === null).toBe(true) }) }) describe('Symbol', () => { it('should create unique symbols even with same description', () => { let id1 = Symbol("id") let id2 = Symbol("id") expect(id1 === id2).toBe(false) }) it('should have accessible description', () => { let id1 = Symbol("id") expect(id1.description).toBe("id") }) it('should work as unique object keys', () => { const ID = Symbol("id") const user = { name: "Alice", [ID]: 12345 } expect(user.name).toBe("Alice") expect(user[ID]).toBe(12345) }) it('should not appear in Object.keys', () => { const ID = Symbol("id") const user = { name: "Alice", [ID]: 12345 } expect(Object.keys(user)).toEqual(["name"]) }) }) describe('typeof Operator', () => { it('should return correct types for primitives', () => { expect(typeof "hello").toBe("string") expect(typeof 42).toBe("number") expect(typeof 42n).toBe("bigint") expect(typeof true).toBe("boolean") expect(typeof undefined).toBe("undefined") expect(typeof Symbol()).toBe("symbol") }) it('should return "object" for null (bug)', () => { expect(typeof null).toBe("object") }) it('should return "object" for objects and arrays', () => { expect(typeof {}).toBe("object") expect(typeof []).toBe("object") }) it('should return "function" for functions', () => { expect(typeof function(){}).toBe("function") }) }) describe('Immutability', () => { it('should not modify original string with methods', () => { let str = "hello" str.toUpperCase() // Returns "HELLO" expect(str).toBe("hello") // Still "hello"! }) it('should require reassignment to capture new value', () => { let str = "hello" str = str.toUpperCase() expect(str).toBe("HELLO") }) }) describe('const vs Immutability', () => { it('should prevent reassignment with const', () => { const name = "Alice" // name = "Bob" would throw TypeError expect(name).toBe("Alice") }) it('should allow mutation of const objects', () => { const person = { name: "Alice" } person.name = "Bob" // Works! person.age = 25 // Works! expect(person.name).toBe("Bob") expect(person.age).toBe(25) }) it('should demonstrate primitives are immutable regardless of const/let', () => { let str = "hello" // In strict mode (which Vitest uses), this throws TypeError // In non-strict mode, it silently fails expect(() => { str[0] = "H" }).toThrow(TypeError) expect(str).toBe("hello") }) }) describe('Autoboxing', () => { it('should allow calling methods on primitive strings', () => { expect("hello".toUpperCase()).toBe("HELLO") }) it('should not modify the original primitive when calling methods', () => { let str = "hello" str.toUpperCase() expect(str).toBe("hello") }) it('should demonstrate wrapper objects are different from primitives', () => { let strObj = new String("hello") expect(typeof strObj).toBe("object") // Not "string"! expect(strObj === "hello").toBe(false) // Object vs primitive }) it('should create primitive strings, not wrapper objects', () => { let str = "hello" expect(typeof str).toBe("string") }) }) describe('null vs undefined Comparison', () => { it('should show loose equality between null and undefined', () => { expect(null == undefined).toBe(true) }) it('should show strict inequality between null and undefined', () => { expect(null === undefined).toBe(false) }) it('should demonstrate checking for nullish values', () => { let value = null expect(value == null).toBe(true) value = undefined expect(value == null).toBe(true) }) it('should check for specific null', () => { let value = null expect(value === null).toBe(true) }) it('should check for specific undefined', () => { let value = undefined expect(value === undefined).toBe(true) }) it('should check for "has a value" (not null/undefined)', () => { let value = "hello" expect(value != null).toBe(true) value = 0 // 0 is a value, not nullish expect(value != null).toBe(true) }) }) describe('JavaScript Quirks', () => { it('should demonstrate NaN is not equal to itself', () => { expect(NaN === NaN).toBe(false) expect(NaN !== NaN).toBe(true) }) it('should use Number.isNaN to check for NaN', () => { expect(Number.isNaN(NaN)).toBe(true) expect(Number.isNaN("hello")).toBe(false) expect(isNaN("hello")).toBe(true) // Has quirks }) it('should demonstrate empty string is falsy but whitespace is truthy', () => { expect(Boolean("")).toBe(false) expect(Boolean(" ")).toBe(true) expect(Boolean("0")).toBe(true) }) it('should demonstrate + operator string concatenation', () => { expect(1 + 2).toBe(3) expect("1" + "2").toBe("12") expect(1 + "2").toBe("12") expect("1" + 2).toBe("12") expect(1 + 2 + "3").toBe("33") expect("1" + 2 + 3).toBe("123") }) it('should force number addition with explicit conversion', () => { expect(Number("1") + Number("2")).toBe(3) expect(parseInt("1") + parseInt("2")).toBe(3) }) it('should force string concatenation with explicit conversion', () => { expect(String(1) + String(2)).toBe("12") expect(`${1}${2}`).toBe("12") }) }) describe('Type Checking Best Practices', () => { it('should check for null explicitly', () => { let value = null expect(value === null).toBe(true) }) it('should use Array.isArray for arrays', () => { expect(Array.isArray([1, 2, 3])).toBe(true) expect(Array.isArray("hello")).toBe(false) }) it('should use Object.prototype.toString for precise type', () => { expect(Object.prototype.toString.call(null)).toBe("[object Null]") expect(Object.prototype.toString.call([])).toBe("[object Array]") expect(Object.prototype.toString.call(new Date())).toBe("[object Date]") }) }) describe('Intl.NumberFormat for Currency', () => { it('should format currency correctly with Intl.NumberFormat', () => { const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', }) expect(formatter.format(0.30)).toBe("$0.30") expect(formatter.format(19.99)).toBe("$19.99") expect(formatter.format(1000)).toBe("$1,000.00") }) it('should handle different locales', () => { const euroFormatter = new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR', }) // German locale uses comma for decimal and period for thousands expect(euroFormatter.format(1234.56)).toContain("1.234,56") }) }) describe('Floating-Point Solutions', () => { it('should use Number.EPSILON for floating-point comparison', () => { const result = 0.1 + 0.2 const expected = 0.3 // Using epsilon comparison for floating-point expect(Math.abs(result - expected) < Number.EPSILON).toBe(true) }) it('should use toFixed for rounding display', () => { expect((0.1 + 0.2).toFixed(2)).toBe("0.30") expect((0.1 + 0.2).toFixed(1)).toBe("0.3") }) it('should use integers (cents) for precise money calculations', () => { // Instead of 0.1 + 0.2, use cents const price1 = 10 // 10 cents const price2 = 20 // 20 cents const total = price1 + price2 expect(total).toBe(30) // Exactly 30 cents expect(total / 100).toBe(0.3) // $0.30 }) }) describe('Array Holes', () => { it('should return undefined for array holes', () => { let arr = [1, , 3] // Sparse array with hole at index 1 expect(arr[0]).toBe(1) expect(arr[1]).toBe(undefined) expect(arr[2]).toBe(3) expect(arr.length).toBe(3) }) it('should skip holes in forEach but include in map', () => { let arr = [1, , 3] let forEachCount = 0 let mapResult arr.forEach(() => forEachCount++) mapResult = arr.map(x => x * 2) expect(forEachCount).toBe(2) // Holes are skipped expect(mapResult).toEqual([2, undefined, 6]) // Hole becomes undefined in map result }) }) describe('String Trim for Empty/Whitespace Check', () => { it('should use trim to check for empty or whitespace-only strings', () => { expect("".trim() === "").toBe(true) expect(" ".trim() === "").toBe(true) expect("\t\n".trim() === "").toBe(true) expect("hello".trim() === "").toBe(false) expect(" hello ".trim() === "").toBe(false) }) it('should use trim with length check for validation', () => { function isEmptyOrWhitespace(str) { return str.trim().length === 0 } expect(isEmptyOrWhitespace("")).toBe(true) expect(isEmptyOrWhitespace(" ")).toBe(true) expect(isEmptyOrWhitespace("hello")).toBe(false) }) }) describe('null vs undefined Patterns', () => { it('should demonstrate clearing with null vs undefined', () => { let user = { name: "Alice" } // Clear intentionally with null user = null expect(user).toBe(null) }) it('should show function returning null for no result', () => { function findUser(id) { const users = [{ id: 1, name: "Alice" }] return users.find(u => u.id === id) || null } expect(findUser(1)).toEqual({ id: 1, name: "Alice" }) expect(findUser(999)).toBe(null) }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/fundamentals/scope-and-closures/scope-and-closures.test.js
tests/fundamentals/scope-and-closures/scope-and-closures.test.js
import { describe, it, expect } from 'vitest' describe('Scope and Closures', () => { describe('Scope Basics', () => { describe('Preventing Naming Conflicts', () => { it('should keep variables separate in different functions', () => { function countApples() { let count = 0 count++ return count } function countOranges() { let count = 0 count++ return count } expect(countApples()).toBe(1) expect(countOranges()).toBe(1) }) }) describe('Memory Management', () => { it('should demonstrate scope cleanup concept', () => { function processData() { let hugeArray = new Array(1000).fill('x') return hugeArray.length } // hugeArray can be garbage collected after function returns expect(processData()).toBe(1000) }) }) describe('Encapsulation', () => { it('should hide implementation details', () => { function createBankAccount() { let balance = 0 return { deposit(amount) { balance += amount }, getBalance() { return balance } } } const account = createBankAccount() account.deposit(100) expect(account.getBalance()).toBe(100) // balance is private - cannot access directly }) }) }) describe('The Three Types of Scope', () => { describe('Global Scope', () => { it('should access global variables from anywhere', () => { const appName = "MyApp" let userCount = 0 function greet() { userCount++ return appName } expect(greet()).toBe("MyApp") expect(userCount).toBe(1) }) }) describe('Function Scope', () => { it('should keep var variables within function', () => { function calculateTotal() { var subtotal = 100 var tax = 10 var total = subtotal + tax return total } expect(calculateTotal()).toBe(110) // subtotal, tax, total are not accessible here }) describe('var Hoisting', () => { it('should demonstrate var hoisting behavior', () => { function example() { const first = message // undefined (not an error!) var message = "Hello" const second = message // "Hello" return { first, second } } const result = example() expect(result.first).toBe(undefined) expect(result.second).toBe("Hello") }) }) }) describe('Block Scope', () => { it('should keep let and const within blocks', () => { let outsideBlock = "outside" if (true) { let blockLet = "I'm block-scoped" const blockConst = "Me too" var functionVar = "I escape the block!" outsideBlock = blockLet // Can access from inside } expect(functionVar).toBe("I escape the block!") expect(outsideBlock).toBe("I'm block-scoped") // blockLet and blockConst are not accessible here }) describe('Temporal Dead Zone', () => { it('should throw ReferenceError when accessing let before declaration', () => { function demo() { // TDZ for 'name' starts here const getName = () => name // This creates closure over TDZ variable let name = "Alice" // TDZ ends here return name } expect(demo()).toBe("Alice") }) it('should demonstrate proper let declaration', () => { function demo() { let name = "Alice" return name } expect(demo()).toBe("Alice") }) }) }) }) describe('var vs let vs const', () => { describe('Redeclaration', () => { it('should allow var redeclaration', () => { var name = "Alice" var name = "Bob" // No error, silently overwrites expect(name).toBe("Bob") }) // Note: let and const redeclaration would cause SyntaxError // which cannot be tested at runtime }) describe('Reassignment', () => { it('should allow var and let reassignment', () => { var count = 1 count = 2 expect(count).toBe(2) let score = 100 score = 200 expect(score).toBe(200) }) it('should allow const object mutation but not reassignment', () => { const user = { name: "Alice" } user.name = "Bob" // Works! user.age = 25 // Works! expect(user.name).toBe("Bob") expect(user.age).toBe(25) // user = {} would throw TypeError }) }) describe('The Classic for-loop Problem', () => { it('should demonstrate var problem with setTimeout', async () => { const results = [] // Using var - only ONE i variable shared for (var i = 0; i < 3; i++) { // Capture current value using IIFE ((j) => { setTimeout(() => { results.push(j) }, 10) })(i) } await new Promise(resolve => setTimeout(resolve, 50)) expect(results.sort()).toEqual([0, 1, 2]) }) it('should demonstrate let solution with setTimeout', async () => { const results = [] // Using let - each iteration gets its OWN i variable for (let i = 0; i < 3; i++) { setTimeout(() => { results.push(i) }, 10) } await new Promise(resolve => setTimeout(resolve, 50)) expect(results.sort()).toEqual([0, 1, 2]) }) }) }) describe('Lexical Scope', () => { it('should access variables from outer scopes', () => { const outer = "I'm outside!" function outerFunction() { const middle = "I'm in the middle!" function innerFunction() { const inner = "I'm inside!" return { inner, middle, outer } } return innerFunction() } const result = outerFunction() expect(result.inner).toBe("I'm inside!") expect(result.middle).toBe("I'm in the middle!") expect(result.outer).toBe("I'm outside!") }) describe('Scope Chain', () => { it('should walk up the scope chain to find variables', () => { const x = "global" function outer() { const x = "outer" function inner() { // Looks for x in inner scope first (not found) // Then looks in outer scope (found!) return x } return inner() } expect(outer()).toBe("outer") }) }) describe('Variable Shadowing', () => { it('should shadow outer variables with inner declarations', () => { const name = "Global" function greet() { const name = "Function" // Shadows global 'name' function inner() { const name = "Block" // Shadows function 'name' return name } return { inner: inner(), outer: name } } const result = greet() expect(result.inner).toBe("Block") expect(result.outer).toBe("Function") expect(name).toBe("Global") }) }) }) describe('Closures', () => { describe('Basic Closure', () => { it('should remember variables from outer scope', () => { function createGreeter(greeting) { return function(name) { return `${greeting}, ${name}!` } } const sayHello = createGreeter("Hello") const sayHola = createGreeter("Hola") expect(sayHello("Alice")).toBe("Hello, Alice!") expect(sayHola("Bob")).toBe("Hola, Bob!") }) }) describe('Data Privacy & Encapsulation', () => { it('should create truly private variables', () => { function createCounter() { let count = 0 // Private variable! return { increment() { count++ return count }, decrement() { count-- return count }, getCount() { return count } } } const counter = createCounter() expect(counter.getCount()).toBe(0) expect(counter.increment()).toBe(1) expect(counter.increment()).toBe(2) expect(counter.decrement()).toBe(1) expect(counter.count).toBe(undefined) // Cannot access directly! }) }) describe('Function Factories', () => { it('should create specialized functions', () => { function createMultiplier(multiplier) { return function(number) { return number * multiplier } } const double = createMultiplier(2) const triple = createMultiplier(3) const tenX = createMultiplier(10) expect(double(5)).toBe(10) expect(triple(5)).toBe(15) expect(tenX(5)).toBe(50) }) it('should create API clients with base URL', () => { function createApiClient(baseUrl) { return { getUrl(endpoint) { return `${baseUrl}${endpoint}` } } } const githubApi = createApiClient('https://api.github.com') const myApi = createApiClient('https://myapp.com/api') expect(githubApi.getUrl('/users')).toBe('https://api.github.com/users') expect(myApi.getUrl('/users')).toBe('https://myapp.com/api/users') }) }) describe('Preserving State in Callbacks', () => { it('should maintain state across multiple calls', () => { function setupClickCounter() { let clicks = 0 return function handleClick() { clicks++ return clicks } } const handleClick = setupClickCounter() expect(handleClick()).toBe(1) expect(handleClick()).toBe(2) expect(handleClick()).toBe(3) }) }) describe('Memoization', () => { it('should cache expensive computation results', () => { function createMemoizedFunction(fn) { const cache = {} return function(arg) { if (arg in cache) { return { value: cache[arg], cached: true } } const result = fn(arg) cache[arg] = result return { value: result, cached: false } } } function factorial(n) { if (n <= 1) return 1 return n * factorial(n - 1) } const memoizedFactorial = createMemoizedFunction(factorial) const first = memoizedFactorial(5) expect(first.value).toBe(120) expect(first.cached).toBe(false) const second = memoizedFactorial(5) expect(second.value).toBe(120) expect(second.cached).toBe(true) }) }) }) describe('The Classic Closure Trap', () => { describe('The Problem with var in Loops', () => { it('should demonstrate the problem', () => { const funcs = [] for (var i = 0; i < 3; i++) { funcs.push(function() { return i }) } // All functions return 3 because they share the same 'i' expect(funcs[0]()).toBe(3) expect(funcs[1]()).toBe(3) expect(funcs[2]()).toBe(3) }) }) describe('Solution 1: Use let', () => { it('should create new binding per iteration', () => { const funcs = [] for (let i = 0; i < 3; i++) { funcs.push(function() { return i }) } expect(funcs[0]()).toBe(0) expect(funcs[1]()).toBe(1) expect(funcs[2]()).toBe(2) }) }) describe('Solution 2: IIFE', () => { it('should capture value in IIFE scope', () => { const funcs = [] for (var i = 0; i < 3; i++) { (function(j) { funcs.push(function() { return j }) })(i) } expect(funcs[0]()).toBe(0) expect(funcs[1]()).toBe(1) expect(funcs[2]()).toBe(2) }) }) describe('Solution 3: forEach', () => { it('should create new scope per iteration', () => { const funcs = [] ;[0, 1, 2].forEach(function(i) { funcs.push(function() { return i }) }) expect(funcs[0]()).toBe(0) expect(funcs[1]()).toBe(1) expect(funcs[2]()).toBe(2) }) }) }) describe('Closure Memory Considerations', () => { it('should demonstrate closure keeping references alive', () => { function createClosure() { const data = { value: 42 } return function() { return data.value } } const getClosure = createClosure() // data is kept alive because getClosure references it expect(getClosure()).toBe(42) }) it('should demonstrate cleanup with null assignment', () => { function createHandler() { let largeData = new Array(100).fill('data') const handler = function() { return largeData.length } return { handler, cleanup() { largeData = null // Allow garbage collection } } } const { handler, cleanup } = createHandler() expect(handler()).toBe(100) cleanup() // Now largeData can be garbage collected }) }) describe('Practical Closure Patterns', () => { describe('Private State Pattern', () => { it('should create objects with private state', () => { function createWallet(initial) { let balance = initial return { spend(amount) { if (amount <= balance) { balance -= amount return true } return false }, getBalance() { return balance } } } const wallet = createWallet(100) expect(wallet.getBalance()).toBe(100) expect(wallet.spend(30)).toBe(true) expect(wallet.getBalance()).toBe(70) expect(wallet.spend(100)).toBe(false) expect(wallet.getBalance()).toBe(70) }) }) describe('Tax Calculator Factory', () => { it('should create specialized tax calculators', () => { function createTaxCalculator(rate) { return (amount) => amount * rate } const calculateVAT = createTaxCalculator(0.20) const calculateGST = createTaxCalculator(0.10) expect(calculateVAT(100)).toBe(20) expect(calculateGST(100)).toBe(10) }) }) describe('Logger Factory', () => { it('should create prefixed loggers', () => { function setupLogger(prefix) { return (message) => `[${prefix}] ${message}` } const errorLogger = setupLogger('ERROR') const infoLogger = setupLogger('INFO') expect(errorLogger('Something went wrong')).toBe('[ERROR] Something went wrong') expect(infoLogger('All good')).toBe('[INFO] All good') }) }) describe('Memoize Pattern', () => { it('should cache results with closures', () => { function memoize(fn) { const cache = {} return (arg) => cache[arg] ?? (cache[arg] = fn(arg)) } let callCount = 0 const expensive = (n) => { callCount++ return n * n } const memoizedExpensive = memoize(expensive) expect(memoizedExpensive(5)).toBe(25) expect(callCount).toBe(1) expect(memoizedExpensive(5)).toBe(25) expect(callCount).toBe(1) // Still 1, used cache expect(memoizedExpensive(6)).toBe(36) expect(callCount).toBe(2) }) }) }) describe('Test Your Knowledge Examples', () => { it('should identify all three scope types', () => { const globalVar = "everywhere" // Global scope function example() { var functionScoped = "function" // Function scope if (true) { let blockScoped = "block" // Block scope expect(blockScoped).toBe("block") } expect(functionScoped).toBe("function") } example() expect(globalVar).toBe("everywhere") }) it('should demonstrate closure definition', () => { function createCounter() { let count = 0 return function() { count++ return count } } const counter = createCounter() expect(counter()).toBe(1) expect(counter()).toBe(2) }) it('should show var loop outputs 3,3,3 pattern', () => { const results = [] for (var i = 0; i < 3; i++) { results.push(() => i) } expect(results[0]()).toBe(3) expect(results[1]()).toBe(3) expect(results[2]()).toBe(3) }) it('should show let loop outputs 0,1,2 pattern', () => { const results = [] for (let i = 0; i < 3; i++) { results.push(() => i) } expect(results[0]()).toBe(0) expect(results[1]()).toBe(1) expect(results[2]()).toBe(2) }) }) describe('Temporal Dead Zone (TDZ)', () => { it('should throw ReferenceError when accessing let before declaration', () => { expect(() => { // Using eval to avoid syntax errors at parse time eval(` const before = x let x = 10 `) }).toThrow(ReferenceError) }) it('should throw ReferenceError when accessing const before declaration', () => { expect(() => { eval(` const before = y const y = 10 `) }).toThrow(ReferenceError) }) it('should demonstrate TDZ exists from block start to declaration', () => { let outsideValue = "outside" expect(() => { eval(` { // TDZ starts here for 'name' const beforeDeclaration = name // ReferenceError let name = "Alice" } `) }).toThrow(ReferenceError) }) it('should not throw for var due to hoisting', () => { // var is hoisted with undefined value, so no TDZ function example() { const before = message // undefined, not an error var message = "Hello" const after = message // "Hello" return { before, after } } const result = example() expect(result.before).toBe(undefined) expect(result.after).toBe("Hello") }) it('should have TDZ in function parameters', () => { // Default parameters can reference earlier parameters but not later ones expect(() => { eval(` function test(a = b, b = 2) { return a + b } test() `) }).toThrow(ReferenceError) }) it('should allow later parameters to reference earlier ones', () => { function test(a = 1, b = a + 1) { return a + b } expect(test()).toBe(3) // a=1, b=2 expect(test(5)).toBe(11) // a=5, b=6 expect(test(5, 10)).toBe(15) // a=5, b=10 }) }) describe('Hoisting Comparison: var vs let/const', () => { it('should demonstrate var hoisting without TDZ', () => { function example() { // var is hoisted and initialized to undefined expect(a).toBe(undefined) var a = 1 expect(a).toBe(1) } example() }) it('should demonstrate function declarations are fully hoisted', () => { // Function can be called before its declaration expect(hoistedFn()).toBe("I was hoisted!") function hoistedFn() { return "I was hoisted!" } }) it('should demonstrate function expressions are not hoisted', () => { expect(() => { eval(` notHoisted() var notHoisted = function() { return "Not hoisted" } `) }).toThrow(TypeError) }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/fundamentals/type-coercion/type-coercion.test.js
tests/fundamentals/type-coercion/type-coercion.test.js
import { describe, it, expect } from 'vitest' describe('Type Coercion', () => { describe('Explicit vs Implicit Coercion', () => { describe('Explicit Coercion', () => { it('should convert to number explicitly', () => { expect(Number("42")).toBe(42) expect(parseInt("42px")).toBe(42) expect(parseFloat("3.14")).toBe(3.14) }) it('should convert to string explicitly', () => { expect(String(42)).toBe("42") expect((123).toString()).toBe("123") }) it('should convert to boolean explicitly', () => { expect(Boolean(1)).toBe(true) expect(Boolean(0)).toBe(false) }) }) describe('Implicit Coercion', () => { it('should demonstrate implicit string coercion with +', () => { expect("5" + 3).toBe("53") expect("5" - 3).toBe(2) }) it('should demonstrate implicit boolean coercion in conditions', () => { let result = null if ("hello") { result = "truthy" } expect(result).toBe("truthy") }) it('should demonstrate loose equality coercion', () => { expect(5 == "5").toBe(true) }) }) }) describe('String Conversion', () => { it('should convert various types to string explicitly', () => { expect(String(123)).toBe("123") expect(String(true)).toBe("true") expect(String(false)).toBe("false") expect(String(null)).toBe("null") expect(String(undefined)).toBe("undefined") }) it('should convert to string implicitly with + and empty string', () => { expect(123 + "").toBe("123") expect(`Value: ${123}`).toBe("Value: 123") expect("Hello " + 123).toBe("Hello 123") }) it('should convert arrays to comma-separated strings', () => { expect([1, 2, 3].toString()).toBe("1,2,3") expect([1, 2, 3] + "").toBe("1,2,3") expect([].toString()).toBe("") }) it('should convert objects to [object Object]', () => { expect({}.toString()).toBe("[object Object]") expect({} + "").toBe("[object Object]") }) describe('The + Operator Split Personality', () => { it('should add two numbers', () => { expect(5 + 3).toBe(8) }) it('should concatenate with any string involved', () => { expect("5" + 3).toBe("53") expect(5 + "3").toBe("53") expect("Hello" + " World").toBe("Hello World") }) it('should evaluate left to right with multiple operands', () => { expect(1 + 2 + "3").toBe("33") // (1+2)=3, then 3+"3"="33" expect("1" + 2 + 3).toBe("123") // all become strings left-to-right }) }) describe('User Input Gotcha', () => { it('should demonstrate string concatenation instead of addition', () => { const userInput = "5" const wrongResult = userInput + 10 expect(wrongResult).toBe("510") const correctResult = Number(userInput) + 10 expect(correctResult).toBe(15) }) }) }) describe('Number Conversion', () => { it('should convert strings to numbers', () => { expect(Number("42")).toBe(42) expect(Number(" 123 ")).toBe(123) // Whitespace trimmed expect(Number.isNaN(Number("123abc"))).toBe(true) // NaN expect(Number("")).toBe(0) // Empty string → 0 expect(Number(" ")).toBe(0) // Whitespace-only → 0 }) it('should convert booleans to numbers', () => { expect(Number(true)).toBe(1) expect(Number(false)).toBe(0) }) it('should demonstrate null vs undefined conversion difference', () => { expect(Number(null)).toBe(0) expect(Number.isNaN(Number(undefined))).toBe(true) expect(null + 5).toBe(5) expect(Number.isNaN(undefined + 5)).toBe(true) }) it('should convert arrays to numbers', () => { expect(Number([])).toBe(0) // [] → "" → 0 expect(Number([1])).toBe(1) // [1] → "1" → 1 expect(Number.isNaN(Number([1, 2]))).toBe(true) // [1,2] → "1,2" → NaN }) it('should return NaN for objects', () => { expect(Number.isNaN(Number({}))).toBe(true) }) describe('Math Operators Always Convert to Numbers', () => { it('should convert operands to numbers for -, *, /, %', () => { expect("6" - "2").toBe(4) expect("6" * "2").toBe(12) expect("6" / "2").toBe(3) expect("10" % "3").toBe(1) }) it('should show why - and + behave differently', () => { expect("5" + 3).toBe("53") // concatenation expect("5" - 3).toBe(2) // math }) }) describe('Unary + Trick', () => { it('should convert to number with unary +', () => { expect(+"42").toBe(42) expect(+true).toBe(1) expect(+false).toBe(0) expect(+null).toBe(0) expect(Number.isNaN(+undefined)).toBe(true) expect(Number.isNaN(+"hello")).toBe(true) expect(+"").toBe(0) }) }) }) describe('Boolean Conversion', () => { describe('The 8 Falsy Values', () => { it('should identify all 8 falsy values', () => { expect(Boolean(false)).toBe(false) expect(Boolean(0)).toBe(false) expect(Boolean(-0)).toBe(false) expect(Boolean(0n)).toBe(false) expect(Boolean("")).toBe(false) expect(Boolean(null)).toBe(false) expect(Boolean(undefined)).toBe(false) expect(Boolean(NaN)).toBe(false) }) }) describe('Truthy Values', () => { it('should identify truthy values including surprises', () => { expect(Boolean(true)).toBe(true) expect(Boolean(1)).toBe(true) expect(Boolean(-1)).toBe(true) expect(Boolean("hello")).toBe(true) expect(Boolean("0")).toBe(true) // Non-empty string! expect(Boolean("false")).toBe(true) // Non-empty string! expect(Boolean([])).toBe(true) // Empty array! expect(Boolean({})).toBe(true) // Empty object! expect(Boolean(function(){})).toBe(true) expect(Boolean(new Date())).toBe(true) expect(Boolean(Infinity)).toBe(true) expect(Boolean(-Infinity)).toBe(true) }) }) describe('Common Gotchas', () => { it('should demonstrate empty array checking', () => { const arr = [] expect(Boolean(arr)).toBe(true) // Array itself is truthy expect(arr.length > 0).toBe(false) // Check length instead }) }) describe('Logical Operators Return Original Values', () => { it('should return first truthy value with ||', () => { expect("hello" || "world").toBe("hello") expect("" || "world").toBe("world") expect("" || 0 || null || "yes").toBe("yes") }) it('should return first falsy value with &&', () => { expect("hello" && "world").toBe("world") expect("" && "world").toBe("") expect(1 && 2 && 3).toBe(3) }) it('should use || for defaults', () => { const userInput = "" const name = userInput || "Anonymous" expect(name).toBe("Anonymous") }) }) }) describe('Object to Primitive Conversion', () => { describe('Built-in Object Conversion', () => { it('should convert arrays via toString', () => { expect([1, 2, 3].toString()).toBe("1,2,3") expect([1, 2, 3] + "").toBe("1,2,3") expect(Number.isNaN([1, 2, 3] - 0)).toBe(true) // "1,2,3" → NaN expect([].toString()).toBe("") expect([] + "").toBe("") expect([] - 0).toBe(0) // "" → 0 expect([1].toString()).toBe("1") expect([1] - 0).toBe(1) }) it('should convert plain objects to [object Object]', () => { expect({}.toString()).toBe("[object Object]") expect({} + "").toBe("[object Object]") }) }) describe('Custom valueOf and toString', () => { it('should use valueOf for number conversion', () => { const price = { amount: 99.99, currency: "USD", valueOf() { return this.amount }, toString() { return `${this.currency} ${this.amount}` } } expect(price - 0).toBe(99.99) expect(price * 2).toBe(199.98) expect(+price).toBe(99.99) }) it('should use toString for string conversion', () => { const price = { amount: 99.99, currency: "USD", valueOf() { return this.amount }, toString() { return `${this.currency} ${this.amount}` } } expect(String(price)).toBe("USD 99.99") expect(`Price: ${price}`).toBe("Price: USD 99.99") }) }) describe('Symbol.toPrimitive', () => { it('should use Symbol.toPrimitive for conversion hints', () => { const obj = { [Symbol.toPrimitive](hint) { if (hint === "number") { return 42 } if (hint === "string") { return "forty-two" } return "default value" } } expect(+obj).toBe(42) // hint: "number" expect(`${obj}`).toBe("forty-two") // hint: "string" expect(obj + "").toBe("default value") // hint: "default" }) }) }) describe('The == Algorithm', () => { describe('Same Type Comparison', () => { it('should compare directly when same type', () => { expect(5 == 5).toBe(true) expect("hello" == "hello").toBe(true) }) }) describe('null and undefined', () => { it('should return true for null == undefined', () => { expect(null == undefined).toBe(true) expect(undefined == null).toBe(true) }) it('should return false for null/undefined vs other values', () => { expect(null == 0).toBe(false) expect(null == "").toBe(false) expect(undefined == 0).toBe(false) expect(undefined == "").toBe(false) }) }) describe('Number and String', () => { it('should convert string to number', () => { expect(5 == "5").toBe(true) expect(0 == "").toBe(true) expect(42 == "42").toBe(true) }) }) describe('Boolean Conversion', () => { it('should convert boolean to number first', () => { expect(true == 1).toBe(true) expect(false == 0).toBe(true) expect(true == "1").toBe(true) }) it('should demonstrate confusing boolean comparisons', () => { expect(true == "true").toBe(false) // true → 1, "true" → NaN expect(false == "false").toBe(false) // false → 0, "false" → NaN expect(true == 2).toBe(false) // true → 1, 1 ≠ 2 }) }) describe('Object to Primitive', () => { it('should convert object to primitive', () => { expect([1] == 1).toBe(true) // [1] → "1" → 1 expect([""] == 0).toBe(true) // [""] → "" → 0 }) }) describe('Step-by-Step Examples', () => { it('should trace "5" == 5', () => { // String vs Number → convert string to number // 5 == 5 → true expect("5" == 5).toBe(true) }) it('should trace true == "1"', () => { // Boolean → number: 1 == "1" // Number vs String → 1 == 1 // true expect(true == "1").toBe(true) }) it('should trace [] == false', () => { // Boolean → number: [] == 0 // Object → primitive: "" == 0 // String → number: 0 == 0 // true expect([] == false).toBe(true) }) it('should trace [] == ![]', () => { // First, evaluate ![] → false (arrays are truthy) // [] == false // Boolean → number: [] == 0 // Object → primitive: "" == 0 // String → number: 0 == 0 // true! expect([] == ![]).toBe(true) }) }) }) describe('JavaScript WAT Moments', () => { describe('+ Operator Split Personality', () => { it('should show string vs number behavior', () => { expect("5" + 3).toBe("53") expect("5" - 3).toBe(2) }) }) describe('Empty Array Weirdness', () => { it('should demonstrate [] + [] behavior', () => { expect([] + []).toBe("") // Both → "", then "" + "" = "" }) it('should demonstrate [] + {} behavior', () => { expect([] + {}).toBe("[object Object]") }) }) describe('Boolean Math', () => { it('should add booleans as numbers', () => { expect(true + true).toBe(2) expect(true + false).toBe(1) expect(true - true).toBe(0) }) }) describe('The Infamous [] == ![]', () => { it('should return true for [] == ![]', () => { const emptyArr = [] const negatedArr = ![] expect(emptyArr == negatedArr).toBe(true) expect(emptyArr === negatedArr).toBe(false) }) }) describe('"foo" + + "bar"', () => { it('should return "fooNaN"', () => { // +"bar" is evaluated first → NaN // "foo" + NaN → "fooNaN" expect("foo" + + "bar").toBe("fooNaN") }) }) describe('NaN Equality', () => { it('should never equal itself', () => { expect(NaN === NaN).toBe(false) expect(NaN == NaN).toBe(false) }) it('should use Number.isNaN to check', () => { expect(Number.isNaN(NaN)).toBe(true) expect(isNaN(NaN)).toBe(true) expect(isNaN("hello")).toBe(true) // Quirk: converts first expect(Number.isNaN("hello")).toBe(false) // Correct }) }) describe('typeof Quirks', () => { it('should demonstrate typeof oddities', () => { expect(typeof NaN).toBe("number") // "Not a Number" is a number expect(typeof null).toBe("object") // Historical bug expect(typeof []).toBe("object") // Arrays are objects expect(typeof function(){}).toBe("function") // Special case }) }) describe('Adding Arrays', () => { it('should concatenate arrays as strings', () => { expect([1, 2] + [3, 4]).toBe("1,23,4") // [1, 2] → "1,2" // [3, 4] → "3,4" // "1,2" + "3,4" → "1,23,4" }) it('should use spread or concat to combine arrays', () => { expect([...[1, 2], ...[3, 4]]).toEqual([1, 2, 3, 4]) expect([1, 2].concat([3, 4])).toEqual([1, 2, 3, 4]) }) }) }) describe('Best Practices', () => { describe('Use === instead of ==', () => { it('should show predictable strict equality', () => { expect(5 === "5").toBe(false) // No coercion expect(5 == "5").toBe(true) // Coerced }) }) describe('When == IS Useful', () => { it('should check for null or undefined in one shot', () => { function checkNullish(value) { return value == null } expect(checkNullish(null)).toBe(true) expect(checkNullish(undefined)).toBe(true) expect(checkNullish(0)).toBe(false) expect(checkNullish("")).toBe(false) }) }) describe('Be Explicit with Conversions', () => { it('should convert explicitly for clarity', () => { const str = "42" // Quick string conversion expect(str + "").toBe("42") expect(String(42)).toBe("42") // Quick number conversion expect(+str).toBe(42) expect(Number(str)).toBe(42) }) }) }) describe('Test Your Knowledge Examples', () => { it('should return "53" for "5" + 3', () => { expect("5" + 3).toBe("53") }) it('should return "1hello" for true + false + "hello"', () => { // true + false = 1 + 0 = 1 // 1 + "hello" = "1hello" expect(true + false + "hello").toBe("1hello") }) }) describe('Modulo Operator with Strings', () => { it('should coerce strings to numbers for modulo', () => { expect("6" % 4).toBe(2) expect("10" % "3").toBe(1) expect(17 % "5").toBe(2) }) it('should return NaN for non-numeric strings', () => { expect(Number.isNaN("hello" % 2)).toBe(true) expect(Number.isNaN(10 % "abc")).toBe(true) }) }) describe('Comparison Operators with Coercion', () => { it('should coerce strings to numbers in comparisons', () => { expect("10" > 5).toBe(true) expect("10" < 5).toBe(false) expect("10" >= 10).toBe(true) expect("10" <= 10).toBe(true) }) it('should compare strings lexicographically when both are strings', () => { // String comparison (lexicographic, not numeric) expect("10" > "9").toBe(false) // "1" < "9" in char codes expect("2" > "10").toBe(true) // "2" > "1" in char codes }) it('should coerce null and undefined in comparisons', () => { expect(null >= 0).toBe(true) // null coerces to 0 expect(null > 0).toBe(false) expect(null == 0).toBe(false) // Special case! // undefined always returns false in comparisons expect(undefined > 0).toBe(false) expect(undefined < 0).toBe(false) expect(undefined >= 0).toBe(false) }) }) describe('Double Negation (!!)', () => { it('should convert values to boolean with !!', () => { // Truthy values expect(!!"hello").toBe(true) expect(!!1).toBe(true) expect(!!{}).toBe(true) expect(!![]).toBe(true) expect(!!-1).toBe(true) // Falsy values expect(!!"").toBe(false) expect(!!0).toBe(false) expect(!!null).toBe(false) expect(!!undefined).toBe(false) expect(!!NaN).toBe(false) }) it('should be equivalent to Boolean()', () => { const values = ["hello", "", 0, 1, null, undefined, {}, []] values.forEach(value => { expect(!!value).toBe(Boolean(value)) }) }) }) describe('Date Coercion', () => { it('should coerce Date to number (timestamp) with + operator', () => { const date = new Date("2025-01-01T00:00:00.000Z") const timestamp = +date expect(typeof timestamp).toBe("number") expect(timestamp).toBe(date.getTime()) }) it('should coerce Date to string with String()', () => { const date = new Date("2025-06-15T12:00:00.000Z") const str = String(date) expect(typeof str).toBe("string") // Use a mid-year date to avoid timezone edge cases expect(str).toContain("2025") }) it('should prefer string coercion with + operator and string', () => { const date = new Date("2025-06-15T12:00:00.000Z") const result = "Date: " + date expect(typeof result).toBe("string") expect(result).toContain("Date:") expect(result).toContain("2025") }) it('should use valueOf for numeric context', () => { const date = new Date("2025-01-01T00:00:00.000Z") // In numeric context, Date uses valueOf (returns timestamp) expect(date - 0).toBe(date.getTime()) expect(date * 1).toBe(date.getTime()) }) }) describe('Implicit Boolean Contexts', () => { it('should coerce to boolean in if statements', () => { let result = "" if ("hello") result += "truthy string " if (0) result += "zero " if ([]) result += "empty array " if ({}) result += "empty object " expect(result).toBe("truthy string empty array empty object ") }) it('should coerce to boolean in ternary operator', () => { expect("hello" ? "yes" : "no").toBe("yes") expect("" ? "yes" : "no").toBe("no") expect(0 ? "yes" : "no").toBe("no") expect(1 ? "yes" : "no").toBe("yes") }) it('should coerce to boolean in logical NOT', () => { expect(!0).toBe(true) expect(!"").toBe(true) expect(!null).toBe(true) expect(!"hello").toBe(false) expect(!1).toBe(false) }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/fundamentals/equality-operators/equality-operators.test.js
tests/fundamentals/equality-operators/equality-operators.test.js
import { describe, it, expect } from 'vitest' describe('Equality and Type Checking', () => { describe('Three Equality Operators Overview', () => { it('should demonstrate different results for same comparison', () => { const num = 1 const str = "1" expect(num == str).toBe(true) // coerces string to number expect(num === str).toBe(false) // different types expect(Object.is(num, str)).toBe(false) // different types }) }) describe('Loose Equality (==)', () => { describe('Same Type Comparison', () => { it('should compare directly when same type', () => { expect(5 == 5).toBe(true) expect("hello" == "hello").toBe(true) }) }) describe('null and undefined', () => { it('should return true for null == undefined', () => { expect(null == undefined).toBe(true) expect(undefined == null).toBe(true) }) }) describe('Number and String', () => { it('should convert string to number', () => { expect(5 == "5").toBe(true) expect(0 == "").toBe(true) expect(100 == "1e2").toBe(true) }) it('should return false for different string comparison', () => { expect("" == "0").toBe(false) // Both strings, different values }) it('should handle NaN conversions', () => { expect(NaN == "NaN").toBe(false) // NaN ≠ anything expect(0 == "hello").toBe(false) // "hello" → NaN }) }) describe('BigInt and String', () => { it('should convert string to BigInt', () => { expect(10n == "10").toBe(true) }) }) describe('Boolean Coercion', () => { it('should convert boolean to number first', () => { expect(true == 1).toBe(true) expect(false == 0).toBe(true) expect(true == "1").toBe(true) expect(false == "").toBe(true) }) it('should demonstrate confusing boolean comparisons', () => { expect(true == "true").toBe(false) // true → 1, "true" → NaN expect(false == "false").toBe(false) // false → 0, "false" → NaN expect(true == 2).toBe(false) // true → 1, 1 ≠ 2 expect(true == "2").toBe(false) // true → 1, "2" → 2 }) }) describe('Object to Primitive', () => { it('should convert object via ToPrimitive', () => { expect([1] == 1).toBe(true) // [1] → "1" → 1 expect([""] == 0).toBe(true) // [""] → "" → 0 }) }) describe('BigInt and Number', () => { it('should compare mathematical values', () => { expect(10n == 10).toBe(true) expect(10n == 10.5).toBe(false) }) }) describe('Special Cases', () => { it('should return false for null/undefined vs other values', () => { expect(null == 0).toBe(false) expect(undefined == 0).toBe(false) expect(Symbol() == Symbol()).toBe(false) }) }) describe('Surprising Results', () => { describe('String and Number', () => { it('should demonstrate string to number conversions', () => { expect(1 == "1").toBe(true) expect(0 == "").toBe(true) expect(0 == "0").toBe(true) expect(100 == "1e2").toBe(true) }) }) describe('null and undefined', () => { it('should demonstrate special null/undefined behavior', () => { expect(null == undefined).toBe(true) expect(null == 0).toBe(false) expect(null == false).toBe(false) expect(null == "").toBe(false) expect(undefined == 0).toBe(false) expect(undefined == false).toBe(false) }) it('should catch both null and undefined with == null', () => { function greet(name) { if (name == null) { return "Hello, stranger!" } return `Hello, ${name}!` } expect(greet(null)).toBe("Hello, stranger!") expect(greet(undefined)).toBe("Hello, stranger!") expect(greet("Alice")).toBe("Hello, Alice!") expect(greet("")).toBe("Hello, !") expect(greet(0)).toBe("Hello, 0!") }) }) describe('Arrays and Objects', () => { it('should convert arrays via ToPrimitive', () => { expect([] == false).toBe(true) expect([] == 0).toBe(true) expect([] == "").toBe(true) expect([1] == 1).toBe(true) expect([1] == "1").toBe(true) expect([1, 2] == "1,2").toBe(true) }) it('should use valueOf on objects with custom valueOf', () => { let obj = { valueOf: () => 42 } expect(obj == 42).toBe(true) }) }) }) describe('Step-by-Step Trace: [] == ![]', () => { it('should demonstrate [] == ![] is true', () => { // Step 1: Evaluate ![] // [] is truthy, so ![] = false const step1 = ![] expect(step1).toBe(false) // Step 2: Now we have [] == false // Boolean → Number: false → 0 // [] == 0 // Step 3: Object → Primitive // [].toString() → "" // "" == 0 // Step 4: String → Number // "" → 0 // 0 == 0 → true const emptyArray = [] expect(emptyArray == step1).toBe(true) }) }) }) describe('Strict Equality (===)', () => { describe('Type Check', () => { it('should return false for different types immediately', () => { expect(1 === "1").toBe(false) expect(true === 1).toBe(false) expect(null === undefined).toBe(false) }) }) describe('Number Comparison', () => { it('should compare numeric values', () => { expect(42 === 42).toBe(true) expect(Infinity === Infinity).toBe(true) }) it('should return false for NaN === NaN', () => { expect(NaN === NaN).toBe(false) }) it('should return true for +0 === -0', () => { expect(+0 === -0).toBe(true) }) }) describe('String Comparison', () => { it('should compare string characters', () => { expect("hello" === "hello").toBe(true) expect("hello" === "Hello").toBe(false) // Case sensitive expect("hello" === "hello ").toBe(false) // Different length }) }) describe('Boolean Comparison', () => { it('should compare boolean values', () => { expect(true === true).toBe(true) expect(false === false).toBe(true) expect(true === false).toBe(false) }) }) describe('BigInt Comparison', () => { it('should compare BigInt values', () => { expect(10n === 10n).toBe(true) expect(10n === 20n).toBe(false) }) }) describe('Symbol Comparison', () => { it('should return false for different symbols', () => { const sym = Symbol("id") expect(sym === sym).toBe(true) expect(Symbol("id") === Symbol("id")).toBe(false) }) }) describe('Object Comparison (Reference)', () => { it('should compare by reference, not value', () => { const obj = { a: 1 } expect(obj === obj).toBe(true) const obj1 = { a: 1 } const obj2 = { a: 1 } expect(obj1 === obj2).toBe(false) // Different objects! }) it('should return false for different arrays', () => { const arr1 = [1, 2, 3] const arr2 = [1, 2, 3] const arr3 = arr1 expect(arr1 === arr2).toBe(false) expect(arr1 === arr3).toBe(true) }) it('should return false for different functions', () => { const fn1 = () => {} const fn2 = () => {} const fn3 = fn1 expect(fn1 === fn2).toBe(false) expect(fn1 === fn3).toBe(true) }) }) describe('null and undefined', () => { it('should compare null and undefined correctly', () => { expect(null === null).toBe(true) expect(undefined === undefined).toBe(true) expect(null === undefined).toBe(false) }) }) describe('Predictable Results', () => { it('should return false for different types', () => { expect(1 === "1").toBe(false) expect(0 === "").toBe(false) expect(true === 1).toBe(false) expect(false === 0).toBe(false) expect(null === undefined).toBe(false) }) it('should return true for same type and value', () => { expect(1 === 1).toBe(true) expect("hello" === "hello").toBe(true) expect(true === true).toBe(true) expect(null === null).toBe(true) expect(undefined === undefined).toBe(true) }) }) describe('Special Cases: NaN and ±0', () => { it('should demonstrate NaN !== NaN', () => { expect(NaN === NaN).toBe(false) expect(Number.isNaN(NaN)).toBe(true) expect(isNaN(NaN)).toBe(true) expect(isNaN("hello")).toBe(true) // Converts to NaN first expect(Number.isNaN("hello")).toBe(false) // No conversion }) it('should demonstrate +0 === -0', () => { expect(+0 === -0).toBe(true) expect(1 / +0).toBe(Infinity) expect(1 / -0).toBe(-Infinity) expect(Object.is(+0, -0)).toBe(false) }) it('should detect -0', () => { expect(0 * -1).toBe(-0) expect(Object.is(0 * -1, -0)).toBe(true) }) }) }) describe('Object.is()', () => { describe('Comparison with ===', () => { it('should behave like === for most cases', () => { expect(Object.is(1, 1)).toBe(true) expect(Object.is("a", "a")).toBe(true) expect(Object.is(null, null)).toBe(true) const obj1 = {} const obj2 = {} expect(Object.is(obj1, obj2)).toBe(false) }) }) describe('NaN Equality', () => { it('should return true for NaN === NaN', () => { expect(Object.is(NaN, NaN)).toBe(true) }) }) describe('±0 Distinction', () => { it('should distinguish +0 from -0', () => { expect(Object.is(+0, -0)).toBe(false) expect(Object.is(-0, 0)).toBe(false) }) }) describe('Practical Uses', () => { it('should check for NaN', () => { function isReallyNaN(value) { return Object.is(value, NaN) } expect(isReallyNaN(NaN)).toBe(true) expect(isReallyNaN("hello")).toBe(false) }) it('should check for negative zero', () => { function isNegativeZero(value) { return Object.is(value, -0) } expect(isNegativeZero(-0)).toBe(true) expect(isNegativeZero(0)).toBe(false) }) }) describe('Complete Comparison Table', () => { it('should show differences between ==, ===, and Object.is()', () => { // 1, "1" expect(1 == "1").toBe(true) expect(1 === "1").toBe(false) expect(Object.is(1, "1")).toBe(false) // 0, false expect(0 == false).toBe(true) expect(0 === false).toBe(false) expect(Object.is(0, false)).toBe(false) // null, undefined expect(null == undefined).toBe(true) expect(null === undefined).toBe(false) expect(Object.is(null, undefined)).toBe(false) // NaN, NaN expect(NaN == NaN).toBe(false) expect(NaN === NaN).toBe(false) expect(Object.is(NaN, NaN)).toBe(true) // +0, -0 expect(+0 == -0).toBe(true) expect(+0 === -0).toBe(true) expect(Object.is(+0, -0)).toBe(false) }) }) }) describe('typeof Operator', () => { describe('Correct Results', () => { it('should return correct types for primitives', () => { expect(typeof "hello").toBe("string") expect(typeof 42).toBe("number") expect(typeof 42n).toBe("bigint") expect(typeof true).toBe("boolean") expect(typeof undefined).toBe("undefined") expect(typeof Symbol()).toBe("symbol") }) it('should return "object" for objects and arrays', () => { expect(typeof {}).toBe("object") expect(typeof []).toBe("object") expect(typeof new Date()).toBe("object") expect(typeof /regex/).toBe("object") }) it('should return "function" for functions', () => { expect(typeof function(){}).toBe("function") expect(typeof (() => {})).toBe("function") expect(typeof class {}).toBe("function") expect(typeof Math.sin).toBe("function") }) }) describe('Famous Quirks', () => { it('should return "object" for null (bug)', () => { expect(typeof null).toBe("object") }) it('should return "object" for arrays', () => { expect(typeof []).toBe("object") expect(typeof [1, 2, 3]).toBe("object") expect(typeof new Array()).toBe("object") }) it('should return "number" for NaN', () => { expect(typeof NaN).toBe("number") }) it('should return "undefined" for undeclared variables', () => { expect(typeof undeclaredVariable).toBe("undefined") }) }) describe('Workarounds', () => { it('should check for null explicitly', () => { function getType(value) { if (value === null) return "null" return typeof value } expect(getType(null)).toBe("null") expect(getType(undefined)).toBe("undefined") expect(getType(42)).toBe("number") }) it('should check for "real" objects', () => { function isRealObject(value) { return value !== null && typeof value === "object" } expect(isRealObject({})).toBe(true) expect(isRealObject([])).toBe(true) expect(isRealObject(null)).toBe(false) }) }) }) describe('Better Type Checking Alternatives', () => { describe('Type-Specific Checks', () => { it('should use Array.isArray for arrays', () => { expect(Array.isArray([])).toBe(true) expect(Array.isArray([1, 2, 3])).toBe(true) expect(Array.isArray({})).toBe(false) expect(Array.isArray("hello")).toBe(false) expect(Array.isArray(null)).toBe(false) }) it('should use Number.isNaN for NaN', () => { expect(Number.isNaN(NaN)).toBe(true) expect(Number.isNaN("hello")).toBe(false) expect(Number.isNaN(undefined)).toBe(false) }) it('should use Number.isFinite for finite numbers', () => { expect(Number.isFinite(42)).toBe(true) expect(Number.isFinite(Infinity)).toBe(false) expect(Number.isFinite(NaN)).toBe(false) }) it('should use Number.isInteger for integers', () => { expect(Number.isInteger(42)).toBe(true) expect(Number.isInteger(42.5)).toBe(false) }) }) describe('instanceof', () => { it('should check instance of constructor', () => { expect([] instanceof Array).toBe(true) expect({} instanceof Object).toBe(true) expect(new Date() instanceof Date).toBe(true) expect(/regex/ instanceof RegExp).toBe(true) }) it('should work with custom classes', () => { class Person {} const p = new Person() expect(p instanceof Person).toBe(true) }) }) describe('Object.prototype.toString', () => { it('should return precise type information', () => { const getType = (value) => Object.prototype.toString.call(value).slice(8, -1) expect(getType(null)).toBe("Null") expect(getType(undefined)).toBe("Undefined") expect(getType([])).toBe("Array") expect(getType({})).toBe("Object") expect(getType(new Date())).toBe("Date") expect(getType(/regex/)).toBe("RegExp") expect(getType(new Map())).toBe("Map") expect(getType(new Set())).toBe("Set") expect(getType(Promise.resolve())).toBe("Promise") expect(getType(function(){})).toBe("Function") expect(getType(42)).toBe("Number") expect(getType("hello")).toBe("String") expect(getType(Symbol())).toBe("Symbol") expect(getType(42n)).toBe("BigInt") }) }) describe('Custom Type Checker', () => { it('should create comprehensive type checker', () => { function getType(value) { if (value === null) return "null" const type = typeof value if (type !== "object" && type !== "function") { return type } const tag = Object.prototype.toString.call(value) return tag.slice(8, -1).toLowerCase() } expect(getType(null)).toBe("null") expect(getType([])).toBe("array") expect(getType({})).toBe("object") expect(getType(new Date())).toBe("date") expect(getType(/regex/)).toBe("regexp") expect(getType(new Map())).toBe("map") expect(getType(Promise.resolve())).toBe("promise") }) }) }) describe('Common Gotchas and Mistakes', () => { describe('Comparing Objects by Value', () => { it('should demonstrate object reference comparison', () => { const user1 = { name: "Alice" } const user2 = { name: "Alice" } expect(user1 === user2).toBe(false) // Never runs as equal! // Option 1: Compare specific properties expect(user1.name === user2.name).toBe(true) // Option 2: JSON.stringify expect(JSON.stringify(user1) === JSON.stringify(user2)).toBe(true) }) }) describe('NaN Comparisons', () => { it('should never use === for NaN', () => { const result = parseInt("hello") expect(result === NaN).toBe(false) // Never works! expect(Number.isNaN(result)).toBe(true) // Correct way expect(Object.is(result, NaN)).toBe(true) // Also works }) }) describe('typeof null Trap', () => { it('should handle null separately from objects', () => { function processObject(obj) { if (obj !== null && typeof obj === "object") { return "real object" } return "not an object" } expect(processObject({})).toBe("real object") expect(processObject(null)).toBe("not an object") }) }) describe('String Comparison Gotchas', () => { it('should demonstrate string comparison issues', () => { // Strings compare lexicographically expect("10" > "9").toBe(false) // "1" < "9" // Convert to numbers for numeric comparison expect(Number("10") > Number("9")).toBe(true) expect(+"10" > +"9").toBe(true) }) }) describe('Empty Array Comparisons', () => { it('should demonstrate array truthiness vs equality', () => { const arr = [] // These seem contradictory expect(arr == false).toBe(true) expect(arr ? true : false).toBe(true) // arr is truthy! // Check array length instead expect(arr.length === 0).toBe(true) expect(!arr.length).toBe(true) }) }) }) describe('Decision Guide', () => { describe('Default to ===', () => { it('should use === for predictable comparisons', () => { expect(5 === 5).toBe(true) expect(5 === "5").toBe(false) // No surprise }) }) describe('Use == null for Nullish Checks', () => { it('should check for null or undefined', () => { function isNullish(value) { return value == null } expect(isNullish(null)).toBe(true) expect(isNullish(undefined)).toBe(true) expect(isNullish(0)).toBe(false) expect(isNullish("")).toBe(false) expect(isNullish(false)).toBe(false) }) }) describe('Use Number.isNaN for NaN', () => { it('should use Number.isNaN, not isNaN', () => { expect(Number.isNaN(NaN)).toBe(true) expect(Number.isNaN("hello")).toBe(false) // Correct expect(isNaN("hello")).toBe(true) // Wrong! }) }) describe('Use Array.isArray for Arrays', () => { it('should use Array.isArray, not typeof', () => { expect(Array.isArray([])).toBe(true) expect(typeof []).toBe("object") // Not helpful }) }) describe('Use Object.is for Edge Cases', () => { it('should use Object.is for NaN and ±0', () => { expect(Object.is(NaN, NaN)).toBe(true) expect(Object.is(+0, -0)).toBe(false) }) }) }) describe('Additional Missing Examples', () => { describe('More Loose Equality Examples', () => { it('should coerce 42 == "42" to true', () => { expect(42 == "42").toBe(true) }) it('should return false for undefined == ""', () => { expect(undefined == "").toBe(false) }) }) describe('More Strict Equality Examples', () => { it('should return false for array === string', () => { const arr = [] const str = "" expect(arr === str).toBe(false) }) it('should demonstrate -0 === 0 is true', () => { expect(-0 === 0).toBe(true) expect(0 === -0).toBe(true) }) }) describe('Negative Zero Edge Cases', () => { it('should demonstrate 1/+0 vs 1/-0', () => { expect(1 / +0).toBe(Infinity) expect(1 / -0).toBe(-Infinity) expect((1 / +0) === (1 / -0)).toBe(false) }) it('should demonstrate Math.sign with -0', () => { expect(Object.is(Math.sign(-0), -0)).toBe(true) expect(Math.sign(-0) === 0).toBe(true) // But === says it equals 0 }) it('should parse -0 from JSON', () => { const negZero = JSON.parse("-0") expect(Object.is(negZero, -0)).toBe(true) }) it('should create -0 through multiplication', () => { expect(Object.is(0 * -1, -0)).toBe(true) expect(Object.is(-0 * 1, -0)).toBe(true) }) }) describe('Map with NaN as Key', () => { it('should use NaN as a Map key', () => { const map = new Map() map.set(NaN, "value for NaN") // Map uses SameValueZero algorithm, which treats NaN === NaN expect(map.get(NaN)).toBe("value for NaN") expect(map.has(NaN)).toBe(true) }) it('should only have one NaN key despite multiple sets', () => { const map = new Map() map.set(NaN, "first") map.set(NaN, "second") expect(map.size).toBe(1) expect(map.get(NaN)).toBe("second") }) }) describe('Number.isSafeInteger', () => { it('should identify safe integers', () => { expect(Number.isSafeInteger(3)).toBe(true) expect(Number.isSafeInteger(-3)).toBe(true) expect(Number.isSafeInteger(0)).toBe(true) expect(Number.isSafeInteger(Number.MAX_SAFE_INTEGER)).toBe(true) expect(Number.isSafeInteger(Number.MIN_SAFE_INTEGER)).toBe(true) }) it('should return false for unsafe integers', () => { expect(Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1)).toBe(false) expect(Number.isSafeInteger(Number.MIN_SAFE_INTEGER - 1)).toBe(false) }) it('should return false for non-integers', () => { expect(Number.isSafeInteger(3.1)).toBe(false) expect(Number.isSafeInteger(NaN)).toBe(false) expect(Number.isSafeInteger(Infinity)).toBe(false) expect(Number.isSafeInteger("3")).toBe(false) }) }) describe('NaN Creation Examples', () => { it('should create NaN from 0/0', () => { expect(Number.isNaN(0 / 0)).toBe(true) }) it('should create NaN from Math.sqrt(-1)', () => { expect(Number.isNaN(Math.sqrt(-1))).toBe(true) }) it('should create NaN from invalid math operations', () => { expect(Number.isNaN(Infinity - Infinity)).toBe(true) expect(Number.isNaN(Infinity / Infinity)).toBe(true) expect(Number.isNaN(0 * Infinity)).toBe(true) }) }) describe('Sorting Array of Number Strings', () => { it('should sort incorrectly with default sort', () => { const arr = ["10", "9", "2", "1", "100"] const sorted = [...arr].sort() // Lexicographic sort - NOT numeric order! expect(sorted).toEqual(["1", "10", "100", "2", "9"]) }) it('should sort correctly with numeric comparison', () => { const arr = ["10", "9", "2", "1", "100"] const sorted = [...arr].sort((a, b) => Number(a) - Number(b)) expect(sorted).toEqual(["1", "2", "9", "10", "100"]) }) it('should sort correctly using + for conversion', () => { const arr = ["10", "9", "2", "1", "100"] const sorted = [...arr].sort((a, b) => +a - +b) expect(sorted).toEqual(["1", "2", "9", "10", "100"]) }) }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/fundamentals/javascript-engines/javascript-engines.test.js
tests/fundamentals/javascript-engines/javascript-engines.test.js
import { describe, it, expect } from 'vitest' describe('JavaScript Engines', () => { describe('Basic Examples from Documentation', () => { it('should demonstrate basic function execution (opening example)', () => { // From the opening of the documentation function greet(name) { return "Hello, " + name + "!" } expect(greet("World")).toBe("Hello, World!") expect(greet("JavaScript")).toBe("Hello, JavaScript!") expect(greet("V8")).toBe("Hello, V8!") }) }) describe('Object Shape Consistency', () => { it('should create objects with consistent property order', () => { // Objects with same properties in same order share hidden classes const point1 = { x: 1, y: 2 } const point2 = { x: 5, y: 10 } // Both should have same property keys in same order expect(Object.keys(point1)).toEqual(['x', 'y']) expect(Object.keys(point2)).toEqual(['x', 'y']) expect(Object.keys(point1)).toEqual(Object.keys(point2)) }) it('should show different key order for differently created objects', () => { // Property order matters for hidden classes const a = { x: 1, y: 2 } const b = { y: 2, x: 1 } // Keys are in different order expect(Object.keys(a)).toEqual(['x', 'y']) expect(Object.keys(b)).toEqual(['y', 'x']) // These have DIFFERENT hidden classes in V8! expect(Object.keys(a)).not.toEqual(Object.keys(b)) }) it('should maintain consistent shapes with factory functions', () => { // Factory functions create consistent shapes (engine-friendly) function createPoint(x, y) { return { x, y } } const p1 = createPoint(1, 2) const p2 = createPoint(3, 4) const p3 = createPoint(5, 6) // All have identical structure expect(Object.keys(p1)).toEqual(Object.keys(p2)) expect(Object.keys(p2)).toEqual(Object.keys(p3)) }) it('should demonstrate transition chains when adding properties', () => { const obj = {} expect(Object.keys(obj)).toEqual([]) obj.x = 1 expect(Object.keys(obj)).toEqual(['x']) obj.y = 2 expect(Object.keys(obj)).toEqual(['x', 'y']) // Each step creates a new hidden class (transition chain) }) it('should compare Pattern A (object literal) vs Pattern B (empty object + properties)', () => { // Pattern A: Object literal - creates shape immediately function createPointA(x, y) { return { x: x, y: y } } // Pattern B: Empty object + property additions - goes through transitions function createPointB(x, y) { const point = {} point.x = x point.y = y return point } const pointA = createPointA(1, 2) const pointB = createPointB(3, 4) // Both produce same final shape expect(Object.keys(pointA)).toEqual(['x', 'y']) expect(Object.keys(pointB)).toEqual(['x', 'y']) // Both work correctly expect(pointA.x).toBe(1) expect(pointA.y).toBe(2) expect(pointB.x).toBe(3) expect(pointB.y).toBe(4) // Pattern A is more engine-friendly because: // - V8 can optimize object literals with known properties // - Pattern B goes through 3 hidden class transitions: {} -> {x} -> {x,y} }) }) describe('Type Consistency', () => { it('should demonstrate consistent number operations', () => { // V8 optimizes for consistent types function add(a, b) { return a + b } // Consistent number usage (monomorphic, fast) expect(add(1, 2)).toBe(3) expect(add(3, 4)).toBe(7) expect(add(5, 6)).toBe(11) }) it('should handle type changes (triggers deoptimization)', () => { function process(x) { return x + x } // Numbers expect(process(5)).toBe(10) expect(process(10)).toBe(20) // Strings (type change - would trigger deoptimization in V8) expect(process("hello")).toBe("hellohello") // Mixed usage works but is slower due to deoptimization }) it('should demonstrate dynamic object shapes with process function', () => { // From JIT compilation section - shows why JS needs JIT function process(x) { return x.value * 2 } // Object with number value expect(process({ value: 10 })).toBe(20) // Object with string value (NaN result) expect(process({ value: "hello" })).toBeNaN() // Different shape (extra property) - still works expect(process({ value: 10, extra: 5 })).toBe(20) // Even more different shape expect(process({ value: 5, a: 1, b: 2 })).toBe(10) // This demonstrates why JavaScript needs JIT: // - x could be any object shape // - x.value could be any type // - AOT compilation can't optimize for all possibilities }) it('should show typeof consistency', () => { let num = 42 expect(typeof num).toBe('number') // Changing types is valid JS but can cause deoptimization // let num = "forty-two" // Would change type // Better: use separate variables const numValue = 42 const strValue = "forty-two" expect(typeof numValue).toBe('number') expect(typeof strValue).toBe('string') }) }) describe('Array Optimization', () => { it('should create dense arrays (engine-friendly)', () => { // Dense array - all indices filled, same type const dense = [1, 2, 3, 4, 5] expect(dense.length).toBe(5) expect(dense[0]).toBe(1) expect(dense[4]).toBe(5) // V8 can use optimized "packed" array representation }) it('should demonstrate sparse arrays (slower)', () => { // Sparse array with holes - V8 uses slower dictionary mode const sparse = [] sparse[0] = 1 sparse[100] = 2 expect(sparse.length).toBe(101) expect(sparse[0]).toBe(1) expect(sparse[50]).toBe(undefined) // Hole expect(sparse[100]).toBe(2) // This creates 99 "holes" - less efficient }) it('should show typed array benefits', () => { // Typed arrays are always optimized (single type, no holes) const int32Array = new Int32Array([1, 2, 3, 4, 5]) expect(int32Array.length).toBe(5) expect(int32Array[0]).toBe(1) // All elements guaranteed to be 32-bit integers }) it('should demonstrate mixed-type arrays (polymorphic)', () => { // Mixed types require more generic handling const mixed = [1, "two", 3, null, { four: 4 }] expect(typeof mixed[0]).toBe('number') expect(typeof mixed[1]).toBe('string') expect(typeof mixed[3]).toBe('object') expect(typeof mixed[4]).toBe('object') // V8 can't assume element types - slower operations }) it('should preserve array type with consistent operations', () => { const numbers = [1, 2, 3, 4, 5] // map preserves array structure const doubled = numbers.map(n => n * 2) expect(doubled).toEqual([2, 4, 6, 8, 10]) // filter preserves type consistency const filtered = numbers.filter(n => n > 2) expect(filtered).toEqual([3, 4, 5]) }) }) describe('Property Access Patterns', () => { it('should demonstrate monomorphic property access', () => { // Monomorphic: always same object shape function getX(obj) { return obj.x } // All objects have same shape - fastest IC state expect(getX({ x: 1, y: 2 })).toBe(1) expect(getX({ x: 3, y: 4 })).toBe(3) expect(getX({ x: 5, y: 6 })).toBe(5) }) it('should show polymorphic access (multiple shapes)', () => { function getX(obj) { return obj.x } // Different shapes - polymorphic IC expect(getX({ x: 1 })).toBe(1) // Shape A expect(getX({ x: 2, y: 3 })).toBe(2) // Shape B expect(getX({ x: 4, y: 5, z: 6 })).toBe(4) // Shape C // Still works, but inline cache has multiple entries }) it('should demonstrate computed property access', () => { const obj = { a: 1, b: 2, c: 3 } // Direct property access (faster) expect(obj.a).toBe(1) // Computed property access (slightly slower but necessary for dynamic keys) const key = 'b' expect(obj[key]).toBe(2) }) it('should demonstrate megamorphic access (many different shapes)', () => { function getX(obj) { return obj.x } // Every call has a completely different shape // This would cause megamorphic IC state in V8 expect(getX({ x: 1 })).toBe(1) expect(getX({ x: 2, a: 1 })).toBe(2) expect(getX({ x: 3, b: 2 })).toBe(3) expect(getX({ x: 4, c: 3 })).toBe(4) expect(getX({ x: 5, d: 4 })).toBe(5) expect(getX({ x: 6, e: 5 })).toBe(6) expect(getX({ x: 7, f: 6 })).toBe(7) // IC gives up after too many shapes - falls back to generic lookup // Still works correctly, just slower than monomorphic/polymorphic }) }) describe('Class vs Object Literal Shapes', () => { it('should create consistent shapes with classes', () => { class Point { constructor(x, y) { this.x = x this.y = y } } const p1 = new Point(1, 2) const p2 = new Point(3, 4) const p3 = new Point(5, 6) // All instances have identical shape expect(Object.keys(p1)).toEqual(['x', 'y']) expect(Object.keys(p2)).toEqual(['x', 'y']) expect(Object.keys(p3)).toEqual(['x', 'y']) }) it('should show prototype chain optimization', () => { class Animal { speak() { return 'sound' } } class Dog extends Animal { speak() { return 'woof' } } const dog = new Dog() // Method lookup follows prototype chain expect(dog.speak()).toBe('woof') expect(dog instanceof Dog).toBe(true) expect(dog instanceof Animal).toBe(true) }) }) describe('Avoiding Deoptimization Patterns', () => { it('should show delete causing shape change', () => { const user = { name: 'Alice', age: 30, temp: true } expect(Object.keys(user)).toEqual(['name', 'age', 'temp']) // delete changes hidden class (bad for performance) delete user.temp expect(Object.keys(user)).toEqual(['name', 'age']) expect(user.temp).toBe(undefined) // Better alternative: set to undefined const user2 = { name: 'Bob', age: 25, temp: true } user2.temp = undefined // Hidden class stays the same expect('temp' in user2).toBe(true) // Property still exists expect(user2.temp).toBe(undefined) }) it('should demonstrate object spread for immutable updates', () => { const original = { x: 1, y: 2, z: 3 } // Instead of mutating, create new object const updated = { ...original, z: 10 } expect(original.z).toBe(3) // Original unchanged expect(updated.z).toBe(10) // New object with update // Both have consistent shapes expect(Object.keys(original)).toEqual(['x', 'y', 'z']) expect(Object.keys(updated)).toEqual(['x', 'y', 'z']) }) it('should show inconsistent shapes with conditional property assignment', () => { // Bad pattern: conditional property assignment creates different shapes function createUserBad(name, age) { const user = {} if (name) user.name = name if (age) user.age = age return user } const user1 = createUserBad('Alice', 30) const user2 = createUserBad('Bob', null) // Only name const user3 = createUserBad(null, 25) // Only age const user4 = createUserBad(null, null) // Empty // All have different shapes! expect(Object.keys(user1)).toEqual(['name', 'age']) expect(Object.keys(user2)).toEqual(['name']) expect(Object.keys(user3)).toEqual(['age']) expect(Object.keys(user4)).toEqual([]) // Compare with good pattern function createUserGood(name, age) { return { name, age } // Always same shape } const goodUser1 = createUserGood('Alice', 30) const goodUser2 = createUserGood('Bob', null) const goodUser3 = createUserGood(null, 25) // Same shape regardless of values (nulls are still properties) expect(Object.keys(goodUser1)).toEqual(['name', 'age']) expect(Object.keys(goodUser2)).toEqual(['name', 'age']) expect(Object.keys(goodUser3)).toEqual(['name', 'age']) }) }) describe('Function Optimization Patterns', () => { it('should demonstrate consistent function signatures', () => { function multiply(a, b) { return a * b } // Consistent argument types enable optimization expect(multiply(2, 3)).toBe(6) expect(multiply(4, 5)).toBe(20) expect(multiply(6, 7)).toBe(42) }) it('should show inlining with small functions', () => { // Small functions are candidates for inlining function square(x) { return x * x } function sumOfSquares(a, b) { return square(a) + square(b) } // V8 may inline square() into sumOfSquares() expect(sumOfSquares(3, 4)).toBe(25) // 9 + 16 }) it('should demonstrate closure optimization', () => { function createAdder(x) { // Closure captures x return function(y) { return x + y } } const add5 = createAdder(5) const add10 = createAdder(10) // Closures with consistent captured values can be optimized expect(add5(3)).toBe(8) expect(add10(3)).toBe(13) }) }) describe('Garbage Collection Concepts', () => { it('should demonstrate object references', () => { let obj = { data: 'important' } const ref = obj // Both point to same object expect(ref.data).toBe('important') // Setting obj to null doesn't GC the object // because ref still holds a reference obj = null expect(ref.data).toBe('important') }) it('should show circular references', () => { const a = { name: 'a' } const b = { name: 'b' } // Circular reference a.ref = b b.ref = a expect(a.ref.name).toBe('b') expect(b.ref.name).toBe('a') expect(a.ref.ref.name).toBe('a') // Modern GC can handle circular references // (mark-and-sweep doesn't rely on reference counting) }) it('should demonstrate WeakRef for GC-friendly references', () => { // WeakRef allows object to be garbage collected let obj = { data: 'temporary' } const weakRef = new WeakRef(obj) // Can access while object exists expect(weakRef.deref()?.data).toBe('temporary') // Note: We can't force GC in tests, but WeakRef // allows the referenced object to be collected }) it('should show Map vs WeakMap for memory management', () => { // Regular Map holds strong references const map = new Map() let key = { id: 1 } map.set(key, 'value') expect(map.get(key)).toBe('value') // WeakMap allows keys to be garbage collected const weakMap = new WeakMap() let weakKey = { id: 2 } weakMap.set(weakKey, 'value') expect(weakMap.get(weakKey)).toBe('value') // If weakKey is set to null and no other references exist, // the entry can be garbage collected }) }) describe('JIT Compilation Observable Behavior', () => { it('should handle hot function calls', () => { function hotFunction(n) { return n * 2 } // Simulating many calls (would trigger JIT in real V8) let result = 0 for (let i = 0; i < 1000; i++) { result = hotFunction(i) } expect(result).toBe(1998) // Last iteration: 999 * 2 }) it('should demonstrate deoptimization scenario', () => { function add(a, b) { return a + b } // Many calls with numbers (would be optimized for numbers) for (let i = 0; i < 100; i++) { add(i, i + 1) } // Then a call with strings (triggers deoptimization) const result = add('hello', 'world') // Still produces correct result despite deoptimization expect(result).toBe('helloworld') }) it('should show consistent returns for optimization', () => { // Always returns same type (optimizer-friendly) function maybeDouble(n, shouldDouble) { if (shouldDouble) { return n * 2 } return n // Always returns number } expect(maybeDouble(5, true)).toBe(10) expect(maybeDouble(5, false)).toBe(5) expect(typeof maybeDouble(5, true)).toBe('number') expect(typeof maybeDouble(5, false)).toBe('number') }) }) describe('Hidden Class Interview Questions', () => { it('should explain why object literal order matters', () => { // Creating objects with different property orders function createA() { return { first: 1, second: 2 } } function createB() { return { second: 2, first: 1 } } const objA = createA() const objB = createB() // Same values, but different hidden classes expect(objA.first).toBe(objB.first) expect(objA.second).toBe(objB.second) // Property order is different expect(Object.keys(objA)[0]).toBe('first') expect(Object.keys(objB)[0]).toBe('second') }) it('should demonstrate best practice with constructor pattern', () => { // Constructor ensures consistent shape function User(name, email, age) { this.name = name this.email = email this.age = age } const user1 = new User('Alice', 'alice@example.com', 30) const user2 = new User('Bob', 'bob@example.com', 25) // Guaranteed same property order expect(Object.keys(user1)).toEqual(['name', 'email', 'age']) expect(Object.keys(user2)).toEqual(['name', 'email', 'age']) }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/fundamentals/value-reference-types/value-reference-types.test.js
tests/fundamentals/value-reference-types/value-reference-types.test.js
import { describe, it, expect } from 'vitest' describe('Value Types and Reference Types', () => { describe('Copying Primitives', () => { it('should create independent copies when copying primitives', () => { let a = 10 let b = a // b gets a COPY of the value 10 b = 20 // changing b has NO effect on a expect(a).toBe(10) // unchanged! expect(b).toBe(20) }) it('should demonstrate string variables are independent copies', () => { let name = "Alice" let age = 25 let user = { name: "Alice" } // Reference on stack, object on heap let scores = [95, 87, 92] // Reference on stack, array on heap expect(name).toBe("Alice") expect(age).toBe(25) expect(user).toEqual({ name: "Alice" }) expect(scores).toEqual([95, 87, 92]) }) }) describe('Copying Objects', () => { it('should share reference when copying objects', () => { let obj1 = { name: "Alice" } let obj2 = obj1 // obj2 gets a COPY of the REFERENCE obj2.name = "Bob" // modifies the SAME object! expect(obj1.name).toBe("Bob") // changed! expect(obj2.name).toBe("Bob") }) it('should share reference when copying arrays', () => { let arr1 = [1, 2, 3] let arr2 = arr1 // arr2 points to the SAME array arr2.push(4) // modifies the shared array expect(arr1).toEqual([1, 2, 3, 4]) // changed! expect(arr2).toEqual([1, 2, 3, 4]) }) }) describe('Comparison Behavior', () => { describe('Primitives: Compared by Value', () => { it('should return true for equal primitive values', () => { let a = "hello" let b = "hello" expect(a === b).toBe(true) let x = 42 let y = 42 expect(x === y).toBe(true) }) }) describe('Objects: Compared by Reference', () => { it('should return false for different objects with same content', () => { let obj1 = { name: "Alice" } let obj2 = { name: "Alice" } expect(obj1 === obj2).toBe(false) // different objects! }) it('should return true for same reference', () => { let obj1 = { name: "Alice" } let obj3 = obj1 expect(obj1 === obj3).toBe(true) // same reference }) it('should return false for empty objects/arrays compared', () => { // These tests intentionally demonstrate that objects compare by reference const emptyObj1 = {} const emptyObj2 = {} expect(emptyObj1 === emptyObj2).toBe(false) const emptyArr1 = [] const emptyArr2 = [] expect(emptyArr1 === emptyArr2).toBe(false) const arr1 = [1, 2] const arr2 = [1, 2] expect(arr1 === arr2).toBe(false) }) }) describe('Comparing Objects by Content', () => { it('should use JSON.stringify for simple comparison', () => { let obj1 = { name: "Alice" } let obj2 = { name: "Alice" } expect(JSON.stringify(obj1) === JSON.stringify(obj2)).toBe(true) }) it('should compare arrays of primitives with every()', () => { let arr1 = [1, 2, 3] let arr2 = [1, 2, 3] expect(arr1.length === arr2.length && arr1.every((v, i) => v === arr2[i])).toBe(true) }) }) }) describe('Functions and Parameters', () => { describe('Passing Primitives', () => { it('should not modify original when passing primitive to function', () => { function double(num) { num = num * 2 return num } let x = 10 let result = double(x) expect(x).toBe(10) // unchanged! expect(result).toBe(20) }) }) describe('Passing Objects', () => { it('should modify original object when mutating through function parameter', () => { function rename(person) { person.name = "Bob" } let user = { name: "Alice" } rename(user) expect(user.name).toBe("Bob") // changed! }) it('should not modify original when reassigning parameter', () => { function replace(person) { person = { name: "Charlie" } // creates NEW local object } let user = { name: "Alice" } replace(user) expect(user.name).toBe("Alice") // unchanged! }) }) }) describe('Mutation vs Reassignment', () => { describe('Mutation', () => { it('should modify array with mutating methods', () => { const arr = [1, 2, 3] arr.push(4) expect(arr).toEqual([1, 2, 3, 4]) arr[0] = 99 expect(arr).toEqual([99, 2, 3, 4]) arr.pop() expect(arr).toEqual([99, 2, 3]) }) it('should modify object properties', () => { const obj = { name: "Alice" } obj.name = "Bob" expect(obj.name).toBe("Bob") obj.age = 25 expect(obj.age).toBe(25) delete obj.age expect(obj.age).toBe(undefined) }) }) describe('Reassignment', () => { it('should point to new value after reassignment', () => { let arr = [1, 2, 3] arr = [4, 5, 6] expect(arr).toEqual([4, 5, 6]) let obj = { name: "Alice" } obj = { name: "Bob" } expect(obj).toEqual({ name: "Bob" }) }) }) describe('const with Objects', () => { it('should allow mutations on const objects', () => { const arr = [1, 2, 3] arr.push(4) expect(arr).toEqual([1, 2, 3, 4]) arr[0] = 99 expect(arr).toEqual([99, 2, 3, 4]) }) it('should allow mutations on const object properties', () => { const obj = { name: "Alice" } obj.name = "Bob" expect(obj.name).toBe("Bob") obj.age = 25 expect(obj.age).toBe(25) }) it('should throw TypeError when reassigning const', () => { expect(() => { eval('const x = 1; x = 2') // Using eval to test const reassignment }).toThrow() }) }) }) describe('Object.freeze()', () => { it('should throw TypeError when modifying frozen object in strict mode', () => { const user = Object.freeze({ name: "Alice", age: 25 }) // In strict mode (which Vitest uses), modifications throw TypeError expect(() => { user.name = "Bob" }).toThrow(TypeError) expect(() => { user.email = "a@b.com" }).toThrow(TypeError) expect(() => { delete user.age }).toThrow(TypeError) expect(user).toEqual({ name: "Alice", age: 25 }) // unchanged! }) it('should check if object is frozen', () => { const frozen = Object.freeze({ a: 1 }) const normal = { a: 1 } expect(Object.isFrozen(frozen)).toBe(true) expect(Object.isFrozen(normal)).toBe(false) }) it('should only freeze shallow - nested objects can still be modified', () => { const user = Object.freeze({ name: "Alice", address: { city: "NYC" } }) // In strict mode, modifying frozen property throws TypeError expect(() => { user.name = "Bob" }).toThrow(TypeError) // But nested object is not frozen, so this works user.address.city = "LA" expect(user.name).toBe("Alice") // unchanged expect(user.address.city).toBe("LA") // changed! }) }) describe('Deep Freeze', () => { it('should freeze nested objects with deep freeze function', () => { function deepFreeze(obj, seen = new WeakSet()) { // Prevent infinite loops from circular references if (seen.has(obj)) return obj seen.add(obj) const propNames = Reflect.ownKeys(obj) for (const name of propNames) { const value = obj[name] if (value && typeof value === "object") { deepFreeze(value, seen) } } return Object.freeze(obj) } const user = deepFreeze({ name: "Alice", address: { city: "NYC" } }) // In strict mode, this throws TypeError since nested object is now frozen expect(() => { user.address.city = "LA" }).toThrow(TypeError) expect(user.address.city).toBe("NYC") // Now blocked! }) it('should handle circular references without infinite loop', () => { function deepFreeze(obj, seen = new WeakSet()) { if (seen.has(obj)) return obj seen.add(obj) const propNames = Reflect.ownKeys(obj) for (const name of propNames) { const value = obj[name] if (value && typeof value === "object") { deepFreeze(value, seen) } } return Object.freeze(obj) } // Create object with circular reference const obj = { name: "test" } obj.self = obj // Circular reference // Should not throw or hang - handles circular reference const frozen = deepFreeze(obj) expect(Object.isFrozen(frozen)).toBe(true) expect(frozen.self).toBe(frozen) // Circular reference preserved expect(() => { frozen.name = "changed" }).toThrow(TypeError) }) }) describe('Object.seal() and Object.preventExtensions()', () => { it('should allow value changes but prevent add/delete with seal()', () => { const sealed = Object.seal({ name: "Alice" }) sealed.name = "Bob" expect(sealed.name).toBe("Bob") // Works! // In strict mode, these throw TypeError instead of failing silently expect(() => { sealed.age = 25 }).toThrow(TypeError) expect(sealed.age).toBe(undefined) expect(() => { delete sealed.name }).toThrow(TypeError) expect(sealed.name).toBe("Bob") }) it('should allow change/delete but prevent add with preventExtensions()', () => { const noExtend = Object.preventExtensions({ name: "Alice" }) noExtend.name = "Bob" expect(noExtend.name).toBe("Bob") // Works! delete noExtend.name expect(noExtend.name).toBe(undefined) // Works! // In strict mode, adding properties throws TypeError expect(() => { noExtend.age = 25 }).toThrow(TypeError) expect(noExtend.age).toBe(undefined) }) }) describe('Shallow Copy', () => { it('should create shallow copy with spread operator', () => { const original = { name: "Alice", scores: [95, 87, 92], address: { city: "NYC" } } const copy1 = { ...original } expect(copy1.name).toBe("Alice") expect(copy1).not.toBe(original) // Different objects }) it('should create shallow copy with Object.assign', () => { const original = { name: "Alice" } const copy2 = Object.assign({}, original) expect(copy2.name).toBe("Alice") expect(copy2).not.toBe(original) }) it('should share nested objects in shallow copy', () => { const original = { name: "Alice", address: { city: "NYC" } } const shallow = { ...original } // Top-level changes are independent shallow.name = "Bob" expect(original.name).toBe("Alice") // But nested objects are SHARED shallow.address.city = "LA" expect(original.address.city).toBe("LA") // Original changed! }) it('should create shallow copy of arrays', () => { const originalArray = [1, 2, 3] const arrCopy1 = [...originalArray] const arrCopy2 = originalArray.slice() const arrCopy3 = Array.from(originalArray) expect(arrCopy1).toEqual([1, 2, 3]) expect(arrCopy2).toEqual([1, 2, 3]) expect(arrCopy3).toEqual([1, 2, 3]) expect(arrCopy1).not.toBe(originalArray) expect(arrCopy2).not.toBe(originalArray) expect(arrCopy3).not.toBe(originalArray) }) }) describe('Deep Copy', () => { it('should create deep copy with structuredClone', () => { const original = { name: "Alice", scores: [95, 87, 92], address: { city: "NYC" }, date: new Date() } const deep = structuredClone(original) // Everything is independent deep.address.city = "LA" expect(original.address.city).toBe("NYC") // unchanged! deep.scores.push(100) expect(original.scores).toEqual([95, 87, 92]) // unchanged! }) it('should create deep copy with JSON trick (with limitations)', () => { const original = { name: "Alice", address: { city: "NYC" } } const deep = JSON.parse(JSON.stringify(original)) deep.address.city = "LA" expect(original.address.city).toBe("NYC") // unchanged! }) it('should demonstrate JSON trick limitations', () => { const obj = { fn: () => {}, date: new Date('2025-01-01'), undef: undefined, set: new Set([1, 2]) } const clone = JSON.parse(JSON.stringify(obj)) expect(clone.fn).toBe(undefined) // Functions lost expect(typeof clone.date).toBe('string') // Date becomes string expect(clone.undef).toBe(undefined) // Property removed expect(clone.set).toEqual({}) // Set becomes empty object }) }) describe('Array Methods: Mutating vs Non-Mutating', () => { describe('Mutating Methods', () => { it('should mutate array with push, pop, shift, unshift', () => { const arr = [1, 2, 3] arr.push(4) expect(arr).toEqual([1, 2, 3, 4]) arr.pop() expect(arr).toEqual([1, 2, 3]) arr.shift() expect(arr).toEqual([2, 3]) arr.unshift(1) expect(arr).toEqual([1, 2, 3]) }) it('should mutate array with sort and reverse', () => { const nums = [3, 1, 2] nums.sort() expect(nums).toEqual([1, 2, 3]) // Original mutated! nums.reverse() expect(nums).toEqual([3, 2, 1]) // Original mutated! }) it('should mutate array with splice', () => { const arr = [1, 2, 3, 4, 5] arr.splice(2, 1) // Remove 1 element at index 2 expect(arr).toEqual([1, 2, 4, 5]) }) }) describe('Non-Mutating Methods', () => { it('should not mutate with map, filter, slice, concat', () => { const original = [1, 2, 3] const mapped = original.map(x => x * 2) expect(original).toEqual([1, 2, 3]) expect(mapped).toEqual([2, 4, 6]) const filtered = original.filter(x => x > 1) expect(original).toEqual([1, 2, 3]) expect(filtered).toEqual([2, 3]) const sliced = original.slice(1) expect(original).toEqual([1, 2, 3]) expect(sliced).toEqual([2, 3]) const concatenated = original.concat([4, 5]) expect(original).toEqual([1, 2, 3]) expect(concatenated).toEqual([1, 2, 3, 4, 5]) }) it('should use toSorted and toReversed for non-mutating sort/reverse (ES2023)', () => { const nums = [3, 1, 2] const sorted = nums.toSorted() expect(nums).toEqual([3, 1, 2]) // Original unchanged expect(sorted).toEqual([1, 2, 3]) const reversed = nums.toReversed() expect(nums).toEqual([3, 1, 2]) // Original unchanged expect(reversed).toEqual([2, 1, 3]) }) }) describe('Safe Sorting Pattern', () => { it('should copy array before sorting to avoid mutation', () => { const nums = [3, 1, 2] const sorted = [...nums].sort() expect(nums).toEqual([3, 1, 2]) // Original unchanged expect(sorted).toEqual([1, 2, 3]) }) }) }) describe('Common Pitfalls', () => { it('should demonstrate accidental array mutation in function', () => { function processUsers(users) { const copy = [...users] copy.push({ name: "New User" }) return copy } const myUsers = [{ name: "Alice" }] const result = processUsers(myUsers) expect(myUsers).toEqual([{ name: "Alice" }]) // Original unchanged expect(result).toEqual([{ name: "Alice" }, { name: "New User" }]) }) it('should demonstrate backup pattern failure', () => { const original = [1, 2, 3] const notABackup = original // NOT a backup! original.push(4) expect(notABackup).toEqual([1, 2, 3, 4]) // "backup" changed! // Correct backup const original2 = [1, 2, 3] const backup = [...original2] original2.push(4) expect(backup).toEqual([1, 2, 3]) // Real backup unchanged }) it('should demonstrate deep equality comparison', () => { function deepEqual(a, b) { return JSON.stringify(a) === JSON.stringify(b) } const obj1 = { name: "Alice", age: 25 } const obj2 = { name: "Alice", age: 25 } expect(obj1 === obj2).toBe(false) expect(deepEqual(obj1, obj2)).toBe(true) }) }) describe('Best Practices: Immutable Patterns', () => { it('should create new object instead of mutating', () => { const user = { name: "Alice", age: 25 } // Instead of: user.name = "Bob" const updatedUser = { ...user, name: "Bob" } expect(user.name).toBe("Alice") // Original unchanged expect(updatedUser.name).toBe("Bob") }) it('should use non-mutating array methods', () => { const numbers = [3, 1, 2] // Instead of: numbers.sort() const sorted = [...numbers].sort((a, b) => a - b) expect(numbers).toEqual([3, 1, 2]) // Original unchanged expect(sorted).toEqual([1, 2, 3]) }) }) describe('structuredClone with Special Types', () => { it('should deep clone objects with Map', () => { const original = { name: "Alice", data: new Map([["key1", "value1"], ["key2", "value2"]]) } const clone = structuredClone(original) // Modify the clone's Map clone.data.set("key1", "modified") clone.data.set("key3", "new value") // Original should be unchanged expect(original.data.get("key1")).toBe("value1") expect(original.data.has("key3")).toBe(false) expect(clone.data.get("key1")).toBe("modified") }) it('should deep clone objects with Set', () => { const original = { name: "Alice", tags: new Set([1, 2, 3]) } const clone = structuredClone(original) // Modify the clone's Set clone.tags.add(4) clone.tags.delete(1) // Original should be unchanged expect(original.tags.has(1)).toBe(true) expect(original.tags.has(4)).toBe(false) expect(clone.tags.has(1)).toBe(false) expect(clone.tags.has(4)).toBe(true) }) it('should deep clone objects with Date', () => { const original = { name: "Event", date: new Date("2025-01-01") } const clone = structuredClone(original) expect(clone.date instanceof Date).toBe(true) expect(clone.date.getTime()).toBe(original.date.getTime()) expect(clone.date).not.toBe(original.date) // Different reference }) }) describe('Shared Default Object Reference Pitfall', () => { it('should demonstrate shared default array problem', () => { const defaultList = [] function addItem(item, list = defaultList) { list.push(item) return list } const result1 = addItem("a") const result2 = addItem("b") // Both calls modified the same defaultList! expect(result1).toEqual(["a", "b"]) expect(result2).toEqual(["a", "b"]) expect(result1).toBe(result2) // Same reference! }) it('should fix shared default with new array creation', () => { function addItem(item, list = []) { list.push(item) return list } const result1 = addItem("a") const result2 = addItem("b") // Each call gets its own array expect(result1).toEqual(["a"]) expect(result2).toEqual(["b"]) expect(result1).not.toBe(result2) }) }) describe('WeakMap vs Map Memory Behavior', () => { it('should demonstrate Map holds strong references', () => { const cache = new Map() let user = { id: 1, name: "Alice" } cache.set(user.id, user) // Even if we clear user, the Map still holds the reference const cachedUser = cache.get(1) expect(cachedUser.name).toBe("Alice") }) it('should demonstrate WeakMap allows garbage collection', () => { const cache = new WeakMap() let user = { id: 1, name: "Alice" } cache.set(user, { computed: "expensive data" }) // WeakMap uses the object itself as key expect(cache.get(user)).toEqual({ computed: "expensive data" }) // WeakMap keys must be objects expect(() => cache.set("string-key", "value")).toThrow(TypeError) }) it('should show WeakMap cannot be iterated', () => { const weakMap = new WeakMap() const obj = { id: 1 } weakMap.set(obj, "value") // WeakMap has no size property expect(weakMap.size).toBe(undefined) // WeakMap is not iterable expect(typeof weakMap[Symbol.iterator]).toBe("undefined") }) }) describe('Clone Function Parameters Pattern', () => { it('should clone parameters before modification', () => { function processData(data) { // Clone to avoid modifying original const copy = structuredClone(data) copy.processed = true copy.items.push("new item") return copy } const original = { name: "data", items: ["item1", "item2"] } const result = processData(original) // Original is unchanged expect(original.processed).toBe(undefined) expect(original.items).toEqual(["item1", "item2"]) // Result has modifications expect(result.processed).toBe(true) expect(result.items).toEqual(["item1", "item2", "new item"]) }) }) describe('let with Object.freeze()', () => { it('should allow reassignment of let variable holding frozen object', () => { let obj = Object.freeze({ a: 1 }) // Cannot modify the frozen object expect(() => { obj.a = 2 }).toThrow(TypeError) // But CAN reassign the variable to a new object obj = { a: 2 } expect(obj.a).toBe(2) }) it('should demonstrate const + freeze for true immutability', () => { const obj = Object.freeze({ a: 1 }) // Cannot modify the frozen object expect(() => { obj.a = 2 }).toThrow(TypeError) // Cannot reassign const // obj = { a: 2 } // Would throw TypeError expect(obj.a).toBe(1) }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/fundamentals/call-stack/call-stack.test.js
tests/fundamentals/call-stack/call-stack.test.js
import { describe, it, expect } from 'vitest' describe('Call Stack', () => { describe('Basic Function Calls', () => { it('should execute nested function calls and return correct greeting', () => { function createGreeting(name) { return "Hello, " + name + "!" } function greet(name) { const greeting = createGreeting(name) return greeting } expect(greet("Alice")).toBe("Hello, Alice!") }) it('should demonstrate function arguments in execution context', () => { function greet(name, age) { return { name, age } } const result = greet("Alice", 25) expect(result).toEqual({ name: "Alice", age: 25 }) }) it('should demonstrate local variables in execution context', () => { function calculate() { const x = 10 let y = 20 var z = 30 return x + y + z } expect(calculate()).toBe(60) }) }) describe('Nested Function Calls', () => { it('should execute multiply, square, and printSquare correctly', () => { function multiply(x, y) { return x * y } function square(n) { return multiply(n, n) } function printSquare(n) { const result = square(n) return result } expect(printSquare(4)).toBe(16) }) it('should handle deep nesting of function calls', () => { function a() { return b() } function b() { return c() } function c() { return d() } function d() { return 'done' } expect(a()).toBe('done') }) it('should calculate maximum stack depth correctly for nested calls', () => { // This test verifies the example where max depth is 4 let maxDepth = 0 let currentDepth = 0 function a() { currentDepth++ maxDepth = Math.max(maxDepth, currentDepth) const result = b() currentDepth-- return result } function b() { currentDepth++ maxDepth = Math.max(maxDepth, currentDepth) const result = c() currentDepth-- return result } function c() { currentDepth++ maxDepth = Math.max(maxDepth, currentDepth) const result = d() currentDepth-- return result } function d() { currentDepth++ maxDepth = Math.max(maxDepth, currentDepth) currentDepth-- return 'done' } a() expect(maxDepth).toBe(4) }) }) describe('Scope Chain in Execution Context', () => { it('should access outer scope variables from inner function', () => { function outer() { const message = "Hello" function inner() { return message } return inner() } expect(outer()).toBe("Hello") }) it('should demonstrate this keyword context in objects', () => { const person = { name: "Alice", greet() { return this.name } } expect(person.greet()).toBe("Alice") }) }) describe('Stack Overflow', () => { it('should throw RangeError for infinite recursion without base case', () => { function countdown(n) { countdown(n - 1) // No base case - infinite recursion } expect(() => countdown(5)).toThrow(RangeError) }) it('should work correctly with proper base case', () => { const results = [] function countdown(n) { if (n <= 0) { results.push("Done!") return } results.push(n) countdown(n - 1) } countdown(5) expect(results).toEqual([5, 4, 3, 2, 1, "Done!"]) }) it('should throw for infinite loop function', () => { function loop() { loop() } expect(() => loop()).toThrow(RangeError) }) it('should throw for base case that is never reached', () => { function countUp(n, limit = 100) { // Modified to have a safety limit for testing if (n >= 1000000000000 || limit <= 0) return n return countUp(n + 1, limit - 1) } // This will return before hitting the impossible base case expect(countUp(0)).toBe(100) }) it('should throw for circular function calls', () => { function a() { return b() } function b() { return a() } expect(() => a()).toThrow(RangeError) }) it('should throw for accidental recursion in setters', () => { class Person { set name(value) { this.name = value // Calls the setter again - infinite loop! } } const p = new Person() expect(() => { p.name = "Alice" }).toThrow(RangeError) }) it('should work correctly with proper setter implementation using different property', () => { class PersonFixed { set name(value) { this._name = value // Use _name instead to avoid recursion } get name() { return this._name } } const p = new PersonFixed() p.name = "Alice" expect(p.name).toBe("Alice") }) }) describe('Recursion with Base Case', () => { it('should calculate factorial correctly', () => { function factorial(n) { if (n <= 1) return 1 return n * factorial(n - 1) } expect(factorial(5)).toBe(120) expect(factorial(1)).toBe(1) expect(factorial(0)).toBe(1) }) it('should demonstrate proper countdown with base case', () => { function countdown(n) { if (n <= 0) { return "Done!" } return countdown(n - 1) } expect(countdown(5)).toBe("Done!") }) }) describe('Error Stack Traces', () => { it('should create error with proper stack trace', () => { function a() { return b() } function b() { return c() } function c() { throw new Error('Something went wrong!') } expect(() => a()).toThrow('Something went wrong!') }) it('should preserve call stack in error', () => { function a() { return b() } function b() { return c() } function c() { throw new Error('Test error') } try { a() } catch (error) { expect(error.stack).toContain('c') expect(error.stack).toContain('b') expect(error.stack).toContain('a') } }) }) describe('Asynchronous Code Preview', () => { it('should demonstrate setTimeout behavior with call stack', async () => { const results = [] results.push('First') await new Promise(resolve => { setTimeout(() => { results.push('Second') resolve() }, 0) results.push('Third') }) // Even with 0ms delay, 'Third' runs before 'Second' expect(results).toEqual(['First', 'Third', 'Second']) }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/object-oriented/this-call-apply-bind/this-call-apply-bind.test.js
tests/object-oriented/this-call-apply-bind/this-call-apply-bind.test.js
import { describe, it, expect } from 'vitest' describe('this, call, apply and bind', () => { describe('Documentation Examples', () => { describe('Introduction: The Pronoun I Analogy', () => { it('should demonstrate this referring to different objects', () => { const alice = { name: "Alice", introduce() { return "I am " + this.name } } const bob = { name: "Bob", introduce() { return "I am " + this.name } } expect(alice.introduce()).toBe("I am Alice") expect(bob.introduce()).toBe("I am Bob") }) it('should allow borrowing methods with call (ventriloquist analogy)', () => { const alice = { name: "Alice" } const bob = { name: "Bob", introduce() { return "I am " + this.name } } // Alice borrows Bob's voice expect(bob.introduce.call(alice)).toBe("I am Alice") }) }) describe('Dynamic Binding: Call-Time Determination', () => { it('should have different this values depending on how function is called', () => { function showThis() { return this } const obj = { showThis } // Plain call - default binding (undefined in strict mode) expect(showThis()).toBeUndefined() // Method call - implicit binding expect(obj.showThis()).toBe(obj) // Explicit binding const customObj = { name: 'custom' } expect(showThis.call(customObj)).toBe(customObj) }) it('should allow one function to work with many objects', () => { function greet() { return `Hello, I'm ${this.name}!` } const alice = { name: "Alice", greet } const bob = { name: "Bob", greet } const charlie = { name: "Charlie", greet } expect(alice.greet()).toBe("Hello, I'm Alice!") expect(bob.greet()).toBe("Hello, I'm Bob!") expect(charlie.greet()).toBe("Hello, I'm Charlie!") }) }) describe('Rectangle Class Example (ES6 Classes)', () => { it('should bind this to instance in class methods', () => { class Rectangle { constructor(width, height) { this.width = width this.height = height } getArea() { return this.width * this.height } } const rect = new Rectangle(10, 5) expect(rect.getArea()).toBe(50) }) }) describe('Explicit Binding: introduce() Example', () => { it('should set this explicitly with call', () => { function introduce() { return `I'm ${this.name}, a ${this.role}` } const alice = { name: "Alice", role: "developer" } const bob = { name: "Bob", role: "designer" } expect(introduce.call(alice)).toBe("I'm Alice, a developer") expect(introduce.call(bob)).toBe("I'm Bob, a designer") }) }) describe('Partial Application: greet with sayHello/sayGoodbye', () => { it('should create specialized greeting functions', () => { function greet(greeting, name) { return `${greeting}, ${name}!` } const sayHello = greet.bind(null, "Hello") const sayGoodbye = greet.bind(null, "Goodbye") expect(sayHello("Alice")).toBe("Hello, Alice!") expect(sayHello("Bob")).toBe("Hello, Bob!") expect(sayGoodbye("Alice")).toBe("Goodbye, Alice!") }) }) }) describe('The 5 Binding Rules', () => { describe('Rule 1: new Binding', () => { it('should bind this to new object with constructor function', () => { function Person(name) { this.name = name } const alice = new Person('Alice') expect(alice.name).toBe('Alice') }) it('should bind this to new object with ES6 class', () => { class Person { constructor(name) { this.name = name } } const bob = new Person('Bob') expect(bob.name).toBe('Bob') }) it('should create separate instances with their own this', () => { class Counter { constructor() { this.count = 0 } increment() { this.count++ } } const counter1 = new Counter() const counter2 = new Counter() counter1.increment() counter1.increment() counter2.increment() expect(counter1.count).toBe(2) expect(counter2.count).toBe(1) }) it('should allow this to reference instance methods', () => { class Calculator { constructor(value) { this.value = value } add(n) { this.value += n return this } multiply(n) { this.value *= n return this } } const calc = new Calculator(5) calc.add(3).multiply(2) expect(calc.value).toBe(16) }) it('should return the new object unless function returns an object', () => { function ReturnsNothing(name) { this.name = name } function ReturnsObject(name) { this.name = name return { customName: 'Custom' } } function ReturnsPrimitive(name) { this.name = name return 42 // Primitive return is ignored } const obj1 = new ReturnsNothing('Alice') const obj2 = new ReturnsObject('Bob') const obj3 = new ReturnsPrimitive('Charlie') expect(obj1.name).toBe('Alice') expect(obj2.customName).toBe('Custom') expect(obj2.name).toBeUndefined() expect(obj3.name).toBe('Charlie') // Primitive ignored }) it('should set up prototype chain correctly', () => { class Animal { speak() { return 'Some sound' } } class Dog extends Animal { speak() { return 'Woof!' } } const dog = new Dog() expect(dog.speak()).toBe('Woof!') expect(dog instanceof Dog).toBe(true) expect(dog instanceof Animal).toBe(true) }) it('should have new binding override explicit binding', () => { function Person(name) { this.name = name } const boundPerson = Person.bind({ name: 'Bound' }) const alice = new boundPerson('Alice') // new overrides bind expect(alice.name).toBe('Alice') }) }) describe('Rule 2: Explicit Binding (call/apply/bind)', () => { it('should set this with call()', () => { function greet() { return `Hello, ${this.name}` } const alice = { name: 'Alice' } expect(greet.call(alice)).toBe('Hello, Alice') }) it('should set this with apply()', () => { function greet() { return `Hello, ${this.name}` } const bob = { name: 'Bob' } expect(greet.apply(bob)).toBe('Hello, Bob') }) it('should set this with bind()', () => { function greet() { return `Hello, ${this.name}` } const charlie = { name: 'Charlie' } const boundGreet = greet.bind(charlie) expect(boundGreet()).toBe('Hello, Charlie') }) it('should have explicit binding override implicit binding', () => { const alice = { name: 'Alice', greet() { return `Hi, I'm ${this.name}` } } const bob = { name: 'Bob' } // Even though called on alice, we force this to be bob expect(alice.greet.call(bob)).toBe("Hi, I'm Bob") }) it('should handle null/undefined thisArg in strict mode', () => { function getThis() { return this } // In strict mode with null/undefined, this remains null/undefined expect(getThis.call(null)).toBe(null) expect(getThis.call(undefined)).toBe(undefined) }) }) describe('Rule 3: Implicit Binding (Method Call)', () => { it('should bind this to the object before the dot', () => { const user = { name: 'Alice', getName() { return this.name } } expect(user.getName()).toBe('Alice') }) it('should use the immediate object for nested objects', () => { const company = { name: 'TechCorp', department: { name: 'Engineering', getName() { return this.name } } } // this is department, not company expect(company.department.getName()).toBe('Engineering') }) it('should allow method chaining with this', () => { const calculator = { value: 0, add(n) { this.value += n return this }, subtract(n) { this.value -= n return this }, getResult() { return this.value } } const result = calculator.add(10).subtract(3).add(5).getResult() expect(result).toBe(12) }) it('should lose implicit binding when method is extracted', () => { const user = { name: 'Alice', getName() { return this?.name } } const getName = user.getName // Lost binding - this is undefined in strict mode expect(getName()).toBeUndefined() }) it('should lose implicit binding in callbacks', () => { const user = { name: 'Alice', getName() { return this?.name } } function executeCallback(callback) { return callback() } // Passing method as callback loses binding expect(executeCallback(user.getName)).toBeUndefined() }) it('should work with computed property access', () => { const obj = { name: 'Object', method() { return this.name } } const methodName = 'method' expect(obj[methodName]()).toBe('Object') }) }) describe('Rule 4: Default Binding', () => { it('should have undefined this in strict mode for plain function calls', () => { function getThis() { return this } // Vitest runs in strict mode expect(getThis()).toBeUndefined() }) it('should have undefined this in IIFE in strict mode', () => { const result = (function() { return this })() expect(result).toBeUndefined() }) it('should have undefined this in nested function calls', () => { const obj = { name: 'Object', method() { function inner() { return this } return inner() } } // Inner function uses default binding expect(obj.method()).toBeUndefined() }) }) describe('Rule 5: Arrow Functions (Lexical this)', () => { it('should inherit this from enclosing scope', () => { const obj = { name: 'Object', method() { const arrow = () => this.name return arrow() } } expect(obj.method()).toBe('Object') }) it('should not change this with call/apply/bind on arrow functions', () => { const obj = { name: 'Original', getArrow() { return () => this.name } } const arrow = obj.getArrow() const other = { name: 'Other' } // Arrow function ignores explicit binding expect(arrow()).toBe('Original') expect(arrow.call(other)).toBe('Original') expect(arrow.apply(other)).toBe('Original') expect(arrow.bind(other)()).toBe('Original') }) it('should preserve this in callbacks with arrow functions', () => { class Counter { constructor() { this.count = 0 } incrementWithArrow() { [1, 2, 3].forEach(() => { this.count++ }) } } const counter = new Counter() counter.incrementWithArrow() expect(counter.count).toBe(3) }) it('should work with arrow function class fields', () => { class Button { constructor(label) { this.label = label } // Arrow function as class field handleClick = () => { return `Clicked: ${this.label}` } } const btn = new Button('Submit') const handler = btn.handleClick // Extract method // Still works because arrow binds lexically expect(handler()).toBe('Clicked: Submit') }) it('should not have arrow functions work as object methods', () => { const user = { name: 'Alice', // Arrow function as method - BAD! greet: () => { return this?.name } } // this is not user, it's the enclosing scope (undefined in strict mode) expect(user.greet()).toBeUndefined() }) it('should capture this at definition time, not call time', () => { function createArrow() { return () => this } const obj1 = { name: 'obj1' } const obj2 = { name: 'obj2' } // Arrow is created with obj1 as this const arrow = createArrow.call(obj1) // Calling with obj2 doesn't change anything expect(arrow.call(obj2)).toBe(obj1) }) }) describe('Arrow Function Limitations', () => { it('should throw when using arrow function with new', () => { const ArrowClass = () => {} expect(() => { new ArrowClass() }).toThrow(TypeError) }) it('should not have arguments object in arrow functions', () => { // Arrow functions don't have their own arguments // They would reference arguments from enclosing scope const arrowWithRest = (...args) => { return args } expect(arrowWithRest(1, 2, 3)).toEqual([1, 2, 3]) }) it('should demonstrate regular vs arrow in nested context', () => { const obj = { name: "Object", regularMethod: function() { // Nested regular function - loses 'this' function inner() { return this } return inner() }, arrowMethod: function() { // Nested arrow function - keeps 'this' const innerArrow = () => { return this.name } return innerArrow() } } expect(obj.regularMethod()).toBeUndefined() expect(obj.arrowMethod()).toBe("Object") }) }) }) describe('call() Method', () => { it('should invoke function immediately with specified this', () => { function greet() { return `Hello, ${this.name}` } expect(greet.call({ name: 'World' })).toBe('Hello, World') }) it('should pass arguments individually', () => { function introduce(greeting, punctuation) { return `${greeting}, I'm ${this.name}${punctuation}` } const alice = { name: 'Alice' } expect(introduce.call(alice, 'Hi', '!')).toBe("Hi, I'm Alice!") }) it('should allow method borrowing', () => { const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 } const result = Array.prototype.slice.call(arrayLike) expect(result).toEqual(['a', 'b', 'c']) }) it('should allow borrowing join method', () => { const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 } const result = Array.prototype.join.call(arrayLike, '-') expect(result).toBe('a-b-c') }) it('should work with prototype methods', () => { const obj = { 0: 1, 1: 2, 2: 3, length: 3 } const sum = Array.prototype.reduce.call(obj, (acc, val) => acc + val, 0) expect(sum).toBe(6) }) it('should allow calling parent class methods', () => { class Animal { speak() { return `${this.name} makes a sound` } } class Dog extends Animal { constructor(name) { super() this.name = name } speak() { const parentSays = Animal.prototype.speak.call(this) return `${parentSays}. Woof!` } } const dog = new Dog('Rex') expect(dog.speak()).toBe('Rex makes a sound. Woof!') }) it('should work with no arguments after thisArg', () => { function getThisName() { return this.name } expect(getThisName.call({ name: 'Test' })).toBe('Test') }) it('should keep primitives as-is in strict mode when passed as thisArg', () => { function getThis() { return this } // In strict mode, primitives are NOT converted to wrapper objects const result = getThis.call(42) expect(result).toBe(42) expect(typeof result).toBe('number') }) }) describe('apply() Method', () => { it('should invoke function immediately with specified this', () => { function greet() { return `Hello, ${this.name}` } expect(greet.apply({ name: 'World' })).toBe('Hello, World') }) it('should pass arguments as an array', () => { function introduce(greeting, punctuation) { return `${greeting}, I'm ${this.name}${punctuation}` } const bob = { name: 'Bob' } expect(introduce.apply(bob, ['Hey', '?'])).toBe("Hey, I'm Bob?") }) it('should work with Math.max', () => { const numbers = [5, 2, 9, 1, 7] const max = Math.max.apply(null, numbers) expect(max).toBe(9) }) it('should work with Math.min', () => { const numbers = [5, 2, 9, 1, 7] const min = Math.min.apply(null, numbers) expect(min).toBe(1) }) it('should work with array-like arguments', () => { function sum() { return Array.prototype.reduce.call(arguments, (acc, n) => acc + n, 0) } const numbers = [1, 2, 3, 4, 5] expect(sum.apply(null, numbers)).toBe(15) }) it('should work with empty array', () => { function returnArgs() { return Array.prototype.slice.call(arguments) } expect(returnArgs.apply(null, [])).toEqual([]) }) it('should work with null/undefined args array', () => { function noArgs() { return 'called' } expect(noArgs.apply(null, null)).toBe('called') expect(noArgs.apply(null, undefined)).toBe('called') }) it('should allow combining arrays with concat-like behavior', () => { const arr1 = [1, 2, 3] const arr2 = [4, 5, 6] Array.prototype.push.apply(arr1, arr2) expect(arr1).toEqual([1, 2, 3, 4, 5, 6]) }) it('should be replaceable by spread operator for Math operations', () => { const numbers = [5, 2, 9, 1, 7] // Old way with apply const maxApply = Math.max.apply(null, numbers) const minApply = Math.min.apply(null, numbers) // Modern way with spread const maxSpread = Math.max(...numbers) const minSpread = Math.min(...numbers) expect(maxApply).toBe(maxSpread) expect(minApply).toBe(minSpread) expect(maxSpread).toBe(9) expect(minSpread).toBe(1) }) }) describe('bind() Method', () => { it('should return a new function', () => { function greet() { return `Hello, ${this.name}` } const alice = { name: 'Alice' } const boundGreet = greet.bind(alice) expect(typeof boundGreet).toBe('function') expect(boundGreet).not.toBe(greet) }) it('should not invoke the function immediately', () => { let called = false function setFlag() { called = true } const bound = setFlag.bind({}) expect(called).toBe(false) bound() expect(called).toBe(true) }) it('should permanently bind this', () => { function getName() { return this.name } const alice = { name: 'Alice' } const bob = { name: 'Bob' } const boundToAlice = getName.bind(alice) expect(boundToAlice()).toBe('Alice') expect(boundToAlice.call(bob)).toBe('Alice') // call ignored expect(boundToAlice.apply(bob)).toBe('Alice') // apply ignored }) it('should not allow rebinding with another bind', () => { function getName() { return this.name } const alice = { name: 'Alice' } const bob = { name: 'Bob' } const boundToAlice = getName.bind(alice) const triedRebind = boundToAlice.bind(bob) expect(triedRebind()).toBe('Alice') // Still Alice! }) it('should support partial application', () => { function multiply(a, b) { return a * b } const double = multiply.bind(null, 2) const triple = multiply.bind(null, 3) expect(double(5)).toBe(10) expect(triple(5)).toBe(15) }) it('should support partial application with multiple arguments', () => { function greet(greeting, punctuation, name) { return `${greeting}, ${name}${punctuation}` } const sayHello = greet.bind(null, 'Hello', '!') expect(sayHello('Alice')).toBe('Hello, Alice!') expect(sayHello('Bob')).toBe('Hello, Bob!') }) it('should work with event handler pattern', () => { class Button { constructor(label) { this.label = label this.handleClick = this.handleClick.bind(this) } handleClick() { return `${this.label} clicked` } } const btn = new Button('Submit') const handler = btn.handleClick expect(handler()).toBe('Submit clicked') }) it('should work with setTimeout pattern', () => { class Delayed { constructor(message) { this.message = message } getMessage() { return this.message } } const delayed = new Delayed('Hello') const boundGetMessage = delayed.getMessage.bind(delayed) // Simulating what setTimeout would do const callback = boundGetMessage expect(callback()).toBe('Hello') }) it('should preserve the length property minus bound args', () => { function fn(a, b, c) { return a + b + c } const bound0 = fn.bind(null) const bound1 = fn.bind(null, 1) const bound2 = fn.bind(null, 1, 2) expect(fn.length).toBe(3) expect(bound0.length).toBe(3) expect(bound1.length).toBe(2) expect(bound2.length).toBe(1) }) it('should work with new even when bound', () => { function Person(name) { this.name = name } const BoundPerson = Person.bind({ name: 'Ignored' }) const alice = new BoundPerson('Alice') // new overrides the bound this expect(alice.name).toBe('Alice') }) }) describe('Common Patterns', () => { describe('Method Borrowing', () => { it('should borrow array methods for array-like objects', () => { const arrayLike = { 0: 'first', 1: 'second', 2: 'third', length: 3 } const mapped = Array.prototype.map.call(arrayLike, item => item.toUpperCase()) expect(mapped).toEqual(['FIRST', 'SECOND', 'THIRD']) }) it('should borrow methods between similar objects', () => { const logger = { prefix: '[LOG]', log(message) { return `${this.prefix} ${message}` } } const errorLogger = { prefix: '[ERROR]' } expect(logger.log.call(errorLogger, 'Something failed')).toBe('[ERROR] Something failed') }) it('should use hasOwnProperty safely', () => { const obj = Object.create(null) // No prototype obj.name = 'test' // obj.hasOwnProperty would fail, but we can borrow it const hasOwn = Object.prototype.hasOwnProperty.call(obj, 'name') expect(hasOwn).toBe(true) }) }) describe('Partial Application', () => { it('should create specialized functions', () => { function log(level, timestamp, message) { return `[${level}] ${timestamp}: ${message}` } const logError = log.bind(null, 'ERROR') const logInfo = log.bind(null, 'INFO') expect(logError('2024-01-15', 'Failed')).toBe('[ERROR] 2024-01-15: Failed') expect(logInfo('2024-01-15', 'Started')).toBe('[INFO] 2024-01-15: Started') }) it('should allow creating multiplier functions', () => { function multiply(a, b) { return a * b } const double = multiply.bind(null, 2) const triple = multiply.bind(null, 3) const quadruple = multiply.bind(null, 4) expect(double(10)).toBe(20) expect(triple(10)).toBe(30) expect(quadruple(10)).toBe(40) }) it('should work with more complex functions', () => { function createUrl(protocol, domain, path) { return `${protocol}://${domain}${path}` } const httpUrl = createUrl.bind(null, 'https') const apiUrl = httpUrl.bind(null, 'api.example.com') expect(apiUrl('/users')).toBe('https://api.example.com/users') expect(apiUrl('/posts')).toBe('https://api.example.com/posts') }) }) describe('Preserving Context in Classes', () => { it('should preserve context with bind in constructor', () => { class Timer { constructor() { this.seconds = 0 this.tick = this.tick.bind(this) } tick() { this.seconds++ return this.seconds } } const timer = new Timer() const tick = timer.tick expect(tick()).toBe(1) expect(tick()).toBe(2) }) it('should preserve context with arrow class fields', () => { class Timer { seconds = 0 tick = () => { this.seconds++ return this.seconds } } const timer = new Timer() const tick = timer.tick expect(tick()).toBe(1) expect(tick()).toBe(2) }) }) }) describe('Gotchas and Edge Cases', () => { describe('Lost Context Scenarios', () => { it('should demonstrate lost context in forEach without arrow', () => { const calculator = { value: 10, addAll(numbers) { const self = this // Old-school workaround numbers.forEach(function(n) { self.value += n }) return this.value } } expect(calculator.addAll([1, 2, 3])).toBe(16) }) it('should fix lost context with arrow function', () => { const calculator = { value: 10, addAll(numbers) { numbers.forEach((n) => { this.value += n }) return this.value } } expect(calculator.addAll([1, 2, 3])).toBe(16) }) it('should fix lost context with thisArg parameter', () => { const calculator = { value: 10, addAll(numbers) { numbers.forEach(function(n) { this.value += n }, this) // Pass this as second argument return this.value } } expect(calculator.addAll([1, 2, 3])).toBe(16) }) }) describe('this in Different Contexts', () => { it('should have correct this in nested methods', () => { const outer = { name: 'Outer', inner: { name: 'Inner', getOuterName() { // Can't access outer.name via this return this.name } } } expect(outer.inner.getOuterName()).toBe('Inner') }) it('should demonstrate closure workaround for nested this', () => { const outer = { name: 'Outer', createInner() { const outerThis = this return { name: 'Inner', getOuterName() { return outerThis.name } } } } const inner = outer.createInner() expect(inner.getOuterName()).toBe('Outer') }) }) describe('Binding Priority', () => { it('should have new override bind', () => { function Foo(value) { this.value = value } const BoundFoo = Foo.bind({ value: 'bound' }) const instance = new BoundFoo('new') expect(instance.value).toBe('new') }) it('should have explicit override implicit', () => { const obj1 = { name: 'obj1', getName() { return this.name } } const obj2 = { name: 'obj2' } expect(obj1.getName()).toBe('obj1') expect(obj1.getName.call(obj2)).toBe('obj2') }) it('should have implicit override default', () => { function getName() { return this?.name } const obj = { name: 'obj', getName } expect(getName()).toBeUndefined() // Default binding expect(obj.getName()).toBe('obj') // Implicit binding }) }) }) describe('Quiz Questions from Documentation', () => { it('Question 1: extracted method loses context', () => { const user = { name: 'Alice', greet() { return `Hi, I'm ${this?.name}` } } const greet = user.greet expect(greet()).toBe("Hi, I'm undefined") }) it('Question 2: arrow function class fields preserve context', () => { class Counter { count = 0 increment = () => { this.count++ } } const counter = new Counter() const inc = counter.increment inc() inc() expect(counter.count).toBe(2) }) it('Question 3: bind cannot be overridden by call', () => { function greet() { return `Hello, ${this.name}!` } const alice = { name: 'Alice' } const bob = { name: 'Bob' } const greetAlice = greet.bind(alice) expect(greetAlice.call(bob)).toBe('Hello, Alice!') }) it('Question 4: nested object uses immediate parent as this', () => { const obj = { name: 'Outer', inner: { name: 'Inner', getName() { return this.name } } } expect(obj.inner.getName()).toBe('Inner') }) it('Question 5: forEach callback loses this context', () => { const calculator = { value: 10, add(numbers) { // This demonstrates the BROKEN behavior let localValue = this.value numbers.forEach(function(n) { // this.value would be undefined here in strict mode // so we can't actually add to it localValue += 0 // simulating the broken behavior })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
true
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/object-oriented/inheritance-polymorphism/inheritance-polymorphism.test.js
tests/object-oriented/inheritance-polymorphism/inheritance-polymorphism.test.js
import { describe, it, expect } from 'vitest' describe('Inheritance & Polymorphism', () => { // ============================================================ // BASE CLASSES FOR TESTING // ============================================================ class Character { constructor(name, health = 100) { this.name = name this.health = health } introduce() { return `I am ${this.name} with ${this.health} HP` } attack() { return `${this.name} attacks!` } takeDamage(amount) { this.health -= amount return `${this.name} takes ${amount} damage! (${this.health} HP left)` } get isAlive() { return this.health > 0 } static createRandom() { const names = ['Hero', 'Villain', 'Sidekick'] return new this(names[Math.floor(Math.random() * names.length)]) } } class Warrior extends Character { constructor(name) { super(name, 150) // Warriors have more health this.rage = 0 this.weapon = 'Sword' } attack() { return `${this.name} swings a mighty sword!` } battleCry() { this.rage += 10 return `${this.name} roars with fury! Rage: ${this.rage}` } } class Mage extends Character { constructor(name) { super(name, 80) // Mages have less health this.mana = 100 } attack() { return `${this.name} casts a fireball!` } castSpell(spell) { this.mana -= 10 return `${this.name} casts ${spell}!` } } class Archer extends Character { constructor(name) { super(name, 90) this.arrows = 20 } attack() { this.arrows-- return `${this.name} fires an arrow!` } } // ============================================================ // CLASS INHERITANCE WITH EXTENDS // ============================================================ describe('Class Inheritance with extends', () => { it('should inherit properties from parent class', () => { const warrior = new Warrior('Conan') // Inherited from Character expect(warrior.name).toBe('Conan') expect(warrior.health).toBe(150) // Custom value passed to super() // Unique to Warrior expect(warrior.rage).toBe(0) expect(warrior.weapon).toBe('Sword') }) it('should inherit methods from parent class', () => { const warrior = new Warrior('Conan') // Inherited method works expect(warrior.introduce()).toBe('I am Conan with 150 HP') expect(warrior.takeDamage(20)).toBe('Conan takes 20 damage! (130 HP left)') }) it('should inherit getters from parent class', () => { const warrior = new Warrior('Conan') expect(warrior.isAlive).toBe(true) warrior.health = 0 expect(warrior.isAlive).toBe(false) }) it('should inherit static methods from parent class', () => { const randomWarrior = Warrior.createRandom() expect(randomWarrior).toBeInstanceOf(Warrior) expect(randomWarrior).toBeInstanceOf(Character) expect(['Hero', 'Villain', 'Sidekick']).toContain(randomWarrior.name) }) it('should allow child classes to have unique methods', () => { const warrior = new Warrior('Conan') const mage = new Mage('Gandalf') // Warrior-specific method expect(warrior.battleCry()).toBe('Conan roars with fury! Rage: 10') expect(typeof mage.battleCry).toBe('undefined') // Mage-specific method expect(mage.castSpell('Fireball')).toBe('Gandalf casts Fireball!') expect(typeof warrior.castSpell).toBe('undefined') }) }) // ============================================================ // THE SUPER KEYWORD // ============================================================ describe('The super Keyword', () => { it('super() should call parent constructor with arguments', () => { const warrior = new Warrior('Conan') // super(name, 150) was called in Warrior constructor expect(warrior.name).toBe('Conan') expect(warrior.health).toBe(150) }) it('super.method() should call parent method', () => { class ExtendedWarrior extends Character { constructor(name) { super(name, 150) this.weapon = 'Axe' } attack() { const baseAttack = super.attack() // "Name attacks!" return `${baseAttack} With an ${this.weapon}!` } describe() { return `${super.introduce()} - Warrior Class` } } const hero = new ExtendedWarrior('Gimli') expect(hero.attack()).toBe('Gimli attacks! With an Axe!') expect(hero.describe()).toBe('I am Gimli with 150 HP - Warrior Class') }) it('should throw ReferenceError if super() is not called before this', () => { // This would cause an error - we test the concept expect(() => { class BrokenWarrior extends Character { constructor(name) { // Intentionally not calling super() first // this.rage = 0 // Would throw ReferenceError super(name) } } new BrokenWarrior('Test') }).not.toThrow() // The fixed version doesn't throw }) }) // ============================================================ // METHOD OVERRIDING // ============================================================ describe('Method Overriding', () => { it('should override parent method with child implementation', () => { const character = new Character('Generic') const warrior = new Warrior('Conan') const mage = new Mage('Gandalf') const archer = new Archer('Legolas') // Each class has different attack() implementation expect(character.attack()).toBe('Generic attacks!') expect(warrior.attack()).toBe('Conan swings a mighty sword!') expect(mage.attack()).toBe('Gandalf casts a fireball!') expect(archer.attack()).toBe('Legolas fires an arrow!') }) it('should allow extending parent behavior with super.method()', () => { class VerboseWarrior extends Character { attack() { return `${super.attack()} POWERFULLY!` } } const hero = new VerboseWarrior('Hero') expect(hero.attack()).toBe('Hero attacks! POWERFULLY!') }) it('should allow complete replacement of parent behavior', () => { class SilentWarrior extends Character { attack() { return '...' // Completely different, no super.attack() } } const ninja = new SilentWarrior('Shadow') expect(ninja.attack()).toBe('...') }) }) // ============================================================ // POLYMORPHISM // ============================================================ describe('Polymorphism', () => { it('should treat different types uniformly through common interface', () => { const party = [ new Warrior('Conan'), new Mage('Gandalf'), new Archer('Legolas'), new Character('Villager') ] // All can attack(), each in their own way const attacks = party.map(char => char.attack()) expect(attacks).toEqual([ 'Conan swings a mighty sword!', 'Gandalf casts a fireball!', 'Legolas fires an arrow!', 'Villager attacks!' ]) }) it('should allow functions to work with any subtype', () => { function executeBattle(characters) { return characters.map(char => char.attack()) } const team1 = [new Warrior('W1'), new Warrior('W2')] const team2 = [new Mage('M1'), new Archer('A1')] const mixedTeam = [new Warrior('W'), new Mage('M'), new Archer('A')] // Same function works with any combination expect(executeBattle(team1)).toHaveLength(2) expect(executeBattle(team2)).toHaveLength(2) expect(executeBattle(mixedTeam)).toHaveLength(3) }) it('instanceof should check entire prototype chain', () => { const warrior = new Warrior('Conan') expect(warrior instanceof Warrior).toBe(true) expect(warrior instanceof Character).toBe(true) expect(warrior instanceof Object).toBe(true) expect(warrior instanceof Mage).toBe(false) }) it('should enable the Open/Closed principle', () => { // We can add new character types without changing existing code class Healer extends Character { attack() { return `${this.name} heals the party!` } } // Existing function works with new type function getAttacks(chars) { return chars.map(c => c.attack()) } const team = [new Warrior('W'), new Healer('H')] const attacks = getAttacks(team) expect(attacks).toContain('W swings a mighty sword!') expect(attacks).toContain('H heals the party!') }) }) // ============================================================ // PROTOTYPE CHAIN (Under the Hood) // ============================================================ describe('Prototype Chain', () => { it('should set up prototype chain correctly with extends', () => { const warrior = new Warrior('Conan') // Instance -> Warrior.prototype -> Character.prototype -> Object.prototype expect(Object.getPrototypeOf(warrior)).toBe(Warrior.prototype) expect(Object.getPrototypeOf(Warrior.prototype)).toBe(Character.prototype) expect(Object.getPrototypeOf(Character.prototype)).toBe(Object.prototype) }) it('should find methods by walking up the prototype chain', () => { const warrior = new Warrior('Conan') // attack() is on Warrior.prototype (overridden) expect(Warrior.prototype.hasOwnProperty('attack')).toBe(true) // introduce() is on Character.prototype (inherited) expect(Warrior.prototype.hasOwnProperty('introduce')).toBe(false) expect(Character.prototype.hasOwnProperty('introduce')).toBe(true) // Both work on the instance expect(warrior.attack()).toContain('sword') expect(warrior.introduce()).toContain('Conan') }) }) // ============================================================ // COMPOSITION PATTERN // ============================================================ describe('Composition Pattern', () => { it('should compose behaviors instead of inheriting', () => { // Behavior factories const canFly = (state) => ({ fly() { return `${state.name} soars through the sky!` } }) const canCast = (state) => ({ castSpell(spell) { return `${state.name} casts ${spell}!` } }) const canFight = (state) => ({ attack() { return `${state.name} attacks!` } }) // Compose a flying mage function createFlyingMage(name) { const state = { name, health: 100, mana: 50 } return { ...state, ...canFly(state), ...canCast(state), ...canFight(state) } } const merlin = createFlyingMage('Merlin') expect(merlin.fly()).toBe('Merlin soars through the sky!') expect(merlin.castSpell('Ice')).toBe('Merlin casts Ice!') expect(merlin.attack()).toBe('Merlin attacks!') expect(merlin.health).toBe(100) expect(merlin.mana).toBe(50) }) it('should allow mixing and matching behaviors freely', () => { const canSwim = (state) => ({ swim() { return `${state.name} swims!` } }) const canFly = (state) => ({ fly() { return `${state.name} flies!` } }) // Duck can both swim and fly function createDuck(name) { const state = { name } return { ...state, ...canSwim(state), ...canFly(state) } } // Fish can only swim function createFish(name) { const state = { name } return { ...state, ...canSwim(state) } } const duck = createDuck('Donald') const fish = createFish('Nemo') expect(duck.swim()).toBe('Donald swims!') expect(duck.fly()).toBe('Donald flies!') expect(fish.swim()).toBe('Nemo swims!') expect(fish.fly).toBeUndefined() }) }) // ============================================================ // MIXINS // ============================================================ describe('Mixins', () => { it('should mix behavior into class prototype with Object.assign', () => { const Swimmer = { swim() { return `${this.name} swims!` } } const Flyer = { fly() { return `${this.name} flies!` } } class Animal { constructor(name) { this.name = name } } class Duck extends Animal {} Object.assign(Duck.prototype, Swimmer, Flyer) const donald = new Duck('Donald') expect(donald.swim()).toBe('Donald swims!') expect(donald.fly()).toBe('Donald flies!') }) it('should support functional mixin pattern', () => { const withLogging = (Base) => class extends Base { log(message) { return `[${this.name}]: ${message}` } } const withTimestamp = (Base) => class extends Base { getTimestamp() { return '2024-01-15' } } class Character { constructor(name) { this.name = name } } // Stack mixins class LoggedCharacter extends withTimestamp(withLogging(Character)) { doAction() { return this.log(`Action at ${this.getTimestamp()}`) } } const hero = new LoggedCharacter('Aragorn') expect(hero.log('Hello')).toBe('[Aragorn]: Hello') expect(hero.getTimestamp()).toBe('2024-01-15') expect(hero.doAction()).toBe('[Aragorn]: Action at 2024-01-15') }) it('should handle mixin name collisions (last one wins)', () => { const MixinA = { greet() { return 'Hello from A' } } const MixinB = { greet() { return 'Hello from B' } } class Base {} Object.assign(Base.prototype, MixinA, MixinB) const instance = new Base() // MixinB's greet() overwrites MixinA's expect(instance.greet()).toBe('Hello from B') }) }) // ============================================================ // COMMON MISTAKES // ============================================================ describe('Common Mistakes', () => { it('should demonstrate that inherited methods can be accidentally lost', () => { class Parent { method() { return 'parent' } } class Child extends Parent { method() { return 'child' } // Completely replaces parent } const child = new Child() expect(child.method()).toBe('child') // To preserve parent behavior, use super.method() class BetterChild extends Parent { method() { return `${super.method()} + child` } } const betterChild = new BetterChild() expect(betterChild.method()).toBe('parent + child') }) it('should show the problem with inheriting for code reuse only', () => { // BAD: Stack is NOT an Array (violates IS-A) // A Stack should only allow push/pop, not shift/unshift class BadStack extends Array { peek() { return this[this.length - 1] } } const badStack = new BadStack() badStack.push(1, 2, 3) // Problem: Array methods we DON'T want are available expect(badStack.shift()).toBe(1) // Stacks shouldn't allow this! // GOOD: Composition - Stack HAS-A array class GoodStack { #items = [] push(item) { this.#items.push(item) } pop() { return this.#items.pop() } peek() { return this.#items[this.#items.length - 1] } } const goodStack = new GoodStack() goodStack.push(1) goodStack.push(2) expect(goodStack.peek()).toBe(2) expect(typeof goodStack.shift).toBe('undefined') // Correctly unavailable }) }) // ============================================================ // SHAPE POLYMORPHISM (Interview Question Example) // ============================================================ describe('Shape Polymorphism (Interview Example)', () => { class Shape { area() { return 0 } } class Rectangle extends Shape { constructor(width, height) { super() this.width = width this.height = height } area() { return this.width * this.height } } class Circle extends Shape { constructor(radius) { super() this.radius = radius } area() { return Math.PI * this.radius ** 2 } } it('should calculate area differently for each shape type', () => { const rectangle = new Rectangle(4, 5) const circle = new Circle(3) expect(rectangle.area()).toBe(20) expect(circle.area()).toBeCloseTo(28.274, 2) // Math.PI * 9 }) it('should treat all shapes uniformly through common interface', () => { const shapes = [new Rectangle(4, 5), new Circle(3), new Shape()] const areas = shapes.map(s => s.area()) expect(areas[0]).toBe(20) expect(areas[1]).toBeCloseTo(28.274, 2) expect(areas[2]).toBe(0) // Base shape }) it('should verify instanceof for shape hierarchy', () => { const rect = new Rectangle(2, 3) const circle = new Circle(5) expect(rect instanceof Rectangle).toBe(true) expect(rect instanceof Shape).toBe(true) expect(circle instanceof Circle).toBe(true) expect(circle instanceof Shape).toBe(true) expect(rect instanceof Circle).toBe(false) }) }) // ============================================================ // MULTI-LEVEL INHERITANCE // ============================================================ describe('Multi-level Inheritance', () => { it('should support multi-level inheritance (keep shallow!)', () => { class Entity { constructor(id) { this.id = id } } class Character extends Entity { constructor(id, name) { super(id) this.name = name } } class Warrior extends Character { constructor(id, name) { super(id, name) this.class = 'Warrior' } } const hero = new Warrior(1, 'Conan') expect(hero.id).toBe(1) expect(hero.name).toBe('Conan') expect(hero.class).toBe('Warrior') expect(hero instanceof Warrior).toBe(true) expect(hero instanceof Character).toBe(true) expect(hero instanceof Entity).toBe(true) }) it('should call super() chain correctly', () => { const calls = [] class A { constructor() { calls.push('A') } } class B extends A { constructor() { super() calls.push('B') } } class C extends B { constructor() { super() calls.push('C') } } new C() // Constructors called from parent to child expect(calls).toEqual(['A', 'B', 'C']) }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/object-oriented/factories-classes/factories-classes.test.js
tests/object-oriented/factories-classes/factories-classes.test.js
import { describe, it, expect } from 'vitest' describe('Factories and Classes', () => { // =========================================== // Opening Example: Factory vs Class // =========================================== describe('Opening Example: Factory vs Class', () => { it('should create objects with factory function', () => { function createPlayer(name) { return { name, health: 100, attack() { return `${this.name} attacks!` } } } const player = createPlayer('Alice') expect(player.name).toBe('Alice') expect(player.health).toBe(100) expect(player.attack()).toBe('Alice attacks!') }) it('should create objects with class', () => { class Enemy { constructor(name) { this.name = name this.health = 100 } attack() { return `${this.name} attacks!` } } const enemy = new Enemy('Goblin') expect(enemy.name).toBe('Goblin') expect(enemy.health).toBe(100) expect(enemy.attack()).toBe('Goblin attacks!') }) it('should show both patterns produce similar results', () => { function createPlayer(name) { return { name, health: 100, attack() { return `${this.name} attacks!` } } } class Enemy { constructor(name) { this.name = name this.health = 100 } attack() { return `${this.name} attacks!` } } const player = createPlayer('Alice') const enemy = new Enemy('Goblin') // Both have same structure expect(player.name).toBe('Alice') expect(enemy.name).toBe('Goblin') expect(player.health).toBe(enemy.health) // Both attack methods work expect(player.attack()).toBe('Alice attacks!') expect(enemy.attack()).toBe('Goblin attacks!') }) }) // =========================================== // Part 1: The Problem — Manual Object Creation // =========================================== describe('Part 1: The Problem — Manual Object Creation', () => { it('should show manual object creation is repetitive', () => { const player1 = { name: 'Alice', health: 100, attack() { return `${this.name} attacks!` } } const player2 = { name: 'Bob', health: 100, attack() { return `${this.name} attacks!` } } expect(player1.attack()).toBe('Alice attacks!') expect(player2.attack()).toBe('Bob attacks!') // Each object has its own copy of the method expect(player1.attack).not.toBe(player2.attack) }) }) // =========================================== // Part 2: Factory Functions // =========================================== describe('Part 2: Factory Functions', () => { describe('Basic Factory Function', () => { it('should create objects with a factory function', () => { function createPlayer(name) { return { name, health: 100, level: 1, attack() { return `${this.name} attacks for ${10 + this.level * 2} damage!` } } } const alice = createPlayer('Alice') const bob = createPlayer('Bob') expect(alice.name).toBe('Alice') expect(bob.name).toBe('Bob') expect(alice.health).toBe(100) expect(alice.attack()).toBe('Alice attacks for 12 damage!') }) it('should create independent objects', () => { function createCounter() { return { count: 0, increment() { this.count++ } } } const counter1 = createCounter() const counter2 = createCounter() counter1.increment() counter1.increment() counter1.increment() counter2.increment() expect(counter1.count).toBe(3) expect(counter2.count).toBe(1) }) }) describe('Factory with Multiple Parameters', () => { it('should accept multiple parameters', () => { function createEnemy(name, health, attackPower) { return { name, health, attackPower, isAlive: true, attack(target) { return `${this.name} attacks ${target.name} for ${this.attackPower} damage!` }, takeDamage(amount) { this.health -= amount if (this.health <= 0) { this.health = 0 this.isAlive = false } return this.health } } } const goblin = createEnemy('Goblin', 50, 10) const dragon = createEnemy('Dragon', 500, 50) expect(goblin.health).toBe(50) expect(dragon.health).toBe(500) expect(goblin.attack(dragon)).toBe('Goblin attacks Dragon for 10 damage!') }) }) describe('Factory with Configuration Object', () => { it('should use defaults and merge with config', () => { function createCharacter(config = {}) { const defaults = { name: 'Unknown', health: 100, attackPower: 10, defense: 5 } return { ...defaults, ...config } } const warrior = createCharacter({ name: 'Warrior', health: 150, defense: 20 }) const mage = createCharacter({ name: 'Mage', attackPower: 30 }) const villager = createCharacter() expect(warrior.name).toBe('Warrior') expect(warrior.health).toBe(150) expect(warrior.defense).toBe(20) expect(warrior.attackPower).toBe(10) // default expect(mage.attackPower).toBe(30) expect(mage.health).toBe(100) // default expect(villager.name).toBe('Unknown') }) }) describe('Factory with Private Variables (Closures)', () => { it('should create truly private variables', () => { function createBankAccount(initialBalance = 0) { let balance = initialBalance return { deposit(amount) { if (amount > 0) balance += amount return balance }, withdraw(amount) { if (amount > 0 && amount <= balance) { balance -= amount } return balance }, getBalance() { return balance } } } const account = createBankAccount(1000) expect(account.getBalance()).toBe(1000) expect(account.deposit(500)).toBe(1500) expect(account.withdraw(200)).toBe(1300) // Private variable is not accessible expect(account.balance).toBe(undefined) // Can't modify balance directly account.balance = 1000000 expect(account.getBalance()).toBe(1300) }) it('should keep transaction history private', () => { function createAccount() { let balance = 0 const history = [] return { deposit(amount) { balance += amount history.push({ type: 'deposit', amount }) return balance }, getHistory() { return [...history] // return copy } } } const account = createAccount() account.deposit(100) account.deposit(50) const history = account.getHistory() expect(history).toHaveLength(2) expect(history[0]).toEqual({ type: 'deposit', amount: 100 }) // Modifying returned array doesn't affect internal state history.push({ type: 'fake', amount: 9999 }) expect(account.getHistory()).toHaveLength(2) // Can't access history directly expect(account.history).toBe(undefined) }) it('should have private functions', () => { function createCounter() { let count = 0 function logChange(action) { return `[LOG] ${action}: count is now ${count}` } return { increment() { count++ return logChange('increment') }, getCount() { return count } } } const counter = createCounter() expect(counter.increment()).toBe('[LOG] increment: count is now 1') expect(counter.getCount()).toBe(1) // Private function is not accessible expect(counter.logChange).toBe(undefined) }) }) describe('Factory Creating Different Types', () => { it('should return different object types based on input', () => { function createWeapon(type) { const weapons = { sword: { name: 'Sword', damage: 25, type: 'melee' }, bow: { name: 'Bow', damage: 20, type: 'ranged', range: 100 }, staff: { name: 'Staff', damage: 35, type: 'magic', manaCost: 10 } } if (!weapons[type]) { throw new Error(`Unknown weapon: ${type}`) } return { ...weapons[type] } } const sword = createWeapon('sword') const bow = createWeapon('bow') const staff = createWeapon('staff') expect(sword.damage).toBe(25) expect(bow.range).toBe(100) expect(staff.manaCost).toBe(10) expect(() => createWeapon('laser')).toThrow('Unknown weapon: laser') }) }) }) // =========================================== // Part 3: Constructor Functions // =========================================== describe('Part 3: Constructor Functions', () => { describe('Basic Constructor Function', () => { it('should create objects with new keyword', () => { function Player(name) { this.name = name this.health = 100 this.level = 1 } const alice = new Player('Alice') const bob = new Player('Bob') expect(alice.name).toBe('Alice') expect(bob.name).toBe('Bob') expect(alice.health).toBe(100) }) it('should work with instanceof', () => { function Player(name) { this.name = name } function Enemy(name) { this.name = name } const alice = new Player('Alice') const goblin = new Enemy('Goblin') expect(alice instanceof Player).toBe(true) expect(alice instanceof Enemy).toBe(false) expect(goblin instanceof Enemy).toBe(true) expect(goblin instanceof Object).toBe(true) }) }) describe('The new Keyword', () => { it('should simulate what new does', () => { function myNew(Constructor, ...args) { const obj = Object.create(Constructor.prototype) const result = Constructor.apply(obj, args) return typeof result === 'object' && result !== null ? result : obj } function Player(name) { this.name = name this.health = 100 } Player.prototype.attack = function () { return `${this.name} attacks!` } const player = myNew(Player, 'Alice') expect(player.name).toBe('Alice') expect(player.health).toBe(100) expect(player.attack()).toBe('Alice attacks!') expect(player instanceof Player).toBe(true) }) it('should return custom object if constructor returns one', () => { function ReturnsObject() { this.value = 42 return { custom: 'object' } } function ReturnsPrimitive() { this.value = 42 return 'ignored' } const obj1 = new ReturnsObject() const obj2 = new ReturnsPrimitive() expect(obj1).toEqual({ custom: 'object' }) expect(obj2.value).toBe(42) // primitive return is ignored }) }) describe('Prototype Methods', () => { it('should share methods via prototype', () => { function Player(name) { this.name = name } Player.prototype.attack = function () { return `${this.name} attacks!` } const p1 = new Player('Alice') const p2 = new Player('Bob') // Methods are shared expect(p1.attack).toBe(p2.attack) expect(p1.attack()).toBe('Alice attacks!') expect(p2.attack()).toBe('Bob attacks!') }) it('should add multiple methods to prototype', () => { function Character(name, health) { this.name = name this.health = health } Character.prototype.attack = function () { return `${this.name} attacks!` } Character.prototype.takeDamage = function (amount) { this.health -= amount return this.health } Character.prototype.isAlive = function () { return this.health > 0 } const hero = new Character('Hero', 100) expect(hero.attack()).toBe('Hero attacks!') expect(hero.takeDamage(30)).toBe(70) expect(hero.isAlive()).toBe(true) expect(hero.takeDamage(80)).toBe(-10) expect(hero.isAlive()).toBe(false) }) }) }) // =========================================== // Part 4: ES6 Classes // =========================================== describe('Part 4: ES6 Classes', () => { describe('Basic Class Syntax', () => { it('should create objects with class syntax', () => { class Player { constructor(name) { this.name = name this.health = 100 this.level = 1 } attack() { return `${this.name} attacks for ${10 + this.level * 2} damage!` } } const alice = new Player('Alice') expect(alice.name).toBe('Alice') expect(alice.health).toBe(100) expect(alice.attack()).toBe('Alice attacks for 12 damage!') expect(alice instanceof Player).toBe(true) }) it('should share methods via prototype (like constructors)', () => { class Player { constructor(name) { this.name = name } attack() { return `${this.name} attacks!` } } const p1 = new Player('Alice') const p2 = new Player('Bob') expect(p1.attack).toBe(p2.attack) // Shared via prototype }) }) describe('Class Fields', () => { it('should support class fields with default values', () => { class Character { level = 1 experience = 0 constructor(name) { this.name = name } } const hero = new Character('Hero') expect(hero.level).toBe(1) expect(hero.experience).toBe(0) expect(hero.name).toBe('Hero') }) }) describe('Static Methods and Properties', () => { it('should define static methods on class', () => { class MathUtils { static PI = 3.14159 static square(x) { return x * x } static cube(x) { return x * x * x } } expect(MathUtils.PI).toBe(3.14159) expect(MathUtils.square(5)).toBe(25) expect(MathUtils.cube(3)).toBe(27) // Not available on instances const utils = new MathUtils() expect(utils.PI).toBe(undefined) expect(utils.square).toBe(undefined) }) it('should use static factory methods', () => { class User { constructor(id, name) { this.id = id this.name = name } static createGuest() { return new User(0, 'Guest') } static fromData(data) { return new User(data.id, data.name) } } const guest = User.createGuest() const user = User.fromData({ id: 1, name: 'Alice' }) expect(guest.id).toBe(0) expect(guest.name).toBe('Guest') expect(user.id).toBe(1) expect(user.name).toBe('Alice') }) }) describe('Getters and Setters', () => { it('should define getters and setters', () => { class Circle { constructor(radius) { this._radius = radius } get radius() { return this._radius } set radius(value) { if (value < 0) throw new Error('Radius cannot be negative') this._radius = value } get diameter() { return this._radius * 2 } set diameter(value) { this._radius = value / 2 } get area() { return Math.PI * this._radius ** 2 } } const circle = new Circle(5) expect(circle.radius).toBe(5) expect(circle.diameter).toBe(10) expect(circle.area).toBeCloseTo(78.54, 1) circle.diameter = 20 expect(circle.radius).toBe(10) expect(() => { circle.radius = -5 }).toThrow('Radius cannot be negative') }) }) describe('Private Fields (#)', () => { it('should create truly private fields', () => { class BankAccount { #balance = 0 constructor(initialBalance) { this.#balance = initialBalance } deposit(amount) { if (amount > 0) this.#balance += amount return this.#balance } getBalance() { return this.#balance } } const account = new BankAccount(1000) expect(account.getBalance()).toBe(1000) expect(account.deposit(500)).toBe(1500) // Private field is not accessible expect(account.balance).toBe(undefined) expect(account['#balance']).toBe(undefined) }) it('should support private methods', () => { class Counter { #count = 0 #log(action) { return `[${action}] count: ${this.#count}` } increment() { this.#count++ return this.#log('increment') } getCount() { return this.#count } } const counter = new Counter() expect(counter.increment()).toBe('[increment] count: 1') expect(counter.getCount()).toBe(1) // Private method is not accessible expect(counter.log).toBe(undefined) }) }) describe('Classes are Syntactic Sugar', () => { it('should prove classes are functions', () => { class Player { constructor(name) { this.name = name } } expect(typeof Player).toBe('function') }) it('should have same prototype behavior as constructor functions', () => { class Player { constructor(name) { this.name = name } attack() { return `${this.name} attacks!` } } const player = new Player('Alice') expect(player.constructor).toBe(Player) expect(Object.getPrototypeOf(player)).toBe(Player.prototype) expect(player.__proto__).toBe(Player.prototype) }) }) }) // =========================================== // Part 5: Inheritance // =========================================== describe('Part 5: Inheritance', () => { describe('Class Inheritance with extends', () => { it('should inherit from parent class', () => { class Character { constructor(name, health) { this.name = name this.health = health } attack() { return `${this.name} attacks!` } takeDamage(amount) { this.health -= amount return this.health } } class Warrior extends Character { constructor(name) { super(name, 150) // Call parent constructor this.armor = 20 } shieldBash() { return `${this.name} bashes with shield for ${this.armor} damage!` } } const conan = new Warrior('Conan') expect(conan.name).toBe('Conan') expect(conan.health).toBe(150) expect(conan.armor).toBe(20) expect(conan.attack()).toBe('Conan attacks!') expect(conan.shieldBash()).toBe('Conan bashes with shield for 20 damage!') }) it('should work with instanceof through inheritance chain', () => { class Animal {} class Dog extends Animal {} const rex = new Dog() expect(rex instanceof Dog).toBe(true) expect(rex instanceof Animal).toBe(true) expect(rex instanceof Object).toBe(true) }) }) describe('Method Overriding', () => { it('should override parent methods', () => { class Animal { speak() { return 'Some sound' } } class Dog extends Animal { speak() { return 'Woof!' } } class Cat extends Animal { speak() { return 'Meow!' } } const animal = new Animal() const dog = new Dog() const cat = new Cat() expect(animal.speak()).toBe('Some sound') expect(dog.speak()).toBe('Woof!') expect(cat.speak()).toBe('Meow!') }) it('should call parent method with super', () => { class Character { constructor(name) { this.name = name } attack() { return `${this.name} attacks!` } } class Warrior extends Character { attack() { return `${super.attack()} With great strength!` } } const warrior = new Warrior('Conan') expect(warrior.attack()).toBe('Conan attacks! With great strength!') }) }) describe('The super Keyword', () => { it('should require super() before using this in derived class', () => { class Parent { constructor(name) { this.name = name } } class Child extends Parent { constructor(name, age) { super(name) // Must call before using this this.age = age } } const child = new Child('Alice', 10) expect(child.name).toBe('Alice') expect(child.age).toBe(10) }) }) describe('Factory Composition', () => { it('should compose behaviors from multiple sources', () => { const canWalk = (state) => ({ walk() { state.position += state.speed return `${state.name} walks to position ${state.position}` } }) const canSwim = (state) => ({ swim() { state.position += state.speed * 1.5 return `${state.name} swims to position ${state.position}` } }) const canFly = (state) => ({ fly() { state.position += state.speed * 3 return `${state.name} flies to position ${state.position}` } }) function createDuck(name) { const state = { name, position: 0, speed: 2 } return { name: state.name, ...canWalk(state), ...canSwim(state), ...canFly(state), getPosition: () => state.position } } function createPenguin(name) { const state = { name, position: 0, speed: 1 } return { name: state.name, ...canWalk(state), ...canSwim(state), // No fly! getPosition: () => state.position } } const duck = createDuck('Donald') const penguin = createPenguin('Tux') expect(duck.walk()).toBe('Donald walks to position 2') expect(duck.swim()).toBe('Donald swims to position 5') expect(duck.fly()).toBe('Donald flies to position 11') expect(penguin.walk()).toBe('Tux walks to position 1') expect(penguin.swim()).toBe('Tux swims to position 2.5') expect(penguin.fly).toBe(undefined) // Penguins can't fly }) it('should support canSpeak behavior composition', () => { const canSpeak = (state) => ({ speak(message) { return `${state.name} says: "${message}"` } }) const canWalk = (state) => ({ walk() { state.position += state.speed return `${state.name} walks to position ${state.position}` } }) function createDuck(name) { const state = { name, position: 0, speed: 2 } return { name: state.name, ...canWalk(state), ...canSpeak(state), getPosition: () => state.position } } function createFish(name) { const state = { name, position: 0, speed: 4 } return { name: state.name, // Fish can't speak! getPosition: () => state.position } } const duck = createDuck('Donald') const fish = createFish('Nemo') expect(duck.speak('Quack!')).toBe('Donald says: "Quack!"') expect(duck.walk()).toBe('Donald walks to position 2') expect(fish.speak).toBe(undefined) // Fish can't speak }) it('should allow flexible behavior combinations', () => { const withHealth = (state) => ({ takeDamage(amount) { state.health -= amount return state.health }, heal(amount) { state.health = Math.min(state.maxHealth, state.health + amount) return state.health }, getHealth: () => state.health, isAlive: () => state.health > 0 }) const withMana = (state) => ({ useMana(amount) { if (state.mana >= amount) { state.mana -= amount return true } return false }, getMana: () => state.mana }) function createWarrior(name) { const state = { name, health: 150, maxHealth: 150 } return { name: state.name, ...withHealth(state) // No mana for warriors } } function createMage(name) { const state = { name, health: 80, maxHealth: 80, mana: 100 } return { name: state.name, ...withHealth(state), ...withMana(state) } } const warrior = createWarrior('Conan') const mage = createMage('Gandalf') expect(warrior.getHealth()).toBe(150) expect(warrior.takeDamage(50)).toBe(100) expect(warrior.getMana).toBe(undefined) // Warriors don't have mana expect(mage.getHealth()).toBe(80) expect(mage.getMana()).toBe(100) expect(mage.useMana(30)).toBe(true) expect(mage.getMana()).toBe(70) }) }) }) // =========================================== // Part 6: Factory vs Class Comparison // =========================================== describe('Part 6: Factory vs Class Comparison', () => { describe('instanceof behavior', () => { it('should work with classes but not factories', () => { class ClassPlayer { constructor(name) { this.name = name } } function createPlayer(name) { return { name } } const classPlayer = new ClassPlayer('Alice') const factoryPlayer = createPlayer('Bob') expect(classPlayer instanceof ClassPlayer).toBe(true) expect(factoryPlayer instanceof Object).toBe(true) // Factory objects are just plain objects }) }) describe('Memory efficiency', () => { it('should show classes share prototype methods', () => { class ClassPlayer { attack() { return 'attack' } } const p1 = new ClassPlayer() const p2 = new ClassPlayer() expect(p1.attack).toBe(p2.attack) // Same function reference }) it('should show factories create new methods for each instance', () => { function createPlayer() { return { attack() { return 'attack' } } } const p1 = createPlayer() const p2 = createPlayer() expect(p1.attack).not.toBe(p2.attack) // Different function references }) }) describe('Privacy comparison', () => { it('should show both can achieve true privacy', () => { // Class with private fields class ClassWallet { #balance = 0 deposit(amount) { this.#balance += amount } getBalance() { return this.#balance } } // Factory with closures function createWallet() { let balance = 0 return { deposit(amount) { balance += amount }, getBalance() { return balance } } } const classWallet = new ClassWallet() const factoryWallet = createWallet() classWallet.deposit(100) factoryWallet.deposit(100) expect(classWallet.getBalance()).toBe(100) expect(factoryWallet.getBalance()).toBe(100) // Both are truly private expect(classWallet.balance).toBe(undefined) expect(factoryWallet.balance).toBe(undefined) }) }) }) // =========================================== // Common Mistakes // =========================================== describe('Common Mistakes', () => { describe('Mistake 1: Forgetting new with Constructor Functions', () => { it('should throw or behave unexpectedly when new is forgotten (strict mode)', () => { function Player(name) { this.name = name this.health = 100 } // In strict mode (which modern JS uses), forgetting 'new' throws an error // because 'this' is undefined, not the global object expect(() => Player('Alice')).toThrow() }) it('should work correctly with new keyword', () => { function Player(name) { this.name = name this.health = 100 } const bob = new Player('Bob') expect(bob.name).toBe('Bob') expect(bob.health).toBe(100) expect(bob instanceof Player).toBe(true) }) it('should throw error when calling class without new', () => { class Player { constructor(name) { this.name = name } } // Classes protect against this mistake expect(() => Player('Alice')).toThrow() }) }) describe('Mistake 3: Underscore Convention vs True Privacy', () => { it('should show underscore properties ARE accessible (not truly private)', () => { class BankAccount { constructor(balance) { this._balance = balance // Convention only, NOT private! } getBalance() { return this._balance } } const account = new BankAccount(1000) // Underscore properties are fully accessible! expect(account._balance).toBe(1000) // Can be modified directly account._balance = 999999 expect(account.getBalance()).toBe(999999) }) it('should show private fields (#) are truly private', () => { class SecureBankAccount { #balance // Truly private constructor(balance) { this.#balance = balance } getBalance() { return this.#balance } } const secure = new SecureBankAccount(1000) // Private field is not accessible expect(secure.balance).toBe(undefined) // Can only access via methods expect(secure.getBalance()).toBe(1000) }) }) describe('Mistake 4: Using this Incorrectly in Factory Functions', () => { it('should show this can break when method is extracted', () => { function createCounter() { return { count: 0, increment() { this.count++ // 'this' depends on how method is called }
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
true
leonardomso/33-js-concepts
https://github.com/leonardomso/33-js-concepts/blob/5cda73bac940173b77d19a23a208fea234ca6c33/tests/object-oriented/object-creation-prototypes/object-creation-prototypes.test.js
tests/object-oriented/object-creation-prototypes/object-creation-prototypes.test.js
import { describe, it, expect } from 'vitest' describe('Object Creation & Prototypes', () => { describe('Opening Hook - Inherited Methods', () => { it('should have inherited methods from Object.prototype', () => { // You create a simple object const player = { name: 'Alice', health: 100 } // But it has methods you never defined! expect(typeof player.toString).toBe('function') expect(player.toString()).toBe('[object Object]') expect(player.hasOwnProperty('name')).toBe(true) // Where do these come from? expect(Object.getPrototypeOf(player)).toBe(Object.prototype) }) }) describe('Prototype Chain', () => { it('should look up properties through the prototype chain', () => { const grandparent = { familyName: 'Smith' } const parent = Object.create(grandparent) parent.job = 'Engineer' const child = Object.create(parent) child.name = 'Alice' // Property lookup walks the chain expect(child.name).toBe('Alice') // found on child expect(child.job).toBe('Engineer') // found on parent expect(child.familyName).toBe('Smith') // found on grandparent }) it('should inherit methods from prototype (wizard/apprentice example)', () => { // Create a simple object const wizard = { name: 'Gandalf', castSpell() { return `${this.name} casts a spell!` } } // Create another object that inherits from wizard const apprentice = Object.create(wizard) apprentice.name = 'Harry' // apprentice has its own 'name' property expect(apprentice.name).toBe('Harry') // But castSpell comes from the prototype (wizard) expect(apprentice.castSpell()).toBe('Harry casts a spell!') // The prototype chain: // apprentice → wizard → Object.prototype → null expect(Object.getPrototypeOf(apprentice)).toBe(wizard) expect(Object.getPrototypeOf(wizard)).toBe(Object.prototype) expect(Object.getPrototypeOf(Object.prototype)).toBeNull() }) it('should return undefined when property is not found in chain', () => { const obj = { name: 'test' } expect(obj.nonexistent).toBeUndefined() }) it('should end the chain at null', () => { const obj = {} expect(Object.getPrototypeOf(Object.prototype)).toBeNull() }) it('should shadow inherited properties when set on object', () => { const prototype = { greeting: 'Hello', count: 0 } const obj = Object.create(prototype) // Before shadowing expect(obj.greeting).toBe('Hello') // Shadow the property obj.greeting = 'Hi' // obj has its own property now expect(obj.greeting).toBe('Hi') // Prototype is unchanged expect(prototype.greeting).toBe('Hello') expect(obj.hasOwnProperty('greeting')).toBe(true) }) }) describe('[[Prototype]], __proto__, and .prototype', () => { it('should have Object.prototype as prototype for plain objects', () => { const obj = {} expect(Object.getPrototypeOf(obj)).toBe(Object.prototype) }) it('should have .prototype property only on functions', () => { function Player(name) { this.name = name } const alice = new Player('Alice') // Functions have .prototype expect(Player.prototype).toBeDefined() expect(typeof Player.prototype).toBe('object') // Instances don't have .prototype expect(alice.prototype).toBeUndefined() // Instance's [[Prototype]] is the constructor's .prototype expect(Object.getPrototypeOf(alice)).toBe(Player.prototype) }) }) describe('Object Literals', () => { it('should have Object.prototype as prototype', () => { // Object literal — prototype is automatically Object.prototype const player = { name: 'Alice', health: 100, attack() { return `${this.name} attacks!` } } expect(Object.getPrototypeOf(player)).toBe(Object.prototype) expect(player.attack()).toBe('Alice attacks!') }) }) describe('Object.create()', () => { it('should create object with specified prototype', () => { const animalProto = { speak() { return `${this.name} makes a sound.` } } const dog = Object.create(animalProto) dog.name = 'Rex' expect(Object.getPrototypeOf(dog)).toBe(animalProto) expect(dog.speak()).toBe('Rex makes a sound.') }) it('should create object with null prototype', () => { const dict = Object.create(null) // No inherited properties expect(dict.toString).toBeUndefined() expect(dict.hasOwnProperty).toBeUndefined() expect(Object.getPrototypeOf(dict)).toBeNull() // Can use any key without collision dict['hasOwnProperty'] = 'safe!' expect(dict['hasOwnProperty']).toBe('safe!') }) it('should create object with property descriptors', () => { const person = Object.create(Object.prototype, { name: { value: 'Alice', writable: true, enumerable: true, configurable: true }, age: { value: 30, writable: false, enumerable: true, configurable: false } }) expect(person.name).toBe('Alice') expect(person.age).toBe(30) // Can modify writable property person.name = 'Bob' expect(person.name).toBe('Bob') // Cannot modify non-writable property (throws in strict mode) expect(() => { person.age = 25 }).toThrow(TypeError) expect(person.age).toBe(30) // unchanged }) }) describe('new operator', () => { it('should create object with correct prototype', () => { function Player(name) { this.name = name } Player.prototype.greet = function () { return `Hello, ${this.name}!` } const alice = new Player('Alice') expect(Object.getPrototypeOf(alice)).toBe(Player.prototype) expect(alice.greet()).toBe('Hello, Alice!') }) it('should bind this to the new object', () => { function Counter() { this.count = 0 this.increment = function () { this.count++ } } const counter = new Counter() expect(counter.count).toBe(0) counter.increment() expect(counter.count).toBe(1) }) it('should return the object unless constructor returns an object', () => { function ReturnsNothing(name) { this.name = name // Implicitly returns the new object } function ReturnsPrimitive(name) { this.name = name return 42 // Primitive is ignored } function ReturnsObject(name) { this.name = name return { different: true } // Object is returned instead } const obj1 = new ReturnsNothing('test') expect(obj1.name).toBe('test') const obj2 = new ReturnsPrimitive('test') expect(obj2.name).toBe('test') // Primitive return ignored const obj3 = new ReturnsObject('test') expect(obj3.different).toBe(true) expect(obj3.name).toBeUndefined() // Original object not returned }) it('can be simulated with Object.create and apply', () => { function myNew(Constructor, ...args) { const obj = Object.create(Constructor.prototype) const result = Constructor.apply(obj, args) return result !== null && typeof result === 'object' ? result : obj } function Player(name, health) { this.name = name this.health = health } Player.prototype.attack = function () { return `${this.name} attacks!` } const player1 = new Player('Alice', 100) const player2 = myNew(Player, 'Bob', 100) expect(player1.name).toBe('Alice') expect(player2.name).toBe('Bob') expect(player1.attack()).toBe('Alice attacks!') expect(player2.attack()).toBe('Bob attacks!') expect(player1 instanceof Player).toBe(true) expect(player2 instanceof Player).toBe(true) }) }) describe('Object.assign()', () => { it('should copy enumerable own properties', () => { const target = { a: 1 } const source = { b: 2, c: 3 } const result = Object.assign(target, source) expect(result).toEqual({ a: 1, b: 2, c: 3 }) expect(result).toBe(target) // Returns the target }) it('should merge multiple objects (later sources overwrite)', () => { const defaults = { theme: 'light', fontSize: 14 } const userPrefs = { theme: 'dark' } const session = { fontSize: 18 } const settings = Object.assign({}, defaults, userPrefs, session) expect(settings.theme).toBe('dark') expect(settings.fontSize).toBe(18) }) it('should perform shallow copy only', () => { const original = { name: 'Alice', scores: [90, 85] } const clone = Object.assign({}, original) // Primitive is copied by value clone.name = 'Bob' expect(original.name).toBe('Alice') // Array is copied by reference clone.scores.push(100) expect(original.scores).toEqual([90, 85, 100]) // Modified! }) it('should not copy inherited or non-enumerable properties', () => { const proto = { inherited: 'from prototype' } const source = Object.create(proto) source.own = 'my own property' Object.defineProperty(source, 'hidden', { value: 'non-enumerable', enumerable: false }) const target = {} Object.assign(target, source) expect(target.own).toBe('my own property') expect(target.inherited).toBeUndefined() // Not copied expect(target.hidden).toBeUndefined() // Not copied }) }) describe('Prototype inspection', () => { it('Object.getPrototypeOf should return the prototype', () => { const proto = { test: true } const obj = Object.create(proto) expect(Object.getPrototypeOf(obj)).toBe(proto) }) it('Object.setPrototypeOf should change the prototype', () => { const swimmer = { swim: () => 'swimming' } const flyer = { fly: () => 'flying' } const duck = { name: 'Donald' } Object.setPrototypeOf(duck, swimmer) expect(duck.swim()).toBe('swimming') Object.setPrototypeOf(duck, flyer) expect(duck.fly()).toBe('flying') expect(duck.swim).toBeUndefined() }) it('instanceof should check the prototype chain', () => { function Animal(name) { this.name = name } function Dog(name) { Animal.call(this, name) } Dog.prototype = Object.create(Animal.prototype) Dog.prototype.constructor = Dog const rex = new Dog('Rex') expect(rex instanceof Dog).toBe(true) expect(rex instanceof Animal).toBe(true) expect(rex instanceof Object).toBe(true) expect(rex instanceof Array).toBe(false) }) it('isPrototypeOf should check if object is in prototype chain', () => { const animal = { eats: true } const dog = Object.create(animal) expect(animal.isPrototypeOf(dog)).toBe(true) expect(Object.prototype.isPrototypeOf(dog)).toBe(true) expect(Array.prototype.isPrototypeOf(dog)).toBe(false) }) }) describe('Common prototype methods', () => { it('hasOwnProperty should check only own properties', () => { const proto = { inherited: true } const obj = Object.create(proto) obj.own = true expect(obj.hasOwnProperty('own')).toBe(true) expect(obj.hasOwnProperty('inherited')).toBe(false) // 'in' checks the whole chain expect('own' in obj).toBe(true) expect('inherited' in obj).toBe(true) }) it('Object.keys should return only own enumerable properties', () => { const proto = { inherited: 'value' } const obj = Object.create(proto) obj.own1 = 'a' obj.own2 = 'b' expect(Object.keys(obj)).toEqual(['own1', 'own2']) expect(Object.keys(obj)).not.toContain('inherited') }) it('Object.getOwnPropertyNames should return all own properties', () => { const obj = { visible: true } Object.defineProperty(obj, 'hidden', { value: 'secret', enumerable: false }) expect(Object.keys(obj)).toEqual(['visible']) expect(Object.getOwnPropertyNames(obj)).toEqual(['visible', 'hidden']) }) }) describe('Common mistakes', () => { it('should not share reference types on prototype', () => { // Wrong way - array on prototype is shared function BadPlayer(name) { this.name = name } BadPlayer.prototype.inventory = [] const alice = new BadPlayer('Alice') const bob = new BadPlayer('Bob') alice.inventory.push('sword') expect(bob.inventory).toContain('sword') // Bob has Alice's sword! // Correct way - array in constructor function GoodPlayer(name) { this.name = name this.inventory = [] } const charlie = new GoodPlayer('Charlie') const dave = new GoodPlayer('Dave') charlie.inventory.push('shield') expect(dave.inventory).not.toContain('shield') // Dave's inventory is separate }) }) })
javascript
MIT
5cda73bac940173b77d19a23a208fea234ca6c33
2026-01-04T14:56:49.684692Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb/base.js
packages/eslint-config-airbnb/base.js
module.exports = { extends: ['eslint-config-airbnb-base'].map(require.resolve), rules: {}, };
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb/index.js
packages/eslint-config-airbnb/index.js
module.exports = { extends: [ 'eslint-config-airbnb-base', './rules/react', './rules/react-a11y', ].map(require.resolve), rules: {} };
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb/legacy.js
packages/eslint-config-airbnb/legacy.js
module.exports = { extends: ['eslint-config-airbnb-base/legacy'].map(require.resolve), rules: {}, };
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb/whitespace.js
packages/eslint-config-airbnb/whitespace.js
/* eslint global-require: 0 */ const { isArray } = Array; const { entries } = Object; const { CLIEngine } = require('eslint'); if (CLIEngine) { /* eslint no-inner-declarations: 0 */ const whitespaceRules = require('./whitespaceRules'); const baseConfig = require('.'); const severities = ['off', 'warn', 'error']; function getSeverity(ruleConfig) { if (isArray(ruleConfig)) { return getSeverity(ruleConfig[0]); } if (typeof ruleConfig === 'number') { return severities[ruleConfig]; } return ruleConfig; } function onlyErrorOnRules(rulesToError, config) { const errorsOnly = { ...config }; const cli = new CLIEngine({ baseConfig: config, useEslintrc: false }); const baseRules = cli.getConfigForFile(require.resolve('./')).rules; entries(baseRules).forEach((rule) => { const ruleName = rule[0]; const ruleConfig = rule[1]; const severity = getSeverity(ruleConfig); if (rulesToError.indexOf(ruleName) === -1 && severity === 'error') { if (isArray(ruleConfig)) { errorsOnly.rules[ruleName] = ['warn'].concat(ruleConfig.slice(1)); } else if (typeof ruleConfig === 'number') { errorsOnly.rules[ruleName] = 1; } else { errorsOnly.rules[ruleName] = 'warn'; } } }); return errorsOnly; } module.exports = onlyErrorOnRules(whitespaceRules, baseConfig); } else { const path = require('path'); const { execSync } = require('child_process'); // NOTE: ESLint adds runtime statistics to the output (so it's no longer JSON) if TIMING is set module.exports = JSON.parse(String(execSync(path.join(__dirname, 'whitespace-async.js'), { env: { ...process.env, TIMING: undefined, } }))); }
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb/whitespaceRules.js
packages/eslint-config-airbnb/whitespaceRules.js
module.exports = [ 'array-bracket-newline', 'array-bracket-spacing', 'array-element-newline', 'arrow-spacing', 'block-spacing', 'comma-spacing', 'computed-property-spacing', 'dot-location', 'eol-last', 'func-call-spacing', 'function-paren-newline', 'generator-star-spacing', 'implicit-arrow-linebreak', 'indent', 'key-spacing', 'keyword-spacing', 'line-comment-position', 'linebreak-style', 'multiline-ternary', 'newline-per-chained-call', 'no-irregular-whitespace', 'no-mixed-spaces-and-tabs', 'no-multi-spaces', 'no-regex-spaces', 'no-spaced-func', 'no-trailing-spaces', 'no-whitespace-before-property', 'nonblock-statement-body-position', 'object-curly-newline', 'object-curly-spacing', 'object-property-newline', 'one-var-declaration-per-line', 'operator-linebreak', 'padded-blocks', 'padding-line-between-statements', 'rest-spread-spacing', 'semi-spacing', 'semi-style', 'space-before-blocks', 'space-before-function-paren', 'space-in-parens', 'space-infix-ops', 'space-unary-ops', 'spaced-comment', 'switch-colon-spacing', 'template-tag-spacing', 'import/newline-after-import', // eslint-plugin-react rules 'react/jsx-child-element-spacing', 'react/jsx-closing-bracket-location', 'react/jsx-closing-tag-location', 'react/jsx-curly-spacing', 'react/jsx-equals-spacing', 'react/jsx-first-prop-newline', 'react/jsx-indent', 'react/jsx-indent-props', 'react/jsx-max-props-per-line', 'react/jsx-one-expression-per-line', 'react/jsx-space-before-closing', 'react/jsx-tag-spacing', 'react/jsx-wrap-multilines', ];
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb/hooks.js
packages/eslint-config-airbnb/hooks.js
module.exports = { extends: [ './rules/react-hooks.js', ].map(require.resolve), rules: {} };
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb/whitespace-async.js
packages/eslint-config-airbnb/whitespace-async.js
#!/usr/bin/env node const { isArray } = Array; const { entries } = Object; const { ESLint } = require('eslint'); const baseConfig = require('.'); const whitespaceRules = require('./whitespaceRules'); const severities = ['off', 'warn', 'error']; function getSeverity(ruleConfig) { if (isArray(ruleConfig)) { return getSeverity(ruleConfig[0]); } if (typeof ruleConfig === 'number') { return severities[ruleConfig]; } return ruleConfig; } async function onlyErrorOnRules(rulesToError, config) { const errorsOnly = { ...config }; const cli = new ESLint({ useEslintrc: false, baseConfig: config }); const baseRules = (await cli.calculateConfigForFile(require.resolve('./'))).rules; entries(baseRules).forEach((rule) => { const ruleName = rule[0]; const ruleConfig = rule[1]; const severity = getSeverity(ruleConfig); if (rulesToError.indexOf(ruleName) === -1 && severity === 'error') { if (isArray(ruleConfig)) { errorsOnly.rules[ruleName] = ['warn'].concat(ruleConfig.slice(1)); } else if (typeof ruleConfig === 'number') { errorsOnly.rules[ruleName] = 1; } else { errorsOnly.rules[ruleName] = 'warn'; } } }); return errorsOnly; } onlyErrorOnRules(whitespaceRules, baseConfig).then((config) => console.log(JSON.stringify(config)));
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb/rules/react-hooks.js
packages/eslint-config-airbnb/rules/react-hooks.js
module.exports = { plugins: [ 'react-hooks', ], parserOptions: { ecmaFeatures: { jsx: true, }, }, rules: { // Enforce Rules of Hooks // https://github.com/facebook/react/blob/c11015ff4f610ac2924d1fc6d569a17657a404fd/packages/eslint-plugin-react-hooks/src/RulesOfHooks.js 'react-hooks/rules-of-hooks': 'error', // Verify the list of the dependencies for Hooks like useEffect and similar // https://github.com/facebook/react/blob/1204c789776cb01fbaf3e9f032e7e2ba85a44137/packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js 'react-hooks/exhaustive-deps': 'error', }, };
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb/rules/react.js
packages/eslint-config-airbnb/rules/react.js
const baseStyleRules = require('eslint-config-airbnb-base/rules/style').rules; const dangleRules = baseStyleRules['no-underscore-dangle']; module.exports = { plugins: [ 'react', ], parserOptions: { ecmaFeatures: { jsx: true, }, }, // View link below for react rules documentation // https://github.com/jsx-eslint/eslint-plugin-react#list-of-supported-rules rules: { 'no-underscore-dangle': [dangleRules[0], { ...dangleRules[1], allow: dangleRules[1].allow.concat(['__REDUX_DEVTOOLS_EXTENSION_COMPOSE__']), }], // Specify whether double or single quotes should be used in JSX attributes // https://eslint.org/docs/rules/jsx-quotes 'jsx-quotes': ['error', 'prefer-double'], 'class-methods-use-this': ['error', { exceptMethods: [ 'render', 'getInitialState', 'getDefaultProps', 'getChildContext', 'componentWillMount', 'UNSAFE_componentWillMount', 'componentDidMount', 'componentWillReceiveProps', 'UNSAFE_componentWillReceiveProps', 'shouldComponentUpdate', 'componentWillUpdate', 'UNSAFE_componentWillUpdate', 'componentDidUpdate', 'componentWillUnmount', 'componentDidCatch', 'getSnapshotBeforeUpdate' ], }], // This rule enforces onChange or readonly attribute for checked property of input elements. // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/checked-requires-onchange-or-readonly.md 'react/checked-requires-onchange-or-readonly': ['off', { ignoreMissingProperties: false, ignoreExclusiveCheckedAttribute: false }], // Prevent missing displayName in a React component definition // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/display-name.md 'react/display-name': ['off', { ignoreTranspilerName: false }], // Forbid certain propTypes (any, array, object) // https://github.com/jsx-eslint/eslint-plugin-react/blob/843d71a432baf0f01f598d7cf1eea75ad6896e4b/docs/rules/forbid-prop-types.md 'react/forbid-prop-types': ['error', { forbid: ['any', 'array', 'object'], checkContextTypes: true, checkChildContextTypes: true, }], // Forbid certain props on DOM Nodes // https://github.com/jsx-eslint/eslint-plugin-react/blob/843d71a432baf0f01f598d7cf1eea75ad6896e4b/docs/rules/forbid-dom-props.md 'react/forbid-dom-props': ['off', { forbid: [] }], // Enforce boolean attributes notation in JSX // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-boolean-value.md 'react/jsx-boolean-value': ['error', 'never', { always: [] }], // Validate closing bracket location in JSX // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-closing-bracket-location.md 'react/jsx-closing-bracket-location': ['error', 'line-aligned'], // Validate closing tag location in JSX // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-closing-tag-location.md 'react/jsx-closing-tag-location': 'error', // Enforce or disallow spaces inside of curly braces in JSX attributes // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-curly-spacing.md 'react/jsx-curly-spacing': ['error', 'never', { allowMultiline: true }], // Enforce event handler naming conventions in JSX // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-handler-names.md 'react/jsx-handler-names': ['off', { eventHandlerPrefix: 'handle', eventHandlerPropPrefix: 'on', }], // Validate props indentation in JSX // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-indent-props.md 'react/jsx-indent-props': ['error', 2], // Validate JSX has key prop when in array or iterator // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-key.md // Turned off because it has too many false positives 'react/jsx-key': 'off', // Limit maximum of props on a single line in JSX // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-max-props-per-line.md 'react/jsx-max-props-per-line': ['error', { maximum: 1, when: 'multiline' }], // Prevent usage of .bind() in JSX props // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md 'react/jsx-no-bind': ['error', { ignoreRefs: true, allowArrowFunctions: true, allowFunctions: false, allowBind: false, ignoreDOMComponents: true, }], // Prevent duplicate props in JSX // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-duplicate-props.md 'react/jsx-no-duplicate-props': ['error', { ignoreCase: true }], // Prevent usage of unwrapped JSX strings // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-literals.md 'react/jsx-no-literals': ['off', { noStrings: true }], // Disallow undeclared variables in JSX // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-undef.md 'react/jsx-no-undef': 'error', // Enforce PascalCase for user-defined JSX components // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-pascal-case.md 'react/jsx-pascal-case': ['error', { allowAllCaps: true, ignore: [], }], // Enforce propTypes declarations alphabetical sorting // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/sort-prop-types.md 'react/sort-prop-types': ['off', { ignoreCase: true, callbacksLast: false, requiredFirst: false, sortShapeProp: true, }], // Deprecated in favor of react/jsx-sort-props 'react/jsx-sort-prop-types': 'off', // Enforce props alphabetical sorting // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-sort-props.md 'react/jsx-sort-props': ['off', { ignoreCase: true, callbacksLast: false, shorthandFirst: false, shorthandLast: false, noSortAlphabetically: false, reservedFirst: true, }], // Enforce defaultProps declarations alphabetical sorting // https://github.com/jsx-eslint/eslint-plugin-react/blob/843d71a432baf0f01f598d7cf1eea75ad6896e4b/docs/rules/jsx-sort-default-props.md 'react/jsx-sort-default-props': ['off', { ignoreCase: true, }], // Prevent React to be incorrectly marked as unused // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-uses-react.md 'react/jsx-uses-react': ['error'], // Prevent variables used in JSX to be incorrectly marked as unused // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-uses-vars.md 'react/jsx-uses-vars': 'error', // Prevent usage of dangerous JSX properties // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-danger.md 'react/no-danger': 'warn', // Prevent usage of deprecated methods // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-deprecated.md 'react/no-deprecated': ['error'], // Prevent usage of setState in componentDidMount // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-did-mount-set-state.md // this is necessary for server-rendering 'react/no-did-mount-set-state': 'off', // Prevent usage of setState in componentDidUpdate // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-did-update-set-state.md 'react/no-did-update-set-state': 'error', // Prevent usage of setState in componentWillUpdate // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-will-update-set-state.md 'react/no-will-update-set-state': 'error', // Prevent direct mutation of this.state // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-direct-mutation-state.md 'react/no-direct-mutation-state': 'off', // Prevent usage of isMounted // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-is-mounted.md 'react/no-is-mounted': 'error', // Prevent multiple component definition per file // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-multi-comp.md 'react/no-multi-comp': 'off', // Prevent usage of setState // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-set-state.md 'react/no-set-state': 'off', // Prevent using string references // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-string-refs.md 'react/no-string-refs': 'error', // Prevent usage of unknown DOM property // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-unknown-property.md 'react/no-unknown-property': 'error', // Require ES6 class declarations over React.createClass // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/prefer-es6-class.md 'react/prefer-es6-class': ['error', 'always'], // Require stateless functions when not using lifecycle methods, setState or ref // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/prefer-stateless-function.md 'react/prefer-stateless-function': ['error', { ignorePureComponents: true }], // Prevent missing props validation in a React component definition // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/prop-types.md 'react/prop-types': ['error', { ignore: [], customValidators: [], skipUndeclared: false }], // Prevent missing React when using JSX // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/react-in-jsx-scope.md 'react/react-in-jsx-scope': 'error', // Require render() methods to return something // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/require-render-return.md 'react/require-render-return': 'error', // Prevent extra closing tags for components without children // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/self-closing-comp.md 'react/self-closing-comp': 'error', // Enforce component methods order // https://github.com/jsx-eslint/eslint-plugin-react/blob/843d71a432baf0f01f598d7cf1eea75ad6896e4b/docs/rules/sort-comp.md 'react/sort-comp': ['error', { order: [ 'static-variables', 'static-methods', 'instance-variables', 'lifecycle', '/^handle.+$/', '/^on.+$/', 'getters', 'setters', '/^(get|set)(?!(InitialState$|DefaultProps$|ChildContext$)).+$/', 'instance-methods', 'everything-else', 'rendering', ], groups: { lifecycle: [ 'displayName', 'propTypes', 'contextTypes', 'childContextTypes', 'mixins', 'statics', 'defaultProps', 'constructor', 'getDefaultProps', 'getInitialState', 'state', 'getChildContext', 'getDerivedStateFromProps', 'componentWillMount', 'UNSAFE_componentWillMount', 'componentDidMount', 'componentWillReceiveProps', 'UNSAFE_componentWillReceiveProps', 'shouldComponentUpdate', 'componentWillUpdate', 'UNSAFE_componentWillUpdate', 'getSnapshotBeforeUpdate', 'componentDidUpdate', 'componentDidCatch', 'componentWillUnmount' ], rendering: [ '/^render.+$/', 'render' ], }, }], // Prevent missing parentheses around multilines JSX // https://github.com/jsx-eslint/eslint-plugin-react/blob/843d71a432baf0f01f598d7cf1eea75ad6896e4b/docs/rules/jsx-wrap-multilines.md 'react/jsx-wrap-multilines': ['error', { declaration: 'parens-new-line', assignment: 'parens-new-line', return: 'parens-new-line', arrow: 'parens-new-line', condition: 'parens-new-line', logical: 'parens-new-line', prop: 'parens-new-line', }], // Require that the first prop in a JSX element be on a new line when the element is multiline // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-first-prop-new-line.md 'react/jsx-first-prop-new-line': ['error', 'multiline-multiprop'], // Enforce spacing around jsx equals signs // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-equals-spacing.md 'react/jsx-equals-spacing': ['error', 'never'], // Enforce JSX indentation // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-indent.md 'react/jsx-indent': ['error', 2], // Disallow target="_blank" on links // https://github.com/jsx-eslint/eslint-plugin-react/blob/ac102885765be5ff37847a871f239c6703e1c7cc/docs/rules/jsx-no-target-blank.md 'react/jsx-no-target-blank': ['error', { enforceDynamicLinks: 'always' }], // only .jsx files may have JSX // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-filename-extension.md 'react/jsx-filename-extension': ['error', { extensions: ['.jsx'] }], // prevent accidental JS comments from being injected into JSX as text // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-comment-textnodes.md 'react/jsx-no-comment-textnodes': 'error', // disallow using React.render/ReactDOM.render's return value // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-render-return-value.md 'react/no-render-return-value': 'error', // require a shouldComponentUpdate method, or PureRenderMixin // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/require-optimization.md 'react/require-optimization': ['off', { allowDecorators: [] }], // warn against using findDOMNode() // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-find-dom-node.md 'react/no-find-dom-node': 'error', // Forbid certain props on Components // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/forbid-component-props.md 'react/forbid-component-props': ['off', { forbid: [] }], // Forbid certain elements // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/forbid-elements.md 'react/forbid-elements': ['off', { forbid: [], }], // Prevent problem with children and props.dangerouslySetInnerHTML // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-danger-with-children.md 'react/no-danger-with-children': 'error', // Prevent unused propType definitions // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-unused-prop-types.md 'react/no-unused-prop-types': ['error', { customValidators: [ ], skipShapeProps: true, }], // Require style prop value be an object or var // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/style-prop-object.md 'react/style-prop-object': 'error', // Prevent invalid characters from appearing in markup // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-unescaped-entities.md 'react/no-unescaped-entities': 'error', // Prevent passing of children as props // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-children-prop.md 'react/no-children-prop': 'error', // Validate whitespace in and around the JSX opening and closing brackets // https://github.com/jsx-eslint/eslint-plugin-react/blob/843d71a432baf0f01f598d7cf1eea75ad6896e4b/docs/rules/jsx-tag-spacing.md 'react/jsx-tag-spacing': ['error', { closingSlash: 'never', beforeSelfClosing: 'always', afterOpening: 'never', beforeClosing: 'never', }], // Enforce spaces before the closing bracket of self-closing JSX elements // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-space-before-closing.md // Deprecated in favor of jsx-tag-spacing 'react/jsx-space-before-closing': ['off', 'always'], // Prevent usage of Array index in keys // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-array-index-key.md 'react/no-array-index-key': 'error', // Enforce a defaultProps definition for every prop that is not a required prop // https://github.com/jsx-eslint/eslint-plugin-react/blob/843d71a432baf0f01f598d7cf1eea75ad6896e4b/docs/rules/require-default-props.md 'react/require-default-props': ['error', { forbidDefaultForRequired: true, }], // Forbids using non-exported propTypes // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/forbid-foreign-prop-types.md // this is intentionally set to "warn". it would be "error", // but it's only critical if you're stripping propTypes in production. 'react/forbid-foreign-prop-types': ['warn', { allowInPropTypes: true }], // Prevent void DOM elements from receiving children // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/void-dom-elements-no-children.md 'react/void-dom-elements-no-children': 'error', // Enforce all defaultProps have a corresponding non-required PropType // https://github.com/jsx-eslint/eslint-plugin-react/blob/9e13ae2c51e44872b45cc15bf1ac3a72105bdd0e/docs/rules/default-props-match-prop-types.md 'react/default-props-match-prop-types': ['error', { allowRequiredDefaults: false }], // Prevent usage of shouldComponentUpdate when extending React.PureComponent // https://github.com/jsx-eslint/eslint-plugin-react/blob/9e13ae2c51e44872b45cc15bf1ac3a72105bdd0e/docs/rules/no-redundant-should-component-update.md 'react/no-redundant-should-component-update': 'error', // Prevent unused state values // https://github.com/jsx-eslint/eslint-plugin-react/pull/1103/ 'react/no-unused-state': 'error', // Enforces consistent naming for boolean props // https://github.com/jsx-eslint/eslint-plugin-react/blob/843d71a432baf0f01f598d7cf1eea75ad6896e4b/docs/rules/boolean-prop-naming.md 'react/boolean-prop-naming': ['off', { propTypeNames: ['bool', 'mutuallyExclusiveTrueProps'], rule: '^(is|has)[A-Z]([A-Za-z0-9]?)+', message: '', }], // Prevents common casing typos // https://github.com/jsx-eslint/eslint-plugin-react/blob/73abadb697034b5ccb514d79fb4689836fe61f91/docs/rules/no-typos.md 'react/no-typos': 'error', // Enforce curly braces or disallow unnecessary curly braces in JSX props and/or children // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-curly-brace-presence.md 'react/jsx-curly-brace-presence': ['error', { props: 'never', children: 'never' }], // One JSX Element Per Line // https://github.com/jsx-eslint/eslint-plugin-react/blob/843d71a432baf0f01f598d7cf1eea75ad6896e4b/docs/rules/jsx-one-expression-per-line.md 'react/jsx-one-expression-per-line': ['error', { allow: 'single-child' }], // Enforce consistent usage of destructuring assignment of props, state, and context // https://github.com/jsx-eslint/eslint-plugin-react/blob/843d71a432baf0f01f598d7cf1eea75ad6896e4b/docs/rules/destructuring-assignment.md 'react/destructuring-assignment': ['error', 'always'], // Prevent using this.state within a this.setState // https://github.com/jsx-eslint/eslint-plugin-react/blob/843d71a432baf0f01f598d7cf1eea75ad6896e4b/docs/rules/no-access-state-in-setstate.md 'react/no-access-state-in-setstate': 'error', // Prevent usage of button elements without an explicit type attribute // https://github.com/jsx-eslint/eslint-plugin-react/blob/843d71a432baf0f01f598d7cf1eea75ad6896e4b/docs/rules/button-has-type.md 'react/button-has-type': ['error', { button: true, submit: true, reset: false, }], // Ensures inline tags are not rendered without spaces between them 'react/jsx-child-element-spacing': 'off', // Prevent this from being used in stateless functional components // https://github.com/jsx-eslint/eslint-plugin-react/blob/843d71a432baf0f01f598d7cf1eea75ad6896e4b/docs/rules/no-this-in-sfc.md 'react/no-this-in-sfc': 'error', // Validate JSX maximum depth // https://github.com/jsx-eslint/eslint-plugin-react/blob/abe8381c0d6748047224c430ce47f02e40160ed0/docs/rules/jsx-max-depth.md 'react/jsx-max-depth': 'off', // Disallow multiple spaces between inline JSX props // https://github.com/jsx-eslint/eslint-plugin-react/blob/ac102885765be5ff37847a871f239c6703e1c7cc/docs/rules/jsx-props-no-multi-spaces.md 'react/jsx-props-no-multi-spaces': 'error', // Prevent usage of UNSAFE_ methods // https://github.com/jsx-eslint/eslint-plugin-react/blob/157cc932be2cfaa56b3f5b45df6f6d4322a2f660/docs/rules/no-unsafe.md 'react/no-unsafe': 'off', // Enforce shorthand or standard form for React fragments // https://github.com/jsx-eslint/eslint-plugin-react/blob/bc976b837abeab1dffd90ac6168b746a83fc83cc/docs/rules/jsx-fragments.md 'react/jsx-fragments': ['error', 'syntax'], // Enforce linebreaks in curly braces in JSX attributes and expressions. // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-curly-newline.md 'react/jsx-curly-newline': ['error', { multiline: 'consistent', singleline: 'consistent', }], // Enforce state initialization style // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/state-in-constructor.md // TODO: set to "never" once babel-preset-airbnb supports public class fields 'react/state-in-constructor': ['error', 'always'], // Enforces where React component static properties should be positioned // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/static-property-placement.md // TODO: set to "static public field" once babel-preset-airbnb supports public class fields 'react/static-property-placement': ['error', 'property assignment'], // Disallow JSX props spreading // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-props-no-spreading.md 'react/jsx-props-no-spreading': ['error', { html: 'enforce', custom: 'enforce', explicitSpread: 'ignore', exceptions: [], }], // Enforce that props are read-only // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/prefer-read-only-props.md 'react/prefer-read-only-props': 'off', // Prevent usage of `javascript:` URLs // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-script-url.md 'react/jsx-no-script-url': ['error', [ { name: 'Link', props: ['to'], }, ]], // Disallow unnecessary fragments // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-useless-fragment.md 'react/jsx-no-useless-fragment': 'error', // Prevent adjacent inline elements not separated by whitespace // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-adjacent-inline-elements.md // TODO: enable? semver-major 'react/no-adjacent-inline-elements': 'off', // Enforce a specific function type for function components // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/function-component-definition.md 'react/function-component-definition': ['error', { namedComponents: ['function-declaration', 'function-expression'], unnamedComponents: 'function-expression', }], // Enforce a new line after jsx elements and expressions // https://github.com/jsx-eslint/eslint-plugin-react/blob/e2eaadae316f9506d163812a09424eb42698470a/docs/rules/jsx-newline.md 'react/jsx-newline': 'off', // Prevent react contexts from taking non-stable values // https://github.com/jsx-eslint/eslint-plugin-react/blob/e2eaadae316f9506d163812a09424eb42698470a/docs/rules/jsx-no-constructed-context-values.md 'react/jsx-no-constructed-context-values': 'error', // Prevent creating unstable components inside components // https://github.com/jsx-eslint/eslint-plugin-react/blob/c2a790a3472eea0f6de984bdc3ee2a62197417fb/docs/rules/no-unstable-nested-components.md 'react/no-unstable-nested-components': 'error', // Enforce that namespaces are not used in React elements // https://github.com/jsx-eslint/eslint-plugin-react/blob/8785c169c25b09b33c95655bf508cf46263bc53f/docs/rules/no-namespace.md 'react/no-namespace': 'error', // Prefer exact proptype definitions // https://github.com/jsx-eslint/eslint-plugin-react/blob/8785c169c25b09b33c95655bf508cf46263bc53f/docs/rules/prefer-exact-props.md 'react/prefer-exact-props': 'error', // Lifecycle methods should be methods on the prototype, not class fields // https://github.com/jsx-eslint/eslint-plugin-react/blob/21e01b61af7a38fc86d94f27eb66cda8054582ed/docs/rules/no-arrow-function-lifecycle.md 'react/no-arrow-function-lifecycle': 'error', // Prevent usage of invalid attributes // https://github.com/jsx-eslint/eslint-plugin-react/blob/21e01b61af7a38fc86d94f27eb66cda8054582ed/docs/rules/no-invalid-html-attribute.md 'react/no-invalid-html-attribute': 'error', // Prevent declaring unused methods of component class // https://github.com/jsx-eslint/eslint-plugin-react/blob/21e01b61af7a38fc86d94f27eb66cda8054582ed/docs/rules/no-unused-class-component-methods.md 'react/no-unused-class-component-methods': 'error', // Ensure destructuring and symmetric naming of useState hook value and setter variables // https://github.com/jsx-eslint/eslint-plugin-react/blob/c8833f301314dab3e79ef7ac4cf863e4d5fa0019/docs/rules/hook-use-state.md // TODO: semver-major, enable 'react/hook-use-state': 'off', // Enforce sandbox attribute on iframe elements // https://github.com/jsx-eslint/eslint-plugin-react/blob/c8833f301314dab3e79ef7ac4cf863e4d5fa0019/docs/rules/iframe-missing-sandbox.md // TODO: semver-major, enable 'react/iframe-missing-sandbox': 'off', // Prevent problematic leaked values from being rendered // https://github.com/jsx-eslint/eslint-plugin-react/blob/c42b624d0fb9ad647583a775ab9751091eec066f/docs/rules/jsx-no-leaked-render.md // TODO: semver-major, enable 'react/jsx-no-leaked-render': 'off', // https://github.com/jsx-eslint/eslint-plugin-react/blob/66b58dd4864678eb869a7bf434c72ff7ac530eb1/docs/rules/no-object-type-as-default-prop.md // TODO: semver-major, enable 'react/no-object-type-as-default-prop': 'off', // https://github.com/jsx-eslint/eslint-plugin-react/blob/66b58dd4864678eb869a7bf434c72ff7ac530eb1/docs/rules/sort-default-props.md // TODO: semver-major, enable? 'react/sort-default-props': ['off', { ignoreCase: false }], // https://github.com/jsx-eslint/eslint-plugin-react/blob/9668ee0762acd5c23f53cd3a372e2d8d9563944d/docs/rules/forward-ref-uses-ref.md // TODO: semver-major, enable 'react/forward-ref-uses-ref': 'off', // https://github.com/jsx-eslint/eslint-plugin-react/blob/9668ee0762acd5c23f53cd3a372e2d8d9563944d/docs/rules/jsx-props-no-spread-multi.md // TODO: semver-major, enable 'react/jsx-props-no-spread-multi': 'off', }, settings: { 'import/resolver': { node: { extensions: ['.js', '.jsx', '.json'] } }, react: { pragma: 'React', version: 'detect', }, propWrapperFunctions: [ 'forbidExtraProps', // https://www.npmjs.com/package/airbnb-prop-types 'exact', // https://www.npmjs.com/package/prop-types-exact 'Object.freeze', // https://tc39.github.io/ecma262/#sec-object.freeze ], } };
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb/rules/react-a11y.js
packages/eslint-config-airbnb/rules/react-a11y.js
module.exports = { plugins: [ 'jsx-a11y', 'react' ], parserOptions: { ecmaFeatures: { jsx: true, }, }, rules: { // ensure emoji are accessible // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/accessible-emoji.md // disabled; rule is deprecated 'jsx-a11y/accessible-emoji': 'off', // Enforce that all elements that require alternative text have meaningful information // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/alt-text.md 'jsx-a11y/alt-text': ['error', { elements: ['img', 'object', 'area', 'input[type="image"]'], img: [], object: [], area: [], 'input[type="image"]': [], }], // Enforce that anchors have content // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/anchor-has-content.md 'jsx-a11y/anchor-has-content': ['error', { components: [] }], // ensure <a> tags are valid // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/0745af376cdc8686d85a361ce36952b1fb1ccf6e/docs/rules/anchor-is-valid.md 'jsx-a11y/anchor-is-valid': ['error', { components: ['Link'], specialLink: ['to'], aspects: ['noHref', 'invalidHref', 'preferButton'], }], // elements with aria-activedescendant must be tabbable // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-activedescendant-has-tabindex.md 'jsx-a11y/aria-activedescendant-has-tabindex': 'error', // Enforce all aria-* props are valid. // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-props.md 'jsx-a11y/aria-props': 'error', // Enforce ARIA state and property values are valid. // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-proptypes.md 'jsx-a11y/aria-proptypes': 'error', // Require ARIA roles to be valid and non-abstract // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-role.md 'jsx-a11y/aria-role': ['error', { ignoreNonDOM: false }], // Enforce that elements that do not support ARIA roles, states, and // properties do not have those attributes. // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-unsupported-elements.md 'jsx-a11y/aria-unsupported-elements': 'error', // Ensure the autocomplete attribute is correct and suitable for the form field it is used with // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/29c68596b15c4ff0a40daae6d4a2670e36e37d35/docs/rules/autocomplete-valid.md 'jsx-a11y/autocomplete-valid': ['off', { inputComponents: [], }], // require onClick be accompanied by onKeyUp/onKeyDown/onKeyPress // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/click-events-have-key-events.md 'jsx-a11y/click-events-have-key-events': 'error', // Enforce that a control (an interactive element) has a text label. // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/control-has-associated-label.md 'jsx-a11y/control-has-associated-label': ['error', { labelAttributes: ['label'], controlComponents: [], ignoreElements: [ 'audio', 'canvas', 'embed', 'input', 'textarea', 'tr', 'video', ], ignoreRoles: [ 'grid', 'listbox', 'menu', 'menubar', 'radiogroup', 'row', 'tablist', 'toolbar', 'tree', 'treegrid', ], depth: 5, }], // ensure <hX> tags have content and are not aria-hidden // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/heading-has-content.md 'jsx-a11y/heading-has-content': ['error', { components: [''] }], // require HTML elements to have a "lang" prop // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/html-has-lang.md 'jsx-a11y/html-has-lang': 'error', // ensure iframe elements have a unique title // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/iframe-has-title.md 'jsx-a11y/iframe-has-title': 'error', // Prevent img alt text from containing redundant words like "image", "picture", or "photo" // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/img-redundant-alt.md 'jsx-a11y/img-redundant-alt': 'error', // Elements with an interactive role and interaction handlers must be focusable // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/interactive-supports-focus.md 'jsx-a11y/interactive-supports-focus': 'error', // Enforce that a label tag has a text label and an associated control. // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/b800f40a2a69ad48015ae9226fbe879f946757ed/docs/rules/label-has-associated-control.md 'jsx-a11y/label-has-associated-control': ['error', { labelComponents: [], labelAttributes: [], controlComponents: [], assert: 'both', depth: 25 }], // require HTML element's lang prop to be valid // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/lang.md 'jsx-a11y/lang': 'error', // media elements must have captions // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/media-has-caption.md 'jsx-a11y/media-has-caption': ['error', { audio: [], video: [], track: [], }], // require that mouseover/out come with focus/blur, for keyboard-only users // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/mouse-events-have-key-events.md 'jsx-a11y/mouse-events-have-key-events': 'error', // Prevent use of `accessKey` // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-access-key.md 'jsx-a11y/no-access-key': 'error', // prohibit autoFocus prop // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-autofocus.md 'jsx-a11y/no-autofocus': ['error', { ignoreNonDOM: true }], // prevent distracting elements, like <marquee> and <blink> // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-distracting-elements.md 'jsx-a11y/no-distracting-elements': ['error', { elements: ['marquee', 'blink'], }], // WAI-ARIA roles should not be used to convert an interactive element to non-interactive // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-interactive-element-to-noninteractive-role.md 'jsx-a11y/no-interactive-element-to-noninteractive-role': ['error', { tr: ['none', 'presentation'], }], // A non-interactive element does not support event handlers (mouse and key handlers) // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-noninteractive-element-interactions.md 'jsx-a11y/no-noninteractive-element-interactions': ['error', { handlers: [ 'onClick', 'onMouseDown', 'onMouseUp', 'onKeyPress', 'onKeyDown', 'onKeyUp', ] }], // WAI-ARIA roles should not be used to convert a non-interactive element to interactive // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-noninteractive-element-to-interactive-role.md 'jsx-a11y/no-noninteractive-element-to-interactive-role': ['error', { ul: ['listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'tree', 'treegrid'], ol: ['listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'tree', 'treegrid'], li: ['menuitem', 'option', 'row', 'tab', 'treeitem'], table: ['grid'], td: ['gridcell'], }], // Tab key navigation should be limited to elements on the page that can be interacted with. // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-noninteractive-tabindex.md 'jsx-a11y/no-noninteractive-tabindex': ['error', { tags: [], roles: ['tabpanel'], allowExpressionValues: true, }], // require onBlur instead of onChange // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-onchange.md 'jsx-a11y/no-onchange': 'off', // ensure HTML elements do not specify redundant ARIA roles // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-redundant-roles.md 'jsx-a11y/no-redundant-roles': ['error', { nav: ['navigation'], }], // Enforce that DOM elements without semantic behavior not have interaction handlers // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-static-element-interactions.md 'jsx-a11y/no-static-element-interactions': ['error', { handlers: [ 'onClick', 'onMouseDown', 'onMouseUp', 'onKeyPress', 'onKeyDown', 'onKeyUp', ] }], // Enforce that elements with ARIA roles must have all required attributes // for that role. // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/role-has-required-aria-props.md 'jsx-a11y/role-has-required-aria-props': 'error', // Enforce that elements with explicit or implicit roles defined contain // only aria-* properties supported by that role. // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/role-supports-aria-props.md 'jsx-a11y/role-supports-aria-props': 'error', // only allow <th> to have the "scope" attr // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/scope.md 'jsx-a11y/scope': 'error', // Enforce tabIndex value is not greater than zero. // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/tabindex-no-positive.md 'jsx-a11y/tabindex-no-positive': 'error', // ---------------------------------------------------- // Rules that no longer exist in eslint-plugin-jsx-a11y // ---------------------------------------------------- // require that JSX labels use "htmlFor" // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/label-has-for.md // deprecated: replaced by `label-has-associated-control` rule 'jsx-a11y/label-has-for': ['off', { components: [], required: { every: ['nesting', 'id'], }, allowChildren: false, }], // Ensures anchor text is not ambiguous // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/93f78856655696a55309440593e0948c6fb96134/docs/rules/anchor-ambiguous-text.md // TODO: semver-major, enable 'jsx-a11y/anchor-ambiguous-text': 'off', // Enforce that aria-hidden="true" is not set on focusable elements. // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/93f78856655696a55309440593e0948c6fb96134/docs/rules/no-aria-hidden-on-focusable.md // TODO: semver-major, enable 'jsx-a11y/no-aria-hidden-on-focusable': 'off', // Enforces using semantic DOM elements over the ARIA role property. // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/93f78856655696a55309440593e0948c6fb96134/docs/rules/prefer-tag-over-role.md // TODO: semver-major, enable 'jsx-a11y/prefer-tag-over-role': 'off', }, };
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb/test/test-base.js
packages/eslint-config-airbnb/test/test-base.js
import fs from 'fs'; import path from 'path'; import test from 'tape'; const base = require('../base'); const files = { base }; const rulesDir = path.join(__dirname, '../rules'); fs.readdirSync(rulesDir).forEach((name) => { if (name === 'react.js' || name === 'react-a11y.js') { return; } // eslint-disable-next-line import/no-dynamic-require files[name] = require(path.join(rulesDir, name)); // eslint-disable-line global-require }); Object.keys(files).forEach((name) => { const config = files[name]; test(`${name}: does not reference react`, (t) => { t.plan(2); // scan plugins for react and fail if it is found const hasReactPlugin = Object.prototype.hasOwnProperty.call(config, 'plugins') && config.plugins.indexOf('react') !== -1; t.notOk(hasReactPlugin, 'there is no react plugin'); // scan rules for react/ and fail if any exist const reactRuleIds = Object.keys(config.rules) .filter((ruleId) => ruleId.indexOf('react/') === 0); t.deepEquals(reactRuleIds, [], 'there are no react/ rules'); }); });
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb/test/requires.js
packages/eslint-config-airbnb/test/requires.js
/* eslint strict: 0, global-require: 0 */ 'use strict'; const test = require('tape'); test('all entry points parse', (t) => { t.doesNotThrow(() => require('..'), 'index does not throw'); t.doesNotThrow(() => require('../base'), 'base does not throw'); t.doesNotThrow(() => require('../legacy'), 'legacy does not throw'); t.doesNotThrow(() => require('../whitespace'), 'whitespace does not throw'); t.doesNotThrow(() => require('../hooks'), 'hooks does not throw'); t.end(); });
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb/test/test-react-order.js
packages/eslint-config-airbnb/test/test-react-order.js
import test from 'tape'; import { CLIEngine, ESLint } from 'eslint'; import eslintrc from '..'; import reactRules from '../rules/react'; import reactA11yRules from '../rules/react-a11y'; const rules = { // It is okay to import devDependencies in tests. 'import/no-extraneous-dependencies': [2, { devDependencies: true }], // this doesn't matter for tests 'lines-between-class-members': 0, // otherwise we need some junk in our fixture code 'react/no-unused-class-component-methods': 0, }; const cli = new (CLIEngine || ESLint)({ useEslintrc: false, baseConfig: eslintrc, ...(CLIEngine ? { rules } : { overrideConfig: { rules } }), }); async function lint(text) { // @see https://eslint.org/docs/developer-guide/nodejs-api.html#executeonfiles // @see https://eslint.org/docs/developer-guide/nodejs-api.html#executeontext const linter = CLIEngine ? cli.executeOnText(text) : await cli.lintText(text); return (CLIEngine ? linter.results : linter)[0]; } function wrapComponent(body) { return `\ import React from 'react'; export default class MyComponent extends React.Component { /* eslint no-empty-function: 0, class-methods-use-this: 0 */ ${body}} `; } test('validate react methods order', (t) => { t.test('make sure our eslintrc has React and JSX linting dependencies', (t) => { t.plan(2); t.deepEqual(reactRules.plugins, ['react']); t.deepEqual(reactA11yRules.plugins, ['jsx-a11y', 'react']); }); t.test('passes a good component', async (t) => { const result = await lint(wrapComponent(` componentDidMount() {} handleSubmit() {} onButtonAClick() {} setFoo() {} getFoo() {} setBar() {} someMethod() {} renderDogs() {} render() { return <div />; } `)); t.notOk(result.warningCount, 'no warnings'); t.deepEquals(result.messages, [], 'no messages in results'); t.notOk(result.errorCount, 'no errors'); }); t.test('order: when random method is first', async (t) => { const result = await lint(wrapComponent(` someMethod() {} componentDidMount() {} setFoo() {} getFoo() {} setBar() {} renderDogs() {} render() { return <div />; } `)); t.ok(result.errorCount, 'fails'); t.deepEqual(result.messages.map((msg) => msg.ruleId), ['react/sort-comp'], 'fails due to sort'); }); t.test('order: when random method after lifecycle methods', async (t) => { const result = await lint(wrapComponent(` componentDidMount() {} someMethod() {} setFoo() {} getFoo() {} setBar() {} renderDogs() {} render() { return <div />; } `)); t.ok(result.errorCount, 'fails'); t.deepEqual(result.messages.map((msg) => msg.ruleId), ['react/sort-comp'], 'fails due to sort'); }); t.test('order: when handler method with `handle` prefix after method with `on` prefix', async (t) => { const result = await lint(wrapComponent(` componentDidMount() {} onButtonAClick() {} handleSubmit() {} setFoo() {} getFoo() {} render() { return <div />; } `)); t.ok(result.errorCount, 'fails'); t.deepEqual(result.messages.map((msg) => msg.ruleId), ['react/sort-comp'], 'fails due to sort'); }); t.test('order: when lifecycle methods after event handler methods', async (t) => { const result = await lint(wrapComponent(` handleSubmit() {} componentDidMount() {} setFoo() {} getFoo() {} render() { return <div />; } `)); t.ok(result.errorCount, 'fails'); t.deepEqual(result.messages.map((msg) => msg.ruleId), ['react/sort-comp'], 'fails due to sort'); }); t.test('order: when event handler methods after getters and setters', async (t) => { const result = await lint(wrapComponent(` componentDidMount() {} setFoo() {} getFoo() {} handleSubmit() {} render() { return <div />; } `)); t.ok(result.errorCount, 'fails'); t.deepEqual(result.messages.map((msg) => msg.ruleId), ['react/sort-comp'], 'fails due to sort'); }); });
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb-base/index.js
packages/eslint-config-airbnb-base/index.js
module.exports = { extends: [ './rules/best-practices', './rules/errors', './rules/node', './rules/style', './rules/variables', './rules/es6', './rules/imports', './rules/strict', ].map(require.resolve), parserOptions: { ecmaVersion: 2018, sourceType: 'module', }, rules: {}, };
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb-base/legacy.js
packages/eslint-config-airbnb-base/legacy.js
module.exports = { extends: [ './rules/best-practices', './rules/errors', './rules/node', './rules/style', './rules/variables' ].map(require.resolve), env: { browser: true, node: true, amd: false, mocha: false, jasmine: false }, rules: { 'comma-dangle': ['error', 'never'], 'prefer-numeric-literals': 'off', 'no-restricted-properties': ['error', { object: 'arguments', property: 'callee', message: 'arguments.callee is deprecated', }, { property: '__defineGetter__', message: 'Please use Object.defineProperty instead.', }, { property: '__defineSetter__', message: 'Please use Object.defineProperty instead.', }], 'no-var': 'off', 'prefer-object-spread': 'off', strict: ['error', 'safe'], } };
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb-base/whitespace.js
packages/eslint-config-airbnb-base/whitespace.js
/* eslint global-require: 0 */ const { isArray } = Array; const { entries } = Object; const { CLIEngine } = require('eslint'); if (CLIEngine) { /* eslint no-inner-declarations: 0 */ const whitespaceRules = require('./whitespaceRules'); const baseConfig = require('.'); const severities = ['off', 'warn', 'error']; function getSeverity(ruleConfig) { if (isArray(ruleConfig)) { return getSeverity(ruleConfig[0]); } if (typeof ruleConfig === 'number') { return severities[ruleConfig]; } return ruleConfig; } function onlyErrorOnRules(rulesToError, config) { const errorsOnly = { ...config }; const cli = new CLIEngine({ baseConfig: config, useEslintrc: false }); const baseRules = cli.getConfigForFile(require.resolve('./')).rules; entries(baseRules).forEach((rule) => { const ruleName = rule[0]; const ruleConfig = rule[1]; const severity = getSeverity(ruleConfig); if (rulesToError.indexOf(ruleName) === -1 && severity === 'error') { if (isArray(ruleConfig)) { errorsOnly.rules[ruleName] = ['warn'].concat(ruleConfig.slice(1)); } else if (typeof ruleConfig === 'number') { errorsOnly.rules[ruleName] = 1; } else { errorsOnly.rules[ruleName] = 'warn'; } } }); return errorsOnly; } module.exports = onlyErrorOnRules(whitespaceRules, baseConfig); } else { const path = require('path'); const { execSync } = require('child_process'); // NOTE: ESLint adds runtime statistics to the output (so it's no longer JSON) if TIMING is set module.exports = JSON.parse(String(execSync(path.join(__dirname, 'whitespace-async.js'), { env: { ...process.env, TIMING: undefined, } }))); }
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb-base/whitespaceRules.js
packages/eslint-config-airbnb-base/whitespaceRules.js
module.exports = [ 'array-bracket-newline', 'array-bracket-spacing', 'array-element-newline', 'arrow-spacing', 'block-spacing', 'comma-spacing', 'computed-property-spacing', 'dot-location', 'eol-last', 'func-call-spacing', 'function-paren-newline', 'generator-star-spacing', 'implicit-arrow-linebreak', 'indent', 'key-spacing', 'keyword-spacing', 'line-comment-position', 'linebreak-style', 'multiline-ternary', 'newline-per-chained-call', 'no-irregular-whitespace', 'no-mixed-spaces-and-tabs', 'no-multi-spaces', 'no-regex-spaces', 'no-spaced-func', 'no-trailing-spaces', 'no-whitespace-before-property', 'nonblock-statement-body-position', 'object-curly-newline', 'object-curly-spacing', 'object-property-newline', 'one-var-declaration-per-line', 'operator-linebreak', 'padded-blocks', 'padding-line-between-statements', 'rest-spread-spacing', 'semi-spacing', 'semi-style', 'space-before-blocks', 'space-before-function-paren', 'space-in-parens', 'space-infix-ops', 'space-unary-ops', 'spaced-comment', 'switch-colon-spacing', 'template-tag-spacing', 'import/newline-after-import' ];
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb-base/whitespace-async.js
packages/eslint-config-airbnb-base/whitespace-async.js
#!/usr/bin/env node const { isArray } = Array; const { entries } = Object; const { ESLint } = require('eslint'); const baseConfig = require('.'); const whitespaceRules = require('./whitespaceRules'); const severities = ['off', 'warn', 'error']; function getSeverity(ruleConfig) { if (isArray(ruleConfig)) { return getSeverity(ruleConfig[0]); } if (typeof ruleConfig === 'number') { return severities[ruleConfig]; } return ruleConfig; } async function onlyErrorOnRules(rulesToError, config) { const errorsOnly = { ...config }; const cli = new ESLint({ useEslintrc: false, baseConfig: config }); const baseRules = (await cli.calculateConfigForFile(require.resolve('./'))).rules; entries(baseRules).forEach((rule) => { const ruleName = rule[0]; const ruleConfig = rule[1]; const severity = getSeverity(ruleConfig); if (rulesToError.indexOf(ruleName) === -1 && severity === 'error') { if (isArray(ruleConfig)) { errorsOnly.rules[ruleName] = ['warn'].concat(ruleConfig.slice(1)); } else if (typeof ruleConfig === 'number') { errorsOnly.rules[ruleName] = 1; } else { errorsOnly.rules[ruleName] = 'warn'; } } }); return errorsOnly; } onlyErrorOnRules(whitespaceRules, baseConfig).then((config) => console.log(JSON.stringify(config)));
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb-base/rules/best-practices.js
packages/eslint-config-airbnb-base/rules/best-practices.js
module.exports = { rules: { // enforces getter/setter pairs in objects // https://eslint.org/docs/rules/accessor-pairs 'accessor-pairs': 'off', // enforces return statements in callbacks of array's methods // https://eslint.org/docs/rules/array-callback-return 'array-callback-return': ['error', { allowImplicit: true }], // treat var statements as if they were block scoped // https://eslint.org/docs/rules/block-scoped-var 'block-scoped-var': 'error', // specify the maximum cyclomatic complexity allowed in a program // https://eslint.org/docs/rules/complexity complexity: ['off', 20], // enforce that class methods use "this" // https://eslint.org/docs/rules/class-methods-use-this 'class-methods-use-this': ['error', { exceptMethods: [], }], // require return statements to either always or never specify values // https://eslint.org/docs/rules/consistent-return 'consistent-return': 'error', // specify curly brace conventions for all control statements // https://eslint.org/docs/rules/curly curly: ['error', 'multi-line'], // multiline // require default case in switch statements // https://eslint.org/docs/rules/default-case 'default-case': ['error', { commentPattern: '^no default$' }], // Enforce default clauses in switch statements to be last // https://eslint.org/docs/rules/default-case-last 'default-case-last': 'error', // https://eslint.org/docs/rules/default-param-last 'default-param-last': 'error', // encourages use of dot notation whenever possible // https://eslint.org/docs/rules/dot-notation 'dot-notation': ['error', { allowKeywords: true }], // enforces consistent newlines before or after dots // https://eslint.org/docs/rules/dot-location 'dot-location': ['error', 'property'], // require the use of === and !== // https://eslint.org/docs/rules/eqeqeq eqeqeq: ['error', 'always', { null: 'ignore' }], // Require grouped accessor pairs in object literals and classes // https://eslint.org/docs/rules/grouped-accessor-pairs 'grouped-accessor-pairs': 'error', // make sure for-in loops have an if statement // https://eslint.org/docs/rules/guard-for-in 'guard-for-in': 'error', // enforce a maximum number of classes per file // https://eslint.org/docs/rules/max-classes-per-file 'max-classes-per-file': ['error', 1], // disallow the use of alert, confirm, and prompt // https://eslint.org/docs/rules/no-alert // TODO: enable, semver-major 'no-alert': 'warn', // disallow use of arguments.caller or arguments.callee // https://eslint.org/docs/rules/no-caller 'no-caller': 'error', // disallow lexical declarations in case/default clauses // https://eslint.org/docs/rules/no-case-declarations 'no-case-declarations': 'error', // Disallow returning value in constructor // https://eslint.org/docs/rules/no-constructor-return 'no-constructor-return': 'error', // disallow division operators explicitly at beginning of regular expression // https://eslint.org/docs/rules/no-div-regex 'no-div-regex': 'off', // disallow else after a return in an if // https://eslint.org/docs/rules/no-else-return 'no-else-return': ['error', { allowElseIf: false }], // disallow empty functions, except for standalone funcs/arrows // https://eslint.org/docs/rules/no-empty-function 'no-empty-function': ['error', { allow: [ 'arrowFunctions', 'functions', 'methods', ] }], // disallow empty destructuring patterns // https://eslint.org/docs/rules/no-empty-pattern 'no-empty-pattern': 'error', // Disallow empty static blocks // https://eslint.org/docs/latest/rules/no-empty-static-block // TODO: semver-major, enable 'no-empty-static-block': 'off', // disallow comparisons to null without a type-checking operator // https://eslint.org/docs/rules/no-eq-null 'no-eq-null': 'off', // disallow use of eval() // https://eslint.org/docs/rules/no-eval 'no-eval': 'error', // disallow adding to native types // https://eslint.org/docs/rules/no-extend-native 'no-extend-native': 'error', // disallow unnecessary function binding // https://eslint.org/docs/rules/no-extra-bind 'no-extra-bind': 'error', // disallow Unnecessary Labels // https://eslint.org/docs/rules/no-extra-label 'no-extra-label': 'error', // disallow fallthrough of case statements // https://eslint.org/docs/rules/no-fallthrough 'no-fallthrough': 'error', // disallow the use of leading or trailing decimal points in numeric literals // https://eslint.org/docs/rules/no-floating-decimal 'no-floating-decimal': 'error', // disallow reassignments of native objects or read-only globals // https://eslint.org/docs/rules/no-global-assign 'no-global-assign': ['error', { exceptions: [] }], // deprecated in favor of no-global-assign // https://eslint.org/docs/rules/no-native-reassign 'no-native-reassign': 'off', // disallow implicit type conversions // https://eslint.org/docs/rules/no-implicit-coercion 'no-implicit-coercion': ['off', { boolean: false, number: true, string: true, allow: [], }], // disallow var and named functions in global scope // https://eslint.org/docs/rules/no-implicit-globals 'no-implicit-globals': 'off', // disallow use of eval()-like methods // https://eslint.org/docs/rules/no-implied-eval 'no-implied-eval': 'error', // disallow this keywords outside of classes or class-like objects // https://eslint.org/docs/rules/no-invalid-this 'no-invalid-this': 'off', // disallow usage of __iterator__ property // https://eslint.org/docs/rules/no-iterator 'no-iterator': 'error', // disallow use of labels for anything other than loops and switches // https://eslint.org/docs/rules/no-labels 'no-labels': ['error', { allowLoop: false, allowSwitch: false }], // disallow unnecessary nested blocks // https://eslint.org/docs/rules/no-lone-blocks 'no-lone-blocks': 'error', // disallow creation of functions within loops // https://eslint.org/docs/rules/no-loop-func 'no-loop-func': 'error', // disallow magic numbers // https://eslint.org/docs/rules/no-magic-numbers 'no-magic-numbers': ['off', { ignore: [], ignoreArrayIndexes: true, enforceConst: true, detectObjects: false, }], // disallow use of multiple spaces // https://eslint.org/docs/rules/no-multi-spaces 'no-multi-spaces': ['error', { ignoreEOLComments: false, }], // disallow use of multiline strings // https://eslint.org/docs/rules/no-multi-str 'no-multi-str': 'error', // disallow use of new operator when not part of the assignment or comparison // https://eslint.org/docs/rules/no-new 'no-new': 'error', // disallow use of new operator for Function object // https://eslint.org/docs/rules/no-new-func 'no-new-func': 'error', // disallows creating new instances of String, Number, and Boolean // https://eslint.org/docs/rules/no-new-wrappers 'no-new-wrappers': 'error', // Disallow \8 and \9 escape sequences in string literals // https://eslint.org/docs/rules/no-nonoctal-decimal-escape 'no-nonoctal-decimal-escape': 'error', // Disallow calls to the Object constructor without an argument // https://eslint.org/docs/latest/rules/no-object-constructor // TODO: enable, semver-major 'no-object-constructor': 'off', // disallow use of (old style) octal literals // https://eslint.org/docs/rules/no-octal 'no-octal': 'error', // disallow use of octal escape sequences in string literals, such as // var foo = 'Copyright \251'; // https://eslint.org/docs/rules/no-octal-escape 'no-octal-escape': 'error', // disallow reassignment of function parameters // disallow parameter object manipulation except for specific exclusions // rule: https://eslint.org/docs/rules/no-param-reassign.html 'no-param-reassign': ['error', { props: true, ignorePropertyModificationsFor: [ 'acc', // for reduce accumulators 'accumulator', // for reduce accumulators 'e', // for e.returnvalue 'ctx', // for Koa routing 'context', // for Koa routing 'req', // for Express requests 'request', // for Express requests 'res', // for Express responses 'response', // for Express responses '$scope', // for Angular 1 scopes 'staticContext', // for ReactRouter context ] }], // disallow usage of __proto__ property // https://eslint.org/docs/rules/no-proto 'no-proto': 'error', // disallow declaring the same variable more than once // https://eslint.org/docs/rules/no-redeclare 'no-redeclare': 'error', // disallow certain object properties // https://eslint.org/docs/rules/no-restricted-properties 'no-restricted-properties': ['error', { object: 'arguments', property: 'callee', message: 'arguments.callee is deprecated', }, { object: 'global', property: 'isFinite', message: 'Please use Number.isFinite instead', }, { object: 'self', property: 'isFinite', message: 'Please use Number.isFinite instead', }, { object: 'window', property: 'isFinite', message: 'Please use Number.isFinite instead', }, { object: 'global', property: 'isNaN', message: 'Please use Number.isNaN instead', }, { object: 'self', property: 'isNaN', message: 'Please use Number.isNaN instead', }, { object: 'window', property: 'isNaN', message: 'Please use Number.isNaN instead', }, { property: '__defineGetter__', message: 'Please use Object.defineProperty instead.', }, { property: '__defineSetter__', message: 'Please use Object.defineProperty instead.', }, { object: 'Math', property: 'pow', message: 'Use the exponentiation operator (**) instead.', }], // disallow use of assignment in return statement // https://eslint.org/docs/rules/no-return-assign 'no-return-assign': ['error', 'always'], // disallow redundant `return await` // https://eslint.org/docs/rules/no-return-await 'no-return-await': 'error', // disallow use of `javascript:` urls. // https://eslint.org/docs/rules/no-script-url 'no-script-url': 'error', // disallow self assignment // https://eslint.org/docs/rules/no-self-assign 'no-self-assign': ['error', { props: true, }], // disallow comparisons where both sides are exactly the same // https://eslint.org/docs/rules/no-self-compare 'no-self-compare': 'error', // disallow use of comma operator // https://eslint.org/docs/rules/no-sequences 'no-sequences': 'error', // restrict what can be thrown as an exception // https://eslint.org/docs/rules/no-throw-literal 'no-throw-literal': 'error', // disallow unmodified conditions of loops // https://eslint.org/docs/rules/no-unmodified-loop-condition 'no-unmodified-loop-condition': 'off', // disallow usage of expressions in statement position // https://eslint.org/docs/rules/no-unused-expressions 'no-unused-expressions': ['error', { allowShortCircuit: false, allowTernary: false, allowTaggedTemplates: false, }], // disallow unused labels // https://eslint.org/docs/rules/no-unused-labels 'no-unused-labels': 'error', // disallow unnecessary .call() and .apply() // https://eslint.org/docs/rules/no-useless-call 'no-useless-call': 'off', // Disallow unnecessary catch clauses // https://eslint.org/docs/rules/no-useless-catch 'no-useless-catch': 'error', // disallow useless string concatenation // https://eslint.org/docs/rules/no-useless-concat 'no-useless-concat': 'error', // disallow unnecessary string escaping // https://eslint.org/docs/rules/no-useless-escape 'no-useless-escape': 'error', // disallow redundant return; keywords // https://eslint.org/docs/rules/no-useless-return 'no-useless-return': 'error', // disallow use of void operator // https://eslint.org/docs/rules/no-void 'no-void': 'error', // disallow usage of configurable warning terms in comments: e.g. todo // https://eslint.org/docs/rules/no-warning-comments 'no-warning-comments': ['off', { terms: ['todo', 'fixme', 'xxx'], location: 'start' }], // disallow use of the with statement // https://eslint.org/docs/rules/no-with 'no-with': 'error', // require using Error objects as Promise rejection reasons // https://eslint.org/docs/rules/prefer-promise-reject-errors 'prefer-promise-reject-errors': ['error', { allowEmptyReject: true }], // Suggest using named capture group in regular expression // https://eslint.org/docs/rules/prefer-named-capture-group 'prefer-named-capture-group': 'off', // Prefer Object.hasOwn() over Object.prototype.hasOwnProperty.call() // https://eslint.org/docs/rules/prefer-object-has-own // TODO: semver-major: enable thus rule, once eslint v8.5.0 is required 'prefer-object-has-own': 'off', // https://eslint.org/docs/rules/prefer-regex-literals 'prefer-regex-literals': ['error', { disallowRedundantWrapping: true, }], // require use of the second argument for parseInt() // https://eslint.org/docs/rules/radix radix: 'error', // require `await` in `async function` (note: this is a horrible rule that should never be used) // https://eslint.org/docs/rules/require-await 'require-await': 'off', // Enforce the use of u flag on RegExp // https://eslint.org/docs/rules/require-unicode-regexp 'require-unicode-regexp': 'off', // requires to declare all vars on top of their containing scope // https://eslint.org/docs/rules/vars-on-top 'vars-on-top': 'error', // require immediate function invocation to be wrapped in parentheses // https://eslint.org/docs/rules/wrap-iife.html 'wrap-iife': ['error', 'outside', { functionPrototypeMethods: false }], // require or disallow Yoda conditions // https://eslint.org/docs/rules/yoda yoda: 'error' } };
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb-base/rules/variables.js
packages/eslint-config-airbnb-base/rules/variables.js
const confusingBrowserGlobals = require('confusing-browser-globals'); module.exports = { rules: { // enforce or disallow variable initializations at definition 'init-declarations': 'off', // disallow the catch clause parameter name being the same as a variable in the outer scope 'no-catch-shadow': 'off', // disallow deletion of variables 'no-delete-var': 'error', // disallow labels that share a name with a variable // https://eslint.org/docs/rules/no-label-var 'no-label-var': 'error', // disallow specific globals 'no-restricted-globals': [ 'error', { name: 'isFinite', message: 'Use Number.isFinite instead https://github.com/airbnb/javascript#standard-library--isfinite', }, { name: 'isNaN', message: 'Use Number.isNaN instead https://github.com/airbnb/javascript#standard-library--isnan', }, ].concat(confusingBrowserGlobals.map((g) => ({ name: g, message: `Use window.${g} instead. https://github.com/facebook/create-react-app/blob/HEAD/packages/confusing-browser-globals/README.md`, }))), // disallow declaration of variables already declared in the outer scope 'no-shadow': 'error', // disallow shadowing of names such as arguments 'no-shadow-restricted-names': 'error', // disallow use of undeclared variables unless mentioned in a /*global */ block 'no-undef': 'error', // disallow use of undefined when initializing variables 'no-undef-init': 'error', // disallow use of undefined variable // https://eslint.org/docs/rules/no-undefined // TODO: enable? 'no-undefined': 'off', // disallow declaration of variables that are not used in the code 'no-unused-vars': ['error', { vars: 'all', args: 'after-used', ignoreRestSiblings: true }], // disallow use of variables before they are defined 'no-use-before-define': ['error', { functions: true, classes: true, variables: true }], } };
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb-base/rules/strict.js
packages/eslint-config-airbnb-base/rules/strict.js
module.exports = { rules: { // babel inserts `'use strict';` for us strict: ['error', 'never'] } };
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb-base/rules/style.js
packages/eslint-config-airbnb-base/rules/style.js
module.exports = { rules: { // enforce line breaks after opening and before closing array brackets // https://eslint.org/docs/rules/array-bracket-newline // TODO: enable? semver-major 'array-bracket-newline': ['off', 'consistent'], // object option alternative: { multiline: true, minItems: 3 } // enforce line breaks between array elements // https://eslint.org/docs/rules/array-element-newline // TODO: enable? semver-major 'array-element-newline': ['off', { multiline: true, minItems: 3 }], // enforce spacing inside array brackets 'array-bracket-spacing': ['error', 'never'], // enforce spacing inside single-line blocks // https://eslint.org/docs/rules/block-spacing 'block-spacing': ['error', 'always'], // enforce one true brace style 'brace-style': ['error', '1tbs', { allowSingleLine: true }], // require camel case names camelcase: ['error', { properties: 'never', ignoreDestructuring: false }], // enforce or disallow capitalization of the first letter of a comment // https://eslint.org/docs/rules/capitalized-comments 'capitalized-comments': ['off', 'never', { line: { ignorePattern: '.*', ignoreInlineComments: true, ignoreConsecutiveComments: true, }, block: { ignorePattern: '.*', ignoreInlineComments: true, ignoreConsecutiveComments: true, }, }], // require trailing commas in multiline object literals 'comma-dangle': ['error', { arrays: 'always-multiline', objects: 'always-multiline', imports: 'always-multiline', exports: 'always-multiline', functions: 'always-multiline', }], // enforce spacing before and after comma 'comma-spacing': ['error', { before: false, after: true }], // enforce one true comma style 'comma-style': ['error', 'last', { exceptions: { ArrayExpression: false, ArrayPattern: false, ArrowFunctionExpression: false, CallExpression: false, FunctionDeclaration: false, FunctionExpression: false, ImportDeclaration: false, ObjectExpression: false, ObjectPattern: false, VariableDeclaration: false, NewExpression: false, } }], // disallow padding inside computed properties 'computed-property-spacing': ['error', 'never'], // enforces consistent naming when capturing the current execution context 'consistent-this': 'off', // enforce newline at the end of file, with no multiple empty lines 'eol-last': ['error', 'always'], // https://eslint.org/docs/rules/function-call-argument-newline 'function-call-argument-newline': ['error', 'consistent'], // enforce spacing between functions and their invocations // https://eslint.org/docs/rules/func-call-spacing 'func-call-spacing': ['error', 'never'], // requires function names to match the name of the variable or property to which they are // assigned // https://eslint.org/docs/rules/func-name-matching 'func-name-matching': ['off', 'always', { includeCommonJSModuleExports: false, considerPropertyDescriptor: true, }], // require function expressions to have a name // https://eslint.org/docs/rules/func-names 'func-names': 'warn', // enforces use of function declarations or expressions // https://eslint.org/docs/rules/func-style // TODO: enable 'func-style': ['off', 'expression'], // require line breaks inside function parentheses if there are line breaks between parameters // https://eslint.org/docs/rules/function-paren-newline 'function-paren-newline': ['error', 'multiline-arguments'], // disallow specified identifiers // https://eslint.org/docs/rules/id-denylist 'id-denylist': 'off', // this option enforces minimum and maximum identifier lengths // (variable names, property names etc.) 'id-length': 'off', // require identifiers to match the provided regular expression 'id-match': 'off', // Enforce the location of arrow function bodies with implicit returns // https://eslint.org/docs/rules/implicit-arrow-linebreak 'implicit-arrow-linebreak': ['error', 'beside'], // this option sets a specific tab width for your code // https://eslint.org/docs/rules/indent indent: ['error', 2, { SwitchCase: 1, VariableDeclarator: 1, outerIIFEBody: 1, // MemberExpression: null, FunctionDeclaration: { parameters: 1, body: 1 }, FunctionExpression: { parameters: 1, body: 1 }, CallExpression: { arguments: 1 }, ArrayExpression: 1, ObjectExpression: 1, ImportDeclaration: 1, flatTernaryExpressions: false, // list derived from https://github.com/benjamn/ast-types/blob/HEAD/def/jsx.js ignoredNodes: ['JSXElement', 'JSXElement > *', 'JSXAttribute', 'JSXIdentifier', 'JSXNamespacedName', 'JSXMemberExpression', 'JSXSpreadAttribute', 'JSXExpressionContainer', 'JSXOpeningElement', 'JSXClosingElement', 'JSXFragment', 'JSXOpeningFragment', 'JSXClosingFragment', 'JSXText', 'JSXEmptyExpression', 'JSXSpreadChild'], ignoreComments: false }], // specify whether double or single quotes should be used in JSX attributes // https://eslint.org/docs/rules/jsx-quotes 'jsx-quotes': ['off', 'prefer-double'], // enforces spacing between keys and values in object literal properties 'key-spacing': ['error', { beforeColon: false, afterColon: true }], // require a space before & after certain keywords 'keyword-spacing': ['error', { before: true, after: true, overrides: { return: { after: true }, throw: { after: true }, case: { after: true } } }], // enforce position of line comments // https://eslint.org/docs/rules/line-comment-position // TODO: enable? 'line-comment-position': ['off', { position: 'above', ignorePattern: '', applyDefaultPatterns: true, }], // disallow mixed 'LF' and 'CRLF' as linebreaks // https://eslint.org/docs/rules/linebreak-style 'linebreak-style': ['error', 'unix'], // require or disallow an empty line between class members // https://eslint.org/docs/rules/lines-between-class-members 'lines-between-class-members': ['error', 'always', { exceptAfterSingleLine: false }], // enforces empty lines around comments 'lines-around-comment': 'off', // require or disallow newlines around directives // https://eslint.org/docs/rules/lines-around-directive 'lines-around-directive': ['error', { before: 'always', after: 'always', }], // Require or disallow logical assignment logical operator shorthand // https://eslint.org/docs/latest/rules/logical-assignment-operators // TODO, semver-major: enable 'logical-assignment-operators': ['off', 'always', { enforceForIfStatements: true, }], // specify the maximum depth that blocks can be nested 'max-depth': ['off', 4], // specify the maximum length of a line in your program // https://eslint.org/docs/rules/max-len 'max-len': ['error', 100, 2, { ignoreUrls: true, ignoreComments: false, ignoreRegExpLiterals: true, ignoreStrings: true, ignoreTemplateLiterals: true, }], // specify the max number of lines in a file // https://eslint.org/docs/rules/max-lines 'max-lines': ['off', { max: 300, skipBlankLines: true, skipComments: true }], // enforce a maximum function length // https://eslint.org/docs/rules/max-lines-per-function 'max-lines-per-function': ['off', { max: 50, skipBlankLines: true, skipComments: true, IIFEs: true, }], // specify the maximum depth callbacks can be nested 'max-nested-callbacks': 'off', // limits the number of parameters that can be used in the function declaration. 'max-params': ['off', 3], // specify the maximum number of statement allowed in a function 'max-statements': ['off', 10], // restrict the number of statements per line // https://eslint.org/docs/rules/max-statements-per-line 'max-statements-per-line': ['off', { max: 1 }], // enforce a particular style for multiline comments // https://eslint.org/docs/rules/multiline-comment-style 'multiline-comment-style': ['off', 'starred-block'], // require multiline ternary // https://eslint.org/docs/rules/multiline-ternary // TODO: enable? 'multiline-ternary': ['off', 'never'], // require a capital letter for constructors 'new-cap': ['error', { newIsCap: true, newIsCapExceptions: [], capIsNew: false, capIsNewExceptions: ['Immutable.Map', 'Immutable.Set', 'Immutable.List'], }], // disallow the omission of parentheses when invoking a constructor with no arguments // https://eslint.org/docs/rules/new-parens 'new-parens': 'error', // allow/disallow an empty newline after var statement 'newline-after-var': 'off', // https://eslint.org/docs/rules/newline-before-return 'newline-before-return': 'off', // enforces new line after each method call in the chain to make it // more readable and easy to maintain // https://eslint.org/docs/rules/newline-per-chained-call 'newline-per-chained-call': ['error', { ignoreChainWithDepth: 4 }], // disallow use of the Array constructor 'no-array-constructor': 'error', // disallow use of bitwise operators // https://eslint.org/docs/rules/no-bitwise 'no-bitwise': 'error', // disallow use of the continue statement // https://eslint.org/docs/rules/no-continue 'no-continue': 'error', // disallow comments inline after code 'no-inline-comments': 'off', // disallow if as the only statement in an else block // https://eslint.org/docs/rules/no-lonely-if 'no-lonely-if': 'error', // disallow un-paren'd mixes of different operators // https://eslint.org/docs/rules/no-mixed-operators 'no-mixed-operators': ['error', { // the list of arithmetic groups disallows mixing `%` and `**` // with other arithmetic operators. groups: [ ['%', '**'], ['%', '+'], ['%', '-'], ['%', '*'], ['%', '/'], ['/', '*'], ['&', '|', '<<', '>>', '>>>'], ['==', '!=', '===', '!=='], ['&&', '||'], ], allowSamePrecedence: false }], // disallow mixed spaces and tabs for indentation 'no-mixed-spaces-and-tabs': 'error', // disallow use of chained assignment expressions // https://eslint.org/docs/rules/no-multi-assign 'no-multi-assign': ['error'], // disallow multiple empty lines, only one newline at the end, and no new lines at the beginning // https://eslint.org/docs/rules/no-multiple-empty-lines 'no-multiple-empty-lines': ['error', { max: 1, maxBOF: 0, maxEOF: 0 }], // disallow negated conditions // https://eslint.org/docs/rules/no-negated-condition 'no-negated-condition': 'off', // disallow nested ternary expressions 'no-nested-ternary': 'error', // disallow use of the Object constructor 'no-new-object': 'error', // disallow use of unary operators, ++ and -- // https://eslint.org/docs/rules/no-plusplus 'no-plusplus': 'error', // disallow certain syntax forms // https://eslint.org/docs/rules/no-restricted-syntax 'no-restricted-syntax': [ 'error', { selector: 'ForInStatement', message: 'for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array.', }, { selector: 'ForOfStatement', message: 'iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations.', }, { selector: 'LabeledStatement', message: 'Labels are a form of GOTO; using them makes code confusing and hard to maintain and understand.', }, { selector: 'WithStatement', message: '`with` is disallowed in strict mode because it makes code impossible to predict and optimize.', }, ], // disallow space between function identifier and application // deprecated in favor of func-call-spacing 'no-spaced-func': 'off', // disallow tab characters entirely 'no-tabs': 'error', // disallow the use of ternary operators 'no-ternary': 'off', // disallow trailing whitespace at the end of lines 'no-trailing-spaces': ['error', { skipBlankLines: false, ignoreComments: false, }], // disallow dangling underscores in identifiers // https://eslint.org/docs/rules/no-underscore-dangle 'no-underscore-dangle': ['error', { allow: [], allowAfterThis: false, allowAfterSuper: false, enforceInMethodNames: true, }], // disallow the use of Boolean literals in conditional expressions // also, prefer `a || b` over `a ? a : b` // https://eslint.org/docs/rules/no-unneeded-ternary 'no-unneeded-ternary': ['error', { defaultAssignment: false }], // disallow whitespace before properties // https://eslint.org/docs/rules/no-whitespace-before-property 'no-whitespace-before-property': 'error', // enforce the location of single-line statements // https://eslint.org/docs/rules/nonblock-statement-body-position 'nonblock-statement-body-position': ['error', 'beside', { overrides: {} }], // require padding inside curly braces 'object-curly-spacing': ['error', 'always'], // enforce line breaks between braces // https://eslint.org/docs/rules/object-curly-newline 'object-curly-newline': ['error', { ObjectExpression: { minProperties: 4, multiline: true, consistent: true }, ObjectPattern: { minProperties: 4, multiline: true, consistent: true }, ImportDeclaration: { minProperties: 4, multiline: true, consistent: true }, ExportDeclaration: { minProperties: 4, multiline: true, consistent: true }, }], // enforce "same line" or "multiple line" on object properties. // https://eslint.org/docs/rules/object-property-newline 'object-property-newline': ['error', { allowAllPropertiesOnSameLine: true, }], // allow just one var statement per function 'one-var': ['error', 'never'], // require a newline around variable declaration // https://eslint.org/docs/rules/one-var-declaration-per-line 'one-var-declaration-per-line': ['error', 'always'], // require assignment operator shorthand where possible or prohibit it entirely // https://eslint.org/docs/rules/operator-assignment 'operator-assignment': ['error', 'always'], // Requires operator at the beginning of the line in multiline statements // https://eslint.org/docs/rules/operator-linebreak 'operator-linebreak': ['error', 'before', { overrides: { '=': 'none' } }], // disallow padding within blocks 'padded-blocks': ['error', { blocks: 'never', classes: 'never', switches: 'never', }, { allowSingleLineBlocks: true, }], // Require or disallow padding lines between statements // https://eslint.org/docs/rules/padding-line-between-statements 'padding-line-between-statements': 'off', // Disallow the use of Math.pow in favor of the ** operator // https://eslint.org/docs/rules/prefer-exponentiation-operator 'prefer-exponentiation-operator': 'error', // Prefer use of an object spread over Object.assign // https://eslint.org/docs/rules/prefer-object-spread 'prefer-object-spread': 'error', // require quotes around object literal property names // https://eslint.org/docs/rules/quote-props.html 'quote-props': ['error', 'as-needed', { keywords: false, unnecessary: true, numbers: false }], // specify whether double or single quotes should be used quotes: ['error', 'single', { avoidEscape: true }], // do not require jsdoc // https://eslint.org/docs/rules/require-jsdoc 'require-jsdoc': 'off', // require or disallow use of semicolons instead of ASI semi: ['error', 'always'], // enforce spacing before and after semicolons 'semi-spacing': ['error', { before: false, after: true }], // Enforce location of semicolons // https://eslint.org/docs/rules/semi-style 'semi-style': ['error', 'last'], // requires object keys to be sorted 'sort-keys': ['off', 'asc', { caseSensitive: false, natural: true }], // sort variables within the same declaration block 'sort-vars': 'off', // require or disallow space before blocks 'space-before-blocks': 'error', // require or disallow space before function opening parenthesis // https://eslint.org/docs/rules/space-before-function-paren 'space-before-function-paren': ['error', { anonymous: 'always', named: 'never', asyncArrow: 'always' }], // require or disallow spaces inside parentheses 'space-in-parens': ['error', 'never'], // require spaces around operators 'space-infix-ops': 'error', // Require or disallow spaces before/after unary operators // https://eslint.org/docs/rules/space-unary-ops 'space-unary-ops': ['error', { words: true, nonwords: false, overrides: { }, }], // require or disallow a space immediately following the // or /* in a comment // https://eslint.org/docs/rules/spaced-comment 'spaced-comment': ['error', 'always', { line: { exceptions: ['-', '+'], markers: ['=', '!', '/'], // space here to support sprockets directives, slash for TS /// comments }, block: { exceptions: ['-', '+'], markers: ['=', '!', ':', '::'], // space here to support sprockets directives and flow comment types balanced: true, } }], // Enforce spacing around colons of switch statements // https://eslint.org/docs/rules/switch-colon-spacing 'switch-colon-spacing': ['error', { after: true, before: false }], // Require or disallow spacing between template tags and their literals // https://eslint.org/docs/rules/template-tag-spacing 'template-tag-spacing': ['error', 'never'], // require or disallow the Unicode Byte Order Mark // https://eslint.org/docs/rules/unicode-bom 'unicode-bom': ['error', 'never'], // require regex literals to be wrapped in parentheses 'wrap-regex': 'off' } };
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb-base/rules/imports.js
packages/eslint-config-airbnb-base/rules/imports.js
module.exports = { env: { es6: true }, parserOptions: { ecmaVersion: 6, sourceType: 'module' }, plugins: [ 'import' ], settings: { 'import/resolver': { node: { extensions: ['.mjs', '.js', '.json'] } }, 'import/extensions': [ '.js', '.mjs', '.jsx', ], 'import/core-modules': [ ], 'import/ignore': [ 'node_modules', '\\.(coffee|scss|css|less|hbs|svg|json)$', ], }, rules: { // Static analysis: // ensure imports point to files/modules that can be resolved // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-unresolved.md 'import/no-unresolved': ['error', { commonjs: true, caseSensitive: true }], // ensure named imports coupled with named exports // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/named.md#when-not-to-use-it 'import/named': 'error', // ensure default import coupled with default export // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/default.md#when-not-to-use-it 'import/default': 'off', // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/namespace.md 'import/namespace': 'off', // Helpful warnings: // disallow invalid exports, e.g. multiple defaults // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/export.md 'import/export': 'error', // do not allow a default import name to match a named export // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-named-as-default.md 'import/no-named-as-default': 'error', // warn on accessing default export property names that are also named exports // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-named-as-default-member.md 'import/no-named-as-default-member': 'error', // disallow use of jsdoc-marked-deprecated imports // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-deprecated.md 'import/no-deprecated': 'off', // Forbid the use of extraneous packages // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-extraneous-dependencies.md // paths are treated both as absolute paths, and relative to process.cwd() 'import/no-extraneous-dependencies': ['error', { devDependencies: [ 'test/**', // tape, common npm pattern 'tests/**', // also common npm pattern 'spec/**', // mocha, rspec-like pattern '**/__tests__/**', // jest pattern '**/__mocks__/**', // jest pattern 'test.{js,jsx}', // repos with a single test file 'test-*.{js,jsx}', // repos with multiple top-level test files '**/*{.,_}{test,spec}.{js,jsx}', // tests where the extension or filename suffix denotes that it is a test '**/jest.config.js', // jest config '**/jest.setup.js', // jest setup '**/vue.config.js', // vue-cli config '**/webpack.config.js', // webpack config '**/webpack.config.*.js', // webpack config '**/rollup.config.js', // rollup config '**/rollup.config.*.js', // rollup config '**/gulpfile.js', // gulp config '**/gulpfile.*.js', // gulp config '**/Gruntfile{,.js}', // grunt config '**/protractor.conf.js', // protractor config '**/protractor.conf.*.js', // protractor config '**/karma.conf.js', // karma config '**/.eslintrc.js' // eslint config ], optionalDependencies: false, }], // Forbid mutable exports // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-mutable-exports.md 'import/no-mutable-exports': 'error', // Module systems: // disallow require() // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-commonjs.md 'import/no-commonjs': 'off', // disallow AMD require/define // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-amd.md 'import/no-amd': 'error', // No Node.js builtin modules // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-nodejs-modules.md // TODO: enable? 'import/no-nodejs-modules': 'off', // Style guide: // disallow non-import statements appearing before import statements // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/first.md 'import/first': 'error', // disallow non-import statements appearing before import statements // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/imports-first.md // deprecated: use `import/first` 'import/imports-first': 'off', // disallow duplicate imports // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-duplicates.md 'import/no-duplicates': 'error', // disallow namespace imports // TODO: enable? // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-namespace.md 'import/no-namespace': 'off', // Ensure consistent use of file extension within the import path // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/extensions.md 'import/extensions': ['error', 'ignorePackages', { js: 'never', mjs: 'never', jsx: 'never', }], // ensure absolute imports are above relative imports and that unassigned imports are ignored // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/order.md // TODO: enforce a stricter convention in module import order? 'import/order': ['error', { groups: [['builtin', 'external', 'internal']] }], // Require a newline after the last import/require in a group // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/newline-after-import.md 'import/newline-after-import': 'error', // Require modules with a single export to use a default export // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/prefer-default-export.md 'import/prefer-default-export': 'error', // Restrict which files can be imported in a given folder // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-restricted-paths.md 'import/no-restricted-paths': 'off', // Forbid modules to have too many dependencies // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/max-dependencies.md 'import/max-dependencies': ['off', { max: 10 }], // Forbid import of modules using absolute paths // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-absolute-path.md 'import/no-absolute-path': 'error', // Forbid require() calls with expressions // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-dynamic-require.md 'import/no-dynamic-require': 'error', // prevent importing the submodules of other modules // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-internal-modules.md 'import/no-internal-modules': ['off', { allow: [], }], // Warn if a module could be mistakenly parsed as a script by a consumer // leveraging Unambiguous JavaScript Grammar // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/unambiguous.md // this should not be enabled until this proposal has at least been *presented* to TC39. // At the moment, it's not a thing. 'import/unambiguous': 'off', // Forbid Webpack loader syntax in imports // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-webpack-loader-syntax.md 'import/no-webpack-loader-syntax': 'error', // Prevent unassigned imports // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-unassigned-import.md // importing for side effects is perfectly acceptable, if you need side effects. 'import/no-unassigned-import': 'off', // Prevent importing the default as if it were named // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-named-default.md 'import/no-named-default': 'error', // Reports if a module's default export is unnamed // https://github.com/import-js/eslint-plugin-import/blob/d9b712ac7fd1fddc391f7b234827925c160d956f/docs/rules/no-anonymous-default-export.md 'import/no-anonymous-default-export': ['off', { allowArray: false, allowArrowFunction: false, allowAnonymousClass: false, allowAnonymousFunction: false, allowLiteral: false, allowObject: false, }], // This rule enforces that all exports are declared at the bottom of the file. // https://github.com/import-js/eslint-plugin-import/blob/98acd6afd04dcb6920b81330114e146dc8532ea4/docs/rules/exports-last.md // TODO: enable? 'import/exports-last': 'off', // Reports when named exports are not grouped together in a single export declaration // or when multiple assignments to CommonJS module.exports or exports object are present // in a single file. // https://github.com/import-js/eslint-plugin-import/blob/44a038c06487964394b1e15b64f3bd34e5d40cde/docs/rules/group-exports.md 'import/group-exports': 'off', // forbid default exports. this is a terrible rule, do not use it. // https://github.com/import-js/eslint-plugin-import/blob/44a038c06487964394b1e15b64f3bd34e5d40cde/docs/rules/no-default-export.md 'import/no-default-export': 'off', // Prohibit named exports. this is a terrible rule, do not use it. // https://github.com/import-js/eslint-plugin-import/blob/1ec80fa35fa1819e2d35a70e68fb6a149fb57c5e/docs/rules/no-named-export.md 'import/no-named-export': 'off', // Forbid a module from importing itself // https://github.com/import-js/eslint-plugin-import/blob/44a038c06487964394b1e15b64f3bd34e5d40cde/docs/rules/no-self-import.md 'import/no-self-import': 'error', // Forbid cyclical dependencies between modules // https://github.com/import-js/eslint-plugin-import/blob/d81f48a2506182738409805f5272eff4d77c9348/docs/rules/no-cycle.md 'import/no-cycle': ['error', { maxDepth: '∞' }], // Ensures that there are no useless path segments // https://github.com/import-js/eslint-plugin-import/blob/ebafcbf59ec9f653b2ac2a0156ca3bcba0a7cf57/docs/rules/no-useless-path-segments.md 'import/no-useless-path-segments': ['error', { commonjs: true }], // dynamic imports require a leading comment with a webpackChunkName // https://github.com/import-js/eslint-plugin-import/blob/ebafcbf59ec9f653b2ac2a0156ca3bcba0a7cf57/docs/rules/dynamic-import-chunkname.md 'import/dynamic-import-chunkname': ['off', { importFunctions: [], webpackChunknameFormat: '[0-9a-zA-Z-_/.]+', }], // Use this rule to prevent imports to folders in relative parent paths. // https://github.com/import-js/eslint-plugin-import/blob/c34f14f67f077acd5a61b3da9c0b0de298d20059/docs/rules/no-relative-parent-imports.md 'import/no-relative-parent-imports': 'off', // Reports modules without any exports, or with unused exports // https://github.com/import-js/eslint-plugin-import/blob/f63dd261809de6883b13b6b5b960e6d7f42a7813/docs/rules/no-unused-modules.md // TODO: enable once it supports CJS 'import/no-unused-modules': ['off', { ignoreExports: [], missingExports: true, unusedExports: true, }], // Reports the use of import declarations with CommonJS exports in any module except for the main module. // https://github.com/import-js/eslint-plugin-import/blob/1012eb951767279ce3b540a4ec4f29236104bb5b/docs/rules/no-import-module-exports.md 'import/no-import-module-exports': ['error', { exceptions: [], }], // Use this rule to prevent importing packages through relative paths. // https://github.com/import-js/eslint-plugin-import/blob/1012eb951767279ce3b540a4ec4f29236104bb5b/docs/rules/no-relative-packages.md 'import/no-relative-packages': 'error', // enforce a consistent style for type specifiers (inline or top-level) // https://github.com/import-js/eslint-plugin-import/blob/d5fc8b670dc8e6903dbb7b0894452f60c03089f5/docs/rules/consistent-type-specifier-style.md // TODO, semver-major: enable (just in case) 'import/consistent-type-specifier-style': ['off', 'prefer-inline'], // Reports the use of empty named import blocks. // https://github.com/import-js/eslint-plugin-import/blob/d5fc8b670dc8e6903dbb7b0894452f60c03089f5/docs/rules/no-empty-named-blocks.md // TODO, semver-minor: enable 'import/no-empty-named-blocks': 'off', }, };
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb-base/rules/es6.js
packages/eslint-config-airbnb-base/rules/es6.js
module.exports = { env: { es6: true }, parserOptions: { ecmaVersion: 6, sourceType: 'module', ecmaFeatures: { generators: false, objectLiteralDuplicateProperties: false } }, rules: { // enforces no braces where they can be omitted // https://eslint.org/docs/rules/arrow-body-style // TODO: enable requireReturnForObjectLiteral? 'arrow-body-style': ['error', 'as-needed', { requireReturnForObjectLiteral: false, }], // require parens in arrow function arguments // https://eslint.org/docs/rules/arrow-parens 'arrow-parens': ['error', 'always'], // require space before/after arrow function's arrow // https://eslint.org/docs/rules/arrow-spacing 'arrow-spacing': ['error', { before: true, after: true }], // verify super() callings in constructors 'constructor-super': 'error', // enforce the spacing around the * in generator functions // https://eslint.org/docs/rules/generator-star-spacing 'generator-star-spacing': ['error', { before: false, after: true }], // disallow modifying variables of class declarations // https://eslint.org/docs/rules/no-class-assign 'no-class-assign': 'error', // disallow arrow functions where they could be confused with comparisons // https://eslint.org/docs/rules/no-confusing-arrow 'no-confusing-arrow': ['error', { allowParens: true, }], // disallow modifying variables that are declared using const 'no-const-assign': 'error', // disallow duplicate class members // https://eslint.org/docs/rules/no-dupe-class-members 'no-dupe-class-members': 'error', // disallow importing from the same path more than once // https://eslint.org/docs/rules/no-duplicate-imports // replaced by https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-duplicates.md 'no-duplicate-imports': 'off', // disallow symbol constructor // https://eslint.org/docs/rules/no-new-symbol 'no-new-symbol': 'error', // Disallow specified names in exports // https://eslint.org/docs/rules/no-restricted-exports 'no-restricted-exports': ['error', { restrictedNamedExports: [ 'default', // use `export default` to provide a default export 'then', // this will cause tons of confusion when your module is dynamically `import()`ed, and will break in most node ESM versions ], }], // disallow specific imports // https://eslint.org/docs/rules/no-restricted-imports 'no-restricted-imports': ['off', { paths: [], patterns: [] }], // disallow to use this/super before super() calling in constructors. // https://eslint.org/docs/rules/no-this-before-super 'no-this-before-super': 'error', // disallow useless computed property keys // https://eslint.org/docs/rules/no-useless-computed-key 'no-useless-computed-key': 'error', // disallow unnecessary constructor // https://eslint.org/docs/rules/no-useless-constructor 'no-useless-constructor': 'error', // disallow renaming import, export, and destructured assignments to the same name // https://eslint.org/docs/rules/no-useless-rename 'no-useless-rename': ['error', { ignoreDestructuring: false, ignoreImport: false, ignoreExport: false, }], // require let or const instead of var 'no-var': 'error', // require method and property shorthand syntax for object literals // https://eslint.org/docs/rules/object-shorthand 'object-shorthand': ['error', 'always', { ignoreConstructors: false, avoidQuotes: true, }], // suggest using arrow functions as callbacks 'prefer-arrow-callback': ['error', { allowNamedFunctions: false, allowUnboundThis: true, }], // suggest using of const declaration for variables that are never modified after declared 'prefer-const': ['error', { destructuring: 'any', ignoreReadBeforeAssign: true, }], // Prefer destructuring from arrays and objects // https://eslint.org/docs/rules/prefer-destructuring 'prefer-destructuring': ['error', { VariableDeclarator: { array: false, object: true, }, AssignmentExpression: { array: true, object: false, }, }, { enforceForRenamedProperties: false, }], // disallow parseInt() in favor of binary, octal, and hexadecimal literals // https://eslint.org/docs/rules/prefer-numeric-literals 'prefer-numeric-literals': 'error', // suggest using Reflect methods where applicable // https://eslint.org/docs/rules/prefer-reflect 'prefer-reflect': 'off', // use rest parameters instead of arguments // https://eslint.org/docs/rules/prefer-rest-params 'prefer-rest-params': 'error', // suggest using the spread syntax instead of .apply() // https://eslint.org/docs/rules/prefer-spread 'prefer-spread': 'error', // suggest using template literals instead of string concatenation // https://eslint.org/docs/rules/prefer-template 'prefer-template': 'error', // disallow generator functions that do not have yield // https://eslint.org/docs/rules/require-yield 'require-yield': 'error', // enforce spacing between object rest-spread // https://eslint.org/docs/rules/rest-spread-spacing 'rest-spread-spacing': ['error', 'never'], // import sorting // https://eslint.org/docs/rules/sort-imports 'sort-imports': ['off', { ignoreCase: false, ignoreDeclarationSort: false, ignoreMemberSort: false, memberSyntaxSortOrder: ['none', 'all', 'multiple', 'single'], }], // require a Symbol description // https://eslint.org/docs/rules/symbol-description 'symbol-description': 'error', // enforce usage of spacing in template strings // https://eslint.org/docs/rules/template-curly-spacing 'template-curly-spacing': 'error', // enforce spacing around the * in yield* expressions // https://eslint.org/docs/rules/yield-star-spacing 'yield-star-spacing': ['error', 'after'] } };
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb-base/rules/node.js
packages/eslint-config-airbnb-base/rules/node.js
module.exports = { env: { node: true }, rules: { // enforce return after a callback 'callback-return': 'off', // require all requires be top-level // https://eslint.org/docs/rules/global-require 'global-require': 'error', // enforces error handling in callbacks (node environment) 'handle-callback-err': 'off', // disallow use of the Buffer() constructor // https://eslint.org/docs/rules/no-buffer-constructor 'no-buffer-constructor': 'error', // disallow mixing regular variable and require declarations 'no-mixed-requires': ['off', false], // disallow use of new operator with the require function 'no-new-require': 'error', // disallow string concatenation with __dirname and __filename // https://eslint.org/docs/rules/no-path-concat 'no-path-concat': 'error', // disallow use of process.env 'no-process-env': 'off', // disallow process.exit() 'no-process-exit': 'off', // restrict usage of specified node modules 'no-restricted-modules': 'off', // disallow use of synchronous methods (off by default) 'no-sync': 'off', } };
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb-base/rules/errors.js
packages/eslint-config-airbnb-base/rules/errors.js
module.exports = { rules: { // Enforce “for” loop update clause moving the counter in the right direction // https://eslint.org/docs/rules/for-direction 'for-direction': 'error', // Enforces that a return statement is present in property getters // https://eslint.org/docs/rules/getter-return 'getter-return': ['error', { allowImplicit: true }], // disallow using an async function as a Promise executor // https://eslint.org/docs/rules/no-async-promise-executor 'no-async-promise-executor': 'error', // Disallow await inside of loops // https://eslint.org/docs/rules/no-await-in-loop 'no-await-in-loop': 'error', // Disallow comparisons to negative zero // https://eslint.org/docs/rules/no-compare-neg-zero 'no-compare-neg-zero': 'error', // disallow assignment in conditional expressions 'no-cond-assign': ['error', 'always'], // disallow use of console 'no-console': 'warn', // Disallows expressions where the operation doesn't affect the value // https://eslint.org/docs/rules/no-constant-binary-expression // TODO: semver-major, enable 'no-constant-binary-expression': 'off', // disallow use of constant expressions in conditions 'no-constant-condition': 'warn', // disallow control characters in regular expressions 'no-control-regex': 'error', // disallow use of debugger 'no-debugger': 'error', // disallow duplicate arguments in functions 'no-dupe-args': 'error', // Disallow duplicate conditions in if-else-if chains // https://eslint.org/docs/rules/no-dupe-else-if 'no-dupe-else-if': 'error', // disallow duplicate keys when creating object literals 'no-dupe-keys': 'error', // disallow a duplicate case label. 'no-duplicate-case': 'error', // disallow empty statements 'no-empty': 'error', // disallow the use of empty character classes in regular expressions 'no-empty-character-class': 'error', // disallow assigning to the exception in a catch block 'no-ex-assign': 'error', // disallow double-negation boolean casts in a boolean context // https://eslint.org/docs/rules/no-extra-boolean-cast 'no-extra-boolean-cast': 'error', // disallow unnecessary parentheses // https://eslint.org/docs/rules/no-extra-parens 'no-extra-parens': ['off', 'all', { conditionalAssign: true, nestedBinaryExpressions: false, returnAssign: false, ignoreJSX: 'all', // delegate to eslint-plugin-react enforceForArrowConditionals: false, }], // disallow unnecessary semicolons 'no-extra-semi': 'error', // disallow overwriting functions written as function declarations 'no-func-assign': 'error', // https://eslint.org/docs/rules/no-import-assign 'no-import-assign': 'error', // disallow function or variable declarations in nested blocks 'no-inner-declarations': 'error', // disallow invalid regular expression strings in the RegExp constructor 'no-invalid-regexp': 'error', // disallow irregular whitespace outside of strings and comments 'no-irregular-whitespace': 'error', // Disallow Number Literals That Lose Precision // https://eslint.org/docs/rules/no-loss-of-precision 'no-loss-of-precision': 'error', // Disallow characters which are made with multiple code points in character class syntax // https://eslint.org/docs/rules/no-misleading-character-class 'no-misleading-character-class': 'error', // disallow the use of object properties of the global object (Math and JSON) as functions 'no-obj-calls': 'error', // Disallow new operators with global non-constructor functions // https://eslint.org/docs/latest/rules/no-new-native-nonconstructor // TODO: semver-major, enable 'no-new-native-nonconstructor': 'off', // Disallow returning values from Promise executor functions // https://eslint.org/docs/rules/no-promise-executor-return 'no-promise-executor-return': 'error', // disallow use of Object.prototypes builtins directly // https://eslint.org/docs/rules/no-prototype-builtins 'no-prototype-builtins': 'error', // disallow multiple spaces in a regular expression literal 'no-regex-spaces': 'error', // Disallow returning values from setters // https://eslint.org/docs/rules/no-setter-return 'no-setter-return': 'error', // disallow sparse arrays 'no-sparse-arrays': 'error', // Disallow template literal placeholder syntax in regular strings // https://eslint.org/docs/rules/no-template-curly-in-string 'no-template-curly-in-string': 'error', // Avoid code that looks like two expressions but is actually one // https://eslint.org/docs/rules/no-unexpected-multiline 'no-unexpected-multiline': 'error', // disallow unreachable statements after a return, throw, continue, or break statement 'no-unreachable': 'error', // Disallow loops with a body that allows only one iteration // https://eslint.org/docs/rules/no-unreachable-loop 'no-unreachable-loop': ['error', { ignore: [], // WhileStatement, DoWhileStatement, ForStatement, ForInStatement, ForOfStatement }], // disallow return/throw/break/continue inside finally blocks // https://eslint.org/docs/rules/no-unsafe-finally 'no-unsafe-finally': 'error', // disallow negating the left operand of relational operators // https://eslint.org/docs/rules/no-unsafe-negation 'no-unsafe-negation': 'error', // disallow use of optional chaining in contexts where the undefined value is not allowed // https://eslint.org/docs/rules/no-unsafe-optional-chaining 'no-unsafe-optional-chaining': ['error', { disallowArithmeticOperators: true }], // Disallow Unused Private Class Members // https://eslint.org/docs/rules/no-unused-private-class-members // TODO: enable once eslint 7 is dropped (which is semver-major) 'no-unused-private-class-members': 'off', // Disallow useless backreferences in regular expressions // https://eslint.org/docs/rules/no-useless-backreference 'no-useless-backreference': 'error', // disallow negation of the left operand of an in expression // deprecated in favor of no-unsafe-negation 'no-negated-in-lhs': 'off', // Disallow assignments that can lead to race conditions due to usage of await or yield // https://eslint.org/docs/rules/require-atomic-updates // note: not enabled because it is very buggy 'require-atomic-updates': 'off', // disallow comparisons with the value NaN 'use-isnan': 'error', // ensure JSDoc comments are valid // https://eslint.org/docs/rules/valid-jsdoc 'valid-jsdoc': 'off', // ensure that the results of typeof are compared against a valid string // https://eslint.org/docs/rules/valid-typeof 'valid-typeof': ['error', { requireStringLiterals: true }], } };
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb-base/test/test-base.js
packages/eslint-config-airbnb-base/test/test-base.js
import fs from 'fs'; import path from 'path'; import test from 'tape'; import index from '..'; const files = { ...{ index } }; // object spread is to test parsing const rulesDir = path.join(__dirname, '../rules'); fs.readdirSync(rulesDir).forEach((name) => { // eslint-disable-next-line import/no-dynamic-require files[name] = require(path.join(rulesDir, name)); // eslint-disable-line global-require }); Object.keys(files).forEach(( name, // trailing function comma is to test parsing ) => { const config = files[name]; test(`${name}: does not reference react`, (t) => { t.plan(2); // scan plugins for react and fail if it is found const hasReactPlugin = Object.prototype.hasOwnProperty.call(config, 'plugins') && config.plugins.indexOf('react') !== -1; t.notOk(hasReactPlugin, 'there is no react plugin'); // scan rules for react/ and fail if any exist const reactRuleIds = Object.keys(config.rules) .filter((ruleId) => ruleId.indexOf('react/') === 0); t.deepEquals(reactRuleIds, [], 'there are no react/ rules'); }); });
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
airbnb/javascript
https://github.com/airbnb/javascript/blob/0e2ef178a26ba9ac3495402a182891ad8096d3a0/packages/eslint-config-airbnb-base/test/requires.js
packages/eslint-config-airbnb-base/test/requires.js
/* eslint strict: 0, global-require: 0 */ 'use strict'; const test = require('tape'); test('all entry points parse', (t) => { t.doesNotThrow(() => require('..'), 'index does not throw'); t.doesNotThrow(() => require('../legacy'), 'legacy does not throw'); t.doesNotThrow(() => require('../whitespace'), 'whitespace does not throw'); t.end(); });
javascript
MIT
0e2ef178a26ba9ac3495402a182891ad8096d3a0
2026-01-04T14:56:49.223287Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/express.js
express.js
import "dotenv/config"; import statsCard from "./api/index.js"; import repoCard from "./api/pin.js"; import langCard from "./api/top-langs.js"; import wakatimeCard from "./api/wakatime.js"; import gistCard from "./api/gist.js"; import express from "express"; const app = express(); const router = express.Router(); router.get("/", statsCard); router.get("/pin", repoCard); router.get("/top-langs", langCard); router.get("/wakatime", wakatimeCard); router.get("/gist", gistCard); app.use("/api", router); const port = process.env.PORT || process.env.port || 9000; app.listen(port, "0.0.0.0", () => { console.log(`Server running on port ${port}`); });
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/jest.e2e.config.js
jest.e2e.config.js
export default { clearMocks: true, transform: {}, testEnvironment: "node", coverageProvider: "v8", testMatch: ["<rootDir>/tests/e2e/**/*.test.js"], };
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/jest.bench.config.js
jest.bench.config.js
export default { clearMocks: true, transform: {}, testEnvironment: "jsdom", coverageProvider: "v8", testPathIgnorePatterns: ["<rootDir>/node_modules/", "<rootDir>/tests/e2e/"], modulePathIgnorePatterns: ["<rootDir>/node_modules/", "<rootDir>/tests/e2e/"], coveragePathIgnorePatterns: [ "<rootDir>/node_modules/", "<rootDir>/tests/e2e/", ], testRegex: "(\\.bench)\\.(ts|tsx|js)$", };
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/jest.config.js
jest.config.js
export default { clearMocks: true, transform: {}, testEnvironment: "jsdom", coverageProvider: "v8", testPathIgnorePatterns: ["<rootDir>/node_modules/", "<rootDir>/tests/e2e/"], modulePathIgnorePatterns: ["<rootDir>/node_modules/", "<rootDir>/tests/e2e/"], coveragePathIgnorePatterns: [ "<rootDir>/node_modules/", "<rootDir>/tests/E2E/", ], };
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/scripts/generate-theme-doc.js
scripts/generate-theme-doc.js
import fs from "fs"; import { themes } from "../themes/index.js"; const TARGET_FILE = "./themes/README.md"; const REPO_CARD_LINKS_FLAG = "<!-- REPO_CARD_LINKS -->"; const STAT_CARD_LINKS_FLAG = "<!-- STATS_CARD_LINKS -->"; const STAT_CARD_TABLE_FLAG = "<!-- STATS_CARD_TABLE -->"; const REPO_CARD_TABLE_FLAG = "<!-- REPO_CARD_TABLE -->"; const THEME_TEMPLATE = `## Available Themes <!-- DO NOT EDIT THIS FILE DIRECTLY --> With inbuilt themes, you can customize the look of the card without doing any manual customization. Use \`?theme=THEME_NAME\` parameter like so: \`\`\`md ![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra&theme=dark&show_icons=true) \`\`\` ## Stats > These themes work with all five of our cards: Stats Card, Repo Card, Gist Card, Top Languages Card, and WakaTime Card. | | | | | :--: | :--: | :--: | ${STAT_CARD_TABLE_FLAG} ## Repo Card > These themes work with all five of our cards: Stats Card, Repo Card, Gist Card, Top Languages Card, and WakaTime Card. | | | | | :--: | :--: | :--: | ${REPO_CARD_TABLE_FLAG} ${STAT_CARD_LINKS_FLAG} ${REPO_CARD_LINKS_FLAG} `; const createRepoMdLink = (theme) => { return `\n[${theme}_repo]: https://github-readme-stats.vercel.app/api/pin/?username=anuraghazra&repo=github-readme-stats&cache_seconds=86400&theme=${theme}`; }; const createStatMdLink = (theme) => { return `\n[${theme}]: https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&hide=contribs,prs&cache_seconds=86400&theme=${theme}`; }; const generateLinks = (fn) => { return Object.keys(themes) .map((name) => fn(name)) .join(""); }; const createTableItem = ({ link, label, isRepoCard }) => { if (!link || !label) { return ""; } return `\`${label}\` ![${link}][${link}${isRepoCard ? "_repo" : ""}]`; }; const generateTable = ({ isRepoCard }) => { const rows = []; const themesFiltered = Object.keys(themes).filter( (name) => name !== (isRepoCard ? "default" : "default_repocard"), ); for (let i = 0; i < themesFiltered.length; i += 3) { const one = themesFiltered[i]; const two = themesFiltered[i + 1]; const three = themesFiltered[i + 2]; let tableItem1 = createTableItem({ link: one, label: one, isRepoCard }); let tableItem2 = createTableItem({ link: two, label: two, isRepoCard }); let tableItem3 = createTableItem({ link: three, label: three, isRepoCard }); rows.push(`| ${tableItem1} | ${tableItem2} | ${tableItem3} |`); } return rows.join("\n"); }; const buildReadme = () => { return THEME_TEMPLATE.split("\n") .map((line) => { if (line.includes(REPO_CARD_LINKS_FLAG)) { return generateLinks(createRepoMdLink); } if (line.includes(STAT_CARD_LINKS_FLAG)) { return generateLinks(createStatMdLink); } if (line.includes(REPO_CARD_TABLE_FLAG)) { return generateTable({ isRepoCard: true }); } if (line.includes(STAT_CARD_TABLE_FLAG)) { return generateTable({ isRepoCard: false }); } return line; }) .join("\n"); }; fs.writeFileSync(TARGET_FILE, buildReadme());
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/scripts/close-stale-theme-prs.js
scripts/close-stale-theme-prs.js
/** * @file Script that can be used to close stale theme PRs that have a `invalid` label. */ import * as dotenv from "dotenv"; dotenv.config(); import { debug, setFailed } from "@actions/core"; import github from "@actions/github"; import { RequestError } from "@octokit/request-error"; import { getGithubToken, getRepoInfo } from "./helpers.js"; const CLOSING_COMMENT = ` \rThis theme PR has been automatically closed due to inactivity. Please reopen it if you want to continue working on it.\ \rThank you for your contributions. `; const REVIEWER = "github-actions[bot]"; /** * Retrieve the review user. * @returns {string} review user. */ const getReviewer = () => { return process.env.REVIEWER ? process.env.REVIEWER : REVIEWER; }; /** * Fetch open PRs from a given repository. * * @param {module:@actions/github.Octokit} octokit The octokit client. * @param {string} user The user name of the repository owner. * @param {string} repo The name of the repository. * @param {string} reviewer The reviewer to filter by. * @returns {Promise<Object[]>} The open PRs. */ export const fetchOpenPRs = async (octokit, user, repo, reviewer) => { const openPRs = []; let hasNextPage = true; let endCursor; while (hasNextPage) { try { const { repository } = await octokit.graphql( ` { repository(owner: "${user}", name: "${repo}") { open_prs: pullRequests(${ endCursor ? `after: "${endCursor}", ` : "" } first: 100, states: OPEN, orderBy: {field: CREATED_AT, direction: DESC}) { nodes { number commits(last:1){ nodes{ commit{ pushedDate } } } labels(first: 100, orderBy:{field: CREATED_AT, direction: DESC}) { nodes { name } } reviews(first: 100, states: CHANGES_REQUESTED, author: "${reviewer}") { nodes { submittedAt } } } pageInfo { endCursor hasNextPage } } } } `, ); openPRs.push(...repository.open_prs.nodes); hasNextPage = repository.open_prs.pageInfo.hasNextPage; endCursor = repository.open_prs.pageInfo.endCursor; } catch (error) { if (error instanceof RequestError) { setFailed(`Could not retrieve top PRs using GraphQl: ${error.message}`); } throw error; } } return openPRs; }; /** * Retrieve pull requests that have a given label. * * @param {Object[]} pulls The pull requests to check. * @param {string} label The label to check for. * @returns {Object[]} The pull requests that have the given label. */ export const pullsWithLabel = (pulls, label) => { return pulls.filter((pr) => { return pr.labels.nodes.some((lab) => lab.name === label); }); }; /** * Check if PR is stale. Meaning that it hasn't been updated in a given time. * * @param {Object} pullRequest request object. * @param {number} staleDays number of days. * @returns {boolean} indicating if PR is stale. */ const isStale = (pullRequest, staleDays) => { const lastCommitDate = new Date( pullRequest.commits.nodes[0].commit.pushedDate, ); if (pullRequest.reviews.nodes[0]) { const lastReviewDate = new Date( pullRequest.reviews.nodes.sort((a, b) => (a < b ? 1 : -1))[0].submittedAt, ); const lastUpdateDate = lastCommitDate >= lastReviewDate ? lastCommitDate : lastReviewDate; const now = new Date(); return (now - lastUpdateDate) / (1000 * 60 * 60 * 24) >= staleDays; } else { return false; } }; /** * Main function. * * @returns {Promise<void>} A promise. */ const run = async () => { try { // Create octokit client. const dryRun = process.env.DRY_RUN === "true" || false; const staleDays = process.env.STALE_DAYS || 20; debug("Creating octokit client..."); const octokit = github.getOctokit(getGithubToken()); const { owner, repo } = getRepoInfo(github.context); const reviewer = getReviewer(); // Retrieve all theme pull requests. debug("Retrieving all theme pull requests..."); const prs = await fetchOpenPRs(octokit, owner, repo, reviewer); const themePRs = pullsWithLabel(prs, "themes"); const invalidThemePRs = pullsWithLabel(themePRs, "invalid"); debug("Retrieving stale theme PRs..."); const staleThemePRs = invalidThemePRs.filter((pr) => isStale(pr, staleDays), ); const staleThemePRsNumbers = staleThemePRs.map((pr) => pr.number); debug(`Found ${staleThemePRs.length} stale theme PRs`); // Loop through all stale invalid theme pull requests and close them. for (const prNumber of staleThemePRsNumbers) { debug(`Closing #${prNumber} because it is stale...`); if (dryRun) { debug("Dry run enabled, skipping..."); } else { await octokit.rest.issues.createComment({ owner, repo, issue_number: prNumber, body: CLOSING_COMMENT, }); await octokit.rest.pulls.update({ owner, repo, pull_number: prNumber, state: "closed", }); } } } catch (error) { setFailed(error.message); } }; run();
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/scripts/preview-theme.js
scripts/preview-theme.js
/** * @file This script is used to preview the theme on theme PRs. */ import * as dotenv from "dotenv"; dotenv.config(); import { debug, setFailed } from "@actions/core"; import github from "@actions/github"; import ColorContrastChecker from "color-contrast-checker"; import { info } from "console"; import Hjson from "hjson"; import snakeCase from "lodash.snakecase"; import parse from "parse-diff"; import { inspect } from "util"; import { isValidHexColor, isValidGradient } from "../src/common/color.js"; import { themes } from "../themes/index.js"; import { getGithubToken, getRepoInfo } from "./helpers.js"; const COMMENTER = "github-actions[bot]"; const COMMENT_TITLE = "Automated Theme Preview"; const THEME_PR_FAIL_TEXT = ":x: Theme PR does not adhere to our guidelines."; const THEME_PR_SUCCESS_TEXT = ":heavy_check_mark: Theme PR does adhere to our guidelines."; const FAIL_TEXT = ` \rUnfortunately, your theme PR contains an error or does not adhere to our [theme guidelines](https://github.com/anuraghazra/github-readme-stats/blob/master/CONTRIBUTING.md#themes-contribution). Please fix the issues below, and we will review your\ \r PR again. This pull request will **automatically close in 20 days** if no changes are made. After this time, you must re-open the PR for it to be reviewed. `; const THEME_CONTRIB_GUIDELINES = ` \rHi, thanks for the theme contribution. Please read our theme [contribution guidelines](https://github.com/anuraghazra/github-readme-stats/blob/master/CONTRIBUTING.md#themes-contribution). \r> [!WARNING]\ \r> Keep in mind that we already have a vast collection of different themes. To keep their number manageable, we began to add only themes supported by the community. Your pull request with theme addition will be merged once we get enough positive feedback from the community in the form of thumbs up :+1: emojis (see [#1935](https://github.com/anuraghazra/github-readme-stats/issues/1935#top-themes-prs)). We expect to see at least 10-15 thumbs up before making a decision to merge your pull request into the master branch. Remember that you can also support themes of other contributors that you liked to speed up their merge. \r> [!WARNING]\ \r> Please do not submit a pull request with a batch of themes, since it will be hard to judge how the community will react to each of them. We will only merge one theme per pull request. If you have several themes, please submit a separate pull request for each of them. Situations when you have several versions of the same theme (e.g. light and dark) are an exception to this rule. \r> [!NOTE]\ \r> Also, note that if this theme is exclusively for your personal use, then instead of adding it to our theme collection, you can use card [customization options](https://github.com/anuraghazra/github-readme-stats#customization). `; const COLOR_PROPS = { title_color: 6, icon_color: 6, text_color: 6, bg_color: 23, border_color: 6, }; const ACCEPTED_COLOR_PROPS = Object.keys(COLOR_PROPS); const REQUIRED_COLOR_PROPS = ACCEPTED_COLOR_PROPS.slice(0, 4); const INVALID_REVIEW_COMMENT = (commentUrl) => `Some themes are invalid. See the [Automated Theme Preview](${commentUrl}) comment above for more information.`; var OCTOKIT; var OWNER; var REPO; var PULL_REQUEST_ID; /** * Incorrect JSON format error. * @extends Error * @param {string} message Error message. * @returns {Error} IncorrectJsonFormatError. */ class IncorrectJsonFormatError extends Error { /** * Constructor. * * @param {string} message Error message. */ constructor(message) { super(message); this.name = "IncorrectJsonFormatError"; } } /** * Retrieve PR number from the event payload. * * @returns {number} PR number. */ const getPrNumber = () => { if (process.env.MOCK_PR_NUMBER) { return process.env.MOCK_PR_NUMBER; // For testing purposes. } const pullRequest = github.context.payload.pull_request; if (!pullRequest) { throw Error("Could not get pull request number from context"); } return pullRequest.number; }; /** * Retrieve the commenting user. * @returns {string} Commenting user. */ const getCommenter = () => { return process.env.COMMENTER ? process.env.COMMENTER : COMMENTER; }; /** * Returns whether the comment is a preview comment. * * @param {Object} inputs Action inputs. * @param {Object} comment Comment object. * @returns {boolean} Whether the comment is a preview comment. */ const isPreviewComment = (inputs, comment) => { return ( (inputs.commentAuthor && comment.user ? comment.user.login === inputs.commentAuthor : true) && (inputs.bodyIncludes && comment.body ? comment.body.includes(inputs.bodyIncludes) : true) ); }; /** * Find the preview theme comment. * * @param {Object} octokit Octokit instance. * @param {number} issueNumber Issue number. * @param {string} owner Owner of the repository. * @param {string} repo Repository name. * @param {string} commenter Comment author. * @returns {Object | undefined} The GitHub comment object. */ const findComment = async (octokit, issueNumber, owner, repo, commenter) => { const parameters = { owner, repo, issue_number: issueNumber, }; const inputs = { commentAuthor: commenter, bodyIncludes: COMMENT_TITLE, }; // Search each page for the comment for await (const { data: comments } of octokit.paginate.iterator( octokit.rest.issues.listComments, parameters, )) { const comment = comments.find((comment) => isPreviewComment(inputs, comment), ); if (comment) { debug(`Found theme preview comment: ${inspect(comment)}`); return comment; } else { debug(`No theme preview comment found.`); } } return undefined; }; /** * Create or update the preview comment. * * @param {Object} octokit Octokit instance. * @param {number} issueNumber Issue number. * @param {Object} repo Repository name. * @param {Object} owner Owner of the repository. * @param {number} commentId Comment ID. * @param {string} body Comment body. * @returns {string} The comment URL. */ const upsertComment = async ( octokit, issueNumber, repo, owner, commentId, body, ) => { let resp; if (commentId === undefined) { resp = await octokit.rest.issues.createComment({ owner, repo, issue_number: issueNumber, body, }); } else { resp = await octokit.rest.issues.updateComment({ owner, repo, comment_id: commentId, body, }); } return resp.data.html_url; }; /** * Adds a review to the pull request. * * @param {Object} octokit Octokit instance. * @param {number} prNumber Pull request number. * @param {string} owner Owner of the repository. * @param {string} repo Repository name. * @param {string} reviewState The review state. Options are (APPROVE, REQUEST_CHANGES, COMMENT, PENDING). * @param {string} reason The reason for the review. * @returns {Promise<void>} Promise. */ const addReview = async ( octokit, prNumber, owner, repo, reviewState, reason, ) => { await octokit.rest.pulls.createReview({ owner, repo, pull_number: prNumber, event: reviewState, body: reason, }); }; /** * Add label to pull request. * * @param {Object} octokit Octokit instance. * @param {number} prNumber Pull request number. * @param {string} owner Repository owner. * @param {string} repo Repository name. * @param {string[]} labels Labels to add. * @returns {Promise<void>} Promise. */ const addLabel = async (octokit, prNumber, owner, repo, labels) => { await octokit.rest.issues.addLabels({ owner, repo, issue_number: prNumber, labels, }); }; /** * Remove label from the pull request. * * @param {Object} octokit Octokit instance. * @param {number} prNumber Pull request number. * @param {string} owner Repository owner. * @param {string} repo Repository name. * @param {string} label Label to add or remove. * @returns {Promise<void>} Promise. */ const removeLabel = async (octokit, prNumber, owner, repo, label) => { await octokit.rest.issues.removeLabel({ owner, repo, issue_number: prNumber, name: label, }); }; /** * Adds or removes a label from the pull request. * * @param {Object} octokit Octokit instance. * @param {number} prNumber Pull request number. * @param {string} owner Repository owner. * @param {string} repo Repository name. * @param {string} label Label to add or remove. * @param {boolean} add Whether to add or remove the label. * @returns {Promise<void>} Promise. */ const addRemoveLabel = async (octokit, prNumber, owner, repo, label, add) => { const res = await octokit.rest.pulls.get({ owner, repo, pull_number: prNumber, }); if (add) { if (!res.data.labels.find((l) => l.name === label)) { await addLabel(octokit, prNumber, owner, repo, [label]); } } else { if (res.data.labels.find((l) => l.name === label)) { await removeLabel(octokit, prNumber, owner, repo, label); } } }; /** * Retrieve webAim contrast color check link. * * @param {string} color1 First color. * @param {string} color2 Second color. * @returns {string} WebAim contrast color check link. */ const getWebAimLink = (color1, color2) => { return `https://webaim.org/resources/contrastchecker/?fcolor=${color1}&bcolor=${color2}`; }; /** * Retrieves the theme GRS url. * * @param {Object} colors The theme colors. * @returns {string} GRS theme url. */ const getGRSLink = (colors) => { const url = `https://github-readme-stats.vercel.app/api?username=anuraghazra`; const colorString = Object.keys(colors) .map((colorKey) => `${colorKey}=${colors[colorKey]}`) .join("&"); return `${url}&${colorString}&show_icons=true`; }; /** * Retrieve javascript object from json string. * * @description Wraps the Hjson parse function to fix several known json syntax errors. * * @param {string} json The json to parse. * @returns {Object} Object parsed from the json. */ const parseJSON = (json) => { try { const parsedJson = Hjson.parse(json); if (typeof parsedJson === "object") { return parsedJson; } else { throw new IncorrectJsonFormatError( "PR diff is not a valid theme JSON object.", ); } } catch (error) { // Resolve eslint no-unused-vars error; // Remove trailing commas (if any). let parsedJson = json.replace(/(,\s*})/g, "}"); // Remove JS comments (if any). parsedJson = parsedJson.replace(/\/\/[A-z\s]*\s/g, ""); // Fix incorrect open bracket (if any). const splitJson = parsedJson .split(/([\s\r\s]*}[\s\r\s]*,[\s\r\s]*)(?=[\w"-]+:)/) .filter((x) => typeof x !== "string" || !!x.trim()); // Split json into array of strings and objects. if (splitJson[0].replace(/\s+/g, "") === "},") { splitJson[0] = "},"; if (/\s*}\s*,?\s*$/.test(splitJson[1])) { splitJson.shift(); } else { splitJson.push(splitJson.shift()); } parsedJson = splitJson.join(""); } // Try to parse the fixed json. try { return Hjson.parse(parsedJson); } catch (error) { throw new IncorrectJsonFormatError( `Theme JSON file could not be parsed: ${error.message}`, ); } } }; /** * Check whether the theme name is still available. * @param {string} name Theme name. * @returns {boolean} Whether the theme name is available. */ const themeNameAlreadyExists = (name) => { return themes[name] !== undefined; }; const DRY_RUN = process.env.DRY_RUN === "true" || false; /** * Main function. * * @returns {Promise<void>} Promise. */ export const run = async () => { try { debug("Retrieve action information from context..."); debug(`Context: ${inspect(github.context)}`); let commentBody = ` \r# ${COMMENT_TITLE} \r${THEME_CONTRIB_GUIDELINES} `; const ccc = new ColorContrastChecker(); OCTOKIT = github.getOctokit(getGithubToken()); PULL_REQUEST_ID = getPrNumber(); const { owner, repo } = getRepoInfo(github.context); OWNER = owner; REPO = repo; const commenter = getCommenter(); PULL_REQUEST_ID = getPrNumber(); debug(`Owner: ${OWNER}`); debug(`Repo: ${REPO}`); debug(`Commenter: ${commenter}`); // Retrieve the PR diff and preview-theme comment. debug("Retrieve PR diff..."); const res = await OCTOKIT.rest.pulls.get({ owner: OWNER, repo: REPO, pull_number: PULL_REQUEST_ID, mediaType: { format: "diff", }, }); debug("Retrieve preview-theme comment..."); const comment = await findComment( OCTOKIT, PULL_REQUEST_ID, OWNER, REPO, commenter, ); // Retrieve theme changes from the PR diff. debug("Retrieve themes..."); const diff = parse(res.data); // Retrieve all theme changes from the PR diff and convert to JSON. debug("Retrieve theme changes..."); const content = diff .find((file) => file.to === "themes/index.js") .chunks.map((chunk) => chunk.changes .filter((c) => c.type === "add") .map((c) => c.content.replace("+", "")) .join(""), ) .join(""); const themeObject = parseJSON(content); if ( Object.keys(themeObject).every( (key) => typeof themeObject[key] !== "object", ) ) { throw new Error("PR diff is not a valid theme JSON object."); } // Loop through themes and create theme preview body. debug("Create theme preview body..."); const themeValid = Object.fromEntries( Object.keys(themeObject).map((name) => [name, true]), ); let previewBody = ""; for (const theme in themeObject) { debug(`Create theme preview for ${theme}...`); const themeName = theme; const colors = themeObject[theme]; const warnings = []; const errors = []; // Check if the theme name is valid. debug("Theme preview body: Check if the theme name is valid..."); if (themeNameAlreadyExists(themeName)) { warnings.push("Theme name already taken"); themeValid[theme] = false; } if (themeName !== snakeCase(themeName)) { warnings.push("Theme name isn't in snake_case"); themeValid[theme] = false; } // Check if the theme colors are valid. debug("Theme preview body: Check if the theme colors are valid..."); let invalidColors = false; if (colors) { const missingKeys = REQUIRED_COLOR_PROPS.filter( (x) => !Object.keys(colors).includes(x), ); const extraKeys = Object.keys(colors).filter( (x) => !ACCEPTED_COLOR_PROPS.includes(x), ); if (missingKeys.length > 0 || extraKeys.length > 0) { for (const missingKey of missingKeys) { errors.push(`Theme color properties \`${missingKey}\` are missing`); } for (const extraKey of extraKeys) { warnings.push( `Theme color properties \`${extraKey}\` is not supported`, ); } invalidColors = true; } else { for (const [colorKey, colorValue] of Object.entries(colors)) { if (colorValue[0] === "#") { errors.push( `Theme color property \`${colorKey}\` should not start with '#'`, ); invalidColors = true; } else if (colorValue.length > COLOR_PROPS[colorKey]) { errors.push( `Theme color property \`${colorKey}\` can not be longer than \`${COLOR_PROPS[colorKey]}\` characters`, ); invalidColors = true; } else if ( !(colorKey === "bg_color" && colorValue.split(",").length > 1 ? isValidGradient(colorValue.split(",")) : isValidHexColor(colorValue)) ) { errors.push( `Theme color property \`${colorKey}\` is not a valid hex color: <code>${colorValue}</code>`, ); invalidColors = true; } } } } else { warnings.push("Theme colors are missing"); invalidColors = true; } if (invalidColors) { themeValid[theme] = false; previewBody += ` \r### ${ themeName.charAt(0).toUpperCase() + themeName.slice(1) } theme preview \r${warnings.map((warning) => `- :warning: ${warning}.\n`).join("")} \r${errors.map((error) => `- :x: ${error}.\n`).join("")} \r>:x: Cannot create theme preview. `; continue; } // Check color contrast. debug("Theme preview body: Check color contrast..."); const titleColor = colors.title_color; const iconColor = colors.icon_color; const textColor = colors.text_color; const bgColor = colors.bg_color; const borderColor = colors.border_color; const url = getGRSLink(colors); const colorPairs = { title_color: [titleColor, bgColor], icon_color: [iconColor, bgColor], text_color: [textColor, bgColor], }; Object.keys(colorPairs).forEach((item) => { let color1 = colorPairs[item][0]; let color2 = colorPairs[item][1]; const isGradientColor = color2.split(",").length > 1; if (isGradientColor) { return; } color1 = color1.length === 4 ? color1.slice(0, 3) : color1.slice(0, 6); color2 = color2.length === 4 ? color2.slice(0, 3) : color2.slice(0, 6); if (!ccc.isLevelAA(`#${color1}`, `#${color2}`)) { const permalink = getWebAimLink(color1, color2); warnings.push( `\`${item}\` does not pass [AA contrast ratio](${permalink})`, ); themeValid[theme] = false; } }); // Create theme preview body. debug("Theme preview body: Create theme preview body..."); previewBody += ` \r### ${ themeName.charAt(0).toUpperCase() + themeName.slice(1) } theme preview \r${warnings.map((warning) => `- :warning: ${warning}.\n`).join("")} \ntitle_color: <code>#${titleColor}</code> | icon_color: <code>#${iconColor}</code> | text_color: <code>#${textColor}</code> | bg_color: <code>#${bgColor}</code>${ borderColor ? ` | border_color: <code>#${borderColor}</code>` : "" } \r[Preview Link](${url}) \r[![](${url})](${url}) `; } // Create comment body. debug("Create comment body..."); commentBody += ` \r${ Object.values(themeValid).every((value) => value) ? THEME_PR_SUCCESS_TEXT : THEME_PR_FAIL_TEXT } \r## Test results \r${Object.entries(themeValid) .map( ([key, value]) => `- ${value ? ":heavy_check_mark:" : ":x:"} ${key}`, ) .join("\r")} \r${ Object.values(themeValid).every((value) => value) ? "**Result:** :heavy_check_mark: All themes are valid." : "**Result:** :x: Some themes are invalid.\n\n" + FAIL_TEXT } \r## Details \r${previewBody} `; // Create or update theme-preview comment. debug("Create or update theme-preview comment..."); let comment_url; if (DRY_RUN) { info(`DRY_RUN: Comment body: ${commentBody}`); comment_url = ""; } else { comment_url = await upsertComment( OCTOKIT, PULL_REQUEST_ID, REPO, OWNER, comment?.id, commentBody, ); } // Change review state and add/remove `invalid` label based on theme PR validity. debug( "Change review state and add/remove `invalid` label based on whether all themes passed...", ); const themesValid = Object.values(themeValid).every((value) => value); const reviewState = themesValid ? "APPROVE" : "REQUEST_CHANGES"; const reviewReason = themesValid ? undefined : INVALID_REVIEW_COMMENT(comment_url); if (DRY_RUN) { info(`DRY_RUN: Review state: ${reviewState}`); info(`DRY_RUN: Review reason: ${reviewReason}`); } else { await addReview( OCTOKIT, PULL_REQUEST_ID, OWNER, REPO, reviewState, reviewReason, ); await addRemoveLabel( OCTOKIT, PULL_REQUEST_ID, OWNER, REPO, "invalid", !themesValid, ); } } catch (error) { debug("Set review state to `REQUEST_CHANGES` and add `invalid` label..."); if (DRY_RUN) { info(`DRY_RUN: Review state: REQUEST_CHANGES`); info(`DRY_RUN: Review reason: ${error.message}`); } else { await addReview( OCTOKIT, PULL_REQUEST_ID, OWNER, REPO, "REQUEST_CHANGES", "**Something went wrong in the theme preview action:** `" + error.message + "`", ); await addRemoveLabel( OCTOKIT, PULL_REQUEST_ID, OWNER, REPO, "invalid", true, ); } setFailed(error.message); } }; run();
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/scripts/generate-langs-json.js
scripts/generate-langs-json.js
import axios from "axios"; import fs from "fs"; import jsYaml from "js-yaml"; const LANGS_FILEPATH = "./src/common/languageColors.json"; //Retrieve languages from github linguist repository yaml file //@ts-ignore axios .get( "https://raw.githubusercontent.com/github/linguist/master/lib/linguist/languages.yml", ) .then((response) => { //and convert them to a JS Object const languages = jsYaml.load(response.data); const languageColors = {}; //Filter only language colors from the whole file Object.keys(languages).forEach((lang) => { languageColors[lang] = languages[lang].color; }); //Debug Print //console.dir(languageColors); fs.writeFileSync( LANGS_FILEPATH, JSON.stringify(languageColors, null, " "), ); });
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/scripts/helpers.js
scripts/helpers.js
/** * @file Contains helper functions used in the scripts. */ import { getInput } from "@actions/core"; const OWNER = "anuraghazra"; const REPO = "github-readme-stats"; /** * Retrieve information about the repository that ran the action. * * @param {Object} ctx Action context. * @returns {Object} Repository information. */ export const getRepoInfo = (ctx) => { try { return { owner: ctx.repo.owner, repo: ctx.repo.repo, }; } catch (error) { // Resolve eslint no-unused-vars error; return { owner: OWNER, repo: REPO, }; } }; /** * Retrieve github token and throw error if it is not found. * * @returns {string} GitHub token. */ export const getGithubToken = () => { const token = getInput("github_token") || process.env.GITHUB_TOKEN; if (!token) { throw Error("Could not find github token"); } return token; };
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/index.js
src/index.js
export * from "./common/index.js"; export * from "./cards/index.js";
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/calculateRank.js
src/calculateRank.js
/** * Calculates the exponential cdf. * * @param {number} x The value. * @returns {number} The exponential cdf. */ function exponential_cdf(x) { return 1 - 2 ** -x; } /** * Calculates the log normal cdf. * * @param {number} x The value. * @returns {number} The log normal cdf. */ function log_normal_cdf(x) { // approximation return x / (1 + x); } /** * Calculates the users rank. * * @param {object} params Parameters on which the user's rank depends. * @param {boolean} params.all_commits Whether `include_all_commits` was used. * @param {number} params.commits Number of commits. * @param {number} params.prs The number of pull requests. * @param {number} params.issues The number of issues. * @param {number} params.reviews The number of reviews. * @param {number} params.repos Total number of repos. * @param {number} params.stars The number of stars. * @param {number} params.followers The number of followers. * @returns {{ level: string, percentile: number }} The users rank. */ function calculateRank({ all_commits, commits, prs, issues, reviews, // eslint-disable-next-line no-unused-vars repos, // unused stars, followers, }) { const COMMITS_MEDIAN = all_commits ? 1000 : 250, COMMITS_WEIGHT = 2; const PRS_MEDIAN = 50, PRS_WEIGHT = 3; const ISSUES_MEDIAN = 25, ISSUES_WEIGHT = 1; const REVIEWS_MEDIAN = 2, REVIEWS_WEIGHT = 1; const STARS_MEDIAN = 50, STARS_WEIGHT = 4; const FOLLOWERS_MEDIAN = 10, FOLLOWERS_WEIGHT = 1; const TOTAL_WEIGHT = COMMITS_WEIGHT + PRS_WEIGHT + ISSUES_WEIGHT + REVIEWS_WEIGHT + STARS_WEIGHT + FOLLOWERS_WEIGHT; const THRESHOLDS = [1, 12.5, 25, 37.5, 50, 62.5, 75, 87.5, 100]; const LEVELS = ["S", "A+", "A", "A-", "B+", "B", "B-", "C+", "C"]; const rank = 1 - (COMMITS_WEIGHT * exponential_cdf(commits / COMMITS_MEDIAN) + PRS_WEIGHT * exponential_cdf(prs / PRS_MEDIAN) + ISSUES_WEIGHT * exponential_cdf(issues / ISSUES_MEDIAN) + REVIEWS_WEIGHT * exponential_cdf(reviews / REVIEWS_MEDIAN) + STARS_WEIGHT * log_normal_cdf(stars / STARS_MEDIAN) + FOLLOWERS_WEIGHT * log_normal_cdf(followers / FOLLOWERS_MEDIAN)) / TOTAL_WEIGHT; const level = LEVELS[THRESHOLDS.findIndex((t) => rank * 100 <= t)]; return { level, percentile: rank * 100 }; } export { calculateRank }; export default calculateRank;
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/translations.js
src/translations.js
// @ts-check import { encodeHTML } from "./common/html.js"; /** * Retrieves stat card labels in the available locales. * * @param {object} props Function arguments. * @param {string} props.name The name of the locale. * @param {string} props.apostrophe Whether to use apostrophe or not. * @returns {object} The locales object. * * @see https://www.andiamo.co.uk/resources/iso-language-codes/ for language codes. */ const statCardLocales = ({ name, apostrophe }) => { const encodedName = encodeHTML(name); return { "statcard.title": { en: `${encodedName}'${apostrophe} GitHub Stats`, ar: `${encodedName} إحصائيات جيت هاب`, az: `${encodedName}'${apostrophe} Hesabının GitHub Statistikası`, ca: `Estadístiques de GitHub de ${encodedName}`, cn: `${encodedName} 的 GitHub 统计数据`, "zh-tw": `${encodedName} 的 GitHub 統計資料`, cs: `GitHub statistiky uživatele ${encodedName}`, de: `${encodedName + apostrophe} GitHub-Statistiken`, sw: `GitHub Stats za ${encodedName}`, ur: `${encodedName} کے گٹ ہب کے اعداد و شمار`, bg: `GitHub статистика на потребител ${encodedName}`, bn: `${encodedName} এর GitHub পরিসংখ্যান`, es: `Estadísticas de GitHub de ${encodedName}`, fa: `آمار گیت‌هاب ${encodedName}`, fi: `${encodedName}:n GitHub-tilastot`, fr: `Statistiques GitHub de ${encodedName}`, hi: `${encodedName} के GitHub आँकड़े`, sa: `${encodedName} इत्यस्य GitHub सांख्यिकी`, hu: `${encodedName} GitHub statisztika`, it: `Statistiche GitHub di ${encodedName}`, ja: `${encodedName}の GitHub 統計`, kr: `${encodedName}의 GitHub 통계`, nl: `${encodedName}'${apostrophe} GitHub-statistieken`, "pt-pt": `Estatísticas do GitHub de ${encodedName}`, "pt-br": `Estatísticas do GitHub de ${encodedName}`, np: `${encodedName}'${apostrophe} गिटहब तथ्याङ्क`, el: `Στατιστικά GitHub του ${encodedName}`, ro: `Statisticile GitHub ale lui ${encodedName}`, ru: `Статистика GitHub пользователя ${encodedName}`, "uk-ua": `Статистика GitHub користувача ${encodedName}`, id: `Statistik GitHub ${encodedName}`, ml: `${encodedName}'${apostrophe} ഗിറ്റ്ഹബ് സ്ഥിതിവിവരക്കണക്കുകൾ`, my: `${encodedName} ရဲ့ GitHub အခြေအနေများ`, ta: `${encodedName} கிட்ஹப் புள்ளிவிவரங்கள்`, sk: `GitHub štatistiky používateľa ${encodedName}`, tr: `${encodedName} Hesabının GitHub İstatistikleri`, pl: `Statystyki GitHub użytkownika ${encodedName}`, uz: `${encodedName}ning GitHub'dagi statistikasi`, vi: `Thống Kê GitHub ${encodedName}`, se: `GitHubstatistik för ${encodedName}`, he: `סטטיסטיקות הגיטהאב של ${encodedName}`, fil: `Mga Stats ng GitHub ni ${encodedName}`, th: `สถิติ GitHub ของ ${encodedName}`, sr: `GitHub статистика корисника ${encodedName}`, "sr-latn": `GitHub statistika korisnika ${encodedName}`, no: `GitHub-statistikk for ${encodedName}`, }, "statcard.ranktitle": { en: `${encodedName}'${apostrophe} GitHub Rank`, ar: `${encodedName} إحصائيات جيت هاب`, az: `${encodedName}'${apostrophe} Hesabının GitHub Statistikası`, ca: `Estadístiques de GitHub de ${encodedName}`, cn: `${encodedName} 的 GitHub 统计数据`, "zh-tw": `${encodedName} 的 GitHub 統計資料`, cs: `GitHub statistiky uživatele ${encodedName}`, de: `${encodedName + apostrophe} GitHub-Statistiken`, sw: `GitHub Rank ya ${encodedName}`, ur: `${encodedName} کی گٹ ہب رینک`, bg: `GitHub ранг на ${encodedName}`, bn: `${encodedName} এর GitHub পরিসংখ্যান`, es: `Estadísticas de GitHub de ${encodedName}`, fa: `رتبه گیت‌هاب ${encodedName}`, fi: `${encodedName}:n GitHub-sijoitus`, fr: `Statistiques GitHub de ${encodedName}`, hi: `${encodedName} का GitHub स्थान`, sa: `${encodedName} इत्यस्य GitHub स्थानम्`, hu: `${encodedName} GitHub statisztika`, it: `Statistiche GitHub di ${encodedName}`, ja: `${encodedName} の GitHub ランク`, kr: `${encodedName}의 GitHub 통계`, nl: `${encodedName}'${apostrophe} GitHub-statistieken`, "pt-pt": `Estatísticas do GitHub de ${encodedName}`, "pt-br": `Estatísticas do GitHub de ${encodedName}`, np: `${encodedName}'${apostrophe} गिटहब तथ्याङ्क`, el: `Στατιστικά GitHub του ${encodedName}`, ro: `Rankul GitHub al lui ${encodedName}`, ru: `Рейтинг GitHub пользователя ${encodedName}`, "uk-ua": `Рейтинг GitHub користувача ${encodedName}`, id: `Statistik GitHub ${encodedName}`, ml: `${encodedName}'${apostrophe} ഗിറ്റ്ഹബ് സ്ഥിതിവിവരക്കണക്കുകൾ`, my: `${encodedName} ရဲ့ GitHub အဆင့်`, ta: `${encodedName} கிட்ஹப் தரவரிசை`, sk: `GitHub štatistiky používateľa ${encodedName}`, tr: `${encodedName} Hesabının GitHub Yıldızları`, pl: `Statystyki GitHub użytkownika ${encodedName}`, uz: `${encodedName}ning GitHub'dagi statistikasi`, vi: `Thống Kê GitHub ${encodedName}`, se: `GitHubstatistik för ${encodedName}`, he: `דרגת הגיטהאב של ${encodedName}`, fil: `Ranggo ng GitHub ni ${encodedName}`, th: `อันดับ GitHub ของ ${encodedName}`, sr: `Ранк корисника ${encodedName}`, "sr-latn": `Rank korisnika ${encodedName}`, no: `GitHub-statistikk for ${encodedName}`, }, "statcard.totalstars": { en: "Total Stars Earned", ar: "مجموع النجوم", az: "Ümumi Ulduz", ca: "Total d'estrelles", cn: "获标星数", "zh-tw": "得標星星數量(Star)", cs: "Celkem hvězd", de: "Insgesamt erhaltene Sterne", sw: "Medali(stars) ulizojishindia", ur: "کل ستارے حاصل کیے", bg: "Получени звезди", bn: "সর্বমোট Star", es: "Estrellas totales", fa: "مجموع ستاره‌های دریافت‌شده", fi: "Ansaitut tähdet yhteensä", fr: "Total d'étoiles", hi: "कुल अर्जित सितारे", sa: "अर्जिताः कुल-तारकाः", hu: "Csillagok", it: "Stelle totali", ja: "スターされた数", kr: "받은 스타 수", nl: "Totaal Sterren Ontvangen", "pt-pt": "Total de estrelas", "pt-br": "Total de estrelas", np: "कुल ताराहरू", el: "Σύνολο Αστεριών", ro: "Total de stele câștigate", ru: "Всего звёзд", "uk-ua": "Всього зірок", id: "Total Bintang", ml: "ആകെ നക്ഷത്രങ്ങൾ", my: "စုစုပေါင်းကြယ်များ", ta: "சம்பாதித்த மொத்த நட்சத்திரங்கள்", sk: "Hviezdy", tr: "Toplam Yıldız", pl: "Liczba otrzymanych gwiazdek", uz: "Yulduzchalar", vi: "Tổng Số Sao", se: "Antal intjänade stjärnor", he: "סך כל הכוכבים שהושגו", fil: "Kabuuang Nakuhang Bituin", th: "ดาวทั้งหมดที่ได้รับ", sr: "Број освојених звездица", "sr-latn": "Broj osvojenih zvezdica", no: "Totalt antall stjerner", }, "statcard.commits": { en: "Total Commits", ar: "مجموع المساهمات", az: "Ümumi Commit", ca: "Commits totals", cn: "累计提交总数", "zh-tw": "累計提交數量(Commit)", cs: "Celkem commitů", de: "Anzahl Commits", sw: "Matendo yako yote", ur: "کل کمٹ", bg: "Общо ангажименти", bn: "সর্বমোট Commit", es: "Commits totales", fa: "مجموع کامیت‌ها", fi: "Yhteensä committeja", fr: "Total des Commits", hi: "कुल commits", sa: "कुल-समिन्चयः", hu: "Összes commit", it: "Commit totali", ja: "合計コミット数", kr: "전체 커밋 수", nl: "Aantal commits", "pt-pt": "Total de Commits", "pt-br": "Total de Commits", np: "कुल Commits", el: "Σύνολο Commits", ro: "Total Commit-uri", ru: "Всего коммитов", "uk-ua": "Всього комітів", id: "Total Komitmen", ml: "ആകെ കമ്മിറ്റുകൾ", my: "စုစုပေါင်း Commit များ", ta: `மொத்த கமிட்கள்`, sk: "Všetky commity", tr: "Toplam Commit", pl: "Wszystkie commity", uz: "'Commit'lar", vi: "Tổng Số Cam Kết", se: "Totalt antal commits", he: "סך כל ה־commits", fil: "Kabuuang Commits", th: "Commit ทั้งหมด", sr: "Укупно commit-ова", "sr-latn": "Ukupno commit-ova", no: "Totalt antall commits", }, "statcard.prs": { en: "Total PRs", ar: "مجموع طلبات السحب", az: "Ümumi PR", ca: "PRs totals", cn: "发起的 PR 总数", "zh-tw": "拉取請求數量(PR)", cs: "Celkem PRs", de: "PRs Insgesamt", sw: "PRs Zote", ur: "کل پی آرز", bg: "Заявки за изтегляния", bn: "সর্বমোট PR", es: "PRs totales", fa: "مجموع Pull Request", fi: "Yhteensä PR:t", fr: "Total des PRs", hi: "कुल PR", sa: "कुल-पीआर", hu: "Összes PR", it: "PR totali", ja: "合計 PR", kr: "PR 횟수", nl: "Aantal PR's", "pt-pt": "Total de PRs", "pt-br": "Total de PRs", np: "कुल PRs", el: "Σύνολο PRs", ro: "Total PR-uri", ru: "Всего запросов изменений", "uk-ua": "Всього запитів на злиття", id: "Total Permintaan Tarik", ml: "ആകെ പുൾ അഭ്യർത്ഥനകൾ", my: "စုစုပေါင်း PR များ", ta: `மொத்த இழுக்கும் கோரிக்கைகள்`, sk: "Všetky PR", tr: "Toplam PR", pl: "Wszystkie PR-y", uz: "'Pull Request'lar", vi: "Tổng Số PR", se: "Totalt antal PR", he: "סך כל ה־PRs", fil: "Kabuuang PRs", th: "PR ทั้งหมด", sr: "Укупно PR-ова", "sr-latn": "Ukupno PR-ova", no: "Totalt antall PR", }, "statcard.issues": { en: "Total Issues", ar: "مجموع التحسينات", az: "Ümumi Problem", ca: "Issues totals", cn: "提出的 issue 总数", "zh-tw": "提出問題數量(Issue)", cs: "Celkem problémů", de: "Anzahl Issues", sw: "Masuala Ibuka", ur: "کل مسائل", bg: "Брой въпроси", bn: "সর্বমোট Issue", es: "Issues totales", fa: "مجموع مسائل", fi: "Yhteensä ongelmat", fr: "Nombre total d'incidents", hi: "कुल मुद्दे(Issues)", sa: "कुल-समस्याः", hu: "Összes hibajegy", it: "Segnalazioni totali", ja: "合計 issue", kr: "이슈 개수", nl: "Aantal kwesties", "pt-pt": "Total de Issues", "pt-br": "Total de Issues", np: "कुल मुद्दाहरू", el: "Σύνολο Ζητημάτων", ro: "Total Issue-uri", ru: "Всего вопросов", "uk-ua": "Всього питань", id: "Total Masalah Dilaporkan", ml: "ആകെ പ്രശ്നങ്ങൾ", my: "စုစုပေါင်းပြဿနာများ", ta: `மொத்த சிக்கல்கள்`, sk: "Všetky problémy", tr: "Toplam Hata", pl: "Wszystkie problemy", uz: "'Issue'lar", vi: "Tổng Số Vấn Đề", se: "Total antal issues", he: "סך כל ה־issues", fil: "Kabuuang mga Isyu", th: "Issue ทั้งหมด", sr: "Укупно пријављених проблема", "sr-latn": "Ukupno prijavljenih problema", no: "Totalt antall issues", }, "statcard.contribs": { en: "Contributed to (last year)", ar: "ساهم في (العام الماضي)", az: "Töhfə verdi (ötən il)", ca: "Contribucions (l'any passat)", cn: "贡献的项目数(去年)", "zh-tw": "參與項目數量(去年)", cs: "Přispěl k (minulý rok)", de: "Beigetragen zu (letztes Jahr)", sw: "Idadi ya michango (mwaka mzima)", ur: "پچھلے سال میں تعاون کیا", bg: "Приноси (за изминалата година)", bn: "অবদান (গত বছর)", es: "Contribuciones en (el año pasado)", fa: "مشارکت در (سال گذشته)", fi: "Osallistunut (viime vuonna)", fr: "Contribué à (l'année dernière)", hi: "(पिछले वर्ष) में योगदान दिया", sa: "(गते वर्षे) योगदानम् कृतम्", hu: "Hozzájárulások (tavaly)", it: "Ha contribuito a (l'anno scorso)", ja: "貢献したリポジトリ (昨年)", kr: "(작년) 기여", nl: "Bijgedragen aan (vorig jaar)", "pt-pt": "Contribuiu em (ano passado)", "pt-br": "Contribuiu para (ano passado)", np: "कुल योगदानहरू (गत वर्ष)", el: "Συνεισφέρθηκε σε (πέρυσι)", ro: "Total Contribuiri", ru: "Внесено вклада (за прошлый год)", "uk-ua": "Зроблено внесок (за минулий рік)", id: "Berkontribusi ke (tahun lalu)", ml: "(കഴിഞ്ഞ വർഷത്തെ)ആകെ സംഭാവനകൾ ", my: "အကူအညီပေးခဲ့သည် (ပြီးခဲ့သည့်နှစ်)", ta: "(கடந்த ஆண்டு) பங்களித்தது", sk: "Účasti (minulý rok)", tr: "Katkı Verildi (geçen yıl)", pl: "Kontrybucje (w zeszłym roku)", uz: "Hissa qoʻshgan (o'tgan yili)", vi: "Đã Đóng Góp (năm ngoái)", se: "Bidragit till (förra året)", he: "תרם ל... (שנה שעברה)", fil: "Nag-ambag sa (nakaraang taon)", th: "มีส่วนร่วมใน (ปีที่แล้ว)", sr: "Доприноси (прошла година)", "sr-latn": "Doprinosi (prošla godina)", no: "Bidro til (i fjor)", }, "statcard.reviews": { en: "Total PRs Reviewed", ar: "طلبات السحب التي تم مراجعتها", az: "Nəzərdən Keçirilən Ümumi PR", ca: "Total de PRs revisats", cn: "审查的 PR 总数", "zh-tw": "審核的 PR 總計", cs: "Celkový počet PR", de: "Insgesamt überprüfte PRs", sw: "Idadi ya PRs zilizopitiliwa upya", ur: "کل پی آرز کا جائزہ لیا", bg: "Разгледани заявки за изтегляне", bn: "সর্বমোট পুনরালোচনা করা PR", es: "PR totales revisados", fa: "مجموع درخواست‌های ادغام بررسی‌شده", fi: "Yhteensä tarkastettuja PR:itä", fr: "Nombre total de PR examinés", hi: "कुल PRs की समीक्षा की गई", sa: "समीक्षिताः कुल-पीआर", hu: "Összes ellenőrzött PR", it: "PR totali esaminati", ja: "レビューされた PR の総数", kr: "검토된 총 PR", nl: "Totaal beoordeelde PR's", "pt-pt": "Total de PRs revistos", "pt-br": "Total de PRs revisados", np: "कुल पीआर समीक्षित", el: "Σύνολο Αναθεωρημένων PR", ro: "Total PR-uri Revizuite", ru: "Всего запросов проверено", "uk-ua": "Всього запитів перевірено", id: "Total PR yang Direview", ml: "ആകെ പുൾ അവലോകനങ്ങൾ", my: "စုစုပေါင်း PR များကို ပြန်လည်သုံးသပ်ခဲ့မှု", ta: "மதிப்பாய்வு செய்யப்பட்ட மொத்த இழுத்தல் கோரிக்கைகள்", sk: "Celkový počet PR", tr: "İncelenen toplam PR", pl: "Łącznie sprawdzonych PR", uz: "Koʻrib chiqilgan PR-lar soni", vi: "Tổng Số PR Đã Xem Xét", se: "Totalt antal granskade PR", he: "סך כל ה־PRs שנסרקו", fil: "Kabuuang PR na Na-review", th: "รีวิว PR แล้วทั้งหมด", sr: "Укупно прегледаних PR-ова", "sr-latn": "Ukupno pregledanih PR-ova", no: "Totalt antall vurderte PR", }, "statcard.discussions-started": { en: "Total Discussions Started", ar: "مجموع المناقشات التي بدأها", az: "Başladılan Ümumi Müzakirə", ca: "Discussions totals iniciades", cn: "发起的讨论总数", "zh-tw": "發起的討論總數", cs: "Celkem zahájených diskusí", de: "Gesamt gestartete Diskussionen", sw: "Idadi ya majadiliano yaliyoanzishwa", ur: "کل مباحثے شروع کیے", bg: "Започнати дискусии", bn: "সর্বমোট আলোচনা শুরু", es: "Discusiones totales iniciadas", fa: "مجموع بحث‌های آغازشده", fi: "Aloitetut keskustelut yhteensä", fr: "Nombre total de discussions lancées", hi: "कुल चर्चाएँ शुरू हुईं", sa: "प्रारब्धाः कुल-चर्चाः", hu: "Összes megkezdett megbeszélés", it: "Discussioni totali avviate", ja: "開始されたディスカッションの総数", kr: "시작된 토론 총 수", nl: "Totaal gestarte discussies", "pt-pt": "Total de Discussões Iniciadas", "pt-br": "Total de Discussões Iniciadas", np: "कुल चर्चा सुरु", el: "Σύνολο Συζητήσεων που Ξεκίνησαν", ro: "Total Discuții Începute", ru: "Всего начатых обсуждений", "uk-ua": "Всього розпочатих дискусій", id: "Total Diskusi Dimulai", ml: "ആരംഭിച്ച ആലോചനകൾ", my: "စုစုပေါင်း စတင်ခဲ့သော ဆွေးနွေးမှုများ", ta: "மொத்த விவாதங்கள் தொடங்கின", sk: "Celkový počet začatých diskusií", tr: "Başlatılan Toplam Tartışma", pl: "Łącznie rozpoczętych dyskusji", uz: "Boshlangan muzokaralar soni", vi: "Tổng Số Thảo Luận Bắt Đầu", se: "Totalt antal diskussioner startade", he: "סך כל הדיונים שהותחלו", fil: "Kabuuang mga Diskusyon na Sinimulan", th: "เริ่มหัวข้อสนทนาทั้งหมด", sr: "Укупно покренутих дискусија", "sr-latn": "Ukupno pokrenutih diskusija", no: "Totalt antall startede diskusjoner", }, "statcard.discussions-answered": { en: "Total Discussions Answered", ar: "مجموع المناقشات المُجابة", az: "Cavablandırılan Ümumi Müzakirə", ca: "Discussions totals respostes", cn: "回复的讨论总数", "zh-tw": "回覆討論總計", cs: "Celkem zodpovězených diskusí", de: "Gesamt beantwortete Diskussionen", sw: "Idadi ya majadiliano yaliyojibiwa", ur: "کل مباحثے جواب دیے", bg: "Отговорени дискусии", bn: "সর্বমোট আলোচনা উত্তর", es: "Discusiones totales respondidas", fa: "مجموع بحث‌های پاسخ‌داده‌شده", fi: "Vastatut keskustelut yhteensä", fr: "Nombre total de discussions répondues", hi: "कुल चर्चाओं के उत्तर", sa: "उत्तरिताः कुल-चर्चाः", hu: "Összes megválaszolt megbeszélés", it: "Discussioni totali risposte", ja: "回答されたディスカッションの総数", kr: "답변된 토론 총 수", nl: "Totaal beantwoorde discussies", "pt-pt": "Total de Discussões Respondidas", "pt-br": "Total de Discussões Respondidas", np: "कुल चर्चा उत्तर", el: "Σύνολο Συζητήσεων που Απαντήθηκαν", ro: "Total Răspunsuri La Discuții", ru: "Всего отвеченных обсуждений", "uk-ua": "Всього відповідей на дискусії", id: "Total Diskusi Dibalas", ml: "ഉത്തരം നൽകിയ ആലോചനകൾ", my: "စုစုပေါင်း ပြန်လည်ဖြေကြားခဲ့သော ဆွေးနွေးမှုများ", ta: "பதிலளிக்கப்பட்ட மொத்த விவாதங்கள்", sk: "Celkový počet zodpovedaných diskusií", tr: "Toplam Cevaplanan Tartışma", pl: "Łącznie odpowiedzianych dyskusji", uz: "Javob berilgan muzokaralar soni", vi: "Tổng Số Thảo Luận Đã Trả Lời", se: "Totalt antal diskussioner besvarade", he: "סך כל הדיונים שנענו", fil: "Kabuuang mga Diskusyon na Sinagot", th: "ตอบกลับหัวข้อสนทนาทั้งหมด", sr: "Укупно одговорених дискусија", "sr-latn": "Ukupno odgovorenih diskusija", no: "Totalt antall besvarte diskusjoner", }, "statcard.prs-merged": { en: "Total PRs Merged", ar: "مجموع طلبات السحب المُدمجة", az: "Birləşdirilmiş Ümumi PR", ca: "PRs totals fusionats", cn: "合并的 PR 总数", "zh-tw": "合併的 PR 總計", cs: "Celkem sloučených PR", de: "Insgesamt zusammengeführte PRs", sw: "Idadi ya PRs zilizounganishwa", ur: "کل پی آرز ضم کیے", bg: "Сляти заявки за изтегляния", bn: "সর্বমোট PR একত্রীকৃত", es: "PR totales fusionados", fa: "مجموع درخواست‌های ادغام شده", fi: "Yhteensä yhdistetyt PR:t", fr: "Nombre total de PR fusionnés", hi: "कुल PR का विलय", sa: "विलीनाः कुल-पीआर", hu: "Összes egyesített PR", it: "PR totali uniti", ja: "マージされた PR の総数", kr: "병합된 총 PR", nl: "Totaal samengevoegde PR's", "pt-pt": "Total de PRs Fundidos", "pt-br": "Total de PRs Integrados", np: "कुल विलयित PRs", el: "Σύνολο Συγχωνευμένων PR", ro: "Total PR-uri Fuzionate", ru: "Всего объединённых запросов", "uk-ua": "Всього об'єднаних запитів", id: "Total PR Digabungkan", my: "စုစုပေါင်း ပေါင်းစည်းခဲ့သော PR များ", ta: "இணைக்கப்பட்ட மொத்த PRகள்", sk: "Celkový počet zlúčených PR", tr: "Toplam Birleştirilmiş PR", pl: "Łącznie połączonych PR", uz: "Birlangan PR-lar soni", vi: "Tổng Số PR Đã Hợp Nhất", se: "Totalt antal sammanfogade PR", he: "סך כל ה־PRs ששולבו", fil: "Kabuuang mga PR na Pinagsama", th: "PR ที่ถูก Merged แล้วทั้งหมด", sr: "Укупно спојених PR-ова", "sr-latn": "Ukupno spojenih PR-ova", no: "Totalt antall sammenslåtte PR", }, "statcard.prs-merged-percentage": { en: "Merged PRs Percentage", ar: "نسبة طلبات السحب المُدمجة", az: "Birləşdirilmiş PR-ların Faizi", ca: "Percentatge de PRs fusionats", cn: "被合并的 PR 占比", "zh-tw": "合併的 PR 百分比", cs: "Sloučené PRs v procentech", de: "Zusammengeführte PRs in Prozent", sw: "Asilimia ya PRs zilizounganishwa", ur: "ضم کیے گئے پی آرز کی شرح", bg: "Процент сляти заявки за изтегляния", bn: "PR একত্রীকরণের শতাংশ", es: "Porcentaje de PR fusionados", fa: "درصد درخواست‌های ادغام‌شده", fi: "Yhdistettyjen PR:ien prosentti", fr: "Pourcentage de PR fusionnés", hi: "मर्ज किए गए PRs प्रतिशत", sa: "विलीन-पीआर प्रतिशतम्", hu: "Egyesített PR-k százaléka", it: "Percentuale di PR uniti", ja: "マージされた PR の割合", kr: "병합된 PR의 비율", nl: "Percentage samengevoegde PR's", "pt-pt": "Percentagem de PRs Fundidos", "pt-br": "Porcentagem de PRs Integrados", np: "PR मर्ज गरिएको प्रतिशत", el: "Ποσοστό Συγχωνευμένων PR", ro: "Procentaj PR-uri Fuzionate", ru: "Процент объединённых запросов", "uk-ua": "Відсоток об'єднаних запитів", id: "Persentase PR Digabungkan", my: "PR များကို ပေါင်းစည်းခဲ့သော ရာခိုင်နှုန်း", ta: "இணைக்கப்பட்ட PRகள் சதவீதம்", sk: "Percento zlúčených PR", tr: "Birleştirilmiş PR Yüzdesi", pl: "Procent połączonych PR", uz: "Birlangan PR-lar foizi", vi: "Tỷ Lệ PR Đã Hợp Nhất", se: "Procent av sammanfogade PR", he: "אחוז ה־PRs ששולבו", fil: "Porsyento ng mga PR na Pinagsama", th: "เปอร์เซ็นต์ PR ที่ถูก Merged แล้วทั้งหมด", sr: "Проценат спојених PR-ова", "sr-latn": "Procenat spojenih PR-ova", no: "Prosentandel sammenslåtte PR", }, }; }; const repoCardLocales = { "repocard.template": { en: "Template", ar: "قالب", az: "Şablon", bg: "Шаблон", bn: "টেমপ্লেট", ca: "Plantilla", cn: "模板", "zh-tw": "模板", cs: "Šablona", de: "Vorlage", sw: "Kigezo", ur: "سانچہ", es: "Plantilla", fa: "الگو", fi: "Malli", fr: "Modèle", hi: "खाका", sa: "प्रारूपम्", hu: "Sablon", it: "Template", ja: "テンプレート", kr: "템플릿", nl: "Sjabloon", "pt-pt": "Modelo", "pt-br": "Modelo", np: "टेम्पलेट", el: "Πρότυπο", ro: "Șablon", ru: "Шаблон", "uk-ua": "Шаблон", id: "Pola", ml: "ടെംപ്ലേറ്റ്", my: "ပုံစံ", ta: `டெம்ப்ளேட்`, sk: "Šablóna", tr: "Şablon", pl: "Szablony", uz: "Shablon", vi: "Mẫu", se: "Mall", he: "תבנית", fil: "Suleras", th: "เทมเพลต", sr: "Шаблон", "sr-latn": "Šablon", no: "Mal", }, "repocard.archived": { en: "Archived", ar: "مُؤرشف", az: "Arxiv", bg: "Архивирани", bn: "আর্কাইভড", ca: "Arxivats", cn: "已归档", "zh-tw": "已封存", cs: "Archivováno", de: "Archiviert", sw: "Hifadhiwa kwenye kumbukumbu", ur: "محفوظ شدہ", es: "Archivados", fa: "بایگانی‌شده", fi: "Arkistoitu", fr: "Archivé", hi: "संग्रहीत", sa: "संगृहीतम्", hu: "Archivált", it: "Archiviata", ja: "アーカイブ済み", kr: "보관됨", nl: "Gearchiveerd", "pt-pt": "Arquivados", "pt-br": "Arquivados", np: "अभिलेख राखियो", el: "Αρχειοθετημένα", ro: "Arhivat", ru: "Архивирован", "uk-ua": "Архивований", id: "Arsip", ml: "ശേഖരിച്ചത്", my: "သိုလှောင်ပြီး", ta: `காப்பகப்படுத்தப்பட்டது`, sk: "Archivované", tr: "Arşiv", pl: "Zarchiwizowano", uz: "Arxivlangan", vi: "Đã Lưu Trữ", se: "Arkiverade", he: "גנוז", fil: "Naka-arkibo", th: "เก็บถาวร", sr: "Архивирано", "sr-latn": "Arhivirano", no: "Arkivert", }, }; const langCardLocales = { "langcard.title": { en: "Most Used Languages", ar: "أكثر اللغات استخدامًا", az: "Ən Çox İstifadə Olunan Dillər", ca: "Llenguatges més utilitzats", cn: "最常用的语言", "zh-tw": "最常用的語言", cs: "Nejpoužívanější jazyky", de: "Meist verwendete Sprachen", bg: "Най-използвани езици", bn: "সর্বাধিক ব্যবহৃত ভাষা সমূহ", sw: "Lugha zilizotumika zaidi", ur: "سب سے زیادہ استعمال شدہ زبانیں", es: "Lenguajes más usados", fa: "زبان‌های پرکاربرد", fi: "Käytetyimmät kielet", fr: "Langages les plus utilisés", hi: "सर्वाधिक प्रयुक्त भाषा", sa: "सर्वाधिक-प्रयुक्ताः भाषाः", hu: "Leggyakrabban használt nyelvek", it: "Linguaggi più utilizzati", ja: "最もよく使っている言語", kr: "가장 많이 사용된 언어", nl: "Meest gebruikte talen", "pt-pt": "Linguagens mais usadas", "pt-br": "Linguagens mais usadas", np: "अधिक प्रयोग गरिएको भाषाहरू", el: "Οι περισσότερο χρησιμοποιούμενες γλώσσες", ro: "Cele Mai Folosite Limbaje", ru: "Наиболее используемые языки", "uk-ua": "Найбільш використовувані мови", id: "Bahasa Yang Paling Banyak Digunakan", ml: "കൂടുതൽ ഉപയോഗിച്ച ഭാഷകൾ", my: "အများဆုံးအသုံးပြုသောဘာသာစကားများ", ta: `அதிகம் பயன்படுத்தப்படும் மொழிகள்`, sk: "Najviac používané jazyky", tr: "En Çok Kullanılan Diller", pl: "Najczęściej używane języki", uz: "Eng koʻp ishlatiladigan tillar", vi: "Ngôn Ngữ Thường Sử Dụng", se: "Mest använda språken", he: "השפות הכי משומשות", fil: "Mga Pinakamadalas na Ginagamit na Wika", th: "ภาษาที่ใช้บ่อยที่สุด", sr: "Најкоришћенији језици", "sr-latn": "Najkorišćeniji jezici", no: "Mest brukte språk", }, "langcard.nodata": { en: "No languages data.", ar: "لا توجد بيانات للغات.", az: "Dil məlumatı yoxdur.", ca: "Sense dades d'idiomes",
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
true
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/cards/repo.js
src/cards/repo.js
// @ts-check import { Card } from "../common/Card.js"; import { getCardColors } from "../common/color.js"; import { kFormatter, wrapTextMultiline } from "../common/fmt.js"; import { encodeHTML } from "../common/html.js"; import { I18n } from "../common/I18n.js"; import { icons } from "../common/icons.js"; import { clampValue, parseEmojis } from "../common/ops.js"; import { flexLayout, measureText, iconWithLabel, createLanguageNode, } from "../common/render.js"; import { repoCardLocales } from "../translations.js"; const ICON_SIZE = 16; const DESCRIPTION_LINE_WIDTH = 59; const DESCRIPTION_MAX_LINES = 3; /** * Retrieves the repository description and wraps it to fit the card width. * * @param {string} label The repository description. * @param {string} textColor The color of the text. * @returns {string} Wrapped repo description SVG object. */ const getBadgeSVG = (label, textColor) => ` <g data-testid="badge" class="badge" transform="translate(320, -18)"> <rect stroke="${textColor}" stroke-width="1" width="70" height="20" x="-12" y="-14" ry="10" rx="10"></rect> <text x="23" y="-5" alignment-baseline="central" dominant-baseline="central" text-anchor="middle" fill="${textColor}" > ${label} </text> </g> `; /** * @typedef {import("../fetchers/types").RepositoryData} RepositoryData Repository data. * @typedef {import("./types").RepoCardOptions} RepoCardOptions Repo card options. */ /** * Renders repository card details. * * @param {RepositoryData} repo Repository data. * @param {Partial<RepoCardOptions>} options Card options. * @returns {string} Repository card SVG object. */ const renderRepoCard = (repo, options = {}) => { const { name, nameWithOwner, description, primaryLanguage, isArchived, isTemplate, starCount, forkCount, } = repo; const { hide_border = false, title_color, icon_color, text_color, bg_color, show_owner = false, theme = "default_repocard", border_radius, border_color, locale, description_lines_count, } = options; const lineHeight = 10; const header = show_owner ? nameWithOwner : name; const langName = (primaryLanguage && primaryLanguage.name) || "Unspecified"; const langColor = (primaryLanguage && primaryLanguage.color) || "#333"; const descriptionMaxLines = description_lines_count ? clampValue(description_lines_count, 1, DESCRIPTION_MAX_LINES) : DESCRIPTION_MAX_LINES; const desc = parseEmojis(description || "No description provided"); const multiLineDescription = wrapTextMultiline( desc, DESCRIPTION_LINE_WIDTH, descriptionMaxLines, ); const descriptionLinesCount = description_lines_count ? clampValue(description_lines_count, 1, DESCRIPTION_MAX_LINES) : multiLineDescription.length; const descriptionSvg = multiLineDescription .map((line) => `<tspan dy="1.2em" x="25">${encodeHTML(line)}</tspan>`) .join(""); const height = (descriptionLinesCount > 1 ? 120 : 110) + descriptionLinesCount * lineHeight; const i18n = new I18n({ locale, translations: repoCardLocales, }); // returns theme based colors with proper overrides and defaults const colors = getCardColors({ title_color, icon_color, text_color, bg_color, border_color, theme, }); const svgLanguage = primaryLanguage ? createLanguageNode(langName, langColor) : ""; const totalStars = kFormatter(starCount); const totalForks = kFormatter(forkCount); const svgStars = iconWithLabel( icons.star, totalStars, "stargazers", ICON_SIZE, ); const svgForks = iconWithLabel( icons.fork, totalForks, "forkcount", ICON_SIZE, ); const starAndForkCount = flexLayout({ items: [svgLanguage, svgStars, svgForks], sizes: [ measureText(langName, 12), ICON_SIZE + measureText(`${totalStars}`, 12), ICON_SIZE + measureText(`${totalForks}`, 12), ], gap: 25, }).join(""); const card = new Card({ defaultTitle: header.length > 35 ? `${header.slice(0, 35)}...` : header, titlePrefixIcon: icons.contribs, width: 400, height, border_radius, colors, }); card.disableAnimations(); card.setHideBorder(hide_border); card.setHideTitle(false); card.setCSS(` .description { font: 400 13px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${colors.textColor} } .gray { font: 400 12px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${colors.textColor} } .icon { fill: ${colors.iconColor} } .badge { font: 600 11px 'Segoe UI', Ubuntu, Sans-Serif; } .badge rect { opacity: 0.2 } `); return card.render(` ${ isTemplate ? // @ts-ignore getBadgeSVG(i18n.t("repocard.template"), colors.textColor) : isArchived ? // @ts-ignore getBadgeSVG(i18n.t("repocard.archived"), colors.textColor) : "" } <text class="description" x="25" y="-5"> ${descriptionSvg} </text> <g transform="translate(30, ${height - 75})"> ${starAndForkCount} </g> `); }; export { renderRepoCard }; export default renderRepoCard;
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/cards/gist.js
src/cards/gist.js
// @ts-check import { measureText, flexLayout, iconWithLabel, createLanguageNode, } from "../common/render.js"; import Card from "../common/Card.js"; import { getCardColors } from "../common/color.js"; import { kFormatter, wrapTextMultiline } from "../common/fmt.js"; import { encodeHTML } from "../common/html.js"; import { icons } from "../common/icons.js"; import { parseEmojis } from "../common/ops.js"; /** Import language colors. * * @description Here we use the workaround found in * https://stackoverflow.com/questions/66726365/how-should-i-import-json-in-node * since vercel is using v16.14.0 which does not yet support json imports without the * --experimental-json-modules flag. */ import { createRequire } from "module"; const require = createRequire(import.meta.url); const languageColors = require("../common/languageColors.json"); // now works const ICON_SIZE = 16; const CARD_DEFAULT_WIDTH = 400; const HEADER_MAX_LENGTH = 35; /** * @typedef {import('./types').GistCardOptions} GistCardOptions Gist card options. * @typedef {import('../fetchers/types').GistData} GistData Gist data. */ /** * Render gist card. * * @param {GistData} gistData Gist data. * @param {Partial<GistCardOptions>} options Gist card options. * @returns {string} Gist card. */ const renderGistCard = (gistData, options = {}) => { const { name, nameWithOwner, description, language, starsCount, forksCount } = gistData; const { title_color, icon_color, text_color, bg_color, theme, border_radius, border_color, show_owner = false, hide_border = false, } = options; // returns theme based colors with proper overrides and defaults const { titleColor, textColor, iconColor, bgColor, borderColor } = getCardColors({ title_color, icon_color, text_color, bg_color, border_color, theme, }); const lineWidth = 59; const linesLimit = 10; const desc = parseEmojis(description || "No description provided"); const multiLineDescription = wrapTextMultiline(desc, lineWidth, linesLimit); const descriptionLines = multiLineDescription.length; const descriptionSvg = multiLineDescription .map((line) => `<tspan dy="1.2em" x="25">${encodeHTML(line)}</tspan>`) .join(""); const lineHeight = descriptionLines > 3 ? 12 : 10; const height = (descriptionLines > 1 ? 120 : 110) + descriptionLines * lineHeight; const totalStars = kFormatter(starsCount); const totalForks = kFormatter(forksCount); const svgStars = iconWithLabel( icons.star, totalStars, "starsCount", ICON_SIZE, ); const svgForks = iconWithLabel( icons.fork, totalForks, "forksCount", ICON_SIZE, ); const languageName = language || "Unspecified"; // @ts-ignore const languageColor = languageColors[languageName] || "#858585"; const svgLanguage = createLanguageNode(languageName, languageColor); const starAndForkCount = flexLayout({ items: [svgLanguage, svgStars, svgForks], sizes: [ measureText(languageName, 12), ICON_SIZE + measureText(`${totalStars}`, 12), ICON_SIZE + measureText(`${totalForks}`, 12), ], gap: 25, }).join(""); const header = show_owner ? nameWithOwner : name; const card = new Card({ defaultTitle: header.length > HEADER_MAX_LENGTH ? `${header.slice(0, HEADER_MAX_LENGTH)}...` : header, titlePrefixIcon: icons.gist, width: CARD_DEFAULT_WIDTH, height, border_radius, colors: { titleColor, textColor, iconColor, bgColor, borderColor, }, }); card.setCSS(` .description { font: 400 13px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor} } .gray { font: 400 12px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor} } .icon { fill: ${iconColor} } `); card.setHideBorder(hide_border); return card.render(` <text class="description" x="25" y="-5"> ${descriptionSvg} </text> <g transform="translate(30, ${height - 75})"> ${starAndForkCount} </g> `); }; export { renderGistCard, HEADER_MAX_LENGTH }; export default renderGistCard;
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/cards/index.js
src/cards/index.js
export { renderRepoCard } from "./repo.js"; export { renderStatsCard } from "./stats.js"; export { renderTopLanguages } from "./top-languages.js"; export { renderWakatimeCard } from "./wakatime.js";
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/cards/wakatime.js
src/cards/wakatime.js
// @ts-check import { Card } from "../common/Card.js"; import { getCardColors } from "../common/color.js"; import { I18n } from "../common/I18n.js"; import { clampValue, lowercaseTrim } from "../common/ops.js"; import { createProgressNode, flexLayout } from "../common/render.js"; import { wakatimeCardLocales } from "../translations.js"; /** Import language colors. * * @description Here we use the workaround found in * https://stackoverflow.com/questions/66726365/how-should-i-import-json-in-node * since vercel is using v16.14.0 which does not yet support json imports without the * --experimental-json-modules flag. */ import { createRequire } from "module"; const require = createRequire(import.meta.url); const languageColors = require("../common/languageColors.json"); // now works const DEFAULT_CARD_WIDTH = 495; const MIN_CARD_WIDTH = 250; const COMPACT_LAYOUT_MIN_WIDTH = 400; const DEFAULT_LINE_HEIGHT = 25; const PROGRESSBAR_PADDING = 130; const HIDDEN_PROGRESSBAR_PADDING = 170; const COMPACT_LAYOUT_PROGRESSBAR_PADDING = 25; const TOTAL_TEXT_WIDTH = 275; /** * Creates the no coding activity SVG node. * * @param {object} props The function properties. * @param {string} props.color No coding activity text color. * @param {string} props.text No coding activity translated text. * @returns {string} No coding activity SVG node string. */ const noCodingActivityNode = ({ color, text }) => { return ` <text x="25" y="11" class="stat bold" fill="${color}">${text}</text> `; }; /** * @typedef {import('../fetchers/types').WakaTimeLang} WakaTimeLang */ /** * Format language value. * * @param {Object} args The function arguments. * @param {WakaTimeLang} args.lang The language object. * @param {"time" | "percent"} args.display_format The display format of the language node. * @returns {string} The formatted language value. */ const formatLanguageValue = ({ display_format, lang }) => { return display_format === "percent" ? `${lang.percent.toFixed(2).toString()} %` : lang.text; }; /** * Create compact WakaTime layout. * * @param {Object} args The function arguments. * @param {WakaTimeLang} args.lang The languages array. * @param {number} args.x The x position of the language node. * @param {number} args.y The y position of the language node. * @param {"time" | "percent"} args.display_format The display format of the language node. * @returns {string} The compact layout language SVG node. */ const createCompactLangNode = ({ lang, x, y, display_format }) => { // @ts-ignore const color = languageColors[lang.name] || "#858585"; const value = formatLanguageValue({ display_format, lang }); return ` <g transform="translate(${x}, ${y})"> <circle cx="5" cy="6" r="5" fill="${color}" /> <text data-testid="lang-name" x="15" y="10" class='lang-name'> ${lang.name} - ${value} </text> </g> `; }; /** * Create WakaTime language text node item. * * @param {Object} args The function arguments. * @param {WakaTimeLang[]} args.langs The language objects. * @param {number} args.y The y position of the language node. * @param {"time" | "percent"} args.display_format The display format of the language node. * @param {number} args.card_width Width in px of the card. * @returns {string[]} The language text node items. */ const createLanguageTextNode = ({ langs, y, display_format, card_width }) => { const LEFT_X = 25; const RIGHT_X_BASE = 230; const rightOffset = (card_width - DEFAULT_CARD_WIDTH) / 2; const RIGHT_X = RIGHT_X_BASE + rightOffset; return langs.map((lang, index) => { const isLeft = index % 2 === 0; return createCompactLangNode({ lang, x: isLeft ? LEFT_X : RIGHT_X, y: y + DEFAULT_LINE_HEIGHT * Math.floor(index / 2), display_format, }); }); }; /** * Create WakaTime text item. * * @param {Object} args The function arguments. * @param {string} args.id The id of the text node item. * @param {string} args.label The label of the text node item. * @param {string} args.value The value of the text node item. * @param {number} args.index The index of the text node item. * @param {number} args.percent Percentage of the text node item. * @param {boolean=} args.hideProgress Whether to hide the progress bar. * @param {string} args.progressBarColor The color of the progress bar. * @param {string} args.progressBarBackgroundColor The color of the progress bar background. * @param {number} args.progressBarWidth The width of the progress bar. * @returns {string} The text SVG node. */ const createTextNode = ({ id, label, value, index, percent, hideProgress, progressBarColor, progressBarBackgroundColor, progressBarWidth, }) => { const staggerDelay = (index + 3) * 150; const cardProgress = hideProgress ? null : createProgressNode({ x: 110, y: 4, progress: percent, color: progressBarColor, width: progressBarWidth, // @ts-ignore name: label, progressBarBackgroundColor, delay: staggerDelay + 300, }); return ` <g class="stagger" style="animation-delay: ${staggerDelay}ms" transform="translate(25, 0)"> <text class="stat bold" y="12.5" data-testid="${id}">${label}:</text> <text class="stat" x="${hideProgress ? HIDDEN_PROGRESSBAR_PADDING : PROGRESSBAR_PADDING + progressBarWidth}" y="12.5" >${value}</text> ${cardProgress} </g> `; }; /** * Recalculating percentages so that, compact layout's progress bar does not break when * hiding languages. * * @param {WakaTimeLang[]} languages The languages array. * @returns {void} The recalculated languages array. */ const recalculatePercentages = (languages) => { const totalSum = languages.reduce( (totalSum, language) => totalSum + language.percent, 0, ); const weight = +(100 / totalSum).toFixed(2); languages.forEach((language) => { language.percent = +(language.percent * weight).toFixed(2); }); }; /** * Retrieves CSS styles for a card. * * @param {Object} colors The colors to use for the card. * @param {string} colors.titleColor The title color. * @param {string} colors.textColor The text color. * @returns {string} Card CSS styles. */ const getStyles = ({ // eslint-disable-next-line no-unused-vars titleColor, textColor, }) => { return ` .stat { font: 600 14px 'Segoe UI', Ubuntu, "Helvetica Neue", Sans-Serif; fill: ${textColor}; } @supports(-moz-appearance: auto) { /* Selector detects Firefox */ .stat { font-size:12px; } } .stagger { opacity: 0; animation: fadeInAnimation 0.3s ease-in-out forwards; } .not_bold { font-weight: 400 } .bold { font-weight: 700 } `; }; /** * Normalize incoming width (string or number) and clamp to minimum. * * @param {Object} args The function arguments. * @param {WakaTimeOptions["layout"] | undefined} args.layout The incoming layout value. * @param {number|undefined} args.value The incoming width value. * @returns {number} The normalized width value. */ const normalizeCardWidth = ({ value, layout }) => { if (value === undefined || value === null || isNaN(value)) { return DEFAULT_CARD_WIDTH; } return Math.max( layout === "compact" ? COMPACT_LAYOUT_MIN_WIDTH : MIN_CARD_WIDTH, value, ); }; /** * @typedef {import('../fetchers/types').WakaTimeData} WakaTimeData * @typedef {import('./types').WakaTimeOptions} WakaTimeOptions */ /** * Renders WakaTime card. * * @param {Partial<WakaTimeData>} stats WakaTime stats. * @param {Partial<WakaTimeOptions>} options Card options. * @returns {string} WakaTime card SVG. */ const renderWakatimeCard = (stats = {}, options = { hide: [] }) => { let { languages = [] } = stats; const { hide_title = false, hide_border = false, card_width, hide, line_height = DEFAULT_LINE_HEIGHT, title_color, icon_color, text_color, bg_color, theme = "default", hide_progress, custom_title, locale, layout, langs_count = languages.length, border_radius, border_color, display_format = "time", disable_animations, } = options; const normalizedWidth = normalizeCardWidth({ value: card_width, layout }); const shouldHideLangs = Array.isArray(hide) && hide.length > 0; if (shouldHideLangs) { const languagesToHide = new Set(hide.map((lang) => lowercaseTrim(lang))); languages = languages.filter( (lang) => !languagesToHide.has(lowercaseTrim(lang.name)), ); } // Since the percentages are sorted in descending order, we can just // slice from the beginning without sorting. languages = languages.slice(0, langs_count); recalculatePercentages(languages); const i18n = new I18n({ locale, translations: wakatimeCardLocales, }); const lheight = parseInt(String(line_height), 10); const langsCount = clampValue(langs_count, 1, langs_count); // returns theme based colors with proper overrides and defaults const { titleColor, textColor, iconColor, bgColor, borderColor } = getCardColors({ title_color, icon_color, text_color, bg_color, border_color, theme, }); const filteredLanguages = languages .filter((language) => language.hours || language.minutes) .slice(0, langsCount); // Calculate the card height depending on how many items there are // but if rank circle is visible clamp the minimum height to `150` let height = Math.max(45 + (filteredLanguages.length + 1) * lheight, 150); const cssStyles = getStyles({ titleColor, textColor, }); let finalLayout = ""; // RENDER COMPACT LAYOUT if (layout === "compact") { const width = normalizedWidth - 5; height = 90 + Math.round(filteredLanguages.length / 2) * DEFAULT_LINE_HEIGHT; // progressOffset holds the previous language's width and used to offset the next language // so that we can stack them one after another, like this: [--][----][---] let progressOffset = 0; const compactProgressBar = filteredLanguages .map((language) => { const progress = ((width - COMPACT_LAYOUT_PROGRESSBAR_PADDING) * language.percent) / 100; // @ts-ignore const languageColor = languageColors[language.name] || "#858585"; const output = ` <rect mask="url(#rect-mask)" data-testid="lang-progress" x="${progressOffset}" y="0" width="${progress}" height="8" fill="${languageColor}" /> `; progressOffset += progress; return output; }) .join(""); finalLayout = ` <mask id="rect-mask"> <rect x="${COMPACT_LAYOUT_PROGRESSBAR_PADDING}" y="0" width="${width - 2 * COMPACT_LAYOUT_PROGRESSBAR_PADDING}" height="8" fill="white" rx="5" /> </mask> ${compactProgressBar} ${ filteredLanguages.length ? createLanguageTextNode({ y: 25, langs: filteredLanguages, display_format, card_width: normalizedWidth, }).join("") : noCodingActivityNode({ // @ts-ignore color: textColor, text: stats.is_coding_activity_visible ? stats.is_other_usage_visible ? i18n.t("wakatimecard.nocodingactivity") : i18n.t("wakatimecard.nocodedetails") : i18n.t("wakatimecard.notpublic"), }) } `; } else { finalLayout = flexLayout({ items: filteredLanguages.length ? filteredLanguages.map((language, index) => { return createTextNode({ id: language.name, label: language.name, value: formatLanguageValue({ display_format, lang: language }), index, percent: language.percent, // @ts-ignore progressBarColor: titleColor, // @ts-ignore progressBarBackgroundColor: textColor, hideProgress: hide_progress, progressBarWidth: normalizedWidth - TOTAL_TEXT_WIDTH, }); }) : [ noCodingActivityNode({ // @ts-ignore color: textColor, text: stats.is_coding_activity_visible ? stats.is_other_usage_visible ? i18n.t("wakatimecard.nocodingactivity") : i18n.t("wakatimecard.nocodedetails") : i18n.t("wakatimecard.notpublic"), }), ], gap: lheight, direction: "column", }).join(""); } // Get title range text let titleText = i18n.t("wakatimecard.title"); switch (stats.range) { case "last_7_days": titleText += ` (${i18n.t("wakatimecard.last7days")})`; break; case "last_year": titleText += ` (${i18n.t("wakatimecard.lastyear")})`; break; } const card = new Card({ customTitle: custom_title, defaultTitle: titleText, width: normalizedWidth, height, border_radius, colors: { titleColor, textColor, iconColor, bgColor, borderColor, }, }); if (disable_animations) { card.disableAnimations(); } card.setHideBorder(hide_border); card.setHideTitle(hide_title); card.setCSS( ` ${cssStyles} @keyframes slideInAnimation { from { width: 0; } to { width: calc(100%-100px); } } @keyframes growWidthAnimation { from { width: 0; } to { width: 100%; } } .lang-name { font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor} } #rect-mask rect{ animation: slideInAnimation 1s ease-in-out forwards; } .lang-progress{ animation: growWidthAnimation 0.6s ease-in-out forwards; } `, ); return card.render(` <svg x="0" y="0" width="100%"> ${finalLayout} </svg> `); }; export { renderWakatimeCard }; export default renderWakatimeCard;
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/cards/top-languages.js
src/cards/top-languages.js
// @ts-check import { Card } from "../common/Card.js"; import { getCardColors } from "../common/color.js"; import { formatBytes } from "../common/fmt.js"; import { I18n } from "../common/I18n.js"; import { chunkArray, clampValue, lowercaseTrim } from "../common/ops.js"; import { createProgressNode, flexLayout, measureText, } from "../common/render.js"; import { langCardLocales } from "../translations.js"; const DEFAULT_CARD_WIDTH = 300; const MIN_CARD_WIDTH = 280; const DEFAULT_LANG_COLOR = "#858585"; const CARD_PADDING = 25; const COMPACT_LAYOUT_BASE_HEIGHT = 90; const MAXIMUM_LANGS_COUNT = 20; const NORMAL_LAYOUT_DEFAULT_LANGS_COUNT = 5; const COMPACT_LAYOUT_DEFAULT_LANGS_COUNT = 6; const DONUT_LAYOUT_DEFAULT_LANGS_COUNT = 5; const PIE_LAYOUT_DEFAULT_LANGS_COUNT = 6; const DONUT_VERTICAL_LAYOUT_DEFAULT_LANGS_COUNT = 6; /** * @typedef {import("../fetchers/types").Lang} Lang */ /** * Retrieves the programming language whose name is the longest. * * @param {Lang[]} arr Array of programming languages. * @returns {{ name: string, size: number, color: string }} Longest programming language object. */ const getLongestLang = (arr) => arr.reduce( (savedLang, lang) => lang.name.length > savedLang.name.length ? lang : savedLang, { name: "", size: 0, color: "" }, ); /** * Convert degrees to radians. * * @param {number} angleInDegrees Angle in degrees. * @returns {number} Angle in radians. */ const degreesToRadians = (angleInDegrees) => angleInDegrees * (Math.PI / 180.0); /** * Convert radians to degrees. * * @param {number} angleInRadians Angle in radians. * @returns {number} Angle in degrees. */ const radiansToDegrees = (angleInRadians) => angleInRadians / (Math.PI / 180.0); /** * Convert polar coordinates to cartesian coordinates. * * @param {number} centerX Center x coordinate. * @param {number} centerY Center y coordinate. * @param {number} radius Radius of the circle. * @param {number} angleInDegrees Angle in degrees. * @returns {{x: number, y: number}} Cartesian coordinates. */ const polarToCartesian = (centerX, centerY, radius, angleInDegrees) => { const rads = degreesToRadians(angleInDegrees); return { x: centerX + radius * Math.cos(rads), y: centerY + radius * Math.sin(rads), }; }; /** * Convert cartesian coordinates to polar coordinates. * * @param {number} centerX Center x coordinate. * @param {number} centerY Center y coordinate. * @param {number} x Point x coordinate. * @param {number} y Point y coordinate. * @returns {{radius: number, angleInDegrees: number}} Polar coordinates. */ const cartesianToPolar = (centerX, centerY, x, y) => { const radius = Math.sqrt(Math.pow(x - centerX, 2) + Math.pow(y - centerY, 2)); let angleInDegrees = radiansToDegrees(Math.atan2(y - centerY, x - centerX)); if (angleInDegrees < 0) { angleInDegrees += 360; } return { radius, angleInDegrees }; }; /** * Calculates length of circle. * * @param {number} radius Radius of the circle. * @returns {number} The length of the circle. */ const getCircleLength = (radius) => { return 2 * Math.PI * radius; }; /** * Calculates height for the compact layout. * * @param {number} totalLangs Total number of languages. * @returns {number} Card height. */ const calculateCompactLayoutHeight = (totalLangs) => { return COMPACT_LAYOUT_BASE_HEIGHT + Math.round(totalLangs / 2) * 25; }; /** * Calculates height for the normal layout. * * @param {number} totalLangs Total number of languages. * @returns {number} Card height. */ const calculateNormalLayoutHeight = (totalLangs) => { return 45 + (totalLangs + 1) * 40; }; /** * Calculates height for the donut layout. * * @param {number} totalLangs Total number of languages. * @returns {number} Card height. */ const calculateDonutLayoutHeight = (totalLangs) => { return 215 + Math.max(totalLangs - 5, 0) * 32; }; /** * Calculates height for the donut vertical layout. * * @param {number} totalLangs Total number of languages. * @returns {number} Card height. */ const calculateDonutVerticalLayoutHeight = (totalLangs) => { return 300 + Math.round(totalLangs / 2) * 25; }; /** * Calculates height for the pie layout. * * @param {number} totalLangs Total number of languages. * @returns {number} Card height. */ const calculatePieLayoutHeight = (totalLangs) => { return 300 + Math.round(totalLangs / 2) * 25; }; /** * Calculates the center translation needed to keep the donut chart centred. * @param {number} totalLangs Total number of languages. * @returns {number} Donut center translation. */ const donutCenterTranslation = (totalLangs) => { return -45 + Math.max(totalLangs - 5, 0) * 16; }; /** * Trim top languages to lang_count while also hiding certain languages. * * @param {Record<string, Lang>} topLangs Top languages. * @param {number} langs_count Number of languages to show. * @param {string[]=} hide Languages to hide. * @returns {{ langs: Lang[], totalLanguageSize: number }} Trimmed top languages and total size. */ const trimTopLanguages = (topLangs, langs_count, hide) => { let langs = Object.values(topLangs); let langsToHide = {}; let langsCount = clampValue(langs_count, 1, MAXIMUM_LANGS_COUNT); // populate langsToHide map for quick lookup // while filtering out if (hide) { hide.forEach((langName) => { // @ts-ignore langsToHide[lowercaseTrim(langName)] = true; }); } // filter out languages to be hidden langs = langs .sort((a, b) => b.size - a.size) .filter((lang) => { // @ts-ignore return !langsToHide[lowercaseTrim(lang.name)]; }) .slice(0, langsCount); const totalLanguageSize = langs.reduce((acc, curr) => acc + curr.size, 0); return { langs, totalLanguageSize }; }; /** * Get display value corresponding to the format. * * @param {number} size Bytes size. * @param {number} percentages Percentage value. * @param {string} format Format of the stats. * @returns {string} Display value. */ const getDisplayValue = (size, percentages, format) => { return format === "bytes" ? formatBytes(size) : `${percentages.toFixed(2)}%`; }; /** * Create progress bar text item for a programming language. * * @param {object} props Function properties. * @param {number} props.width The card width * @param {string} props.color Color of the programming language. * @param {string} props.name Name of the programming language. * @param {number} props.size Size of the programming language. * @param {number} props.totalSize Total size of all languages. * @param {string} props.statsFormat Stats format. * @param {number} props.index Index of the programming language. * @returns {string} Programming language SVG node. */ const createProgressTextNode = ({ width, color, name, size, totalSize, statsFormat, index, }) => { const staggerDelay = (index + 3) * 150; const paddingRight = 95; const progressTextX = width - paddingRight + 10; const progressWidth = width - paddingRight; const progress = (size / totalSize) * 100; const displayValue = getDisplayValue(size, progress, statsFormat); return ` <g class="stagger" style="animation-delay: ${staggerDelay}ms"> <text data-testid="lang-name" x="2" y="15" class="lang-name">${name}</text> <text x="${progressTextX}" y="34" class="lang-name">${displayValue}</text> ${createProgressNode({ x: 0, y: 25, color, width: progressWidth, progress, progressBarBackgroundColor: "#ddd", delay: staggerDelay + 300, })} </g> `; }; /** * Creates compact text item for a programming language. * * @param {object} props Function properties. * @param {Lang} props.lang Programming language object. * @param {number} props.totalSize Total size of all languages. * @param {boolean=} props.hideProgress Whether to hide percentage. * @param {string=} props.statsFormat Stats format * @param {number} props.index Index of the programming language. * @returns {string} Compact layout programming language SVG node. */ const createCompactLangNode = ({ lang, totalSize, hideProgress, statsFormat = "percentages", index, }) => { const percentages = (lang.size / totalSize) * 100; const displayValue = getDisplayValue(lang.size, percentages, statsFormat); const staggerDelay = (index + 3) * 150; const color = lang.color || "#858585"; return ` <g class="stagger" style="animation-delay: ${staggerDelay}ms"> <circle cx="5" cy="6" r="5" fill="${color}" /> <text data-testid="lang-name" x="15" y="10" class='lang-name'> ${lang.name} ${hideProgress ? "" : displayValue} </text> </g> `; }; /** * Create compact languages text items for all programming languages. * * @param {object} props Function properties. * @param {Lang[]} props.langs Array of programming languages. * @param {number} props.totalSize Total size of all languages. * @param {boolean=} props.hideProgress Whether to hide percentage. * @param {string=} props.statsFormat Stats format * @returns {string} Programming languages SVG node. */ const createLanguageTextNode = ({ langs, totalSize, hideProgress, statsFormat, }) => { const longestLang = getLongestLang(langs); const chunked = chunkArray(langs, langs.length / 2); const layouts = chunked.map((array) => { // @ts-ignore const items = array.map((lang, index) => createCompactLangNode({ lang, totalSize, hideProgress, statsFormat, index, }), ); return flexLayout({ items, gap: 25, direction: "column", }).join(""); }); const percent = ((longestLang.size / totalSize) * 100).toFixed(2); const minGap = 150; const maxGap = 20 + measureText(`${longestLang.name} ${percent}%`, 11); return flexLayout({ items: layouts, gap: maxGap < minGap ? minGap : maxGap, }).join(""); }; /** * Create donut languages text items for all programming languages. * * @param {object} props Function properties. * @param {Lang[]} props.langs Array of programming languages. * @param {number} props.totalSize Total size of all languages. * @param {string} props.statsFormat Stats format * @returns {string} Donut layout programming language SVG node. */ const createDonutLanguagesNode = ({ langs, totalSize, statsFormat }) => { return flexLayout({ items: langs.map((lang, index) => { return createCompactLangNode({ lang, totalSize, hideProgress: false, statsFormat, index, }); }), gap: 32, direction: "column", }).join(""); }; /** * Renders the default language card layout. * * @param {Lang[]} langs Array of programming languages. * @param {number} width Card width. * @param {number} totalLanguageSize Total size of all languages. * @param {string} statsFormat Stats format. * @returns {string} Normal layout card SVG object. */ const renderNormalLayout = (langs, width, totalLanguageSize, statsFormat) => { return flexLayout({ items: langs.map((lang, index) => { return createProgressTextNode({ width, name: lang.name, color: lang.color || DEFAULT_LANG_COLOR, size: lang.size, totalSize: totalLanguageSize, statsFormat, index, }); }), gap: 40, direction: "column", }).join(""); }; /** * Renders the compact language card layout. * * @param {Lang[]} langs Array of programming languages. * @param {number} width Card width. * @param {number} totalLanguageSize Total size of all languages. * @param {boolean=} hideProgress Whether to hide progress bar. * @param {string} statsFormat Stats format. * @returns {string} Compact layout card SVG object. */ const renderCompactLayout = ( langs, width, totalLanguageSize, hideProgress, statsFormat = "percentages", ) => { const paddingRight = 50; const offsetWidth = width - paddingRight; // progressOffset holds the previous language's width and used to offset the next language // so that we can stack them one after another, like this: [--][----][---] let progressOffset = 0; const compactProgressBar = langs .map((lang) => { const percentage = parseFloat( ((lang.size / totalLanguageSize) * offsetWidth).toFixed(2), ); const progress = percentage < 10 ? percentage + 10 : percentage; const output = ` <rect mask="url(#rect-mask)" data-testid="lang-progress" x="${progressOffset}" y="0" width="${progress}" height="8" fill="${lang.color || "#858585"}" /> `; progressOffset += percentage; return output; }) .join(""); return ` ${ hideProgress ? "" : ` <mask id="rect-mask"> <rect x="0" y="0" width="${offsetWidth}" height="8" fill="white" rx="5"/> </mask> ${compactProgressBar} ` } <g transform="translate(0, ${hideProgress ? "0" : "25"})"> ${createLanguageTextNode({ langs, totalSize: totalLanguageSize, hideProgress, statsFormat, })} </g> `; }; /** * Renders donut vertical layout to display user's most frequently used programming languages. * * @param {Lang[]} langs Array of programming languages. * @param {number} totalLanguageSize Total size of all languages. * @param {string} statsFormat Stats format. * @returns {string} Compact layout card SVG object. */ const renderDonutVerticalLayout = (langs, totalLanguageSize, statsFormat) => { // Donut vertical chart radius and total length const radius = 80; const totalCircleLength = getCircleLength(radius); // SVG circles let circles = []; // Start indent for donut vertical chart parts let indent = 0; // Start delay coefficient for donut vertical chart parts let startDelayCoefficient = 1; // Generate each donut vertical chart part for (const lang of langs) { const percentage = (lang.size / totalLanguageSize) * 100; const circleLength = totalCircleLength * (percentage / 100); const delay = startDelayCoefficient * 100; circles.push(` <g class="stagger" style="animation-delay: ${delay}ms"> <circle cx="150" cy="100" r="${radius}" fill="transparent" stroke="${lang.color}" stroke-width="25" stroke-dasharray="${totalCircleLength}" stroke-dashoffset="${indent}" size="${percentage}" data-testid="lang-donut" /> </g> `); // Update the indent for the next part indent += circleLength; // Update the start delay coefficient for the next part startDelayCoefficient += 1; } return ` <svg data-testid="lang-items"> <g transform="translate(0, 0)"> <svg data-testid="donut"> ${circles.join("")} </svg> </g> <g transform="translate(0, 220)"> <svg data-testid="lang-names" x="${CARD_PADDING}"> ${createLanguageTextNode({ langs, totalSize: totalLanguageSize, hideProgress: false, statsFormat, })} </svg> </g> </svg> `; }; /** * Renders pie layout to display user's most frequently used programming languages. * * @param {Lang[]} langs Array of programming languages. * @param {number} totalLanguageSize Total size of all languages. * @param {string} statsFormat Stats format. * @returns {string} Compact layout card SVG object. */ const renderPieLayout = (langs, totalLanguageSize, statsFormat) => { // Pie chart radius and center coordinates const radius = 90; const centerX = 150; const centerY = 100; // Start angle for the pie chart parts let startAngle = 0; // Start delay coefficient for the pie chart parts let startDelayCoefficient = 1; // SVG paths const paths = []; // Generate each pie chart part for (const lang of langs) { if (langs.length === 1) { paths.push(` <circle cx="${centerX}" cy="${centerY}" r="${radius}" stroke="none" fill="${lang.color}" data-testid="lang-pie" size="100" /> `); break; } const langSizePart = lang.size / totalLanguageSize; const percentage = langSizePart * 100; // Calculate the angle for the current part const angle = langSizePart * 360; // Calculate the end angle const endAngle = startAngle + angle; // Calculate the coordinates of the start and end points of the arc const startPoint = polarToCartesian(centerX, centerY, radius, startAngle); const endPoint = polarToCartesian(centerX, centerY, radius, endAngle); // Determine the large arc flag based on the angle const largeArcFlag = angle > 180 ? 1 : 0; // Calculate delay const delay = startDelayCoefficient * 100; // SVG arc markup paths.push(` <g class="stagger" style="animation-delay: ${delay}ms"> <path data-testid="lang-pie" size="${percentage}" d="M ${centerX} ${centerY} L ${startPoint.x} ${startPoint.y} A ${radius} ${radius} 0 ${largeArcFlag} 1 ${endPoint.x} ${endPoint.y} Z" fill="${lang.color}" /> </g> `); // Update the start angle for the next part startAngle = endAngle; // Update the start delay coefficient for the next part startDelayCoefficient += 1; } return ` <svg data-testid="lang-items"> <g transform="translate(0, 0)"> <svg data-testid="pie"> ${paths.join("")} </svg> </g> <g transform="translate(0, 220)"> <svg data-testid="lang-names" x="${CARD_PADDING}"> ${createLanguageTextNode({ langs, totalSize: totalLanguageSize, hideProgress: false, statsFormat, })} </svg> </g> </svg> `; }; /** * Creates the SVG paths for the language donut chart. * * @param {number} cx Donut center x-position. * @param {number} cy Donut center y-position. * @param {number} radius Donut arc Radius. * @param {number[]} percentages Array with donut section percentages. * @returns {{d: string, percent: number}[]} Array of svg path elements */ const createDonutPaths = (cx, cy, radius, percentages) => { const paths = []; let startAngle = 0; let endAngle = 0; const totalPercent = percentages.reduce((acc, curr) => acc + curr, 0); for (let i = 0; i < percentages.length; i++) { const tmpPath = {}; let percent = parseFloat( ((percentages[i] / totalPercent) * 100).toFixed(2), ); endAngle = 3.6 * percent + startAngle; const startPoint = polarToCartesian(cx, cy, radius, endAngle - 90); // rotate donut 90 degrees counter-clockwise. const endPoint = polarToCartesian(cx, cy, radius, startAngle - 90); // rotate donut 90 degrees counter-clockwise. const largeArc = endAngle - startAngle <= 180 ? 0 : 1; tmpPath.percent = percent; tmpPath.d = `M ${startPoint.x} ${startPoint.y} A ${radius} ${radius} 0 ${largeArc} 0 ${endPoint.x} ${endPoint.y}`; paths.push(tmpPath); startAngle = endAngle; } return paths; }; /** * Renders the donut language card layout. * * @param {Lang[]} langs Array of programming languages. * @param {number} width Card width. * @param {number} totalLanguageSize Total size of all languages. * @param {string} statsFormat Stats format. * @returns {string} Donut layout card SVG object. */ const renderDonutLayout = (langs, width, totalLanguageSize, statsFormat) => { const centerX = width / 3; const centerY = width / 3; const radius = centerX - 60; const strokeWidth = 12; const colors = langs.map((lang) => lang.color); const langsPercents = langs.map((lang) => parseFloat(((lang.size / totalLanguageSize) * 100).toFixed(2)), ); const langPaths = createDonutPaths(centerX, centerY, radius, langsPercents); const donutPaths = langs.length === 1 ? `<circle cx="${centerX}" cy="${centerY}" r="${radius}" stroke="${colors[0]}" fill="none" stroke-width="${strokeWidth}" data-testid="lang-donut" size="100"/>` : langPaths .map((section, index) => { const staggerDelay = (index + 3) * 100; const delay = staggerDelay + 300; const output = ` <g class="stagger" style="animation-delay: ${delay}ms"> <path data-testid="lang-donut" size="${section.percent}" d="${section.d}" stroke="${colors[index]}" fill="none" stroke-width="${strokeWidth}"> </path> </g> `; return output; }) .join(""); const donut = `<svg width="${width}" height="${width}">${donutPaths}</svg>`; return ` <g transform="translate(0, 0)"> <g transform="translate(0, 0)"> ${createDonutLanguagesNode({ langs, totalSize: totalLanguageSize, statsFormat })} </g> <g transform="translate(125, ${donutCenterTranslation(langs.length)})"> ${donut} </g> </g> `; }; /** * @typedef {import("./types").TopLangOptions} TopLangOptions * @typedef {TopLangOptions["layout"]} Layout */ /** * Creates the no languages data SVG node. * * @param {object} props Object with function properties. * @param {string} props.color No languages data text color. * @param {string} props.text No languages data translated text. * @param {Layout | undefined} props.layout Card layout. * @returns {string} No languages data SVG node string. */ const noLanguagesDataNode = ({ color, text, layout }) => { return ` <text x="${ layout === "pie" || layout === "donut-vertical" ? CARD_PADDING : 0 }" y="11" class="stat bold" fill="${color}">${text}</text> `; }; /** * Get default languages count for provided card layout. * * @param {object} props Function properties. * @param {Layout=} props.layout Input layout string. * @param {boolean=} props.hide_progress Input hide_progress parameter value. * @returns {number} Default languages count for input layout. */ const getDefaultLanguagesCountByLayout = ({ layout, hide_progress }) => { if (layout === "compact" || hide_progress === true) { return COMPACT_LAYOUT_DEFAULT_LANGS_COUNT; } else if (layout === "donut") { return DONUT_LAYOUT_DEFAULT_LANGS_COUNT; } else if (layout === "donut-vertical") { return DONUT_VERTICAL_LAYOUT_DEFAULT_LANGS_COUNT; } else if (layout === "pie") { return PIE_LAYOUT_DEFAULT_LANGS_COUNT; } else { return NORMAL_LAYOUT_DEFAULT_LANGS_COUNT; } }; /** * @typedef {import('../fetchers/types').TopLangData} TopLangData */ /** * Renders card that display user's most frequently used programming languages. * * @param {TopLangData} topLangs User's most frequently used programming languages. * @param {Partial<TopLangOptions>} options Card options. * @returns {string} Language card SVG object. */ const renderTopLanguages = (topLangs, options = {}) => { const { hide_title = false, hide_border = false, card_width, title_color, text_color, bg_color, hide, hide_progress, theme, layout, custom_title, locale, langs_count = getDefaultLanguagesCountByLayout({ layout, hide_progress }), border_radius, border_color, disable_animations, stats_format = "percentages", } = options; const i18n = new I18n({ locale, translations: langCardLocales, }); const { langs, totalLanguageSize } = trimTopLanguages( topLangs, langs_count, hide, ); let width = card_width ? isNaN(card_width) ? DEFAULT_CARD_WIDTH : card_width < MIN_CARD_WIDTH ? MIN_CARD_WIDTH : card_width : DEFAULT_CARD_WIDTH; let height = calculateNormalLayoutHeight(langs.length); // returns theme based colors with proper overrides and defaults const colors = getCardColors({ title_color, text_color, bg_color, border_color, theme, }); let finalLayout = ""; if (langs.length === 0) { height = COMPACT_LAYOUT_BASE_HEIGHT; finalLayout = noLanguagesDataNode({ color: colors.textColor, text: i18n.t("langcard.nodata"), layout, }); } else if (layout === "pie") { height = calculatePieLayoutHeight(langs.length); finalLayout = renderPieLayout(langs, totalLanguageSize, stats_format); } else if (layout === "donut-vertical") { height = calculateDonutVerticalLayoutHeight(langs.length); finalLayout = renderDonutVerticalLayout( langs, totalLanguageSize, stats_format, ); } else if (layout === "compact" || hide_progress == true) { height = calculateCompactLayoutHeight(langs.length) + (hide_progress ? -25 : 0); finalLayout = renderCompactLayout( langs, width, totalLanguageSize, hide_progress, stats_format, ); } else if (layout === "donut") { height = calculateDonutLayoutHeight(langs.length); width = width + 50; // padding finalLayout = renderDonutLayout( langs, width, totalLanguageSize, stats_format, ); } else { finalLayout = renderNormalLayout( langs, width, totalLanguageSize, stats_format, ); } const card = new Card({ customTitle: custom_title, defaultTitle: i18n.t("langcard.title"), width, height, border_radius, colors, }); if (disable_animations) { card.disableAnimations(); } card.setHideBorder(hide_border); card.setHideTitle(hide_title); card.setCSS( ` @keyframes slideInAnimation { from { width: 0; } to { width: calc(100%-100px); } } @keyframes growWidthAnimation { from { width: 0; } to { width: 100%; } } .stat { font: 600 14px 'Segoe UI', Ubuntu, "Helvetica Neue", Sans-Serif; fill: ${colors.textColor}; } @supports(-moz-appearance: auto) { /* Selector detects Firefox */ .stat { font-size:12px; } } .bold { font-weight: 700 } .lang-name { font: 400 11px "Segoe UI", Ubuntu, Sans-Serif; fill: ${colors.textColor}; } .stagger { opacity: 0; animation: fadeInAnimation 0.3s ease-in-out forwards; } #rect-mask rect{ animation: slideInAnimation 1s ease-in-out forwards; } .lang-progress{ animation: growWidthAnimation 0.6s ease-in-out forwards; } `, ); if (layout === "pie" || layout === "donut-vertical") { return card.render(finalLayout); } return card.render(` <svg data-testid="lang-items" x="${CARD_PADDING}"> ${finalLayout} </svg> `); }; export { getLongestLang, degreesToRadians, radiansToDegrees, polarToCartesian, cartesianToPolar, getCircleLength, calculateCompactLayoutHeight, calculateNormalLayoutHeight, calculateDonutLayoutHeight, calculateDonutVerticalLayoutHeight, calculatePieLayoutHeight, donutCenterTranslation, trimTopLanguages, renderTopLanguages, MIN_CARD_WIDTH, getDefaultLanguagesCountByLayout, };
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/cards/stats.js
src/cards/stats.js
// @ts-check import { Card } from "../common/Card.js"; import { getCardColors } from "../common/color.js"; import { CustomError } from "../common/error.js"; import { kFormatter } from "../common/fmt.js"; import { I18n } from "../common/I18n.js"; import { icons, rankIcon } from "../common/icons.js"; import { clampValue } from "../common/ops.js"; import { flexLayout, measureText } from "../common/render.js"; import { statCardLocales, wakatimeCardLocales } from "../translations.js"; const CARD_MIN_WIDTH = 287; const CARD_DEFAULT_WIDTH = 287; const RANK_CARD_MIN_WIDTH = 420; const RANK_CARD_DEFAULT_WIDTH = 450; const RANK_ONLY_CARD_MIN_WIDTH = 290; const RANK_ONLY_CARD_DEFAULT_WIDTH = 290; /** * Long locales that need more space for text. Keep sorted alphabetically. * * @type {(keyof typeof wakatimeCardLocales["wakatimecard.title"])[]} */ const LONG_LOCALES = [ "az", "bg", "cs", "de", "el", "es", "fil", "fi", "fr", "hu", "id", "ja", "ml", "my", "nl", "pl", "pt-br", "pt-pt", "ru", "sr", "sr-latn", "sw", "ta", "uk-ua", "uz", "zh-tw", ]; /** * Create a stats card text item. * * @param {object} params Object that contains the createTextNode parameters. * @param {string} params.icon The icon to display. * @param {string} params.label The label to display. * @param {number} params.value The value to display. * @param {string} params.id The id of the stat. * @param {string=} params.unitSymbol The unit symbol of the stat. * @param {number} params.index The index of the stat. * @param {boolean} params.showIcons Whether to show icons. * @param {number} params.shiftValuePos Number of pixels the value has to be shifted to the right. * @param {boolean} params.bold Whether to bold the label. * @param {string} params.numberFormat The format of numbers on card. * @param {number=} params.numberPrecision The precision of numbers on card. * @returns {string} The stats card text item SVG object. */ const createTextNode = ({ icon, label, value, id, unitSymbol, index, showIcons, shiftValuePos, bold, numberFormat, numberPrecision, }) => { const precision = typeof numberPrecision === "number" && !isNaN(numberPrecision) ? clampValue(numberPrecision, 0, 2) : undefined; const kValue = numberFormat.toLowerCase() === "long" || id === "prs_merged_percentage" ? value : kFormatter(value, precision); const staggerDelay = (index + 3) * 150; const labelOffset = showIcons ? `x="25"` : ""; const iconSvg = showIcons ? ` <svg data-testid="icon" class="icon" viewBox="0 0 16 16" version="1.1" width="16" height="16"> ${icon} </svg> ` : ""; return ` <g class="stagger" style="animation-delay: ${staggerDelay}ms" transform="translate(25, 0)"> ${iconSvg} <text class="stat ${ bold ? " bold" : "not_bold" }" ${labelOffset} y="12.5">${label}:</text> <text class="stat ${bold ? " bold" : "not_bold"}" x="${(showIcons ? 140 : 120) + shiftValuePos}" y="12.5" data-testid="${id}" >${kValue}${unitSymbol ? ` ${unitSymbol}` : ""}</text> </g> `; }; /** * Calculates progress along the boundary of the circle, i.e. its circumference. * * @param {number} value The rank value to calculate progress for. * @returns {number} Progress value. */ const calculateCircleProgress = (value) => { const radius = 40; const c = Math.PI * (radius * 2); if (value < 0) { value = 0; } if (value > 100) { value = 100; } return ((100 - value) / 100) * c; }; /** * Retrieves the animation to display progress along the circumference of circle * from the beginning to the given value in a clockwise direction. * * @param {{progress: number}} progress The progress value to animate to. * @returns {string} Progress animation css. */ const getProgressAnimation = ({ progress }) => { return ` @keyframes rankAnimation { from { stroke-dashoffset: ${calculateCircleProgress(0)}; } to { stroke-dashoffset: ${calculateCircleProgress(progress)}; } } `; }; /** * Retrieves CSS styles for a card. * * @param {Object} colors The colors to use for the card. * @param {string} colors.titleColor The title color. * @param {string} colors.textColor The text color. * @param {string} colors.iconColor The icon color. * @param {string} colors.ringColor The ring color. * @param {boolean} colors.show_icons Whether to show icons. * @param {number} colors.progress The progress value to animate to. * @returns {string} Card CSS styles. */ const getStyles = ({ // eslint-disable-next-line no-unused-vars titleColor, textColor, iconColor, ringColor, show_icons, progress, }) => { return ` .stat { font: 600 14px 'Segoe UI', Ubuntu, "Helvetica Neue", Sans-Serif; fill: ${textColor}; } @supports(-moz-appearance: auto) { /* Selector detects Firefox */ .stat { font-size:12px; } } .stagger { opacity: 0; animation: fadeInAnimation 0.3s ease-in-out forwards; } .rank-text { font: 800 24px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor}; animation: scaleInAnimation 0.3s ease-in-out forwards; } .rank-percentile-header { font-size: 14px; } .rank-percentile-text { font-size: 16px; } .not_bold { font-weight: 400 } .bold { font-weight: 700 } .icon { fill: ${iconColor}; display: ${show_icons ? "block" : "none"}; } .rank-circle-rim { stroke: ${ringColor}; fill: none; stroke-width: 6; opacity: 0.2; } .rank-circle { stroke: ${ringColor}; stroke-dasharray: 250; fill: none; stroke-width: 6; stroke-linecap: round; opacity: 0.8; transform-origin: -10px 8px; transform: rotate(-90deg); animation: rankAnimation 1s forwards ease-in-out; } ${process.env.NODE_ENV === "test" ? "" : getProgressAnimation({ progress })} `; }; /** * Return the label for commits according to the selected options * * @param {boolean} include_all_commits Option to include all years * @param {number|undefined} commits_year Option to include only selected year * @param {I18n} i18n The I18n instance. * @returns {string} The label corresponding to the options. */ const getTotalCommitsYearLabel = (include_all_commits, commits_year, i18n) => include_all_commits ? "" : commits_year ? ` (${commits_year})` : ` (${i18n.t("wakatimecard.lastyear")})`; /** * @typedef {import('../fetchers/types').StatsData} StatsData * @typedef {import('./types').StatCardOptions} StatCardOptions */ /** * Renders the stats card. * * @param {StatsData} stats The stats data. * @param {Partial<StatCardOptions>} options The card options. * @returns {string} The stats card SVG object. */ const renderStatsCard = (stats, options = {}) => { const { name, totalStars, totalCommits, totalIssues, totalPRs, totalPRsMerged, mergedPRsPercentage, totalReviews, totalDiscussionsStarted, totalDiscussionsAnswered, contributedTo, rank, } = stats; const { hide = [], show_icons = false, hide_title = false, hide_border = false, card_width, hide_rank = false, include_all_commits = false, commits_year, line_height = 25, title_color, ring_color, icon_color, text_color, text_bold = true, bg_color, theme = "default", custom_title, border_radius, border_color, number_format = "short", number_precision, locale, disable_animations = false, rank_icon = "default", show = [], } = options; const lheight = parseInt(String(line_height), 10); // returns theme based colors with proper overrides and defaults const { titleColor, iconColor, textColor, bgColor, borderColor, ringColor } = getCardColors({ title_color, text_color, icon_color, bg_color, border_color, ring_color, theme, }); const apostrophe = /s$/i.test(name.trim()) ? "" : "s"; const i18n = new I18n({ locale, translations: { ...statCardLocales({ name, apostrophe }), ...wakatimeCardLocales, }, }); // Meta data for creating text nodes with createTextNode function const STATS = {}; STATS.stars = { icon: icons.star, label: i18n.t("statcard.totalstars"), value: totalStars, id: "stars", }; STATS.commits = { icon: icons.commits, label: `${i18n.t("statcard.commits")}${getTotalCommitsYearLabel( include_all_commits, commits_year, i18n, )}`, value: totalCommits, id: "commits", }; STATS.prs = { icon: icons.prs, label: i18n.t("statcard.prs"), value: totalPRs, id: "prs", }; if (show.includes("prs_merged")) { STATS.prs_merged = { icon: icons.prs_merged, label: i18n.t("statcard.prs-merged"), value: totalPRsMerged, id: "prs_merged", }; } if (show.includes("prs_merged_percentage")) { STATS.prs_merged_percentage = { icon: icons.prs_merged_percentage, label: i18n.t("statcard.prs-merged-percentage"), value: mergedPRsPercentage.toFixed( typeof number_precision === "number" && !isNaN(number_precision) ? clampValue(number_precision, 0, 2) : 2, ), id: "prs_merged_percentage", unitSymbol: "%", }; } if (show.includes("reviews")) { STATS.reviews = { icon: icons.reviews, label: i18n.t("statcard.reviews"), value: totalReviews, id: "reviews", }; } STATS.issues = { icon: icons.issues, label: i18n.t("statcard.issues"), value: totalIssues, id: "issues", }; if (show.includes("discussions_started")) { STATS.discussions_started = { icon: icons.discussions_started, label: i18n.t("statcard.discussions-started"), value: totalDiscussionsStarted, id: "discussions_started", }; } if (show.includes("discussions_answered")) { STATS.discussions_answered = { icon: icons.discussions_answered, label: i18n.t("statcard.discussions-answered"), value: totalDiscussionsAnswered, id: "discussions_answered", }; } STATS.contribs = { icon: icons.contribs, label: i18n.t("statcard.contribs"), value: contributedTo, id: "contribs", }; // @ts-ignore const isLongLocale = locale ? LONG_LOCALES.includes(locale) : false; // filter out hidden stats defined by user & create the text nodes const statItems = Object.keys(STATS) .filter((key) => !hide.includes(key)) .map((key, index) => { // @ts-ignore const stats = STATS[key]; // create the text nodes, and pass index so that we can calculate the line spacing return createTextNode({ icon: stats.icon, label: stats.label, value: stats.value, id: stats.id, unitSymbol: stats.unitSymbol, index, showIcons: show_icons, shiftValuePos: 79.01 + (isLongLocale ? 50 : 0), bold: text_bold, numberFormat: number_format, numberPrecision: number_precision, }); }); if (statItems.length === 0 && hide_rank) { throw new CustomError( "Could not render stats card.", "Either stats or rank are required.", ); } // Calculate the card height depending on how many items there are // but if rank circle is visible clamp the minimum height to `150` let height = Math.max( 45 + (statItems.length + 1) * lheight, hide_rank ? 0 : statItems.length ? 150 : 180, ); // the lower the user's percentile the better const progress = 100 - rank.percentile; const cssStyles = getStyles({ titleColor, ringColor, textColor, iconColor, show_icons, progress, }); const calculateTextWidth = () => { return measureText( custom_title ? custom_title : statItems.length ? i18n.t("statcard.title") : i18n.t("statcard.ranktitle"), ); }; /* When hide_rank=true, the minimum card width is 270 px + the title length and padding. When hide_rank=false, the minimum card_width is 340 px + the icon width (if show_icons=true). Numbers are picked by looking at existing dimensions on production. */ const iconWidth = show_icons && statItems.length ? 16 + /* padding */ 1 : 0; const minCardWidth = (hide_rank ? clampValue( 50 /* padding */ + calculateTextWidth() * 2, CARD_MIN_WIDTH, Infinity, ) : statItems.length ? RANK_CARD_MIN_WIDTH : RANK_ONLY_CARD_MIN_WIDTH) + iconWidth; const defaultCardWidth = (hide_rank ? CARD_DEFAULT_WIDTH : statItems.length ? RANK_CARD_DEFAULT_WIDTH : RANK_ONLY_CARD_DEFAULT_WIDTH) + iconWidth; let width = card_width ? isNaN(card_width) ? defaultCardWidth : card_width : defaultCardWidth; if (width < minCardWidth) { width = minCardWidth; } const card = new Card({ customTitle: custom_title, defaultTitle: statItems.length ? i18n.t("statcard.title") : i18n.t("statcard.ranktitle"), width, height, border_radius, colors: { titleColor, textColor, iconColor, bgColor, borderColor, }, }); card.setHideBorder(hide_border); card.setHideTitle(hide_title); card.setCSS(cssStyles); if (disable_animations) { card.disableAnimations(); } /** * Calculates the right rank circle translation values such that the rank circle * keeps respecting the following padding: * * width > RANK_CARD_DEFAULT_WIDTH: The default right padding of 70 px will be used. * width < RANK_CARD_DEFAULT_WIDTH: The left and right padding will be enlarged * equally from a certain minimum at RANK_CARD_MIN_WIDTH. * * @returns {number} - Rank circle translation value. */ const calculateRankXTranslation = () => { if (statItems.length) { const minXTranslation = RANK_CARD_MIN_WIDTH + iconWidth - 70; if (width > RANK_CARD_DEFAULT_WIDTH) { const xMaxExpansion = minXTranslation + (450 - minCardWidth) / 2; return xMaxExpansion + width - RANK_CARD_DEFAULT_WIDTH; } else { return minXTranslation + (width - minCardWidth) / 2; } } else { return width / 2 + 20 - 10; } }; // Conditionally rendered elements const rankCircle = hide_rank ? "" : `<g data-testid="rank-circle" transform="translate(${calculateRankXTranslation()}, ${ height / 2 - 50 })"> <circle class="rank-circle-rim" cx="-10" cy="8" r="40" /> <circle class="rank-circle" cx="-10" cy="8" r="40" /> <g class="rank-text"> ${rankIcon(rank_icon, rank?.level, rank?.percentile)} </g> </g>`; // Accessibility Labels const labels = Object.keys(STATS) .filter((key) => !hide.includes(key)) .map((key) => { // @ts-ignore const stats = STATS[key]; if (key === "commits") { return `${i18n.t("statcard.commits")} ${getTotalCommitsYearLabel( include_all_commits, commits_year, i18n, )} : ${stats.value}`; } return `${stats.label}: ${stats.value}`; }) .join(", "); card.setAccessibilityLabel({ title: `${card.title}, Rank: ${rank.level}`, desc: labels, }); return card.render(` ${rankCircle} <svg x="0" y="0"> ${flexLayout({ items: statItems, gap: lheight, direction: "column", }).join("")} </svg> `); }; export { renderStatsCard }; export default renderStatsCard;
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/common/envs.js
src/common/envs.js
// @ts-check const whitelist = process.env.WHITELIST ? process.env.WHITELIST.split(",") : undefined; const gistWhitelist = process.env.GIST_WHITELIST ? process.env.GIST_WHITELIST.split(",") : undefined; const excludeRepositories = process.env.EXCLUDE_REPO ? process.env.EXCLUDE_REPO.split(",") : []; export { whitelist, gistWhitelist, excludeRepositories };
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/common/ops.js
src/common/ops.js
// @ts-check import toEmoji from "emoji-name-map"; /** * Returns boolean if value is either "true" or "false" else the value as it is. * * @param {string | boolean} value The value to parse. * @returns {boolean | undefined } The parsed value. */ const parseBoolean = (value) => { if (typeof value === "boolean") { return value; } if (typeof value === "string") { if (value.toLowerCase() === "true") { return true; } else if (value.toLowerCase() === "false") { return false; } } return undefined; }; /** * Parse string to array of strings. * * @param {string} str The string to parse. * @returns {string[]} The array of strings. */ const parseArray = (str) => { if (!str) { return []; } return str.split(","); }; /** * Clamp the given number between the given range. * * @param {number} number The number to clamp. * @param {number} min The minimum value. * @param {number} max The maximum value. * @returns {number} The clamped number. */ const clampValue = (number, min, max) => { // @ts-ignore if (Number.isNaN(parseInt(number, 10))) { return min; } return Math.max(min, Math.min(number, max)); }; /** * Lowercase and trim string. * * @param {string} name String to lowercase and trim. * @returns {string} Lowercased and trimmed string. */ const lowercaseTrim = (name) => name.toLowerCase().trim(); /** * Split array of languages in two columns. * * @template T Language object. * @param {Array<T>} arr Array of languages. * @param {number} perChunk Number of languages per column. * @returns {Array<T>} Array of languages split in two columns. */ const chunkArray = (arr, perChunk) => { return arr.reduce((resultArray, item, index) => { const chunkIndex = Math.floor(index / perChunk); if (!resultArray[chunkIndex]) { // @ts-ignore resultArray[chunkIndex] = []; // start a new chunk } // @ts-ignore resultArray[chunkIndex].push(item); return resultArray; }, []); }; /** * Parse emoji from string. * * @param {string} str String to parse emoji from. * @returns {string} String with emoji parsed. */ const parseEmojis = (str) => { if (!str) { throw new Error("[parseEmoji]: str argument not provided"); } return str.replace(/:\w+:/gm, (emoji) => { return toEmoji.get(emoji) || ""; }); }; /** * Get diff in minutes between two dates. * * @param {Date} d1 First date. * @param {Date} d2 Second date. * @returns {number} Number of minutes between the two dates. */ const dateDiff = (d1, d2) => { const date1 = new Date(d1); const date2 = new Date(d2); const diff = date1.getTime() - date2.getTime(); return Math.round(diff / (1000 * 60)); }; export { parseBoolean, parseArray, clampValue, lowercaseTrim, chunkArray, parseEmojis, dateDiff, };
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/common/index.js
src/common/index.js
// @ts-check export { blacklist } from "./blacklist.js"; export { Card } from "./Card.js"; export { I18n } from "./I18n.js"; export { icons } from "./icons.js"; export { retryer } from "./retryer.js"; export { ERROR_CARD_LENGTH, renderError, flexLayout, measureText, } from "./render.js";
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/common/cache.js
src/common/cache.js
// @ts-check import { clampValue } from "./ops.js"; const MIN = 60; const HOUR = 60 * MIN; const DAY = 24 * HOUR; /** * Common durations in seconds. */ const DURATIONS = { ONE_MINUTE: MIN, FIVE_MINUTES: 5 * MIN, TEN_MINUTES: 10 * MIN, FIFTEEN_MINUTES: 15 * MIN, THIRTY_MINUTES: 30 * MIN, TWO_HOURS: 2 * HOUR, FOUR_HOURS: 4 * HOUR, SIX_HOURS: 6 * HOUR, EIGHT_HOURS: 8 * HOUR, TWELVE_HOURS: 12 * HOUR, ONE_DAY: DAY, TWO_DAY: 2 * DAY, SIX_DAY: 6 * DAY, TEN_DAY: 10 * DAY, }; /** * Common cache TTL values in seconds. */ const CACHE_TTL = { STATS_CARD: { DEFAULT: DURATIONS.ONE_DAY, MIN: DURATIONS.TWELVE_HOURS, MAX: DURATIONS.TWO_DAY, }, TOP_LANGS_CARD: { DEFAULT: DURATIONS.SIX_DAY, MIN: DURATIONS.TWO_DAY, MAX: DURATIONS.TEN_DAY, }, PIN_CARD: { DEFAULT: DURATIONS.TEN_DAY, MIN: DURATIONS.ONE_DAY, MAX: DURATIONS.TEN_DAY, }, GIST_CARD: { DEFAULT: DURATIONS.TWO_DAY, MIN: DURATIONS.ONE_DAY, MAX: DURATIONS.TEN_DAY, }, WAKATIME_CARD: { DEFAULT: DURATIONS.ONE_DAY, MIN: DURATIONS.TWELVE_HOURS, MAX: DURATIONS.TWO_DAY, }, ERROR: DURATIONS.TEN_MINUTES, }; /** * Resolves the cache seconds based on the requested, default, min, and max values. * * @param {Object} args The parameters object. * @param {number} args.requested The requested cache seconds. * @param {number} args.def The default cache seconds. * @param {number} args.min The minimum cache seconds. * @param {number} args.max The maximum cache seconds. * @returns {number} The resolved cache seconds. */ const resolveCacheSeconds = ({ requested, def, min, max }) => { let cacheSeconds = clampValue(isNaN(requested) ? def : requested, min, max); if (process.env.CACHE_SECONDS) { const envCacheSeconds = parseInt(process.env.CACHE_SECONDS, 10); if (!isNaN(envCacheSeconds)) { cacheSeconds = envCacheSeconds; } } return cacheSeconds; }; /** * Disables caching by setting appropriate headers on the response object. * * @param {any} res The response object. */ const disableCaching = (res) => { // Disable caching for browsers, shared caches/CDNs, and GitHub Camo. res.setHeader( "Cache-Control", "no-cache, no-store, must-revalidate, max-age=0, s-maxage=0", ); res.setHeader("Pragma", "no-cache"); res.setHeader("Expires", "0"); }; /** * Sets the Cache-Control headers on the response object. * * @param {any} res The response object. * @param {number} cacheSeconds The cache seconds to set in the headers. */ const setCacheHeaders = (res, cacheSeconds) => { if (cacheSeconds < 1 || process.env.NODE_ENV === "development") { disableCaching(res); return; } res.setHeader( "Cache-Control", `max-age=${cacheSeconds}, ` + `s-maxage=${cacheSeconds}, ` + `stale-while-revalidate=${DURATIONS.ONE_DAY}`, ); }; /** * Sets the Cache-Control headers for error responses on the response object. * * @param {any} res The response object. */ const setErrorCacheHeaders = (res) => { const envCacheSeconds = process.env.CACHE_SECONDS ? parseInt(process.env.CACHE_SECONDS, 10) : NaN; if ( (!isNaN(envCacheSeconds) && envCacheSeconds < 1) || process.env.NODE_ENV === "development" ) { disableCaching(res); return; } // Use lower cache period for errors. res.setHeader( "Cache-Control", `max-age=${CACHE_TTL.ERROR}, ` + `s-maxage=${CACHE_TTL.ERROR}, ` + `stale-while-revalidate=${DURATIONS.ONE_DAY}`, ); }; export { resolveCacheSeconds, setCacheHeaders, setErrorCacheHeaders, DURATIONS, CACHE_TTL, };
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/common/error.js
src/common/error.js
// @ts-check /** * @type {string} A general message to ask user to try again later. */ const TRY_AGAIN_LATER = "Please try again later"; /** * @type {Object<string, string>} A map of error types to secondary error messages. */ const SECONDARY_ERROR_MESSAGES = { MAX_RETRY: "You can deploy own instance or wait until public will be no longer limited", NO_TOKENS: "Please add an env variable called PAT_1 with your GitHub API token in vercel", USER_NOT_FOUND: "Make sure the provided username is not an organization", GRAPHQL_ERROR: TRY_AGAIN_LATER, GITHUB_REST_API_ERROR: TRY_AGAIN_LATER, WAKATIME_USER_NOT_FOUND: "Make sure you have a public WakaTime profile", }; /** * Custom error class to handle custom GRS errors. */ class CustomError extends Error { /** * Custom error constructor. * * @param {string} message Error message. * @param {string} type Error type. */ constructor(message, type) { super(message); this.type = type; this.secondaryMessage = SECONDARY_ERROR_MESSAGES[type] || type; } static MAX_RETRY = "MAX_RETRY"; static NO_TOKENS = "NO_TOKENS"; static USER_NOT_FOUND = "USER_NOT_FOUND"; static GRAPHQL_ERROR = "GRAPHQL_ERROR"; static GITHUB_REST_API_ERROR = "GITHUB_REST_API_ERROR"; static WAKATIME_ERROR = "WAKATIME_ERROR"; } /** * Missing query parameter class. */ class MissingParamError extends Error { /** * Missing query parameter error constructor. * * @param {string[]} missedParams An array of missing parameters names. * @param {string=} secondaryMessage Optional secondary message to display. */ constructor(missedParams, secondaryMessage) { const msg = `Missing params ${missedParams .map((p) => `"${p}"`) .join(", ")} make sure you pass the parameters in URL`; super(msg); this.missedParams = missedParams; this.secondaryMessage = secondaryMessage; } } /** * Retrieve secondary message from an error object. * * @param {Error} err The error object. * @returns {string|undefined} The secondary message if available, otherwise undefined. */ const retrieveSecondaryMessage = (err) => { return "secondaryMessage" in err && typeof err.secondaryMessage === "string" ? err.secondaryMessage : undefined; }; export { CustomError, MissingParamError, SECONDARY_ERROR_MESSAGES, TRY_AGAIN_LATER, retrieveSecondaryMessage, };
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/common/http.js
src/common/http.js
// @ts-check import axios from "axios"; /** * Send GraphQL request to GitHub API. * * @param {import('axios').AxiosRequestConfig['data']} data Request data. * @param {import('axios').AxiosRequestConfig['headers']} headers Request headers. * @returns {Promise<any>} Request response. */ const request = (data, headers) => { return axios({ url: "https://api.github.com/graphql", method: "post", headers, data, }); }; export { request };
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/common/I18n.js
src/common/I18n.js
// @ts-check const FALLBACK_LOCALE = "en"; /** * I18n translation class. */ class I18n { /** * Constructor. * * @param {Object} options Options. * @param {string=} options.locale Locale. * @param {any} options.translations Translations. */ constructor({ locale, translations }) { this.locale = locale || FALLBACK_LOCALE; this.translations = translations; } /** * Get translation. * * @param {string} str String to translate. * @returns {string} Translated string. */ t(str) { if (!this.translations[str]) { throw new Error(`${str} Translation string not found`); } if (!this.translations[str][this.locale]) { throw new Error( `'${str}' translation not found for locale '${this.locale}'`, ); } return this.translations[str][this.locale]; } } export { I18n }; export default I18n;
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/common/blacklist.js
src/common/blacklist.js
const blacklist = [ "renovate-bot", "technote-space", "sw-yx", "YourUsername", "[YourUsername]", ]; export { blacklist }; export default blacklist;
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/common/render.js
src/common/render.js
// @ts-check import { SECONDARY_ERROR_MESSAGES, TRY_AGAIN_LATER } from "./error.js"; import { getCardColors } from "./color.js"; import { encodeHTML } from "./html.js"; import { clampValue } from "./ops.js"; /** * Auto layout utility, allows us to layout things vertically or horizontally with * proper gaping. * * @param {object} props Function properties. * @param {string[]} props.items Array of items to layout. * @param {number} props.gap Gap between items. * @param {"column" | "row"=} props.direction Direction to layout items. * @param {number[]=} props.sizes Array of sizes for each item. * @returns {string[]} Array of items with proper layout. */ const flexLayout = ({ items, gap, direction, sizes = [] }) => { let lastSize = 0; // filter() for filtering out empty strings return items.filter(Boolean).map((item, i) => { const size = sizes[i] || 0; let transform = `translate(${lastSize}, 0)`; if (direction === "column") { transform = `translate(0, ${lastSize})`; } lastSize += size + gap; return `<g transform="${transform}">${item}</g>`; }); }; /** * Creates a node to display the primary programming language of the repository/gist. * * @param {string} langName Language name. * @param {string} langColor Language color. * @returns {string} Language display SVG object. */ const createLanguageNode = (langName, langColor) => { return ` <g data-testid="primary-lang"> <circle data-testid="lang-color" cx="0" cy="-5" r="6" fill="${langColor}" /> <text data-testid="lang-name" class="gray" x="15">${langName}</text> </g> `; }; /** * Create a node to indicate progress in percentage along a horizontal line. * * @param {Object} params Object that contains the createProgressNode parameters. * @param {number} params.x X-axis position. * @param {number} params.y Y-axis position. * @param {number} params.width Width of progress bar. * @param {string} params.color Progress color. * @param {number} params.progress Progress value. * @param {string} params.progressBarBackgroundColor Progress bar bg color. * @param {number} params.delay Delay before animation starts. * @returns {string} Progress node. */ const createProgressNode = ({ x, y, width, color, progress, progressBarBackgroundColor, delay, }) => { const progressPercentage = clampValue(progress, 2, 100); return ` <svg width="${width}" x="${x}" y="${y}"> <rect rx="5" ry="5" x="0" y="0" width="${width}" height="8" fill="${progressBarBackgroundColor}"></rect> <svg data-testid="lang-progress" width="${progressPercentage}%"> <rect height="8" fill="${color}" rx="5" ry="5" x="0" y="0" class="lang-progress" style="animation-delay: ${delay}ms;" /> </svg> </svg> `; }; /** * Creates an icon with label to display repository/gist stats like forks, stars, etc. * * @param {string} icon The icon to display. * @param {number|string} label The label to display. * @param {string} testid The testid to assign to the label. * @param {number} iconSize The size of the icon. * @returns {string} Icon with label SVG object. */ const iconWithLabel = (icon, label, testid, iconSize) => { if (typeof label === "number" && label <= 0) { return ""; } const iconSvg = ` <svg class="icon" y="-12" viewBox="0 0 16 16" version="1.1" width="${iconSize}" height="${iconSize}" > ${icon} </svg> `; const text = `<text data-testid="${testid}" class="gray">${label}</text>`; return flexLayout({ items: [iconSvg, text], gap: 20 }).join(""); }; // Script parameters. const ERROR_CARD_LENGTH = 576.5; const UPSTREAM_API_ERRORS = [ TRY_AGAIN_LATER, SECONDARY_ERROR_MESSAGES.MAX_RETRY, ]; /** * Renders error message on the card. * * @param {object} args Function arguments. * @param {string} args.message Main error message. * @param {string} [args.secondaryMessage=""] The secondary error message. * @param {object} [args.renderOptions={}] Render options. * @param {string=} args.renderOptions.title_color Card title color. * @param {string=} args.renderOptions.text_color Card text color. * @param {string=} args.renderOptions.bg_color Card background color. * @param {string=} args.renderOptions.border_color Card border color. * @param {Parameters<typeof getCardColors>[0]["theme"]=} args.renderOptions.theme Card theme. * @param {boolean=} args.renderOptions.show_repo_link Whether to show repo link or not. * @returns {string} The SVG markup. */ const renderError = ({ message, secondaryMessage = "", renderOptions = {}, }) => { const { title_color, text_color, bg_color, border_color, theme = "default", show_repo_link = true, } = renderOptions; // returns theme based colors with proper overrides and defaults const { titleColor, textColor, bgColor, borderColor } = getCardColors({ title_color, text_color, icon_color: "", bg_color, border_color, ring_color: "", theme, }); return ` <svg width="${ERROR_CARD_LENGTH}" height="120" viewBox="0 0 ${ERROR_CARD_LENGTH} 120" fill="${bgColor}" xmlns="http://www.w3.org/2000/svg"> <style> .text { font: 600 16px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${titleColor} } .small { font: 600 12px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor} } .gray { fill: #858585 } </style> <rect x="0.5" y="0.5" width="${ ERROR_CARD_LENGTH - 1 }" height="99%" rx="4.5" fill="${bgColor}" stroke="${borderColor}"/> <text x="25" y="45" class="text">Something went wrong!${ UPSTREAM_API_ERRORS.includes(secondaryMessage) || !show_repo_link ? "" : " file an issue at https://tiny.one/readme-stats" }</text> <text data-testid="message" x="25" y="55" class="text small"> <tspan x="25" dy="18">${encodeHTML(message)}</tspan> <tspan x="25" dy="18" class="gray">${secondaryMessage}</tspan> </text> </svg> `; }; /** * Retrieve text length. * * @see https://stackoverflow.com/a/48172630/10629172 * @param {string} str String to measure. * @param {number} fontSize Font size. * @returns {number} Text length. */ const measureText = (str, fontSize = 10) => { // prettier-ignore const widths = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.2796875, 0.2765625, 0.3546875, 0.5546875, 0.5546875, 0.8890625, 0.665625, 0.190625, 0.3328125, 0.3328125, 0.3890625, 0.5828125, 0.2765625, 0.3328125, 0.2765625, 0.3015625, 0.5546875, 0.5546875, 0.5546875, 0.5546875, 0.5546875, 0.5546875, 0.5546875, 0.5546875, 0.5546875, 0.5546875, 0.2765625, 0.2765625, 0.584375, 0.5828125, 0.584375, 0.5546875, 1.0140625, 0.665625, 0.665625, 0.721875, 0.721875, 0.665625, 0.609375, 0.7765625, 0.721875, 0.2765625, 0.5, 0.665625, 0.5546875, 0.8328125, 0.721875, 0.7765625, 0.665625, 0.7765625, 0.721875, 0.665625, 0.609375, 0.721875, 0.665625, 0.94375, 0.665625, 0.665625, 0.609375, 0.2765625, 0.3546875, 0.2765625, 0.4765625, 0.5546875, 0.3328125, 0.5546875, 0.5546875, 0.5, 0.5546875, 0.5546875, 0.2765625, 0.5546875, 0.5546875, 0.221875, 0.240625, 0.5, 0.221875, 0.8328125, 0.5546875, 0.5546875, 0.5546875, 0.5546875, 0.3328125, 0.5, 0.2765625, 0.5546875, 0.5, 0.721875, 0.5, 0.5, 0.5, 0.3546875, 0.259375, 0.353125, 0.5890625, ]; const avg = 0.5279276315789471; return ( str .split("") .map((c) => c.charCodeAt(0) < widths.length ? widths[c.charCodeAt(0)] : avg, ) .reduce((cur, acc) => acc + cur) * fontSize ); }; export { ERROR_CARD_LENGTH, renderError, createLanguageNode, createProgressNode, iconWithLabel, flexLayout, measureText, };
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/common/retryer.js
src/common/retryer.js
// @ts-check import { CustomError } from "./error.js"; import { logger } from "./log.js"; // Script variables. // Count the number of GitHub API tokens available. const PATs = Object.keys(process.env).filter((key) => /PAT_\d*$/.exec(key), ).length; const RETRIES = process.env.NODE_ENV === "test" ? 7 : PATs; /** * @typedef {import("axios").AxiosResponse} AxiosResponse Axios response. * @typedef {(variables: any, token: string, retriesForTests?: number) => Promise<AxiosResponse>} FetcherFunction Fetcher function. */ /** * Try to execute the fetcher function until it succeeds or the max number of retries is reached. * * @param {FetcherFunction} fetcher The fetcher function. * @param {any} variables Object with arguments to pass to the fetcher function. * @param {number} retries How many times to retry. * @returns {Promise<any>} The response from the fetcher function. */ const retryer = async (fetcher, variables, retries = 0) => { if (!RETRIES) { throw new CustomError("No GitHub API tokens found", CustomError.NO_TOKENS); } if (retries > RETRIES) { throw new CustomError( "Downtime due to GitHub API rate limiting", CustomError.MAX_RETRY, ); } try { // try to fetch with the first token since RETRIES is 0 index i'm adding +1 let response = await fetcher( variables, // @ts-ignore process.env[`PAT_${retries + 1}`], // used in tests for faking rate limit retries, ); // react on both type and message-based rate-limit signals. // https://github.com/anuraghazra/github-readme-stats/issues/4425 const errors = response?.data?.errors; const errorType = errors?.[0]?.type; const errorMsg = errors?.[0]?.message || ""; const isRateLimited = (errors && errorType === "RATE_LIMITED") || /rate limit/i.test(errorMsg); // if rate limit is hit increase the RETRIES and recursively call the retryer // with username, and current RETRIES if (isRateLimited) { logger.log(`PAT_${retries + 1} Failed`); retries++; // directly return from the function return retryer(fetcher, variables, retries); } // finally return the response return response; } catch (err) { /** @type {any} */ const e = err; // network/unexpected error → let caller treat as failure if (!e?.response) { throw e; } // prettier-ignore // also checking for bad credentials if any tokens gets invalidated const isBadCredential = e?.response?.data?.message === "Bad credentials"; const isAccountSuspended = e?.response?.data?.message === "Sorry. Your account was suspended."; if (isBadCredential || isAccountSuspended) { logger.log(`PAT_${retries + 1} Failed`); retries++; // directly return from the function return retryer(fetcher, variables, retries); } // HTTP error with a response → return it for caller-side handling return e.response; } }; export { retryer, RETRIES }; export default retryer;
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/common/icons.js
src/common/icons.js
// @ts-check const icons = { star: `<path fill-rule="evenodd" d="M8 .25a.75.75 0 01.673.418l1.882 3.815 4.21.612a.75.75 0 01.416 1.279l-3.046 2.97.719 4.192a.75.75 0 01-1.088.791L8 12.347l-3.766 1.98a.75.75 0 01-1.088-.79l.72-4.194L.818 6.374a.75.75 0 01.416-1.28l4.21-.611L7.327.668A.75.75 0 018 .25zm0 2.445L6.615 5.5a.75.75 0 01-.564.41l-3.097.45 2.24 2.184a.75.75 0 01.216.664l-.528 3.084 2.769-1.456a.75.75 0 01.698 0l2.77 1.456-.53-3.084a.75.75 0 01.216-.664l2.24-2.183-3.096-.45a.75.75 0 01-.564-.41L8 2.694v.001z"/>`, commits: `<path fill-rule="evenodd" d="M1.643 3.143L.427 1.927A.25.25 0 000 2.104V5.75c0 .138.112.25.25.25h3.646a.25.25 0 00.177-.427L2.715 4.215a6.5 6.5 0 11-1.18 4.458.75.75 0 10-1.493.154 8.001 8.001 0 101.6-5.684zM7.75 4a.75.75 0 01.75.75v2.992l2.028.812a.75.75 0 01-.557 1.392l-2.5-1A.75.75 0 017 8.25v-3.5A.75.75 0 017.75 4z"/>`, prs: `<path fill-rule="evenodd" d="M7.177 3.073L9.573.677A.25.25 0 0110 .854v4.792a.25.25 0 01-.427.177L7.177 3.427a.25.25 0 010-.354zM3.75 2.5a.75.75 0 100 1.5.75.75 0 000-1.5zm-2.25.75a2.25 2.25 0 113 2.122v5.256a2.251 2.251 0 11-1.5 0V5.372A2.25 2.25 0 011.5 3.25zM11 2.5h-1V4h1a1 1 0 011 1v5.628a2.251 2.251 0 101.5 0V5A2.5 2.5 0 0011 2.5zm1 10.25a.75.75 0 111.5 0 .75.75 0 01-1.5 0zM3.75 12a.75.75 0 100 1.5.75.75 0 000-1.5z"/>`, prs_merged: `<path fill-rule="evenodd" d="M5.45 5.154A4.25 4.25 0 0 0 9.25 7.5h1.378a2.251 2.251 0 1 1 0 1.5H9.25A5.734 5.734 0 0 1 5 7.123v3.505a2.25 2.25 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.95-.218ZM4.25 13.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm8.5-4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5ZM5 3.25a.75.75 0 1 0 0 .005V3.25Z" />`, prs_merged_percentage: `<path fill-rule="evenodd" d="M13.442 2.558a.625.625 0 0 1 0 .884l-10 10a.625.625 0 1 1-.884-.884l10-10a.625.625 0 0 1 .884 0zM4.5 6a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm0 1a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5zm7 6a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm0 1a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5z" />`, issues: `<path fill-rule="evenodd" d="M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM0 8a8 8 0 1116 0A8 8 0 010 8zm9 3a1 1 0 11-2 0 1 1 0 012 0zm-.25-6.25a.75.75 0 00-1.5 0v3.5a.75.75 0 001.5 0v-3.5z"/>`, icon: `<path fill-rule="evenodd" d="M2 2.5A2.5 2.5 0 014.5 0h8.75a.75.75 0 01.75.75v12.5a.75.75 0 01-.75.75h-2.5a.75.75 0 110-1.5h1.75v-2h-8a1 1 0 00-.714 1.7.75.75 0 01-1.072 1.05A2.495 2.495 0 012 11.5v-9zm10.5-1V9h-8c-.356 0-.694.074-1 .208V2.5a1 1 0 011-1h8zM5 12.25v3.25a.25.25 0 00.4.2l1.45-1.087a.25.25 0 01.3 0L8.6 15.7a.25.25 0 00.4-.2v-3.25a.25.25 0 00-.25-.25h-3.5a.25.25 0 00-.25.25z"/>`, contribs: `<path fill-rule="evenodd" d="M2 2.5A2.5 2.5 0 014.5 0h8.75a.75.75 0 01.75.75v12.5a.75.75 0 01-.75.75h-2.5a.75.75 0 110-1.5h1.75v-2h-8a1 1 0 00-.714 1.7.75.75 0 01-1.072 1.05A2.495 2.495 0 012 11.5v-9zm10.5-1V9h-8c-.356 0-.694.074-1 .208V2.5a1 1 0 011-1h8zM5 12.25v3.25a.25.25 0 00.4.2l1.45-1.087a.25.25 0 01.3 0L8.6 15.7a.25.25 0 00.4-.2v-3.25a.25.25 0 00-.25-.25h-3.5a.25.25 0 00-.25.25z"/>`, fork: `<path fill-rule="evenodd" d="M5 3.25a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm0 2.122a2.25 2.25 0 10-1.5 0v.878A2.25 2.25 0 005.75 8.5h1.5v2.128a2.251 2.251 0 101.5 0V8.5h1.5a2.25 2.25 0 002.25-2.25v-.878a2.25 2.25 0 10-1.5 0v.878a.75.75 0 01-.75.75h-4.5A.75.75 0 015 6.25v-.878zm3.75 7.378a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm3-8.75a.75.75 0 100-1.5.75.75 0 000 1.5z"></path>`, reviews: `<path fill-rule="evenodd" d="M8 2c1.981 0 3.671.992 4.933 2.078 1.27 1.091 2.187 2.345 2.637 3.023a1.62 1.62 0 0 1 0 1.798c-.45.678-1.367 1.932-2.637 3.023C11.67 13.008 9.981 14 8 14c-1.981 0-3.671-.992-4.933-2.078C1.797 10.83.88 9.576.43 8.898a1.62 1.62 0 0 1 0-1.798c.45-.677 1.367-1.931 2.637-3.022C4.33 2.992 6.019 2 8 2ZM1.679 7.932a.12.12 0 0 0 0 .136c.411.622 1.241 1.75 2.366 2.717C5.176 11.758 6.527 12.5 8 12.5c1.473 0 2.825-.742 3.955-1.715 1.124-.967 1.954-2.096 2.366-2.717a.12.12 0 0 0 0-.136c-.412-.621-1.242-1.75-2.366-2.717C10.824 4.242 9.473 3.5 8 3.5c-1.473 0-2.825.742-3.955 1.715-1.124.967-1.954 2.096-2.366 2.717ZM8 10a2 2 0 1 1-.001-3.999A2 2 0 0 1 8 10Z"/>`, discussions_started: `<path fill-rule="evenodd" d="M1.75 1h8.5c.966 0 1.75.784 1.75 1.75v5.5A1.75 1.75 0 0 1 10.25 10H7.061l-2.574 2.573A1.458 1.458 0 0 1 2 11.543V10h-.25A1.75 1.75 0 0 1 0 8.25v-5.5C0 1.784.784 1 1.75 1ZM1.5 2.75v5.5c0 .138.112.25.25.25h1a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h3.5a.25.25 0 0 0 .25-.25v-5.5a.25.25 0 0 0-.25-.25h-8.5a.25.25 0 0 0-.25.25Zm13 2a.25.25 0 0 0-.25-.25h-.5a.75.75 0 0 1 0-1.5h.5c.966 0 1.75.784 1.75 1.75v5.5A1.75 1.75 0 0 1 14.25 12H14v1.543a1.458 1.458 0 0 1-2.487 1.03L9.22 12.28a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215l2.22 2.22v-2.19a.75.75 0 0 1 .75-.75h1a.25.25 0 0 0 .25-.25Z" />`, discussions_answered: `<path fill-rule="evenodd" d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z" />`, gist: `<path fill-rule="evenodd" d="M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25Zm7.47 3.97a.75.75 0 0 1 1.06 0l2 2a.75.75 0 0 1 0 1.06l-2 2a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L10.69 8 9.22 6.53a.75.75 0 0 1 0-1.06ZM6.78 6.53 5.31 8l1.47 1.47a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215l-2-2a.75.75 0 0 1 0-1.06l2-2a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042Z" />`, }; /** * Get rank icon * * @param {string} rankIcon - The rank icon type. * @param {string} rankLevel - The rank level. * @param {number} percentile - The rank percentile. * @returns {string} - The SVG code of the rank icon */ const rankIcon = (rankIcon, rankLevel, percentile) => { switch (rankIcon) { case "github": return ` <svg x="-38" y="-30" height="66" width="66" aria-hidden="true" viewBox="0 0 16 16" version="1.1" data-view-component="true" data-testid="github-rank-icon"> <path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path> </svg> `; case "percentile": return ` <text x="-5" y="-12" alignment-baseline="central" dominant-baseline="central" text-anchor="middle" data-testid="percentile-top-header" class="rank-percentile-header"> Top </text> <text x="-5" y="12" alignment-baseline="central" dominant-baseline="central" text-anchor="middle" data-testid="percentile-rank-value" class="rank-percentile-text"> ${percentile.toFixed(1)}% </text> `; case "default": default: return ` <text x="-5" y="3" alignment-baseline="central" dominant-baseline="central" text-anchor="middle" data-testid="level-rank-icon"> ${rankLevel} </text> `; } }; export { icons, rankIcon }; export default icons;
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/common/html.js
src/common/html.js
// @ts-check /** * Encode string as HTML. * * @see https://stackoverflow.com/a/48073476/10629172 * * @param {string} str String to encode. * @returns {string} Encoded string. */ const encodeHTML = (str) => { return str .replace(/[\u00A0-\u9999<>&](?!#)/gim, (i) => { return "&#" + i.charCodeAt(0) + ";"; }) .replace(/\u0008/gim, ""); }; export { encodeHTML };
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/common/color.js
src/common/color.js
// @ts-check import { themes } from "../../themes/index.js"; /** * Checks if a string is a valid hex color. * * @param {string} hexColor String to check. * @returns {boolean} True if the given string is a valid hex color. */ const isValidHexColor = (hexColor) => { return new RegExp( /^([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}|[A-Fa-f0-9]{4})$/, ).test(hexColor); }; /** * Check if the given string is a valid gradient. * * @param {string[]} colors Array of colors. * @returns {boolean} True if the given string is a valid gradient. */ const isValidGradient = (colors) => { return ( colors.length > 2 && colors.slice(1).every((color) => isValidHexColor(color)) ); }; /** * Retrieves a gradient if color has more than one valid hex codes else a single color. * * @param {string} color The color to parse. * @param {string | string[]} fallbackColor The fallback color. * @returns {string | string[]} The gradient or color. */ const fallbackColor = (color, fallbackColor) => { let gradient = null; let colors = color ? color.split(",") : []; if (colors.length > 1 && isValidGradient(colors)) { gradient = colors; } return ( (gradient ? gradient : isValidHexColor(color) && `#${color}`) || fallbackColor ); }; /** * Object containing card colors. * @typedef {{ * titleColor: string; * iconColor: string; * textColor: string; * bgColor: string | string[]; * borderColor: string; * ringColor: string; * }} CardColors */ /** * Returns theme based colors with proper overrides and defaults. * * @param {Object} args Function arguments. * @param {string=} args.title_color Card title color. * @param {string=} args.text_color Card text color. * @param {string=} args.icon_color Card icon color. * @param {string=} args.bg_color Card background color. * @param {string=} args.border_color Card border color. * @param {string=} args.ring_color Card ring color. * @param {string=} args.theme Card theme. * @returns {CardColors} Card colors. */ const getCardColors = ({ title_color, text_color, icon_color, bg_color, border_color, ring_color, theme, }) => { const defaultTheme = themes["default"]; const isThemeProvided = theme !== null && theme !== undefined; // @ts-ignore const selectedTheme = isThemeProvided ? themes[theme] : defaultTheme; const defaultBorderColor = "border_color" in selectedTheme ? selectedTheme.border_color : // @ts-ignore defaultTheme.border_color; // get the color provided by the user else the theme color // finally if both colors are invalid fallback to default theme const titleColor = fallbackColor( title_color || selectedTheme.title_color, "#" + defaultTheme.title_color, ); // get the color provided by the user else the theme color // finally if both colors are invalid we use the titleColor const ringColor = fallbackColor( // @ts-ignore ring_color || selectedTheme.ring_color, titleColor, ); const iconColor = fallbackColor( icon_color || selectedTheme.icon_color, "#" + defaultTheme.icon_color, ); const textColor = fallbackColor( text_color || selectedTheme.text_color, "#" + defaultTheme.text_color, ); const bgColor = fallbackColor( bg_color || selectedTheme.bg_color, "#" + defaultTheme.bg_color, ); const borderColor = fallbackColor( border_color || defaultBorderColor, "#" + defaultBorderColor, ); if ( typeof titleColor !== "string" || typeof textColor !== "string" || typeof ringColor !== "string" || typeof iconColor !== "string" || typeof borderColor !== "string" ) { throw new Error( "Unexpected behavior, all colors except background should be string.", ); } return { titleColor, iconColor, textColor, bgColor, borderColor, ringColor }; }; export { isValidHexColor, isValidGradient, getCardColors };
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/common/log.js
src/common/log.js
// @ts-check const noop = () => {}; /** * Return console instance based on the environment. * * @type {Console | {log: () => void, error: () => void}} */ const logger = process.env.NODE_ENV === "test" ? { log: noop, error: noop } : console; export { logger }; export default logger;
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/common/fmt.js
src/common/fmt.js
// @ts-check import wrap from "word-wrap"; import { encodeHTML } from "./html.js"; /** * Retrieves num with suffix k(thousands) precise to given decimal places. * * @param {number} num The number to format. * @param {number=} precision The number of decimal places to include. * @returns {string|number} The formatted number. */ const kFormatter = (num, precision) => { const abs = Math.abs(num); const sign = Math.sign(num); if (typeof precision === "number" && !isNaN(precision)) { return (sign * (abs / 1000)).toFixed(precision) + "k"; } if (abs < 1000) { return sign * abs; } return sign * parseFloat((abs / 1000).toFixed(1)) + "k"; }; /** * Convert bytes to a human-readable string representation. * * @param {number} bytes The number of bytes to convert. * @returns {string} The human-readable representation of bytes. * @throws {Error} If bytes is negative or too large. */ const formatBytes = (bytes) => { if (bytes < 0) { throw new Error("Bytes must be a non-negative number"); } if (bytes === 0) { return "0 B"; } const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB"]; const base = 1024; const i = Math.floor(Math.log(bytes) / Math.log(base)); if (i >= sizes.length) { throw new Error("Bytes is too large to convert to a human-readable string"); } return `${(bytes / Math.pow(base, i)).toFixed(1)} ${sizes[i]}`; }; /** * Split text over multiple lines based on the card width. * * @param {string} text Text to split. * @param {number} width Line width in number of characters. * @param {number} maxLines Maximum number of lines. * @returns {string[]} Array of lines. */ const wrapTextMultiline = (text, width = 59, maxLines = 3) => { const fullWidthComma = ","; const encoded = encodeHTML(text); const isChinese = encoded.includes(fullWidthComma); let wrapped = []; if (isChinese) { wrapped = encoded.split(fullWidthComma); // Chinese full punctuation } else { wrapped = wrap(encoded, { width, }).split("\n"); // Split wrapped lines to get an array of lines } const lines = wrapped.map((line) => line.trim()).slice(0, maxLines); // Only consider maxLines lines // Add "..." to the last line if the text exceeds maxLines if (wrapped.length > maxLines) { lines[maxLines - 1] += "..."; } // Remove empty lines if text fits in less than maxLines lines const multiLineText = lines.filter(Boolean); return multiLineText; }; export { kFormatter, formatBytes, wrapTextMultiline };
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/common/access.js
src/common/access.js
// @ts-check import { renderError } from "./render.js"; import { blacklist } from "./blacklist.js"; import { whitelist, gistWhitelist } from "./envs.js"; const NOT_WHITELISTED_USERNAME_MESSAGE = "This username is not whitelisted"; const NOT_WHITELISTED_GIST_MESSAGE = "This gist ID is not whitelisted"; const BLACKLISTED_MESSAGE = "This username is blacklisted"; /** * Guards access using whitelist/blacklist. * * @param {Object} args The parameters object. * @param {any} args.res The response object. * @param {string} args.id Resource identifier (username or gist id). * @param {"username"|"gist"|"wakatime"} args.type The type of identifier. * @param {{ title_color?: string, text_color?: string, bg_color?: string, border_color?: string, theme?: string }} args.colors Color options for the error card. * @returns {{ isPassed: boolean, result?: any }} The result object indicating success or failure. */ const guardAccess = ({ res, id, type, colors }) => { if (!["username", "gist", "wakatime"].includes(type)) { throw new Error( 'Invalid type. Expected "username", "gist", or "wakatime".', ); } const currentWhitelist = type === "gist" ? gistWhitelist : whitelist; const notWhitelistedMsg = type === "gist" ? NOT_WHITELISTED_GIST_MESSAGE : NOT_WHITELISTED_USERNAME_MESSAGE; if (Array.isArray(currentWhitelist) && !currentWhitelist.includes(id)) { const result = res.send( renderError({ message: notWhitelistedMsg, secondaryMessage: "Please deploy your own instance", renderOptions: { ...colors, show_repo_link: false, }, }), ); return { isPassed: false, result }; } if ( type === "username" && currentWhitelist === undefined && blacklist.includes(id) ) { const result = res.send( renderError({ message: BLACKLISTED_MESSAGE, secondaryMessage: "Please deploy your own instance", renderOptions: { ...colors, show_repo_link: false, }, }), ); return { isPassed: false, result }; } return { isPassed: true }; }; export { guardAccess };
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/common/Card.js
src/common/Card.js
// @ts-check import { encodeHTML } from "./html.js"; import { flexLayout } from "./render.js"; class Card { /** * Creates a new card instance. * * @param {object} args Card arguments. * @param {number=} args.width Card width. * @param {number=} args.height Card height. * @param {number=} args.border_radius Card border radius. * @param {string=} args.customTitle Card custom title. * @param {string=} args.defaultTitle Card default title. * @param {string=} args.titlePrefixIcon Card title prefix icon. * @param {object} [args.colors={}] Card colors arguments. * @param {string=} args.colors.titleColor Card title color. * @param {string=} args.colors.textColor Card text color. * @param {string=} args.colors.iconColor Card icon color. * @param {string|string[]=} args.colors.bgColor Card background color. * @param {string=} args.colors.borderColor Card border color. */ constructor({ width = 100, height = 100, border_radius = 4.5, colors = {}, customTitle, defaultTitle = "", titlePrefixIcon, }) { this.width = width; this.height = height; this.hideBorder = false; this.hideTitle = false; this.border_radius = border_radius; // returns theme based colors with proper overrides and defaults this.colors = colors; this.title = customTitle === undefined ? encodeHTML(defaultTitle) : encodeHTML(customTitle); this.css = ""; this.paddingX = 25; this.paddingY = 35; this.titlePrefixIcon = titlePrefixIcon; this.animations = true; this.a11yTitle = ""; this.a11yDesc = ""; } /** * @returns {void} */ disableAnimations() { this.animations = false; } /** * @param {Object} props The props object. * @param {string} props.title Accessibility title. * @param {string} props.desc Accessibility description. * @returns {void} */ setAccessibilityLabel({ title, desc }) { this.a11yTitle = title; this.a11yDesc = desc; } /** * @param {string} value The CSS to add to the card. * @returns {void} */ setCSS(value) { this.css = value; } /** * @param {boolean} value Whether to hide the border or not. * @returns {void} */ setHideBorder(value) { this.hideBorder = value; } /** * @param {boolean} value Whether to hide the title or not. * @returns {void} */ setHideTitle(value) { this.hideTitle = value; if (value) { this.height -= 30; } } /** * @param {string} text The title to set. * @returns {void} */ setTitle(text) { this.title = text; } /** * @returns {string} The rendered card title. */ renderTitle() { const titleText = ` <text x="0" y="0" class="header" data-testid="header" >${this.title}</text> `; const prefixIcon = ` <svg class="icon" x="0" y="-13" viewBox="0 0 16 16" version="1.1" width="16" height="16" > ${this.titlePrefixIcon} </svg> `; return ` <g data-testid="card-title" transform="translate(${this.paddingX}, ${this.paddingY})" > ${flexLayout({ items: [this.titlePrefixIcon ? prefixIcon : "", titleText], gap: 25, }).join("")} </g> `; } /** * @returns {string} The rendered card gradient. */ renderGradient() { if (typeof this.colors.bgColor !== "object") { return ""; } const gradients = this.colors.bgColor.slice(1); return typeof this.colors.bgColor === "object" ? ` <defs> <linearGradient id="gradient" gradientTransform="rotate(${this.colors.bgColor[0]})" gradientUnits="userSpaceOnUse" > ${gradients.map((grad, index) => { let offset = (index * 100) / (gradients.length - 1); return `<stop offset="${offset}%" stop-color="#${grad}" />`; })} </linearGradient> </defs> ` : ""; } /** * Retrieves css animations for a card. * * @returns {string} Animation css. */ getAnimations = () => { return ` /* Animations */ @keyframes scaleInAnimation { from { transform: translate(-5px, 5px) scale(0); } to { transform: translate(-5px, 5px) scale(1); } } @keyframes fadeInAnimation { from { opacity: 0; } to { opacity: 1; } } `; }; /** * @param {string} body The inner body of the card. * @returns {string} The rendered card. */ render(body) { return ` <svg width="${this.width}" height="${this.height}" viewBox="0 0 ${this.width} ${this.height}" fill="none" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="descId" > <title id="titleId">${this.a11yTitle}</title> <desc id="descId">${this.a11yDesc}</desc> <style> .header { font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${this.colors.titleColor}; animation: fadeInAnimation 0.8s ease-in-out forwards; } @supports(-moz-appearance: auto) { /* Selector detects Firefox */ .header { font-size: 15.5px; } } ${this.css} ${process.env.NODE_ENV === "test" ? "" : this.getAnimations()} ${ this.animations === false ? `* { animation-duration: 0s !important; animation-delay: 0s !important; }` : "" } </style> ${this.renderGradient()} <rect data-testid="card-bg" x="0.5" y="0.5" rx="${this.border_radius}" height="99%" stroke="${this.colors.borderColor}" width="${this.width - 1}" fill="${ typeof this.colors.bgColor === "object" ? "url(#gradient)" : this.colors.bgColor }" stroke-opacity="${this.hideBorder ? 0 : 1}" /> ${this.hideTitle ? "" : this.renderTitle()} <g data-testid="main-card-body" transform="translate(0, ${ this.hideTitle ? this.paddingX : this.paddingY + 20 })" > ${body} </g> </svg> `; } } export { Card }; export default Card;
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/fetchers/repo.js
src/fetchers/repo.js
// @ts-check import { MissingParamError } from "../common/error.js"; import { request } from "../common/http.js"; import { retryer } from "../common/retryer.js"; /** * Repo data fetcher. * * @param {object} variables Fetcher variables. * @param {string} token GitHub token. * @returns {Promise<import('axios').AxiosResponse>} The response. */ const fetcher = (variables, token) => { return request( { query: ` fragment RepoInfo on Repository { name nameWithOwner isPrivate isArchived isTemplate stargazers { totalCount } description primaryLanguage { color id name } forkCount } query getRepo($login: String!, $repo: String!) { user(login: $login) { repository(name: $repo) { ...RepoInfo } } organization(login: $login) { repository(name: $repo) { ...RepoInfo } } } `, variables, }, { Authorization: `token ${token}`, }, ); }; const urlExample = "/api/pin?username=USERNAME&amp;repo=REPO_NAME"; /** * @typedef {import("./types").RepositoryData} RepositoryData Repository data. */ /** * Fetch repository data. * * @param {string} username GitHub username. * @param {string} reponame GitHub repository name. * @returns {Promise<RepositoryData>} Repository data. */ const fetchRepo = async (username, reponame) => { if (!username && !reponame) { throw new MissingParamError(["username", "repo"], urlExample); } if (!username) { throw new MissingParamError(["username"], urlExample); } if (!reponame) { throw new MissingParamError(["repo"], urlExample); } let res = await retryer(fetcher, { login: username, repo: reponame }); const data = res.data.data; if (!data.user && !data.organization) { throw new Error("Not found"); } const isUser = data.organization === null && data.user; const isOrg = data.user === null && data.organization; if (isUser) { if (!data.user.repository || data.user.repository.isPrivate) { throw new Error("User Repository Not found"); } return { ...data.user.repository, starCount: data.user.repository.stargazers.totalCount, }; } if (isOrg) { if ( !data.organization.repository || data.organization.repository.isPrivate ) { throw new Error("Organization Repository Not found"); } return { ...data.organization.repository, starCount: data.organization.repository.stargazers.totalCount, }; } throw new Error("Unexpected behavior"); }; export { fetchRepo }; export default fetchRepo;
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/fetchers/gist.js
src/fetchers/gist.js
// @ts-check import { retryer } from "../common/retryer.js"; import { MissingParamError } from "../common/error.js"; import { request } from "../common/http.js"; const QUERY = ` query gistInfo($gistName: String!) { viewer { gist(name: $gistName) { description owner { login } stargazerCount forks { totalCount } files { name language { name } size } } } } `; /** * Gist data fetcher. * * @param {object} variables Fetcher variables. * @param {string} token GitHub token. * @returns {Promise<import('axios').AxiosResponse>} The response. */ const fetcher = async (variables, token) => { return await request( { query: QUERY, variables }, { Authorization: `token ${token}` }, ); }; /** * @typedef {{ name: string; language: { name: string; }, size: number }} GistFile Gist file. */ /** * This function calculates the primary language of a gist by files size. * * @param {GistFile[]} files Files. * @returns {string} Primary language. */ const calculatePrimaryLanguage = (files) => { /** @type {Record<string, number>} */ const languages = {}; for (const file of files) { if (file.language) { if (languages[file.language.name]) { languages[file.language.name] += file.size; } else { languages[file.language.name] = file.size; } } } let primaryLanguage = Object.keys(languages)[0]; for (const language in languages) { if (languages[language] > languages[primaryLanguage]) { primaryLanguage = language; } } return primaryLanguage; }; /** * @typedef {import('./types').GistData} GistData Gist data. */ /** * Fetch GitHub gist information by given username and ID. * * @param {string} id GitHub gist ID. * @returns {Promise<GistData>} Gist data. */ const fetchGist = async (id) => { if (!id) { throw new MissingParamError(["id"], "/api/gist?id=GIST_ID"); } const res = await retryer(fetcher, { gistName: id }); if (res.data.errors) { throw new Error(res.data.errors[0].message); } if (!res.data.data.viewer.gist) { throw new Error("Gist not found"); } const data = res.data.data.viewer.gist; return { name: data.files[Object.keys(data.files)[0]].name, nameWithOwner: `${data.owner.login}/${ data.files[Object.keys(data.files)[0]].name }`, description: data.description, language: calculatePrimaryLanguage(data.files), starsCount: data.stargazerCount, forksCount: data.forks.totalCount, }; }; export { fetchGist }; export default fetchGist;
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false
anuraghazra/github-readme-stats
https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/fetchers/wakatime.js
src/fetchers/wakatime.js
// @ts-check import axios from "axios"; import { CustomError, MissingParamError } from "../common/error.js"; /** * WakaTime data fetcher. * * @param {{username: string, api_domain: string }} props Fetcher props. * @returns {Promise<import("./types").WakaTimeData>} WakaTime data response. */ const fetchWakatimeStats = async ({ username, api_domain }) => { if (!username) { throw new MissingParamError(["username"]); } try { const { data } = await axios.get( `https://${ api_domain ? api_domain.replace(/\/$/gi, "") : "wakatime.com" }/api/v1/users/${username}/stats?is_including_today=true`, ); return data.data; } catch (err) { if (err.response.status < 200 || err.response.status > 299) { throw new CustomError( `Could not resolve to a User with the login of '${username}'`, "WAKATIME_USER_NOT_FOUND", ); } throw err; } }; export { fetchWakatimeStats }; export default fetchWakatimeStats;
javascript
MIT
8108ba1417faaad7182399e01dd724777adc63e5
2026-01-04T14:56:49.628708Z
false