Changes between Version 2 and Version 3 of Ticket #6433


Ignore:
Timestamp:
03/01/2018 10:01:26 AM (2 years ago)
Author:
mjethani
Comment:

Legend:

Unmodified
Added
Removed
Modified
  • Ticket #6433 – Description

    v2 v3  
    2525This is a function that takes an input and returns a list, in this case a list of URLs from the given element. 
    2626 
    27 ES6 has support for generators, which makes it possible to write the same code in a cleaner way. 
     27ES6 has support for generators, which makes it possible to write the same code in a cleaner and possibly more efficient way. 
    2828 
    2929For example: 
     
    5252}}} 
    5353 
    54 There is often a `for...of` loop on the calling side, which already works with generators, so there's no need for any change. 
     54There is often a `for...of` loop on the calling side, which already works with generators, so there's no need for any change. If the caller terminates the iteration, the entire generator chain returns, which has the added benefit of improving performance. 
    5555 
    56 This is already an improvement, but we can go further. For example, by adopting a functional style: 
     56For example, in the following code: 
     57 
     58{{{ 
     59for (let url of getURLsFromElement(element)) 
     60{ 
     61  if (url) 
     62  { 
     63    doSomething(url); 
     64    break; 
     65  } 
     66} 
     67}}} 
     68 
     69The loop terminates if the first URL returned is truth-y, and in that case the function `getURLsFromElement` does not bother checking the values of the `srcset` attributes and the attribute values of the children. Without generators, the callee would need to know the requirements of the caller up front in order to do this kind of optimization, but with generators the caller decides when to terminate the callee. 
     70 
     71This is already an improvement, but we can go further in terms of code readability. For example, by adopting a functional style: 
    5772 
    5873{{{ 
     
    7085}}} 
    7186 
    72 Further, if yielding false-y values is not a concern, then this can be combined with object destructuring in the parameter list to make the code even more succinct: 
     87Note that this does negate some of the aforementioned performance benefits, since now we're trimming every URL before it's even needed. 
     88 
     89Further, if yielding false-y values is not a concern, this can be combined with object destructuring in the parameter list to make the code even more succinct: 
    7390 
    7491{{{ 
     
    83100}}} 
    84101 
    85 Note that with each change we may degrade the performance slightly. 
     102With each change we may degrade the performance slightly in exchange for better readability. 
    86103 
    87104Also note that this only works transparently with pure functions, i.e. functions that have no side effects, or where the side effects and the order in which they occur do not matter.