Skip to content

Commit

Permalink
Cache with Map.
Browse files Browse the repository at this point in the history
  • Loading branch information
sandinmyjoints committed Jan 22, 2024
1 parent e6a9306 commit 93c1fac
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions lib/parsers/string.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,30 @@
'use strict';

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

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

const decoder = Iconv.getDecoder(encoding, options || {});
const decoderArgs = { encoding, options: options || {} };
const decoder =
decoderCache.get(decoderArgs) ||
decoderCache
.set(
decoderArgs,
Iconv.getDecoder(decoderArgs.encoding, decoderArgs.options),
)
.get(decoderArgs);

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

return trail ? res + trail : res;
};

exports.encode = function(string, encoding, options) {
exports.encode = function (string, encoding, options) {
if (Buffer.isEncoding(encoding)) {
return Buffer.from(string, encoding);
}
Expand Down

0 comments on commit 93c1fac

Please sign in to comment.