javascript

exercises

exercises.js
// ============================================
// 17.2 Template Literals - Exercises
// ============================================

// Exercise 1: Basic Interpolation
// Create a greeting message using template literal
const firstName = 'John';
const lastName = 'Doe';

// Your code here - create fullGreeting:
// const fullGreeting = ...

// console.log(fullGreeting);  // Should print: 'Hello, John Doe!'

/*
Solution:
const fullGreeting = `Hello, ${firstName} ${lastName}!`;
console.log(fullGreeting);  // 'Hello, John Doe!'
*/

// --------------------------------------------

// Exercise 2: Expression Interpolation
// Calculate and display the result in a template literal
const price = 29.99;
const quantity = 3;
const taxRate = 0.08;

// Your code here - calculate total with tax:
// const receipt = ...

// Should print: 'Items: 3 x $29.99 = $89.97, Tax: $7.20, Total: $97.17'

/*
Solution:
const subtotal = price * quantity;
const tax = subtotal * taxRate;
const total = subtotal + tax;
const receipt = `Items: ${quantity} x $${price} = $${subtotal.toFixed(2)}, Tax: $${tax.toFixed(2)}, Total: $${total.toFixed(2)}`;
console.log(receipt);
*/

// --------------------------------------------

// Exercise 3: Multi-line String
// Create an HTML card template using template literals
const product = {
  name: 'Laptop',
  price: 999.99,
  inStock: true,
};

// Your code here - create productCard HTML:
// const productCard = ...

/*
Should produce:
<div class="product">
    <h3>Laptop</h3>
    <p class="price">$999.99</p>
    <span class="stock">In Stock</span>
</div>
*/

/*
Solution:
const productCard = `
<div class="product">
    <h3>${product.name}</h3>
    <p class="price">$${product.price}</p>
    <span class="stock">${product.inStock ? 'In Stock' : 'Out of Stock'}</span>
</div>
`;
console.log(productCard);
*/

// --------------------------------------------

// Exercise 4: Nested Template Literals
// Create an unordered list from an array
const colors = ['Red', 'Green', 'Blue', 'Yellow'];

// Your code here - create colorList:
// const colorList = ...

/*
Should produce:
<ul>
    <li>Red</li>
    <li>Green</li>
    <li>Blue</li>
    <li>Yellow</li>
</ul>
*/

/*
Solution:
const colorList = `
<ul>
${colors.map(color => `    <li>${color}</li>`).join('\n')}
</ul>
`;
console.log(colorList);
*/

// --------------------------------------------

// Exercise 5: Conditional in Template
// Create a user status message with conditional content
const user = {
  name: 'Alice',
  isOnline: true,
  lastSeen: '2 hours ago',
};

// Your code here - create userStatus:
// Show "Online now" if online, otherwise "Last seen: {lastSeen}"

/*
Solution:
const userStatus = `${user.name} - ${user.isOnline ? 'Online now' : `Last seen: ${user.lastSeen}`}`;
console.log(userStatus);  // 'Alice - Online now'
*/

// --------------------------------------------

// Exercise 6: Simple Tagged Template
// Create a tag function that converts all values to uppercase

// Your code here:
// function upperValues(strings, ...values) {
//     ...
// }

// const name = 'alice';
// const city = 'new york';
// const result = upperValues`${name} lives in ${city}`;
// console.log(result);  // Should print: 'ALICE lives in NEW YORK'

/*
Solution:
function upperValues(strings, ...values) {
    return strings.reduce((result, str, i) => {
        const value = values[i] !== undefined 
            ? String(values[i]).toUpperCase() 
            : '';
        return result + str + value;
    }, '');
}

const name = 'alice';
const city = 'new york';
const result = upperValues`${name} lives in ${city}`;
console.log(result);  // 'ALICE lives in NEW YORK'
*/

// --------------------------------------------

// Exercise 7: HTML Escape Tag
// Create a tag function that escapes HTML special characters

// Your code here:
// function safeHTML(strings, ...values) {
//     ...
// }

// const userInput = '<script>alert("hack")</script>';
// const output = safeHTML`<div>User says: ${userInput}</div>`;
// Should escape < > " characters

/*
Solution:
function safeHTML(strings, ...values) {
    const escape = str => String(str)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;');
    
    return strings.reduce((result, str, i) => {
        const value = values[i] !== undefined ? escape(values[i]) : '';
        return result + str + value;
    }, '');
}

const userInput = '<script>alert("hack")</script>';
const output = safeHTML`<div>User says: ${userInput}</div>`;
console.log(output);
// '<div>User says: &lt;script&gt;alert(&quot;hack&quot;)&lt;/script&gt;</div>'
*/

// --------------------------------------------

// Exercise 8: Currency Formatter Tag
// Create a tag that formats numbers as currency

// Your code here:
// function usd(strings, ...values) {
//     ...
// }

// const amount = 1234.5;
// const formatted = usd`Total: ${amount}`;
// console.log(formatted);  // Should print: 'Total: $1,234.50'

/*
Solution:
function usd(strings, ...values) {
    return strings.reduce((result, str, i) => {
        let value = values[i];
        if (typeof value === 'number') {
            value = '$' + value.toLocaleString('en-US', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
        }
        return result + str + (value !== undefined ? value : '');
    }, '');
}

const amount = 1234.5;
const formatted = usd`Total: ${amount}`;
console.log(formatted);  // 'Total: $1,234.50'
*/

// --------------------------------------------

// Exercise 9: Debug Logger Tag
// Create a tag that logs variable names and values

// Your code here:
// function debug(strings, ...values) {
//     // Should show: "x = 5, y = 10"
// }

// const x = 5;
// const y = 10;
// debug`x = ${x}, y = ${y}`;

