tailieunhanh - Test Driven JavaScript Development- P7
Test Driven JavaScript Development- P7:This book is about programming JavaScript for the real world, using the techniques and workflow suggested by Test-Driven Development. It is about gaining confidence in your code through test coverage, and gaining the ability to fearlessly refactor and organically evolve your code base. It is about writing modular and testable code. It is about writing JavaScript that works in a wide variety of environments and that doesn’t get in your user’s way. | Memoization 113 Listing Memoizing the Fibonacci sequence in a closure var fibonacci function var cache function fibonacci x if x 2 return 1 if cache x cache x fibonacci x - 1 fibonacci x - 2 return cache x return fibonacci This alternative version of fibonacci runs many orders of magnitude faster than the original one and by extension is capable of calculating more numbers in the sequence. However mixing computation with caching logic is a bit ugly. Again we will add a function to to help separate concerns. The memoize method in Listing is capable of wrapping a method adding memoization without cluttering the calculation logic. Listing A general purpose memoize method if function var cache var func this return function x if x in cache cache x this x return cache x Please purchase PDF Split-Merge on to remove this watermark. From the Library of 114 Applied Functions and Closures This method offers a clean way to memoize functions as seen in Listing . Listing Memoizing the Fibonacci function TestCase FibonacciTest test calculate high fib value with memoization function var fibonacciFast assertEquals 1346269 fibonacciFast 30 The memoize method offers a clean solution but unfortunately only deals with functions that take a single argument. Limiting its use further is the fact that it blindly coerces all arguments to strings by nature of property assignment which will be discussed in detail in Chapter 7 Objects and Prototypal Inheritance. To improve the memoizer we would need to serialize all arguments to use as keys. One way to do this which is only slightly more complex than what we already have is to simply join the arguments as Listing does. Listing A slightly better memoize method if function var cache var func this var join .
đang nạp các trang xem trước