{"name":"@protoplasm/recall","version":"0.2.2","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":"^26.0.20","jest":"^27.3.1","prettier":"^2.2.1","ts-jest":"^27.0.7","typescript":"^4.1.3"},"gitHead":"2c26a0ffa6eba283c44222ce2d1fc1af1e6da98a","bugs":{"url":"https://github.com/queerviolet/recall/issues"},"homepage":"https://github.com/queerviolet/recall#readme","_id":"@protoplasm/recall@0.2.2","_nodeVersion":"16.5.0","_npmVersion":"7.19.1","dist":{"integrity":"sha512-grQIYNd3UsFjHXL1g5Qw5MdUNAddEcD1KfqiO6WeMOQHgIgECXo7r4jfcXGIh37q17HoGQgq/G4guMGkzQ+UOA==","shasum":"4d8b259efba89938220088d444011b961ae3775a","tarball":"http://registry-npm.ywwl.com/@protoplasm/recall/download/@protoplasm/recall-0.2.2.tgz","fileCount":43,"unpackedSize":67189,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJiQyQ0ACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2Vmoq1A//cK+cOw/8Pse3t/WHgKMdd358YKk2mFDMaLO/LOhjURUMXgTH\r\n5gdOq+DbWFg9c+b04F6ftrD8CFxinQbH+XDcoK7TXdrxs1rD/3Nhx6tXEFk5\r\nm+mFoRAQFNJLizF9OnqLeWcv3aET97e0ARaBTCqGk19E8VbRlfv9GUTHzZkQ\r\nxMzPlF0jeBKTm35Rcw+hoCN7fn0XQoGS1sc0gN4JSdJ+qemtdC+UkFdSfm5D\r\niMascc3tZEqlX1vt889BVJdaddlfzzjdGiInTKNlpciU9a/tnZm509fQIDNy\r\nOXf6dPQbw02lXdMqrojd20UXM6IcgVi3uVihv9x+Hz06YGXhKkyb7DASFrhb\r\nRmkPemezw4byf///ghaupC49DrASXF7cguHhbUwGfxfPAopW0RmHozKN2+qm\r\n1HiCp5f588gT4HXr2AejFRExYc4zu5vCoLyCDs4cjqaJlgL0/DO4ypoLo6u8\r\nm28OdEq033kqGxe44Lri99Cpq9WujHUX5eKsOzuv2xOts/wGtJsB9n80FeK8\r\nG6+EDnaI7m172JfIJ08Q6fj2jwE2bc6I/Shq6r1ii1hUMu5Fa9VdIya4Bsk1\r\nree507bhJWU7kE5uCLY+C+3FBBDYmpWjcRjyiELAQjabUvFm3R8Yjc2IDxiG\r\nnNCNBp1JlKygZ4NFTZ51p7UzfdUaDoexI3Y=\r\n=CFnB\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIBbFzOBNclOKKnFEDbSYXhg7/xf0ME402a9q8rE5dJURAiEA7s/SUZHd+0AdN1TAy5CeE3vGtEBtk5uXMeS/RSnsLJ8="}],"size":17106,"noattachment":false,"key":"/@protoplasm/recall/-/@protoplasm/recall-0.2.2.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.2_1648567348604_0.8897034377799546"},"_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":1648567348746,"_cnpm_publish_time":1648567348746,"dist-tags":{"latest":"0.2.4"}}