Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Array index constructor.

License

NotificationsYou must be signed in to change notification settings

stdlib-js/array-index

 
 

Repository files navigation

About stdlib...

We believe in a future in which the web is a preferred environment for numerical computation. To help realize this future, we've built stdlib. stdlib is a standard library, with an emphasis on numerical and scientific computation, written in JavaScript (and C) for execution in browsers and in Node.js.

The library is fully decomposable, being architected in such a way that you can swap out and mix and match APIs and functionality to cater to your exact preferences and use cases.

When you use stdlib, you can be absolutely certain that you are using the most thorough, rigorous, well-written, studied, documented, tested, measured, and high-quality code out there.

To join us in bringing numerical computing to the web, get started by checking us out onGitHub, and please considerfinancially supporting stdlib. We greatly appreciate your continued support!

ArrayIndex

NPM versionBuild StatusCoverage Status

Array index constructor.

In JavaScript, only strings and symbols are valid property names. When providing values for property names which are not strings or symbols, the values are serialized to stringsprior to attempting to access property values. For example, the following

// Create an array:varx=[1,2,3,4];// Define a list of indices for elements we want to retrieve from `x`:vary=[0,2];// Attempt to retrieve the desired elements:varv=x[y];// => desired: [ 1, 3 ]// returns undefined

is equivalent to

varx=[1,2,3,4];vary=[0,2];varv=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 leverageProxy 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. TheArrayIndex constructor described below provides one such mechanism.

Specifically, instantiatedArrayIndex objects are assigned a unique identifier and stored in a local cache. When provided as property values toArrayIndex 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.

Usage

To use in Observable,

ArrayIndex=require('https://cdn.jsdelivr.net/gh/stdlib-js/array-index@umd/browser.js')

To vendor stdlib functionality and avoid installing dependency trees for Node.js, you can use the UMD server build:

varArrayIndex=require('path/to/vendor/umd/array-index/index.js')

To include the bundle in a webpage,

<scripttype="text/javascript"src="https://cdn.jsdelivr.net/gh/stdlib-js/array-index@umd/browser.js"></script>

If no recognized module system is present, access bundle contents via the global scope:

<scripttype="text/javascript">(function(){window.ArrayIndex;})();</script>

ArrayIndex( x[, options] )

Wraps a provided array as an array index object.

