consumable/index.js
2020-07-19 00:25:05 +02:00

44 lines
885 B
JavaScript

"use strict";
module.exports = function createConsumable(initialValue) {
let currentValue = initialValue;
let isSet = (initialValue !== (void 0));
return {
set: function (newValue) {
currentValue = newValue;
isSet = true;
},
peek: function () {
if (isSet) {
return currentValue;
} else {
throw new Error(`No value is currently set`);
}
},
isSet: function () {
return isSet;
},
replace: function (newValue) {
if (isSet) {
let consumedValue = currentValue;
currentValue = newValue;
isSet = true;
return consumedValue;
} else {
throw new Error(`No value is currently set`);
}
},
consume: function () {
if (isSet) {
let consumedValue = currentValue;
currentValue = undefined;
isSet = false;
return consumedValue;
} else {
throw new Error(`No value is currently set`);
}
}
};
};