@kingjs/linq.default-select-id

Default id selector; Identity operator.

Stats

stars 🌟issues ⚠️updated 🛠created 🐣size 🏋️‍♀️
@kingjs/linq.default-select-id
Minified + gzip package size for @kingjs/linq.default-select-id in KB

Readme

@kingjs/linq.default-selectId

Default id selector; Identity operator.

Usage

Id selectors are used to identify objects when the default string conversion is insufficient. For example, implement a function remove duplicates from an array like this:

var defaultSelectId = require('@kingjs/linq.default-select-id');

function removeDuplicates(array, selectId) {
  var result = [];

  if (!selectId)
    selectId = defaultSelectId;

  var visited = { };
  for (var i = 0; i < array.length; i ++) {
    var value = array[i];

    var id = selectId(value);
    if (id in visited)
      continue;
    visited[id] = undefined;

    result.push(value);
  }

  return result;
}

This can be used to remove the duplicate 'Alice' record when records are:

  • strings and default string conversion is sufficient
  • objects with a name property and an idSelector is necessary

For example:

{
  asStrings: removeDuplicates([
    'Alice',
    'Alice',
    'Bob',
  ]),

  asObjects: removeDuplicates([
    { name: 'Alice' },
    { name: 'Alice' },
    { name: 'Bob' },
  ], function(x) { // without this, de-dup fails
    return x.name; 
  }),
}

result:

{
  asStrings: [ 
    'Alice', 
    'Bob' 
  ],
  asObjects: [
    { name: 'Alice' },
    { name: 'Bob' }
  ],
}

API

function defaultIdSelector(x: any): any

Parameters

  • x: The object whose id is to be selected.

Result

A value whose string representation identifies the object.

Remarks

LINQ set algorithms like union and except need to identify objects and so adopt the selectId pattern.

More Remarks

In C# all objects implement .GetHashCode and .Equals enabling any object can be used as the key to a dictionary.

In Javascript only strings may be used as keys. As such, an object used as a key to a dictionary needs to be converted to a string. When the default conversion may not suitable for this purpose, functions should allow callers to pass an idSelector.

Install

With npm installed, run

$ npm install @kingjs/link.default-equal

License

MIT

If you find any bugs or have a feature request, please open an issue on github!

The npm package download data comes from npm's download counts api and package details come from npms.io.