Skip to content

angular-package/callback

 
 

Repository files navigation

Packages

Useful and simple to use packages based on the angular.io.

Package Description Status
callback Manages the callback function. npm version
change-detection Improves application performance. npm version
component-loader Handles dynamic loading components. npm version
core Core features. npm version
error Manages an Error. npm version
prism Prism highlighter module. npm version
property Handles object properties. npm version
reactive Automatize the process of creating some rxjs features. npm version
testing Support for testing other packages. npm version
type Common types, type guards, and type checkers. npm version
ui User interface. In Progress

Click on the package name to visit its GitHub page.

angular-package/callback

Manages the callback function.

npm version

GitHub issues GitHub forks GitHub stars GitHub license

GitHub sponsors Support me on Patreon


Table of contents



Basic concepts

Checks

It's to check the provided value to be the same as expected.

Type guard (constrain)

Constrains the parameter type to not let input unexpected value in the code editor.

Guards

It's a combination of both above, constrains the type of the parameter in the code editor, and checks its provided argument.

Defines

Returns defined value from a method of an object.
Defines new value in an object and returns a defined value.

Gets

Returns a value from an object.

Sets

Adds or updates an element with a specified key and a value to an object and returns an object.


Skeleton

This package was built by the library skeleton which was generated with Angular CLI version 12.2.5.

Copy this package to the packages/callback folder of the library skeleton then run the commands below.

Build

Run ng build callback to build the package. The build artifacts will be stored in the dist/ directory.

Running unit tests

Run ng test callback to execute the unit tests via Karma.


Installation

Install @angular-package/callback package with command:

npm i @angular-package/callback --save

Api

import {
  // Class.
  Callback,
} from '@angular-package/callback';

Callback

Manages the callback function of ResultCallback and ForEachCallback type.


Static methods:

Callback. Description
defineErrorCallback() Defines callback function of ResultCallback type to throw ValidationError with a specified message on a state from the supplied throwOnState.
defineForEachCallback() Defines callback function of ForEachCallback type to handle forEach() method of functions prefixed with are from @angular-package/type.
defineResultCallback() Defines callback function of ResultCallback type that contains ResultHandler function to handle the result, value, and optional payload without returning the result.
guard() Guards the provided resultCallback to be ResultCallback type.
isCallback() Checks if the provided value is an instance of Callback with optional allowed names under which callback functions can be stored.

Constructor:

Constructor Description
Callback() Initialize an instance of Callback with allowed names under which callback functions can be stored.

Instance methods:

Callback.prototype. Description
getForEachCallback() Gets from the storage specified by-name callback function of ForEachCallback type.
getResultCallback() Gets from the storage specified by-name callback function of a ResultCallback type.
setErrorCallback() Sets a callback function of a ResultCallback type that throws ValidationError with a specified message on a state from the provided throwOnState to the storage under the given allowed name restricted by AllowNames.
setForEachCallback() Sets a callback function of a ForEachCallback type to the storage under the given allowed name, which is restricted by AllowNames.
setResultCallback() Sets a callback function of a ResultCallback type to the storage under the given allowed name, which is restricted by AllowNames.

Callback static methods

Callback.defineErrorCallback()

update

Defines callback function of ResultCallback type to throw ValidationError with a specified message on a state from the supplied throwOnState. The provided result, value, and payload from the defined callback function of ResultCallback are being passed to a thrown error of ValidationError.

static defineErrorCallback<Value = any, Payload extends object = object>(
  message: string | ErrorMessage,
  throwOnState: boolean = false,
  resultHandler?: ResultHandler<Value, Payload>,
  defaultPayload?: Payload
): ResultCallback<Value, Payload> {
  return Callback.defineResultCallback((result, value, payload): void => {
    if (isFunction(resultHandler)) {
      resultHandler(result, value, payload);
    }
    if (isFalse(throwOnState) ? isFalse(result) : isTrue(result)) {
      throw Object.assign(new ValidationError(message), {
        result,
        value,
        payload,
      });
    }
  }, defaultPayload);
}

