Skip to content

nyteshade/ne-foundation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@nejs/basic-extensions

Overview

@nejs/basic-extensions is a JavaScript library that provides a collection of essential extensions to built-in JavaScript objects like Array, Object, Function, and Reflect. These extensions are designed to enhance the native capabilities of JavaScript objects, providing developers with additional utility methods for common tasks and improving code readability and efficiency.

Features

  • Array Extensions: Adds convenience methods to JavaScript arrays, like first and last, for easy access to the first and last elements.

  • Object Extensions: Introduces utility functions to the Object class, such as methods for checking object types and manipulating properties.

  • Function Extensions: Enriches the Function class with methods to identify function types, such as arrow functions, async functions, and bound functions.

  • Reflect Extensions: Extends the Reflect object with advanced property interaction methods, including checks for the presence of multiple or specific keys.

Installation

Install @nejs/basic-extensions using npm:

npm install @nejs/basic-extensions

Or using yarn:

yarn add @nejs/basic-extensions

Usage

Import the desired extensions in your JavaScript project:

import { ArrayPrototypeExtensions } from '@nejs/basic-extensions';
// Use the Array extensions
import { FunctionExtensions } from '@nejs/basic-extensions';
// Use the Function extensions

API

Table of Contents

Deferred

Extends Promise

Deferreds, which were first introduced by jQuery for browsers in the early 2000s, are a way to manage asynchronous operations. They have been widely used and replicated by engineers since then. Although the Promise class in modern JavaScript provides a static method called withResolvers that returns an object with similar properties to a Deferred, it is not directly supported by Node.js.

const withResolvers = Promise.withResolvers()
Reflect.has(withResolvers, 'promise') // true
Reflect.has(withResolvers, 'resolve') // true
Reflect.has(withResolvers, 'reject')  // true

This Deferred class extends the Promise class, allowing it to capture the value or reason for easy access after resolution, akin to Promise.withResolvers. As it extends Promise, it is 'thenable' and works with await as if it were a native Promise. This allows seamless integration with code expecting Promise-like objects.

Parameters

  • options object see above for examples on supported options, but when supplied, the constructor can take instructions on how to auto resolve or reject the deferred created here.

value

When the Deferred is settled with Deferred.resolve, the value passed to that function will be set here as well.

Type: any

reason

When the Deferred is settled with Deferred.reject, the reason passed to that rejection will also be stored here.

Type: any

settled

Returns a boolean value that indicates whether or not this Deferred has been settled (either resolve or reject have been invoked).

Returns boolean true if either Deferred.resolve or Deferred.reject have been invoked; false otherwise

promise

Accessor for the promise managed by this Deferred instance.

This getter provides access to the internal promise which is controlled by the Deferred's resolve and reject methods. It allows external code to attach callbacks for the resolution or rejection of the Deferred without the ability to directly resolve or reject it.

Returns Promise The promise controlled by this Deferred instance.

resolve

Resolves the Deferred with the given value. If the value is a thenable (i.e., has a "then" method), the Deferred will "follow" that thenable, adopting its eventual state; otherwise, the Deferred will be fulfilled with the value. This function behaves the same as Promise.resolve.

Parameters
  • value any The value to resolve the Deferred with.

Returns Promise A Promise that is resolved with the given value.

reject

Rejects the Deferred with the given reason. This function behaves the same as Promise.reject. The Deferred will be rejected with the provided reason.

Parameters
  • reason any The reason to reject the Deferred with.

Returns Promise A Promise that is rejected with the given reason.

species

A getter for the species symbol which returns a custom DeferredPromise class. This class extends from Deferred and is used to ensure that the constructor signature matches that of a Promise. The executor function passed to the constructor of this class is used to initialize the Deferred object with resolve and reject functions, similar to how a Promise would be initialized.

Returns DeferredPromise A DeferredPromise class that extends Deferred.

promise

The promise backing this deferred object. Created when the constructor runs, this promise is what all Promise.prototype functions are routed to.

Type: Promise

reject

