Hone logo
Hone
Problems

Implement take Function in JavaScript

The take function is a fundamental utility in many programming languages, especially in functional programming paradigms. It's used to extract a specified number of elements from the beginning of an array or a string. Mastering take is crucial for efficient data manipulation and building more complex array-processing functions.

Problem Description

Your task is to implement a JavaScript function called take that accepts two arguments: an array or string (let's call it collection) and a non-negative integer (let's call it n).

The function should return a new array containing the first n elements of the collection. If the collection has fewer than n elements, the function should return all elements of the collection. If n is 0 or negative, it should return an empty array.

Key Requirements:

  • The function must handle both arrays and strings as the collection argument.
  • The returned value must always be an array.
  • The original collection should not be modified.

Examples

Example 1:

Input: collection = [1, 2, 3, 4, 5], n = 3
Output: [1, 2, 3]
Explanation: We take the first 3 elements from the array.

Example 2:

Input: collection = "hello", n = 2
Output: ["h", "e"]
Explanation: We take the first 2 characters from the string and return them as an array.

Example 3:

Input: collection = [10, 20], n = 5
Output: [10, 20]
Explanation: The collection has fewer than n elements, so all elements are returned.

Example 4:

Input: collection = [1, 2, 3], n = 0
Output: []
Explanation: When n is 0, an empty array is returned.

Example 5:

Input: collection = [1, 2, 3], n = -2
Output: []
Explanation: When n is negative, an empty array is returned.

Constraints

  • n will be an integer.
  • The collection will either be an array or a string.
  • The collection can be empty.
  • Performance is important; the solution should be reasonably efficient for large collections.

Notes

  • Consider how you can handle both arrays and strings with a single implementation.
  • Think about edge cases like an empty collection or n being larger than the collection's length.
  • You might find built-in array methods helpful, but consider if they directly solve the problem or if you need to combine them.
Loading editor...
javascript