@nejs/basic-extensions
v2.20.0
Published
Basic but commonly used extensions
Downloads
13
Maintainers
Readme
@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
andlast
, 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
- ArrayExtensions
- ArrayPrototypeExtensions
- ifArray
- contains
- findEntry
- first
- last
- isArray
- ifArray
- oneIs
- someAre
- allAre
- BigIntExtensions
- BigIntPrototypeExtensions
- getClassProperties
- isAsync
- ifAsync
- isAsyncGenerator
- ifAsyncGenerator
- isBigArrow
- ifBigArrow
- isBound
- ifBound
- isClass
- ifClass
- isFunction
- ifFunction
- isGenerator
- ifGenerator
- StringTagHasInstance
- FunctionExtensions
- isAsync
- ifAsync
- isAsyncGenerator
- ifAsyncGenerator
- isBigArrow
- ifBigArrow
- isBound
- ifBound
- isClass
- ifClass
- isFunction
- ifFunction
- isGenerator
- ifGenerator
- getClassProperties
- isThenElse
- maskAs
- maskAsString
- maskAsNumber
- GenericMask
- StringMask
- NumberMask
- blendProtos
- extractFrom
- mightContain
- JSONStartPattern
- isMap
- ifMap
- isMap
- ifMap
- getKey
- isNumber
- areNumbers
- ifNumber
- ifNumbers
- clamp
- NumberExtensions
- instance
- isNumber
- ifNumber
- NumberPrototypeExtensions
- ObjectExtensions
- ObjectPrototypeExtensions
- copy
- deepCopy
- definitionType
- define
- defineAccessor
- fromEntriesUsing
- getPrototypeChainEntries
- getStringTag
- getType
- hasStringTag
- isNullDefined
- ifNullDefined
- isObject
- isPrimitive
- ifPrimitive
- isValidKey
- ifValidKey
- kDescriptorStore
- prekeyed
- stripTo
- getPrototypeChainEntries
- hasStringTag
- getStringTag
- stripTo
- isObject
- ifObject
- isNullDefined
- ifNullDefined
- isPrimitive
- ifPrimitive
- isValidKey
- ifValidKey
- copyObject
- ReflectExtensions
- owner
- key
- value
- descriptor
- isReadOnly
- isAssignable
- isAccessor
- isData
- anything
- nonCaptureGroup
- captureGroup
- oneOf
- zeroOrMore
- zeroOrOne
- escape
- null
- bool
- currencySymbols
- number
- integer
- float
- integer
- pretty
- jsLiteral
- SetExtensions
- SetPrototypeExtensions
- isSet
- ifSet
- concat
- contains
- every
- find
- findLast
- isSet
- ifSet
- length
- map
- reduce
- some
- StringExtensions
- isString
- ifString
- instance
- extractSubstring
- StringPrototypeExtensions
- SymbolExtensions
- instance
- data
- data
- mightHaveEmbeddedJSON
- for
- Deferred
- promise
- reject
- resolve
- settled
- object
- constructor
- isAccessor
- isData
- isDescriptor
- configurable
- configurable
- enumerable
- enumerable
- writable
- writable
- value
- value
- get
- get
- boundGet
- set
- set
- boundSet
- hasObject
- object
- object
- for
- applyTo
- toObject
- toPrimitive
- toStringTag
- for
- getData
- getAccessor
- base
- accessor
- data
- isDescriptor
- isData
- isAccessor
- flexible
- enigmatic
- intrinsic
- transparent
- SHARED_KEYS
- ACCESSOR_KEYS
- DATA_KEYS
- Iterable
- Iterator
- mapEach
- constructor
- parse
- validate
- tryParsers
- safeTryParsers
- NoValidParsersFound
- ParametersMustBeArrayError
- ParsersArrayMustContainParsersError
- toStringTag
- hasInstance
- response
- ResponseType
- nameFromType
- typeNames
- type
- apply
- construct
- defineProperty
- deleteProperty
- get
- getOwnPropertyDescriptor
- getPrototypeOf
- has
- isExtensible
- ownKeys
- preventExtensions
- set
- setPrototypeOf
- RefMap
- isValidReference
- RefSet
- Symkeys
- AsyncIterable
- AsyncIterator
ArrayExtensions
ArrayExtensions
is a constant that applies a patch to the global
Array
constructor. This patch extends the Array
with additional
methods and properties, enhancing its functionality.
The Patch
function takes two arguments: the target object to be patched
(in this case, Array
), and an object containing the methods and
properties to be added to the target object.
Type: Patch
Examples
// Using a method added by ArrayExtensions
const arr = [1, 2, 3];
console.log(Array.ifArray(arr, 'Array', 'Not Array')); // Output: 'Array'
ArrayPrototypeExtensions
ArrayPrototypeExtensions
is a constant that applies a patch to the
Array prototype. This patch extends the Array prototype with additional
methods and properties, enhancing its functionality.
The Patch
function takes two arguments: the target object to be patched
(in this case, Array.prototype
), and an object containing the methods
and properties to be added to the target object.
Type: Patch
Examples
// Using a method added by ArrayPrototypeExtensions
const arr = [1, 2, 3];
console.log(arr.ifArray('Array', 'Not Array')); // Output: 'Array'
ifArray
Checks if the provided value is an array and returns one of two provided values based on the result. This function is a convenience method for performing conditional operations based on the type of the provided value.
Type: function
Parameters
value
any The value to be checked.thenValue
(function | any) The value to be returned if the provided value is an array.elseValue
(function | any) The value to be returned if the provided value is not an array.
Examples
const arr = [1, 2, 3];
console.log(ArrayExtensions.ifArray(arr, 'Array', 'Not Array'));
// Output: 'Array'
const notArr = "I'm not an array";
console.log(ArrayExtensions.ifArray(notArr, 'Array', 'Not Array'));
// Output: 'Not Array'
Returns any Returns thenValue
if the provided value is an array,
otherwise returns elseValue
.
contains
Sometimes defining even a short function for the invocation of find
can be troublesome. This helper function performs that job for you. If
the specified element is in the array, true
will be returned.
Parameters
value
any the value to search for. This value must triple equals the array element in order to return true.
Returns any true if the exact element exists in the array, false otherwise
findEntry
The findEntry
function searches the entries of the object and returns
the [index, value]
entry array for the first matching value found.
Parameters
findFn
function a function that takes the element to be checked and returns a boolean value
Returns any if findFn
returns true
, an array with two elements, the first
being the index, the second being the value, is returned.
first
A getter property that returns the first element of the array. If the
array is empty, it returns undefined
. This property is useful for
scenarios where you need to quickly access the first item of an array
without the need for additional checks or method calls.
Returns any The first element of the array or undefined
if the array
is empty.
last
A getter property that returns the last element of the array. It
calculates the last index based on the array's length. If the array is
empty, it returns undefined
. This property is beneficial when you need
to access the last item in an array, improving code readability and
avoiding manual index calculation.
Returns any The last element of the array or undefined
if the
array is empty.
isArray
A getter property that checks if the current context (this
) is an
array. This is a convenience method that wraps the native
Array.isArray
function.
Type: function
Examples
const arr = [1, 2, 3];
console.log(arr.isArray); // Output: true
const notArr = "I'm not an array";
console.log(notArr.isArray); // Output: false
Returns boolean true
if the current context is an array,
false
otherwise.
ifArray
Checks if the current context (this
) is an array and returns one of
two provided values based on the result. This function is a convenience
method for performing conditional operations based on the type of
the current context.
Type: function
Parameters
thenValue
(function | any) The value to be returned if the current context is an array.elseValue
(function | any) The value to be returned if the current context is not an array.
Examples
const arr = [1, 2, 3];
console.log(arr.ifArray('Array', 'Not Array')); // Output: 'Array'
const notArr = "I'm not an array";
console.log(notArr.ifArray('Array', 'Not Array')); // Output: 'Not Array'
Returns any Returns thenValue
if the current context is an array,
otherwise returns elseValue
.
oneIs
Checks if at least one element in the array is equal to the provided
value. This method uses the Array.prototype.some
function to iterate
over the array and compare each element with the provided value.
Type: function
Parameters
value
any The value to be compared with the array elements.doubleEqualsOkay
boolean A flag indicating whether to use loose equality (==
) or strict equality (===
) for the comparison. Iftrue
, loose equality is used. Iffalse
, strict equality is used. (optional, defaulttrue
)
Examples
const arr = [1, 2, 3];
console.log(arr.oneIs(2)); // Output: true
const arr2 = ['1', '2', '3'];
console.log(arr2.oneIs(2, false)); // Output: false
Returns boolean Returns true
if at least one element in the array
is equal to the provided value, otherwise false
.
someAre
Checks if some elements in the array are included in the provided values.
This method uses the Array.prototype.some
function to iterate over the
array and checks if any of the elements are included in the provided values.
Type: function
Parameters
values
...any The values to be checked against the array elements.
Examples
const arr = [1, 2, 3];
console.log(arr.someAre(2, 4)); // Output: true
const arr2 = ['1', '2', '3'];
console.log(arr2.someAre(4, 5)); // Output: false
Returns boolean Returns true
if at least one element in the array
is included in the provided values, otherwise false
.
allAre
Checks if all elements in the array are equal to the provided value.
This method uses the Array.prototype.every
function to iterate over
the array and compare each element with the provided value.
Type: function
Parameters
value
any The value to be compared with the array elements.doubleEqualsOkay
boolean A flag indicating whether to use loose equality (==
) or strict equality (===
) for the comparison. Iftrue
, loose equality is used. Iffalse
, strict equality is used. (optional, defaulttrue
)
Examples
const arr = [2, 2, 2];
console.log(arr.allAre(2)); // Output: true
const arr2 = ['2', '2', '2'];
console.log(arr2.allAre(2, false)); // Output: false
Returns boolean Returns true
if all elements in the array are equal
to the provided value, otherwise false
.
BigIntExtensions
BigIntExtensions
is a patch for the JavaScript built-in BigInt
class.
It adds utility methods to the BigInt
class without modifying the global
namespace directly. This patch includes methods for checking if a value is
a BigInt
and conditionally returning a value based on whether the supplied
value is a BigInt
or not.
Type: Patch
Examples
import { BigIntExtensions } from 'big.int.extension.js'
BigIntExtensions.apply()
// Now the `BigInt` class has additional methods available
isBigInt
Determines if the supplied value
is a BigInt
. This check is
performed by first checking the typeof
the value
and then
checking to see if the value
is an instanceof
BigInt
Parameters
value
any The value that needs to be checked to determine if it is aBigInt
or not
Examples
const bigInt = 1234567890123456789012345678901234567890n
isBigInt(bigInt) // true
isBigInt(1234567890123456789012345678901234567890) // false
isBigInt('1234567890123456789012345678901234567890') // false
isBigInt(BigInt('1234567890123456789012345678901234567890')) // true
Returns boolean true
if the supplied value
is a BigInt
,
false
otherwise
ifBigInt
Conditionally returns a value based on whether the supplied
value
is a BigInt
or not. If the value
is a BigInt
,
the thenValue
will be returned. If it is not a BigInt
,
the elseValue
will be returned instead.
Parameters
value
any The value to check to determine if it is aBigInt
thenValue
any The value to return if the suppliedvalue
is aBigInt
elseValue
any The value to return if the suppliedvalue
is not aBigInt
Examples
const bigInt = 1234567890123456789012345678901234567890n
const num = 42
ifBigInt(bigInt, 'is a BigInt', 'not a BigInt')
// 'is a BigInt'
ifBigInt(num, 'is a BigInt', 'not a BigInt')
// 'not a BigInt'
Returns any Either the thenValue
or elseValue
depending
on if the supplied value
is a BigInt
BigIntPrototypeExtensions
BigIntPrototypeExtensions
is a patch for the JavaScript built-in
BigInt.prototype
. It adds utility methods to the BigInt
prototype
without modifying the global namespace directly. This patch includes
methods for checking if a value is a BigInt and conditionally returning
a value based on whether the supplied value is a BigInt or not.
Type: Patch
Examples
import { BigIntPrototypeExtensions } from 'big.int.extension.js'
BigIntPrototypeExtensions.apply()
// Now the `BigInt` prototype has additional methods available
instance
A getter method that returns an object representation of the BigInt instance.
This method wraps the BigInt instance in an object, allowing it to be
treated as an object. The returned object is created using the Object()
constructor, which takes the BigInt instance as its argument.
Type: Object
Examples
const bigInt = 1234567890123456789012345678901234567890n
console.log(typeof bigInt) // 'bigint'
console.log(typeof bigInt.instance) // 'object'
isBigInt
A getter method that checks if the current instance is a BigInt.
This method uses the pIsBigInt
function from the BigIntExtensions
patch to determine if the current instance (this
) is a BigInt.
Type: boolean
Examples
const bigInt = 1234567890123456789012345678901234567890n
console.log(bigInt.isBigInt) // Output: true
const notBigInt = 42
console.log(notBigInt.isBigInt) // Output: false
ifBigInt
Checks if the current object is a BigInt and returns the corresponding value based on the result.
This method uses the pIfBigInt
function from the BigIntExtensions
patch to determine if the current object (this
) is a BigInt. If it is
a BigInt, the thenValue
is returned. Otherwise, the elseValue
is
returned.
Parameters
thenValue
any The value to return if the current object is a BigInt.elseValue
any The value to return if the current object is not a BigInt.
Examples
const bigInt = 1234567890123456789012345678901234567890n
// 'Is a BigInt'
console.log(bigInt.ifBigInt('Is a BigInt', 'Not a BigInt'))
const notBigInt = 42
// 'Not a BigInt'
console.log(notBigInt.ifBigInt('Is a BigInt', 'Not a BigInt'))
Returns any The thenValue
if the current object is a BigInt, or
the elseValue
if it is not a BigInt.
getClassProperties
Retrieves the properties of a function and its prototype.
This method uses the Reflect.ownKeys
function to get all the keys
(including non-enumerable and symbol keys) of the function and its
prototype. It then uses Object.getOwnPropertyDescriptor
to get the
property descriptors for each key. The descriptors include information
about the property's value, writability, enumerability, and
configurability.
Parameters
fn
Function The function whose properties are to be retrieved.
Examples
function MyFunction() {}
MyFunction.myProp = 'hello';
MyFunction.prototype.myProtoProp = 'world';
const result = getClassProperties(MyFunction);
console.log(result);
// Output: [MyFunction, { myProp: { value: 'hello', writable: true,
// enumerable: true, configurable: true } }, MyFunction.prototype,
// { myProtoProp: { value: 'world', writable: true, enumerable: true,
// configurable: true } }]
Returns Array An array containing the function itself, its property descriptors, its prototype, and the prototype's property descriptors.
isAsync
Determines if a given value is an asynchronous function. It checks if the
value is an instance of Function
and if its string representation
includes the keyword 'Async'. This method is particularly useful for
identifying async functions.
Parameters
value
any The value to be checked.
Returns boolean Returns true
if the value is an async function,
otherwise false
.
ifAsync
- See: isThenElse
The ifAsync
function checks if a given value is an async function and
returns one of two provided values based on the result. This function is
a convenience method for performing conditional operations based on the
type of a value.
Parameters
value
any The value to be checked. If this is an async function,thenValue
is returned, otherwiseelseValue
is returned.thenValue
any The value to be returned ifvalue
is an async function.elseValue
any The value to be returned ifvalue
is not an async function.
Examples
// Suppose we have an async function and a regular function
async function asyncFunc() { return 'I am async'; }
function regularFunc() { return 'I am regular'; }
// Using ifAsync
console.log(Function.ifAsync(asyncFunc, 'Async', 'Not Async'));
// Output: 'Async'
console.log(Function.ifAsync(regularFunc, 'Async', 'Not Async'));
// Output: 'Not Async'
Returns any Returns thenValue
if value
is an async function,
otherwise returns elseValue
.
isAsyncGenerator
The function checks if a given value is an async generator function
Parameters
value
any Thevalue
parameter is the value that we want to check if it is a generator function.
Returns boolean true
if the value is an instance of a function and
its string tag is 'AsyncGeneratorFunction', otherwise it returns false
.
ifAsyncGenerator
The ifAsyncGenerator
function checks if a given value is an async
generator function and returns one of two provided values based on the
result. This function is a convenience method for performing conditional
operations based on the type of a value.
Parameters
value
any The value to be checked. If this is an async generator function,thenValue
is returned, otherwiseelseValue
is returned.thenValue
any The value to be returned ifvalue
is an async generator function.elseValue
any The value to be returned ifvalue
is not an async generator function.
Examples
// Suppose we have an async generator function and a regular function
async function* asyncGenFunc() { yield 'I am async'; }
function regularFunc() { return 'I am regular'; }
// Using ifAsyncGenerator
console.log(Function.ifAsyncGenerator(asyncGenFunc, 'Async', 'Not Async'));
// Output: 'Async'
console.log(Function.ifAsyncGenerator(regularFunc, 'Async', 'Not Async'));
// Output: 'Not Async'
Returns any Returns thenValue
if value
is an async generator
function, otherwise returns elseValue
.
isBigArrow
Checks if a given value is an arrow function. It verifies if the value is
an instance of Function
, if its string representation includes the '=>'
symbol, and if it lacks a prototype, which is a characteristic of arrow
functions in JavaScript.
Parameters
value
any The value to be checked.
Returns boolean Returns true
if the value is an arrow function,
otherwise false
.
ifBigArrow
The ifBigArrow
function checks if a given value is an arrow function
and returns one of two provided values based on the result. This function
is a convenience method for performing conditional operations based on
the type of a value.
Parameters
value
any The value to be checked. If this is an arrow function,thenValue
is returned, otherwiseelseValue
is returned.thenValue
any The value to be returned ifvalue
is an arrow function.elseValue
any The value to be returned ifvalue
is not an arrow function.
Examples
// Suppose we have an arrow function and a regular function
const arrowFunc = () => 'I am an arrow function';
function regularFunc() { return 'I am a regular function'; }
// Using ifBigArrow
console.log(Function.ifBigArrow(arrowFunc, 'Arrow', 'Not Arrow'));
// Output: 'Arrow'
console.log(Function.ifBigArrow(regularFunc, 'Arrow', 'Not Arrow'));
// Output: 'Not Arrow'
Returns any Returns thenValue
if value
is an arrow function,
otherwise returns elseValue
.
isBound
Determines if a given value is a bound function. Bound functions are
created using the Function.prototype.bind
method, which allows setting
the this
value at the time of binding. This method checks if the value
is an instance of Function
, if its string representation starts with
'bound', and if it lacks a prototype
property. These characteristics
are indicative of bound functions in JavaScript.
Parameters
value
any The value to be checked, typically a function.
Returns boolean Returns true
if the value is a bound function,
otherwise false
. Bound functions have a specific format in their
string representation and do not have their own prototype
property.
ifBound
The ifBound
function checks if a given value is a bound function and
returns one of two provided values based on the result. This function
is a convenience method for performing conditional operations based on
the type of a value.
Parameters
value
any The value to be checked. If this is a bound function,thenValue
is returned, otherwiseelseValue
is returned.thenValue
any The value to be returned ifvalue
is a bound function.elseValue
any The value to be returned ifvalue
is not a bound function.
Examples
// Suppose we have a bound function and a regular function
const boundFunc = function() { return this.x }.bind({x: 'I am bound'});
function regularFunc() { return 'I am a regular function'; }
// Using ifBound
console.log(Function.ifBound(boundFunc, 'Bound', 'Not Bound'));
// Output: 'Bound'
console.log(Function.ifBound(regularFunc, 'Bound', 'Not Bound'));
// Output: 'Not Bound'
Returns any Returns thenValue
if value
is a bound function,
otherwise returns elseValue
.
isClass
Determines if a given value is a class. It checks if the value is an
instance of Function
and if its string representation includes the
keyword 'class'. This method is useful for distinguishing classes from
other function types in JavaScript.
Parameters
value
any The value to be checked.
Returns boolean Returns true
if the value is a class, otherwise
false
.
ifClass
The ifClass
function checks if a given value is a class and returns
one of two provided values based on the result. This function is a
convenience method for performing conditional operations based on the
type of a value.
Parameters
value
any The value to be checked. If this is a class,thenValue
is returned, otherwiseelseValue
is returned.thenValue
any The value to be returned ifvalue
is a class.elseValue
any The value to be returned ifvalue
is not a class.
Examples
// Suppose we have a class and a regular function
class MyClass {}
function myFunction() {}
// Using ifClass
console.log(Function.ifClass(MyClass, 'Class', 'Not Class'));
// Output: 'Class'
console.log(Function.ifClass(myFunction, 'Class', 'Not Class'));
// Output: 'Not Class'
Returns any Returns thenValue
if value
is a class, otherwise returns
elseValue
.
isFunction
Checks if a given value is a regular function. This method verifies if
the value is an instance of Function
, which includes regular functions,
classes, and async functions but excludes arrow functions.
Parameters
value
any The value to be checked.
Returns boolean Returns true
if the value is a regular function,
otherwise false
.
ifFunction
The ifFunction
method checks if a given value is a regular function
and returns one of two provided values based on the result. This method
is a convenience for performing conditional operations based on the
type of a value.
Parameters
value
any The value to be checked. If this is a function,thenValue
is returned, otherwiseelseValue
is returned.thenValue
any The value to be returned ifvalue
is a function.elseValue
any The value to be returned ifvalue
is not a function.
Examples
// Suppose we have a function and a non-function value
function myFunction() {}
let notFunction = "I'm not a function";
// Using ifFunction
console.log(Function.ifFunction(myFunction, 'Function', 'Not Function'));
// Output: 'Function'
console.log(Function.ifFunction(notFunction, 'Function', 'Not Function'));
// Output: 'Not Function'
Returns any Returns thenValue
if value
is a function, otherwise
returns elseValue
.
isGenerator
The function checks if a given value is a generator function
Parameters
value
any Thevalue
parameter is the value that we want to check if it is a generator function.
Returns boolean true
if the value is an instance of a function and
its string tag is 'GeneratorFunction', otherwise it returns false
.
ifGenerator
The ifGenerator
method checks if a given value is a generator function
and returns one of two provided values based on the result. This method
is a convenience for performing conditional operations based on the
type of a value.
Parameters
value
any The value to be checked. If this is a generator function,thenValue
is returned, otherwiseelseValue
is returned.thenValue
any The value to be returned ifvalue
is a generator function.elseValue
any The value to be returned ifvalue
is not a generator function.
Examples
// Suppose we have a generator function and a non-generator function
function* myGenerator() {}
function myFunction() {}
// Using ifGenerator
console.log(Function.ifGenerator(myGenerator, 'Generator', 'Not Generator'));
// Output: 'Generator'
console.log(Function.ifGenerator(myFunction, 'Generator', 'Not Generator'));
// Output: 'Not Generator'
Returns any Returns thenValue
if value
is a generator function,
otherwise returns elseValue
.
StringTagHasInstance
This method modifies the behavior of the instanceof
operator for a
given class. It does this by defining a custom Symbol.hasInstance
method on the class. The custom method checks if the string tag of the
instance matches the name of the class or if the instance is part of
the prototype chain of the class.
Parameters
Class
Function The class for which to modify the behavior of theinstanceof
operator.
Examples
// Suppose we have a class `MyClass`
class MyClass {}
// And an instance of the class
const myInstance = new MyClass();
// Before applying `StringTagHasInstance`, `instanceof` works as usual
console.log(myInstance instanceof MyClass); // Output: true
// Now we apply `StringTagHasInstance` to `MyClass`
FunctionExtensions.patches.StringTagHasInstance(MyClass);
// `instanceof` now checks the string tag and the prototype chain
console.log(myInstance instanceof MyClass); // Output: true
FunctionExtensions
The FunctionExtensions
class is a patch applied to the built-in JavaScript
Function
constructor. It extends Function
with additional utility methods
for determining the specific type or nature of function-like objects. These
methods allow developers to distinguish between classes, regular functions,
async functions, and arrow functions in a more intuitive and straightforward
manner. This class is part of the @nejs/extension
library and enhances the
capabilities of function handling and introspection in JavaScript.
isAsync
Determines if a given value is an asynchronous function. It checks if the
value is an instance of Function
and if its string representation
includes the keyword 'Async'. This method is particularly useful for
identifying async functions.
Returns boolean Returns true
if the value is an async function,
otherwise false
.
ifAsync
- See: Function.ifAsync
The ifAsync
method checks if the current function is asynchronous and
returns one of two provided values based on the result. This method is
a convenience for performing conditional operations based on the
type of a function.
Parameters
thenValue
any The value to be returned if the function is asynchronous.elseValue
any The value to be returned if the function is not asynchronous.
Examples
// Suppose we have an async function and a non-async function
async function myAsyncFunction() {}
function myFunction() {}
// Using ifAsync
console.log(myAsyncFunction.ifAsync('Async', 'Not Async'));
// Output: 'Async'
console.log(myFunction.ifAsync('Async', 'Not Async'));
// Output: 'Not Async'
Returns any Returns thenValue
if the function is asynchronous,
otherwise returns elseValue
.
isAsyncGenerator
The function checks if a given value is an async generator function
Returns boolean true
if the value is an instance of a function and
its string tag is 'AsyncGeneratorFunction', otherwise it returns false
.
ifAsyncGenerator
The ifAsyncGenerator
method checks if the current function is an
asynchronous generator and returns one of two provided values based on
the result. This method is a convenience for performing conditional
operations based on the type of a function.
Parameters
thenValue
any The value to be returned if the function is an asynchronous generator.elseValue
any The value to be returned if the function is not an asynchronous generator.
Examples
// Suppose we have an async generator function and a non-async function
async function* myAsyncGeneratorFunction() {}
function myFunction() {}
// Using ifAsyncGenerator
console.log(myAsyncGeneratorFunction.ifAsyncGenerator(
'Async Generator', 'Not Async Generator'
));
// Output: 'Async Generator'
console.log(myFunction.ifAsyncGenerator(
'Async Generator', 'Not Async Generator'
));
// Output: 'Not Async Generator'
Returns any Returns thenValue
if the function is an asynchronous
generator, otherwise returns elseValue
.
isBigArrow
Checks if a given value is an arrow function. It verifies if the value is
an instance of Function
, if its string representation includes the '=>'
symbol, and if it lacks a prototype, which is a characteristic of arrow
functions in JavaScript.
Returns boolean Returns true
if the value is an arrow function,
otherwise false
.
ifBigArrow
Checks if the current function is a "big arrow" function and returns one of two provided values based on the result.
A "big arrow" function is an arrow function that is not bound
to a specific context and does not have its own this
value.
Parameters
thenValue
any The value to be returned if the function is a "big arrow" function.elseValue
any The value to be returned if the function is not a "big arrow" function.
Examples
// Suppose we have a "big arrow" function and a regular function
const bigArrowFn = () => {}
function regularFn() {}
// Using ifBigArrow
console.log(bigArrowFn.ifBigArrow('Big Arrow', 'Not Big Arrow'))
// Output: 'Big Arrow'
console.log(regularFn.ifBigArrow('Big Arrow', 'Not Big Arrow'))
// Output: 'Not Big Arrow'
Returns any Returns thenValue
if the function is a "big arrow"
function, otherwise returns elseValue
.
isBound
Determines if a given value is a bound function. Bound functions are
created using the Function.prototype.bind
method, which allows setting
the this
value at the time of binding. This method checks if the value
is an instance of Function
, if its string representation starts with
'bound', and if it lacks a prototype
property. These characteristics
are indicative of bound functions in JavaScript.
Returns boolean Returns true
if the value is a bound function,
otherwise false
. Bound functions have a specific format in their
string representation and do not have their own prototype
property.
ifBound
Checks if the current function is bound and returns one of two provided values based on the result.
A bound function is a function that has a fixed this
value and
may have preset arguments. It is created using the
Function.prototype.bind
method.
Parameters
thenValue
any The value to be returned if the function is bound.elseValue
any The value to be returned if the function is not bound.
Examples
// Suppose we have a bound function and a regular function
const boundFn = function() {}.bind(null)
function regularFn() {}
// Using ifBound
console.log(boundFn.ifBound('Bound', 'Not Bound'))
// Output: 'Bound'
console.log(regularFn.ifBound('Bound', 'Not Bound'))
// Output: 'Not Bound'
Returns any Returns thenValue
if the function is bound,
otherwise returns elseValue
.
isClass
Determines if a given value is a class. It checks if the value is an
instance of Function
and if its string representation includes the
keyword 'class'. This method is useful for distinguishing classes from
other function types in JavaScript.
Returns boolean Returns true
if the value is a class, otherwise
false
.
ifClass
Checks if the current function is a class and returns one of two provided values based on the result.
A class is a special type of function in JavaScript that is
defined using the class
keyword. It serves as a blueprint for
creating objects and encapsulates data and behavior.
Parameters
thenValue
any The value to be returned if the function is a class.elseValue
any The value to be returned if the function is not a class.
Examples
// Suppose we have a class and a regular function
class MyClass {}
function myFunction() {}
// Using ifClass
console.log(MyClass.ifClass('Class', 'Not Class'))
// Output: 'Class'
console.log(myFunction.ifClass('Class', 'Not Class'))
// Output: 'Not Class'
Returns any Returns thenValue
if the function is a class,
otherwise returns elseValue
.
isFunction
Checks if a given value is a regular function. This method verifies if
the value is an instance of Function
, which includes regular functions,
classes, and async functions but excludes arrow functions.
Returns boolean Returns true
if the value is a regular function,
otherwise false
.
ifFunction
Checks if the current function is a regular function and returns one of two provided values based on the result.
A regular function is an instance of Function
, which includes
regular functions, classes, and async functions but excludes
arrow functions.
Parameters
thenValue
any The value to be returned if the function is a regular function.elseValue
any The value to be returned if the function is not a regular function.
Examples
// Suppose we have a regular function and an arrow function
function regularFunction() {}
const arrowFunction = () => {}
// Using ifFunction
console.log(regularFunction.ifFunction('Regular', 'Not Regular'))
// Output: 'Regular'
console.log(arrowFunction.ifFunction('Regular', 'Not Regular'))
// Output: 'Not Regular'
Returns any Returns thenValue
if the function is a regular
function, otherwise returns elseValue
.
isGenerator
The function checks if a given value is a generator function
Returns boolean true
if the value is an instance of a function and
its string tag is 'GeneratorFunction', otherwise it returns false
.
ifGenerator
Checks if the current function is a generator function and returns one of two provided values based on the result.
A generator function is a special type of function that can be paused and resumed, allowing it to yield multiple values over time rather than returning a single value.
Parameters
thenValue
any The value to be returned if the function is a generator function.elseValue
any The value to be returned if the function is not a generator function.
Examples
// Suppose we have a generator function and a regular function
function* generatorFunction() {
yield 1
yield 2
yield 3
}
function regularFunction() {}
// Using ifGenerator
console.log(generatorFunction.ifGenerator('Generator', 'Regular'))
// Output: 'Generator'
console.log(regularFunction.ifGenerator('Generator', 'Regular'))
// Output: 'Regular'
Returns any Returns thenValue
if the function is a
generator function, otherwise returns elseValue
.
getClassProperties
Retrieves the properties of the current function and its prototype.
This method uses the getClassProperties
function from the
FunctionExtensions.patches
object to get all the properties of the
current function and its prototype. The properties include both
enumerable and non-enumerable properties, as well as properties
defined with symbols.
Examples
// Suppose we have a function with a property and a prototype property
function MyFunction() {}
MyFunction.myProp = 'hello';
MyFunction.prototype.myProtoProp = 'world';
// Using getClassProperties
const result = MyFunction.getClassProperties();
console.log(result);
// Output: [MyFunction, { myProp: { value: 'hello', writable: true,
// enumerable: true, configurable: true } }, MyFunction.prototype,
// { myProtoProp: { value: 'world', writable: true, enumerable: true,
// configurable: true } }]
Returns Array An array containing the function itself, its property descriptors, its prototype, and the prototype's property descriptors.
isThenElse
The isThenElse
function is a utility function that behaves like a
ternary operator. It takes three arguments: boolValue
, thenValue
,
and elseValue
.
It first checks the truthiness of boolValue
.
If boolValue
is truthy, it returns thenValue
; otherwise,
it returns elseValue
.
If thenValue
or elseValue
is a function, it will be invoked with
boolValue
as an argument.
If elseValue
is not provided, it returns boolValue
or thenValue
depending on the truthiness of boolValue
.
If only boolValue
is provided, it simply returns boolValue
.
Parameters
boolValue
any Any object or value that is tested for truthiness.thenValue
(function | any)? The value to return ifboolValue
is truthy. If a function, it's invoked withboolValue
.elseValue
(function | any)? The value to return ifboolValue
is falsy. If a function, it's invoked withboolValue
.
Examples
// Using values
isThenElse(true, 'yes', 'no'); // Returns: 'yes'
isThenElse(false, 'yes', 'no'); // Returns: 'no'
// Using functions
isThenElse(true, val => val ? 'yes' : 'no'); // Returns: 'yes'
isThenElse(false, val => val ? 'yes' : 'no'); // Returns: 'no'
Returns (boolean | any) The result of the ternary operation.
maskAs
Transforms an object to mimic a specified prototype, altering its type conversion and inspection behaviors. This function is especially useful for creating objects that need to behave like different primitive types under various operations.
Parameters
object
Object The object to be transformed.classPrototype
- `option