Generic type variables:

Name Default value Description
Value any A generic type variable Value by default equal to any determines the type of the value parameter of returned ResultCallback function.
Payload object The shape of the optional payload parameter of returned ResultCallback function constrained by the object type. Its value can be captured from a type of the provided defaultPayload optional parameter.

Parameters:

Name: type Description
message: string | ErrorMessage The message of string type or ErrorMessage interface to throw with an error of ValidationError.
throwOnState: boolean A state of boolean type on which an error of ValidationError should be thrown. By default, it's set to false.
resultHandler?: ResultHandler<Value, Payload> An optional function of ResultHandler type to inject into returned callback function of ResultCallback type in order to execute it before the thrown error.
defaultPayload?: Payload An optional object of generic type variable Payload as the default value of payload parameter of ResultHandler function from the supplied resultHandler parameter.

Returns:

Returns Type Description
ResultCallback<Value, Payload> function The return type is a function of a ResultCallback type.

The return value is a function of a ResultCallback type that throws a ValidationError.

Usage:

// Example usage.
import { Callback } from '@angular-package/callback';
import { is } from '@angular-package/type';

// Define callback function of `ResultCallback` type for the `is.string()` method.
const stringCallback = Callback.defineErrorCallback(
  'Something went wrong',
  false,
  (result, value, payload) => {
    // Console returns {field: 'firstName'}
    console.log(payload);
  },
  { field: 'firstName' }
);

// Uncaught ValidationError: Something went wrong
is.string(5, stringCallback);
// Example usage.
import { Callback } from '@angular-package/callback';
import { is } from '@angular-package/type';

// Define callback function for the `is.string()` method to check `firstName` against string type.
const isNameCallback = Callback.defineErrorCallback<
  string,
  { field?: 'firstName'; age?: number }
>(
  'Name must be a string type.',
  false,
  (result, value, payload) => {
    // Console returns {name: 'isFirstName', field: 'firstName'}
    console.log(payload);
  },
  { field: 'firstName' }
);

// Define `isFirstName()` function to check the string.
const isFirstName = (value: any, callback = isNameCallback): value is boolean =>
  is.string(3, callback, { name: 'isFirstName' });

// Uncaught ValidationError: Name must be a string type.
isFirstName(3);

// Caught ValidationError: Name must be a string type.
try {
  isFirstName(3);
} catch (e) {
  e.result; // false
  e.value; // 3
  e.payload; // {name: 'isFirstName', field: 'firstName'}
}
// Example usage.
import { Callback } from '@angular-package/callback';
import { is, ResultCallback } from '@angular-package/type';

// Define the `Person` type.
type Person = { id?: number; firstName?: string; age?: number };

// Define `isPerson()` function.
const isPerson = (
  value: Person,
  callback: ResultCallback<Person, { database: string }> = (result) => result
): any => callback(typeof value === 'object', value);

// Define callback function of `ResultCallback` for the `isPerson()` function.
const personErrorCallback = Callback.defineErrorCallback<Person>(
  'It is not a person',
  true,
  { database: 'person_1' }
);

try {
  isPerson({ id: 1, firstName: 'name', age: 27 }, personErrorCallback);
} catch (e) {
  // Console returns { "database": "person_1" }
  console.log(e.payload);
}

Callback.defineForEachCallback()

new

Defines callback function of ForEachCallback type to handle forEach() method of functions prefixed with are from @angular-package/type.

static defineForEachCallback<Value = any, Payload extends object = object>(
  forEachCallback: ForEachCallback<Value, Payload>,
  defaultPayload?: Payload
): ForEachCallback<Value, Payload> {
  return (result, value, index, array, payload) =>
    forEachCallback(result, value, index, array, {
      ...payload,
      ...defaultPayload,
    } as any);
}

Generic type variables:

Name Default value Description
Value any A generic type variable Value by default equal to any determines the type of the value parameter of the ForEachCallback function in the supplied forEachCallback parameter and return type.
Payload object The shape of the optional payload parameter of the ForEachCallback function of the supplied forEachCallback parameter and the return type. Its value can be captured from a type of the provided defaultPayload optional parameter.

Parameters:

Name: type Description
forEachCallback: ForEachCallback<Value, Payload> The function of ForEachCallback type to define.
defaultPayload?: Payload An optional object of generic type variable Payload as the default value of payload parameter of the returned ForEachCallback function.

Returns:

Returns Type Description
ForEachCallback<Value, Payload> function The return type is a function of ForEachCallback.

The return value is a function of the ForEachCallback type.

Usage:

// Example usage.
import { Callback } from '@angular-package/callback';
import { are } from '@angular-package/type';

// Define callback function of `ForEachCallback` type for the `are.string()` method.
const areStringCallback = Callback.defineForEachCallback(
  (result, value, index, array, payload) => {
    console.log(`areString()`, result, value, index, array, payload);
  },
  { database: 'person' } as any
);

are
  .string('someone', null, '')
  // Console returns
  // areString() true someone 0 (3) ['someone', null, ''] {name: 'no name', database: 'person'}
  // areString() false null 1 (3) ['someone', null, ''] {name: 'no name', database: 'person'}
  // areString() true  2 (3) ['someone', null, ''] {name: 'no name', database: 'person'}
  .forEach(areStringCallback, { name: 'no name' });
// Example usage.
import { Callback } from '../lib/callback.class';
import { are, ForEachCallback } from '@angular-package/type';

// Example usage in the `class`.
class Person {
  #callback!: Callback<'check'>;

