Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array filter function with multiply choices using closure - Javascript

I need to create a function for filter and it must have 2 choices.

  1. inBetween(a, b) - which will return array between a and b
  2. inArray([...]) - which will return an array of items that match with filtering array.

Something like this:

let arr = [1, 2, 3, 4, 5, 6, 7];

console.log( arr.filter(f(inBetween(3, 6))) ); // 3,4,5,6
console.log( arr.filter(f(inArray([1, 2, 10]))) ); // 1,2

I tried this function:

function f(item) {
  let result = [];

  function inBetween(from, to){
    if (item >= from && item <= to){
      result.push(item);
    }
  }

  function inArray(array){
    if (array.indexOf(item) >= 0){
      result.push(item);
    }
  }

  return result;
}

But I don't know how to attach my function into filter. It gives this error:

console.log( arr.filter(f(inBetween(3, 6))) ); // 3,4,5,6

ReferenceError: inBetween is not defined

Is it somehow possible?

like image 293
Robert Hovhannisyan Avatar asked Dec 22 '22 21:12

Robert Hovhannisyan


1 Answers

array.filter() requires a function. If you want to pre-bind some parameters, you'll need a function that returns a function. In this case, both inBetween and inArray should return functions.

So it should be:

let arr = [1, 2, 3, 4, 5, 6, 7];

function inBetween(min, max) {
  return function(value) {
    // When this is called by array.filter(), it can use min and max.
    return min <= value && value <= max
  }
}

function inArray(array) {
  return function(value) {
    // When this is called by array.filter(), it can use array.
    return array.includes(value)
  }
}

console.log( arr.filter(inBetween(3, 6)) )
console.log( arr.filter(inArray([1, 2, 10])) )

In this case, min, max, and array close over the returned function such that when array.filter() calls the returned function, it has access to those values.


Your inArray() functionality is already implemented by the native array.includes().

like image 79
Joseph Avatar answered Dec 28 '22 09:12

Joseph