You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

27 lines
907 B

  1. exports = module.exports = stringify
  2. exports.getSerialize = serializer
  3. function stringify(obj, replacer, spaces, cycleReplacer) {
  4. return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces)
  5. }
  6. function serializer(replacer, cycleReplacer) {
  7. var stack = [], keys = []
  8. if (cycleReplacer == null) cycleReplacer = function(key, value) {
  9. if (stack[0] === value) return "[Circular ~]"
  10. return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]"
  11. }
  12. return function(key, value) {
  13. if (stack.length > 0) {
  14. var thisPos = stack.indexOf(this)
  15. ~thisPos ? stack.splice(thisPos + 1) : stack.push(this)
  16. ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)
  17. if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value)
  18. }
  19. else stack.push(value)
  20. return replacer == null ? value : replacer.call(this, key, value)
  21. }
  22. }