-
Notifications
You must be signed in to change notification settings - Fork 7.1k
Description
Documentation claims to use string keyed properties:
An alternative to _.reduce; this method transforms object to a new accumulator object which is the result of running each of its own enumerable string keyed properties thru iteratee, with each invocation potentially mutating the accumulator object. If accumulator is not provided, a new object with the same [[Prototype]] will be used. The iteratee is invoked with four arguments: (accumulator, value, key, object). Iteratee functions may exit iteration early by explicitly returning false.
However in the source it checks for Array, and switches to arrayEach https://github.com/lodash/lodash/blob/4.13.1/lodash.js#L13130
Here's a demo of the difference in behaviour:
https://runkit.com/graingert/transform-bad-docs
const assert = require('assert');
const _ = require('lodash');
const collection = [1, 2, 3];
collection.foo = 4;
const newCollection = [];
for (let x in collection) {
if (Object.prototype.hasOwnProperty.call(collection, x)) {
newCollection.push(collection[x]);
}
}
assert.deepEqual(newCollection, [1, 2, 3, 4]);
const newCollection2 = _.transform(collection, (acc, next) => { acc.push(next) }, []);
assert.deepEqual(newCollection2, [1, 2, 3]);
console.log('iterating own string keyed properties', newCollection)
console.log('using transform', newCollection2);Perhaps the documentation should be updated like:
An alternative to _.reduce; this method transforms object to a new accumulator object which if object is a Array-like is the result of running each element in object thu iteratee, else is the result of running each of its own enumerable string keyed properties thru iteratee, with each invocation potentially mutating the accumulator object. If accumulator is not provided, a new object with the same [[Prototype]] will be used. The iteratee is invoked with four arguments: (accumulator, value, key, object). Iteratee functions may exit iteration early by explicitly returning false.
Or the check should be removed and _.transform should always use string keyed properties