Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coffeescript resetCards is not a function

I have been running coffeescript along with expressjs on nodejs, I am making a little script to give you 9 random playing cards (with no duplicates), I made a function resetCards to reset the cards after every display, but when I run the script it gives me:

TypeError: resetCards is not a function
    at Object.<anonymous> (/home/zunon/projects/xKoot/router.js:10:1)
    at Module._compile (module.js:398:26)
    at Object.Module._extensions..js (module.js:405:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/home/zunon/projects/xKoot/xkoot.js:6:10)
    at Module._compile (module.js:398:26)
    at Object.Module._extensions..js (module.js:405:10)

Here is the file router.coffee:

express = require 'express'
router = express.Router()

cards = []

resetCards()

router.route '/randomcard'
    .get (req, res) ->
        cardNames = []
        for i in [1..9] by 1
            cardNames[i] = createCardName()
        console.log cardNames
        res.render 'randomcard', {cardNames}
        return

createCardName = ->
    position = Math.floor Math.random() * cards.length
    cards.splice position, 1
    cards[position]

resetCards = ->
    for i in [1..13] by 1
        cards[i - 1] = "club#{i}"
        cards[i + 12] = "dmnd#{i}"
        cards[i + 25] = "hart#{i}"
        cards[i + 38] = "spad#{i}"
        if i < 3
            cards[i + 51] = "joke#{i}"  

module.exports = router
like image 561
Zunon Avatar asked Dec 24 '22 10:12

Zunon


1 Answers

CoffeeScript doesn't hoist functions to the top of the scope the way JavaScript does. In JavaScript, if you say:

f();
function f() { }

it will work because the definition of f is hoisted to the top so that code is equivalent to:

function f() { }
f();

However, CoffeeScript only hoists the declaration to the top, not the definition. So when say this in CoffeeScript:

f()
f = ->

it looks like this in JavaScript:

var f;
f();
f = function() { };

so f is undefined when it is called and you get a TypeError.

The solution is to put your resetCards() call below the definition of resetCards:

resetCards = ->
    for i in [1..13] by 1
        cards[i - 1] = "club#{i}"
        cards[i + 12] = "dmnd#{i}"
        cards[i + 25] = "hart#{i}"
        cards[i + 38] = "spad#{i}"
        if i < 3
            cards[i + 51] = "joke#{i}"

resetCards()

Another way of looking at it is to realize that this CoffeeScript:

f = ->

is the same as this JavaScript:

var f;
f = function() { };

but that's not quite the same as:

function f() { }

There is no equivalent to function f() { } in CoffeeScript.

like image 101
mu is too short Avatar answered Jan 09 '23 16:01

mu is too short