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

27 lines
1 KiB
JavaScript

"use strict";
const consumable = require("./");
let singleUseValue = consumable(42);
console.log(singleUseValue.isSet()); // true
console.log(singleUseValue.peek()); // 42
console.log(singleUseValue.consume()); // 42
console.log(singleUseValue.peek()); // Throws!
console.log(singleUseValue.isSet()); // false
/* Now let's try with a different value, and using `replace`... */
singleUseValue.set(13);
console.log(singleUseValue.peek()); // 13
console.log(singleUseValue.replace(9001)); // 13
console.log(singleUseValue.peek()); // 9001
/* Note how it can distinguish between an explicitly-set `undefined`, and just nothing being set. */
singleUseValue.set(undefined);
console.log(singleUseValue.isSet()); // true
console.log(singleUseValue.peek()); // undefined
console.log(singleUseValue.consume()); // undefined
console.log(singleUseValue.isSet()); // false
console.log(singleUseValue.peek()); // Throws!
console.log(singleUseValue.consume()); // Throws!