Shuu12121/CodeModernBERT-Crow-v3-len1024
Fill-Mask β’ 0.1B β’ Updated β’ 55
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'\n\n// ====================(...TRUNCATED) | javascript | MIT | 5cda73bac940173b77d19a23a208fea234ca6c33 | 2026-01-04T14:56:49.684692Z | true |