Skip to content

Commit

Permalink
[Robustness] use call-bind to invoke replacer
Browse files Browse the repository at this point in the history
  • Loading branch information
ljharb committed Nov 10, 2023
1 parent 494a3ce commit c52438f
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
9 changes: 5 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ var jsonStringify = (typeof JSON !== 'undefined' ? JSON : require('jsonify')).st

var isArray = require('isarray');
var objectKeys = require('object-keys');
var callBind = require('call-bind');

module.exports = function (obj, opts) {
if (!opts) { opts = {}; }
if (typeof opts === 'function') { opts = { cmp: opts }; }
var space = opts.space || '';
if (typeof space === 'number') { space = Array(space + 1).join(' '); }
var cycles = typeof opts.cycles === 'boolean' ? opts.cycles : false;
var replacer = opts.replacer || function (key, value) { return value; };
var replacer = opts.replacer ? callBind(opts.replacer) : function (parent, key, value) { return value; };

var cmpOpt = opts.cmp;
var cmp = cmpOpt && function (node) {
Expand All @@ -34,7 +35,7 @@ module.exports = function (obj, opts) {
node = node.toJSON();
}

node = replacer.call(parent, key, node);
node = replacer(parent, key, node);

if (node === undefined) {
return;
Expand Down Expand Up @@ -65,8 +66,8 @@ module.exports = function (obj, opts) {
if (!value) { continue; }

var keyValue = jsonStringify(key)
+ colonSeparator
+ value;
+ colonSeparator
+ value;

out.push(indent + space + keyValue);
}
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"description": "deterministic JSON.stringify() with custom sorting to get deterministic hashes from stringified results",
"main": "index.js",
"dependencies": {
"call-bind": "^1.0.5",
"isarray": "^2.0.5",
"jsonify": "^0.0.1",
"object-keys": "^1.1.1"
Expand Down

0 comments on commit c52438f

Please sign in to comment.