Skip to content

Instantly share code, notes, and snippets.

@cpojer
Last active May 16, 2021 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cpojer/56ab736128a1af55b8075e98164926d8 to your computer and use it in GitHub Desktop.
Save cpojer/56ab736128a1af55b8075e98164926d8 to your computer and use it in GitHub Desktop.
// Add memoization to two string helpers in jsdom that are called
// tens of thousands of times on the same strings and slow tests
// down by up to 3x.
//
// See https://github.com/jsdom/jsdom/commit/63d24a06d04a60279599782dc97899cde59d901d#diff-a29b6d0a417180220d299dde53ac3e1f820c3ade3daec396118f27c4270e1457R137
const {createRequire} = require('module');
const envRequire = createRequire(require.resolve('jest-environment-jsdom'));
const stringHelpers = envRequire('jsdom/lib/jsdom/living/helpers/strings.js');
const memoize = (fn) => {
const map = new Map();
return (string) => {
if (map.has(string)) {
return map.get(string);
}
const value = fn(string);
map.set(string, value);
return value;
};
};
stringHelpers.asciiUppercase = memoize(stringHelpers.asciiUppercase);
stringHelpers.asciiLowercase = memoize(stringHelpers.asciiLowercase);
module.exports = require('jest-environment-jsdom');
@cpojer
Copy link
Author

cpojer commented May 15, 2021

@SimenB
Copy link

SimenB commented May 15, 2021

const {createRequire} = require('module');

const envRequire = createRequire(require.resolve('jest-environment-jsdom'));

const stringHelpers = envRequire('jsdom/lib/jsdom/living/helpers/strings.js')`;

is probably safer so you won't have to rely on on FS layout of node_modules

https://nodejs.org/api/module.html#module_module_createrequire_filename

@cpojer
Copy link
Author

cpojer commented May 15, 2021

Ah, good point – I'm operating in a place where there are multiple jsdoms.

@Kjir
Copy link

Kjir commented May 16, 2021

There's an extra backtick on line 10

@cpojer
Copy link
Author

cpojer commented May 16, 2021

Thanks, copy paste mistake, fixed!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment