Add a getOrPutComputed method in the RefSetCache class

This is equivalent to the native `Map.prototype.getOrInsertComputed()` method, and it helps simplify/shorten some existing code.
This commit is contained in:
Jonas Jenwald 2026-07-15 13:19:37 +02:00
parent c661ba1408
commit a18b581f00
5 changed files with 22 additions and 22 deletions

View File

@ -455,12 +455,7 @@ class PDFEditor {
// Re-entry means a (malformed) cycle back to this stream: allocate its
// reference now to break the loop, like the generic path's eager alloc.
if (resourceStreamPath.has(oldRef)) {
let ref = oldRefMapping.get(oldRef);
if (!ref) {
ref = this.newRef;
oldRefMapping.put(oldRef, ref);
}
return ref;
return oldRefMapping.getOrPutComputed(oldRef, () => this.newRef);
}
const key = oldRef.toString();

View File

@ -228,11 +228,7 @@ class GlobalImageCache {
}
shouldCache(ref, pageIndex) {
let pageIndexSet = this._refCache.get(ref);
if (!pageIndexSet) {
pageIndexSet = new Set();
this._refCache.put(ref, pageIndexSet);
}
const pageIndexSet = this._refCache.getOrPutComputed(ref, () => new Set());
pageIndexSet.add(pageIndex);
if (pageIndexSet.size < GlobalImageCache.NUM_PAGES_THRESHOLD) {

View File

@ -398,6 +398,16 @@ class RefSetCache {
this._map.set(ref.toString(), this.get(aliasRef));
}
getOrPutComputed(ref, callback) {
const map = this._map,
refStr = ref.toString();
if (!map.has(refStr)) {
map.set(refStr, callback(ref));
}
return map.get(refStr);
}
[Symbol.iterator]() {
return this._map.values();
}

View File

@ -93,12 +93,7 @@ class StructTreeRoot {
return;
}
this.structParentIds ||= new RefSetCache();
let ids = this.structParentIds.get(pageRef);
if (!ids) {
ids = [];
this.structParentIds.put(pageRef, ids);
}
ids.push([id, type]);
this.structParentIds.getOrPutComputed(pageRef, makeArr).push([id, type]);
}
addAnnotationIdToPage(pageRef, id) {
@ -537,11 +532,9 @@ class StructTreeRoot {
return;
}
let cachedParentDict = cache.get(parentRef);
if (!cachedParentDict) {
cachedParentDict = parentDict.clone();
cache.put(parentRef, cachedParentDict);
}
const cachedParentDict = cache.getOrPutComputed(parentRef, () =>
parentDict.clone()
);
const parentKidsRaw = cachedParentDict.getRaw("K");
let cachedParentKids =
parentKidsRaw instanceof Ref ? cache.get(parentKidsRaw) : null;

View File

@ -568,6 +568,12 @@ describe("primitives", function () {
cache.put(ref2, obj2);
expect([...cache.keys()]).toEqual([ref1, ref2]);
});
it("should handle getOrPutComputed correctly", function () {
expect(cache.getOrPutComputed(ref1, () => obj1)).toEqual(obj1);
// Trying to set it again should be ignored.
expect(cache.getOrPutComputed(ref1, () => obj2)).toEqual(obj1);
});
});
describe("isName", function () {