Add content selection before removing content
[GitHub/WoltLab/WCF.git] / wcfsetup / install / files / js / WoltLabSuite / Core / List.js
CommitLineData
ca3ef487
AE
1/**
2 * List implementation relying on an array or if supported on a Set to hold values.
3 *
4 * @author Alexander Ebert
c839bd49 5 * @copyright 2001-2018 WoltLab GmbH
ca3ef487 6 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
58d7e8f8 7 * @module WoltLabSuite/Core/List
ca3ef487
AE
8 */
9define([], function() {
10 "use strict";
11
d0023381 12 var _hasSet = objOwns(window, 'Set') && typeof window.Set === 'function';
ca3ef487
AE
13
14 /**
15 * @constructor
16 */
17 function List() {
18 this._set = (_hasSet) ? new Set() : [];
e0d2121e 19 }
ca3ef487
AE
20 List.prototype = {
21 /**
22 * Appends an element to the list, silently rejects adding an already existing value.
23 *
e0d2121e 24 * @param {?} value unique element
ca3ef487
AE
25 */
26 add: function(value) {
27 if (_hasSet) {
28 this._set.add(value);
29 }
30 else if (!this.has(value)) {
31 this._set.push(value);
32 }
33 },
34
35 /**
36 * Removes all elements from the list.
37 */
38 clear: function() {
39 if (_hasSet) {
40 this._set.clear();
41 }
42 else {
43 this._set = [];
44 }
45 },
46
47 /**
48 * Removes an element from the list, returns true if the element was in the list.
49 *
e0d2121e
AE
50 * @param {?} value element
51 * @return {boolean} true if element was in the list
ca3ef487
AE
52 */
53 'delete': function(value) {
54 if (_hasSet) {
55 return this._set['delete'](value);
56 }
57 else {
b8eab696 58 var index = this._set.indexOf(value);
ca3ef487
AE
59 if (index === -1) {
60 return false;
61 }
62
63 this._set.splice(index, 1);
64 return true;
65 }
66 },
67
68 /**
69 * Calls `callback` for each element in the list.
70 */
71 forEach: function(callback) {
72 if (_hasSet) {
73 this._set.forEach(callback);
74 }
75 else {
76 for (var i = 0, length = this._set.length; i < length; i++) {
77 callback(this._set[i]);
78 }
79 }
80 },
81
82 /**
83 * Returns true if the list contains the element.
84 *
e0d2121e
AE
85 * @param {?} value element
86 * @return {boolean} true if element is in the list
ca3ef487
AE
87 */
88 has: function(value) {
89 if (_hasSet) {
90 return this._set.has(value);
91 }
92 else {
93 return (this._set.indexOf(value) !== -1);
94 }
95 }
96 };
97
98 Object.defineProperty(List.prototype, 'size', {
99 enumerable: false,
100 configurable: true,
101 get: function() {
e0d2121e 102 if (_hasSet) {
ca3ef487
AE
103 return this._set.size;
104 }
105 else {
106 return this._set.length;
107 }
108 }
109 });
110
111 return List;
112});