meleyal
meleyal

Reputation: 33300

How to refactor this array comparison with underscore.js?

Can this code be refactored in a more functional/underscore style, mainly the part that checks for the presence of addedEvents in actualEvents?

describe 'when removing', ->

  it 'should remove all bound events from the window', ->
    @view.remove()
    addedEvents = ['dragenter', 'drop', 'dragleave', 'register']
    actualEvents = _.keys $._data(window, 'events') #=> ['onload', 'drop', 'etc.']
    for event in addedEvents
      present = _.contains(actualEvents, event)
      expect(present).toBe(false)

Upvotes: 0

Views: 243

Answers (2)

epidemian
epidemian

Reputation: 19219

Maybe using Coffee's postfix for and in operator can make the code more readable:

addedEvents = ['dragenter', 'drop', 'dragleave', 'register']
actualEvents = _.keys $._data(window, 'events') #=> ['onload', 'drop', 'etc.']
expect(event not in actualEvents).toBe(true) for event in addedEvents

If you're using Jasmine as your testing library, you can use the toContain which i think is more readable :)

expect(actualEvents).not.toContain(event) for event in addedEvents

Finally, if you want to go for a more functional style with Underscore, you can think of this assertion as checking that none of the addedEvents is present on the actualEvents, in other words, that the intersection of those two arrays is empty:

expect(_.intersection(actualEvents, addedEvents).length).toBe(0)

Upvotes: 1

phenomnomnominal
phenomnomnominal

Reputation: 5515

If you specifically want it to be using underscore functions, then the following should do.

addedEvents = ['dragenter', 'drop', 'dragleave', 'register']
actualEvents = _.keys $._data(window, 'events')
present = _.reduce addedEvents, ((prev, current) ->
  prev or _.contains actualEvents, current 
  ), false)
expect(present).toBe false

Of course, you can do this without underscore, but it requires ES5 functions:

addedEvents = ['dragenter', 'drop', 'dragleave', 'register']
actualEvents = Object.keys $._data(window, 'events')
present = addedEvents.reduce, ((prev, current) ->
  prev or actualEvents.indexOf(current) > -1
  ), false)
expect(present).toBe false

Upvotes: 1

Related Questions