javascript
examples
examples.jsā”javascript
/**
* ============================================
* 3.8 REST OPERATOR - EXAMPLES
* ============================================
*/
// ============================================
// EXAMPLE 1: Collecting All Arguments
// ============================================
console.log('--- Collecting All Arguments ---');
function sum(...numbers) {
console.log('Type of numbers:', Array.isArray(numbers)); // true
return numbers.reduce((total, num) => total + num, 0);
}
console.log('sum(1, 2):', sum(1, 2)); // 3
console.log('sum(1, 2, 3, 4, 5):', sum(1, 2, 3, 4, 5)); // 15
console.log('sum():', sum()); // 0
// ============================================
// EXAMPLE 2: Collecting Remaining Arguments
// ============================================
console.log('\n--- Collecting Remaining Arguments ---');
function greet(greeting, ...names) {
console.log('Greeting:', greeting);
console.log('Names:', names);
return names.map((name) => `${greeting}, ${name}!`);
}
const greetings = greet('Hello', 'Alice', 'Bob', 'Charlie');
console.log('Result:', greetings);
// ============================================
// EXAMPLE 3: Rest vs arguments
// ============================================
console.log('\n--- Rest vs arguments ---');
// Old way with arguments
function oldWay() {
console.log('arguments is array?', Array.isArray(arguments)); // false
// Need to convert to use array methods
return Array.from(arguments).join(', ');
}
console.log('Old way:', oldWay('a', 'b', 'c'));
// New way with rest
function newWay(...args) {
console.log('args is array?', Array.isArray(args)); // true
return args.join(', '); // Works directly!
}
console.log('New way:', newWay('a', 'b', 'c'));
// Rest works with arrow functions (arguments doesn't!)
const arrowFn = (...args) => args.length;
console.log('Arrow function with rest:', arrowFn(1, 2, 3, 4)); // 4
// ============================================
// EXAMPLE 4: Array Destructuring with Rest
// ============================================
console.log('\n--- Array Destructuring with Rest ---');
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log('first:', first); // 1
console.log('second:', second); // 2
console.log('rest:', rest); // [3, 4, 5]
// Head and tail pattern
const list = ['a', 'b', 'c', 'd', 'e'];
const [head, ...tail] = list;
console.log('head:', head); // 'a'
console.log('tail:', tail); // ['b', 'c', 'd', 'e']
// ============================================
// EXAMPLE 5: Skipping Elements
// ============================================
console.log('\n--- Skipping Elements ---');
const values = [1, 2, 3, 4, 5, 6];
// Skip second element
const [a, , ...remaining] = values;
console.log('a:', a); // 1
console.log('remaining:', remaining); // [3, 4, 5, 6]
// Skip multiple
const [first2, , , ...afterThird] = values;
console.log('first2:', first2); // 1
console.log('afterThird:', afterThird); // [4, 5, 6]
// ============================================
// EXAMPLE 6: Object Destructuring with Rest
// ============================================
console.log('\n--- Object Destructuring with Rest ---');
const user = {
id: 1,
name: 'John',
email: 'john@example.com',
age: 30,
role: 'admin',
};
const { name, email, ...otherDetails } = user;
console.log('name:', name); // 'John'
console.log('email:', email); // 'john@example.com'
console.log('otherDetails:', otherDetails); // { id: 1, age: 30, role: 'admin' }
// ============================================
// EXAMPLE 7: Removing Sensitive Data
// ============================================
console.log('\n--- Removing Sensitive Data ---');
const userRecord = {
id: 1,
username: 'john_doe',
password: 'hashed_password',
token: 'secret_token',
email: 'john@example.com',
};
// Remove sensitive fields
const { password, token, ...safeUser } = userRecord;
console.log('Safe user data:', safeUser);
// ============================================
// EXAMPLE 8: Function with Object Rest
// ============================================
console.log('\n--- Function with Object Rest ---');
function createApiRequest({ method, url, ...options }) {
console.log('Method:', method);
console.log('URL:', url);
console.log('Other options:', options);
}
createApiRequest({
method: 'POST',
url: '/api/users',
headers: { 'Content-Type': 'application/json' },
body: { name: 'John' },
timeout: 5000,
});
// ============================================
// EXAMPLE 9: Combining Rest and Spread
// ============================================
console.log('\n--- Combining Rest and Spread ---');
// Collect with rest, then spread
function logSorted(...numbers) {
const sorted = [...numbers].sort((a, b) => a - b);
console.log('Original:', numbers);
console.log('Sorted:', sorted);
}
logSorted(3, 1, 4, 1, 5, 9, 2, 6);
// ============================================
// EXAMPLE 10: Array Manipulation
// ============================================
console.log('\n--- Array Manipulation ---');
const arr = [1, 2, 3, 4, 5];
// Remove first (immutably)
const [, ...withoutFirst] = arr;
console.log('Without first:', withoutFirst); // [2, 3, 4, 5]
// Swap first two
const [firstEl, secondEl, ...restEls] = arr;
const swapped = [secondEl, firstEl, ...restEls];
console.log('Swapped:', swapped); // [2, 1, 3, 4, 5]
// Rotate left
const [headEl, ...tailEls] = arr;
const rotated = [...tailEls, headEl];
console.log('Rotated:', rotated); // [2, 3, 4, 5, 1]
// ============================================
// EXAMPLE 11: Variadic Function
// ============================================
console.log('\n--- Variadic Function ---');
function log(level, ...messages) {
const timestamp = new Date().toISOString();
const formatted = messages.map(
(msg) => `[${timestamp}] [${level.toUpperCase()}] ${msg}`
);
formatted.forEach((msg) => console.log(msg));
}
log('info', 'Server starting', 'Loading config');
log('error', 'Connection failed');
// ============================================
// EXAMPLE 12: Partial Application
// ============================================
console.log('\n--- Partial Application ---');
function partial(fn, ...presetArgs) {
return function (...laterArgs) {
return fn(...presetArgs, ...laterArgs);
};
}
function add(a, b, c) {
return a + b + c;
}
const add5 = partial(add, 5);
console.log('add5(3, 2):', add5(3, 2)); // 10
const add5and3 = partial(add, 5, 3);
console.log('add5and3(2):', add5and3(2)); // 10
// ============================================
// EXAMPLE 13: Pick and Omit Utilities
// ============================================
console.log('\n--- Pick and Omit Utilities ---');
// Pick specific properties
function pick(obj, ...keys) {
return keys.reduce((result, key) => {
if (key in obj) {
result[key] = obj[key];
}
return result;
}, {});
}
const fullUser = { id: 1, name: 'John', email: 'john@example.com', age: 30 };
console.log('Picked:', pick(fullUser, 'name', 'email'));
// Omit specific properties
function omit(obj, ...keys) {
const keysToOmit = new Set(keys);
return Object.fromEntries(
Object.entries(obj).filter(([key]) => !keysToOmit.has(key))
);
}
console.log('Omitted:', omit(fullUser, 'id', 'age'));
// ============================================
// EXAMPLE 14: Default Values with Rest
// ============================================
console.log('\n--- Default Values with Rest ---');
const short = [1];
const [val1, val2 = 'default', ...restVals] = short;
console.log('val1:', val1); // 1
console.log('val2:', val2); // 'default'
console.log('restVals:', restVals); // []
// ============================================
// EXAMPLE 15: Rest in Nested Destructuring
// ============================================
console.log('\n--- Nested Destructuring ---');
const data = {
user: {
name: 'John',
age: 30,
address: { city: 'NYC', zip: '10001' },
},
posts: [1, 2, 3],
metadata: { created: '2024-01-01' },
};
const {
user: { name: userName, ...userRest },
...otherData
} = data;
console.log('userName:', userName);
console.log('userRest:', userRest);
console.log('otherData:', otherData);
console.log('\nā
All rest operator examples completed!');