The reject() resolver that will be assigned when a new instance is created. Invoking this function with or without a reason will cause the deferred's promise to be settled.

Type: function

resolve

The resolve() resolver that will be assigned when a new instance is created. Invoking this function with or without a value will cause the deferred's promise to be settled.

Type: function

settled

When either Deferred.resolve or Deferred.reject are called, this property is set to true. Its current status at any time can be queried using the Deferred.settled getter.

Type: boolean

secret

Sets the secret key used for signing and verifying JWT tokens. This method allows for updating the secret key at runtime. The new secret should be a string that is kept secure and not exposed to unauthorized entities. It is critical to ensure that the secret key is valid and kept confidential to maintain the integrity and security of the tokens being processed.

Parameters

  • value (string | function) The new secret key to be used for JWT operations.

secretSet

Getter for the private static member #secretSet. This property indicates whether the JWT secret has been set for the JWTExtension class. It is primarily used to check if the secret key is available before performing JWT operations. This getter ensures encapsulation by preventing direct access to the private static member.

Returns boolean True if the secret is set, false otherwise.

init

Initializes the JWTExtension with a given secret key. This method is used to set the secret key for JWT operations at the start of the application. The secret key is essential for the encoding and decoding of the tokens, ensuring their integrity and security. The method returns the class itself, allowing for method chaining.

Parameters

  • secret string The secret key used for signing and verifying JWT tokens. It should be a string that is kept secure and not exposed to unauthorized entities.

Returns JWTExtension The JWTExtension class for method chaining.

sign

Signs a payload to create a JSON Web Token (JWT). This method can be used synchronously or asynchronously, depending on whether a callback is provided. If a callback is provided, the method returns a promise and the callback is called with the error or the signed token. If no callback is provided, the token is signed synchronously and returned.

Before signing, the method checks if the secret key has been set. If not, it throws an error to prevent the creation of an unsigned token.

Parameters

  • payload (Object | string) The data to be signed into the token.
  • durationOrOptions (Object | string | number)? Either the duration for which the token is valid, or an options object. If an object is provided, it should conform to the options that the underlying jsonwebtoken library accepts.
  • callback Function? Optional callback for Node.js style asynchronous operation. Called with an error or the signed token.
  • Throws Error If the secret key has not been set before calling this method.

Returns (Promise | string) If a callback is provided, a promise is returned that resolves with the signed token or rejects with an error. If no callback is provided, the signed token is returned synchronously.

decode

Decodes or verifies a JSON Web Token (JWT) using a secret key. This method can operate synchronously or asynchronously, depending on whether a callback function is provided. If a callback is provided or true is passed, the method returns a promise and the callback is called with the error or the decoded token. If no callback is provided, the token is verified synchronously and the decoded token is returned.

Parameters

  • token string The JWT to decode or verify.
  • options Object? Optional settings for token verification, such as secret to override the default, algorithms to specify the expected signing algorithm, issuer to check the issuer, audience to check the audience, and others. If decode is set to true in options and raw is true, the token is decoded without verification.
  • callback (Function | boolean)? Optional callback for Node.js style asynchronous operation, or true to return a promise without using a callback. Called with an error or the decoded token.
  • Throws Error If the secret key has not been set before calling this method.

Returns (Promise | Object | string) If a callback is provided or true is passed, a promise is returned that resolves with the decoded token or rejects with an error. If no callback is provided, the decoded token is returned synchronously.

Range

Represents a numerical range with a start, end, and step value. The range can be inclusive or exclusive of the end value. It can be iterated over and can check if a value is included within the range. The start, end, and step can be static values or functions that return the respective values. The step value must be non-zero. The range can be used in for...of loops and other iterable contexts.

Parameters

  • start (object | number) An object containing all properties, or the starting value of the range. If an object is provided, other parameters are ignored.
  • end number? The ending value of the range. Required if start is a number.
  • step (number | function) The step value between each value in the range, or a function that returns the step value. Must be a non-zero number or function returning a non-zero number. (optional, default 1)
  • inclusive boolean Determines whether the range includes the end value. (optional, default true)

Examples

