1

I currently have a function that allows me to test if something a piece (for connect 4) is in an array, as well as 1, 2, and less respectively. If all 4 numbers are in the array are present, then it returns true. This works.

What I am trying to do is make it so I can use .some, so I can test if the array contains any cases of having a number, and again 3, 2, and 1 less than the number tested.

Right now it will test an individual piece, but I don't know how to get it to grab onto the array to check the index of the individual element it is testing. Thank you for any responses/Ideas.

const testPieces = [1, 2, 3, 4]

const fourInARow = function(piece, array) {
  for (var i = piece; i >= piece - 3; i--) {
    if (array.indexOf(i) === -1) {
      return false
    }
  }
  return true
}
testPieces.some(fourInARow) // The piece that I don't know how to make work
Dave Anderson
  • 11,836
  • 3
  • 58
  • 79
Julian Sirkin
  • 47
  • 1
  • 3
  • 2
    I've read this a few times and I still don't get what you're asking. Imagine that we don't know anything about your project and try again. Provide sample input/output for your imaginary function `some` with explanations. – Lee Taylor Aug 03 '18 at 01:41

2 Answers2

0

Calling .some on your testPieces array will pass in each element of the array to the fourInARow function as the piece argument. It will not pass in your second array argument.

You need to provide a function to the .some call that already knows about the array for testing. You can do this by returning a function from the function e.g.

const fourInARow = function(array) {
  return function(piece) {
    for (var i = piece; i >= piece - 3; i--) {
      if (array.indexOf(i) === -1) {
        return false
      }
    }
    return true
  };
}

The array you are testing can now be passed to the .some call like this;

testPieces.some(fourInARow([1,2]));

The returned function has created a closure which retains a reference to the test array [1,2] which is then compared to the piece argument supplied by the call to .some.

Dave Anderson
  • 11,836
  • 3
  • 58
  • 79
  • Thank you sir! I appreciate the response. I got it to work with another for loop using this as a callback, but I will still try out your solution still, because it is a lot cleaner than what I have. – Julian Sirkin Aug 03 '18 at 02:13
0

Just wondering why not flip the logic to start from the other side and use instead of some every with includes?

const testPieces = [1, 2, 3, 4]

const inARow = (arr, base) => arr.every((x) => base.includes(x))

console.log(inARow([4,3,1,2], testPieces))
console.log(inARow([5,2,1], testPieces))

It becomes one line, it does not care about the order etc. Let me know if I am missing something ...

Akrion
  • 18,117
  • 1
  • 34
  • 54