README
Object Inverse
Inverts an object, such that keys are values and values are keys.
Installation
$ npm install utils-object-inverse
Usage
var invert = require( 'utils-object-inverse' );
invert( obj[, opts] )
Inverts an object
, such that keys are values and values are keys.
var out = invert({
'a': 'beep',
'b': 'boop'
});
// returns {'beep':'a','boop':'b'}
The function accepts the following options:
- duplicates:
boolean
indicating whether to store keys mapped to duplicate values inarrays
. Default:true
.
By default, keys mapped to duplicate values are stored in arrays
.
var out = invert({
'a': 'beep',
'b': 'beep'
});
// returns {'beep':['a','b']}
To not allow duplicates, set the duplicates
option to false
. The output key-value
pair will be the key
most recently inserted into the input object
.
var obj = {};
obj.a = 'beep';
obj.b = 'boop';
obj.c = 'beep'; // inserted after `a`
var out = invert( obj, {
'duplicates': false
});
// returns {'beep':'c','boop':'b'}
Notes
Insertion order is not guaranteed, as
object
key enumeration is not specified according to the ECMAScript specification. In practice, however, most engines use insertion order to sort anobject
's keys, thus allowing for deterministic inversion.Beware when providing
objects
having values which are themselvesobjects
. This implementation relies on nativeobject
serialization (#toString
) when converting values to keys.var obj = { 'a': [1,2,3], 'b': {'c':'d'} }; var out = invert( obj ); // returns {'1,2,3':'a','[object Object]':'b'}
Examples
var invert = require( 'utils-object-inverse' );
var arr = new Array( 1000 ),
len = arr.length,
out,
i;
// Create an array of random integers...
for ( i = 0; i < len; i++ ) {
arr[ i ] = Math.round( Math.random()*100 );
}
// Invert the array to determine value frequency...
out = invert( arr );
keys = Object.keys( out );
len = keys.length;
for ( i = 0; i < len; i++ ) {
out[ i ] = out[ i ].length;
}
console.dir( out );
To run the example code from the top-level application directory,
$ node ./examples/index.js
Tests
Unit
Unit tests use the Mocha test framework with Chai assertions. To run the tests, execute the following command in the top-level application directory:
$ make test
All new feature development should have corresponding unit tests to validate correct functionality.
Test Coverage
This repository uses Istanbul as its code coverage tool. To generate a test coverage report, execute the following command in the top-level application directory:
$ make test-cov
Istanbul creates a ./reports/coverage
directory. To access an HTML version of the report,
$ make view-cov
License
Copyright
Copyright © 2015. Athan Reines.