// Create an inclusive range from 1 to 5 with a step of 1
const range = new Range(1, 5);
for (const value of range) {
  console.log(value); // Logs 1, 2, 3, 4, 5
}
// Create an exclusive range from 10 to 20 with a step of 2
const exclusiveRange = new Range({
  start: 10, end: 20, step: 2, inclusive: false
});
for (const value of exclusiveRange) {
  console.log(value); // Logs 10, 12, 14, 16, 18
}

inclusive

Determines whether the range includes the end value. When set to true, the range will include the end value in its set of values. When set to false, the end value is not included. This property is true by default, meaning ranges are inclusive of the end value unless explicitly set otherwise.

Type: boolean

start

Retrieves the starting value of the range. If the starting value is a function, it invokes the function and returns its result. Otherwise, it returns the starting value directly.

Returns number The starting value of the range or the result of the starting value function.

start

Sets the starting value of the range. This value can be a number or a function that returns a number. If a function is provided, it will be invoked to determine the starting value each time the start property is accessed.

Parameters
  • value (number | function) The new starting value or a function that returns the starting value.

end

Retrieves the ending value of the range. If the ending value is a function, it invokes the function and returns its result. Otherwise, it returns the ending value directly.

Returns number The ending value of the range or the result of the ending value function.

end

Sets the ending value of the range. This value can be a number or a function that returns a number. If a function is provided, it will be invoked to determine the ending value each time the end property is accessed.

Parameters
  • value (number | function) The new ending value or a function that returns the ending value.

step

Retrieves the step value of the range. If the step value is a function, it invokes the function and returns its result. Otherwise, it returns the step value directly. This value determines the increment between each number in the range.

Returns number The step value of the range or the result of the step value function.

step

Sets the step value of the range. The step value determines the increment between each number in the range. It can be a non-zero number or a function that returns a non-zero number. If the provided value is zero, not a number, or a function that returns zero or not a number, an error is thrown.

Parameters
  • value (number | function) The new step value or a function that returns the step value. Must not be zero or return zero.
  • Throws Error If the value is zero, not a number, or a function that returns zero or not a number.

size

Retrieves the size of the range, which is the number of steps from the start value to the end value. If the end value is undefined, it returns the number of steps from the start value to zero. The size is always rounded down to the nearest whole number when the end value is defined, and rounded to the nearest whole number in general when the end value is undefined.

Returns number The size of the range, representing the count of discrete steps within the range.

each

Iterates over the range, executing a callback for each value in the range. The iteration order is from the start value to the end value, inclusive or exclusive based on the 'inclusive' property. If 'inclusive' is true, the end value is included in the iteration; otherwise, it is excluded. The iteration step is determined by the 'step' property. If the start value is less than the end value, the iteration is in ascending order; if the start value is greater than the end value, the iteration is in descending order.

Parameters
  • callback Function The function to execute for each value in the range. It receives the current value as an argument.

includes

Determines whether a given value is included in the range. If the range's end value is not a number (NaN), it checks if the start value is equal to the given value. If the end value is a number, it checks if the given value is between the start and end values, and if the difference between the start value and the given value is an exact multiple of the step value. This method takes into account whether the range is inclusive of the end value.

Parameters
  • val number The value to check for inclusion in the range.

Returns boolean True if the value is included in the range, false otherwise.

iterator

Creates an iterator that yields each value in the range according to the start, end, and step properties. The iterator can be used in for...of loops and other constructs that consume iterables. If the range is inclusive, the end value is yielded; otherwise, it is not. The iteration respects the direction of the range, ascending or descending, based on the start and end values.

Singleton

The Singleton class is a design pattern that ensures only one instance of a class is created and provides a way to access that instance.

__instanceMap

Static map of all instances of the Singleton. Any class that extends Singleton and has its shared property retrieved will be stored here with the class as the key and the single shared instance as the value.

shared

The function returns a shared instance of a class, creating a new instance if one does not already exist.

Returns any The shared instance of the Singleton class.

species

The above function returns the constructor function of the current object. This is crucial to allow other classes that are to extend from Singleton to have their