  #persons: Array<{ checked: boolean; name: string }> = [
    { checked: false, name: 'Someone' },
    { checked: false, name: undefined as any },
    { checked: true, name: 'Someone' },
  ];

  constructor(handleCallback: Callback<'check'>) {
    if (handleCallback) {
      this.#callback = handleCallback;
    }
  }

  public check(
    callbackFn: ForEachCallback = this.#callback.getForEachCallback('check')
  ): this {
    are
      .true(...this.#persons.map((v) => v.checked))
      .forEach(callbackFn, this.#persons);
    return this;
  }
}

// Initialize default callbacks.
const defaultCallbacks = new Callback('check').setForEachCallback<boolean, any>(
  'check',
  (result, value, index, array, persons) => {
    if (result === true) {
      // Console returns 2 true {checked: true, name: 'Someone'}
      console.log(index, result, persons[index]);
    } else {
      persons[index].checked = true;
    }
  }
);

// Inject `defaultCallbacks` into instance of `Person` and set `checked` to `true` if `false` by using `check()` method.
new Person(defaultCallbacks).check();

Callback.defineResultCallback()

update

Defines callback function of ResultCallback type that contains ResultHandler function to handle the result, value, and optional payload without returning the result.

static defineResultCallback<Value = any, Payload extends object = object>(
  resultHandler: ResultHandler<Value, Payload>,
  defaultPayload?: Payload
): ResultCallback<Value, Payload> {
  return (result, value, payload) => (
    resultHandler(result, value, {
      ...payload,
      ...defaultPayload,
    } as Payload),
    result
  );
}

Generic type variables:

Name Default value Description
Value any A generic type variable Value by default equal to any determines the type of the value parameter of returned ResultCallback function and ResultHandler function from the supplied resultHandler parameter.
Payload object The shape of the optional payload parameter of returned ResultCallback function and ResultHandler function from the supplied resultHandler parameter, constrained by the object type. Its value can be captured from a type of the provided defaultPayload optional parameter.

Parameters:

Name: type Description
resultHandler: ResultHandler<Value, Payload> The function of ResultHandler type to inject into returned callback function of ResultCallback type.
defaultPayload?: Payload An optional object of generic type variable Payload as the default value of payload parameter of returned ResultCallback function and ResultHandler function from given resultHandler parameter.

Returns:

Returns Type Description
ResultCallback<Value, Payload> function The return type is a function of ResultCallback.

The return value is a function of the ResultCallback type that contains the given function of ResultHandler type.

Usage:

// Example usage.
import { Callback } from '@angular-package/callback';
import { is } from '@angular-package/type';

const stringCallback = Callback.defineResultCallback(
  (result: boolean, payload) => {
    if (is.false(result)) {
      console.log(`Something went wrong`, payload);
    }
  }
);

// Returns in console 'Something went wrong' 5
is.string(5, stringCallback);
// Example usage.
import { Callback } from '@angular-package/callback';
import { ResultCallback } from '@angular-package/type';

// Define the `Person` type.
type Person = { id?: number; firstName?: string; age?: number };

// Define `isPerson()` function.
const isPerson = (
  value: Person,
  callback: ResultCallback<Person, { database: string }> = (result) => result
): any => callback(typeof value === 'object', value);

// Define callback function of `ResultCallback` type.
const personResultCallback = Callback.defineResultCallback(
  (result, value, payload) => {
    if (payload !== undefined) {
      console.log(result, value, payload);
    }
  },
  { database: 'person' }
);

// Console returns true { firstName: 'My name' } { database: 'person' }
isPerson({ firstName: 'My name' }, personResultCallback);

Callback.guard()

update

Guards the provided resultCallback to be ResultCallback type.

static guard<Value = any, Payload extends object = object>(
  resultCallback: ResultCallback<Value, Payload>
): resultCallback is ResultCallback<Value, Payload> {
  return guardFunction(resultCallback);
}

Generic type variables:

Name Default value Description
Value any A generic type variable Value by default equal to any determines the type of the value parameter of the returned ResultCallback function.
Payload object The shape of the optional payload parameter of the ResultCallback and ResultHandler function constrained by the object type. Its value can be captured from a type of the provided defaultPayload optional parameter.

Parameters:

Name: type Description
resultCallback: ResultCallback<Value, Payload> The function of ResultCallback type to guard.

Returns:

Returns Type Description
resultCallback is ResultCallback<Value, Payload> boolean The return type is boolean as the result of its statement that indicates the provided resultCallback is a function of a ResultCallback type.

The return value is a boolean indicating whether the provided resultCallback parameter is a function.

Usage:

// Example usage.
import { Callback } from '@angular-package/callback';

Callback.guard(result => result); // Returns `true`.
Callback.guard({} as any); // Returns `false`.

Callback.isCallback()

Checks if the provided value is an instance of Callback with optional allowed names under which callback functions can be stored.

static isCallback<AllowNames extends string>(
  value: any,
  ...allowNames: AllowNames[]
): value is Callback<AllowNames> {
  return isInstance(value, Callback);
}

Generic type variables:

Name Default value Description
AllowNames string A generic type variable AllowNames constrained by the string type that is used to indicate allowed names under which callback functions can be stored via the return type value is Callback<AllowNames>. Its value can be captured from the provided allowNames rest parameter.

Parameters:

Name: type Description
value: any The value of any type to check.
...allowNames: AllowNames[] A rest parameter of generic type variable AllowNames is being used only to capture the type for AllowNames of returned Callback.

Returns:

Returns Type Description
value is Callback<AllowNames> boolean The return type is boolean as the result of its statement that indicates the provided value is Callback with allowed names from the provided allowNames parameter or generic type variable AllowNames.

The return value is a boolean indicating whether the value is an instance of Callback.

Usage:

// Example usage.
import { Callback } from '@angular-package/callback';

Callback.isCallback({}); // Returns `false`
Callback.isCallback(new Callback()); // Returns `true`

const callback = new Callback('one', 'two', 'three');
if (Callback.isCallback(callback)) {
  // There's no hint on `name` parameter about allowed names.
  callback.setCallback('one', result => result);
}
if (Callback.isCallback(callback, 'one', 'two')) {
  // There is a hint from the provided `allowNames` parameter of the `isCallback()` method.
  callback.setCallback('one', result => result);
}

Callback constructor

Callback()

Initialize an instance of Callback with allowed names under which callback functions can be stored.

new Callback<AllowNames extends string>(...allowNames: AllowNames[]) {
  this.#allowedNames = guard.array(allowNames)
    ? new Set(allowNames)
    : this.#allowedNames;
}

Generic type variables:

Name Default value Description
AllowNames string A generic type variable of AllowNames name constrained by string type that is used to restrict allowed names under which callback functions can be stored. Its value must be captured from the provided allowNames rest parameter to work properly with isNameAllowed() private method.

Parameters:

Name: type Description
allowNames: AllowedNames[] A rest parameter of string type allowed names under which callback functions can be stored. Only those names given by this parameter are being checked by the isNameAllowed() private method.

Returns:

The return value is new instance of a Callback.

Usage:

// Example usage.
import { Callback } from '@angular-package/callback';

// Initialize `Callback`.
const callback = new Callback('set', 'define');

Callback instance methods

Callback.prototype.getForEachCallback()

new

Gets from the storage specified by-name callback function of ForEachCallback type.

public getForEachCallback<
  Value = any,
  Payload extends object = object,
  Name extends AllowNames = AllowNames
>(name: Name, capturePayload?: Payload): ForEachCallback<Value, Payload> {
  return this.#storage.get(name);
}

Generic type variables:

Name Default value Description
Value any A generic type variable Value by default equal to any determines the type of the value parameter of returned ForEachCallback function.
Payload object The shape of the optional payload parameter of returned ForEachCallback function, constrained by the object type. Its value can be captured from a type of the provided capturePayload optional parameter.
Name AllowNames A generic type variable Name constrained by generic type variable AllowNames, captured from the supplied name indicates the name under which callback function is picked from the storage.

Parameters:

Name: type Description
name: Name The name of a generic type variable Name to get stored callback function.
capturePayload?: Payload An optional object of generic type variable Payload that is used only to capture the value by the generic type variable Payload.

Returns:

Returns Type Description
ForEachCallback<Value, Payload> function The return type is ForEachCallback function.

The return value is the callback function of the ForEachCallback type from the storage.

Usage:

// Example usage.
import { Callback } from '@angular-package/callback';

// Initialize `Callback`.
const callback = new Callback('firstName');

// Define the default `payload`.
const defaultPersonPayload = { database: 'person', field: 'firstName' };

// Set the callback function of the `ResultCallback` type under the given name.
callback.setForEachCallback(
  'firstName',
  (result) => result,
  defaultPersonPayload
);

// Usage.
callback.getForEachCallback<string, typeof defaultPersonPayload>('firstName')(
  false,
  'my name',
  1,
  []
);

// Get the function of the `ForEachCallback` type stored under the given name.
const personCallback = callback.getForEachCallback<
  string,
  typeof defaultPersonPayload
>('firstName');

// Usage.
personCallback(false, 'my name', 1, []);
// Example usage in the `class`.
class Person {
  #callback!: Callback<'check'>;

  #persons: Array<{ checked: boolean; name: string }> = [
    { checked: false, name: 'Someone' },
    { checked: false, name: undefined as any },
    { checked: true, name: 'Someone' },
  ];

  constructor(handleCallback: Callback<'check'>) {
    if (handleCallback) {
      this.#callback = handleCallback;
    }
  }

  public check(
    callbackFn: ForEachCallback = this.#callback.getForEachCallback('check')
  ): this {
    are
      .true(...this.#persons.map((v) => v.checked))
      .forEach(callbackFn, this.#persons);
    return this;
  }
}

// Initialize default callbacks.
const defaultCallbacks = new Callback('check').setForEachCallback<boolean, any>(
  'check',
  (result, value, index, array, persons) => {
    if (result === true) {
      console.log(index, result, persons[index]);
    } else {
      persons[index].checked = true;
    }
  }
);

// Inject `defaultCallbacks` into the `Person` and set `checked` to `true` if `false`.
new Person(defaultCallbacks).check();

Callback.prototype.getResultCallback()

new

Gets from the storage specified by-name callback function of ResultCallback type.

public getResultCallback<
  Value = any,
  Payload extends object = object,
  Name extends AllowNames = AllowNames
>(name: Name, capturePayload?: Payload): ResultCallback<Value, Payload> {
  return this.#storage.get(name);
}

Generic type variables:

Name Default value Description
Value any A generic type variable Value by default equal to any determines the type of the value parameter of returned ResultCallback function.
Payload object The shape of the optional payload parameter of returned ResultCallback function, constrained by the object type. Its value can be captured from a type of the provided capturePayload optional parameter.
Name AllowNames A generic type variable Name constrained by generic type variable AllowNames, captured from the supplied name indicates the name under which callback function is picked from the storage.

Parameters:

Name: type Description
name: Name The name of a generic type variable Name to get the stored callback function.
capturePayload?: Payload An optional object of generic type variable Payload that is used only to capture the value by the generic type variable Payload.

Returns:

Returns Type Description
ResultCallback<Value, Payload> function The return type is ResultCallback function.

The return value is the callback function of the ResultCallback type from the storage.

Usage:

// Example usage.
import { Callback } from '@angular-package/callback';

// Initialize `Callback`.
const callback = new Callback('firstName');

callback
  // Set the callback function of the `ResultCallback` type under the 'firstName' name.
  .setResultCallback('firstName', result => result)
  // Get the function of the `ResultCallback` type stored under the 'firstName' name.
  .getResultCallback('firstName');
// Generic type variable payload example usage.
import { Callback } from '@angular-package/callback';

// Initialize `Callback`.
const callbackInstance = new Callback('firstName');

// Define type for the `Payload`.
type CustomPayload = { id: number; name: string };

// Set the callback function of `ResultCallback` under the 'firstName' name.
callbackInstance.setResultCallback<any, CustomPayload>(
  'firstName',
  (result, value, payload) => {
    result //
    value // 
    if (payload) {
      // It handles two properties from the payload.
      // payload.id
      // payload.name
    }
  }
);

// Get the function of the `ResultCallback` type stored under the 'firstName' name with the `CustomPayload` type.
const firstNameCallback = callbackInstance.getResultCallback<
  any,
  CustomPayload
>('firstName');

// Use the defined callback function with a defined `CustomPayload`.
firstNameCallback(false, 5, { id: 5, name: 'there is no name', age: 1 }); // TypeError because of the `age`

Callback.prototype.setErrorCallback

update

Sets callback function of ResultCallback type that throws ValidationError with a specified message on a state from the provided throwOnState to the storage under the given allowed name.

public setErrorCallback<
  Value = any,
  Payload extends object = object,
  Name extends AllowNames = AllowNames,
>(
  name: Name,
  message: string | ErrorMessage,
  throwOnState: boolean = false,
  resultHandler?: ResultHandler<Value, Payload>,
  defaultPayload?: Payload
): this {
  if (this.isNameAllowed(name)) {
    this.#storage.set(
      name,
      Callback.defineErrorCallback(message, throwOnState, resultHandler, defaultPayload)
    );
  }
  return this;
}

Generic type variables:

Name Default value Description
Value any A generic type variable Value by default equal to any determines the type of the value parameter of ResultHandler function from optional supplied resultHandler parameter.
Payload object The shape of the optional payload parameter of ResultHandler function from optional supplied resultHandler parameter, constrained by the object type. Its value can be captured from a type of the provided defaultPayload optional parameter.
Name AllowNames A generic type variable Name constrained by generic type variable AllowNames, captured from supplied name indicates the name under which callback function is stored.

Parameters:

Name: type Description
name: Name The name of a generic type variable Name under which callback function is stored. The allowed status of the provided name is checked by the private method isNameAllowed().
message: string | ErrorMessage The message of string type or ErrorMessage interface, to throw with an error of ValidationError.
throwOnState: boolean A state of boolean type on which an error of ValidationError should be thrown. By default, it's set to false.
resultHandler?: ResultHandler<Value, Payload> An optional function of ResultHandler type to inject into returned callback function of ResultCallback type in order to execute it before the thrown error.
defaultPayload?: Payload An optional object of generic type variable Payload as the default value of payload parameter of returned ResultCallback function and ResultHandler function from the supplied resultHandler parameter.

Returns:

Returns Type Description
this object The return type is an instance of Callback.

The return value is an instance of Callback.

Usage:

// Example usage.
import { Callback } from '@angular-package/callback';

// Initialize `Callback`.
const callback = new Callback('firstName', 'lastName');

// Set the error callback function of the `ResultCallback` type under the 'lastName' name.
callback.setErrorCallback('lastName', 'LastName must be a string type', false);
// Example usage.
import { Callback } from '@angular-package/callback';

// Initialize `Callback`.
const callback = new Callback('firstName', 'lastName');

// Set the error callback function of the `ResultCallback` type under the 'lastName' name.
callback.setErrorCallback(
  'lastName',
  'LastName must be a string type',
  false,
  (result, value, payload) => {
    payload?.field // Returns 'lastName'
    payload // Returns {moreField: true, field: 'lastName'}
  },
  { field: 'lastName' }
);

// Execute stored callback function.
callback.getResultCallback('lastName')(true, 'my name', { moreField: true });

Callback.prototype.setForEachCallback

new

Sets callback function of ForEachCallback type to the storage under the given allowed name.

public setForEachCallback<
  Value = any,
  Payload extends object = object,
  Name extends AllowNames = AllowNames
>(
  name: Name,
  forEachCallback: ForEachCallback<Value, Payload>,
  defaultPayload?: Payload
): this {
  if (this.isNameAllowed(name)) {
    this.#storage.set(
      name,
      Callback.defineForEachCallback(forEachCallback, defaultPayload)
    );
  }
  return this;
}

