-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbag.js
54 lines (46 loc) · 896 Bytes
/
bag.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const Node = require('../node/node')
const { Iterator } = require('../../abstracts')
/**
* Bag
* @classdesc Generic Bag implementation based on linked-lists.
* @implements {Iterator}
* @see p. 155
*/
class Bag {
constructor () {
this._n = 0
this._first = null
Object.seal(this)
}
/**
* Returns if the Bag is empty
*/
isEmpty () {
return this._first === null
}
/**
* Returns the Bags' size
*/
size () {
return this._n
}
/**
* Inserts an item to the Bag
* @param {*} item The item to be stored
*/
add (item) {
const oldFirst = this._first
this._first = new Node()
this._first._item = item
this._first._next = oldFirst
this._n++
}
/**
* Returns an Iterator to traverse the bag.
* @returns {Iterator}
*/
[Symbol.iterator] () {
return new Iterator(this._first)
}
}
module.exports = Bag