From 6381b5b08f69cc55cbc55564956550001cbec653 Mon Sep 17 00:00:00 2001 From: Jonas Jenwald Date: Thu, 16 Jul 2020 11:57:50 +0200 Subject: [PATCH] Add a `size` getter, to `Dict` instances, to provide an easier way of checking the number of entries This removes the need to manually call `Dict.getKeys()` and check its length. --- src/core/document.js | 2 +- src/core/primitives.js | 4 ++++ test/unit/primitives_spec.js | 11 +++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/core/document.js b/src/core/document.js index 45b6abcfd..1e02d414c 100644 --- a/src/core/document.js +++ b/src/core/document.js @@ -551,7 +551,7 @@ class PDFDocument { // Check if a Collection dictionary is present in the document. try { const collection = this.catalog.catDict.get("Collection"); - if (isDict(collection) && collection.getKeys().length > 0) { + if (isDict(collection) && collection.size > 0) { this.collection = collection; } } catch (ex) { diff --git a/src/core/primitives.js b/src/core/primitives.js index f9c7ecbdb..06d0e21d9 100644 --- a/src/core/primitives.js +++ b/src/core/primitives.js @@ -85,6 +85,10 @@ var Dict = (function DictClosure() { this.xref = newXref; }, + get size() { + return Object.keys(this._map).length; + }, + // automatically dereferences Ref objects get(key1, key2, key3) { let value = this._map[key1]; diff --git a/test/unit/primitives_spec.js b/test/unit/primitives_spec.js index fa1c3ab9b..cbd3d01f5 100644 --- a/test/unit/primitives_spec.js +++ b/test/unit/primitives_spec.js @@ -117,6 +117,17 @@ describe("primitives", function () { expect(dict.xref).toEqual(xref); }); + it("should return correct size", function () { + const dict = new Dict(null); + expect(dict.size).toEqual(0); + + dict.set("Type", Name.get("Page")); + expect(dict.size).toEqual(1); + + dict.set("Contents", Ref.get(10, 0)); + expect(dict.size).toEqual(2); + }); + it("should return invalid values for unknown keys", function () { checkInvalidHasValues(emptyDict); checkInvalidKeyValues(emptyDict);