gpt-4o-mini-2024-07-18· openai
WildChat-4.8M
Как здесь строку operation привести к соответствующей функции? function…
- User
Как здесь строку operation привести к соответствующей функции? function getOperation(operation, a, b){ return operation(a, b); }
let add = (a, b) => a + b; let sub = (a, b) => a - b; let prod = (a, b) => a * b; let min = (a, b) => Math.min(a, b); let max = (a, b) => Math.max(a, b); let avg = (a, b) => (a + b) / 2;
- Assistant
Чтобы привести строку
operationк соответствующей функции, вы можете использовать объект для сопоставления строк и функций. Например, создайте объект, который будет содержать ключи с названиями операций и значения с соответствующими функциями. Вот пример реализации:function getOperation(operation, a, b) { const operations = { add: (a, b) => a + b, sub: (a, b) => a - b, prod: (a, b) => a * b, min: (a, b) => Math.min(a, b), max: (a, b) => Math.max(a, b), avg: (a, b) => (a + b) / 2 }; // Проверяем, существует ли операция в объекте if (operations[operation]) { return operations[operation](a, b); } else { throw new Error(`Операция "${operation}" не поддерживается.`); } } // Примеры использования console.log(getOperation('add', 5, 3)); // 8 console.log(getOperation('sub', 5, 3)); // 2 console.log(getOperation('prod', 5, 3)); // 15 console.log(getOperation('min', 5, 3)); // 3 console.log(getOperation('max', 5, 3)); // 5 console.log(getOperation('avg', 5, 3)); // 4
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.