Halaman

Senin, 07 Maret 2011

international saimoe league voting

my voting result:




































































































































































































Kamis, 24 Februari 2011

[shared] javascript function with flexible parameters

for example, in ruby i can write a method like this:
def certain_method *args
  "name: " + args[0..1].join(' ') + "\noccupation: " + args[2..-1].join(' ')
end

certain_method 'aya', 'hirano', 'the', 'best', 'seiyuu', 'in', 'the', 'world'
# -> "name: aya hirano\noccupation: the best seiyuu in the world"

but how to do it in javascript?

we can use function's arguments for that.
arguments object is a local variable within all functions.

You can refer to a function's arguments within the function by using the arguments object. This object contains an entry for each argument passed to the function, the first entry's index starting at 0. For example, if a function is passed three arguments, you can refer to the argument as: arguments[0], arguments[1], arguments[2]

more detailed article can be seen here:
https://developer.mozilla.org/en/JavaScript/Reference/functions_and_function_scope/arguments

ok, now for the above ruby method, the js function with equal behavior should be something like this:
function certainMethod(like, usual, you, can, define, any, parameters, here) {
    var argsArr = $(arguments).get(); // convert arguments to array
    
    return 'name: ' + argsArr.slice(0, 2).join(' ') + "\noccupation: " + argsArr.slice(2).join(' ');
    
    // first params (like) equal with arguments[0]
}

Demo

[shared] rounding closer to zero in javascript

dengan menggunakan double bitwise not operator (~~)
contoh:
var a = 1.9;
var b = -1.8;
var c = '-2.8';
var d = 'string';
var e = document;
~~a; // -> 1
~~b; // -> -1
~~c; // -> -2
~~d; // -> 0
~~e; // -> 0

operator ~~ lebih cepat dari Math.floor atau Math.ceil jadi bisa menjadi alternatif 2 fungsi tersebut..

demo: