jsartisan / frontend-challenges

FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
https://frontend-challenges.com
27 stars 4 forks source link

Array.prototype.map #78

Closed jsartisan closed 3 months ago

jsartisan commented 3 months ago

Info

difficulty: easy
title: Array.prototype.map
type: question
template: javascript
tags: javascript

Question

Implement a custom arrayMap function that mimics the behavior of the native map method.

The arrayMap function should take an array and a callback function as arguments. The callback function should be invoked with three arguments: the current element, the index of the current element, and the array itself. The arrayMap function should return a new array containing the results of applying the callback function to each element of the original array.

Use the following example to understand how the arrayMap function should work:

const arrayMap = (array, callback) => {
  // Your implementation here
};

const multiplyByTwo = (num) => num * 2;

const numbers = [1, 2, 3, 4, 5, 6];
const doubledNumbers = arrayMap(numbers, multiplyByTwo);

console.log(doubledNumbers);
// Output: [2, 4, 6, 8, 10, 12]

Template

index.js

export function arrayMap(array, callback) {
  // your code here
}

index.test.js

import { arrayMap } from './';

describe('arrayMap function', () => {
  it('should double the numbers', () => {
    const multiplyByTwo = (num) => num * 2;
    const numbers = [1, 2, 3, 4, 5, 6];
    const doubledNumbers = arrayMap(numbers, multiplyByTwo);
    expect(doubledNumbers).toEqual([2, 4, 6, 8, 10, 12]);
  });

  it('should add index to each number', () => {
    const addIndex = (num, index) => num + index;
    const numbers = [1, 2, 3, 4, 5, 6];
    const indexedNumbers = arrayMap(numbers, addIndex);
    expect(indexedNumbers).toEqual([1, 3, 5, 7, 9, 11]);
  });

  it('should return an empty array when the input array is empty', () => {
    const multiplyByTwo = (num) => num * 2;
    const numbers = [];
    const doubledNumbers = arrayMap(numbers, multiplyByTwo);
    expect(doubledNumbers).toEqual([]);
  });

  it('should pass the correct arguments to the callback', () => {
    const mockCallback = jest.fn();
    const numbers = [1, 2, 3];
    arrayMap(numbers, mockCallback);
    expect(mockCallback).toHaveBeenCalledWith(1, 0, numbers);
    expect(mockCallback).toHaveBeenCalledWith(2, 1, numbers);
    expect(mockCallback).toHaveBeenCalledWith(3, 2, numbers);
  });

  it('should transform elements to strings', () => {
    const toString = (num) => num.toString();
    const numbers = [1, 2, 3, 4, 5, 6];
    const stringNumbers = arrayMap(numbers, toString);
    expect(stringNumbers).toEqual(['1', '2', '3', '4', '5', '6']);
  });
});
github-actions[bot] commented 3 months ago

79 - Pull Request updated.