whet.extend.coffee 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. ###
  2. * whet.extend v0.9.7
  3. * Standalone port of jQuery.extend that actually works on node.js
  4. * https://github.com/Meettya/whet.extend
  5. *
  6. * Copyright 2012, Dmitrii Karpich
  7. * Released under the MIT License
  8. ###
  9. module.exports = extend = (deep, target, args...) ->
  10. unless _isClass deep, 'Boolean'
  11. args.unshift target
  12. [ target, deep ] = [ deep or {}, false ]
  13. #Handle case when target is a string or something (possible in deep copy)
  14. target = {} if _isPrimitiveType target
  15. for options in args when options?
  16. for name, copy of options
  17. target[name] = _findValue deep, copy, target[name]
  18. target
  19. ###
  20. Internal methods from now
  21. ###
  22. _isClass = (obj, str) ->
  23. "[object #{str}]" is Object::toString.call obj
  24. _isOwnProp = (obj, prop) ->
  25. Object::hasOwnProperty.call obj, prop
  26. _isTypeOf = (obj, str) ->
  27. str is typeof obj
  28. _isPlainObj = (obj) ->
  29. return false unless obj
  30. return false if obj.nodeType or obj.setInterval or not _isClass obj, 'Object'
  31. # Not own constructor property must be Object
  32. return false if obj.constructor and
  33. not _isOwnProp(obj, 'constructor') and
  34. not _isOwnProp(obj.constructor::, 'isPrototypeOf')
  35. # Own properties are enumerated firstly, so to speed up,
  36. # if last one is own, then all properties are own.
  37. key for key of obj
  38. key is undefined or _isOwnProp obj, key
  39. _isPrimitiveType = (obj) ->
  40. not ( _isTypeOf(obj, 'object') or _isTypeOf(obj, 'function') )
  41. _prepareClone = (copy, src) ->
  42. if _isClass copy, 'Array'
  43. if _isClass src, 'Array' then src else []
  44. else
  45. if _isPlainObj src then src else {}
  46. _findValue = (deep, copy, src) ->
  47. # if we're merging plain objects or arrays
  48. if deep and ( _isClass(copy, 'Array') or _isPlainObj copy )
  49. clone = _prepareClone copy, src
  50. extend deep, clone, copy
  51. else
  52. copy