Commit b807a4c1 authored by Wolfgang Knopki's avatar Wolfgang Knopki
Browse files

Merge branch 'revert-jul13' into 'testing'

Revert "Merge branch 'MLAB-677' into 'testing'"

See merge request !168
parents 81e73777 08d3a3ba
Pipeline #6895 passed with stage
in 16 seconds
var test = require('tape');
var equal = require('../');
test('NaN and 0 values', function (t) {
t.ok(equal(NaN, NaN));
t.notOk(equal(0, NaN));
t.ok(equal(0, 0));
t.notOk(equal(0, 1));
t.end();
});
test('nested NaN values', function (t) {
t.ok(equal([ NaN, 1, NaN ], [ NaN, 1, NaN ]));
t.end();
});
var test = require('tape');
var equal = require('../');
test('equal', function (t) {
t.ok(equal(
{ a : [ 2, 3 ], b : [ 4 ] },
{ a : [ 2, 3 ], b : [ 4 ] }
));
t.end();
});
test('not equal', function (t) {
t.notOk(equal(
{ x : 5, y : [6] },
{ x : 5, y : 6 }
));
t.end();
});
test('nested nulls', function (t) {
t.ok(equal([ null, null, null ], [ null, null, null ]));
t.end();
});
var test = require('tape');
var equal = require('../');
test('0 values', function (t) {
t.ok(equal( 0, 0), ' 0 === 0');
t.ok(equal( 0, +0), ' 0 === +0');
t.ok(equal(+0, +0), '+0 === +0');
t.ok(equal(-0, -0), '-0 === -0');
t.notOk(equal(-0, 0), '-0 !== 0');
t.notOk(equal(-0, +0), '-0 !== +0');
t.end();
});
## 2.0.1
- fix(types): incorrect return type on `size()`
## 2.0.0
- fix!: `push` & `unshift` now accept `undefined` values to match behaviour of `Array` (fixes #25) (#35)
- This is only a **BREAKING** change if you are currently expecting `push(undefined)` and `unshift(undefined)` to do
nothing - the new behaviour now correctly adds undefined values to the queue.
- **Note**: behaviour of `push()` & `unshift()` (no arguments) remains unchanged (nothing gets added to the queue).
- **Note**: If you need to differentiate between `undefined` values in the queue and the return value of `pop()` then
check the queue `.length` before popping.
- fix: incorrect methods in types definition file
## 1.5.1
- perf: minor performance tweak when growing queue size (#29)
## 1.5.0
- feat: adds capacity option for circular buffers (#27)
......
Copyright (c) 2018 Mike Diarmid (Salakar) <mike.diarmid@gmail.com>
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this library except in compliance with the License.
You may obtain a copy of the License at
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018-present Invertase Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
<p align="center">
<a href="https://invertase.io">
<img src="https://static.invertase.io/assets/invertase-logo-small.png"><br/>
</a>
<h2 align="center">Denque</h2>
<h1 align="center">Denque</h1>
</p>
<p align="center">
<a href="https://www.npmjs.com/package/denque"><img src="https://img.shields.io/npm/dm/denque.svg?style=flat-square" alt="NPM downloads"></a>
<a href="https://www.npmjs.com/package/denque"><img src="https://img.shields.io/npm/v/denque.svg?style=flat-square" alt="NPM version"></a>
<a href="https://travis-ci.org/Salakar/denque"><img src="https://travis-ci.org/invertase/denque.svg" alt="Build version"></a>
<a href="https://coveralls.io/github/invertase/denque?branch=master"><img src="https://coveralls.io/repos/github/invertase/denque/badge.svg?branch=master" alt="Build version"></a>
<a href="https://github.com/invertase/denque/actions/workflows/testing.yam"><img src="https://github.com/invertase/denque/actions/workflows/testing.yaml/badge.svg" alt="Tests status"></a>
<a href="https://codecov.io/gh/invertase/denque"><img src="https://codecov.io/gh/invertase/denque/branch/master/graph/badge.svg?token=rn91iI4bSe" alt="Coverage"></a>
<a href="/LICENSE"><img src="https://img.shields.io/npm/l/denque.svg?style=flat-square" alt="License"></a>
<a href="https://discord.gg/C9aK28N"><img src="https://img.shields.io/discord/295953187817521152.svg?logo=discord&style=flat-square&colorA=7289da&label=discord" alt="Chat"></a>
<a href="https://twitter.com/invertaseio"><img src="https://img.shields.io/twitter/follow/invertaseio.svg?style=social&label=Follow" alt="Follow on Twitter"></a>
</p>
Extremely fast and lightweight [double-ended queue](http://en.wikipedia.org/wiki/Double-ended_queue) implementation with zero dependencies.
Denque is a well tested, extremely fast and lightweight [double-ended queue](http://en.wikipedia.org/wiki/Double-ended_queue)
implementation with zero dependencies and includes TypeScript types.
Double-ended queues can also be used as a:
- [Stack](http://en.wikipedia.org/wiki/Stack_\(abstract_data_type\))
- [Queue](http://en.wikipedia.org/wiki/Queue_\(data_structure\))
This implementation is currently the fastest available, even faster than `double-ended-queue`, see the [benchmarks](#benchmarks)
This implementation is currently the fastest available, even faster than `double-ended-queue`, see the [benchmarks](https://docs.page/invertase/denque/benchmarks).
Every queue operation is done at a constant `O(1)` - including random access from `.peekAt(index)`.
**Works on all node versions >= v0.10**
# Quick Start
## Quick Start
npm install denque
Install the package:
```js
const Denque = require("denque");
const denque = new Denque([1,2,3,4]);
denque.shift(); // 1
denque.pop(); // 4
```bash
npm install denque
```
# API
- [`new Denque()`](#new-denque---denque)
- [`new Denque(Array items)`](#new-denquearray-items---denque)
- [`push(item)`](#pushitem---int)
- [`unshift(item)`](#unshiftitem---int)
- [`pop()`](#pop---dynamic)
- [`shift()`](#shift---dynamic)
- [`toArray()`](#toarray---array)
- [`peekBack()`](#peekback---dynamic)
- [`peekFront()`](#peekfront---dynamic)
- [`peekAt(int index)`](#peekAtint-index---dynamic)
- [`remove(int index, int count)`](#remove)
- [`removeOne(int index)`](#removeOne)
- [`splice(int index, int count, item1, item2, ...)`](#splice)
- [`isEmpty()`](#isempty---boolean)
- [`clear()`](#clear---void)
#### `new Denque()` -> `Denque`
Creates an empty double-ended queue with initial capacity of 4.
Create and consume a queue:
```js
var denque = new Denque();
denque.push(1);
denque.push(2);
denque.push(3);
denque.shift(); //1
denque.pop(); //3
```
<hr>
#### `new Denque(Array items)` -> `Denque`
Creates a double-ended queue from `items`.
const Denque = require("denque");
```js
var denque = new Denque([1,2,3,4]);
const denque = new Denque([1,2,3,4]);
denque.shift(); // 1
denque.pop(); // 4
```
<hr>
#### `push(item)` -> `int`
Push an item to the back of this queue. Returns the amount of items currently in the queue after the operation.
```js
var denque = new Denque();
denque.push(1);
denque.pop(); // 1
denque.push(2);
denque.push(3);
denque.shift(); // 2
denque.shift(); // 3
```
<hr>
#### `unshift(item)` -> `int`
Unshift an item to the front of this queue. Returns the amount of items currently in the queue after the operation.
```js
var denque = new Denque([2,3]);
denque.unshift(1);
denque.toString(); // "1,2,3"
denque.unshift(-2);
denque.toString(); // "-2,-1,0,1,2,3"
```
<hr>
#### `pop()` -> `dynamic`
Pop off the item at the back of this queue.
Note: The item will be removed from the queue. If you simply want to see what's at the back of the queue use [`peekBack()`](#peekback---dynamic) or [`.peekAt(-1)`](#peekAtint-index---dynamic).
If the queue is empty, `undefined` is returned. If you need to differentiate between `undefined` values in the queue and `pop()` return value -
check the queue `.length` before popping.
```js
var denque = new Denque([1,2,3]);
denque.pop(); // 3
denque.pop(); // 2
denque.pop(); // 1
denque.pop(); // undefined
```
**Aliases:** `removeBack`
<hr>
#### `shift()` -> `dynamic`
Shifts off the item at the front of this queue.
Note: The item will be removed from the queue. If you simply want to see what's at the front of the queue use [`peekFront()`](#peekfront---dynamic) or [`.peekAt(0)`](#peekAtint-index---dynamic).
If the queue is empty, `undefined` is returned. If you need to differentiate between `undefined` values in the queue and `shift()` return value -
check the queue `.length` before shifting.
```js
var denque = new Denque([1,2,3]);
denque.shift(); // 1
denque.shift(); // 2
denque.shift(); // 3
denque.shift(); // undefined
```
<hr>
#### `toArray()` -> `Array`
Returns the items in the queue as an array. Starting from the item in the front of the queue and ending to the item at the back of the queue.
```js
var denque = new Denque([1,2,3]);
denque.push(4);
denque.unshift(0);
denque.toArray(); // [0,1,2,3,4]
```
<hr>
#### `peekBack()` -> `dynamic`
Returns the item that is at the back of this queue without removing it.
If the queue is empty, `undefined` is returned.
```js
var denque = new Denque([1,2,3]);
denque.push(4);
denque.peekBack(); // 4
```
<hr>
#### `peekFront()` -> `dynamic`
Returns the item that is at the front of this queue without removing it.
If the queue is empty, `undefined` is returned.
```js
var denque = new Denque([1,2,3]);
denque.push(4);
denque.peekFront(); // 1
```
<hr>
#### `peekAt(int index)` -> `dynamic`
Returns the item that is at the given `index` of this queue without removing it.
The index is zero-based, so `.peekAt(0)` will return the item that is at the front, `.peekAt(1)` will return
the item that comes after and so on.
The index can be negative to read items at the back of the queue. `.peekAt(-1)` returns the item that is at the back of the queue,
`.peekAt(-2)` will return the item that comes before and so on.
Returns `undefined` if `index` is not a valid index into the queue.
```js
var denque = new Denque([1,2,3]);
denque.peekAt(0); //1
denque.peekAt(1); //2
denque.peekAt(2); //3
denque.peekAt(-1); // 3
denque.peekAt(-2); // 2
denque.peekAt(-3); // 1
```
**Note**: The implementation has O(1) random access using `.peekAt()`.
**Aliases:** `get`
<hr>
#### `remove(int index, int count)` -> `array`
Remove number of items from the specified index from the list.
Returns array of removed items.
Returns undefined if the list is empty.
```js
var denque = new Denque([1,2,3,4,5,6,7]);
denque.remove(0,3); //[1,2,3]
denque.remove(1,2); //[5,6]
var denque1 = new Denque([1,2,3,4,5,6,7]);
denque1.remove(4, 100); //[5,6,7]
```
<hr>
#### `removeOne(int index)` -> `dynamic`
Remove and return the item at the specified index from the list.
Returns undefined if the list is empty.
```js
var denque = new Denque([1,2,3,4,5,6,7]);
denque.removeOne(4); // 5
denque.removeOne(3); // 4
denque1.removeOne(1); // 2
```
<hr>
#### `splice(int index, int count, item1, item2, ...)` -> `array`
Native splice implementation.
Remove number of items from the specified index from the list and/or add new elements.
Returns array of removed items or empty array if count == 0.
Returns undefined if the list is empty.
See the [API reference documentation](https://docs.page/invertase/denque/api) for more examples.
```js
var denque = new Denque([1,2,3,4,5,6,7]);
denque.splice(denque.length, 0, 8, 9, 10); // []
denque.toArray() // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
denque.splice(3, 3, 44, 55, 66); // [4,5,6]
denque.splice(5,4, 666,667,668,669); // [ 66, 7, 8, 9 ]
denque.toArray() // [ 1, 2, 3, 44, 55, 666, 667, 668, 669, 10 ]
```
<hr>
#### `isEmpty()` -> `boolean`
Return `true` if this queue is empty, `false` otherwise.
```js
var denque = new Denque();
denque.isEmpty(); // true
denque.push(1);
denque.isEmpty(); // false
```
<hr>
#### `clear()` -> `void`
Remove all items from this queue. Does not change the queue's capacity.
```js
var denque = new Denque([1,2,3]);
denque.toString(); // "1,2,3"
denque.clear();
denque.toString(); // ""
```
<hr>
## Benchmarks
#### Platform info:
```
Darwin 17.0.0 x64
Node.JS 9.4.0
V8 6.2.414.46-node.17
Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz × 8
```
#### 1000 items in queue
(3 x shift + 3 x push ops per 'op')
denque x 64,365,425 ops/sec ±0.69% (92 runs sampled)
double-ended-queue x 26,646,882 ops/sec ±0.47% (94 runs sampled)
#### 2 million items in queue
(3 x shift + 3 x push ops per 'op')
denque x 61,994,249 ops/sec ±0.26% (95 runs sampled)
double-ended-queue x 26,363,500 ops/sec ±0.42% (91 runs sampled)
#### Splice
(1 x splice per 'op') - initial size of 100,000 items
---
denque.splice x 925,749 ops/sec ±22.29% (77 runs sampled)
native array splice x 7,777 ops/sec ±8.35% (50 runs sampled)
## Who's using it?
#### Remove
- [Kafka Node.js client](https://www.npmjs.com/package/kafka-node)
- [MariaDB Node.js client](https://www.npmjs.com/package/mariadb)
- [MongoDB Node.js client](https://www.npmjs.com/package/mongodb)
- [MySQL Node.js client](https://www.npmjs.com/package/mysql2)
- [Redis Node.js clients](https://www.npmjs.com/package/redis)
(1 x remove + 10 x push per 'op') - initial size of 100,000 items
... and [many more](https://www.npmjs.com/browse/depended/denque).
denque.remove x 2,635,275 ops/sec ±0.37% (95 runs sampled)
native array splice - Fails to complete: "JavaScript heap out of memory"
#### Remove One
---
(1 x removeOne + 10 x push per 'op') - initial size of 100,000 items
## License
denque.removeOne x 1,088,240 ops/sec ±0.21% (93 runs sampled)
native array splice x 5,300 ops/sec ±0.41% (96 runs sampled)
- See [LICENSE](/LICENSE)
---
Built and maintained with 💛 by [Invertase](https://invertase.io).
- [💼 Hire Us](https://invertase.io/hire-us)
- [☕️ Sponsor Us](https://opencollective.com/react-native-firebase)
- [👩‍💻 Work With Us](https://invertase.io/jobs)
<p align="center">
<a href="https://invertase.io/?utm_source=readme&utm_medium=footer&utm_campaign=denque">
<img width="75px" src="https://static.invertase.io/assets/invertase/invertase-rounded-avatar.png">
</a>
<p align="center">
Built and maintained by <a href="https://invertase.io/?utm_source=readme&utm_medium=footer&utm_campaign=denque">Invertase</a>.
</p>
</p>
declare class Denque<T = any> {
length: number;
constructor();
constructor(array: T[]);
constructor(array: T[], options: IDenqueOptions);
push(item: T): number;
unshift(item: T): number;
pop(): T | undefined;
removeBack(): T | undefined;
shift(): T | undefined;
peekBack(): T | undefined;
peekFront(): T | undefined;
peekAt(index: number): T | undefined;
get(index: number): T | undefined;
remove(index: number, count: number): T[];
removeOne(index: number): T | undefined;
splice(index: number, count: number, ...item: T[]): T[] | undefined;
isEmpty(): boolean;
clear(): void;
size(): number;
toString(): string;
toArray(): T[];
length: number;
toArray(): T[];
}
interface IDenqueOptions {
......
......@@ -17,7 +17,7 @@ function Denque(array, options) {
}
/**
* -------------
* --------------
* PUBLIC API
* -------------
*/
......@@ -102,7 +102,7 @@ Denque.prototype.size = function size() {
* @param item
*/
Denque.prototype.unshift = function unshift(item) {
if (item === undefined) return this.size();
if (arguments.length === 0) return this.size();
var len = this._list.length;
this._head = (this._head - 1 + len) & this._capacityMask;
this._list[this._head] = item;
......@@ -132,7 +132,7 @@ Denque.prototype.shift = function shift() {
* @param item
*/
Denque.prototype.push = function push(item) {
if (item === undefined) return this.size();
if (arguments.length === 0) return this.size();
var tail = this._tail;
this._list[tail] = item;
this._tail = (tail + 1) & this._capacityMask;
......@@ -190,7 +190,7 @@ Denque.prototype.removeOne = function removeOne(index) {
this._head = (this._head + 1 + len) & this._capacityMask;
} else {
for (k = size - 1 - index; k > 0; k--) {
this._list[i] = this._list[i = ( i + 1 + len) & this._capacityMask];
this._list[i] = this._list[i = (i + 1 + len) & this._capacityMask];
}
this._list[i] = void 0;
this._tail = (this._tail - 1 + len) & this._capacityMask;
......@@ -426,7 +426,7 @@ Denque.prototype._growArray = function _growArray() {
// head is at 0 and array is now full, safe to extend
this._tail = this._list.length;
this._list.length *= 2;
this._list.length <<= 1;
this._capacityMask = (this._capacityMask << 1) | 1;
};
......
{
"name": "denque",
"version": "1.5.0",
"description": "The fastest javascript implementation of a double-ended queue. Maintains compatability with deque.",
"version": "2.0.1",
"description": "The fastest javascript implementation of a double-ended queue. Used by the official Redis, MongoDB, MariaDB & MySQL libraries for Node.js and many other libraries. Maintains compatability with deque.",
"main": "index.js",
"engines": {
"node": ">=0.10"
......@@ -43,10 +43,10 @@
"bugs": {
"url": "https://github.com/invertase/denque/issues"
},
"homepage": "https://github.com/invertase/denque#readme",
"homepage": "https://docs.page/invertase/denque",
"devDependencies": {
"benchmark": "^2.1.4",
"coveralls": "^2.13.3",
"codecov": "^3.8.3",
"double-ended-queue": "^2.1.0-0",
"istanbul": "^0.4.5",
"mocha": "^3.5.3",
......
2.0.0 / 2018-10-26
==================
* Drop support for Node.js 0.6
* Replace internal `eval` usage with `Function` constructor
* Use instance methods on `process` to check for listeners
1.1.2 / 2018-01-11
==================
......
(The MIT License)
Copyright (c) 2014-2017 Douglas Christopher Wilson
Copyright (c) 2014-2018 Douglas Christopher Wilson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
......
......@@ -267,14 +267,14 @@ deprecate.property(exports, 'oldprop', 'oldprop >= 0.10')
[MIT](LICENSE)
[npm-version-image]: https://img.shields.io/npm/v/depd.svg
[npm-downloads-image]: https://img.shields.io/npm/dm/depd.svg
[npm-url]: https://npmjs.org/package/depd
[travis-image]: https://img.shields.io/travis/dougwilson/nodejs-depd/master.svg?label=linux
[travis-url]: https://travis-ci.org/dougwilson/nodejs-depd
[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/nodejs-depd/master.svg?label=windows
[appveyor-image]: https://badgen.net/appveyor/ci/dougwilson/nodejs-depd/master?label=windows
[appveyor-url]: https://ci.appveyor.com/project/dougwilson/nodejs-depd
[coveralls-image]: https://img.shields.io/coveralls/dougwilson/nodejs-depd/master.svg
[coveralls-image]: https://badgen.net/coveralls/c/github/dougwilson/nodejs-depd/master
[coveralls-url]: https://coveralls.io/r/dougwilson/nodejs-depd?branch=master
[node-image]: https://img.shields.io/node/v/depd.svg
[node-image]: https://badgen.net/npm/node/depd
[node-url]: https://nodejs.org/en/download/
[npm-downloads-image]: https://badgen.net/npm/dm/depd
[npm-url]: https://npmjs.org/package/depd
[npm-version-image]: https://badgen.net/npm/v/depd
[travis-image]: https://badgen.net/travis/dougwilson/nodejs-depd/master?label=linux
[travis-url]: https://travis-ci.org/dougwilson/nodejs-depd
/*!
* depd
* Copyright(c) 2014-2017 Douglas Christopher Wilson
* Copyright(c) 2014-2018 Douglas Christopher Wilson
* MIT Licensed
*/
......@@ -8,8 +8,6 @@
* Module dependencies.
*/
var callSiteToString = require('./lib/compat').callSiteToString
var eventListenerCount = require('./lib/compat').eventListenerCount
var relative = require('path').relative
/**
......@@ -92,7 +90,7 @@ function createStackString (stack) {
}
for (var i = 0; i < stack.length; i++) {
str += '\n at ' + callSiteToString(stack[i])
str += '\n at ' + stack[i].toString()
}
return str
......@@ -128,12 +126,31 @@ function depd (namespace) {
return deprecate
}
/**
* Determine if event emitter has listeners of a given type.
*
* The way to do this check is done three different ways in Node.js >= 0.8
* so this consolidates them into a minimal set using instance methods.
*
* @param {EventEmitter} emitter
* @param {string} type
* @returns {boolean}
* @private
*/
function eehaslisteners (emitter, type) {
var count = typeof emitter.listenerCount !== 'function'
? emitter.listeners(type).length
: emitter.listenerCount(type)
return count > 0
}
/**
* Determine if namespace is ignored.
*/
function isignored (namespace) {
/* istanbul ignore next: tested in a child processs */
if (process.noDeprecation) {
// --no-deprecation support
return true
......@@ -150,7 +167,6 @@ function isignored (namespace) {
*/
function istraced (namespace) {
/* istanbul ignore next: tested in a child processs */
if (process.traceDeprecation) {
// --trace-deprecation support
return true
......@@ -167,7 +183,7 @@ function istraced (namespace) {
*/
function log (message, site) {
var haslisteners = eventListenerCount(process, 'deprecation') !== 0
var haslisteners = eehaslisteners(process, 'deprecation')
// abort early if no destination
if (!haslisteners && this._ignored) {
......@@ -310,7 +326,7 @@ function formatPlain (msg, caller, stack) {
// add stack trace
if (this._traced) {
for (var i = 0; i < stack.length; i++) {
formatted += '\n at ' + callSiteToString(stack[i])
formatted += '\n at ' + stack[i].toString()
}
return formatted
......@@ -335,7 +351,7 @@ function formatColor (msg, caller, stack) {
// add stack trace
if (this._traced) {
for (var i = 0; i < stack.length; i++) {
formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan
formatted += '\n \x1b[36mat ' + stack[i].toString() + '\x1b[39m' // cyan
}
return formatted
......@@ -400,18 +416,18 @@ function wrapfunction (fn, message) {
}
var args = createArgumentsString(fn.length)
var deprecate = this // eslint-disable-line no-unused-vars
var stack = getStack()
var site = callSiteLocation(stack[1])
site.name = fn.name
// eslint-disable-next-line no-eval
var deprecatedfn = eval('(function (' + args + ') {\n' +
// eslint-disable-next-line no-new-func
var deprecatedfn = new Function('fn', 'log', 'deprecate', 'message', 'site',
'"use strict"\n' +
'return function (' + args + ') {' +
'log.call(deprecate, message, site)\n' +
'return fn.apply(this, arguments)\n' +
'})')
'}')(fn, log, this, message, site)
return deprecatedfn
}
......
/*!
* depd
* Copyright(c) 2014 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module exports.
*/
module.exports = callSiteToString
/**
* Format a CallSite file location to a string.
*/
function callSiteFileLocation (callSite) {
var fileName
var fileLocation = ''
if (callSite.isNative()) {
fileLocation = 'native'
} else if (callSite.isEval()) {
fileName = callSite.getScriptNameOrSourceURL()
if (!fileName) {
fileLocation = callSite.getEvalOrigin()
}
} else {
fileName = callSite.getFileName()
}
if (fileName) {
fileLocation += fileName
var lineNumber = callSite.getLineNumber()
if (lineNumber != null) {
fileLocation += ':' + lineNumber
var columnNumber = callSite.getColumnNumber()
if (columnNumber) {
fileLocation += ':' + columnNumber
}
}
}
return fileLocation || 'unknown source'
}
/**
* Format a CallSite to a string.
*/
function callSiteToString (callSite) {
var addSuffix = true
var fileLocation = callSiteFileLocation(callSite)
var functionName = callSite.getFunctionName()
var isConstructor = callSite.isConstructor()
var isMethodCall = !(callSite.isToplevel() || isConstructor)
var line = ''
if (isMethodCall) {
var methodName = callSite.getMethodName()
var typeName = getConstructorName(callSite)
if (functionName) {
if (typeName && functionName.indexOf(typeName) !== 0) {
line += typeName + '.'
}
line += functionName
if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) {
line += ' [as ' + methodName + ']'
}
} else {
line += typeName + '.' + (methodName || '<anonymous>')
}
} else if (isConstructor) {
line += 'new ' + (functionName || '<anonymous>')
} else if (functionName) {
line += functionName
} else {
addSuffix = false
line += fileLocation
}
if (addSuffix) {
line += ' (' + fileLocation + ')'
}
return line
}
/**
* Get constructor name of reviver.
*/
function getConstructorName (obj) {
var receiver = obj.receiver
return (receiver.constructor && receiver.constructor.name) || null
}
/*!
* depd
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module exports.
* @public
*/
module.exports = eventListenerCount
/**
* Get the count of listeners on an event emitter of a specific type.
*/
function eventListenerCount (emitter, type) {
return emitter.listeners(type).length
}
/*!
* depd
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var EventEmitter = require('events').EventEmitter
/**
* Module exports.
* @public
*/
lazyProperty(module.exports, 'callSiteToString', function callSiteToString () {
var limit = Error.stackTraceLimit
var obj = {}
var prep = Error.prepareStackTrace
function prepareObjectStackTrace (obj, stack) {
return stack
}
Error.prepareStackTrace = prepareObjectStackTrace
Error.stackTraceLimit = 2
// capture the stack
Error.captureStackTrace(obj)
// slice the stack
var stack = obj.stack.slice()
Error.prepareStackTrace = prep
Error.stackTraceLimit = limit
return stack[0].toString ? toString : require('./callsite-tostring')
})
lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () {
return EventEmitter.listenerCount || require('./event-listener-count')
})
/**
* Define a lazy property.
*/
function lazyProperty (obj, prop, getter) {
function get () {
var val = getter()
Object.defineProperty(obj, prop, {
configurable: true,
enumerable: true,
value: val
})
return val
}
Object.defineProperty(obj, prop, {
configurable: true,
enumerable: true,
get: get
})
}
/**
* Call toString() on the obj
*/
function toString (obj) {
return obj.toString()
}
{
"name": "depd",
"description": "Deprecate all the things",
"version": "1.1.2",
"version": "2.0.0",
"author": "Douglas Christopher Wilson <doug@somethingdoug.com>",
"license": "MIT",
"keywords": [
......@@ -13,13 +13,17 @@
"devDependencies": {
"benchmark": "2.1.4",
"beautify-benchmark": "0.2.4",
"eslint": "3.19.0",
"eslint-config-standard": "7.1.0",
"eslint": "5.7.0",
"eslint-config-standard": "12.0.0",
"eslint-plugin-import": "2.14.0",
"eslint-plugin-markdown": "1.0.0-beta.7",
"eslint-plugin-promise": "3.6.0",
"eslint-plugin-standard": "3.0.1",
"eslint-plugin-node": "7.0.1",
"eslint-plugin-promise": "4.0.1",
"eslint-plugin-standard": "4.0.0",
"istanbul": "0.4.5",
"mocha": "~1.21.5"
"mocha": "5.2.0",
"safe-buffer": "5.1.2",
"uid-safe": "2.1.5"
},
"files": [
"lib/",
......@@ -29,13 +33,13 @@
"Readme.md"
],
"engines": {
"node": ">= 0.6"
"node": ">= 0.8"
},
"scripts": {
"bench": "node benchmark/index.js",
"lint": "eslint --plugin markdown --ext js,md .",
"test": "mocha --reporter spec --bail test/",
"test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --no-exit test/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/"
"test-ci": "istanbul cover --print=none node_modules/mocha/bin/_mocha -- --reporter spec test/ && istanbul report lcovonly text-summary",
"test-cov": "istanbul cover --print=none node_modules/mocha/bin/_mocha -- --reporter dot test/ && istanbul report lcov text-summary"
}
}
......@@ -2,6 +2,7 @@
The MIT License (MIT)
Copyright (c) 2014 Jonathan Ong me@jongleberry.com
Copyright (c) 2015-2022 Douglas Christopher Wilson doug@somethingdoug.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
......
# Destroy
# destroy
[![NPM version][npm-image]][npm-url]
[![Build status][travis-image]][travis-url]
[![Build Status][github-actions-ci-image]][github-actions-ci-url]
[![Test coverage][coveralls-image]][coveralls-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![Gittip][gittip-image]][gittip-url]
Destroy a stream.
......@@ -18,17 +17,23 @@ and Node.js bugs.
var destroy = require('destroy')
```
### destroy(stream)
### destroy(stream [, suppress])
Destroy the given stream. In most cases, this is identical to a simple
`stream.destroy()` call. The rules are as follows for a given stream:
Destroy the given stream, and optionally suppress any future `error` events.
In most cases, this is identical to a simple `stream.destroy()` call. The rules
are as follows for a given stream:
1. If the `stream` is an instance of `ReadStream`, then call `stream.destroy()`
and add a listener to the `open` event to call `stream.close()` if it is
fired. This is for a Node.js bug that will leak a file descriptor if
`.destroy()` is called before `open`.
2. If the `stream` is not an instance of `Stream`, then nothing happens.
3. If the `stream` has a `.destroy()` method, then call it.
2. If the `stream` is an instance of a zlib stream, then call `stream.destroy()`
and close the underlying zlib handle if open, otherwise call `stream.close()`.
This is for consistency across Node.js versions and a Node.js bug that will
leak a native zlib handle.
3. If the `stream` is not an instance of `Stream`, then nothing happens.
4. If the `stream` has a `.destroy()` method, then call it.
The function returns the `stream` passed in as the argument.
......@@ -48,13 +53,11 @@ destroy(stream)
[npm-url]: https://npmjs.org/package/destroy
[github-tag]: http://img.shields.io/github/tag/stream-utils/destroy.svg?style=flat-square
[github-url]: https://github.com/stream-utils/destroy/tags
[travis-image]: https://img.shields.io/travis/stream-utils/destroy.svg?style=flat-square
[travis-url]: https://travis-ci.org/stream-utils/destroy
[coveralls-image]: https://img.shields.io/coveralls/stream-utils/destroy.svg?style=flat-square
[coveralls-url]: https://coveralls.io/r/stream-utils/destroy?branch=master
[license-image]: http://img.shields.io/npm/l/destroy.svg?style=flat-square
[license-url]: LICENSE.md
[downloads-image]: http://img.shields.io/npm/dm/destroy.svg?style=flat-square
[downloads-url]: https://npmjs.org/package/destroy
[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square
[gittip-url]: https://www.gittip.com/jonathanong/
[github-actions-ci-image]: https://img.shields.io/github/workflow/status/stream-utils/destroy/ci/master?label=ci&style=flat-square
[github-actions-ci-url]: https://github.com/stream-utils/destroy/actions/workflows/ci.yml
/*!
* destroy
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2015-2022 Douglas Christopher Wilson
* MIT Licensed
*/
......@@ -11,8 +12,10 @@
* @private
*/
var EventEmitter = require('events').EventEmitter
var ReadStream = require('fs').ReadStream
var Stream = require('stream')
var Zlib = require('zlib')
/**
* Module exports.
......@@ -22,23 +25,25 @@ var Stream = require('stream')
module.exports = destroy
/**
* Destroy a stream.
* Destroy the given stream, and optionally suppress any future `error` events.
*
* @param {object} stream
* @param {boolean} suppress
* @public
*/
function destroy(stream) {
if (stream instanceof ReadStream) {
return destroyReadStream(stream)
}
if (!(stream instanceof Stream)) {
return stream
function destroy (stream, suppress) {
if (isFsReadStream(stream)) {
destroyReadStream(stream)
} else if (isZlibStream(stream)) {
destroyZlibStream(stream)
} else if (hasDestroy(stream)) {
stream.destroy()
}
if (typeof stream.destroy === 'function') {
stream.destroy()
if (isEventEmitter(stream) && suppress) {
stream.removeAllListeners('error')
stream.addListener('error', noop)
}
return stream
......@@ -51,15 +56,144 @@ function destroy(stream) {
* @private
*/
function destroyReadStream(stream) {
function destroyReadStream (stream) {
stream.destroy()
if (typeof stream.close === 'function') {
// node.js core bug work-around
stream.on('open', onOpenClose)
}
}
return stream
/**
* Close a Zlib stream.
*
* Zlib streams below Node.js 4.5.5 have a buggy implementation
* of .close() when zlib encountered an error.
*
* @param {object} stream
* @private
*/
function closeZlibStream (stream) {
if (stream._hadError === true) {
var prop = stream._binding === null
? '_binding'
: '_handle'
stream[prop] = {
close: function () { this[prop] = null }
}
}
stream.close()
}
/**
* Destroy a Zlib stream.
*
* Zlib streams don't have a destroy function in Node.js 6. On top of that
* simply calling destroy on a zlib stream in Node.js 8+ will result in a
* memory leak. So until that is fixed, we need to call both close AND destroy.
*
* PR to fix memory leak: https://github.com/nodejs/node/pull/23734
*
* In Node.js 6+8, it's important that destroy is called before close as the
* stream would otherwise emit the error 'zlib binding closed'.
*
* @param {object} stream
* @private
*/
function destroyZlibStream (stream) {
if (typeof stream.destroy === 'function') {
// node.js core bug work-around
// istanbul ignore if: node.js 0.8
if (stream._binding) {
// node.js < 0.10.0
stream.destroy()
if (stream._processing) {
stream._needDrain = true
stream.once('drain', onDrainClearBinding)
} else {
stream._binding.clear()
}
} else if (stream._destroy && stream._destroy !== Stream.Transform.prototype._destroy) {
// node.js >= 12, ^11.1.0, ^10.15.1
stream.destroy()
} else if (stream._destroy && typeof stream.close === 'function') {
// node.js 7, 8
stream.destroyed = true
stream.close()
} else {
// fallback
// istanbul ignore next
stream.destroy()
}
} else if (typeof stream.close === 'function') {
// node.js < 8 fallback
closeZlibStream(stream)
}
}
/**
* Determine if stream has destroy.
* @private
*/
function hasDestroy (stream) {
return stream instanceof Stream &&
typeof stream.destroy === 'function'
}
/**
* Determine if val is EventEmitter.
* @private
*/
function isEventEmitter (val) {
return val instanceof EventEmitter
}
/**
* Determine if stream is fs.ReadStream stream.
* @private
*/
function isFsReadStream (stream) {
return stream instanceof ReadStream
}
/**
* Determine if stream is Zlib stream.
* @private
*/
function isZlibStream (stream) {
return stream instanceof Zlib.Gzip ||
stream instanceof Zlib.Gunzip ||
stream instanceof Zlib.Deflate ||
stream instanceof Zlib.DeflateRaw ||
stream instanceof Zlib.Inflate ||
stream instanceof Zlib.InflateRaw ||
stream instanceof Zlib.Unzip
}
/**
* No-op function.
* @private
*/
function noop () {}
/**
* On drain handler to clear binding.
* @private
*/
// istanbul ignore next: node.js 0.8
function onDrainClearBinding () {
this._binding.clear()
}
/**
......@@ -67,7 +201,7 @@ function destroyReadStream(stream) {
* @private
*/
function onOpenClose() {
function onOpenClose () {
if (typeof this.fd === 'number') {
// actually close down the fd
this.close()
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment