1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-10-18 20:09:08 +02:00
unleash.unleash/lib/client-metrics/list.js

126 lines
2.8 KiB
JavaScript
Raw Normal View History

2016-11-06 20:52:08 +01:00
'use strict';
const { EventEmitter } = require('events');
class Node {
2017-06-28 10:17:14 +02:00
constructor(value) {
2016-11-06 20:52:08 +01:00
this.value = value;
this.next = null;
}
2017-06-28 10:17:14 +02:00
link(next) {
2016-11-06 20:52:08 +01:00
this.next = next;
next.prev = this;
2016-11-07 08:44:46 +01:00
return this;
2016-11-06 20:52:08 +01:00
}
}
module.exports = class List extends EventEmitter {
2017-06-28 10:17:14 +02:00
constructor() {
2016-11-06 20:52:08 +01:00
super();
this.start = null;
this.tail = null;
}
2017-06-28 10:17:14 +02:00
add(obj) {
2016-11-06 20:52:08 +01:00
const node = new Node(obj);
2016-11-07 08:44:46 +01:00
if (this.start) {
this.start = node.link(this.start);
2016-11-06 20:52:08 +01:00
} else {
this.start = node;
this.tail = node;
}
return node;
}
2017-06-28 10:17:14 +02:00
iterate(fn) {
2016-11-06 20:52:08 +01:00
if (!this.start) {
return;
}
let cursor = this.start;
while (cursor) {
const result = fn(cursor);
if (result === false) {
cursor = null;
} else {
cursor = cursor.next;
}
}
}
2017-06-28 10:17:14 +02:00
iterateReverse(fn) {
2016-11-06 20:52:08 +01:00
if (!this.tail) {
return;
}
let cursor = this.tail;
while (cursor) {
const result = fn(cursor);
if (result === false) {
cursor = null;
} else {
cursor = cursor.prev;
}
}
}
2017-06-28 10:17:14 +02:00
reverseRemoveUntilTrue(fn) {
2016-11-06 20:52:08 +01:00
if (!this.tail) {
return;
}
let cursor = this.tail;
while (cursor) {
const result = fn(cursor);
if (result === false && cursor === this.start) {
// whole list is removed
this.emit('evicted', cursor.value);
this.start = null;
2016-12-27 21:03:50 +01:00
this.tail = null;
2016-11-06 20:52:08 +01:00
// stop iteration
cursor = null;
} else if (result === true) {
// when TRUE, set match as new tail
if (cursor !== this.tail) {
this.tail = cursor;
cursor.next = null;
}
// stop iteration
cursor = null;
} else {
// evicted
this.emit('evicted', cursor.value);
// iterate to next
cursor = cursor.prev;
}
}
}
2017-06-28 10:17:14 +02:00
toArray() {
2016-11-06 20:52:08 +01:00
const result = [];
if (this.start) {
let cursor = this.start;
while (cursor) {
result.push(cursor.value);
cursor = cursor.next;
}
}
return result;
}
// toArrayReverse () {
// const result = [];
2016-11-06 20:52:08 +01:00
// if (this.tail) {
// let cursor = this.tail;
// while (cursor) {
// result.push(cursor.value);
// cursor = cursor.prev;
// }
// }
2016-11-06 20:52:08 +01:00
// return result;
// }
2016-11-06 20:52:08 +01:00
};