| 1 | /** |
| 2 | * List implementation relying on an array or if supported on a Set to hold values. |
| 3 | * |
| 4 | * @author Alexander Ebert |
| 5 | * @copyright 2001-2018 WoltLab GmbH |
| 6 | * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> |
| 7 | * @module WoltLabSuite/Core/List |
| 8 | */ |
| 9 | define([], function() { |
| 10 | "use strict"; |
| 11 | |
| 12 | var _hasSet = objOwns(window, 'Set') && typeof window.Set === 'function'; |
| 13 | |
| 14 | /** |
| 15 | * @constructor |
| 16 | */ |
| 17 | function List() { |
| 18 | this._set = (_hasSet) ? new Set() : []; |
| 19 | } |
| 20 | List.prototype = { |
| 21 | /** |
| 22 | * Appends an element to the list, silently rejects adding an already existing value. |
| 23 | * |
| 24 | * @param {?} value unique element |
| 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 | * |
| 50 | * @param {?} value element |
| 51 | * @return {boolean} true if element was in the list |
| 52 | */ |
| 53 | 'delete': function(value) { |
| 54 | if (_hasSet) { |
| 55 | return this._set['delete'](value); |
| 56 | } |
| 57 | else { |
| 58 | var index = this._set.indexOf(value); |
| 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 | * |
| 85 | * @param {?} value element |
| 86 | * @return {boolean} true if element is in the list |
| 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() { |
| 102 | if (_hasSet) { |
| 103 | return this._set.size; |
| 104 | } |
| 105 | else { |
| 106 | return this._set.length; |
| 107 | } |
| 108 | } |
| 109 | }); |
| 110 | |
| 111 | return List; |
| 112 | }); |