Understanding Arrify a Simple yet Powerful Utility Function

Understanding `arrify`: A Simple yet Powerful Utility Function

`arrify` is a lightweight utility function that ensures a given input is always returned as an array. This is particularly useful when you want to handle both single values and arrays uniformly in your code.

Basic Usage of `arrify`

The most basic use case for `arrify` is converting a single value to an array:


const arrify = (input) => (Array.isArray(input) ? input : [input]);

console.log(arrify('hello')); 
// Output: ['hello']

console.log(arrify(['hello', 'world'])); 
// Output: ['hello', 'world']

Handling Null and Undefined

`arrify` can gracefully handle null and undefined inputs, returning an empty array:


console.log(arrify(null)); 
// Output: []

console.log(arrify(undefined)); 
// Output: []

Dealing with Objects and Other Data Types

`arrify` can be used with various data types, ensuring they are returned as array elements:


console.log(arrify(123)); 
// Output: [123]

console.log(arrify({ key: 'value' })); 
// Output: [{ key: 'value' }]

An Example Application with `arrify`

Here’s a simple app that uses `arrify` to handle different types of inputs uniformly. This example demonstrates fetching data for multiple users, whether the user list is passed as a single ID or an array of IDs:


const fetchDataForUsers = (userIDs) => {
  const ids = arrify(userIDs);
  return ids.map(id => `Fetching data for user ${id}`);
};

console.log(fetchDataForUsers(1)); 
// Output: ['Fetching data for user 1']

console.log(fetchDataForUsers([1, 2, 3])); 
// Output: ['Fetching data for user 1', 'Fetching data for user 2', 'Fetching data for user 3']

Conclusion

`arrify` is a simple yet powerful function that can make your code more robust and easier to handle. Whether dealing with single values or arrays, `arrify` ensures your inputs are always in a consistent format.

Hash: 4a7320d4de4a1ab58487861b2a72a81838314ad54638cc0ce92cde7f10ef52c6

Leave a Reply

Your email address will not be published. Required fields are marked *