Skip to content

Commit

Permalink
Cache with lru-cache.
Browse files Browse the repository at this point in the history
  • Loading branch information
sandinmyjoints committed Jan 22, 2024
1 parent 93c1fac commit 096329d
Showing 1 changed file with 11 additions and 9 deletions.
20 changes: 11 additions & 9 deletions lib/parsers/string.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
'use strict';

const Iconv = require('iconv-lite');
const decoderCache = new Map();
const LRU = require('lru-cache');

const decoderCache = new LRU({
max: 500,
});

exports.decode = function (buffer, encoding, start, end, options) {
if (Buffer.isEncoding(encoding)) {
return buffer.toString(encoding, start, end);
}

const decoderArgs = { encoding, options: options || {} };
const decoder =
decoderCache.get(decoderArgs) ||
decoderCache
.set(
decoderArgs,
Iconv.getDecoder(decoderArgs.encoding, decoderArgs.options),
)
.get(decoderArgs);
const decoderKey = JSON.stringify(decoderArgs);
let decoder = decoderCache.get(decoderKey);
if (!decoder) {
decoder = Iconv.getDecoder(decoderArgs.encoding, decoderArgs.options);
decoderCache.set(decoderKey, decoder);
}

const res = decoder.write(buffer.slice(start, end));
const trail = decoder.end();
Expand Down

0 comments on commit 096329d

Please sign in to comment.