Generic type variables:

Name Default value Description
Value any A generic type variable Value by default equal to any determines the type of the value parameter of supplied forEachCallback function.
Payload object The shape of the optional payload parameter of supplied forEachCallback function, constrained by the object type. Its value can be captured from a type of the provided defaultPayload optional parameter.
Name AllowNames A generic type variable Name constrained by generic type variable AllowNames, captured from supplied name indicates the name under which callback function is stored.

Parameters:

Name: type Description
name: Name The name of a generic type variable Name under which callback function is stored. The allowed status of the provided name is checked by the private method isNameAllowed().
forEachCallback: ForEachCallback<Value, Payload> The callback function of ForEachCallback type to set under the given name.
defaultPayload?: Payload An optional object of generic type variable Payload as the default value of payload parameter of supplied forEachCallback function.

Returns:

Returns Type Description
this object The return type is an instance of Callback.

The return value is an instance of Callback.

Usage:

// Example usage.
import { Callback } from '@angular-package/callback';
import { are } from '@angular-package/type';

// Define database with addresses.
const database = [
  { city: 'New York', postCode: 1 },
  { city: 'Warsaw', postCode: 2 },
  { city: 'London', postCode: 3 },
  { city: undefined, postCode: 4 },
  { city: null, postCode: 6 },
  { city: 'San Francisco', postCode: 5 },
];

