简体   繁体   中英

Passing function as parameter in JavaScript

Have to port a little piece of code from JavaScript to JAVA:

var N = 3;
var w = 8, h = 8;

var matrix = [ 

               [1, 0, 0, 0, 0, 0, 0, 0],
               [1, 1, 0, 0, 0, 0, 0, 0],
               [1, 1, 1, 0, 0, 0, 0, 0],
               [1, 1, 1, 1, 0, 0, 0, 0],
               [1, 1, 1, 1, 1, 0, 0, 0],
               [1, 1, 1, 1, 1, 1, 0, 0],
               [1, 1, 1, 1, 1, 1, 1, 0],
               [1, 1, 1, 1, 1, 1, 1, 1]

             ];

//[1, 1, 1, 1, 1, 1, 0, 1, 1]
console.log(complexFunction(2, 1));

//first function
function simpleFunction(f_) {

    var out = new Array(N * N);

    for (var y = 0; y < N; y++) {
        for (var x = 0; x < N; x++) {

        out[x + y * N] = f_(x, y);

        }
    }

    return out;

};

//second function     
function complexFunction(x_, y_) {

    return simpleFunction(function (dx, dy) { return matrix[(x + dx) % w][(y + dy) % h]; });

};

Have experimented with Callable without any success. Ideally, the ported result should have the same structure as JavaScript source.

Unfortunately, I have to use Java 7, which doesn't have lambdas, so had to make everything as simple as possible:

Integer[] complexFunction(int dx_, int dy_){

     Integer[] out = new Integer[N * N];

     for (Integer y = 0; y < N; y++) {
        for (Integer x = 0; x < N; x++) {

          out[x + y * N] = matrix[(x + dx_) % w][(y + dy_) % h];

        }
     }
     return out; 

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM