@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.
-
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.
Install @nejs/basic-extensions using npm:
npm install @nejs/basic-extensions
Or using yarn:
yarn add @nejs/basic-extensions
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
- FunctionExtensions
- isAsync
- isAsyncGenerator
- isBigArrow
- isBound
- isClass
- isFunction
- isGenerator
- ObjectExtensions
- stripTo
- getKey
- concat
- contains
- every
- find
- findLast
- length
- map
- reduce
- some
- ReflectExtensions
- StringExtensions
- SymbolExtensions
- ArrayPrototypeExtensions
- 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
- maskAs
- maskAsString
- maskAsNumber
- GenericMask
- StringMask
- NumberMask
- RefSet
- RefMap
- isValidReference
- Deferred
- promise
- reject
- resolve
- settled
- AsyncIterable
- AsyncIterator
- Iterable
- Iterator
- mapEach
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.
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.
value
any The value to be checked.
Returns boolean Returns true
if the value is an async function,
otherwise false
.
The function checks if a given value is an async generator function
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
.
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.
value
any The value to be checked.
Returns boolean Returns true
if the value is an arrow function,
otherwise false
.
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.
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.
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.
value
any The value to be checked.
Returns boolean Returns true
if the value is a class, otherwise
false
.
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.
value
any The value to be checked.
Returns boolean Returns true
if the value is a regular function,
otherwise false
.
The function checks if a given value is a generator function
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
.
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
.
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
.
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
.
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.
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
.
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
.
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
.
ObjectExtensions
is a patch for the JavaScript built-in Object
class.
It adds utility methods to the Object
class without modifying the global
namespace directly. This patch includes methods for key validation, object
type checking, and retrieving the string tag of an object. These methods
are useful for enhancing the capabilities of the standard Object
class
with additional utility functions.
The function checks if a value is either undefined
or null
.
value
any The parameter "value" is a variable that can hold any value.
Returns boolean true
if the value is either undefined
or null
,
and false
otherwise.
Checks to see if the supplied value
is both an object, and has the
appropriate symbol defined.
value
any the value to determine if it contains a definedSymbol.toStringTag
defined.
Returns any true if the symbol is defined, false otherwise
Retrieves the string tag of an object. The string tag is a representation
of the object's type, as defined by its Object.prototype.toString
method. This utility method is helpful for getting a more descriptive
type of an object than what is returned by the typeof
operator,
especially for custom objects.
value
any The object whose string tag is to be retrieved.strict
boolean if this is set to true, undefined will be returned whenever a supplied object does not have aSymbol.toStringTag
defined, period. if false, the default, (optional, defaultfalse
)
Returns string The string tag of the object, indicating its type.
Determines the type of the given value based on its string tag. This method
uses Object.getStringTag
to obtain the string tag of the value, which
represents its more specific type (e.g., Array, Map, Set) rather than just
'object'. The method then maps this string tag to the corresponding type
present in the provided owner
object, which defaults to globalThis
.
This utility method is especially useful for identifying the specific
constructor or class of an object, beyond the basic types identified by
the typeof
operator.
value
any The value whose type is to be determined.owner
object The object in which to look up the constructor corresponding to the string tag. Defaults toglobalThis
, which covers global constructors likeArray
,Object
, etc. (optional, defaultglobalThis
)
Returns (Function | object | null | undefined) Returns the constructor or
type of the value based on its string tag. For 'Null' and 'Undefined',
it returns null
and undefined
, respectively. For other types, it
returns the corresponding constructor (e.g., Array
for arrays) if
available in the owner
object.
Determines if the provided value is an object. This method checks whether
the value is an instance of Object
or if its type is 'object'. It's a
utility method for type-checking, ensuring that a value is an object
before performing operations that are specific to objects.
value
any The value to be checked.
Returns boolean Returns true
if the value is an object,
otherwise false
.
Checks to see if the supplied value is a primitive value.
value
any the value to test to see if it is a primitive value type
Returns any true if the object is considered widely to be a primitive value, false otherwise.
Checks if the given value is a valid key for an object. In JavaScript, a valid key can be either a string or a symbol. This method is useful for validating object keys before using them in operations like setting or getting object properties.
value
any The value to be checked.
Returns boolean Returns true
if the value is a valid object key
(string or symbol), otherwise false
.
Strips an object down to only the keys specified. Optionally, any accessors can be made to retain their context on the source object.
object
object the object to pare downkeys
Array<(string | symbol)> the keys that should appear in the final reduced objectbindAccessors
boolean if this value is true then any accessors from the source object will continue to have theirthis
value bound to the source. If the getter or setter on that object is defined using an arrow function, this will not work as intended. (optional, defaulttrue
)
Returns object an object containing only the keys and symbols
specified in the keys
parameter.
Strips an object down to only the keys specified. Optionally, any accessors can be made to retain their context on the source object. This is a passthrough to the static Object.stripTo function
keys
Array<(string | symbol)> the keys that should appear in the final reduced objectbindAccessors
boolean if this value is true then any accessors from the source object will continue to have theirthis
value bound to the source. If the getter or setter on that object is defined using an arrow function, this will not work as intended. (optional, defaulttrue
)
Returns object an object containing only the keys and symbols
specified in the keys
parameter.
The function getKey
returns the key associated with a given value
in a map.
value
any The value parameter is the value that you want to find the corresponding key for in the map.strict
The "strict" parameter is a boolean value that determines whether strict equality (===) or loose equality (==) should be used when comparing the "value" parameter with the values in the entries of the object. If "strict" is set to true, strict equality will be used. (optional, defaulttrue
)
Returns any the key associated with the given value. If a matching key is found, it is returned. If no matching key is found, null is returned.
Merges multiple iterables into the set. Each element from the iterables is added to the set, ensuring uniqueness of all elements. This method mutates the original set.
iterables
...Iterable One or more iterable objects (like Set or Array) whose elements will be added to the set.
Checks to see if any value within the Set
loosely equals the supplied
value.
value
any any value that might be loosely equal to an item in the set, as opposed to Set.has which is the equivalent of a strict or triple equals (===
) check
Returns boolean true
if any value within the set is loosely equal to
the supplied value, false
otherwise
Checks if every element in the set passes the test implemented by the provided function. The function is called with each element of the set. Note: Since sets do not have indices, the index parameter is always NaN.
everyFn
Function The function to test each element. Receives the element, index (always NaN), and the set itself.thisArg
Object? Optional. Value to use asthis
when executingeveryFn
.
- Throws TypeError If
everyFn
is not a function.
Returns boolean True if every element passes the test, false otherwise.
Finds the first element in the set satisfying the provided testing function. If no elements satisfy the testing function, undefined is returned. The function is called with each element of the set. Note: Since sets do not have indices, the index parameter is always NaN.
findFn
Function The function to execute on each element. It receives the element, index (always NaN), and the set itself.thisArg
Object? Optional. Value to use asthis
when executingfindFn
.
- Throws TypeError If
findFn
is not a function.
Returns any The first element that satisfies findFn
, or undefined.
Finds the last element in the set satisfying the provided testing function. If no elements satisfy the testing function, undefined is returned. The function is called with each element of the set in reverse order. Note: Since sets do not have indices, the index parameter is always NaN.
findFn
Function The function to execute on each element. It receives the element, index (always NaN), and the set itself.thisArg
Object? Optional. Value to use asthis
when executingfindFn
.
- Throws TypeError If
findFn
is not a function.
Returns any The last element that satisfies findFn
, or undefined.
A getter property that returns the number of elements in the set.
This is an alias for the size
property of the set.
Returns number The number of elements in the set.
Creates a new array populated with the results of calling the provided function on every element in the set. The function is called with each element of the set. Note: Since sets do not have indices, the index parameter is always NaN.
mapFn
Function The function to execute on each element. It receives the element, index (always NaN), and the set itself.thisArg
Object? Optional. Value to use asthis
when executingmapFn
.
- Throws TypeError If
mapFn
is not a function.
Returns Array A new array with each element being the result of the
mapFn
.
Applies a function against an accumulator and each element in the set to reduce it to a single value. The function is called with each element of the set. Note: Since sets do not have indices, the index parameter is always NaN.
reduceFn
Function The function to execute on each element. It receives the accumulator, element, index (always NaN), and the set itself.initialValue
any The initial value to start reducing from.thisArg
Object? Optional. Value to use asthis
when executingreduceFn
.
- Throws TypeError If
reduceFn
is not a function.
Returns any The reduced value.
Tests whether at least one element in the set passes the test implemented by the provided function. The function is called with each element of the set. Note: Since sets do not have indices, the index parameter is always NaN.
someFn
Function The function to test each element. It receives the element, index (always NaN), and the set itself.thisArg
Object? Optional. Value to use asthis
when executingsomeFn
.
- Throws TypeError If
someFn
is not a function.
Returns boolean True if at least one element passes the test, false otherwise.
The ReflectExtensions
class is a patch applied to the built-in JavaScript
Reflect
object. It extends Reflect
with additional utility methods that
enhance its capabilities. These methods provide more advanced ways of
interacting with object properties, such as checking for the presence of
multiple keys at once (hasAll
) or verifying if at least one specified key
exists in an object (hasSome
). This class is part of the @nejs/extension
library and is designed to offer these extended functionalities in a way
that is consistent with the existing Reflect
API, making it intuitive for
developers who are already familiar with standard reflection methods in
JavaScript.
The function checks if an object has all the specified keys.
object
Theobject
parameter is the object that we want to check if it has all the specified keys.keys
...any Thekeys
parameter is a rest parameter, which means it can accept any number of arguments. In this case, it is expected to receive multiple keys as arguments.
Returns any a boolean value.
Fetches all descriptors of an object, including those mapped to a symbol descriptor value.
object
object the object from whose descriptors need to be retrieved.
- Throws TypeError if the supplied
object
is null or not an object a TypeError exception will be thrown
Returns object with keys mapped to object descriptors
The function checks if an object has at least one of the specified keys.
object
Theobject
parameter is the object that we want to check for the presence of certain keys.keys
...any Thekeys
parameter is a rest parameter, which means it can accept any number of arguments. These arguments are the keys that we want to check if they exist in theobject
.
Returns any The function hasSome
returns a boolean value indicating whether
at least one of the keys provided as arguments exists in the given object.
Retrieves an array of [key, descriptor] pairs for each property of the
provided object. This method is akin to Object.entries
but includes
property descriptors instead of the property values. It's useful for cases
where you need detailed information about properties, including their
configurability, enumerability, and accessors.
object
object The object whose property entries are to be retrieved.
Returns Array An array of [key, descriptor] pairs, where each pair consists of the property name (key) and its descriptor. Returns an empty array if the input is not a valid object.
Retrieves an array of values from the property descriptors of the given
object. This method works similarly to Object.values
but operates on
property descriptors instead. It's useful when you need the values of
properties including getters, setters, and other descriptor-specific
attributes.
object
object The object whose property values are to be retrieved.
Returns Array An array of values extracted from the object's property
descriptors. The values correspond to the value
attribute in each
property's descriptor. Returns an empty array if the input is not a valid
object.
StringExtensions
is a patch for the JavaScript built-in String
class. It
adds utility methods to the String
class without modifying the global namespace
directly. This patch includes methods for key validation, object type checking,
and retrieving the string tag of an object. These methods are useful for
enhancing the capabilities of the standard String
class with additional
utility functions.
The isString
method does exactly what one would it expect. It returns
true if the string matches typeof or instanceof as a string.
value
any checks to see if thevalue
is a string
Returns boolean true
if it is a String
, false
otherwise
SymbolExtensions
is a patch for the JavaScript built-in Symbol
class. It
adds utility methods to the Symbol
class without modifying the global namespace
directly. This patch includes methods for key validation, object type checking,
and retrieving the string tag of an object. These methods are useful for
enhancing the capabilities of the standard Symbol
class with additional
utility functions.
The isSymbol
method does exactly what one would it expect. It returns
true if the string matches typeof or instanceof as a symbol.
value
any checks to see if thevalue
is a string
Returns boolean true
if it is a Symbol
, false
otherwise
Returns true if the supplied value is a Symbol created using
Symbol.for()
.
value
any assumption is that the supplied value is of type 'symbol' however, unlessallowOnlySymbols
is set totrue
,false
will be returned for any non-symbol values.allowOnlySymbols
boolean true if an error should be thrown if the supplied value is not of type 'symbol' (optional, defaultfalse
)
Returns any true if the symbol is registered, meaning, none of the spec
static symbols (toStringTag
, iterator
, etc...), and no symbols
created by passing a value directly to the Symbol function, such as
Symbol('name')
A function that returns true if the symbol is not registered, meaning,
any of the spec static symbols (toStringTag
, iterator
, etc...), and
any symbols created by passing a value directly to the Symbol
function,
such as Symbol('name')
.
value
any assumption is that the supplied value is of type 'symbol' however, unless allowOnlySymbols is set to true, false will be returned for any non-symbol values.allowOnlySymbols
boolean true if an error should be thrown if the supplied value is not of type 'symbol' (optional, defaultfalse
)
Returns any true if the symbol is not registered, meaning, any of the
spec static symbols (toStringTag
, iterator
, etc...), and any symbols
created by passing a value directly to the Symbol
function, such as
Symbol('name')
Returns any true if the value
in question is both a symbol
and has
returns undefined
if passed to Symbol.keyFor
The ArrayPrototypeExtensions
patch extends the prototype of the built-in
JavaScript Array
with additional properties for convenience and improved
readability. By applying this patch, all array instances gain new getter
properties first
and last
, which provide quick access to the first and
last elements of the array, respectively. This enhancement simplifies common
operations on arrays and makes code more expressive and concise.
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.
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
The findEntry
function searches the entries of the object and returns
the [index, value]
entry array for the first matching value found.
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.
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.
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.
An optionally associated object, usually the parent from which the descriptor was taken, or undefined if none was able to be derived.
Type: object
Constructs a Descriptor instance which wraps and manages an object property descriptor. The constructor can handle an existing descriptor object or create a new one based on an object and a property key.
object
(object | Descriptor) The target object or an existing Descriptor instance. If it's an object, it is used in conjunction withkey
to create a descriptor. If it's a Descriptor instance, it is used directly as the descriptor.key
(string | symbol)? The property key for which the descriptor is to be created. This parameter is ignored ifobject
is a Descriptor instance. Ifkey
is an object andobject
is a valid descriptor,key
is treated as the associated object.
- Throws Error Throws an error if the constructed descriptor is not valid.
Detects whether or not this instance is an accessor object descriptor
Returns boolean true if this object has a getter or setter and is not a data descriptor
Detects whether or not this instance is an data object descriptor
Returns boolean true if this object has a value property and is not an accessor descriptor
Detects whether or not this instance is a valid object descriptor
Returns boolean true if this descriptor store is a valid descriptor
Getter around the configurable
object descriptor property of
this instance of Descriptor.
Returns boolean a boolean value or undefined if the internal descriptor store is invalid.
Sets the configurable
value of this object. If the internal descriptor
store store is invalid, the value is thrown away
value
boolean the value to set for theconfigurable
descriptor property. If this value is not aboolean
it will be converted to one
Getter around the enumerable
object descriptor property of
this instance of Descriptor.
Returns boolean a boolean value or undefined if the internal descriptor store is invalid.
Sets the enumerable
value of this object. If the internal descriptor
store is invalid, the value is thrown away
value
boolean the value to set for theenumerable
descriptor property. If this value is not aboolean
it will be converted to one
Getter around the writable
object descriptor property of
this instance of Descriptor.
Returns boolean a boolean value or undefined if the internal descriptor store is invalid.
Sets the writable
value of this object. If the internal descriptor
store is invalid, the value is thrown away
value
boolean the value to set for thewritable
descriptor property. If this value is not aboolean
it will be converted to one
Getter around the value
object descriptor property of
this instance of Descriptor.
Returns any any value stored in this descriptor
Sets the value
value of this object. If the internal descriptor
store is invalid, the value is thrown away
value
any the value to set for thevalue
descriptor property.
Getter around the get
object descriptor property of
this instance of Descriptor.
Returns function a function if the getter for this descriptor is
defined or undefined
if the internal descriptor object or the getter
is undefined.
Sets the get
value of this object. If the internal descriptor
store is invalid, the value is thrown away
value
function the getter function for this descriptor
Retrieves the get function for this accessor and binds it to the object from which the descriptor was derived, if that value is set. Otherwise this method is identical to the get accessor.
Returns function the getter if one is defined. If possible this
getter will be bound the associated and previously set object
.
Getter around the set
object descriptor property of
this instance of Descriptor.
Returns function a function if the setter for this descriptor is
defined or undefined
if the internal descriptor object or the setter
is undefined.
Sets the set
value of this object. If the internal descriptor
store is invalid, the value is thrown away
value
function the setter function for this descriptor
Retrieves the set function for this accessor and binds it to the object from which the descriptor was derived, if that value is set. Otherwise this method is identical to the set accessor.
Returns function the setter if one is defined. If possible this
setter will be bound the associated and previously set object
.
The function checks the descriptor's associated object has been set on this
instance of Descriptor
.
Returns boolean true
if the object
property has been set,
false
otherwise
Returns the descriptor's associated object
value. This is usually the
parent object from which the descriptor was derived. If the value is preset
it will be returned. Undefined will be returned otherwise
Returns object the associated object for this descriptor or undefined if it has not yet been set.
Sets the descriptor's associated object
value. This is usually the
parent object from which the descriptor was derived.
value
object sets the object for which this descriptor is to be associated with.
The function returns a string representation of a descriptor object with additional information about its type when used in the NodeJS repl.
depth
number Thedepth
parameter is used to specify the maximum depth to which nested objects and arrays will be formatted. If the depth is exceeded, the output will be truncated with ellipses.options
object Theoptions
parameter is an object that contains various configuration options for theinspect
function. These options can be used to customize the output of the inspection.inspect
function Theinspect
parameter is a function that is used to convert an object into a string representation. It is typically used for debugging purposes or when displaying an object's properties.
Returns any a string that represents a descriptor. The string includes the type of the descriptor (either "Accessor" or "Data") and the result of inspecting the descriptor object using the provided options and depth.
Take the descriptor defined by this objects values and apply them to the specified object using the specified key.
object
object the object to apply this descriptor toforKey
(string | symbol) the string or symbol for which this descriptor will abe appliedbindAccessors
(optional, defaultfalse
)
Converts this Descriptor class instance into a basic object descriptor that is accepted by all the standard JavaScript runtime methods that deal with object descriptors.
bindAccessors
(boolean | object) iftrue
, a non-fatal attempt to bind accessor getter and setter methods is made before returning the object. IfbindAccessors
is truthy and is also an object, this is the object the accessors will be bound to. If the value is falsy or if the descriptor instance represents a data descriptor, nothing happens. (optional, defaultfalse
)
Returns object the object instance's basic object representation as a descriptor.
Converts this descriptor object into a base representation
hint
string one ofstring
,number
or default;
Returns any if the hint is 'string', then a string identifying the enum
and its type is returned. number
will always be NaN since it is incoret
Ensures that the constructor of this object instance's name is returned if the string tag for this instance is queried
Returns string the name of the class
Shorthand for Object.getOwnPropertyDescriptor()
object
object a non-null object instancekey
(string | symbol) a symbol or string referencing which key on the object to return a descriptor for.wrap
(optional, defaultfalse
)
Returns any an object descriptor for the requested field or null
The function getData
retrieves the value of a property from an object
if it exists and is a data property.
object
object The "object" parameter is the object from which we want to retrieve data.property
(string | symbol) Theproperty
parameter is the name of the property that you want to retrieve the data from.
Returns any either the value of the specified property if it exists and is a data property, or undefined if the property does not exist or is not a data property.
The function getAccessor
checks if an object has a getter/setter accessor
for a given property and returns the accessor functions if found.
object
Theobject
parameter is the object from which we want to retrieve the accessor for a specific property.property
Theproperty
parameter is the name of the property for which we want to get the accessor.
Returns any an object that contains the getter and setter functions for the specified property of the given object. If the property is an accessor property (defined with a getter and/or setter), the returned object will also have additional properties such as "accessor" and "descriptor". If the property is not found or is not an accessor property, the function returns undefined.
The function returns an object with enumerable and configurable properties based on the input parameters.
enumerable
A boolean value indicating whether the property can be enumerated (listed) when iterating over the object's properties. (optional, defaultfalse
)configurable
Theconfigurable
parameter determines whether the property can be deleted or its attributes can be modified. Ifconfigurable
is set totrue
, the property can be deleted and its attributes can be changed. Ifconfigurable
is set tofalse
, the property cannot be deleted and (optional, defaultfalse
)
Returns any An object with the properties enumerable
and configurable
is
being returned. The values of these properties are determined by the
arguments passed to the base
function.
The function "newAccessor" creates a new property descriptor object with a getter and setter function, along with optional enumerable and configurable flags.
-
getter
The getter parameter is a function that will be used as the getter for the property. It will be called when the property is accessed. -
setter
Thesetter
parameter is a function that will be used as the setter for the property. It will be called whenever the property is assigned a new value. -
null
Object *getter
: A function that will be used as the getter for the property. (optional, defaultDescriptor.base()
)null.enumerable
null.configurable
Returns any an object with properties "get", "set", "enumerable", and "configurable".
The function "newData" creates a new data object with customizable properties.
-
value
The value parameter represents the value that will be assigned to the property. -
writable
Thewritable
parameter determines whether the value of the property can be changed. Ifwritable
is set totrue
, the value can be changed. Ifwritable
is set tofalse
, the value cannot be changed. (optional, defaulttrue
) -
null
Object *value
: The value to be assigned to the property. (optional, defaultDescriptor.base()
)null.enumerable
null.configurable
Returns any an object with properties value
, enumerable
, writable
, and
configurable
.
The function checks if an object is a likely an object descriptor in JavaScript. This is determined as an object with some of the known descriptor keys (e.g. enumerable, configurable, value, writable, get, or set). Technically, any object could serve as a descriptor but this function only returns true if known descriptor keys are found.
object
Theobject
parameter is the object that we want to check if it is a descriptor.
Returns any a boolean value.
The function checks if a given property or descriptor is a data property.
brie
object_orProp
property
descriptor_orProp
Thedescriptor_orProp
parameter can be either a descriptor or a property name.object
Theobject
parameter is the object that you want to check for data properties.
Returns any a boolean value. It returns true
if the descriptor
object
has any keys that match the DATA_KEYS
array, otherwise it returns
false
.
The function checks if a given property descriptor or property of an object is an accessor.
object_orProp
Thedescriptor_orProp
parameter can be either a descriptor object or a property name.property
Theobject
parameter is the object that you want to check for accessor properties.
Returns any a boolean value. It returns true if the descriptor or property passed as an argument is an accessor descriptor, and false otherwise.
A base descriptor (new for each read) that is both enumerable and configurable
Returns any The method flexible
is returning the result of calling the
base
method with the arguments true
and true
.
A base descriptor (new for each read) that is not enumerable but is configurable
Returns any The method enigmatic
is returning the result of calling
the base
method with the arguments false
and true
.
A base descriptor (new for each read) that is neither enumerable nor configurable
Returns any The code is returning the result of calling the base
method with
the arguments false
and false
.
A base descriptor (new for each read) that enumerable but not configurable
Returns any The method is returning the result of calling the base
method with the arguments true
and false
.
The function returns an array of shared descriptor keys.
Returns any An array containing the strings 'configurable' and 'enumerable'.
The function returns an array of accessor descriptor keys.
Returns any An array containing the strings 'get' and 'set' is being returned.
The function returns an array of data descriptor keys.
Returns any An array containing the strings 'value' and 'writable' is being returned.
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.
object
Object The object to be transformed.classPrototype
options
prototype
(Function | Object) The prototype or class to emulate. If a function is provided, its prototype is used. Defaults to String.prototype. (optional, defaultString.prototype
)toPrimitive
Function A function defining how the object should be converted to a primitive value. It receives a type hint ('number', 'string', or 'default') and the object, returning the primitive value. (optional, default(hint,val)=>String(val)
)
Returns (Object | null) The transformed object, or null if neither a class nor a prototype could be derived from the provided prototype parameter.
Masks an object as a string-like object by setting its prototype to String and defining how it converts to primitive types. This is particularly useful when an object needs to behave like a string in certain contexts, such as type coercion or logging.
object
Object The object to be masked as a string.stringKey
string The object property key used for the string representation. Defaults to 'value'. (optional, default'value'
)toPrimitive
Function? Optional custom function for primitive conversion. If omitted, a default function handling various conversion hints is used.
Returns (Object | null) The string-masked object, or null if the object doesn't have the specified stringKey property.
Masks an object as a number-like object. This allows the object to behave like a number in operations like arithmetic and type coercion. It sets the prototype to Number and defines custom conversion behavior.
object
Object The object to be masked as a number representation. Defaults to 'value'.numberKey
toPrimitive
Function? Optional custom function for primitive conversion. If not provided, a default function handling different conversion hints is used.
Returns (Object | null) The number-masked object, or null if the object doesn't have the specified numberKey property.
Generates options for generic masking of an object, providing defaults for prototype and toPrimitive function if not specified.
-
options
Object The options object including prototype, targetKey, and toPrimitive function.options.prototype
options.targetKey
(optional, default'value'
)options.toPrimitive
Returns Object The options object with defaults applied as necessary.
Generates options for string masking of an object, providing a default toPrimitive function if not specified.
targetKey
string The object property key for string representation.toPrimitive
Function Custom function for primitive conversion.
Returns Object Options for string masking.
Generates options for number masking of an object, providing a default toPrimitive function if not specified.
targetKey
string The object property key for number representation.toPrimitive
Function Custom function for primitive conversion.
Returns Object Options for number masking.
Extends Set
RefSet class extends the standard Set object to manage a collection of WeakRef objects. It provides additional functionality such as objectification of values and various utility methods.
Unlike standard Sets or Arrays, RefSet stores weak references to objects, allowing them to be garbage-collected if there are no other references to them. This behavior is different from Arrays and standard Sets, which maintain strong references to their elements.
Method to control whether the RefSet should objectify its values. When objectifying, primitive values (number, string, boolean, bigint) are converted to their respective object types, which allows them to be used as WeakRef targets.
setObjectification
boolean Flag to enable or disable objectification. (optional, defaulttrue
)
Returns RefSet The current RefSet instance to allow method chaining.
Returns the state indicating whether or not RefSet
will attempt to
convert non-valid primitives into targets that are valid input for
new WeakRef
object instances. If this value is false
then no
objectification will occur.
Returns boolean The current state of objectifyValues.
Setting this value to true, will cause all added values to the Set to
be analyzed for validity as a candidate to be wrapped in a WeakRef
object. If true, and if possible, the object will be turned into an
Object
variant first. This will also enable less rigid variable
comparison in the .has()
method (i.e. ==
instead of ===
).
value
boolean The new state to set for objectifyValues.
Overrides the add method of Set. Adds a value to the RefSet, converting it
to a WeakRef. Throws an error if the value is not a valid WeakRef target
(e.g., null, undefined, or a registered symbol). If objectifyValues
is
enabled, an attempt to convert primitives to their object variants will be
made. These are numbers, strings, boolean values and big integers.
value
any The value to be added to the RefSet.
- Throws TypeError If the value is not a valid WeakRef target.
Adds multiple values to the RefSet. The supplied values
should be
iterable and truthy. This function defers to .add()
for its logic so
each value from the supplied collection of values will also be subject
to the criteria of that function.
values
Iterable An iterable of values to add to the RefSet.
- Throws TypeError If the supplied values are falsey or non-iterable.
Removes all elements from the RefSet that have been garbage collected (i.e., their WeakRef no longer points to an object).
Returns RefSet The current RefSet instance to allow method chaining.
Executes a provided function once for each value in the RefSet. The callback function receives the dereferenced value, the value again (as RefSet doesn't use keys), and the RefSet itself. This method provides a way to iterate over and apply operations to the values stored in the RefSet, taking into account that they are weak references and may have been garbage-collected.
forEachFn
Function Function to execute for each element. It takes three arguments: element, element (again, as RefSet has no key), and the RefSet itself.thisArg
any Value to use asthis
when executingforEachFn
.
Iterate over the items in the set and pass them to the supplied
function ala Array.prototype.forEach
. Note however, there are no
indexes on Sets and as such, the index parameter of the callback
will always be NaN
. Subsequently the array
or third parameter
will receive the set instance rather than an array.
forEachFn
function the function to use for each element in the set.thisArg
object thethis
argument to be applied to each invocation of theforEachFn
callback. Note, this value is unable to be applied if theforEachFn
is a big arrow function
Returns an iterator for the values in the RefSet. Each value is dereferenced from its WeakRef before being returned. This method allows iterating over he set's values, similar to how one would iterate over values in a standard Set or Array, but with the understanding that the values are weakly referenced and may no longer exist (in which case they are skipped).
Returns Iterator An iterator for the values.
Returns an iterator for the keys of the RefSet. In RefSet, keys and
values are identical, so this method behaves the same as values()
. It
provides compatibility with the standard Set interface and allows use in
contexts where keys are expected, despite RefSet not differentiating
between keys and values.
Returns Iterator An iterator for the keys.
Determines whether an element with the specified value exists in the
RefSet
. For non-objectified sets, this method checks if the dereferenced
values of the set include the specified value.
For objectified sets, it uses the contains
method which accounts for
the objectification. This method differs from standard Set has
in that
it works with weak references and considers objectification settings.
value
any The value to check for presence in the RefSet.
Returns boolean True if an element with the specified value exists in the RefSet, false otherwise.
Checks if the RefSet contains a value that is equal to the specified
value. This method is used primarily in objectified RefSets to determine
the presence of a value, taking into account objectification. It differs
from the has
method in that it's tailored for sets that have
transformed their primitive values into objects, whereas has
is more
general-purpose.
value
any The value to search for in the RefSet.
Returns boolean True if the RefSet contains the value, false otherwise.
Creates a new array with all elements that pass the test implemented by
the provided function. This method iterates over each element,
dereferences it, and applies the filter function. Unlike Array filter
,
the callback receives the dereferenced value and not an index or array,
reflecting the non-indexed nature of RefSet. Useful for selectively
creating arrays from the set based on certain conditions, especially when
dealing with weak references.
filterFn
Function Function to test each element of the RefSet. The function receives the dereferenced value.thisArg
any Value to use asthis
when executingfilterFn
.
Returns Array A new array with the elements that pass the test.
Returns the value of the first element in the RefSet that satisfies the
provided testing function. Similar to Array find
, this method iterates
over the RefSet, dereferencing each value and applying the testing
function. The non-indexed nature of RefSet is considered, as the
callback does not receive an index. This method is useful for finding a
specific element based on a condition.
findFn
thisArg
any Value to use as this when executing findFn.
Returns any The value of the first element in the RefSet that satisfies the testing function, or undefined if none found.
Returns any the dereferenced value if found, or undefined otherwise
Creates a new array or RefSet
with the results of calling a provided
function on every element in the calling RefSet
. This method dereferences
each value, applies the mapFn
, and collects the results. If toRefSet
is
true
, a new RefSet
is returned; otherwise, an array. This method
differs from Array.map
in handling weak references and the potential to
return a new RefSet
instead of an array.
mapFn
Function Function that produces an element of the new array orRefSet
, taking three arguments.thisArg
any Value to use as this when executing mapFn.toRefSet
boolean Determines if the output should be a newRefSet
(true
) or an array (false
).mirrorObjectification
boolean Iftrue
andtoRefSet
istrue
, the newRefSet
mirrors the objectification setting of the original.
Returns (Array | RefSet) A new array or RefSet
with each element being
the result of the mapFn
.
Ensures that the constructor of this object instance's name is returned if the string tag for this instance is queried
Returns string the name of the class
Extends Map
RefMap class extends the standard Map object to manage a collection of WeakRef values mapped to strong keys. It provides additional functionality such as objectification of values and various utility methods.
Unlike standard Maps or Objects, RefMap stores weak references to objects, allowing them to be garbage-collected if there are no other references to them. This behavior is different from Maps and standard Objects, which maintain strong references to their elements.
args
...any
Method to control whether the RefMap should objectify its values. When objectifying, primitive values (number, string, boolean, bigint) are converted to their respective object types, which allows them to be used as WeakRef targets.
setObjectification
boolean Flag to enable or disable objectification. (optional, defaulttrue
)
Returns RefMap The current RefMap instance to allow method chaining.
The function converts a JavaScript Map object into a regular JavaScript object, handling invalid keys by converting them to strings.
Returns object an object; keys that are not either a String
or a
Symbol
will be converted to a string.
Returns the state indicating whether or not RefMap
will attempt to
convert non-valid primitives into targets that are valid input for
new WeakRef
object instances. If this value is false
then no
objectification will occur.
Returns boolean The current state of objectifyValues.
Setting this value to true, will cause all set values to the Map to
be analyzed for validity as a candidate to be wrapped in a WeakRef
object. If true, and if possible, the object will be turned into an
Object
variant first.
value
boolean The new state to set for objectifyValues.
The get
function retrieves a value from a map and returns it, or returns a
default value if the value is null or undefined. The actual retrieved value
is a dereferenced WeakRef
. If the result is undefined
and this is not the
expected response, it is likely the value has been garbage collected.
key
any The key parameter is the key of the value you want to retrieve from the data structure.defaultValue
any ThedefaultValue
parameter is the value that will be returned if the key does not exist in the map or if the value associated with the key has been garbage collected (i.e., it no longer exists).
Returns any The method is returning the value associated with the given key. If the value is not found or if it has been garbage collected (deref() returns null), then the defaultValue is returned.
Overrides the set method of Map
. Adds a value to the RefMap
,
converting it to a WeakRef
. Throws an error if the value is not a
valid WeakRef
target (e.g., null
, undefined
, or a registered
symbol
). If objectifyValues is enabled, an attempt to convert
primitives to their object variants will be made. These are numbers
,
strings
, boolean
values and bigint
s.
key
any Thekey
to be set on theRefMap
value
any The value to be associated with thekey
- Throws TypeError If the value is not a valid WeakRef target.
Sets multiple values at a single time. The format is an array of array
or rather an array of Object.entries (for example,
[[key1,value1], [key2,value2]]
). For each entry pair, if the length
is not 2, either missing a key or value, it will be skipped.
entries
values
Iterable An iterable of values to add to the RefMap.
- Throws TypeError If the supplied values are falsey or non-iterable.
Returns RepMap returns this
to allow for chaining
Removes all elements from the RefMap that have been garbage collected (i.e., their WeakRef no longer points to an object).
Returns RefMap The current RefMap instance to allow method chaining.
Executes a provided function once for each value in the RefMap. The callback function receives the dereferenced value, the value again (as RefMap doesn't use keys), and the RefMap itself. This method provides a way to iterate over and apply operations to the values stored in the RefMap, taking into account that they are weak references and may have been garbage-collected.
forEachFn
Function Function to execute for each element. It takes three arguments: element, element (again, as RefMap has no key), and the RefMap itself.thisArg
any Value to use asthis
when executingforEachFn
.
Iterate over the items in the map and pass them to the supplied
function ala Map.prototype.forEach
. Note however, there are no
indexes on Maps and as such, the index parameter of the callback
will always be the value's key. Subsequently the array
or third
parameter will receive the map instance rather than an array.
forEachFn
function the function to use for each element in the set.thisArg
object thethis
argument to be applied to each invocation of theforEachFn
callback. Note, this value is unable to be applied if theforEachFn
is a big arrow function
Returns an iterator for the values in the RefMap. Each value is dereferenced from its WeakRef before being returned. This method allows iterating over he set's values, similar to how one would iterate over values in a standard Map or Array, but with the understanding that the values are weakly referenced and may no longer exist (in which case they are skipped).
Returns Iterator An iterator for the values.
Determines whether an element with the specified value exists in the
RefMap
. For non-objectified sets, this method checks if the dereferenced
values of the map include the specified value.
For objectified sets, strict is set to false which uses loose
equality to allow for things like Object(5)
to equal 5
. This is important
because otherwise primitives could not be weakly referenced. In the grand
scheme of things, this is only useful if the objectified value is the
one being referenced.
value
any The value to check for presence in the RefMap.strict
boolean iftrue
, the default, then the supplied value is hard compared to the dereferenced value (===
). Iffalse
, then a loose comparison is used (==
) (optional, defaulttrue
)
Returns boolean True if an element with the specified value exists in the RefMap, false otherwise.
The filter
function filters the entries of a RefMap
object based on
a given filter function. The dereferenced entries of the values of the map
will be passed to the function rather than a WeakRef
itself.
A new resulting entry set will be generated and a new RefMap
will be made
from these entries and returned. Note that this function never returns
null
filterFn
function ThefilterFn
parameter is a function that will be used to filter the entries in theRefMap
. It will be called with three arguments: the value of the current entry, the key of the current entry, and theRefMap
itself. The function should returntrue
thisArg
object ThethisArg
parameter is an optional argument that specifies the value to be used asthis
when executing thefilterFn
function. It allows you to explicitly set the context in which thefilterFn
function is called. IfthisArg
is not provided, `this
Returns array The filter
method is returning an array of filtered map
entries
The find
function iterates over a map and calls a given function on
each value, returning the first value for which the function returns
a truthy value.
The function signature of findFn
is
function findFn(value, key, map)
'value' is passed to findFn up to two times; first with the WeakRef
value, second with the result of WeakRef.deref. If findFn
returns true for either of these the dereferenced value will be
returned from the call to RefMap.find.
key
represents the key object that the value is mapped to.
map
is simply a reference to this
map.
findFn
findFn
is a function that will be called for each element in the map. It takes three arguments:ref
,key
, andmap
; whereref
is the value of the current element in the map,key
is the key of the current element, andmap
is a reference to the instance being searched.thisArg
ThethisArg
parameter is the value to be used as thethis
value when executing thefindFn
function. It allows you to specify the context in which thefindFn
function should be called.
Returns any the first dereferenced value that satisfies the condition
specified by the findFn
function. If no value satisfies the condition,
it returns null
.
Creates a new array or RefMap
with the results of calling a provided
function on every element in the calling RefMap
. This method dereferences
each value, applies the mapFn
, and collects the results. If toRefMap
is
true
, a new RefMap
is returned; otherwise, an array. This method
differs from Array.map
in handling weak references and the potential to
return a new RefMap
instead of an array.
mapFn
Function Function that produces an element of the new array orRefMap
, taking three arguments.thisArg
any Value to use as this when executing mapFn.toRefMap
boolean Determines if the output should be a newRefMap
(true
) or an array (false
).mirrorObjectification
boolean Iftrue
andtoRefMap
istrue
, the newRefMap
mirrors the objectification setting of the original.
Returns (Array | RefMap) A new array or RefMap
with each element being
the result of the mapFn
.
The function returns an iterator that iterates over the entries of an object, dereferencing any weak references.
Returns Iterator A new iterator object is being returned.
Ensures that the constructor of this object instance's name is returned if the string tag for this instance is queried
Returns string the name of the class
A static method to check if a given value is a valid target for a WeakRef.
value
any The value to check for validity as a WeakRef target.
Returns boolean True if the value is a valid WeakRef target, false otherwise.
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.
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.
When the Deferred is settled with Deferred.resolve, the value
passed to that function will be set here as well.
Type: any
When the Deferred is settled with Deferred.reject, the reason
passed to that rejection will also be stored here.
Type: any
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
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.
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.
value
any The value to resolve the Deferred with.
Returns Promise A Promise that is resolved with the given value.
Rejects the Deferred with the given reason. This function behaves the same as Promise.reject. The Deferred will be rejected with the provided reason.
reason
any The reason to reject the Deferred with.
Returns Promise A Promise that is rejected with the given reason.
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.
The promise backing this deferred object. Created when the constructor
runs, this promise is what all Promise.prototype
functions are routed
to.
Type: Promise
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
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
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
The AsyncIterable class extends the concept of Iterable to asynchronous operations. It allows creating iterable objects where each element can be an asynchronous entity, like a Promise. This class is particularly useful when dealing with asynchronous data sources, such as API responses, file reading in chunks, or any other data that is not immediately available but arrives over time.
elementsOrFirstElement
(Iterable | AsyncGeneratorFunction | Promise | any) An iterable object, an async generator function, a Promise, or the first element.moreElements
...(Promise | any) Additional elements if the first argument is not an iterable or an async generator function.
Implements the async iterable protocol. When an instance of AsyncIterable
is used in a for await...of
loop, this async generator function is
invoked. It yields each element as a Promise, allowing asynchronous
iteration. Elements that are not Promises are automatically wrapped in
a resolved Promise to ensure consistency.
Returns AsyncGenerator An async generator that yields each element as a Promise.
Ensures that the constructor of this object instance's name is returned if the string tag for this instance is queried
Returns string the name of the class
Checks if a given value is an async iterable. This method determines if
the provided value has a Symbol.asyncIterator
property that is an async
generator function. It's a precise way to identify if the value conforms
to the async iterable protocol using an async generator function.
Note: This method specifically checks for async generator functions. Some async iterables might use regular async functions that return an async iterator, which this method won't identify.
value
any The value to be checked for async iterability.
Returns boolean Returns true if the value is an async iterable implemented using an async generator function, false otherwise.
Being able to create a compliant AsyncIterator
around any type of
iterable object. This can be wrapped around any type of object that
has a [Symbol.asyncIterator]
property assigned to a generator
function.
asyncIterable
(object | AsyncGeneratorFunction) any object that has a[Symbol.asyncIterable]
property assigned to a generator function or an async generator function itself.
Returns a new Array
derived from the iterable this object
wraps.
Returns array a new Array
generated from the wrapped
iterable. The method is generated from using an async for of
loop.
Returns the actual iterable object passed to the constructor that created this instance.
Returns object the object containing the [Symbol.iterator]
The function retrieves the next value in the iterator. If the
the iterator has run its course, reset()
can be invoked to
reset the pointer to the beginning of the iteration.
Returns any the next value
Resets the async iterator to the beginning allowing it to be iterated over again.
The existence of this symbol on the object instances, indicates that
it can be used in for(.. of ..)
loops and its values can be
extracted from calls to Array.from()
Returns AsyncIterable this is returned since this object is already conforming to the expected JavaScript AsyncIterator interface
Ensures that the constructor of this object instance's name is returned if the string tag for this instance is queried
Returns string the name of the class
The Iterable class is designed to provide a convenient way to create synchronous
iterable objects. It can be initialized with either an array or individual elements.
This class implements the iterable protocol, allowing instances to be used with
for...of
loops and other standard JavaScript iteration mechanisms.
elementsOrFirstElement
(Iterable | any) An iterable object or the first element.moreElements
...any Additional elements if the first argument is not an iterable.
Implements the iterable protocol. When an instance of Iterable is used
in a for...of
loop or spread syntax, this generator function is invoked
to yield the elements one by one in a synchronous manner.
Returns Generator A generator that yields each element of the iterable.
Provides access to the elements as a standard array. Useful for scenarios where array methods and behaviors are needed.
Returns Array An array containing all the elements of the iterable.
Ensures that the constructor of this object instance's name is returned if the string tag for this instance is queried
Returns string the name of the class
Checks if a given value is an iterable. This method determines if the
provided value has a Symbol.iterator
property that is a generator
function. It's a precise way to identify if the value conforms to the
iterable protocol using a generator function.
Note: This method specifically checks for generator functions. Some iterables might use regular functions that return an iterator, which this method won't identify.
value
any The value to be checked for iterability.
Returns boolean Returns true if the value is an iterable implemented using a generator function, false otherwise.
Being able to create a compliant Iterator
around any type of iterable
object. This can be wrapped around any type of object that has a
[Symbol.iterator]
property assigned to a generator function.
iterable
object any object that has a[Symbol.iterator]
property assigned to a generator function.mapEach
function when providedmapEach
is a callback that takes an entry as input and receives one as output.
Returns a new Array
derived from the iterable this object
wraps.
Returns array a new Array
generated from the wrapped
iterable. The method is generated from Array.from()
Returns the actual iterable object passed to the constructor that created this instance.
Returns object the object containing the [Symbol.iterator]
The function retrieves the next value in the iterator. If the
the iterator has run its course, reset()
can be invoked to
reset the pointer to the beginning of the iteration.
Returns any the next value
Resets the iterator to the beginning allowing it to be iterated over again.
The existence of this symbol on the object instances, indicates that
it can be used in for(.. of ..)
loops and its values can be
extracted from calls to Array.from()
Returns Iterator this is returned since this object is already conforming to the expected JavaScript Iterator interface
Ensures that the constructor of this object instance's name is returned if the string tag for this instance is queried
Returns string the name of the class
A private function that when provided has the following signature:
function mapEach(entry) -> entry
. This allows any changes to be made
to each element, conditionally and programmatically, as needed before
they are returned to the called code.
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.
@nejs/basic-extensions is licensed under the MIT License. See the LICENSE file for more details.