// Define callback for `are` checking functions.
const checkAddress = new Callback('city');

// Set callback function for checking the city against the string type.
checkAddress.setForEachCallback(
  'city',
  (result, value, index, array, addresses) =>
    result === false ? console.log(value) : console.log(value),
  database
);

// Execute the check.
are
  .string(...database.map((v) => v.city))
  .forEach(checkAddress.getForEachCallback('city'), database);

Callback.prototype.setResultCallback()

update

Sets callback function of ResultCallback type to the storage under the given allowed name.

public setResultCallback<
  Value = any,
  Payload extends object = object,
  Name extends AllowNames = AllowNames
>(
  name: Name,
  resultHandler: ResultHandler<Value, Payload>,
  defaultPayload?: Payload
): this {
  if (this.isNameAllowed(name)) {
    this.#storage.set(
      name,
      Callback.defineResultCallback(resultHandler, defaultPayload)
    );
  }
  return this;
}

Generic type variables:

Name Default value Description
Value any A generic type variable Value by default equal to any determines the type of the value parameter of supplied resultHandler function.
Payload object The shape of the optional payload parameter of supplied resultHandler function, constrained by the object type. Its value can be captured from a type of the provided capturePayload optional parameter.
Name AllowNames A generic type variable Name constrained by generic type variable AllowNames, captured from supplied name indicates the name under which callback function is stored.

