Description
Inputs:
[specific utility functions or patterns]: ‘e.g., array manipulation, string formatting, asynchronous operations’
[specific problem domain]: ‘e.g., data processing, DOM manipulation, event handling’
Output:
Absolutely, let’s dive into crafting some JavaScript utility functions! Here’s a starting point with a few commonly used array manipulation functions along with their documentation and tests.
“`javascript
/**
* Filters an array based on a given predicate function.
* @param {Array} array – The array to filter.
* @param {Function} predicate – The predicate function used to filter elements.
* @returns {Array} – The filtered array.
*/
function filterArray(array, predicate) {
return array.filter(predicate);
}
/**
* Maps each element of an array through a mapping function.
* @param {Array} array – The array to map.
* @param {Function} mapper – The mapping function.
* @returns {Array} – The mapped array.
*/
function mapArray(array, mapper) {
return array.map(mapper);
}
/**
* Reduces an array to a single value using a reducer function.
* @param {Array} array – The array to reduce.
* @param {Function} reducer – The reducer function.
* @param {*} initialValue – The initial value.
* @returns {*} – The reduced value.
*/
function reduceArray(array, reducer, initialValue) {
return array.reduce(reducer, initialValue);
}
// Tests
function runTests() {
const numbers = [1, 2, 3, 4, 5];
// Test filterArray
const filteredArray = filterArray(numbers, num => num % 2 === 0);
console.log(“Filtered Array:”, filteredArray); // [2, 4]
// Test mapArray
const mappedArray = mapArray(numbers, num => num * 2);
console.log(“Mapped Array:”, mappedArray); // [2, 4, 6, 8, 10]
// Test reduceArray
const sum = reduceArray(numbers, (acc, curr) => acc + curr, 0);
console.log(“Sum:”, sum); // 15
}
runTests();
“`
Feel free to suggest enhancements or additional utility functions!
Reviews
There are no reviews yet.