Returns any The this keyword is being returned.

trimLeading

Creates a template function for processing string literals with embedded expressions. This function can optionally trim leading whitespace from each line of the string based on the indentation of the first non-empty line.

Parameters

  • applyIndent (optional, default 0)
  • metadata (optional, default undefined)
  • trimLeading boolean When true, trims the leading whitespace from each line of the string to match the indentation of the first non-empty line. When false, it leaves the string as-is. (optional, default true)

Examples

// Usage with template literal:
const trim = trimLeading();
const result = trim`
  Line 1
  Line 2
  Line 3
`;
// result is "Line 1\n Line 2\nLine 3"

Returns Function A template function that takes a template literal and its embedded expressions as arguments. The function processes the template literal, optionally trims leading whitespace, and returns the resulting string.

Hasher

A simple Hasher implementation in JavaScript. This mimics the behavior of Swift's Hasher to some extent. It uses the djb2 algorithm for hashing.

Parameters

  • values ...any The "values" parameter is a rest parameter that allows you to pass in multiple arguments to the constructor. It can accept any number of arguments, and each argument can be of any type. The arguments are passed as an array-like object called "arguments" within the constructor function.

add

Adds the given value into the hasher.

Parameters
  • values ...any
  • value (number | string) The value to hash. If the value is not a number nor a string, then it will be converted into a string

hash

The function returns the absolute value of a hash code as a base-36 string.

Returns any The method is returning the absolute value of the private property hash converted to a base-36 string.

reset

The function "reset" sets the value of the private property "hash" to 5381.

seed

The above function returns the value of the private variable "seed".

Returns any The seed value of the object.

seed

The above function sets the value of the seed property.

Parameters
  • newValue newValue is the new value that will be assigned to the seed property.

toKeys

The function "toKeys" converts the keys of an object into an array of strings.

Parameters
  • object The object parameter is the object for which we want to get the keys.

Returns any an array of strings that represent the keys of the input object.

hasSymbols

The function "hasSymbols" checks if an array contains any symbols and returns true if it does, false otherwise.

Parameters
  • array The parameter "array" is expected to be an array.

Returns any a boolean value. It returns true if the input array contains at least one symbol, and false otherwise.

SemVer

Represents a semantic version (semver) and provides utility methods for managing and comparing versions according to the semver specification.

Parameters

  • semverString string The initial semantic version string. (optional, default "0.0.0")
  • part string by default this is set to * which indicates that the entire semverString is to be parsed. If the part is the name of a property matching one of [major, minor, patch, prerelease or metadata] then only that portion of the version is set. For major, minor and patch, the value will be parsed into an integer. If an unknown key is specified, the entire string will be processed. (optional, default "*")

set

Sets the version based on a semver string. This method parses the string and updates the major, minor, patch, prerelease, and metadata parts of the version accordingly.

Parameters
  • semverString string The semver string to parse and set.
  • part (optional, default '*')
  • Throws Error If semverString is not a string or not in valid semver format.

get

Retrieves the full version string in semver format. Constructs the version string including the major, minor, patch versions, and optionally the prerelease and metadata parts if they are present.

Returns string The full version string in semver format.

increment

Increments part of the SemVer instance by the indicated amount.

Parameters
  • version string the portion of the version to increment. Valid values are major, minor or patch.
  • by number the amount by which the version is incremented. This defaults to 1. (optional, default 1)

Returns SemVer the this instance for further chaining

decrement

Decrements part of the SemVer instance by the indicated amount.

Parameters
  • version string the portion of the version to decrement. Valid values are major, minor or patch.
  • by number the amount by which the version is decremented. This defaults to 1. (optional, default 1)

Returns SemVer the this instance for further chaining

toPrimitive

Converts the version to a primitive value based on the context. When converting to a number, only the major and minor parts are considered. When converting to a string, the full semver string is returned.

Parameters
  • hint string The context in which conversion is requested ("number" or "string").

Returns (string | number | null) The converted value.

isEqual

