{"name":"heap-js","version":"1.2.2","keywords":["heap","binary heap","priority queue","tree","binary tree","data structure","algorithm","typescript"],"author":{"name":"Ignacio Lago @ignlg","email":"ignacio@ignaciolago.com"},"license":"BSD-3-Clause","_id":"heap-js@1.2.2","maintainers":[{"name":"ignlg","email":"ignacio@ignaciolago.com"}],"homepage":"https://github.com/ignlg/heap-js#readme","bugs":{"url":"https://github.com/ignlg/heap-js/issues"},"dist":{"shasum":"33b920bcb59e8880831b1d8f1a87b4ef29178bb5","tarball":"http://registry-npm.ywwl.com/heap-js/download/heap-js-1.2.2.tgz","integrity":"sha512-7s6UOLLmzmDhuWhVv3+LzwWsGbTXDbHIP9LvCp/ij0d0dTNicW7BojFM1JT8q8hZGLEDhq2gU0qyKc8wv4WJnA==","signatures":[{"sig":"MEQCIFIM817Qz/Fzm5OhbF2qwTTI3tL/FGhnKBE2BcYBiisaAiAqKppwj64pP+wrFa3kEK212i2ht/3Vxxjjw4tEZVf3fw==","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"size":632183,"noattachment":false,"key":"/heap-js/-/heap-js-1.2.2.tgz"},"jest":{"testRegex":"(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$","transform":{".(ts|tsx)":"<rootDir>/node_modules/ts-jest/preprocessor.js"},"mapCoverage":true,"coverageThreshold":{"global":{"lines":95,"branches":90,"functions":95,"statements":95}},"moduleFileExtensions":["ts","tsx","js"],"coveragePathIgnorePatterns":["/node_modules/"]},"main":"dist/heap-js.umd.js","files":["dist"],"types":"dist/types/heap-js.d.ts","config":{"commitizen":{"path":"node_modules/cz-conventional-changelog"},"validate-commit-msg":{"types":"conventional-commit-types","helpMessage":"Use \"yarn commit\" instead, we use conventional-changelog format :) (https://github.com/commitizen/cz-cli)"}},"module":"dist/heap-js.es5.js","engines":{"node":">=6.0.0"},"gitHead":"f7d63c546134da5332245835ca24b0ecaf6f3cfb","scripts":{"lint":"tslint --type-check --fix --project tsconfig.json -t codeFrame 'src/**/*.ts'","test":"jest","build":"tsc --project tsconfig.build.json && rollup -c && rimraf compiled && typedoc --out dist/docs --target es6 --theme minimal src","start":"tsc-watch --onSuccess \"rollup -c\"","commit":"git-cz","prebuild":"rimraf dist","precommit":"lint-staged","test:prod":"yarn lint && yarn test -- --coverage --no-cache","test:watch":"jest --watch","report-coverage":"cat ./coverage/lcov.info | coveralls"},"_npmUser":{"name":"ignlg","email":"ignacio@ignaciolago.com"},"repository":{"url":"git+ssh://git@github.com/ignlg/heap-js.git","type":"git"},"_npmVersion":"5.3.0","description":"Heap data structure for JavaScript.","directories":{},"lint-staged":{"src/**/*.ts":["prettier --write --no-semi","git add"]},"_nodeVersion":"8.1.4","devDependencies":{"jest":"^20.0.4","husky":"^0.14.3","rimraf":"^2.6.1","rollup":"^0.43.1","tslint":"^5.4.3","ts-jest":"^20.0.6","ts-node":"^3.0.6","typedoc":"^0.7.1","prettier":"^1.4.4","coveralls":"^2.13.1","cross-env":"^5.0.1","tsc-watch":"^1.0.5","commitizen":"^2.9.6","typescript":"^2.3.4","@types/jest":"^20.0.0","@types/node":"^8.0.0","lint-staged":"^4.0.0","lodash.camelcase":"^4.3.0","validate-commit-msg":"^2.12.2","rollup-plugin-commonjs":"^8.0.2","tslint-config-prettier":"^1.1.0","tslint-config-standard":"^6.0.0","rollup-plugin-sourcemaps":"^0.4.2","cz-conventional-changelog":"^2.0.0","rollup-plugin-node-resolve":"^3.0.0"},"_npmOperationalInternal":{"tmp":"tmp/heap-js-1.2.2.tgz_1501167834527_0.436946441186592","host":"s3://npm-registry-packages"},"readme":"# ![Heap.js](assets/heap-js.png) Heap.js\n\n[![npm version](https://img.shields.io/npm/v/heap-js.svg?style=flat)](https://www.npmjs.com/package/heap-js)\n[![Coverage Status](https://img.shields.io/coveralls/ignlg/heap-js/master.svg?style=flat)](https://coveralls.io/github/ignlg/heap-js?branch=master)\n\n**Efficient Binary heap (priority queue, binary tree) data structure for JavaScript / TypeScript.**\n\n**Now with support for async comparators with the new `HeapAsync` class!**\n\nIncludes JavaScript methods, Python's _heapq module_ methods, and Java's _PriorityQueue_ methods.\n\nEasy to use, known interfaces, tested, and well-documented JavaScript binary heap library.\n\nInstances are `integer min heap` by default.\n\n[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/ignlg/heap-js)\n\n## Is it faster than sorting an array?\n\nIt depends on your usage, but for some scenarios, it is much faster:\n\n```\nheap vs array: push + pop/unshift 50\n heap  x 72,130 ops/sec ±0.50% (93 runs sampled)\n array x 121 ops/sec ±78.09% (5 runs sampled)\n\nheap vs array: push + peek 20\n heap  x 622,332 ops/sec ±27.93% (63 runs sampled)\n array x 207 ops/sec ±78.18% (5 runs sampled)\n\nheap vs array: push + top(1) of 100\n heap  x 124,835 ops/sec ±40.37% (61 runs sampled)\n array x 123 ops/sec ±78.49% (5 runs sampled)\n\nheap vs array: push + top(50) of 100\n heap  x 59,210 ops/sec ±17.66% (82 runs sampled)\n array x 125 ops/sec ±78.79% (5 runs sampled)\n```\n\n## Star History\n\n[![Star History Chart](https://api.star-history.com/svg?repos=ignlg/heap-js&type=Date)](https://star-history.com/#ignlg/heap-js&Date)\n\n## Changelog\n\n### 2.7.1\n\n- Optimize loop condition in HeapAsync init method.\n\n### 2.7\n\n- Improves performance of sorting methods. Thanks to @BeatsuDev for the contribution.\n- Improves tests and documentation.\n\n### 2.6\n\n- Improves performance of remove and sorting methods.\n- Improves tests and documentation.\n\n### 2.5\n\n- Improves the `limit` property to support negative, Infinity, and NaN values. They will be set as `0` and the heap will not be limited.\n- Adds the `setLimit` method to set the limit of the heap. It returns `NaN` if the limit is negative, or NaN. This method is useful to check if the limit was set as expected.\n- Improves tests and documentation.\n\n### 2.4\n\n- Adds the `indexOf` method to find the first index of an element in the heap.\n- Adds the `indexOfEvery` method to find all indexes of an element in the heap.\n- Changes the `remove` method to use the `indexOf` method.\n- Changes the `contains` method to use the `indexOf` method.\n- Improves documentation.\n\n### 2.3\n\n- Adds the `HeapAsync` class, with async methods and supporting async comparators. It is a drop-in replacement for the `Heap` class with Promises.\n\n### 2.2\n\n- Fixes `.iterator()` method to follow [Java's PriorityQueue implementation:\n](https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueue.html)\n  > The Iterator provided in method [iterator()](<https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueue.html#iterator()>) is not guaranteed to traverse the elements of the priority queue in any particular order.\n\nNotice that _using the heap directly as an iterator will consume the heap,_ as Python's `heapq` implementation does.\n\n### 2.1\n\n- Adds `Heap.nlargest` as in `heapq`.\n- Adds `Heap.nsmallest` as in `heapq`.\n- Sanitizes `top` / `bottom` input to force an integer.\n- Linted with Eslint.\n\n### 2.0\n\nThe main breaking change is that now _`top(N)` does NOT sort the output_, because sorting should not be part of the spec for a priority queue. The output is the top N elements, and they will be _partially ordered_ with the peek at index `0` by definition.\n\n- `top(N)` is unordered, only the first element is guaranteed to be the top priority element.\n- Fixes custom heap issue [#31](https://github.com/ignlg/heap-js/issues/31).\n- Performance improvements.\n- More tests, including those for custom heaps.\n- Auxiliary experimental `top(N)` algorithms.\n- (WIP) Benchmarks.\n\n### 1.5\n\n- Adds the `Iterator` interface and `iterator()` method.\n\n## Examples\n\n### Basic usage\n\n#### Min Heap\n\nA heap where the smallest element is always at the top. It is the default heap.\n\n```js\nimport { Heap } from 'heap-js';\n\n// Min Heap by default\nconst minHeap = new Heap();\n\n// Initialize the heap with an array\nminHeap.init([5, 18, 1]);\n// Push a new value\nminHeap.push(2);\n\nconsole.log(minHeap.peek()); //> 1\nconsole.log(minHeap.pop()); //> 1\nconsole.log(minHeap.peek()); //> 2\n```\n\n#### Max Heap\n\nA heap where the largest element is always at the top.\n\n```js\nimport { Heap } from 'heap-js';\n\n// Max Heap\nconst maxHeap = new Heap(Heap.maxComparator);\n\n// Initialize the heap with an array\nmaxHeap.init([3, 4, 1, 12, 8]);\n// Push a new value\nmaxHeap.push(2);\n\nconsole.log(maxHeap.peek()); //> 12\nconsole.log(maxHeap.pop()); //> 12\nconsole.log(maxHeap.peek()); //> 8\n```\n\n#### Custom Heap\n\nA heap where the most important element is always at the top, but the elements are objects with a `priority` property.\n\n```js\nimport { Heap } from 'heap-js';\n\nconst customPriorityComparator = (a, b) => a.priority - b.priority;\n// Custom Heap\nconst customHeap = new Heap(customPriorityComparator);\n\n// Initialize the heap with an array\ncustomHeap.init([{ priority: 5 }, { priority: 18 }, { priority: 1 }]);\n// Push a new value\ncustomHeap.push({ priority: 2 });\n\nconsole.log(customHeap.peek()); //> { priority: 1 }\nconsole.log(customHeap.pop()); //> { priority: 1 }\nconsole.log(customHeap.peek()); //> { priority: 2 }\n```\n\n#### Min HeapAsync\n\nA heap where the most important element is always at the top, the elements are objects with a `priority` property, and the comparator function is asynchronous. Implements the same interface as `Heap`, but almost all methods return a `Promise`.\n\n```js\nimport { HeapAsync } from 'heap-js';\n\nconst customPriorityComparator = (a, b) => Promise.resolve(a.priority - b.priority);\n// Custom HeapAsync\nconst customHeap = new HeapAsync(customPriorityComparator);\n\n// Initialize the heap with an array\nawait customHeap.init([{ priority: 5 }, { priority: 18 }, { priority: 1 }]);\n// Push a new value\nawait customHeap.push({ priority: 2 });\n\nconsole.log(customHeap.peek()); //> { priority: 1 }\nconsole.log(await customHeap.pop()); //> { priority: 1 }\nconsole.log(await customHeap.peek()); //> { priority: 2 }\n```\n\n### Priority Queue usage\n\n#### JavaScript / Python-style iterator (recommended)\n\nIterates over the heap consuming it, and guarantees to traverse the elements of the heap in the order of priority. Useful.\n\n```js\nconst { Heap } = require('heap-js');\n\n// Get all tasks from the database\nconst tasks = db.collection.find().toArray();\n// The most important task has the lowest priority value\nconst customPriorityComparator = (a, b) => a.priority - b.priority;\n\n// Create the priority queue\nconst priorityQueue = new Heap(customPriorityComparator);\n// Initialize the priority queue with the tasks\npriorityQueue.init(tasks);\n\n// Iterator that will consume the heap while traversing it in the order of priority\nfor (const task of priorityQueue) {\n  console.log(task);\n}\n```\n\n#### Java-style iterator (not recommended)\n\nIterates over the heap without consuming it, but does not guarantee to traverse the elements of the heap in any particular order. Barely useful.\n\n```js\nconst { Heap } = require('heap-js');\n\n// Get all tasks from the database\nconst tasks = db.collection.find().toArray();\n// The most important task has the lowest priority value\nconst customPriorityComparator = (a, b) => a.priority - b.priority;\n\nconst priorityQueue = new Heap(customPriorityComparator);\n// Initialize the priority queue with the tasks\npriorityQueue.init(tasks);\n\n// Iterator, the Java way, that will not consume the heap BUT does not guarantee to traverse the elements of the heap in any particular order. Barely useful.\nfor (const task of priorityQueue.iterator()) {\n  console.log(task);\n}\n```\n\n### Python-like static methods\n\n```js\nimport { Heap } from 'heap-js';\nconst numbers = [2, 3, 7, 5];\n\n// Changes the array elements order into a heap in-place\nHeap.heapify(numbers);\nconsole.log(numbers); //> [ 2, 3, 5, 7 ]\n\n// Pushes a new value to the heap\nHeap.heappush(numbers, 1);\nconsole.log(numbers); //> [ 1, 2, 5, 7, 3 ]\n```\n\n## Installation\n\n```bash\nyarn add heap-js # if you use yarn\n\nnpm install --save heap-js # if you use npm\n```\n\n## Constructor\n\n### Heap\n\n```js\nnew Heap([comparator]);\n```\n\n### HeapAsync\n\n```js\nnew HeapAsync([asyncComparator]);\n```\n\n## Comparators already included\n\n- `Heap.minComparator`: Uses less-than operator to compare elements. It is the default comparator.\n- `Heap.maxComparator`: Uses greater-than operator to compare elements.\n- `Heap.minComparatorNumber`: Uses subtraction `a - b` to compare elements.\n- `Heap.maxComparatorNumber`: Uses subtraction `b - a` to compare elements.\n\n## Implements JavaScript-style methods\n\n- `for (const value of heap)` directly usable as an Iterator, **consumes the heap.**\n- `length` of the heap.\n- `limit` the number of elements in the heap.\n- `pop()` the top element.\n- `push(...elements)` one or more elements to the heap.\n- `pushpop(element)` faster than `push` & `pop`.\n- `replace(element)` faster than `pop` & `push`.\n- `top(number?)` most valuable elements from the heap.\n- `bottom(number?)` least valuable elements from the heap.\n- `indexOf(element, fn?)` returns the internal index of the first occurrence of the element in the heap.\n- `indexOfEvery(element, fn?)` returns an array with the internal indexes of all occurrences of the element in the heap.\n\n## Implements Java's `PriorityQueue` interface\n\n- `add(element)` to the heap.\n- `addAll([element, element, ... ])` to the heap, faster than loop `add`.\n- `clear()`\n- `clone()`\n- `comparator()`\n- `contains(element, fn?)`\n- _`element()` alias of `peek()`_\n- `isEmpty()`\n- `iterator()` returns the same as `toArray()` because it is iterable and follows Java's implementation. Barely useful. Use `for (const value of heap)` instead.\n- _`offer(element)` alias of `add(element)`_\n- `peek()`\n- _`poll()` alias of `pop()`_\n- `remove(element?)`\n- _`removeAll()` alias of `clear()`_\n- _`size()` alias of `length`_\n- `toArray()`\n- `toString()`\n\nTo do:\n\n- `containsAll`\n- `equals`\n- `retainAll`\n\n## Implements static Python's `heapq` interface\n\n- `Heap.heapify(array, comparator?)` that converts an array to an array-heap.\n- `Heap.heappop(heapArray, comparator?)` that takes the peek of the array-heap.\n- `Heap.heappush(heapArray, item, comparator?)` that appends elements to the array-heap.\n- `Heap.heappushpop(heapArray, item, comparator?)` faster than `heappush` & `heappop`.\n- `Heap.heapreplace(heapArray, item, comparator?)` faster than `heappop` & `heappush`.\n- `Heap.nlargest(n, iterable, comparator?)` that gets the `n` most valuable elements of an iterable.\n- `Heap.nsmallest(n, iterable, comparator?)` that gets the `n` least valuable elements of an iterable.\n\nExtras:\n\n- `Heap.heaptop(n, heapArray, comparator?)` that returns the `n` most valuable elements of the array-heap\n- `Heap.heapbottom(n, heapArray, comparator?)` that returns the `n` least valuable elements of the array-heap\n\nTo do:\n\n- `merge(...iterables, comparator?)`\n\n## Documentation\n\n<https://ignlg.github.io/heap-js/>\n\n## Sponsor\n\nWe are looking for sponsors to help us maintain and improve **Heap.js**. If you're interested in supporting this project, please get in touch with us.\n\n## Collaborate\n\nWould you like to contribute to **Heap.js**? Feel free to submit a pull request, open an issue, or reach out to the maintainers. We welcome your feedback and ideas!\n\n### Dev setup\n\n```bash\nyarn\n```\n\n### Tests\n\n```bash\nnpm run test\n```\n\n### Benchmarks\n\n```bash\nnpm run benchmarks\n```\n\n### License\n\nHeap.js is [BSD 3-Clause Licensed](LICENSE).\n","publish_time":1501167836049,"_cnpm_publish_time":1501167836049,"dist-tags":{"latest":"2.7.1"}}