Skip to content

Commit 301ee68

Browse files
committed
chore: Refactor cachedFunction to use selectorToCacheKey
1 parent f4b7c05 commit 301ee68

File tree

2 files changed

+14
-37
lines changed

2 files changed

+14
-37
lines changed

src/index.ts

Lines changed: 13 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,19 @@
11

2+
import _ from 'lodash';
23
import type {CachedFunctionOptions} from './index.d';
3-
import type {AnyFunction} from './paths.d';
4+
import type {AnyFunction, ArgumentPaths} from './paths.d';
45

5-
export function cachedFunction<F extends AnyFunction>(function_: F, options: CachedFunctionOptions<F>) {
6-
console.log(options);
7-
return function_;
6+
export function selectorToCacheKey<F extends AnyFunction>(arguments_: Parameters<F>, selector: ArgumentPaths<F>) {
7+
const selectors = _.castArray(selector);
8+
const values = _.at(arguments_, selectors);
9+
const result = _.zipObject(selectors, values);
10+
return JSON.stringify(result);
811
}
912

10-
/** TEST */
11-
type Person = {
12-
name: string;
13-
age: number;
14-
address: {
15-
city: string;
16-
zip: number;
13+
export function cachedFunction<F extends AnyFunction>(function_: F, options: CachedFunctionOptions<F>) {
14+
return (...arguments_: Parameters<F>): ReturnType<F> => {
15+
const cacheKey = selectorToCacheKey(arguments_, options.selector);
16+
console.log({cacheKey});
17+
return function_(...arguments_);
1718
};
18-
};
19-
20-
const person: Person = {
21-
name: 'John Doe',
22-
age: 30,
23-
address: {
24-
city: 'New York',
25-
zip: 10_001,
26-
},
27-
};
28-
29-
cachedFunction((person: Person) => person.name, {
30-
selector: person => person.name,
31-
});
19+
}

src/paths.d.ts

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -34,15 +34,4 @@ export type Paths<T> = T extends Record<string, unknown>
3434
* @typeparam F - The function type.
3535
* @typeparam Paths - The paths of the arguments of the function type.
3636
*/
37-
export type ArgumentPaths1<F extends AnyFunction> = SingleOrArray<Paths<Parameters<F>>>;
38-
39-
/**
40-
* Represents a function that takes arguments of type `Parameters<F>` and returns `ArgumentPaths1<F>`.
41-
*/
42-
export type ArgumentPaths2<F extends AnyFunction> = (...arguments_: Parameters<F>) => ArgumentPaths1<F>;
43-
44-
/**
45-
* Represents the argument paths for a given function type.
46-
* @template F - The function type.
47-
*/
48-
export type ArgumentPaths<F extends AnyFunction> = ArgumentPaths1<F> | ArgumentPaths2<F>;
37+
export type ArgumentPaths<F extends AnyFunction> = SingleOrArray<Paths<Parameters<F>>>;

0 commit comments

Comments
 (0)