/*
Solution:
function debug(strings, ...values) {
    const output = strings.reduce((result, str, i) => {
        const value = values[i];
        if (value !== undefined) {
            const type = typeof value;
            return result + str + `[${type}:${JSON.stringify(value)}]`;
        }
        return result + str;
    }, '');
    console.log('[DEBUG]', output);
    return output;
}

const x = 5;
const y = 10;
debug`x = ${x}, y = ${y}`;
// [DEBUG] x = [number:5], y = [number:10]
*/

// --------------------------------------------

// Exercise 10: String.raw Usage
// Use String.raw for a Windows file path and regex pattern

// Your code here:
// const windowsPath = ...  // Should be: C:\Users\Documents\file.txt
// const regexPattern = ... // Should be: \d{3}-\d{4}

/*
Solution:
const windowsPath = String.raw`C:\Users\Documents\file.txt`;
console.log(windowsPath);  // C:\Users\Documents\file.txt

const regexPattern = String.raw`\d{3}-\d{4}`;
console.log(regexPattern);  // \d{3}-\d{4}
const regex = new RegExp(regexPattern);
console.log(regex.test('123-4567'));  // true
*/

// --------------------------------------------

// Exercise 11: Table Generator
// Create a function that generates an HTML table from data

// Your code here:
// function generateTable(headers, rows) {
//     ...
// }

const headers = ['Name', 'Age', 'City'];
const rows = [
  ['Alice', 30, 'NYC'],
  ['Bob', 25, 'LA'],
  ['Charlie', 35, 'Chicago'],
];

// const table = generateTable(headers, rows);
// Should produce a properly formatted HTML table

/*
Solution:
function generateTable(headers, rows) {
    return `
<table>
    <thead>
        <tr>
${headers.map(h => `            <th>${h}</th>`).join('\n')}
        </tr>
    </thead>
    <tbody>
${rows.map(row => `        <tr>
${row.map(cell => `            <td>${cell}</td>`).join('\n')}
        </tr>`).join('\n')}
    </tbody>
</table>
    `.trim();
}

const table = generateTable(headers, rows);
console.log(table);
*/

// --------------------------------------------

// Exercise 12: Pluralization Tag
// Create a tag that handles singular/plural forms

// Your code here:
// function plural(strings, ...values) {
//     // If value is 1, use singular, otherwise plural
// }

// const itemCount = 1;
// const result = plural`You have ${itemCount} item(s)`;
// // Should print: 'You have 1 item'

// const itemCount2 = 5;
// const result2 = plural`You have ${itemCount2} item(s)`;
// // Should print: 'You have 5 items'

/*
Solution:
function plural(strings, ...values) {
    let result = strings[0];
    
    for (let i = 0; i < values.length; i++) {
        result += values[i];
        let nextStr = strings[i + 1];
        
        // Handle (s) pattern
        if (nextStr && nextStr.includes('(s)')) {
            const isSingular = values[i] === 1;
            nextStr = nextStr.replace('(s)', isSingular ? '' : 's');
        }
        
        result += nextStr || '';
    }
    
    return result;
}

const itemCount = 1;
console.log(plural`You have ${itemCount} item(s)`);  // 'You have 1 item'

const itemCount2 = 5;
console.log(plural`You have ${itemCount2} item(s)`);  // 'You have 5 items'
*/

// --------------------------------------------

// Exercise 13: SQL Query Builder
// Create a tag for safe SQL query building

// Your code here:
// function sql(strings, ...values) {
//     return { query: ..., params: ... };
// }

// const userId = 123;
// const status = 'active';
// const query = sql`SELECT * FROM users WHERE id = ${userId} AND status = ${status}`;
// // Should return: { query: 'SELECT * FROM users WHERE id = ? AND status = ?', params: [123, 'active'] }

/*
Solution:
function sql(strings, ...values) {
    const query = strings.reduce((result, str, i) => {
        return result + str + (i < values.length ? '?' : '');
    }, '');
    
    return { query, params: values };
}

const userId = 123;
const status = 'active';
const query = sql`SELECT * FROM users WHERE id = ${userId} AND status = ${status}`;
console.log(query);
// { query: 'SELECT * FROM users WHERE id = ? AND status = ?', params: [123, 'active'] }
*/

// --------------------------------------------

// Exercise 14: Markdown Bold Tag
// Create a tag that wraps interpolated values in markdown bold

// Your code here:
// function bold(strings, ...values) {
//     ...
// }

// const name = 'JavaScript';
// const version = 'ES6';
// const result = bold`Learn ${name} with ${version} features`;
// // Should print: 'Learn **JavaScript** with **ES6** features'

/*
Solution:
function bold(strings, ...values) {
    return strings.reduce((result, str, i) => {
        const value = values[i] !== undefined ? `**${values[i]}**` : '';
        return result + str + value;
    }, '');
}

const name = 'JavaScript';
const version = 'ES6';
const result = bold`Learn ${name} with ${version} features`;
console.log(result);  // 'Learn **JavaScript** with **ES6** features'
*/

// --------------------------------------------

// Exercise 15: Email Template Builder
// Create a function that builds an email template

// Your code here:
// function buildEmail({ to, subject, greeting, body, signature }) {
//     ...
// }

const emailData = {
  to: 'john@example.com',
  subject: 'Welcome!',
  greeting: 'Dear John',
  body: 'Thank you for signing up for our service.',
  signature: 'The Team',
};

// const email = buildEmail(emailData);
// Should produce a nicely formatted email template

/*
Solution:
function buildEmail({ to, subject, greeting, body, signature }) {
    return `
To: ${to}
Subject: ${subject}
---

${greeting},

${body}

Best regards,
${signature}
    `.trim();
}

const email = buildEmail(emailData);
console.log(email);
*/
Exercises - JavaScript Tutorial | DeepML