Ivan
Ivan

Reputation: 7746

Global scope & namespaces

How do I access the stocks variable from inside broadcast

var net = require('net');
var ReadWriteLock = require('rwlock');

var stocks = [
    {symbol: "GM", open: 48.37},
    {symbol: "GE", open: 29.50}
];

var server = net.createServer(function(socket) {
    // Handle incoming messages from clients.
    socket.on('data', function (data) {
        broadcast(data, socket);
    });

    function broadcast(message, sender) {
        lock.readLock(function (release) {
            ....
            maxChange = 100.0 * 0.005;
            change = (maxChange - Math.random() * maxChange * 2);

            stock = stocks[symbol],
            maxChange = stock.open * 0.005,
            ....
           //**How do I access stocks  from here?**
        });

        release();
    });    
 }

Gives error:

  maxChange = stock.open * 0.005,                                 ^
  TypeError: Cannot read property 'open' of undefined

Upvotes: 0

Views: 28

Answers (1)

Legit Dongo
Legit Dongo

Reputation: 66

Your code implies that symbol is a key of the array, but it is not. It is a property in one of the objects in the array.
Use this:

Array.prototype.myFind = function(obj) {
    return this.filter(function(item) {
        for (var prop in obj){
            if (!(prop in item) || obj[prop] !== item[prop]){
                 return false;
            }
        }
        return true;
    });
};
// then use:
var arrayFound = stocks.myFind({'symbol':symbol});

This will find the array element where the symbol property of the object is equal to the variable symbol
Found here

Upvotes: 1

Related Questions