@stdlib/array-index
v0.3.0
Published
Array index constructor.
Downloads
284
Readme
ArrayIndex
Array index constructor.
In JavaScript, only strings and symbols are valid property names. When providing values for property names which are not string or symbols, the values are serialized to strings prior to attempting to access property values. For example, the following
// Create an array:
var x = [ 1, 2, 3, 4 ];
// Define a list of indices for elements we want to retrieve from `x`:
var y = [ 0, 2 ];
// Attempt to retrieve the desired elements:
var v = x[ y ]; // => desired: [ 1, 3 ]
// returns undefined
is equivalent to
var x = [ 1, 2, 3, 4 ];
var y = [ 0, 2 ];
var v = x[ y.toString() ];
// returns undefined
// ...which is equivalent to:
v = x[ '0,2' ];
// returns undefined
Accordingly, in order to circumvent built-in property access behavior and support non-traditional access patterns, one can leverage Proxy
objects which allow one to intercept property access and to perform transformations before attempting to access elements in a target object.
To support the access pattern shown in the example above, one can leverage built-in string serialization behavior to reconstruct the original property value provided prior to serialization. The ArrayIndex
constructor described below provides one such mechanism.
Specifically, instantiated ArrayIndex
objects are assigned a unique identifier and stored in a local cache. When provided as property values to ArrayIndex
consumers, instantiated objects serialize to a string containing their unique identifier. ArrayIndex
consumers can then parse the serialized string to obtain the unique identifier and subsequently recover the original array from the local cache.
Installation
npm install @stdlib/array-index
Usage
var ArrayIndex = require( '@stdlib/array-index' );
ArrayIndex( x[, options] )
Wraps a provided array as an array index object.
var x = [ 1, 2, 3, 4 ];
var idx = new ArrayIndex( x );
// returns <ArrayIndex>
The constructor accepts the following arguments:
- x: input array.
- options: function options.
The constructor accepts the following options:
- persist: boolean indicating whether to continue persisting an index object after first usage. Default:
false
.
By default, an ArrayIndex
is invalidated and removed from an internal cache immediately after a consumer resolves the underlying data associated with an ArrayIndex
instance using the ArrayIndex.get()
static method. Immediate invalidation and cache removal ensures that references to the underlying array are not the source of memory leaks.
One may, however, want to reuse an ArrayIndex
instance to avoid additional memory allocation. In order to persist an ArrayIndex
and prevent automatic cache invalidation, set the persist
option to true
.
var x = [ 1, 2, 3, 4 ];
var idx = new ArrayIndex( x, {
'persist': true
});
// returns <ArrayIndex>
// ...
var o = ArrayIndex.get( idx.id );
// returns {...}
// ...
o = ArrayIndex.get( idx.id );
// returns {...}
// ...
// Explicitly free the array index:
ArrayIndex.free( idx.id );
In order to prevent memory leaks when working with persisted ArrayIndex
instances, one must remember to manually free persisted instances using the ArrayIndex.free()
method.
Properties
ArrayIndex.name
String value of the ArrayIndex
constructor name.
var str = ArrayIndex.name;
// returns 'ArrayIndex'
ArrayIndex.prototype.data
Read-only property returning the underlying array associated with an ArrayIndex
instance.
var Uint8Array = require( '@stdlib/array-uint8' );
var idx = new ArrayIndex( new Uint8Array( [ 1, 0, 1, 0 ] ) );
// returns <ArrayIndex>
var v = idx.data;
// returns <Uint8Array>[ 1, 0, 1, 0 ]
ArrayIndex.prototype.dtype
Read-only property returning the data type of the underlying array associated with an ArrayIndex
instance.
var Uint8Array = require( '@stdlib/array-uint8' );
var idx = new ArrayIndex( new Uint8Array( [ 1, 0, 1, 0 ] ) );
// returns <ArrayIndex>
var dt = idx.dtype;
// returns 'uint8'
ArrayIndex.prototype.id
Read-only property returning the unique identifier associated with an ArrayIndex
instance.
var Uint8Array = require( '@stdlib/array-uint8' );
var idx = new ArrayIndex( new Uint8Array( [ 1, 0, 1, 0 ] ) );
// returns <ArrayIndex>
var id = idx.id;
// returns <string>
The identifier should be used by ArrayIndex
consumers to resolve the underlying data associated with an ArrayIndex
instance.
ArrayIndex.prototype.isCached
Read-only property returning a boolean indicating whether an ArrayIndex
instance is actively cached.
var Uint8Array = require( '@stdlib/array-uint8' );
var idx = new ArrayIndex( new Uint8Array( [ 1, 0, 1, 0 ] ) );
// returns <ArrayIndex>
var out = idx.isCached;
// returns true
ArrayIndex.prototype.type
Read-only property returning the array index type.
var Uint8Array = require( '@stdlib/array-uint8' );
var idx = new ArrayIndex( new Uint8Array( [ 1, 0, 1, 0 ] ) );
// returns <ArrayIndex>
var t = idx.type;
// returns 'mask'
The following array index types are supported:
- mask: mask array, in which a value of zero indicates to include a respective element and a value of one indicates to exclude a respective element. A mask array is the complement of a boolean array.
- bool: boolean array, in which a value of
true
indicates to include a respective element and a value offalse
indicates to exclude a respective element. A boolean array is the complement of a mask array. - int: integer array, in which each element is an index indicating the position of an element to include. Elements are not required to be unique (i.e., more than element may resolve to the same position).
Methods
ArrayIndex.free( id )
Frees the ArrayIndex
associated with a provided identifier.
var Uint8Array = require( '@stdlib/array-uint8' );
var idx = new ArrayIndex( new Uint8Array( [ 1, 0, 1, 0 ] ), {
'persist': true
});
// returns <ArrayIndex>
// ...
var out = ArrayIndex.free( idx.id );
// returns true
Once an ArrayIndex
is freed, the instance is invalid and can no longer be used. Any subsequent ArrayIndex
operations (i.e., property and method access) will raise an exception.
ArrayIndex.get( id )
Returns the array associated with the ArrayIndex
having a provided identifier.
var Uint8Array = require( '@stdlib/array-uint8' );
var idx = new ArrayIndex( new Uint8Array( [ 1, 0, 1, 0 ] ), {
'persist': true
});
// returns <ArrayIndex>
// ...
var o = ArrayIndex.get( idx.id );
// returns {...}
var d = o.data;
// returns <Uint8Array>[ 1, 0, 1, 0 ]
var t = o.type;
// returns 'mask'
var dt = o.dtype;
// returns 'uint8'
The returned object has the following properties:
- data: the underlying array associated with the
ArrayIndex
identified by the providedid
. - type: the type of array index. One of the following:
'int'
,'bool'
, or'mask'
. - dtype: the data type of the underlying array.
If the ArrayIndex
associated with a provided identifier was not explicitly persisted, calling this method will cause the ArrayIndex
to be invalidated and removed from an internal cache. Any subsequent instance operations (i.e., property and method access) will raise an exception.
ArrayIndex.prototype.toString()
Serializes an ArrayIndex
as a string.
var Uint8Array = require( '@stdlib/array-uint8' );
var idx = new ArrayIndex( new Uint8Array( [ 1, 0, 1, 0 ] ) );
// returns <ArrayIndex>
var str = idx.toString();
// e.g., 'ArrayIndex<0>'
An ArrayIndex
is intended to be an opaque object used by objects supporting "fancy" indexing (e.g., fancy arrays). As such, when serialized as a string, a serialized ArrayIndex
includes only the unique identifier associated with the respective instance.
ArrayIndex.prototype.toJSON()
Serializes an ArrayIndex
as a JSON object.
var Uint8Array = require( '@stdlib/array-uint8' );
var idx = new ArrayIndex( new Uint8Array( [ 1, 0, 1, 0 ] ) );
// returns <ArrayIndex>
var o = idx.toJSON();
// returns { 'type': 'ArrayIndex', 'data': { 'type': 'Uint8Array', 'data': [ 1, 0, 1, 0 ] } }
JSON.stringify()
implicitly calls this method when stringifying an ArrayIndex
instance.
Notes
ArrayIndex
instances have no explicit functionality; however, they are used by "fancy" arrays and other packages for element retrieval and assignment.Because
ArrayIndex
instances leverage an internal cache implementing the Singleton pattern, one must be sure to use the sameArrayIndex
constructor asArrayIndex
consumers. If one uses a differentArrayIndex
constructor, the consumer will not be able to resolve the original wrapped array, as the consumer will attempt to resolve anArrayIndex
instance in the wrong internal cache.Because non-persisted
ArrayIndex
instances are freed after first use, in order to avoid holding onto memory and to allow garbage collection, one should avoid scenarios in which anArrayIndex
is never used. For example,var Uint8Array = require( '@stdlib/array-uint8' ); var data = new Uint8Array( [ 1, 0, 0, 0 ] ); var idx = new ArrayIndex( data ); var o; if ( data[ 0 ] === 0 ) { // Do something with `idx`... o = ArrayIndex.get( idx.id ); // ... }
will leak memory as
idx
is only consumed within anif
block which never evaluates. In such scenarios, one should either refactor to avoid inadvertently holding onto memory or explicitly free theArrayIndex
.var Uint8Array = require( '@stdlib/array-uint8' ); var data = new Uint8Array( [ 1, 0, 0, 0 ] ); var idx = new ArrayIndex( data ); var o; if ( data[ 0 ] === 0 ) { // Do something with `idx`... o = ArrayIndex.get( idx.id ); // ... } else { ArrayIndex.free( idx.id ); }
Examples
var Uint8Array = require( '@stdlib/array-uint8' );
var Int32Array = require( '@stdlib/array-int32' );
var BooleanArray = require( '@stdlib/array-bool' );
var ArrayIndex = require( '@stdlib/array-index' );
var x = new Uint8Array( [ 1, 0, 1, 0 ] );
var i = new ArrayIndex( x );
// returns <ArrayIndex>
var o = ArrayIndex.get( i.id );
// returns {...}
console.log( 'Type: %s. Data type: %s.', o.type, o.dtype );
x = [ true, false, true, false ];
i = new ArrayIndex( x );
// returns <ArrayIndex>
o = ArrayIndex.get( i.id );
// returns {...}
console.log( 'Type: %s. Data type: %s.', o.type, o.dtype );
x = new BooleanArray( [ true, false, true, false ] );
i = new ArrayIndex( x );
// returns <ArrayIndex>
o = ArrayIndex.get( i.id );
// returns {...}
console.log( 'Type: %s. Data type: %s.', o.type, o.dtype );
x = new Int32Array( [ 1, 3, 4, 7 ] );
i = new ArrayIndex( x );
// returns <ArrayIndex>
o = ArrayIndex.get( i.id );
// returns {...}
console.log( 'Type: %s. Data type: %s.', o.type, o.dtype );
x = [ 1, 3, 4, 7 ];
i = new ArrayIndex( x );
// returns <ArrayIndex>
o = ArrayIndex.get( i.id );
// returns {...}
console.log( 'Type: %s. Data type: %s.', o.type, o.dtype );
See Also
@stdlib/array-to-fancy
: convert an array to an object supporting fancy indexing.
Notice
This package is part of stdlib, a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing. The library provides a collection of robust, high performance libraries for mathematics, statistics, streams, utilities, and more.
For more information on the project, filing bug reports and feature requests, and guidance on how to develop stdlib, see the main project repository.
Community
License
See LICENSE.
Copyright
Copyright © 2016-2024. The Stdlib Authors.