javascript
exercises
exercises.js⚡javascript
/**
* ============================================
* 3.8 REST OPERATOR - EXERCISES
* ============================================
*/
// ============================================
// EXERCISE 1: Sum Function
// ============================================
/**
* Task: Create a function that accepts any number of arguments
* and returns their sum
*/
// Your code here:
// function sum(...) { }
// console.log("Exercise 1:");
// 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
// ============================================
// EXERCISE 2: First and Rest
// ============================================
/**
* Task: Use array destructuring with rest to extract
* the first element and remaining elements
*/
const numbers = [10, 20, 30, 40, 50];
// Your code here:
// const [first, ...rest] = ...
// console.log("Exercise 2:");
// console.log("First:", first); // 10
// console.log("Rest:", rest); // [20, 30, 40, 50]
// ============================================
// EXERCISE 3: Greeting Function
// ============================================
/**
* Task: Create a function that takes a greeting and any number of names,
* returning an array of personalized greetings
*/
// Your code here:
// function greetAll(greeting, ...names) { }
// console.log("Exercise 3:");
// console.log(greetAll("Hello", "Alice", "Bob", "Charlie"));
// // ["Hello, Alice!", "Hello, Bob!", "Hello, Charlie!"]
// ============================================
// EXERCISE 4: Object Property Extraction
// ============================================
/**
* Task: Extract the 'id' and 'name' from the user object,
* and collect all other properties into a 'details' object
*/
const user = {
id: 1,
name: 'John',
email: 'john@example.com',
age: 30,
role: 'admin',
};
// Your code here:
// const { id, name, ...details } = ...
// console.log("Exercise 4:");
// console.log("ID:", id);
// console.log("Name:", name);
// console.log("Details:", details);
// ============================================
// EXERCISE 5: Remove Password
// ============================================
/**
* Task: Create a function that removes the 'password' field
* from a user object and returns the safe user data
*/
// Your code here:
// function removePassword(user) { }
const userWithPwd = {
username: 'john',
password: 'secret',
email: 'john@example.com',
};
// console.log("Exercise 5:");
// console.log(removePassword(userWithPwd));
// // { username: 'john', email: 'john@example.com' }
// ============================================
// EXERCISE 6: Maximum Value
// ============================================
/**
* Task: Create a function that finds the maximum value
* among any number of arguments (without using Math.max)
*/
// Your code here:
// function findMax(...) { }
// console.log("Exercise 6:");
// console.log("findMax(3, 7, 2, 9, 4):", findMax(3, 7, 2, 9, 4)); // 9
// console.log("findMax(-5, -2, -8):", findMax(-5, -2, -8)); // -2
// ============================================
// EXERCISE 7: Head and Tail
// ============================================
/**
* Task: Create functions that return the head (first element)
* and tail (all elements except first) of an array
*/
// Your code here:
// const head = (arr) => ...
// const tail = (arr) => ...
const list = ['a', 'b', 'c', 'd'];
// console.log("Exercise 7:");
// console.log("head:", head(list)); // 'a'
// console.log("tail:", tail(list)); // ['b', 'c', 'd']
// ============================================
// EXERCISE 8: Merge Objects
// ============================================
/**
* Task: Create a function that merges any number of objects
* Later objects override earlier ones
*/
// Your code here:
// function merge(...objects) { }
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const obj3 = { c: 5, d: 6 };
// console.log("Exercise 8:");
// console.log(merge(obj1, obj2, obj3)); // { a: 1, b: 3, c: 5, d: 6 }
// ============================================
// EXERCISE 9: Skip First Two
// ============================================
/**
* Task: Use destructuring with rest to skip the first two elements
* and get the remaining elements
*/
const values = [1, 2, 3, 4, 5, 6];
// Your code here:
// const [, , ...remaining] = ...
// console.log("Exercise 9:");
// console.log("Remaining:", remaining); // [3, 4, 5, 6]
// ============================================
// EXERCISE 10: Flexible Logger
// ============================================
/**
* Task: Create a logger function that:
* - Takes a log level as first argument
* - Takes any number of messages after that
* - Prefixes each message with "[LEVEL] "
*/
// Your code here:
// function log(level, ...messages) { }
// console.log("Exercise 10:");
// log('INFO', 'Server started', 'Port 3000');
// // [INFO] Server started
// // [INFO] Port 3000
// ============================================
// EXERCISE 11: Array Rotation
// ============================================
/**
* Task: Create a function that rotates an array left by one position
* using destructuring with rest and spread
* [1, 2, 3, 4] -> [2, 3, 4, 1]
*/
// Your code here:
// function rotateLeft(arr) { }
// console.log("Exercise 11:");
// console.log(rotateLeft([1, 2, 3, 4])); // [2, 3, 4, 1]
// console.log(rotateLeft(['a', 'b', 'c'])); // ['b', 'c', 'a']
// ============================================
// EXERCISE 12: Pick Properties
// ============================================
/**
* Task: Create a function that picks specified properties from an object
* pick(object, 'prop1', 'prop2', ...)
*/
// Your code here:
// function pick(obj, ...keys) { }
const fullObject = { a: 1, b: 2, c: 3, d: 4, e: 5 };
// console.log("Exercise 12:");
// console.log(pick(fullObject, 'a', 'c', 'e')); // { a: 1, c: 3, e: 5 }
// ============================================
// EXERCISE 13: Average Calculator
// ============================================
/**
* Task: Create a function that calculates the average of any number of values
*/
// Your code here:
// function average(...) { }
// console.log("Exercise 13:");
// console.log("average(10, 20, 30):", average(10, 20, 30)); // 20
// console.log("average(5, 10, 15, 20):", average(5, 10, 15, 20)); // 12.5
// ============================================
// EXERCISE 14: Function Wrapper
// ============================================
/**
* Task: Create a wrapper function that logs all arguments
* passed to a function, calls the function, and logs the result
*/
// Your code here:
// function withLogging(fn) { }
const add = (a, b) => a + b;
// const loggedAdd = withLogging(add);
// console.log("Exercise 14:");
// loggedAdd(5, 3);
// // Should log: Arguments: [5, 3]
// // Should log: Result: 8
// ============================================
// BONUS: Partial Application
// ============================================
/**
* Task: Create a partial function that pre-fills some arguments
* partial(fn, arg1, arg2) returns a function that takes remaining args
*/
// Your code here:
// function partial(fn, ...presetArgs) { }
// function greet(greeting, name, punctuation) {
// return `${greeting}, ${name}${punctuation}`;
// }
// const sayHello = partial(greet, 'Hello');
// console.log("Bonus:");
// console.log(sayHello('Alice', '!')); // "Hello, Alice!"
// console.log(sayHello('Bob', '?')); // "Hello, Bob?"
// ============================================
// SOLUTIONS
// ============================================
/**
* Exercise 1:
* function sum(...numbers) {
* return numbers.reduce((total, n) => total + n, 0);
* }
*
* Exercise 2:
* const [first, ...rest] = numbers;
*
* Exercise 3:
* function greetAll(greeting, ...names) {
* return names.map(name => `${greeting}, ${name}!`);
* }
*
* Exercise 4:
* const { id, name, ...details } = user;
*
* Exercise 5:
* function removePassword(user) {
* const { password, ...safeUser } = user;
* return safeUser;
* }
*
* Exercise 6:
* function findMax(...numbers) {
* return numbers.reduce((max, n) => n > max ? n : max, numbers[0]);
* }
*
* Exercise 7:
* const head = ([first]) => first;
* const tail = ([, ...rest]) => rest;
*
* Exercise 8:
* function merge(...objects) {
* return objects.reduce((merged, obj) => ({ ...merged, ...obj }), {});
* }
*
* Exercise 9:
* const [, , ...remaining] = values;
*
* Exercise 10:
* function log(level, ...messages) {
* messages.forEach(msg => console.log(`[${level.toUpperCase()}] ${msg}`));
* }
*
* Exercise 11:
* function rotateLeft([first, ...rest]) {
* return [...rest, first];
* }
*
* Exercise 12:
* function pick(obj, ...keys) {
* return keys.reduce((result, key) => {
* if (key in obj) result[key] = obj[key];
* return result;
* }, {});
* }
*
* Exercise 13:
* function average(...numbers) {
* return numbers.reduce((sum, n) => sum + n, 0) / numbers.length;
* }
*
* Exercise 14:
* function withLogging(fn) {
* return function(...args) {
* console.log('Arguments:', args);
* const result = fn(...args);
* console.log('Result:', result);
* return result;
* };
* }
*
* Bonus:
* function partial(fn, ...presetArgs) {
* return function(...laterArgs) {
* return fn(...presetArgs, ...laterArgs);
* };
* }
*/