{"name":"heap-js","version":"2.1.5","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@2.1.5","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":"43251ecdd23c632653fe783bc8bdc2b7da4baf4c","tarball":"http://registry-npm.ywwl.com/heap-js/download/heap-js-2.1.5.tgz","fileCount":6,"integrity":"sha512-zJeFH1ZxUHuYG6x9+a8Dy+5kjqbKk1K8yPI1KZEdsi18VCd0UjTyJ2u9PfuIoj7t3+saMmI132rJGV33tP52VQ==","signatures":[{"sig":"MEYCIQDhRhPB6HAGl4ZaFO1qLjFhJjYe5cySP/SfXmIh86t5swIhAINFWCR3D/YcBRVXqAXpDrZC9/oSKQrFrTVO2au4L0U8","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":87607,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgXdcQCRA9TVsSAnZWagAABEAP/R6R+h/S2LtWKUfbgMit\n3loeiWAO3pfV//coJGjW6dGOpOp6Vrqagbi5zTQA4sS+YSWemh0j50R0JCYo\n3GVrs9Ilwqb9Z2Z+1meyqFgqn5Dda57OtffOAfXFFMLNjnHzi3FxycnKDvM2\ntcPhZ13pbyBoPsbb9NioWNC7O3Gzg7YhR1RLdSEdRNUhfolPH2BCiS9layeC\nIAIUbxQGiw0Pv8x72mKNASi5iJf24g9RgN7IR8dkX5FgSUuQn3FXH3zrSvnp\nGWs6SrDLuVZlI/TAJJklM0hfO7ac9a0uUI6UpMCDE2Ih/iM2I6TONunROKa8\nZKkifxOVRF1/7cdNQryMBMnK+p1RCPn0xJNBeOwVZh1WbC+BM8frZCOZf0mg\n4qaScbI9VBDElzV6TJK1fXveqqWMHqrui5TsTjt0u6fOIPMxRDvolQka1bjI\nZcDfKbqSmojHZ394aKKzQ2QNGiYi4ZBThFjqr4pZPlo6tLfpt0uOG/z4dOIK\n/+KXGeax/YqRtiMLyKQD3j9Pz7O4fmOlrJgOMl7tGS/vALJswRhdfbxonqoU\nDFVcHEXb4MiDGuN0kJo+NNDOmj2DMcSwHJ305koq4DcAWm12L3zCGM1kMxa7\nbpoV+PYYvIWI4T13RurRN6KKfb1Ee7o+LpPcp9LeAb5AMt53x8eGG0SCalIs\nqFuC\r\n=4x3Z\r\n-----END PGP SIGNATURE-----\r\n","size":16592,"noattachment":false,"key":"/heap-js/-/heap-js-2.1.5.tgz"},"jest":{"testRegex":"(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$","transform":{".(ts|tsx)":"<rootDir>/node_modules/ts-jest"},"coverageThreshold":{"global":{"lines":100,"branches":100,"functions":100,"statements":100}},"moduleFileExtensions":["ts","tsx","js"],"coveragePathIgnorePatterns":["/node_modules/"]},"main":"dist/heap-js.umd.js","types":"dist/types/Heap.d.ts","module":"dist/heap-js.es5.js","engines":{"node":">=10.0.0"},"gitHead":"67864cca8a73f8a8a30e4e987a146691586aaff2","scripts":{"lint":"eslint --fix 'src/**/*.ts'","test":"jest --coverage --no-cache","build":"tsc --project tsconfig.build.json && rollup -c && rimraf compiled && typedoc","start":"tsc-watch --onSuccess \"rollup -c\"","prebuild":"rimraf dist","benchmark":"node benchmark/benchmark.js","precommit":"lint-staged","test:prod":"npm run lint && npm run test -- --coverage --no-cache","test:watch":"jest --watch","test:heapUsage":"node --expose-gc ./node_modules/.bin/jest --runInBand --logHeapUsage","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":"6.14.11","description":"Efficient Binary heap (priority queue, binary tree) data structure for JavaScript / TypeScript. Includes JavaScript methods, Python's heapq module methods, and Java's PriorityQueue methods.","directories":{},"lint-staged":{"src/**/*.ts":["eslint --fix","jest --coverage --no-cache"]},"_nodeVersion":"14.16.0","_hasShrinkwrap":false,"devDependencies":{"jest":"^26.6.3","husky":"^5.2.0","eslint":"7.22.0","rimraf":"^3.0.2","rollup":"^2.42.4","ts-jest":"^26.5.4","ts-node":"^9.1.1","typedoc":"^0.20.34","prettier":"^2.2.1","benchmark":"^2.1.4","coveralls":"^3.1.0","cross-env":"^7.0.3","tsc-watch":"^4.2.9","typescript":"^4.2.3","@types/jest":"^26.0.22","@types/node":"^14.14.36","lint-staged":"^10.5.4","prettier-eslint":"^12.0.0","@types/benchmark":"^2.1.0","lodash.camelcase":"^4.3.0","eslint-config-prettier":"^8.1.0","eslint-plugin-prettier":"^3.3.1","eslint-plugin-standard":"5.0.0","@rollup/plugin-commonjs":"^17.1.0","rollup-plugin-sourcemaps":"^0.6.3","@typescript-eslint/parser":"^4.19.0","@rollup/plugin-node-resolve":"^11.2.0","@typescript-eslint/eslint-plugin":"4.19.0"},"_npmOperationalInternal":{"tmp":"tmp/heap-js_2.1.5_1616762639799_0.6652407646121172","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":1616762640019,"_cnpm_publish_time":1616762640019,"dist-tags":{"latest":"2.7.1"}}