0

Please review the code below and suggest more elegant ways of doing the same.

I am storing JSON strings in Redis database. To extract an array of objects, I use the following code that works. Just for learning though I wanted to find better ways of doing the same. Here is the CoffeeScript code:

redis = require "redis"
client = module.exports.client = redis.createClient()

getRecord = module.exports.getRecord = (key, fn) ->
  client.get key, (err, result) ->
    fn err, null if err
    obj = JSON.parse(result)
    fn null, obj

getDataSet = module.exports.getDataSet = (pattern, fn) ->
  client.keys pattern, (err, result) ->
    fn err, null if err
    dataSet = []
    length = result.length
    count = 0
    for key in result
      getRecord key, (err, obj) ->
        fn err, null if err
        count = count + 1
        dataSet.push obj
        fn null, dataSet if count is length

1 Answer 1

3

I think your code is pretty solid. Just be warned that your

for key in result

loop is creating a list comprehension; that means that if result.length is large, you're going to see significant performance overhead and perhaps even memory issues. To avoid this, you need to add an explicit return:

for key in result
  getRecord key, (err, obj) ->
    ...
return

There was a proposal to introduce a void function syntax for just such cases, but none of CoffeeScript's core committers seem very fond of it.

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.