Skip to content

Commit

Permalink
fix(memoize): add jest
Browse files Browse the repository at this point in the history
  • Loading branch information
fupengl committed Mar 19, 2022
1 parent ce7212a commit 30a4810
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 5 deletions.
31 changes: 31 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
# For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages

name: test

on: [push]

jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node: ['12', '14', '16']
name: ${{ matrix.os }} Use Node.js ${{ matrix.node }}
steps:
- name: Check out Git repository
uses: actions/checkout@v2
- name: Setup node
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node }}
- name: Setup yarn cache
uses: actions/cache@v2
with:
path: '**/node_modules'
key: ${{ matrix.os }}-${{ matrix.node }}-modules-${{ hashFiles('**/yarn.lock') }}
- name: Install dependencies
run: yarn
- name: Jest
run: yarn test
18 changes: 18 additions & 0 deletions __tests__/promise.memoize.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { memoize, delay } from '../src/promise';

describe('promise/memoize', () => {
test('cache 1000ms', async () => {
let i = 1;
const fn = memoize(
() => Promise.resolve(++i),
() => 1,
1000,
);
for (let i = 0; i < 100; i++) {
expect(await fn()).toBe(2);
}

await delay(1000);
expect(await fn()).toBe(3);
});
});
6 changes: 1 addition & 5 deletions src/promise/memoize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ function memoize<FnType extends AnyPromiseFN>(

if (timeoutMs) {
memos.forEach((item, k) => {
if (item.expiration > Date.now()) {
if (item.expiration < Date.now()) {
memos.delete(k);
}
});
Expand All @@ -37,10 +37,6 @@ function memoize<FnType extends AnyPromiseFN>(
return memos.get(key)!.value;
}

if (queues.has(key)) {
return await queues.get(key)!;
}

const promise = fn(...args);
queues.set(key, promise);

Expand Down

0 comments on commit 30a4810

Please sign in to comment.