All files normalize.js

97.29% Statements 36/37
96.42% Branches 27/28
100% Functions 3/3
97.22% Lines 35/36

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86        1x     1x 1x   1x     1x 1x     1728x         1728x 4x           1724x 554x 491x   63x       1170x 113x     1057x         1057x 1057x 1057x 2592x 585x 585x   2007x 86x 86x   1921x 498x 498x   1423x   1057x                       129x   129x 126x   3x       1x  
'use strict';
 
/* eslint no-use-before-define: ["error", { "functions": false }] */
 
const { error } = require( './error.js' );
const {
	convertBenjaminArrayToZList, isArray, isZObjectReference, isString,
	makeMappedResultEnvelope } = require( './utils.js' );
const { SchemaFactory } = require( './schema' );
 
const mixedFactory = SchemaFactory.MIXED();
// Canonical form syntax is a superset of normal form syntax, so this validator
// captures mixed forms.
const mixedZ1Validator = mixedFactory.create( 'Z1' );
const mixedZ99Validator = mixedFactory.create( 'Z99' );
 
function isQuote( ZObject ) {
	return mixedZ99Validator.validate( ZObject );
}
 
// the input is assumed to be a well-formed ZObject, or else the behaviour is undefined
function normalize( o ) {
	if ( isQuote( o ) ) {
		return {
			Z1K1: normalize( o.Z1K1 ),
			Z99K1: o.Z99K1
		};
	}
 
	if ( isString( o ) ) {
		if ( isZObjectReference( o ) ) {
			return { Z1K1: 'Z9', Z9K1: o };
		} else {
			return { Z1K1: 'Z6', Z6K1: o };
		}
	}
 
	if ( isArray( o ) ) {
		return convertBenjaminArrayToZList( o.map( normalize ), false );
	}
 
	Iif ( o.Z1K1 === 'Z5' &&
		( o.Z5K1.Z1K1 === error.syntax_error || o.Z5K1.Z1K1 === error.not_wellformed ) ) {
		return o;
	}
 
	const keys = Object.keys( o );
	const result = {};
	for ( let i = 0; i < keys.length; i++ ) {
		if ( keys[ i ] === 'Z1K1' && ( o.Z1K1 === 'Z6' || o.Z1K1 === 'Z9' ) ) {
			result.Z1K1 = o.Z1K1;
			continue;
		}
		if ( keys[ i ] === 'Z6K1' && isString( o.Z6K1 ) ) {
			result.Z6K1 = o.Z6K1;
			continue;
		}
		if ( keys[ i ] === 'Z9K1' && isString( o.Z9K1 ) ) {
			result.Z9K1 = o.Z9K1;
			continue;
		}
		result[ keys[ i ] ] = normalize( o[ keys[ i ] ] );
	}
	return result;
}
 
/**
 * Normalizes a canonical ZObject. Returns a Z22/'Evaluation result' containing the normalized
 * ZObject or a Z5/Error (in the metadata map of the Z22).
 *
 * @param {Object} o a ZObject
 * @return {Object} a Z22 / Evaluation result
 */
 
function normalizeExport( o ) {
	const status = mixedZ1Validator.validateStatus( o );
 
	if ( status.isValid() ) {
		return makeMappedResultEnvelope( normalize( o ), null );
	} else {
		return makeMappedResultEnvelope( null, status.getZ5() );
	}
}
 
module.exports = normalizeExport;