0

How can I get rid of the auto generated returns in my coffee script:

createHash = (password) ->
  bcrypt.genSalt 10, (err, salt) ->
    bcrypt.hash password, salt, (err, hash) ->
      hash

I'm getting ...

createHash = function(password) {
  return bcrypt.genSalt(10, function(err, salt) {
    return bcrypt.hash(password, salt, function(err, hash) {
      return hash;
    });
  });
};

... but I desire a solution without the returns:

createHash = function(password) {
  bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(password, salt, function(err, hash) {
      return hash;
    });
  });
};

How am I getting this done?

Timo
  • 261
  • 5
  • 18

1 Answers1

0

By default, CoffeeScript functions return the value of their last expression so this:

f = ->
    # Bunch of interesting things...
    6

is equivalent to:

f = ->
    # Bunch of interesting things...
    return 6

hence the returns appearing in the transpiled JavaScript.

In JavaScript, a function without an explicit return implicitly returns undefined so these return the same thing:

function() { }
function() { return }
function() { return undefined }

Putting those two things together gives you two options:

  1. Throw an undefined at the bottom of your function to bypass the implicit return with an explicit one:

    createHash = (password) ->
      bcrypt.genSalt 10, (err, salt) ->
        bcrypt.hash password, salt, (err, hash) ->
          hash
        undefined
      undefined
    
  2. Or better, explicitly indicate that you're returning nothing with an empty return:

    createHash = (password) ->
      bcrypt.genSalt 10, (err, salt) ->
        bcrypt.hash password, salt, (err, hash) ->
          hash
        return
      return
    

The second option should give you exactly the JavaScript you're looking for:

var createHash;
createHash = function(password) {
  bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(password, salt, function(err, hash) {
      return hash;
    });
  });
};
mu is too short
  • 426,620
  • 70
  • 833
  • 800