There is a task, you need to create a function that will return an array of n elements to fill in according to the pattern (the second variable that is passed to the function). So if you pass numbers, strings, etc. then everything is simple, but it is also necessary to transfer the function, and here is the problem.

function sequence(n, pattern) { let arr = new Array(n); arr.fill(pattern) return arr } sequence(4, arg => arg%2).forEach((func,i) => console.log(func(i))); 

Here is my code.

  • What is the problem? I had no problems, everything works as it should - Darth
  • I’ll correct the question a bit; you don’t just need to transfer the function to the array, but rather that it is executed. For example (i) => i% 2 that would return the remainder of dividing the index by 2 - Pavel Yukhnevich
  • I already corrected your question a little, everything works, the remainder of dividing the index in the console. What is your question? - Darth
  • thanks, blunted a little) - Pavel Yukhnevich

2 answers 2

You can write a check whether the argument is a function or not, and then fill the array accordingly:

 function isFunction(functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; } function sequence(n, pattern) { let arr = new Array(n); if (isFunction(pattern)) { for (i = 0; i < arr.length; i++) { arr[i] = pattern(i); } } else { arr.fill(pattern) } return arr } 

Or implement more interesting ways available in ES5:

 function sequence(n, pattern) { return Array.apply(null, {length: n}).map(Function.call, Number).map(pattern); } 

Or for ES6:

 function sequence(n, pattern) { return Array.from(Array(n).keys()).map(pattern); } 

    Everything works, created an array of 10 functions, namely, 10 of your functions in the array, your function.

    enter image description here enter image description here

    • I’ll correct the question a bit; you don’t just need to transfer the function to the array, but rather that it is executed. For example (i) => i% 2 that would return the remainder of dividing the index by 2 - Pavel Yukhnevich