Skip to content

Commit

Permalink
feat(memoize): add doOnce(), update readme
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Aug 20, 2020
1 parent 66dd3b1 commit 889e00d
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 3 deletions.
2 changes: 1 addition & 1 deletion packages/memoize/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ yarn add @thi.ng/memoize
<script src="https://unpkg.com/@thi.ng/memoize/lib/index.umd.js" crossorigin></script>
```

Package sizes (gzipped, pre-treeshake): ESM: 254 bytes / CJS: 305 bytes / UMD: 389 bytes
Package sizes (gzipped, pre-treeshake): ESM: 282 bytes / CJS: 336 bytes / UMD: 417 bytes

## Dependencies

Expand Down
19 changes: 19 additions & 0 deletions packages/memoize/src/do-once.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { Fn } from "@thi.ng/api";
import { MapLike } from "./api";

/**
* Similar to {@link memoize1}, however optimized for side effects only, i.e.
* functions which DO NOT return any result.
*
* @param fn
* @param cache
*/
export const doOnce = <T>(fn: Fn<T, void>, cache?: MapLike<T, boolean>) => {
!cache && (cache = new Map());
return (x: T) => {
if (!cache!.has(x)) {
cache!.set(x, true);
fn(x);
}
};
};
1 change: 1 addition & 0 deletions packages/memoize/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from "./api";
export * from "./defonce";
export * from "./do-once";
export * from "./memoize";
export * from "./memoize1";
export * from "./memoizej";
4 changes: 2 additions & 2 deletions packages/memoize/src/memoize1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ import type { MapLike } from "./api";
* @param fn -
* @param cache -
*/
export function memoize1<A, B>(fn: Fn<A, B>, cache?: MapLike<A, B>) {
export const memoize1 = <A, B>(fn: Fn<A, B>, cache?: MapLike<A, B>) => {
!cache && (cache = new Map());
return (x: A): B => {
let res;
return cache!.has(x)
? cache!.get(x)!
: (cache!.set(x, (res = fn(x))), res);
};
}
};

0 comments on commit 889e00d

Please sign in to comment.