Determines if this version is exactly equal to another version. This comparison includes the major, minor, patch, prerelease, and metadata parts of the version. It's a strict comparison where all parts must match.

Parameters
  • otherVersion SemVer The other SemVer instance to compare with.

Returns boolean True if all version components are exactly equal.

isLooselyEqual

Checks if this version is equal to another version based only on the major, minor, and patch numbers. This method ignores the prerelease and metadata parts of the version, making it a "loose" or "lenient" comparison. It is useful for determining compatibility or disregarding build and pre-release details.

Parameters
  • otherVersion SemVer The other SemVer instance to compare with.

Returns boolean True if major, minor, and patch numbers are equal.

isSemverEqual

Compares this version to another version according to semver equality rules. In semver, two versions are considered equal if they have the same major, minor, and patch numbers. This method also considers prerelease tags but ignores build metadata. For example, "1.0.0-alpha" and "1.0.0-alpha+build" are considered equal.

Parameters
  • otherVersion SemVer The other SemVer instance to compare with.

Returns boolean True if versions are considered equal in semver terms.

toStringTag

Provides a custom tag when the object is converted to a string. This method overrides the default behavior to return the class name instead of the generic "Object" tag.

Returns string The class name "SemVer".

major

The primary version number for this SemVer instance. This version of the instance, when bumped, indicates likely breaking changes or at least a semmantic separation from previous major revisions

Type: number

minor

The minor version number for this SemVer instance. This version of the instance, when bumped, usually indicates that new features are present. It is expected, however, that minor bump versions are backwards compatible.

Type: number

patch

The patch version number for this SemVer instance. This version of the instance, when bumped, usually indicates that some fix has been applied but that there are no new features or breaking changes. These should usually be taken greedily.

prerelease

This is prerelease string indicator. Usually this has a value like "alpha" or "beta". A SemVer value with a prerelease indicator might look like "1.0.0-beta" indicating, in this example, that it is a beta release for 1.0.0.

Type: string

metadata

The metadata string portion of a SemVer version is a note to the consumer but may not have any real bearing on changes. This is a human readable version. A metadata portion may show up in a SemVer string as "1.0.0-beta+001". In this case maybe providing an iteration value. It can be any string. It is only usually compared in version comparisons, in the strictest compares.

Type: string

FULL

The FULL constant can be passed as a second parameter, inspite of it being the default value, to the .set() method on SemVer instances. It indicates that the full SemVer string should be parsed and set.

Type: string

MAJOR

The MAJOR constant can be used as a parameter to set(), increment(), and decrement() methods. It points to the major semver version number.

Type: string

Examples
semver.increment(SemVer.MAJOR).get()

MINOR

The MINOR constant can be used as a parameter to set(), increment(), and decrement() methods. It points to the minor semver version number.

Type: string

Examples
semver.increment(SemVer.MINOR).get()

PATCH

The PATCH constant can be used as a parameter to set(), increment(), and decrement() methods. It points to the patch semver version number.

Type: string

Examples
semver.increment(SemVer.PATCH).get()

PRERELEASE

The PRERELEASE constant can be used as a parameter to set() method. It points to the pre-release semver version text.

Type: string

Examples
semver.set("beta", SemVer.PRERELEASE).get()

METADATA

The METADATA constant can be used as a parameter to set() method. It points to the metadata semver version text.

Type: string

Examples
semver.set("bries_release", SemVer.METADATA).get()

compare

Compares two semver strings for semver equality. This static method allows for a direct comparison without needing to create SemVer instances externally. It is useful for quick comparisons where instantiation of objects is not necessary.

Parameters
  • leftVersion string The first version string to compare.
  • rightVersion string The second version string to compare.

Returns boolean True if the versions are semver equal according to the isSemverEqual method.

Contributing

Contributions to @nejs/basic-extensions are always welcome. Please refer to our contributing guidelines for more information on how to report issues, submit pull requests, and more.

License

@nejs/basic-extensions is licensed under the MIT License. See the LICENSE file for more details.

About

A replacement for @nejs/core and culmination of @nejs/extension and @nejs/basic-extensions

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published