a0639d94c158048542bde78157471c527cb85dae862446b07963af458eb47558da55846cb9962a247c2c41d9ad659cdcef71eeee1e278a525c157d16f69db2 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # sigmund
  2. Quick and dirty signatures for Objects.
  3. This is like a much faster `deepEquals` comparison, which returns a
  4. string key suitable for caches and the like.
  5. ## Usage
  6. ```javascript
  7. function doSomething (someObj) {
  8. var key = sigmund(someObj, maxDepth) // max depth defaults to 10
  9. var cached = cache.get(key)
  10. if (cached) return cached
  11. var result = expensiveCalculation(someObj)
  12. cache.set(key, result)
  13. return result
  14. }
  15. ```
  16. The resulting key will be as unique and reproducible as calling
  17. `JSON.stringify` or `util.inspect` on the object, but is much faster.
  18. In order to achieve this speed, some differences are glossed over.
  19. For example, the object `{0:'foo'}` will be treated identically to the
  20. array `['foo']`.
  21. Also, just as there is no way to summon the soul from the scribblings
  22. of a cocaine-addled psychoanalyst, there is no way to revive the object
  23. from the signature string that sigmund gives you. In fact, it's
  24. barely even readable.
  25. As with `util.inspect` and `JSON.stringify`, larger objects will
  26. produce larger signature strings.
  27. Because sigmund is a bit less strict than the more thorough
  28. alternatives, the strings will be shorter, and also there is a
  29. slightly higher chance for collisions. For example, these objects
  30. have the same signature:
  31. var obj1 = {a:'b',c:/def/,g:['h','i',{j:'',k:'l'}]}
  32. var obj2 = {a:'b',c:'/def/',g:['h','i','{jkl']}
  33. Like a good Freudian, sigmund is most effective when you already have
  34. some understanding of what you're looking for. It can help you help
  35. yourself, but you must be willing to do some work as well.
  36. Cycles are handled, and cyclical objects are silently omitted (though
  37. the key is included in the signature output.)
  38. The second argument is the maximum depth, which defaults to 10,
  39. because that is the maximum object traversal depth covered by most
  40. insurance carriers.