Parameters:

Name: type Description
name: Name The name of a generic type variable Name under which callback function is stored. The allowed status of the provided name is checked by the private method isNameAllowed().
resultHandler: ResultHandler<Value, Payload> The function of the ResultHandler type to handle the result, value, and optional payload of the ResultCallback function without returning the result.
defaultPayload?: Payload An optional object of generic type variable Payload as the default value of payload parameter of supplied resultHandler function.

Returns:

Returns Type Description
this object The return type is an instance of Callback.

The return value is an instance of Callback.

Usage:

// Example usage.
import { Callback } from '@angular-package/callback';

// Initialize `Callback`.
const callback = new Callback('firstName');

// Set the callback function under the given name.
callback.setResultCallback('firstName', result => result);
// Generic type variable `Value` and `Payload` example usage.
import { Callback } from '@angular-package/callback';

// Initialize `Callback`.
const callback = new Callback('firstName');

// Type for the `Payload`.
type CustomPayload = { id: number; name: string };

// Set the callback function under the given name.
callback.setResultCallback<string, CustomPayload>(
  'firstName',
  (result, value, payload) => {
    result // boolean type
    value // string type
    if (payload) {
      // It handles two properties from the payload.
      // payload.id
      // payload.name
    }
  }
);
// Captured `Payload` example usage.
import { Callback } from '@angular-package/callback';

