Question

I am trying to write a helper method to find the intersection of two hashes/Objects like this...

Object::intersect = (obj)->
  t = {}
  t[k] = @[k] for k of obj 
  t

x = { a: 1, b: 2, c: 3 }
w = { a: true, b: 3 }
x.intersect(w) #=> { a: 1, b: 2, intersect: [Function] }

the results are as I expected/wanted EXCEPT for the addition of 'intersect' key/value.

What am I missing here?

Was it helpful?

Solution

Your property is enumerable, that's why it appears in both objects when you iterate.

A solution would be this :

Object.defineProperty Object.prototype, 'intersect', value:(obj)->
  t = {}
  t[k] = @[k] for k of obj
  t

Demonstration (compiled as JS)

But modifying objects you don't own, especially Object is terrible practice and can lead to many unexpected problems for other coders. Read Maintainable JavaScript: Don’t modify objects you don’t own.

Here it would be as easy and so much cleaner to simply define a function taking two objects as arguments...

OTHER TIPS

Adding the 'ownProperty' check removes this intersect property

Object::intersect= (obj) ->
  t = {}
  t[k] = @[k] for own k of obj
  t

coffee> x = {a:1, b:2, c:3}; w = {a:true, b:3}
{ a: true, b: 3 }
coffee> x.intersect(w)
{ a: 1, b: 2 }

If w has keys that are not in x, they will appear in the result with an undefined value.

A more robust function could be constructed from underscore

_ = require 'underscore'
_.pick(x, _.keys(w))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top