2

UPDATE

There was a problem with the Chai test that the class provided. Thanks for all of your help anyway!

I'm working on a problem for a class. It asks us to write a function called "each." It should call iterator(value, key, collection) for each element of collection. It should iterate over arrays, providing access to the element, index, and array itself. It also should only iterate over the array elements, not properties of the array (another problem I'm having). It also accepts both arrays and objects.

On the test I'm running (at the bottom), it should return:

['ant', 'a', animals],
['bat', 'b', animals],
['cat', 'c', animals]

However, it is returning:

['ant', '0', Array[3] [0:"ant", 1:"bat", 2:"cat"]] 

...and so on in the array.

How do iterate over the array so that it returns the list name, rather than the full array itself?

var testeach = function(collection, iterator) {
        if (Array.isArray(collection)) {
            var len = collection.length;
            for (var i in collection)
                iterator(collection[i], collection.indexOf(collection[i]), collection);
        } else {
            for (var key in collection)
                if (collection.hasOwnProperty(key)) {
                     iterator(collection[key], key, collection);
                }
        }
    };

var animals = ['ant', 'bat', 'cat'];
var iterationInputs = [];
testeach(animals, function(animal, index, list) {
  iterationInputs.push([animal, index, list]);
});

console.log(iterationInputs);

Here is the code for the test, which uses Chai.

describe('each', function() {
      it('should iterate over arrays, providing access to the element, index, and array itself', function() {
        var animals = ['ant', 'bat', 'cat'];
        var iterationInputs = [];

        _.each(animals, function(animal, index, list) {
          iterationInputs.push([animal, index, list]);
        });

        expect(iterationInputs).to.eql([
          ['ant', 0, animals],
          ['bat', 1, animals],
          ['cat', 2, animals]
        ]);
      });
11
  • Make sure you're reading and understanding the problem correctly. Perhaps your interpreting the desired output incorrectly. The word "animals" doesn't have string quotes around it... Commented Sep 21, 2016 at 17:45
  • Thanks, Nate. I pulled the desired output directly form the unit test. It definitely wants the variable name of the input array. In the example, the array animals is provided. Commented Sep 21, 2016 at 17:47
  • 1
    Ah, okay, it's not looking for the name, it's looking to see if the array within the array are the same. Commented Sep 21, 2016 at 18:14
  • 1
    I mean, it's not looking for the string "animals", it's looking to see if the last element in each array (e.g., ['ant', 0, **animals**]) has the same items (['ant', 'bat', 'cat']) as is defined in the test (the var animals ... line), which happens to use the same variable name as the one in your code. Commented Sep 21, 2016 at 18:34
  • 1
    In other words, the test should be passing, assuming Chai's eql method does a deep comparison of arrays. Commented Sep 21, 2016 at 18:36

2 Answers 2

4

As far as JavaScript (and possibly your class instructor) are concerned, Array[3] [0:"ant", 1:"bat", 2:"cat"] is animals. It's not completely correct to say that they can be used interchangeably, but for the purposes of your assignment, that is probably the case.

You can think of animals as a signpost pointing at the array itself (Array[3] [0:"ant", 1:"bat", 2:"cat"]). So if your assignment says it wants animals, it might just be misleadingly written because the assignment writer didn't want to write out the whole array.

Sign up to request clarification or add additional context in comments.

5 Comments

That's what I was thinking! But the assignment checks the code through a unit test using Chai. The test keeps failing. It says, expect(iterationInputs).to.eql([ ['ant', 0, animals], ['bat', 1, animals], ['cat', 2, animals] ]);
@CarolynCommons Looks like that just proves it. It doesn't say eql([ ['ant', 0, 'animals'], ... ]). Notice that there are no quotes around the animals part. animals in the context of the unit test is a variable, probably pointing to an array that's defined high up the chain.
@JosephMarikle That makes sense, but the test is still failing. I provided the test code above. Any thoughts on why it is still failing?
@CarolynCommons Hm... now that I look at it closer, it could be the "index" part. your code is returning 'ant', 'a', Array[3] [ ...' you said. Isn't it supposed to return 'ant', 0, Array[3] [ ...? Note the 0 in place of a
Oops, I just typed it in wrong. Fixed it above. It is indeed returning 'ant', 0, Array[3] [ ... Didn't mean to confuse you!
4

You can't do this. It's a variable identifier, and you can't get a variable name unless you parse the code and you get the abstract syntax tree.

6 Comments

Returning the string "animals" is not what is needed here.
@vlaz But OP said on the question this: How do iterate over the array so that it returns the list name, rather than the full array itself?. What do you understand from the quote? I can fix my answer if you find another meaning to the question..
According to the unit tests ran against the output posted in the OP, the parameter is supposed to be the array itself. Which is also entirely consistent with the behaviour of forEach in JavaScript where the third parameter passed to the function is the array operated on. I fully understand the quote but it is very evident it was an XY problem that OP posed.
@vlaz you're right. BTW I'm not sure about dropping the entire answer or just leave there the original answer without the workaround...
Yes, I think that is fine. While it does not provide a concrete answer to OP's question, I think the mention of the AST parsing is valuable nonetheless.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.