0.0.22 • Published 1 year ago

obj-cached v0.0.22

Weekly downloads
-
License
-
Repository
-
Last release
1 year ago

Object Cached Function

Cache function results in globalThis, useful when playing with bun --hot

Example Usage

Sync

import {objCached} from 'obj-cached'

// sync
const fn = objCached(() => {
    // do something heavy in sync
    // cached with global object
    return ...
}) // cached with globalThis by default, (global['prefix-hashedKeyXXXX'] in node or window['prefix-hashedKeyXXXX'] in browser)

const result = fn()

Async

// async
import {objCachedAsync} from 'obj-cached'
const cacheObj = {} // custom cacheObj
const fna =  objCachedAsync(async ()=> {
    // do something heavy
    // and cached with global object
    return ...
}, cacheObj) // cached with global this

const result = await fn()

Store your Cached Object into File (must by async)

import { FileCacheObj } from "file-cached";
import { objCachedAsync } from "obj-cached";

const cacheObj = FileCacheObj(import.meta.dir + "/cache.json");

const result = await objCachedAsync(async () => {
  // do sth heavy
}, cacheObj)();

Limitations

  1. You can only cache plain JSON object
  2. Use async version when used with FileCacheObj.
  3. objCachedAsync is NOT waitting for cache written
  • so cache data MAY LOST if you terminate process before it's done.
  • and there are maybe conflict cache written

Implementation

export function objCached<Args extends unknown[], Result>(
  fn: (...args: Args) => Result,
  obj: Record<string, unknown> = globalThis,
  prefix = "obj-cached-"
) {
  const key = `${prefix}${fn.toString()}@${JSON.stringify(args)}`;
  return (...args: Args) => (obj[key] ??= fn(...args)) as Result;
}
export function objCachedAsync<Args extends unknown[], Result>(
  fn: (...args: Args) => Promise<Result> | Result,
  obj: Record<string, unknown> = globalThis,
  prefix = "obj-cached-"
) {
  const key = `${prefix}${fn.toString()}@${JSON.stringify(args)}`;
  return async (...args: Args) => (obj[key] ??= await fn(...args)) as Result;
}

License

MIT License

0.0.20

1 year ago

0.0.21

1 year ago

0.0.22

1 year ago

0.0.18

1 year ago

0.0.19

1 year ago

0.0.17

1 year ago

0.0.16

1 year ago

0.0.10

1 year ago

0.0.11

1 year ago

0.0.12

1 year ago

0.0.13

1 year ago

0.0.14

1 year ago

0.0.15

1 year ago

0.0.9

1 year ago

0.0.8

1 year ago

0.0.7

1 year ago

0.0.6

1 year ago

0.0.5

1 year ago

0.0.4

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago