Hat Trick - 2703, 2635 and 2619

2703. Return Length of Arguments Passed

Write a function argumentsLength that returns the count of arguments passed to it.


My solution:

var argumentsLength = (...args) => args.length

In my solution, I accept any number of arguments captured inside the args array. The contents of the args array are not important as the length of said array is easily accesible and using arrow functions implicit return we return args.length.

This exercise appears to be an intro to the concept of dealing with an unknown number of arguments.

In this and most situations, the spread operator used in a function definition is because you either don't know the number of arguments being passed or you intend to allow for multiple arguments.

A good example of this would be a function that takes any amount of numbers and returns their sum:

function sum(...numbers) {
  return numbers.reduce((acc, curr) => acc + curr, 0);
}

console.log(sum(1, 2, 3));         // Output: 6
console.log(sum(4, 5, 6, 7, 8));   // Output: 30
console.log(sum(10));              // Output: 10



2635. Apply Transform Over Each Element in Array

Given an integer array arr and a mapping function fn, return a new array with a transformation applied to each element.

The returned array should be created such that returnedArray[i] = fn(arr[i], i).

Please solve it without the built-in Array.map method.


My solution:

var map = function(arr, fn) {
    const result = arr.map((x, i) => fn(x, i))
    return result
};

This problem is meant to have us recreate a simplified version of the Array.map method that runs a function over each element in the array, returning the array transformed.

First we can create a result variable that we equal to the output of our map function. We want to pass the function two variables, the current element and the current index. Luckily, Array.map passes the current element and index to the provided callback function respectively.

We then pass the callback (x, i) => fn(x, i) which returns the result of passing the current element and current index to the provided function for each element in the array.

We then return the newly transformed array.




2619. Array Prototype Last

Write code that enhances all arrays such that you can call the array.last() method on any array and it will return the last element. If there are no elements in the array, it should return -1.

You may assume the array is the output of JSON.parse.


My solution:

Array.prototype.last = function() {
    return this.length > 0 ? this.pop() : -1
};

There are two possible return conditions here, either we return the last element of the array or we return -1 if the array is empty.

This is a perfect case for the use of a ternary operator. The easiest way to think of the ternary operator is condition ? "return if true" : "return if false". This is very useful for simple situations that return different results based on a condition.

Side note - This is also absolutely necessary for conditional rendering in React.

Lastly, since my code is only one line you might think that this would be a perfect usecase for arrows single line implicit return.

Array.prototype.last = () => this.length > 0 ? this.pop() : -1

This looks pretty clean, you'd likely think this is fine.

Sadly, this no longer accomplishes what we're trying to do. The reason is that arrow functions do not have their own this binding. Instead, they lexically capture the this valueof the enclosing context in which they are defined. This behavior is often referred to as "lexical this."

For this reason, we need to use a regular function so that we can have access to the this and manipulate it as needed. In this case we return this.pop(), the Array.pop function returning the last value of an array.

We've enhanced arrays with a last() method that returns the last element or -1 if the array is empty. The solution introduces a custom implementation using Array.prototype.last and a ternary operator to handle the two return conditions. It emphasizes the need for a regular function instead of an arrow function to preserve access to this and manipulate it accordingly. This article highlights the practicality of the ternary operator for simple conditional scenarios and showcases the importance of lexical this in JavaScript.