{"name":"@protoplasm/recall","version":"0.2.3","description":"lightweight memoization","main":"dist/index.js","types":"dist/index.d.ts","repository":{"type":"git","url":"git+https://github.com/queerviolet/recall.git"},"scripts":{"build":"tsc -p .","watch":"tsc -p . -w","test":"jest","watch:test":"jest --watch","prepare":"npm run build"},"keywords":["memoization"],"author":{"name":"ash","email":"i@ashi.io"},"license":"MIT","engines":{"node":">=12.13.0"},"publishConfig":{"access":"public"},"devDependencies":{"@types/jest":"^27","jest":"^27","prettier":"^2.2.1","ts-jest":"^27","typescript":"^4.1.3"},"gitHead":"702b2e23b0e4632c37c9f4ec96411517890bf3a2","bugs":{"url":"https://github.com/queerviolet/recall/issues"},"homepage":"https://github.com/queerviolet/recall#readme","_id":"@protoplasm/recall@0.2.3","_nodeVersion":"16.5.0","_npmVersion":"7.19.1","dist":{"integrity":"sha512-z3sFVCMK65MZyrSZH/mLhxlO9CxyR7NUUnktU/mkBvVoPi+nPXRgXGEVfSyV9U+C8ZzJAs++pC0nNRv8e+YXTg==","shasum":"43d315b6dd88c6c012cdc5cb5b2c57e9e4d46cbc","tarball":"http://registry-npm.ywwl.com/@protoplasm/recall/download/@protoplasm/recall-0.2.3.tgz","fileCount":43,"unpackedSize":67474,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIFJpatBdW8AB/NbV+3otFiJugULKGl56O+S0rFa4sPkRAiBBKcni+5gLQHC7/I2Y0i9+waTxqf5mCi7medgGvLQ6vw=="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJiYdc9ACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmpeBA/+ILSnEhkPWJAIaJgYWyKpCrSVYvZnm7xc+O52TVNFaGf8/FKf\r\n+cEaHuHKuP2fEmWbJ/f6VCZJmy4vHAg8OAKa3vIkuzRrR6+9GAf/pg7G6fj1\r\nMy+p5QnUDaLPnqay9zBwKp+AWn4Bn12p/hJ0VU9eHpCvXjepUOT8Ojhs8OcV\r\n8Pp9J472fCPOBb3IXQZ6ZSESDD/37Kzur6yt0Gw/YTLWj9GwT8JZV1a8NS7U\r\n9o08ZOjNxjNnWGKyKZUn80+0D4DoPGwP64OC28qtDqNBZrfgjk2C4RL3y/hx\r\nKoVrKLBiOr0/FzBXZSg2EdPFe50WNTOYO5npR8EqI+/2RrtqEnC2I+grAMAm\r\nAb3mwEWTbczErP6RndLoHKPsQABH9WMraNvQvplqFs1M86HfGEu6A5CXBDbf\r\n/66PqpZ2CjMUlVBcomjMMXLlLZosfILIfTy76J1RZ/vBJNiDV82XPMM9iJmP\r\ngWE9wr36RorhaBEC5e6s7UfojuTt5bAs/IHiyRMQzGTSgxeOXZNUEjmTQb4i\r\nA+UiaUnLwxDM5Hhs2Stfb+t0ChWdkfn8p/R2qMan+YWNorbt+tR8gA4T9PFS\r\nP911M2FM3qvkNAztXBa13JF4lQlU9wTsaUHnJ/uR/y2KERVS15t9PLo2XpWu\r\n26nei7CVgL+A/JKZZUE7mS/h0gi4N3Qx7oU=\r\n=DZYz\r\n-----END PGP SIGNATURE-----\r\n","size":17179,"noattachment":false,"key":"/@protoplasm/recall/-/@protoplasm/recall-0.2.3.tgz"},"_npmUser":{"name":"protoplasm","email":"protoplasm@ashi.io"},"directories":{},"maintainers":[{"name":"protoplasm","email":"protoplasm@ashi.io"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/recall_0.2.3_1650579261515_0.713675531058257"},"_hasShrinkwrap":false,"readme":"# recall\n\n```\nnpm i @protoplasm/recall\n```\n\nthis package lets you memoize functions and generators.\n\nmain entry points:\n  - [`recall`](#recall-memoizes-functions) memoizes functions\n  - [`replay`](#replay-memoizes-generators) memoizes generators\n  - [`report`](#reporting-errors-and-other-things) reports non-fatal errors and messages which will also be memoized by `recall` and `replay`\n\n## `recall` memoizes functions\n\n`recall` takes a function and returns a memoized version:\n\n```typescript\nimport recall from '@protoplasm/recall'\n\nlet calls = 0;\nconst hi = recall((data?: any) => {\n  ++calls\n  return { hello: 'world', data }\n})\n\nexpect(hi()).toBe(hi())\nexpect(calls).toBe(1)\n\nexpect(hi(42)).toBe(hi(42))\nexpect(calls).toBe(2)\n```\n\n`recall`ed functions cache both normal and exceptional return paths. if the underlying function throws the first time it's called for a set of arguments, it will always throw the same error when invoked again.\n\narguments are shallowly compared by `===`. there is no way to change this.\n\n### *fn*.`getResult` returns the stored result\n\n`recall`ed functions also make `Result`s available via a `.getResult` method. `getResult` has the same signature as the underlying function, but returns `Result<T>` rather than `T`:\n\n```typescript\nconst evenSquare = recall((n: number) => {\n  if (n % 2 !== 0) throw new Error('odd numbers unsupported')\n  return n ** 2\n})\n\nevenSquare.getResult(2).isReturn() // -> true\nevenSquare.getResult(2).data       // -> 4\nevenSquare.getResult(2).unwrap()   // -> 4\n\nevenSquare.getResult(3).isReturn() // -> false\nevenSquare.getResult(3).isThrow()  // -> true\nevenSquare.getResult(3).error      // -> Error: odd numbers unsupported\nevenSquare.getResult(3).unwrap()   // !! throws Error: odd numbers unsupported\n```\n\n### *fn.*`getExisting` soft queries the cache\n\nthe `.getExisting` method works just like `.getResult`, only it will return `undefined` rather than calling the underlying if no entry for the arguments exists in the cache.\n\n\n## `replay` memoizes generators\n\nif you try to use `recall` on a generator, you're gonna have a bad time:\n\n```typescript\nconst gen = recall(function *() {\n  yield 1\n  yield 2\n  yield 3\n})\ngen() === gen() // -> true\n[...gen()]      // -> [1, 2, 3]\n[...gen()]      // -> []  (shit.)\n```\n\nthis happens because generators return iterators, which are consumed as you iterate over them.\n\n`replay` fixes this:\n\n```typescript\nconst gen = replay(function *() {\n  yield 1\n  yield 2\n  yield 3\n})\ngen() === gen() // -> true\n[...gen()]      // -> [1, 2, 3]\n[...gen()]      // -> [1, 2, 3]\n```\n\n`replay` wraps the generator in an `Iterable` which lazily stores each value the generator emits.\n\n## `report`ing errors\n\n`report` lets functions report messages independent of how they return. for example, you can `report` errors while still returning data:\n\n```typescript\nimport { report } from '@protoplasm/recall'\n\nfunction errorsAndData() {\n  report(new Error('something bad happened'))\n  report(new Error('something else bad happened'))\n  return \"but it's still ok\"\n}\n```\n\n`getResult` collects all messages `report`ed from a block. it returns these as part of a `Result`:\n\n```typescript\nimport { Result, getResult } from '@protoplasm/recall'\n\nconst result: Result<string> = getResult(() => errorsAndData())\nfor (const error of result.errors()) {\n  console.log(error) // -> 'something bad happened'\n                     // -> 'something else bad happened'\n}\nresult.unwrap()   // -> 'but it's still ok'\n```\n### `report`s bubble up\n\n`report` works no matter how deep you are in the call tree:\n\n```typescript\nfunction a() {\n  report(new Error(\"error from a\"))\n  b()\n}\n\nfunction b() {\n  report(new Error(\"error from b\"));\n  threeThingsFail();\n}\n\nfunction threeThingsFail() {\n  report(new Error(\"a\"));\n  report(new Error(\"b\"));\n  report(new Error(\"c\"));\n}\n\nconst result = getResult(() => {\n  a()\n  report(new Error('one last problem'))\n})\nresult.errors()\n  // -> error from a\n  // -> error from b\n  // -> a\n  // -> b\n  // -> c\n  // -> one last problem\n```\n\n## recipes\n\n### `recall` memoizes pure functions\n\nthe simplest case:\n\n```typescript\nconst sum = recall((ary: number[]) => ary.reduce((a, b) => a + b))\nconst a = [1, 2, 3, 4]\nsum(a)\nsum(a) // cache hit\n```\n\n### `recall` composite keys\n\nyou can use `recall` as a composite key map:\n\n```typescript\nconst song = recall((artist: string, title: string) => new Song(artist, title))\nconst coversOf = recall((song: Song) => [])\ncoversOf(song(\"Cher\", \"Believe\")).push(song(\"Okay Kaya\", \"Believe\"))\ncoversOf(song(\"Cher\", \"Believe\")).find(song(\"Okay Kaya\", \"Believe\"))\n```\n\n### `recall` a cache\n\nrecall can accept async functions. it simply caches the promise result:\n\n```typescript\nconst textOf = recall(async (url: string) => await (await fetch(url)).response.text)\nconst result = await textOf(\"https://...)\n```\n\n### `report` multiple errors while returning data\n\n```typescript\nconst doStuff = recall(things => {\n  let goodThings = []\n  for (const thing of things) {\n    if (isBad(thing)) {\n      report(new BadThingError(\"this thing is bad:\", thing))\n    } else {\n      goodThings.push(thing)   \n    }\n  }\n  if (!goodThings.length)\n    throw new Error(\"no good things\")\n  return processKnownGoodThings(goodThings)\n})\n\nconst output = doStuff\n  .getResult(someThings)\n  // prints non-fatal errors to console.log and unwraps:\n  .unwrap(console.log)\n```\n\n### `report` errors while yielding data\n\n```typescript\nconst processedThings = replay(function *(things) {\n  for (const thing of things) {\n    if (isBad(thing)) {\n      report(new BadThingError(\"this thing is bad:\", thing))\n    } else {\n      yield processGoodThing(thing)\n      goodThings.push(thing)   \n    }\n  }\n})\n\nconst output = getResult(() =>\n    // iterate over all processedThings to collect\n    // errors on all of them    \n    [...processedThings(someThings)]\n  ).unwrap(console.log)\n```\n\n\n### using `getResult` as a reporting boundary\n\n`getResult` and *fn.*`getResult` do not bubble `report`s up, so you can use them as error boundaries:\n\n```typescript\nfunction importantStuff() {\n  report(new Error('error in importantStuff'))\n}\n\nfunction optionalSetup() {\n  report(new Error('error in optionalStuff'))\n}\n\ngetResult(() => {\n  importantStuff()\n  optionalStuff()\n}).errors()\n  // -> [Error: error in importantStuff]\n  // -> [Error: error in optionalStuff]\n\ngetResult(() => {\n  importantStuff()\n  getResult(() => optionalStuff())\n    // swallowing the result swallows the error\n}).errors()\n  // -> [Error: error in importantStuff]\n```\n#### manually bubbling\n\nyou can `report(someResult.log)` to explicitly bubble up messages from `someResult`.\n\nthis is useful if you want to use `getResult` (for example, to inspect the errors) but still want bubbling to happen:\n\n```typescript\ngetResult(() => {\n  importantStuff()\n  const result = getResult(() => optionalStuff())\n  for (const error in result.errors()) doSomethingElseWith(error)  \n  report(result.log)\n}).errors()\n  // -> [Error: error in importantStuff]\n  // -> [Error: error in optionalStuff]\n```","publish_time":1650579261615,"_cnpm_publish_time":1650579261615,"dist-tags":{"latest":"0.2.4"}}