// Initialize `Callback`.
const callback = new Callback('firstName');

// Constant from which is going to be captured type for the `Payload`.
const payLoadToCapture = { id: 1, name: '' };

// Set the callback function under the given name.
callback.setResultCallback(
  'firstName',
  (result, value, payload) => {
    if (payload) {
      // It handles two properties from the payload.
      // payload.id
      // payload.name
    }
  },
  payLoadToCapture
);

Type

ResultHandler

update

Internal function to handle the arguments of the ResultCallback function before its result return.

type ResultHandler<Value = any, Payload extends object = object> = (
  result: boolean,
  value: Value,
  payload?: Payload
) => void;

Changelog

The changelog of this package is based on keep a changelog. To read it, click on the CHANGELOG.md link.

A changelog is a file which contains a curated, chronologically ordered list of notable changes for each version of a project. - keep a changelog


GIT

Commit

Versioning

Semantic Versioning 2.0.0

Given a version number MAJOR.MINOR.PATCH, increment the:

  • MAJOR version when you make incompatible API changes,
  • MINOR version when you add functionality in a backwards-compatible manner, and
  • PATCH version when you make backwards-compatible bug fixes.

Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format.

FAQ How should I deal with revisions in the 0.y.z initial development phase?

The simplest thing to do is start your initial development release at 0.1.0 and then increment the minor version for each subsequent release.

How do I know when to release 1.0.0?

If your software is being used in production, it should probably already be 1.0.0. If you have a stable API on which users have come to depend, you should be 1.0.0. If you’re worrying a lot about backwards compatibility, you should probably already be 1.0.0.

License

MIT © angular-package (license)

About

Manage the callback function.

Resources

License

Stars

Watchers

Forks

Sponsor this project

  •  

Packages

No packages published

Contributors 2

  •  
  •