Skip to content

Commit

Permalink
[add] Function Cache utility method
Browse files Browse the repository at this point in the history
[add] VS Code debug configuration
[optimize] add Yarn lock for CI cache
[optimize] update Upstream packages
  • Loading branch information
TechQuery committed Jan 24, 2022
1 parent ab712ae commit 47f14d5
Show file tree
Hide file tree
Showing 12 changed files with 6,336 additions and 52 deletions.
22 changes: 13 additions & 9 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
name: CI & CD
on:
push:
branches:
- master
tags:
- v*
jobs:
Build-and-Deploy:
Build-and-Publish:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Use Node.js
uses: actions/setup-node@v2
with:
node-version: '14'
- name: Install & build
run: |
npm install
npm run build
- name: Deploy
node-version: 14
registry-url: https://registry.npmjs.org
cache: yarn
- name: Install packages
run: yarn
- name: Build & Publish
run: yarn publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Update document
uses: peaceiris/actions-gh-pages@v3
with:
publish_dir: ./docs
Expand Down
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ node_modules/
docs/
dist/
.parcel-cache/
.vscode/
.vscode/settings.json
18 changes: 18 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Jest",
"type": "node",
"request": "launch",
"port": 9229,
"runtimeArgs": [
"--inspect-brk",
"${workspaceRoot}/node_modules/jest/bin/jest.js",
"--runInBand"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
]
}
33 changes: 28 additions & 5 deletions ReadMe.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@

## Installation

```Shell
```shell
npm install web-utility
```

`index.html`

```HTML
```html
<head>
<script src="https://polyfill.app/api/polyfill?features=regenerator-runtime,url,scroll-behavior,intersection-observer"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/text.min.js"></script>
Expand All @@ -26,7 +26,7 @@ npm install web-utility

`tsconfig.json`

```JSON
```json
{
"compilerOptions": {
"module": "ES2021",
Expand All @@ -53,15 +53,38 @@ npm install web-utility

5. [Work with Existed Classes](https://github.com/EasyWebApp/BootCell/blob/a41bbc1/source/Content/Carousel.tsx#L82-L99)

### Function Cache

```typescript
import { cache } from 'web-utility';

const getToken = cache(async (cleaner, code) => {
const { access_token, expires_in } = await (
await fetch(`https://example.com/access_token?code=${code}`)
).json();

setTimeout(cleaner, expires_in * 1000);

return access_token;
}, 'Get Token');

Promise.all([getToken('xxx'), getToken('yyy')]).then(([first, second]) =>
console.assert(
first === second,
'Getting token for many times should return the same before deadline'
)
);
```

### Message Channel

`index.ts`

```TypeScript
```typescript
import { createMessageServer } from 'web-utility';

createMessageServer({
preset: () => ({test: 1})
preset: () => ({ test: 1 })
});
```

Expand Down
26 changes: 13 additions & 13 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "web-utility",
"version": "2.9.5",
"version": "3.0.0",
"license": "LGPL-3.0",
"author": "[email protected]",
"description": "Web front-end toolkit based on TypeScript",
Expand All @@ -24,24 +24,24 @@
"main": "dist/index.js",
"module": "dist/index.esm.js",
"dependencies": {
"@swc/helpers": "^0.2.13",
"@swc/helpers": "^0.3.2",
"regenerator-runtime": "^0.13.9"
},
"devDependencies": {
"@parcel/packager-ts": "^2.0.1",
"@parcel/transformer-typescript-types": "^2.0.1",
"@peculiar/webcrypto": "^1.2.2",
"@types/jest": "^27.0.2",
"@types/node": "^14.17.33",
"@parcel/packager-ts": "^2.2.1",
"@parcel/transformer-typescript-types": "^2.2.1",
"@peculiar/webcrypto": "^1.2.3",
"@types/jest": "^27.4.0",
"@types/node": "^14.18.9",
"husky": "^7.0.4",
"intersection-observer": "^0.12.0",
"jest": "^27.3.1",
"lint-staged": "^11.2.6",
"jest": "^27.4.7",
"lint-staged": "^12.3.1",
"open-cli": "^7.0.1",
"parcel": "^2.0.1",
"prettier": "^2.4.1",
"ts-jest": "^27.0.7",
"typedoc": "^0.22.8",
"parcel": "^2.2.1",
"prettier": "^2.5.1",
"ts-jest": "^27.1.3",
"typedoc": "^0.22.11",
"typedoc-plugin-mdn-links": "^1.0.4",
"typescript": "~4.3.5"
},
Expand Down
23 changes: 23 additions & 0 deletions source/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,29 @@ export function groupBy<T extends Record<IndexKey, any>>(
return data;
}

