From 25eb4df5633351cf7577c167942fcf81340922f7 Mon Sep 17 00:00:00 2001 From: John-David Dalton Date: Mon, 21 Mar 2016 20:16:15 -0700 Subject: [PATCH] Add support for maps and sets to `_.size`. --- lodash.js | 6 ++++++ test/test.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/lodash.js b/lodash.js index db04ca13f..b405e83de 100644 --- a/lodash.js +++ b/lodash.js @@ -8572,6 +8572,12 @@ var result = collection.length; return (result && isString(collection)) ? stringSize(collection) : result; } + if (isObjectLike(collection)) { + var tag = getTag(collection); + if (tag == mapTag || tag == setTag) { + return collection.size; + } + } return keys(collection).length; } diff --git a/test/test.js b/test/test.js index 425e23281..4c0c869e6 100644 --- a/test/test.js +++ b/test/test.js @@ -19104,6 +19104,34 @@ assert.strictEqual(_.size(new Foo(array)), 3); }); + QUnit.test('should work with maps', function(assert) { + assert.expect(1); + + if (Map) { + var map = new Map; + map.set('a', 1); + map.set('b', 2); + assert.strictEqual(_.size(map), 2); + } + else { + skipAssert(assert); + } + }); + + QUnit.test('should work with sets', function(assert) { + assert.expect(1); + + if (Set) { + var set = new Set; + set.add(1); + set.add(2); + assert.strictEqual(_.size(set), 2); + } + else { + skipAssert(assert); + } + }); + QUnit.test('should not treat objects with negative lengths as array-like', function(assert) { assert.expect(1);