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

filter #74

Closed jsartisan closed 3 months ago

jsartisan commented 3 months ago

Info

difficulty: easy
title: filter
type: question
template: javascript
tags: javascript

Question

Implement a custom arrayFilter function that mimics the behavior of the native filter method.

Arguments

The arrayFilter 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.

Return Value

The arrayFilter function should return a new array containing all the elements for which the callback function returns a truthy value.

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

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

const isEven = (num) => num % 2 === 0;

const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = arrayFilter(numbers, isEven);

console.log(evenNumbers);
// Output: [2, 4, 6]

Template

index.js

export function arrayFilter(array, callback) {
 // Your code here
}

index.test.js

import { arrayFilter } from './';

describe('arrayFilter function', () => {
  it('should filter even numbers', () => {
    const isEven = (num) => num % 2 === 0;
    const numbers = [1, 2, 3, 4, 5, 6];
    const evenNumbers = arrayFilter(numbers, isEven);
    expect(evenNumbers).toEqual([2, 4, 6]);
  });

  it('should filter odd numbers', () => {
    const isOdd = (num) => num % 2 !== 0;
    const numbers = [1, 2, 3, 4, 5, 6];
    const oddNumbers = arrayFilter(numbers, isOdd);
    expect(oddNumbers).toEqual([1, 3, 5]);
  });

  it('should return an empty array if no elements match', () => {
    const isGreaterThanTen = (num) => num > 10;
    const numbers = [1, 2, 3, 4, 5, 6];
    const filteredNumbers = arrayFilter(numbers, isGreaterThanTen);
    expect(filteredNumbers).toEqual([]);
  });

  it('should handle an empty array', () => {
    const isEven = (num) => num % 2 === 0;
    const numbers = [];
    const evenNumbers = arrayFilter(numbers, isEven);
    expect(evenNumbers).toEqual([]);
  });

  it('should pass the correct arguments to the callback', () => {
    const mockCallback = jest.fn();
    const numbers = [1, 2, 3];
    arrayFilter(numbers, mockCallback);
    expect(mockCallback).toHaveBeenCalledWith(1, 0, numbers);
    expect(mockCallback).toHaveBeenCalledWith(2, 1, numbers);
    expect(mockCallback).toHaveBeenCalledWith(3, 2, numbers);
  });
});
github-actions[bot] commented 3 months ago

75 - Pull Request updated.