varx=[1,2,3,4];varidx=newArrayIndex(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, anArrayIndex is invalidated and removed from an internal cache immediately after a consumer resolves the underlying data associated with anArrayIndex instance using theArrayIndex.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 anArrayIndex instance to avoid additional memory allocation. In order to persist anArrayIndex and prevent automatic cache invalidation, set thepersist option totrue.

varx=[1,2,3,4];varidx=newArrayIndex(x,{'persist':true});// returns <ArrayIndex>// ...varo=ArrayIndex.get(idx.id);// returns {...}// ...o=ArrayIndex.get(idx.id);// returns {...}// ...// Explicitly free the array index:ArrayIndex.free(idx.id);

In order toprevent memory leaks when working with persistedArrayIndex instances, onemust remember to manually free persisted instances using theArrayIndex.free() method.


Properties

ArrayIndex.name

String value of theArrayIndex constructor name.

varstr=ArrayIndex.name;// returns 'ArrayIndex'

ArrayIndex.prototype.data

Read-only property returning the underlying array associated with anArrayIndex instance.

varUint8Array=require('@stdlib/array-uint8');varidx=newArrayIndex(newUint8Array([1,0,1,0]));// returns <ArrayIndex>varv=idx.data;// returns <Uint8Array>[ 1, 0, 1, 0 ]

ArrayIndex.prototype.dtype

Read-only property returning the data type of the underlying array associated with anArrayIndex instance.

varUint8Array=require('@stdlib/array-uint8');varidx=newArrayIndex(newUint8Array([1,0,1,0]));// returns <ArrayIndex>vardt=idx.dtype;// returns 'uint8'

ArrayIndex.prototype.id

Read-only property returning the unique identifier associated with anArrayIndex instance.

varUint8Array=require('@stdlib/array-uint8');varidx=newArrayIndex(newUint8Array([1,0,1,0]));// returns <ArrayIndex>varid=idx.id;// returns <string>

The identifier should be used byArrayIndex consumers to resolve the underlying data associated with anArrayIndex instance.

ArrayIndex.prototype.isCached

Read-only property returning a boolean indicating whether anArrayIndex instance is actively cached.

varUint8Array=require('@stdlib/array-uint8');varidx=newArrayIndex(newUint8Array([1,0,1,0]));// returns <ArrayIndex>varout=idx.isCached;// returns true

ArrayIndex.prototype.type

Read-only property returning the array index type.

varUint8Array=require('@stdlib/array-uint8');varidx=newArrayIndex(newUint8Array([1,0,1,0]));// returns <ArrayIndex>vart=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 oftrue 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 arenot required to be unique (i.e., more than element may resolve to the same position).

Methods

ArrayIndex.free( id )

Frees theArrayIndex associated with a provided identifier.

varUint8Array=require('@stdlib/array-uint8');varidx=newArrayIndex(newUint8Array([1,0,1,0]),{'persist':true});// returns <ArrayIndex>// ...varout=ArrayIndex.free(idx.id);// returns true

Once anArrayIndex is freed, the instance is invalid and can no longer be used. Any subsequentArrayIndex operations (i.e., property and method access) will raise an exception.

ArrayIndex.get( id )

Returns the array associated with theArrayIndex having a provided identifier.

varUint8Array=require('@stdlib/array-uint8');varidx=newArrayIndex(newUint8Array([1,0,1,0]),{'persist':true});// returns <ArrayIndex>// ...varo=ArrayIndex.get(idx.id);// returns {...}vard=o.data;// returns <Uint8Array>[ 1, 0, 1, 0 ]vart=o.type;// returns 'mask'vardt=o.dtype;// returns 'uint8'

The returned object has the following properties:

  • data: the underlying array associated with theArrayIndex 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 theArrayIndex associated with a provided identifier was not explicitly persisted, calling this method will cause theArrayIndex 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 anArrayIndex as a string.

varUint8Array=require('@stdlib/array-uint8');varidx=newArrayIndex(newUint8Array([1,0,1,0]));// returns <ArrayIndex>varstr=idx.toString();// e.g., 'ArrayIndex<0>'

AnArrayIndex 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 serializedArrayIndex includes only the unique identifier associated with the respective instance.

ArrayIndex.prototype.toJSON()

Serializes anArrayIndex as aJSON object.

varUint8Array=require('@stdlib/array-uint8');varidx=newArrayIndex(newUint8Array([1,0,1,0]));// returns <ArrayIndex>varo=idx.toJSON();// returns { 'type': 'ArrayIndex', 'data': { 'type': 'Uint8Array', 'data': [ 1, 0, 1, 0 ] }}

JSON.stringify() implicitly calls this method when stringifying anArrayIndex instance.


Notes

  • ArrayIndex instances have no explicit functionality; however, they are used by"fancy" arrays and other packages for element retrieval and assignment.

  • BecauseArrayIndex instances leverage an internal cache implementing thesingleton pattern, onemust be sure to use the sameArrayIndex constructor asArrayIndex consumers. If one uses a differentArrayIndex constructor, the consumer willnot be able to resolve the original wrapped array, as the consumer will attempt to resolve anArrayIndex instance in the wrong internal cache.

  • Because non-persistedArrayIndex 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,

    varUint8Array=require('@stdlib/array-uint8');vardata=newUint8Array([1,0,0,0]);varidx=newArrayIndex(data);varo;if(data[0]===0){// Do something with `idx`...o=ArrayIndex.get(idx.id);// ...}

    will leak memory asidx 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.

    varUint8Array=require('@stdlib/array-uint8');vardata=newUint8Array([1,0,0,0]);varidx=newArrayIndex(data);varo;if(data[0]===0){// Do something with `idx`...o=ArrayIndex.get(idx.id);// ...}else{ArrayIndex.free(idx.id);}

Examples

<!DOCTYPE html><htmllang="en"><body><scripttype="text/javascript"src="https://cdn.jsdelivr.net/gh/stdlib-js/array-uint8@umd/browser.js"></script><scripttype="text/javascript"src="https://cdn.jsdelivr.net/gh/stdlib-js/array-int32@umd/browser.js"></script><scripttype="text/javascript"src="https://cdn.jsdelivr.net/gh/stdlib-js/array-bool@umd/browser.js"></script><scripttype="text/javascript"src="https://cdn.jsdelivr.net/gh/stdlib-js/array-index@umd/browser.js"></script><scripttype="text/javascript">(function(){varx=newUint8Array([1,0,1,0]);vari=newArrayIndex(x);// returns <ArrayIndex>varo=ArrayIndex.get(i.id);// returns {...}console.log('Type: %s. Data type: %s.',o.type,o.dtype);x=[true,false,true,false];i=newArrayIndex(x);// returns <ArrayIndex>o=ArrayIndex.get(i.id);// returns {...}console.log('Type: %s. Data type: %s.',o.type,o.dtype);x=newBooleanArray([true,false,true,false]);i=newArrayIndex(x);// returns <ArrayIndex>o=ArrayIndex.get(i.id);// returns {...}console.log('Type: %s. Data type: %s.',o.type,o.dtype);x=newInt32Array([1,3,4,7]);i=newArrayIndex(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=newArrayIndex(x);// returns <ArrayIndex>o=ArrayIndex.get(i.id);// returns {...}console.log('Type: %s. Data type: %s.',o.type,o.dtype);})();</script></body></html>

See Also


Notice

This package is part ofstdlib, 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 developstdlib, see the main projectrepository.

Community

Chat


License

SeeLICENSE.

Copyright

Copyright © 2016-2025. The StdlibAuthors.


[8]ページ先頭

©2009-2025 Movatter.jp