1

Can someone help me translate the following to coffeescript?

Step(
  function readSelf() {
    fs.readFile(__filename, this);
  },
  function capitalize(err, text) {
    if (err) throw err;
    return text.toUpperCase();
  },
  function showIt(err, newText) {
    if (err) throw err;
    console.log(newText);
  }
);

2 Answers 2

3

CoffeeScript equivalent will be the following.

Step (readSelf = ->
  fs.readFile __filename, @
), (capitalize = (err, text) ->
  throw err  if err?
  text.toUpperCase()
), showIt = (err, newText) ->
  throw err  if err?
  console.log newText

You can use this site for this purpose http://js2coffee.org/ or you can download and install the code from https://github.com/rstacruz/js2coffee and use it on your machine.

Sign up to request clarification or add additional context in comments.

3 Comments

I would replace this with @, just because its more CoffeeScript-y. Also, you probably want the existential in those ifs - if err?. I know that translates to slightly different JavaScript, but its more likely what was meant.
@Aaron Nothing wrong with if err . Either err will be undefined/null, or it'll be an object, so the boolean coercion doesn't add any ambiguity. Or perhaps you meant if err? as an aesthetic preference, which is legit.
@Trevor Not knowing what values err might take on, its equal parts readability (since what you're really doing is checking for existence) and correctness (I've seen, in rare and somewhat frightening cases, an error represented by an empty string).
0
Step(
  readSelf = -> fs.readFile __filename, @
  capitalize = (err, text) ->
    throw err if err
    text.toUpperCase()
  showIt = (err, newText) ->
    throw err if err
    console.log newText
)

Don't use converters ever. Your code can be corrupted after conversion. For example code, which you can see in previous post is incorrect. Because expression

throw err if err?

Will generate:

if (typeof err !== "undefined" && err !== null) {
  throw err;
}

I think it's not that you expect to see. I use site of coffee creator for my experiments with coffee. Don't use js2coffee site, there are some mistakes in conversion which can be critical. I had ones.. Good Luck!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.