1
\$\begingroup\$

I need to produce a list objCollector with some results:

objCollector = []

      allRows.each () ->
        obj =
          source: self.source
          url: ''
          host: ''

        currentTag = $(this)
        links = currentTag.find('a')
        getTextFromSpan = currentTag.find('span.lnk').text()
        extractedLink = links[0].attribs.href
        obj.url = self.baseUrl + extractedLink
        obj.host = getTextFromSpan

        objCollector.push obj

Instead of building the result by appending to an empty list, could this be done more elegantly by using something like map?

\$\endgroup\$
1
  • \$\begingroup\$ @NickUdell this code is not broken! it just needs for refactor and code review \$\endgroup\$ Commented May 29, 2015 at 14:30

1 Answer 1

1
\$\begingroup\$

I just moved things around to make it a bit more readable. You can use the map function instead of each. The signature of map is as follows:

  1. element in array
  2. index of element
  3. the array itself

I've added those parameters in the coffee script, but you could have easily done without them for a cleaner look. I assumed that self is some kind of global variable or variable available to the inner scope of the map.

See the Mozilla article on map. It's fantastic!

objCollector = allRows.map (element, index, context) ->
  tag = $(element)

  text = tag.find('span.lnk').text()
  link = tag.find('a').first().attribs.href

  {
    source: self.source
    url: self.baseUrl + link
    host: text
  }
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.