项目作者: blond

项目描述 :
:hash: Set with custom equality comparisons
高级语言: JavaScript
项目地址: git://github.com/blond/hash-set.git
创建时间: 2016-02-29T22:56:43Z
项目社区:https://github.com/blond/hash-set

开源协议:MIT License

下载


hash-set

NPM Status
Travis Status
Coverage Status

The original Set uses Same-value-zero equality.

Use this package if you need custom comparison behavior.

Install

  1. $ npm install --save hash-set

Usage

  1. import hashSet from 'hash-set';
  2. // Create Set class which compares objects with JSON.stringify
  3. const JSONSet = hashSet(JSON.stringify);
  4. // Create instance of JSONSet
  5. const mySet = new JSONSet();
  6. mySet.add({ a: 1 });
  7. mySet.add({ b: 2 });
  8. mySet.has({ a: 1 }); // true
  9. mySet.has({ b: 2 }); // true
  10. mySet.has({ c: 3 }); // false, `{ c: 3 }` has not been added to the set
  11. mySet.size; // 2
  12. mySet.delete({ a: 1 }); // removes `{ a: 1 }` from the set
  13. mySet.has({ a: 1 }); // false, `{ a: 1 }` has been removed
  14. mySet.size; // 1

API

hashSet(hashFn)

Returns Set class with custom equality comparisons.

hashFn

Type: function

The function to determine the unique of value.

HashSet executes a provided function every time you call add(value), has(value), delete(value).

The result of hashFn(value) will be used for comparison with the values of HashSet. For comparison will be used Same-value-zero.

Example

  1. const mySet = new Set();
  2. mySet.add(1); // value has been added to the set
  3. mySet.add('1'); // value has been added to the set
  4. // because `Object.is(1, '1')` is `false`
  5. console.log(mySet); // Set { 1, '1' }
  1. import hashSet from 'hash-set';
  2. function hashFn(value) {
  3. return value.toString();
  4. }
  5. const StringSet = hashSet(hashFn);
  6. const mySet = new StringSet();
  7. mySet.add(1); // value has been added to the set
  8. mySet.add('1'); // value has not been added to the set
  9. // because `Object.is(hashFn(1), hashFn('1'))` is `true`
  10. console.log(mySet); // Set { 1 }

License

MIT © Andrew Abramov