{"versions":{"0.5.0":{"name":"@sevinf/maybe","version":"0.5.0","main":"dist/cjs/index.js","module":"dist/esm/index.js","types":"dist/types/index.d.ts","sideEffects":false,"author":{"name":"Sergey Tatarintsev","email":"sergey@tatarintsev.me","url":"https://github.com/SevInf"},"license":"MIT","scripts":{"test":"jest","build:esm":"tsc --module es2015 --outDir dist/esm --declaration --declarationDir dist/types","build:cjs":"tsc --module commonjs --outDir dist/cjs","build":"run-s build:*","prettier":"prettier '**/*.{ts,json,md}'","format":"yarn prettier --write","lint:eslint":"eslint . --ext ts","lint:prettier":"yarn prettier --check","lint":"run-s lint:*","tsc:check":"tsc --noEmit","prerelease":"run-s clean test build","release":"standard-version","clean":"rimraf dist"},"devDependencies":{"@commitlint/cli":"^7.5.2","@commitlint/config-conventional":"^7.5.0","@types/jest":"^24.0.12","@typescript-eslint/eslint-plugin":"^1.7.0","@typescript-eslint/parser":"^1.7.0","eslint":"^5.16.0","eslint-config-prettier":"^4.2.0","husky":"^2.2.0","jest":"^24.7.1","npm-run-all":"^4.1.5","prettier":"^1.17.0","rimraf":"^2.6.3","standard-version":"^5.0.2","ts-jest":"^24.0.2","typescript":"^3.4.5"},"jest":{"preset":"ts-jest"},"prettier":{"tabWidth":4,"singleQuote":true,"overrides":[{"files":["*.json",".*.json","*.md"],"options":{"tabWidth":2}}]},"commitlint":{"extends":["@commitlint/config-conventional"]},"husky":{"hooks":{"pre-commit":"run-s lint tsc:check","commit-msg":"commitlint -E HUSKY_GIT_PARAMS"}},"description":"Maybe/Optional type implementation in Typescript. Main motivation for creating this library was handling `null` values in deeply nested data, coming from GraphQL APIs, but the library itself is not limited to GraphQL.","licenseText":"MIT License\n\nCopyright (c) 2019 Sergey Tatarintsev\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","_id":"@sevinf/maybe@0.5.0","dist":{"shasum":"e59fcea028df615fe87d708bb30e1f338e46bb44","integrity":"sha512-ARhyoYDnY1LES3vYI0fiG6e9esWfTNcXcO6+MPJJXcnyMV3bim4lnFt45VXouV7y82F4x3YH8nOQ6VztuvUiWg==","tarball":"http://123.232.10.234:8212/nexus/content/groups/npm-public/@sevinf/maybe/-/maybe-0.5.0.tgz","fileCount":27,"unpackedSize":23189,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcz0vwCRA9TVsSAnZWagAAqGwP/0m4yY+nP7meH6w0TYNB\ngmxQzwvXqPBev9ykLgtMpo5PNxE5+HoJzJWQnnAenQO7xRh3rS115uvUrijb\nqqB5u1NwKBVRQCObEo6sQioPdAFrR/tejJRK8QAAy1by0GHai0B0La9FSG52\ng8Usv2tFuWCi/Zc2cc1Gl9oX9uON0hpNB+TfHY2PMP7bk4RhFMYdEYSZHtyA\n0I/wnUQW9rab+SBz1MjijceN3xbi0U8LWpG9vr0h7ZvT8iMNagNiiKAGZ3UW\nB4USCP+GqJ3W0ki/bwQLB06yIKuZ0CMuuaIh2bTvVbjpvCqZKcS6Gf4RXPPk\nvTMTJDyDxUY11KeZJ60WGzsgJfCetkZH0fuetnYrap+6DvKwJMiicAxrdbg6\nG0cVKBVYnInKpGIVrfAbov2nx6Q3x+7DgU4rYOcIgzfoQwt9rPgOzUnSyknK\n5zxESA9SYLf3gm0ynNCZ61l6pvhB9aJ77/9JjCKPyV581VDpiSO51bvFNhuD\nc4ddp5N2ZcCP3qfHfR0xIs2vnLD9iSPRyd2YO0e+vxAJnaqwaVx7RShfVmAF\n4hoACWCUEIkxEpB6lzLUw6qLLZp3qJA3mpr2ggg6Rg0tF982a9A4F+/0gBaL\ndisRgJ1dvsPsJF8dUJUHrpyrK+zA5sR22X1k0/VS3NJWcBBe/GTnx04rYLa7\n7Qzc\r\n=cwxp\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDbvaqL7DlyK2KWx2i+kZi1xGnSQYlQdQbNxZgVGB3FqAIgBnWcLYrhQlY4qjxurqiPN9La8mJEBlLICcbAt+5Fg9A="}]},"maintainers":[{"name":"anonymous","email":"sergey@tatarintsev.me"}],"_npmUser":{"name":"anonymous","email":"sergey@tatarintsev.me"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/maybe_0.5.0_1557089264058_0.7486624888763451"},"_hasShrinkwrap":false,"contributors":[]}},"dist-tags":{"latest":"0.5.0"},"name":"@sevinf/maybe","time":{"created":"2022-01-27T18:13:22.189Z","0.5.0":"2019-05-05T20:47:44.180Z","modified":"2022-01-27T18:13:22.189Z"},"readme":"# maybe\n\nMaybe/Optional type implementation in Typescript.\nMain motivation for creating this library was handling `null` values in deeply nested data, coming from GraphQL APIs, but the library itself is not limited to GraphQL.\n\nMain idea behind this: we put all potentially `null`/`undefined` values in a special `Maybe` box and don't allow you to take it out, unless you tell what exactly should happen in `null`/`undefined` case. We also provide a couple of helper functions, which allow you to operate on `Maybe` boxes as if they were always defined. By chaining this operation you will almost always specify the code for happy-path only and still stay `null`-safe.\n\n## Creating a maybe value\n\n### `maybe(value)`\n\nTakes a value which could potentially be `null` or `undefined` and returns a safe `Maybe` wrapper. These are all valid `maybe` calls:\n\n```js\nimport { maybe } from '@sevinf/maybe';\n\nmaybe('foo');\nmaybe(false);\nmaybe(someObject);\nmaybe(() => alert('Hello!'));\nmaybe(null);\nmaybe(undefined);\n```\n\nPrevents double-wrapping the value. `maybe(foo)` and `maybe(maybe(foo))` return the same value.\n\n### `some(value)`\n\nTakes non-`null`/`undefined` value and returns a `Maybe` wrapper. These are all valid `some` calls:\n\n```js\nimport { some } from '@sevinf/maybe';\n\nsome('foo');\nsome(false);\nsome(someObject);\nsome(() => alert('Hello!'));\n```\n\nThese calls will throw exception in runtime:\n\n```js\nimport { some } from '@sevinf/maybe';\n\nsome(null);\nsome(undefined);\n```\n\nUse it if are absolutely sure it is safe (for example, when passing the constant). In case your are not sure about nullability, use `maybe` instead.\n\n### `none`\n\nConstant, containing `Maybe` wrapper with no value inside. Safe equivalent of `null` value.\n\n## Working with `Maybe` values\n\n`Maybe` instances provide a couple of methods, which allow you to work on them in safe manner, regardless of whether or not they hold `some` or `none` values.\n\n### `.map(fn: (a) => b): Maybe<b>`\n\nThis a main method for manipulating the data inside `Maybe` box. If wrapped value is `null` or `undefined`, does nothing and returns `none` value. Otherwise, calls provided `fn` function with unboxed value (which guaranteed to be non-null) and returns new `Maybe` box from return value of `fn`.\n\nCouple of examples:\n\n```js\nimport { maybe } from '@sevinf/maybe';\n\nconst five = maybe(5);\nconst ten = five.map(x => x + 5); // ten now holds number 10\nconst shout = five.map(x => `${x}!`); // shout holds string '5!'\nconst renderFive = five.map(x => <div>{x}</div>); // contains React element, rendering number 5\n\n// all of these operations are also safe\nconst nothing = maybe(null);\nconst ten = nothing.map(x => x + 5); // ten holds nothing\nconst shout = nothing.map(x => `${x}!`); // shout holds nothing\nconst renderFive = nothing.map(x => <div>{x}</div>); // renderFive holds nothing\n```\n\nYou can chain `.map` calls together:\n\n```js\nimport { maybe } from '@sevinf/maybe';\n\nfunction addFiveShoutAndRender(maybeValue) {\n  return maybeValue\n    .map(x => x + 5)\n    .map(x => `${x}!`)\n    .map(x => <div>${x}</div>);\n}\n\naddFiveShoutAndRender(maybe(5)); // returns maybe box, holding <div>10!</div>\naddFiveShoutAndRender(maybe(null)); // returns maybe box, holding nothing\n```\n\nYou can return `Maybe` values from the `fn` callback. In that case, resulting value will be flattened. You will never have `Maybe` value, wrapped in another `Maybe`:\n\n```js\nimport { none, some } from '@sevinf/maybe';\n\nfunction filterLow(x) {\n  if (x > 100) {\n    return some(x);\n  }\n  return none;\n}\nfunction shoutOver100(maybeValue) {\n  return maybeValue.map(filterLow).map(x => `${x}!`);\n}\n\naddFiveShoutAndRender(maybe(9000)); // returns maybe box, holding string \"9000!\"\naddFiveShoutAndRender(maybe(null)); // returns maybe box, holding nothing\naddFiveShoutAndRender(maybe(5)); // returns maybe box, holding nothing\n```\n\n### `.get(key)`\n\nGetting property of the object or array element is needed often enough so we provide a helper method for this. Functionally equivalent to `.map(value => value[key])`, but nicer to use in case of deeply nested data (for example, GraphQL data):\n\n```js\nimport { maybe } from '@sevinf/maybe';\n\nfunction hasMore(maybeAccount) {\n  return maybeAccount\n    .get('followers')\n    .get('pageInfo')\n    .get('hasMoreData');\n}\n\nhasMore(\n  maybe({\n    followers: {\n      pageInfo: {\n        hasMoreData: true\n      }\n    }\n  })\n); // returns Maybe box, holding `true` inside\n\n// all those calls are safe and return boxes, containing nothing\nhasMore(maybe(null));\nhasMore(maybe({}));\nhasMore(maybe({ followers: null }));\nhasMore(maybe({ followers: {} }));\nhasMore(\n  maybe({\n    followers: {\n      pageInfo: null\n    }\n  })\n);\nhasMore(\n  maybe({\n    followers: {\n      pageInfo: {}\n    }\n  })\n);\n```\n\nAlso works with arrays:\n\n```js\nimport { maybe } from '@sevinf/maybe';\n\nconst safeArray = maybe(['foo', 'bar']);\nsafeArray.get(0); // returns Maybe<foo>\nsafeArray.get(100); // returns maybe, holding nothing\n```\n\n### `.isNone()`\n\nReturns `true` if box holds nothing:\n\n```js\nimport { maybe, none } from '@sevinf/maybe';\n\nnone.isNone(); // true\nmaybe(null).isNone(); // true\nmaybe(undefined).isNone(); // true\n\nmaybe('foo').isNone(); // false\nmaybe(false).isNone(); // false\nmaybe(0).isNone(); // false\n```\n\n## Getting the value out of the `Maybe`\n\nSo far, we learned how to create a `Maybe` value and learned to operate on it in a safe way. It is recommended that you'll pass `Maybe` values around, use `.map` functions and keep values boxes for as long as possible: that way your are safely protected from null pointer exceptions. However, at some point you'll have to get the value out: you can't send `Maybe` to react or renderer or your backend server. In that case, `Maybe` type requires you to explicitly specify what to do in `none` case. It provides a bunch of instance methods for different scenarios.\n\n### `.orElse(fallback)`\n\nReturns boxed value if it is set and provided `fallback` value otherwise:\n\n```js\nimport { maybe } from '@sevinf/maybe';\n\nmaybe(5).orElse(0); // returns 5\nmaybe(null).orElse(0); // returns 0\nmaybe(undefined).orElse(0); // returns 0\n\nmaybe({ foo: 5 })\n  .get('foo')\n  .orElse(0); // returns 5\nmaybe({ foo: 5 })\n  .get('bar')\n  .orElse(0); // returns 0\n```\n\n### `.orCall(getFallback: () => fallback)`\n\nReturns boxed value if it is set. If it is not, calls provided `getFallback` function and returns its return value. Can be used instead of `.orElse` if computing fallback value is expensive.\n\n```js\n// computeExpensiveFallbackValue won't be called unless it is really needed\nsomeMaybeValue.orCall(() => computeExpensiveFallbackValue());\n```\n\n### `.orNull()`\n\nReturns boxed value if it is set and `null` otherwise. Use with caution: you are responsible for `null`-safety on your own after this! Generally, prefer `.orElse` and `.orCall` methods, use `.orNull` only if you absolutely have to.\n\n### `.orThrow(message: ?string)`\n\nReturns boxed value if it is set and throws `TypeError` otherwise. Use only when you are absolutely sure that there is a value inside `Maybe`.\n\n```js\nimport { maybe } from '@sevinf/maybe';\n\nmaybe(5).orThrow(); // returns 5\nmaybe(null).orThrow(); // throws TypeError with default message\nmaybe(undefined).orThrow('This should never happen'); // throws TypeError with custom message\n```\n\n## Helper functions\n\nLibrary provides a number of helper functions for common scenarios:\n\n### `first(items: Maybe[]): Maybe`\n\nReturns the first item in `items`, which holds any value. Returns `none` if all `items` are `none` or the list is empty. Useful for the cases of multiple different fallbacks. Suppose we have an account. We want to display account's nickname, full name or login, whichever is set. If nothing is set, we want to fallback to default message:\n\n```js\nimport { first } from '@sevinf/maybe';\n\nfunction getDisplayName(maybeAccount) {\n  return first([\n    maybeAccount.get('nickname'),\n    maybeAccount.get('fullName'),\n    maybeAccount.get('login')\n  ]).orElse('Unknown User');\n}\n```\n\n### `all(items: Maybe[]): Maybe`\n\nAccepts array of `Maybe` values. If every value in array holds something, return `Maybe`, holding the array of unboxed values. If at least one value is `none`, returns `none`. Useful when you have several required fields and want to do something only when they are all set. For example, you want display account info only when account has both full name and profile picture. If any of those fields are missing, you want to display nothing at all:\n\n```js\nimport { all } from '@sevinf/maybe';\n\nfunction verifyAccount(maybeAccount) {\n  return all([\n    maybeAccount.get('fullName'),\n    maybeAccount.get('profilePicture')\n  ]).map(([fullName, profilePicture]) => {\n    // do something with `fullName` and `profilePicture`, they\n    // are both non-null here\n  });\n}\n```\n\n### `allProperties(object): Maybe`\n\nEquivalent to `all`, only operates on objects properties instead of array items.\n\n```js\nimport { allProperties } from '@sevinf/maybe';\n\nfunction verifyAccount(maybeAccount) {\n  return allProperties({\n    name: maybeAccount.get('fullName'),\n    picture: maybeAccount.get('profilePicture')\n  }).map(verifiedAccount => {\n    // all properties of `verifiedAccount` (name and picture) are\n    // non-null here\n  });\n}\n```\n\nYou can also mix `Maybe` and non-`Maybe` properties:\n\n```js\nimport { allProperties } from '@sevinf/maybe';\n\nfunction verifyAccount(maybeAccount) {\n  return allProperties({\n    id: 'foo'\n    name: maybeAccount.get('fullName'),\n    picture: maybeAccount.get('profilePicture')\n  }).map(verifiedAccount => {\n    // verifiedAccount has non-null `id`, `name` and `picture` properties\n  });\n}\n```\n\n### `compact(items)`\n\nAccepts array of `Maybe` values. Filters out all `none` values and unboxes the rest. Useful for filtering out unwanted items from the lists. Suppose, we have an array of accounts and we want to have only those items, which pass `verifyAccount` check from previous example:\n\n```js\nimport { compact } from '@sevinf/maybe';\n\nfunction getValidAccounts(accountList) {\n  return compact(accountList.map(verifyAccount));\n}\n```","users":{}}