socket-function 0.8.7 → 0.8.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
@@ -1,4 +1,5 @@
1
1
  import { observable, Reaction, IObservable } from "mobx";
2
+ import { cacheLimited } from "../src/caching";
2
3
 
3
4
  export function promiseToObservable<T>(promise: Promise<T>): { value: T | undefined } {
4
5
  let isDone = false;
@@ -29,4 +30,23 @@ export function promiseToObservable<T>(promise: Promise<T>): { value: T | undefi
29
30
  return undefined;
30
31
  }
31
32
  };
33
+ }
34
+
35
+ export function asyncObservable<Output, Key>(maxCount: number, getValue: (key: Key) => Promise<Output>): {
36
+ (key: Key): Output | undefined;
37
+ invalidate(key: Key): void;
38
+ } {
39
+ let cache = cacheLimited(maxCount, (keyJSON: string) => {
40
+ let key = keyJSON ? JSON.parse(keyJSON) : keyJSON;
41
+ // We call inside another function so that synchronous errors still get wrapped in the observable
42
+ let value = (async () => getValue(key))();
43
+ return promiseToObservable(value);
44
+ });
45
+ get["invalidate"] = (key: Key) => {
46
+ cache.invalidate(JSON.stringify(key));
47
+ };
48
+ function get(key: Key) {
49
+ return cache(JSON.stringify(key)).value;
50
+ }
51
+ return get;
32
52
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "socket-function",
3
- "version": "0.8.7",
3
+ "version": "0.8.10",
4
4
  "main": "index.js",
5
5
  "license": "MIT",
6
6
  "dependencies": {
package/src/caching.ts CHANGED
@@ -64,10 +64,17 @@ export function cacheLimited<Output, Key>(
64
64
  // calculating, keeping a consistent output can save (a considerable amount of) time in downstream caches.
65
65
  maxCount: number,
66
66
  getValue: (key: Key) => Output
67
- ): (key: Key) => Output {
67
+ ): {
68
+ (key: Key): Output;
69
+ invalidate(key: Key): void;
70
+ } {
68
71
  let startingCalculating = new Set<Key>();
69
72
  let values = new Map<Key, Output>();
70
- return (input) => {
73
+ get["invalidate"] = (key: Key) => {
74
+ values.delete(key);
75
+ startingCalculating.delete(key);
76
+ };
77
+ function get(input: Key) {
71
78
  let key = input;
72
79
  if (values.has(key)) {
73
80
  return values.get(key) as any;
@@ -91,7 +98,8 @@ export function cacheLimited<Output, Key>(
91
98
  let value = getValue(input);
92
99
  values.set(key, value);
93
100
  return value;
94
- };
101
+ }
102
+ return get;
95
103
  }
96
104
 
97
105
  export function cacheWeak<Output, Key extends object>(getValue: (key: Key) => Output): (key: Key) => Output {