function createUserProfile(name, email, isAdmin) {
return {
name,
email,
isAdmin,
printDetails() {
console.log(`Name: ${this.name}, Email: ${this.email}, Admin: ${this.isAdmin}`);
}
};
}
const user1 = createUserProfile('Alice', '[email protected]', false);
const user2 = createUserProfile('Bob', '[email protected]', true);
user1.printDetails(); // Output: Name: Alice, Email: [email protected], Admin: false
user2.printDetails(); // Output: Name: Bob, Email: [email protected], Admin: true
State Initialization in React Components:
import React, { useState } from 'react';
function createTask(title, description, isCompleted) {
return {
title,
description,
isCompleted,
toggleComplete() {
this.isCompleted = !this.isCompleted;
}
};
}
function TaskList() {
const [tasks, setTasks] = useState([
createTask('Task 1', 'Description 1', false),
createTask('Task 2', 'Description 2', true)
]);
const toggleTaskCompletion = (index) => {
const newTasks = [...tasks];
newTasks[index].toggleComplete();
setTasks(newTasks);
};
return (
<div>
{tasks.map((task, index) => (
<div key={index}>
<h3>{task.title}</h3>
<p>{task.description}</p>
<p>Completed: {task.isCompleted ? 'Yes' : 'No'}</p>
<button onClick={() => toggleTaskCompletion(index)}>Toggle Complete</button>
</div>
))}
</div>
);
}
export default TaskList;
Configuration Objects:
function createConfig(url, method, headers) {
return {
url,
method,
headers,
getConfig() {
return {
url: this.url,
method: this.method,
headers: this.headers
};
}
};
}
const config1 = createConfig('<https://api.example.com>', 'GET', { 'Content-Type': 'application/json' });
const config2 = createConfig('<https://api.example.com>', 'POST', { 'Content-Type': 'application/x-www-form-urlencoded' });
console.log(config1.getConfig());
// Output: { url: '<https://api.example.com>', method: 'GET', headers: { 'Content-Type': 'application/json' } }
console.log(config2.getConfig());
// Output: { url: '<https://api.example.com>', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
Utility Objects:
function createMathUtility() {
return {
add(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
},
multiply(a, b) {
return a * b;
},
divide(a, b) {
return a / b;
}
};
}
const mathUtil = createMathUtility();
console.log(mathUtil.add(10, 5)); // Output: 15
console.log(mathUtil.subtract(10, 5)); // Output: 5
console.log(mathUtil.multiply(10, 5)); // Output: 50
console.log(mathUtil.divide(10, 5)); // Output: 2