Squash Edit

From OIP Wiki
Jump to: navigation, search

In order to save some space in the Florincoin Transaction comments, we reduce down the JSON patch schema to arrays of the operations being preformed. The Javascript example code below accepts JSON Patches (RFC6902) and outputs the "squashed" patch. Below you can find the example code to "squash" and "unsquash" the patch.

Squash Javascript Example

function(patch){
	var squashed = {};

	for (var i = 0; i < patch.length; i++) {
		// Store the operation
		var operation = patch[i].op;
		// Remove operation key from squashed patch
		delete patch[i].op;
		// Check what the operation is, and put it in the right place
		if (!squashed[operation])
			squashed[operation] = [];

		var newPatch = {};

		if (patch[i].path && patch[i].value){
			newPatch[patch[i].path] = patch[i].value

			squashed[operation].push(patch[i]);
		} else if (patch[i].path && !patch[i].value) {
			squashed[operation].push(patch[i].path);
		}
	}
	
	return squashed;
}


Un-Squash Javascript Example

function(squashedPatch){
	var patch = [];

	for (var op in squashedPatch){
		for (var i = 0; i < squashedPatch[op].length; i++) {
			// Load what we saved from the patch
			var singlePatch = squashedPatch[op];
			// Create the new single patch to read from
			var newSingle = {};
			// Restore the operation to the patch
			newSingle.op = op;
			
			if (typeof singlePatch === "string"){
				newSingle.path = singlePatch;
			} else if (typeof singlePatch === "object"){
				var path = Object.keys(singlePatch)[0];
				var value = singlePatch[path];
				newSingle.path = path;
				newSingle.value = value;
			}

			// Add newSingle to patch
			patch.push(newSingle);
		}
	}

	return patch;
}