简体   繁体   中英

Why is my function using lodash _.forEach returning the same value?

I am currently learning lodash and vitest. I created a simple function and an inline test with it.

Here is the test and the function below it

import _ from 'lodash'

if (import.meta.vitest) {
    const { describe, expect, it } = import.meta.vitest;

    describe('#name', () => {
        it('should..', () => {
            expect(
                collectForEach([1, 2], function (n) {
                    return n * 2;
                }),
            ).toEqual([2, 4]);
        });
    });
}

function collectForEach(collection, iteratee) {
    return _.forEach(collection, iteratee);
}

As stated in the test, I am expecting to return an array of [2,4]. However the test fails saying that the actual return is [1,2]. Am I misunderstanding how to use _.forEach or am I making a different type of error?

You should use lodash.map() .

Eg

import assert from 'assert'
import _ from 'lodash'

const collectMap = (collection, iteratee) => _.map(collection, iteratee)

const actual = collectMap([1,2], n => n * 2);
const expected = [2,4]
assert.deepStrictEqual(actual, expected, 'should pass')
console.log('actual: ', actual)

Execution result:

actual:  [ 2, 4 ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM