Example input
[Specify language, e.g., Python, JavaScript, etc.]: JavaScript
[Describe the task, e.g., 'Create a function that sorts an array of numbers in descending order,' or 'Develop a RESTful API endpoint for a user login system.']: Create a function that sorts an array of numbers in descending order '
[List any constraints, e.g., 'Use only built-in functions,' or 'Must execute within 1 second for input sizes up to 1 million elements.']: Use only built-in functions,' or 'Must execute within 1 second for input sizes up to 1 million elements.'
[If applicable, define what needs to be optimized, like speed, memory usage, etc.]: If applicable, define what needs to be optimized, like speed, memory usage, etc.
[JavaScript]: javascript
['Random Quote Generator
Display a random motivational quote each time a button is clicked. This can be hard-coded with a few quotes.']: Create a function that sorts an array of numbers in descending order '
['Use only built-in functions,' or 'Must execute within 1 second for input sizes up to 1 million elements.']: 'Use only built-in functions,' or 'Must execute within 1 second for input sizes up to 1 million elements.
['Simple Calculator
A basic calculator that can perform addition, subtraction, multiplication, and division.']: Create a function that sorts an array of numbers in descending order '
Example output
Sorting an Array in Descending Order
/**
* Sorts an array of numbers in descending order.
* Uses JavaScript's built-in sort method, which is optimized for most cases.
*
* @param {number[]} numbers - Array of numbers to be sorted.
* @returns {number[]} - New array with numbers sorted in descending order.
*/
function sortDescending(numbers) {
// Clone the input array to avoid modifying the original
let sortedNumbers = numbers.slice();
// Sort in descending order by comparing two numbers and returning the correct value
// JavaScript's sort function is generally O(n log n) in time complexity, efficient for large arrays
sortedNumbers.sort((a, b) => b - a);
return sortedNumbers;
}
// Example usage
const numbers = [34, 12, 56, 78, 1, 23];
console.log(sortDescending(numbers)); // Output: [78, 56, 34, 23, 12, 1]