Skip to content

Commit

Permalink
fix: optimize 'only' method for O(1) performance (#1657)
Browse files Browse the repository at this point in the history
  • Loading branch information
mg901 authored Nov 8, 2023
1 parent 5fd6471 commit 3c8c92c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
8 changes: 4 additions & 4 deletions .size-limit.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,19 @@ module.exports = [
name: 'breakpoints',
path: './breakpoints/create-breakpoints-api.prod.js',
import: '{ createBreakpointsApi }',
limit: '254 B',
limit: '295 B',
},
{
name: 'breakpoints.dev',
path: './breakpoints/create-breakpoints-api.dev.js',
import: '{ createBreakpointsApi }',
limit: '804 B',
limit: '840 B',
},
{
name: 'styled-breakpoints',
path: './styled-breakpoints/create-styled-breakpoints-theme/index.js',
import: '{ createStyledBreakpointsTheme }',
limit: '725 B',
limit: '770 B',
},
{
name: 'styled-breakpoints + useMediaQuery',
Expand All @@ -29,6 +29,6 @@ module.exports = [
'./styled-breakpoints/index.js': '{ createStyledBreakpointsTheme }',
'./use-media-query/index.js': '{ useMediaQuery }',
},
limit: '985 B',
limit: '1.1 kB',
},
];
19 changes: 15 additions & 4 deletions breakpoints/create-breakpoints-api.prod.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,31 @@
const { calcMaxWidth } = require('./calc-max-width');

exports.createBreakpointsApi = ({ breakpoints }) => {
const keys = Object.keys(Object(breakpoints));
exports.createBreakpointsApi = ({ breakpoints = {} }) => {
const indexMap = {};
const keys = Object.keys(breakpoints);

const getNextKey = (key) => keys[keys.indexOf(key) + 1];
keys.forEach((key, index) => {
indexMap[key] = index;
});

const up = (min) => breakpoints[min];
const down = (max) => calcMaxWidth(breakpoints[max]);

const getNextKey = (key) => {
const currentIndex = indexMap[key];
const nextIndex = currentIndex + 1;
const isNotLastIndex = currentIndex < keys.length - 1;

return isNotLastIndex ? keys[nextIndex] : undefined;
};

const between = (min, max) => ({
min: up(min),
max: down(max),
});

const only = (key) =>
key === keys.at(-1) ? up(key) : between(key, getNextKey(key));
key !== keys.at(-1) ? between(key, getNextKey(key)) : up(key);

return {
keys,
Expand Down

0 comments on commit 3c8c92c

Please sign in to comment.