Skip to content

Commit

Permalink
[WOM-5333] Wrap BpkCalendar format date methods with memoize (#3689)
Browse files Browse the repository at this point in the history
* Wrap BpkCalendar format date methods with memoize

* Improvements

* Improvement

* Add memoize for formatMonth only to avoid double calls

* Add TS doc

* Add licence header to test file
  • Loading branch information
sarak-works authored Dec 5, 2024
1 parent 0a59555 commit a3d4e5d
Show file tree
Hide file tree
Showing 4 changed files with 125 additions and 3 deletions.
3 changes: 2 additions & 1 deletion packages/bpk-component-calendar/src/BpkCalendarGrid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
getCalendarMonthWeeks,
isSameMonth,
} from './date-utils';
import { memoize } from './utils';

import type { DateModifiers, SelectionConfiguration } from './custom-proptypes';

Expand Down Expand Up @@ -170,7 +171,7 @@ class BpkCalendarGrid extends Component<Props, State> {
dates={dates}
onDateClick={onDateClick}
onDateKeyDown={onDateKeyDown}
formatDateFull={formatDateFull}
formatDateFull={memoize(formatDateFull)}
DateComponent={DateComponent}
dateModifiers={dateModifiers!}
preventKeyboardFocus={preventKeyboardFocus}
Expand Down
5 changes: 3 additions & 2 deletions packages/bpk-component-calendar/src/composeCalendar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import type { ComponentType } from 'react';
import { cssModules } from '../../bpk-react-utils';

import { CALENDAR_SELECTION_TYPE } from './custom-proptypes';
import { memoize } from './utils';

import type {
DaysOfWeek,
Expand Down Expand Up @@ -184,7 +185,7 @@ const composeCalendar = (
{Nav && (
<Nav
changeMonthLabel={changeMonthLabel}
formatMonth={formatMonth}
formatMonth={memoize(formatMonth)}
id={`${id}__bpk_calendar_nav`}
maxDate={maxDate}
minDate={minDate}
Expand All @@ -211,7 +212,7 @@ const composeCalendar = (
dateModifiers={dateModifiers}
daysOfWeek={daysOfWeek}
formatDateFull={formatDateFull}
formatMonth={formatMonth}
formatMonth={memoize(formatMonth)}
month={month}
onDateClick={onDateClick}
onDateKeyDown={onDateKeyDown}
Expand Down
70 changes: 70 additions & 0 deletions packages/bpk-component-calendar/src/utils-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Backpack - Skyscanner's Design System
*
* Copyright 2016 Skyscanner Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { describe, it, expect, jest } from '@jest/globals';

import { memoize } from './utils';

describe('memoize', () => {
it('should call the original function for new arguments', () => {
const mockFn = jest.fn((x: number) => x * 2);
const memoizedFn = memoize(mockFn);

expect(memoizedFn(2)).toBe(4);
expect(mockFn).toHaveBeenCalledTimes(1);

expect(memoizedFn(3)).toBe(6);
expect(mockFn).toHaveBeenCalledTimes(2);
});

it('should return cached results for repeated arguments', () => {
const mockFn = jest.fn((x: number) => x * 2);
const memoizedFn = memoize(mockFn);

memoizedFn(2); // Original function called
memoizedFn(2); // Result from cache
memoizedFn(2); // Result from cache

expect(mockFn).toHaveBeenCalledTimes(1); // Function called only once
});

it('should handle functions with multiple arguments', () => {
const mockFn = jest.fn((x: number, y: number) => x + y);
const memoizedFn = memoize(mockFn);

expect(memoizedFn(2, 3)).toBe(5); // Original function called
expect(mockFn).toHaveBeenCalledTimes(1);

expect(memoizedFn(2, 3)).toBe(5); // Result from cache
expect(mockFn).toHaveBeenCalledTimes(1); // No additional calls

expect(memoizedFn(3, 2)).toBe(5); // New arguments, original function called
expect(mockFn).toHaveBeenCalledTimes(2);
});

it('should handle functions with no arguments', () => {
const mockFn = jest.fn(() => 42);
const memoizedFn = memoize(mockFn);

expect(memoizedFn()).toBe(42); // Original function called
expect(mockFn).toHaveBeenCalledTimes(1);

expect(memoizedFn()).toBe(42); // Result from cache
expect(mockFn).toHaveBeenCalledTimes(1); // No additional calls
});
});
50 changes: 50 additions & 0 deletions packages/bpk-component-calendar/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,53 @@ export const getTransformStyles = (transformValue: string) => {

export const isTransitionEndSupported = () =>
!!(typeof window !== 'undefined' && 'TransitionEvent' in window);

/**
* Memoizes a given function to optimize performance by caching its results based on input arguments.
*
* @template T - The type of the function to be memoized. Must be a function.
* @param {T} fn - The function to be memoized.
* @returns {T} - The memoized version of the input function. Subsequent calls with the same arguments
* will return the cached result, avoiding redundant computations.
*
* @example
* // Simple usage:
* const add = (a: number, b: number) => a + b;
* const memoizedAdd = memoize(add);
*
* console.log(memoizedAdd(1, 2)); // Computes and caches result: 3
* console.log(memoizedAdd(1, 2)); // Fetches from cache: 3
*
* @example
* // With a more complex function:
* const slowFunction = (num: number) => {
* console.log('Computing...');
* return num * 2;
* };
* const memoizedSlowFunction = memoize(slowFunction);
*
* console.log(memoizedSlowFunction(5)); // Logs "Computing...", returns 10
* console.log(memoizedSlowFunction(5)); // Fetches from cache: 10
*
* @remarks
* - This implementation uses a `Map` object and `JSON.stringify` to create cache keys.
* - Functions with non-primitive or cyclic arguments may not work as expected due to
* `JSON.stringify` limitations.
* - The cache is stored in memory and will grow indefinitely unless manually managed or
* the function goes out of scope.
*/
export function memoize<T extends (...args: any[]) => any>(fn: T): T {
const cache = new Map<string, ReturnType<T>>();

function memoizedFunction(...args: Parameters<T>): ReturnType<T> {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key) as ReturnType<T>;
}
const result = fn(...args);
cache.set(key, result);
return result;
}

return memoizedFunction as T;
}

0 comments on commit a3d4e5d

Please sign in to comment.