I attended a JavaScript workshop in Vancouver today and the talk by John Resig was inspiring. I pick up some notices here. http://www.meetup.com/vancouver-javascript-developers/calendar/13867715/?a=cr1p_grp&rv=cr1p
Splittinng arguments
Math.min() accepts a set of values. When you would like to find the minimum value of an array, you can use the following trick:
Math.min.apply(Math, the_array);
Function#apply
receives an object for "text" and arguments in array.
On the other hand Ruby has a feature of this issue as a syntactic sugar.
Math.min(*the_array)
Abbreviating "new"
JavaScript uses "new" operator to create an instance.
var a = new A(x);
You may want to abbreviate the keyword "new" like
var a = A(x);
You can provide such class with the following trick.
On the other hand, Ruby has separate namespace, so you can re-write the following code
a = A.new(x)
as
def A(x); A.new(x); end
a = A(x)
cloning an array
JS:
array2 = array.slice(0);
Ruby:
array2 = array.dup
The JS version is actually not just cloning but converts arguments object to array, so you can regard Array#slice
in JS as the combination of dup
and to_a
in Ruby.
No comments:
Post a Comment