Hone logo
Hone
Problems

Adding the First Element to a TypeScript Array

This challenge focuses on manipulating arrays in TypeScript. You'll be tasked with writing a function that adds a new element to the beginning of an existing array, effectively creating a new array with the added element at index 0. This is a fundamental array operation useful in many programming scenarios, such as building lists dynamically or prepending data.

Problem Description

You need to create a TypeScript function called prependToArray that takes two arguments:

  1. existingArray: An array of any type (any[]). This is the array to which you'll be adding an element.
  2. newElement: An element of any type (any). This is the element you want to add to the beginning of the array.

The function should return a new array. This new array should contain all the elements of existingArray, but with newElement added as the first element (at index 0). The original existingArray should not be modified.

Key Requirements:

  • The function must be written in TypeScript.
  • The function must return a new array, not modify the original.
  • The function must handle arrays of any data type.
  • The function must correctly place the newElement at the beginning of the new array.

Expected Behavior:

The function should return a new array with the newElement as the first element, followed by all the elements of the original existingArray in their original order.

Edge Cases to Consider:

  • existingArray is an empty array ([]).
  • newElement is of a different type than the elements in existingArray (though this shouldn't cause an error, it's good to be aware of).

Examples

Example 1:

Input: ([1, 2, 3], 0)
Output: [0, 1, 2, 3]
Explanation: The new element 0 is added to the beginning of the array [1, 2, 3], resulting in the new array [0, 1, 2, 3].

Example 2:

Input: (["b", "c"], "a")
Output: ["a", "b", "c"]
Explanation: The new element "a" is added to the beginning of the array ["b", "c"], resulting in the new array ["a", "b", "c"].

Example 3:

Input: ([], 5)
Output: [5]
Explanation: When the existing array is empty, the new element becomes the only element in the new array.

Constraints

  • The existingArray can contain elements of any data type.
  • The newElement can be of any data type.
  • The function must not modify the original existingArray.
  • The time complexity of the solution should be O(n), where n is the length of the existingArray. (Creating a new array and copying elements is generally unavoidable for this task).

Notes

Consider using the spread operator (...) to create a new array. This is a concise and efficient way to copy the elements of the original array into the new array while inserting the newElement at the beginning. Remember that immutability is key – avoid directly modifying the input array.

Loading editor...
typescript