export function cache<I, O>(
executor: (cleaner: () => void, ...data: I[]) => O,
title: string
) {
var cacheData: O;

return function (...data: I[]) {
if (cacheData != null) return cacheData;

console.trace(`[Cache] execute: ${title}`);

cacheData = executor.call(
this,
(): void => (cacheData = undefined),
...data
);
Promise.resolve(cacheData).then(data =>
console.log(`[Cache] refreshed: ${title} => ${data}`)
);
return cacheData;
};
}

export function parseJSON(raw: string) {
try {
return JSON.parse(raw, (key, value) =>
Expand Down
2 changes: 1 addition & 1 deletion source/math.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export function carryFloat(raw: number, length: number) {

const cut = (text: string) => text.slice(0, offset - (length ? 0 : 1));

if (!+text[offset]) return cut(text);
if (!+text.slice(offset)) return cut(text);

const result = cut((+cut(text) + 10 ** -length).toFixed(length));

Expand Down
2 changes: 1 addition & 1 deletion source/timer.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export function sleep(seconds = 1) {
return new Promise(resolve => setTimeout(resolve, seconds * 1000));
return new Promise<void>(resolve => setTimeout(resolve, seconds * 1000));
}

export function asyncLoop(executor: (...data: any[]) => any, seconds = 1) {
Expand Down
35 changes: 35 additions & 0 deletions test/data.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ import {
likeArray,
makeArray,
groupBy,
cache,
parseJSON,
parseTextTable,
makeCRC32,
makeSHA
} from '../source/data';
import { sleep } from '../source/timer';

describe('Data', () => {
it('should detect Meaningless Null Values', () => {
Expand Down Expand Up @@ -80,6 +82,39 @@ describe('Data', () => {
});
});

describe('Function Cache', () => {
it('should cache result of a Sync Function', () => {
const add = cache((_, x: number, y: number) => x + y, 'add');

expect(add(1, 1)).toBe(2);
expect(add(1, 2)).toBe(2);
});

it('should cache result of an Async Function', async () => {
const origin = jest.fn(() => Promise.resolve(1));
const asyncFunc = cache(origin, 'async');

expect(asyncFunc()).toBeInstanceOf(Promise);
expect(asyncFunc()).toBe(asyncFunc());
expect(await asyncFunc()).toBe(1);
expect(origin).toBeCalledTimes(1);
});

it('should renew Cache data manually', async () => {
const asyncFunc = cache(async (clean, data: any) => {
setTimeout(clean, 1000);

return data;
}, 'cleanable');

expect(await asyncFunc(1)).toBe(1);
expect(await asyncFunc(2)).toBe(1);

await sleep();
expect(await asyncFunc(3)).toBe(3);
});
});

describe('JSON Parser', () => {
it('should parse JSON strings within Primitive values', () => {
expect(parseJSON('1')).toBe(1);
Expand Down
4 changes: 2 additions & 2 deletions test/math.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ describe('Math functions', () => {
it('should carry rest bits of a Float Number based on length', () => {
expect(carryFloat(0.01, 1)).toBe('0.1');
expect(carryFloat(0.01, 2)).toBe('0.01');
expect(carryFloat(1.01, 0)).toBe('1');
expect(carryFloat(0.03001, 3)).toBe('0.030');
expect(carryFloat(1.01, 0)).toBe('2');
expect(carryFloat(0.03001, 3)).toBe('0.031');
expect(carryFloat(0.049999999999999996, 3)).toBe('0.050');
expect(carryFloat(1573.1666666666667, 1)).toBe('1573.2');
expect(carryFloat(7.527726527090811e-7, 7)).toBe('0.0000008');
Expand Down
41 changes: 21 additions & 20 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
{
"compilerOptions": {
"target": "ES5",
"module": "ES6",
"moduleResolution": "Node",
"esModuleInterop": true,
"downlevelIteration": true,
"declaration": true,
"lib": ["ES2019", "DOM", "DOM.Iterable"],
"outDir": "dist/"
},
"include": ["source/*.ts"],
"typedocOptions": {
"name": "Web utility",
"excludeExternals": true,
"excludePrivate": true,
"readme": "./ReadMe.md",
"out": "docs/"
}
}
{
"compilerOptions": {
"target": "ES5",
"module": "ES6",
"moduleResolution": "Node",
"esModuleInterop": true,
"downlevelIteration": true,
"declaration": true,
"lib": ["ES2019", "DOM", "DOM.Iterable"],
"types": ["node", "jest"],
"outDir": "dist/"
},
"include": ["source/*.ts"],
"typedocOptions": {
"name": "Web utility",
"excludeExternals": true,
"excludePrivate": true,
"readme": "./ReadMe.md",
"out": "docs/"
}
}
Loading

0 comments on commit 47f14d5

Please sign in to comment.