Skip to content

Instantly share code, notes, and snippets.

@joshuawarner32
Created July 24, 2015 00:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshuawarner32/14988fb48cf1a452fb3e to your computer and use it in GitHub Desktop.
Save joshuawarner32/14988fb48cf1a452fb3e to your computer and use it in GitHub Desktop.
function jsonShrink(json: any) {
switch(jsonType(json)) {
case 'number':
case 'boolean':
case 'string':
// TODO: delegate to jsverify's shrinker
return [];
case 'null':
return [];
case 'array':
var res: any[] = []
// 1. An array can be simplified into one of its elements
for(var e of json) {
res.push(e);
}
// 2. An array can be simplified by simplifying one of its elements
for(var i = 0; i < json.length; i++) {
var e = json[i];
for(var r of jsonShrink(e)) {
var a: any[] = [];
for(var j = 0; j < json.length; j++) {
if(i === j) {
a.push(r);
} else {
a.push(json[j]);
}
}
res.push(a);
}
}
// 2. An array can be simplified by removing one of its elements
for(var i = 0; i < json.length; i++) {
var a: any[] = [];
for(var j = 0; j < json.length; j++) {
if(j != i) {
a.push(json[j]);
}
}
res.push(a);
}
return res;
case 'object':
var keys = Object.keys(json);
var res: any[] = [];
for(var k of keys) {
// 1. An object can be simplified into one of it keys
res.push(k);
// 2. An object can be simplified into one of its values
res.push(json[k]);
}
// 3. An object can be simplified by simplifying one of its keys
for(var k of keys) {
for(var r of jsonShrink(k)) {
if(keys.indexOf(r) !== -1) {
continue;
}
var o: any = {};
for(var m of keys) {
if(m === k) {
o[r] = json[m];
} else {
o[m] = json[m];
}
}
res.push(o);
}
}
// 3. An object can be simplified by simplifying one of its values
for(var k of keys) {
for(var r of jsonShrink(json[k])) {
var o: any = {};
for(var m of keys) {
if(m === k) {
o[m] = r;
} else {
o[m] = json[m];
}
}
res.push(o);
}
}
// 4. An object can be simplified by removing one of its key/value pairs
for(var k of keys) {
var o: any = {};
for(var m of keys) {
if(k !== m) {
o[m] = json[m];
}
}
res.push(o);
}
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment