Eloquent JavaScript
Download 2.16 Mb. Pdf ko'rish
|
Eloquent JavaScript
- Bu sahifa navigatsiya:
- The locked box
- Chapter 9 Regular Expressions
Exercises
Retry Say you have a function primitiveMultiply that in 20 percent of cases mul- tiplies two numbers and in the other 80 percent of cases raises an exception of type MultiplicatorUnitFailure . Write a function that wraps this clunky function and just keeps trying until a call succeeds, after which it returns the result. Make sure you handle only the exceptions you are trying to handle. The locked box Consider the following (rather contrived) object: 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; } }; It is a box with a lock. There is an array in the box, but you can get at it only when the box is unlocked. Directly accessing the private _content property is forbidden. Write a function called withBoxUnlocked that takes a function value as ar- gument, unlocks the box, runs the function, and then ensures that the box is locked again before returning, regardless of whether the argument function returned normally or threw an exception. For extra points, make sure that if you call withBoxUnlocked when the box is already unlocked, the box stays unlocked. 142 “Some people, when confronted with a problem, think ‘I know, I’ll use regular expressions.’ Now they have two problems.” —Jamie Zawinski Chapter 9 Regular Expressions Programming tools and techniques survive and spread in a chaotic, evolutionary way. It’s not always the pretty or brilliant ones that win but rather the ones that function well enough within the right niche or that happen to be integrated with another successful piece of technology. In this chapter, I will discuss one such tool, regular expressions. Regular expressions are a way to describe patterns in string data. They form a small, separate language that is part of JavaScript and many other languages and systems. Regular expressions are both terribly awkward and extremely useful. Their syntax is cryptic, and the programming interface JavaScript provides for them is clumsy. But they are a powerful tool for inspecting and processing strings. Properly understanding regular expressions will make you a more effective pro- grammer. Download 2.16 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling