Skip to content

Commit

Permalink
support custom format function
Browse files Browse the repository at this point in the history
  • Loading branch information
vicanso committed Oct 19, 2017
1 parent 5e5c660 commit e8f66c1
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
15 changes: 15 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict';

const customFormat = {};

exports.divider = ' ';

// decide the value should be mask
Expand All @@ -23,6 +25,9 @@ function isObject(value) {
}

function toString(k, v, level) {
if (customFormat[k]) {
return customFormat[k](v);
}
if (exports.isSecret && exports.isSecret(k)) {
if (isString(v)) {
return `${k}="***"`;
Expand Down Expand Up @@ -71,4 +76,14 @@ function stringify(json, level) {
return format(json, level || exports.maxLevel);
}

function addFormat(key, fn) {
customFormat[key] = fn;
}

function removeFormat(key) {
delete customFormat[key];
}

exports.json = stringify;
exports.addFormat = addFormat;
exports.removeFormat = removeFormat;
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "simple-stringify",
"version": "1.1.3",
"version": "1.2.0",
"description": "stringify json on top attr",
"author": "Tree Xie <vicansocanbico@gmail.com>",
"repository": {
Expand Down
8 changes: 8 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ describe('Simple-stringify', () => {
console.dir('test');
},
};

it('add custom format', () => {
stringify.addFormat('myCustomKey', v => `myCustomKey="length(${v.length})"`);
assert.equal(stringify.json({
myCustomKey: 'abcd',
}), 'myCustomKey="length(4)"');
stringify.removeFormat('myCustomKey');
});

it('format json success', () => {
assert.equal(stringify.json(data), 'no=123 mobile=null addresss=undefined disabled=false name="tree.xie" keywords=[] infos={} fn=function');
Expand Down

0 comments on commit e8f66c1

Please sign in to comment.