Skip to content

Instantly share code, notes, and snippets.

@TerribleDev
Last active July 16, 2021 14:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TerribleDev/db48b2c8e143f9364292161346877f93 to your computer and use it in GitHub Desktop.
Save TerribleDev/db48b2c8e143f9364292161346877f93 to your computer and use it in GitHub Desktop.
Wrap reselect's createSelector with a function that measures how long selectors take to run
import {createSelector} from 'reselect';
const hasPerformanceApi =
window &&
window.performance &&
window.performance.measure &&
window.performance.mark;
const createFuncWithMark = (name, callback) => (...args) => {
const startMark = `${name}-Startmark`;
const endMark = `${name}-EndMark`;
window.performance.mark(startMark);
const result = callback(...args);
window.performance.mark(endMark);
window.performance.measure('♻️ ' + `${name}-Selector`, startMark, endMark);
window.performance.clearMarks(startMark);
window.performance.clearMarks(endMark);
window.performance.clearMeasures(startMark);
window.performance.clearMeasures(endMark);
return result;
};
export const createMarkedSelector = (name, ...args) => {
if (!hasPerformanceApi) {
return createSelector(...args);
}
if (!name || typeof name !== 'string') {
throw new Error('marked selectors must have names');
}
const callback = args.pop();
const funcWithMark = createFuncWithMark(name, callback);
args.push(funcWithMark);
return createSelector(...args);
};
@TerribleDev
Copy link
Author

you can use this by instead of calling createSelector call createMarkedSelector('yourSelectorName', ...)

@TerribleDev
Copy link
Author

This is the regex I use in vscode to on mass replace createSelector with createMarkedSelector

https://gist.github.com/TerribleDev/da2fa46ce3194f69ef04239260cacb38

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