Created
July 30, 2021 00:48
-
-
Save yitonghe00/83a18e5fc677d1727d5e8cd5a94a3388 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const box = { | |
locked: true, | |
unlock() { this.locked = false; }, | |
lock() { this.locked = true; }, | |
_content: [], | |
get content() { | |
if (this.locked) throw new Error("Locked!"); | |
return this._content; | |
} | |
}; | |
function withBoxUnlocked(body) { | |
// Your code here. | |
let locked = false; | |
if (box.locked) { | |
locked = true; | |
box.unlock(); | |
} | |
try { | |
body(); | |
} finally { | |
if (locked) { | |
box.lock(); | |
} | |
} | |
} | |
withBoxUnlocked(function() { | |
box.content.push("gold piece"); | |
}); | |
try { | |
withBoxUnlocked(function() { | |
throw new Error("Pirates on the horizon! Abort!"); | |
}); | |
} catch (e) { | |
console.log("Error raised: " + e); | |
} | |
console.log(box.locked); | |
// → true | |
box.unlock(); | |
console.log(box.content); | |
// -> ["gold piece"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment