{"id":27168226,"url":"https://github.com/michaelpiper/result-library","last_synced_at":"2025-04-09T05:29:37.663Z","repository":{"id":272774648,"uuid":"917708969","full_name":"michaelpiper/result-library","owner":"michaelpiper","description":"The Result library is a TypeScript utility that provides a structured way to handle success (Ok) and failure (Err) cases in your application. It is inspired by functional programming patterns and languages like Rust, enabling robust error handling without relying on exceptions.","archived":false,"fork":false,"pushed_at":"2025-03-07T09:34:22.000Z","size":18,"stargazers_count":5,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-07T10:09:30.652Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/michaelpiper.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-01-16T13:59:35.000Z","updated_at":"2025-03-07T09:34:25.000Z","dependencies_parsed_at":"2025-01-16T15:46:52.132Z","dependency_job_id":"f3df404b-4795-4fe4-8600-e97bdeeb7306","html_url":"https://github.com/michaelpiper/result-library","commit_stats":null,"previous_names":["michaelpiper/result-library"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelpiper%2Fresult-library","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelpiper%2Fresult-library/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelpiper%2Fresult-library/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelpiper%2Fresult-library/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/michaelpiper","download_url":"https://codeload.github.com/michaelpiper/result-library/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247985832,"owners_count":21028765,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-04-09T05:29:37.009Z","updated_at":"2025-04-09T05:29:37.655Z","avatar_url":"https://github.com/michaelpiper.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Result Library\n\nThe Result library is a TypeScript utility that provides a structured way to handle success (`Ok`) and failure (`Err`) cases in your application. It is inspired by functional programming patterns and languages like Rust, enabling robust error handling without relying on exceptions.\n\n## Features\n\n- **Type Safety**: Explicitly handle `Ok` and `Err` cases with strong TypeScript typings.\n- **Convenient API**: Simplifies handling success and error scenarios with intuitive methods.\n- **Improved Error Handling**: Avoid unexpected runtime errors with structured control flows.\n- **Reusable Components**: Easily integrate into any TypeScript project.\n\n## Installation\n\n```bash\nnpm install result-library\n```\n\n## Usage\n\n### Creating Results\n\nTo create `Ok` and `Err` results, use the `ResultBuilder` interface.\n\n```typescript\nimport { ResultBuilder } from 'result-library';\n\nconst { Ok, Err } = ResultBuilder();\n\nconst success = Ok(\"Operation was successful\");\nconst failure = Err(\"An error occurred\");\n```\n\n### Checking Results\n\n```typescript\nif (success.is_ok()) {\n  console.log(\"Success:\", success.unwrap());\n} else {\n  console.error(\"Error:\", success.err());\n}\n\nif (failure.is_err()) {\n  console.error(\"Failure:\", failure.unwrap_err());\n}\n```\n\n### Example Use Case\n\n```typescript\nfunction divide(a: number, b: number) {\n  const { Ok, Err } = ResultBuilder();\n  if (b === 0) {\n    return Err(\"Division by zero is not allowed\");\n  }\n  return Ok(a / b);\n}\n\nconst result = divide(10, 2);\nif (result.is_ok()) {\n  console.log(\"Result:\", result.unwrap());\n} else {\n  console.error(\"Error:\", result.unwrap_err());\n}\n```\n\n### Advanced Usage with Types\n\nYou can define explicit types for better type safety.\n\n```typescript\nconst { Ok, Err } = ResultBuilder\u003cnumber, string\u003e();\nconst result = Ok(42);\nconst error = Err(\"Something went wrong\");\n\nif (result.is_ok()) {\n  console.log(result.unwrap());\n} else {\n  console.error(result.unwrap_err());\n}\n```\n\n### Additional Example: Handling Multiple Cases\n\n```typescript\nfunction fetchUserData(userId: string) {\n  const { Ok, Err } = ResultBuilder\u003c{ name: string; age: number }, string\u003e();\n  if (userId === \"123\") {\n    return Ok({ name: \"John Doe\", age: 30 });\n  } else {\n    return Err(\"User not found\");\n  }\n}\n\nconst userResult = fetchUserData(\"123\");\nif (userResult.is_ok()) {\n  console.log(\"User Data:\", userResult.unwrap());\n} else {\n  console.error(\"Error:\", userResult.unwrap_err());\n}\n```\n\n### Use Case: File Processing\n\n```typescript\nfunction processFile(filePath: string) {\n  const { Ok, Err } = ResultBuilder\u003cstring, string\u003e();\n\n  if (!filePath.endsWith(\".txt\")) {\n    return Err(\"Only .txt files are supported\");\n  }\n\n  try {\n    const fileContent = \"File content\"; // Simulate reading a file\n    return Ok(fileContent);\n  } catch (error) {\n    return Err(\"Failed to process the file\");\n  }\n}\n\nconst fileResult = processFile(\"example.txt\");\nif (fileResult.is_ok()) {\n  console.log(\"File Content:\", fileResult.unwrap());\n} else {\n  console.error(\"Error:\", fileResult.unwrap_err());\n}\n```\n\n### Use Case: API Response Handling\n\n```typescript\nasync function fetchData(apiUrl: string) {\n  const { Ok, Err } = ResultBuilder\u003cany, string\u003e();\n\n  try {\n    const response = await fetch(apiUrl);\n    if (!response.ok) {\n      return Err(`API error: ${response.status}`);\n    }\n    const data = await response.json();\n    return Ok(data);\n  } catch (error) {\n    return Err(\"Network error\");\n  }\n}\n\n(async () =\u003e {\n  const apiResult = await fetchData(\"https://api.example.com/data\");\n  if (apiResult.is_ok()) {\n    console.log(\"API Data:\", apiResult.unwrap());\n  } else {\n    console.error(\"Error:\", apiResult.unwrap_err());\n  }\n})();\n```\n\nThe `Result` class provides a way to handle success and error outcomes in a structured way. Below is an example demonstrating how to use `Ok`, `Err`, and the `ResultBuilder` to handle different results.\n\n### Code Example:\n\n```typescript\nimport { ResultBuilder } from 'result-library';\n\n// deconstruct ResultBuilder and create Ok, Err builder instance\nconst { Ok, Err } = ResultBuilder\u003cstring, string\u003e();\n\n// Simulate a function that can either succeed or fail\nfunction fetchData(success: boolean) {\n  if (success) {\n    return Ok('Data retrieved successfully');\n  } else {\n    return Err('Failed to retrieve data');\n  }\n}\n\n// Simulate a success scenario\nconst successResult = fetchData(true);\nif (successResult.is_ok()) {\n  console.log(successResult.ok()); // Output: 'Data retrieved successfully'\n} else {\n  console.log(successResult.err());\n}\n\n// Simulate an error scenario\nconst errorResult = fetchData(false);\nif (errorResult.is_err()) {\n  console.log(errorResult.err()); // Output: 'Failed to retrieve data'\n} else {\n  console.log(errorResult.ok());\n}\n\ntry {\n  console.log(successResult.unwrap()); // Output: 'Data retrieved successfully'\n  console.log(errorResult.unwrap()); // Throws error: \"Called unwrap() on an Ok value\"\n} catch (e) {\n  console.error(e.message);\n}\n\ntry {\n  console.log(successResult.unwrap_err()); // Throws error: \"Called unwrap_err() on an Ok value\"\n} catch (e) {\n  console.error(e.message);\n}\n```\n\n## Advantages\n\n1. **Eliminates Ambiguity**: Clear distinction between success and error states.\n2. **Improves Readability**: Code is more declarative and self-documenting.\n3. **Avoids Exceptions**: Encourages error handling through return types instead of exceptions.\n4. **Enhances Debugging**: Easily identify and manage error cases.\n\n## API Reference\n\n### `Result\u003cA, E\u003e`\n\nA generic class representing either a success (`Ok`) or failure (`Err`) value.\n\n#### Methods:\n\n- **`is_ok(): boolean`**: Returns `true` if the result is `Ok`.\n- **`is_err(): boolean`**: Returns `true` if the result is `Err`.\n- **`ok(): A`**: Retrieves the success value.\n- **`err(): E`**: Retrieves the error value.\n- **`unwrap(): A`**: Returns the success value or throws an error if the result is `Err`.\n- **`unwrap_err(): E`**: Returns the error value or throws an error if the result is `Ok`.\n\n### `Ok\u003cA, E\u003e`\n\nA subclass of `Result` representing a success state.\n\n### `Err\u003cE, A\u003e`\n\nA subclass of `Result` representing an error state.\n\n### `ResultBuilder`\n\nAn interface for creating `Ok` and `Err` instances.\n\n- **`Ok\u003cA, E\u003e(value: A): Ok\u003cA, E\u003e`**: Creates an `Ok` result with the given value.\n- **`Err\u003cE, A\u003e(error: E): Err\u003cE, A\u003e`**: Creates an `Err` result with the given error.\n\n## Contributing\n\nContributions are welcome! Please open an issue or submit a pull request for enhancements or bug fixes.\n\n## License\n\nThis library is licensed under the MIT License. See `LICENSE` for details.\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichaelpiper%2Fresult-library","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmichaelpiper%2Fresult-library","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichaelpiper%2Fresult-library/lists"}