DEV Community


Posted on

How to solve the the 'contains' Function from Implementing Conway's Game of Life on pluralsight

Can someone help me with this problem.

Top comments (1)

ianbrayoni profile image


I helped a mentee with this problem. I was also not very clear on what was required.

The problem involves searching for an array, [1,2], in a search space which is a multidimensional array, e.g[[2,3], [3,4]]. However, the search space is passed in as part of this value to the function.

If we want to bind an object, [[2,3], [3,4]], as this to the contains function it would be contains.bind([[2,3], [3,4]]).

bind returns a new function, and that function then calls contains with the given value as this. If you check your test files, you will notice that bind is used to pass in the search space/state.

function contains(cell) {
   console.dir(this); // will print out [[2,3], [3,4]]
   console.dir(cell); // will print out [1,2]

const containsWithBind = contains.bind([[2,3], [3,4]])

Enter fullscreen mode Exit fullscreen mode

So the contains function should look something like the following, note how this is used in the function:

function contains(cell){
   let found = false;
   [x, y] = cell;

   // state available as `this`
   this.forEach((element) => {
     [j, k] = element;
     // match first occurrence in array
     if (x === j && y === k){
        found = true;
   return found;
Enter fullscreen mode Exit fullscreen mode

this and bind