@sap/cds-dk
Version:
Command line client and development toolkit for the SAP Cloud Application Programming Model
100 lines (81 loc) • 2.3 kB
JavaScript
;
/**
* Library for handling multiple values for same key
*/
var Multimap = (function () {
var mapCtor;
if (typeof Map !== 'undefined') {
mapCtor = Map;
if (!Map.prototype.keys) {
Map.prototype.keys = function () {
var keys = [];
this.forEach(function (item, key) {
keys.push(key);
});
return keys;
};
}
}
function Multimap(iterable) {
var self = this;
self._map = mapCtor;
if (Multimap.Map) {
self._map = Multimap.Map;
}
self._ = self._map ? new self._map() : {};
if (iterable) {
iterable.forEach(function (i) {
self.set(i[0], i[1]);
});
}
}
/**
* @param {Object} key
* @return {Array} An array of values, undefined if no such a key;
*/
Multimap.prototype.get = function (key) {
return this._map ? this._.get(key) : this._[key];
};
/**
* @param {Object} key
* @param {Object} val...
*/
// eslint-disable-next-line no-unused-vars
Multimap.prototype.set = function (key, val) {
var args = Array.prototype.slice.call(arguments);
key = args.shift();
var entry = this.get(key);
if (!entry) {
entry = [];
if (this._map)
this._.set(key, entry);
else
this._[key] = entry;
}
Array.prototype.push.apply(entry, args);
return this;
};
/**
* @return {Array} all the keys in the map
*/
Multimap.prototype.keys = function () {
if (this._map)
return makeIterator(this._.keys());
return makeIterator(Object.keys(this._));
};
function makeIterator(iterator) {
if (Array.isArray(iterator)) {
var nextIndex = 0;
return {
next: function () {
return nextIndex < iterator.length ?
{ value: iterator[nextIndex++], done: false } :
{ done: true };
}
};
}
return iterator;
}
return Multimap;
})();
module.exports = Multimap;