Js passes an optional argument to a function

I have the following code:

    var createThumb128 = function(fileObj, readStream, writeStream) {
        gm(readStream, fileObj.name()).resize('128', '128').stream().pipe(writeStream);
    };

    var store = new FS.Store.GridFS("thumbs_128", { transformWrite: createThumb128})

How to replace 128 × string strings with arguments that I pass to the createThumb function?

I assume that I cannot just add an additional parameter, since the transformWrite property requires a function with a special signature for parameter 3.

+4
source share
4 answers

You can try "Currying" https://en.wikipedia.org/wiki/Currying

var createThumb = function(size) {
    return function(fileObj, readStream, writeStream) {
        gm(readStream, fileObj.name()).resize(size, size).stream().pipe(writeStream);
    };
}

var store = new FS.Store.GridFS("thumbs_128", { transformWrite: createThumb('128')})
+2
source

If transformWritethree parameters are expected, you must provide the appropriate function. However, you can simply create such a function with the required size parameters.

, :

var makeCreateThumb = function(param) {
    return function(fileObj, readStream, writeStream) {
        gm(readStream, fileObj.name())
            .resize(param, param)
            .stream()
            .pipe(writeStream);
    };
}

:

var store = new FS.Store.GridFS("thumbs_128", { 
    transformWrite: makeCreateThumb('128')
})
+2

Use currying as suggested by @TongShen - s bind.

bindallows you to use a function with arguments n, when bindyou can get a function n-xwhere you can fix the first n.

In your case, make this a 4 argument function:

 var createThumb128 = function(len, fileObj, readStream, writeStream) {
        gm(readStream, fileObj.name()).resize(len, len).stream().pipe(writeStream);
    };

then create a copy with three arguments, fixing the length '128'and submit this:

var lengthFixed128 = createThumb128 .bind(undefined, '128'); //first argument binds to a context, can be left undefined for our purpose

var store = new FS.Store.GridFS("thumbs_128", { transformWrite: lengthFixed128 })
0
source

The first option is to return the function.

function abc (_custom) {
  return function (a, b, c) {
      console.log(arguments, _custom);
  }
}

var x = abc();
console.log(x(1,2,3));

Another option is to use bind

function abc (_custom, a,b,c) {
  console.log(arguments);
}

var x = abc.bind(this, 128);
x(1,2,3)
0
source

Source: https://habr.com/ru/post/1621331/


All Articles