11 Commits
v0.0.3 ... dev

Author SHA1 Message Date
github-actions[bot]
74852c481a ci: 👷 update dev branch 2024-01-18 22:17:24 +00:00
github-actions[bot]
be5ea204ce ci: 👷🦋 version packages 2024-01-18 22:11:58 +00:00
Gustavo "Guz" L. de Mello
4c3e60cf85 chore: 🔧 fix node version 2024-01-18 19:11:04 -03:00
Guz
c04b7d5c8c chore: merge #9
feat: try functions
2024-01-18 22:08:16 +00:00
Gustavo "Guz" L. de Mello
a4f857e71e chore: 🔧 package.json exports 2024-01-18 19:05:57 -03:00
Gustavo "Guz" L. de Mello
ecfbfc7ea4 chore: 🔧 add changeset 2024-01-18 18:53:41 -03:00
Gustavo "Guz" L. de Mello
ae87a2da7b feat!: 💥 invert order of array 2024-01-18 18:50:50 -03:00
Gustavo "Guz" L. de Mello
02490a2502 refactor: ♻️ improve and export types 2024-01-18 18:29:51 -03:00
Gustavo "Guz" L. de Mello
3444a1c5da docs: 📚️ add documentation using jsdocs 2024-01-18 18:08:48 -03:00
Gustavo "Guz" L. de Mello
f19a5ec2b1 feat: "try" function 2024-01-18 17:22:05 -03:00
github-actions[bot]
0895f7c1c2 ci: 👷 update dev branch 2024-01-18 04:21:46 +00:00
8 changed files with 284 additions and 21 deletions

View File

@@ -1,5 +1,11 @@
# lilbetter.js
## 0.1.0
### Minor Changes
- ecfbfc7: Created the tryAsync (tryA) and trySync (tryS) functions, said can be used for wrapping and calling functions that can throw error. Said error can then be handled using in a Go-like fashion.
## 0.0.3
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "lilbetter.js",
"version": "0.0.3",
"version": "0.1.0",
"description": "",
"main": "./src/index.js",
"browser": "./src/index.js",
@@ -12,9 +12,16 @@
"url": "https://github.com/LoredDev/lilbetter.js"
},
"exports": {
"import": "./src/index.js",
"default": "./src/index.js",
"types": "./src/index.d.ts"
".": {
"import": "./src/index.js",
"default": "./src/index.js",
"types": "./src/index.d.ts"
},
"./try": {
"import": "./src/try.js",
"default": "./src/try.js",
"types": "./src/try.d.ts"
}
},
"files": [
"./src/**/*.js",
@@ -36,7 +43,7 @@
},
"license": "MIT",
"engines": {
"node": ">=20",
"node": ">=18",
"pnpm": ">=8"
},
"publishConfig": {

5
src/index.d.ts vendored
View File

@@ -1,6 +1,3 @@
interface Test {
name: string,
}
export * from './try.d.ts';
export default Test;

View File

@@ -1,5 +1,3 @@
/*
* Placeholder file
*/
// eslint-disable-next-line no-console
console.log('Hello, world!');
export * from './try.js';

94
src/try.d.ts vendored Normal file
View File

@@ -0,0 +1,94 @@
/**
* The WrappedResult type returned by the wrapped function in {@link trySync}
* and {@link tryAsync}.
*
* **If a error occurred, the result is undefined**.
* If there's not a error, error will be null and the result will be defined.
*/
type WrappedResult<R> = [R, null] | [undefined, Error];
/**
* The returned function from {@link tryAsync}.
*
* @param args - The arguments of the function.
* - The arguments of the wrapped function.
* @returns
* - The final tuple containing the Error object (if one occured) and the resulting value.
*/
type WrappedAsyncFunction<F> = (...args: Parameters<F>) =>
Promise<WrappedResult<Awaited<ReturnType<F>>>>;
/**
* Function-sugar/Syntax-sugar for handling functions that can throw errors. Wrapping then
* into a try-catch block / "curried function" that returns a "tuple as array" of error and
* value, which can be used for handling the error using a Go-like fashion. **This function
* is for asynchronous operations,** for synchronous ones, see {@link trySync}.
*
* **If there's a error, the result is undefined**.
* If there's not a error, error will be null and the result will be defined.
*
* @param func
* - The function to be executed.
* @returns
* - The function to be immediately called with the wrapped function's arguments.
* @example
* const [error, res] = await tryAsync(fetch)("https://example.com");
* if (error !== null) {
* // error handling...
* console.log(error);
* }
* // continue the logic...
*/
function tryAsync<
F extends (...args: Parameters<F>) => (ReturnType<F> extends Promise
? ReturnType<F>
: Promise<ReturnType<F>>
),
>(func: F): WrappedAsyncFunction<F>;
/**
* The returned function from {@link trySync}.
*
* @param args
* - The arguments of the wrapped function.
* @returns
* - The final tuple containing the Error object (if one occured) and the resulting value.
*/
type WrappedFunction<F> = (...args: Parameters<F>) =>
WrappedResult<ReturnType<F>>;
/**
* Function-sugar/Syntax-sugar for handling functions that can throw errors. Wrapping then
* into a try-catch block / "curried function" that returns a "tuple as array" of error and
* value, which can be used for handling the error using a Go-like fashion. **This function
* is for synchronous operations,** for asynchronous ones, see {@link tryAsync}.
*
* **If there's a error, the result is undefined**.
* If there's not a error, error will be null and the result will be defined.
*
* @param func
* - The function to be executed.
* @returns
* - The function to be immediately called with the wrapped function's arguments.
* @example
* const [error, json] = trySync(JSON.parse)('{ "hello": "world" }');
* if (error !== null) {
* // error handling...
* console.log(error);
* }
* // continue the logic...
*/
function trySync<
F extends (...args: Parameters<F>) => ReturnType<F>,
>(func: F): WrappedFunction<F>;
export {
type WrappedAsyncFunction,
type WrappedFunction,
type WrappedResult,
tryAsync as tryA,
tryAsync,
trySync as tryS,
trySync,
};

133
src/try.js Normal file
View File

@@ -0,0 +1,133 @@
/* eslint-disable no-secrets/no-secrets */
/**
* The WrappedResult type returned by the wrapped function in {@link trySync}
* and {@link tryAsync}.
*
* **If a error occurred, the result is undefined**.
* If there's not a error, error will be null and the result will be defined.
*
* @typedef {[R, null] | [undefined, Error]} WrappedResult<R>
* @template R
*/
/**
* The returned function from {@link tryAsync}.
*
* @typedef {(...args: Parameters<F>) => Promise<WrappedResult<Awaited<ReturnType<F>>>>}
* WrappedAsyncFunction
* @template {(...args: Parameters<F>) => ReturnType<F>} F
*/
/**
* Function-sugar/Syntax-sugar for handling functions that can throw errors. Wrapping then
* into a try-catch block / "curried function" that returns a "tuple as array" of error and
* value, which can be used for handling the error using a Go-like fashion. **This function
* is for asynchronous operations,** for synchronous ones, see {@link trySync}.
*
* **If there's a error, the result is undefined**.
* If there's not a error, error will be null and the result will be defined.
*
* @template {(...args: Parameters<F>) => Promise<Awaited<ReturnType<F>>>} F
* @param {F} func
* - The function to be executed.
* @returns {WrappedAsyncFunction<F>}
* - The function to be immediately called with the wrapped function's arguments.
* @example
* const [error, res] = await tryAsync(fetch)("https://example.com");
* if (error !== null) {
* // error handling...
* console.log(error);
* }
* // continue the logic...
*/
function tryAsync(func) {
/**
* The returned function from {@link tryAsync}.
*
* @param {Parameters<F>} args - The arguments of the function.
* - The arguments of the wrapped function.
* @returns {Promise<WrappedResult<Awaited<ReturnType<F>>>>}
* - The final tuple containing the Error object (if one occured) and the resulting value.
*/
return async (...args) => {
try {
return [await func(...args), null];
}
catch (error) {
if (error instanceof Error) return [undefined, error];
const errObj = new Error(error?.toString
// eslint-disable-next-line @typescript-eslint/no-base-to-string
? `Stringified error to: ${error.toString()}`
: 'Could not stringify error',
{ cause: { value: error } });
return [undefined, errObj];
}
};
}
/**
* The returned function from {@link trySync}.
*
* @typedef {(...args: Parameters<F>) => WrappedResult<ReturnType<F>>} WrappedFunction
* @template {(...args: Parameters<F>) => ReturnType<F>} F
*/
/**
* Function-sugar/Syntax-sugar for handling functions that can throw errors. Wrapping then
* into a try-catch block / "curried function" that returns a "tuple as array" of error and
* value, which can be used for handling the error using a Go-like fashion. **This function
* is for synchronous operations,** for asynchronous ones, see {@link tryAsync}.
*
* **If there's a error, the result is undefined**.
* If there's not a error, error will be null and the result will be defined.
*
* @template {(...args: Parameters<F>) => ReturnType<F>} F
* @param {F} func
* - The function to be executed.
* @returns {WrappedFunction<F>}
* - The function to be immediately called with the wrapped function's arguments.
* @example
* const [error, json] = trySync(JSON.parse)('{ "hello": "world" }');
* if (error !== null) {
* // error handling...
* console.log(error);
* }
* // continue the logic...
*/
function trySync(func) {
/**
* The returned function from {@link trySync}.
*
* @param {Parameters<F>} args
* - The arguments of the wrapped function.
* @returns {WrappedResult<ReturnType<F>>}
* - The final tuple containing the Error object (if one occured) and the resulting value.
*/
return (...args) => {
try {
return [func(...args), null];
}
catch (error) {
if (error instanceof Error) return [undefined, error];
const errObj = new Error(error?.toString
// eslint-disable-next-line @typescript-eslint/no-base-to-string
? `Stringified error to: ${error.toString()}`
: 'Could not stringify error',
{ cause: { value: error } });
return [undefined, errObj];
}
};
}
export {
tryAsync as tryA,
tryAsync,
trySync as tryS,
trySync,
};

View File

@@ -1,7 +0,0 @@
// eslint-disable-next-line n/no-unpublished-import
import { expect, test } from 'vitest';
test('placeholder', () => {
expect(1).toBe(1);
});

35
test/try.test.js Normal file
View File

@@ -0,0 +1,35 @@
/* eslint-disable import/no-relative-parent-imports */
// eslint-disable-next-line n/no-unpublished-import
import { describe, it } from 'vitest';
import { tryA, tryS } from '../src/index.js';
describe.concurrent('Return values', () => {
it('JSON parsing [Sync, Success]', ({ expect }) => {
const [json, error] = tryS(JSON.parse)('{ "hello": "world" }');
expect(error).toBe(null);
expect(json).toEqual({ hello: 'world' });
});
it('JSON parsing [Sync, Error]', ({ expect }) => {
const [json, error] = tryS(JSON.parse)('{ "hello: "world" }');
expect(error?.name).toEqual('SyntaxError');
expect(error).toBeInstanceOf(Error);
expect(json).toBe(undefined);
});
it('Fetch function [Async, Success]', async ({ expect }) => {
const [res, error] = await tryA(fetch)('https://example.com');
expect(error).toBe(null);
expect(res?.status).toBe(200);
});
it('Fetch function [Async, Error]', async ({ expect }) => {
const [res, error] = await tryA(fetch)('htps://example.com');
expect(error?.name).toEqual('TypeError');
expect(error).toBeInstanceOf(Error);
expect(res).toBe(undefined);
});
});