var code = arg0 + '[' + arg0 + '.length - 1]';
arg0 is a variable name, this generator returns perfectly acceptable
aList[aList.length - 1]
However, this generator may have unintended behaviour if
arg0 were a
function call. Consider the following code:
randomList()[randomList().length - 1]
The two returned values might be of different lengths, resulting in an out of range condition. Additionally, if the function call has side-effects, then calling it twice could be undesirable.
There are two solutions to this problem. Statement blocks should use temporary variables. Value blocks should use utility functions.
The simplest solution is to assign the offending input to a temporary variable. Care must be taken that this variable does not accidentally collide with an existing variable. The following code shows an example of a temporary variable in a statement block which alerts the last element of a list.
getDistinctName call takes an argument of the desired variable name
("temp_list") and will return an non-colliding name to use (possibly
The downside of temporary variables is that if the offending input was already a variable, then one generates redundant code:
var temp_list = foo; alert(temp_list[temp_list.length - 1]);
To produce cleaner code, check to see if the offending input is a simple literal, and generate code accordingly:
Temporary variables work well in statement blocks (in this case an alert) where the generated code may span multiple lines. However they are unworkable in value blocks which must be on a single line. For value blocks one must use a utility function instead of temporary variables.
Defining a utility function is a powerful way to create blocks that operate at a higher level than the underlying language. Utility functions are not generated unless they are used, and they are only generated once regardless of the number of times they are used.
In the above example we request the definition of a utility function named
list_lastElement (though the actual name may be different in order to avoid
colliding with user variables). See
working example of a utility function.