Tell us what’s happening:
- If the input manifest object is not valid, your validateManifest function should return an object describing missing and/or invalid properties.
Your code so far
function normalizeUnits(manifest) {
const copy = { ...manifest };
if ( copy.unit.toLowerCase() === "lb" ) {
copy.weight = Number((copy.weight * 0.45).toFixed(2));
copy.unit = "kg";
}
return copy;
}
function validateManifest(manifest) {
if (
manifest === null ||
manifest === undefined ||
typeof manifest !== "object" ||
Array.isArray(manifest)
) {
return {
containerId: "Missing",
destination: "Missing",
weight: "Missing",
unit: "Missing",
hazmat: "Missing"
};
}
let errors = {};
if ( manifest.containerId === undefined ) {
errors.containerId = "Missing";
} else if ( typeof manifest.containerId !== "number" || manifest.containerId <= 0 || !Number.isInteger(manifest.containerId) ) {
errors.containerId = "Invalid";
};
if ( manifest.destination === undefined ) {
errors.destination = "Missing";
} else if ( typeof manifest.destination !== "string" || manifest.destination.trim() == "" ) {
errors.destination = "Invalid";
};
if ( manifest.weight === undefined ) {
errors.weight = "Missing";
} else if (typeof manifest.weight !== "number" || manifest.weight < 0 || Number.isNaN(manifest.weight) ) {
errors.weight = "Invalid";
};
if ( manifest.unit === undefined ) {
errors.unit = "Missing";
} else if (typeof manifest.unit != "string" || manifest.unit.toLowerCase().trim() == "" || !["kg", "lb"].includes(manifest.unit.toLowerCase()) ) {
errors.unit = "Invalid";
};
if ( manifest.hazmat === undefined ) {
errors.hazmat = "Missing";
} else if (typeof manifest.hazmat != "boolean" ) {
errors.hazmat = "Invalid";
};
return errors;
}
function processManifest(manifest) {
const validateResult = validateManifest(manifest);
if (Object.keys(validateResult).length === 0 ) {
console.log(`Validation success: ${manifest.containerId}`);
const normalizedWeight = normalizeUnits(manifest);
console.log(`Total weight: ${normalizedWeight.weight} kg`)
} else {
console.log(`Validation error: ${manifest.containerId}`)
console.log(validateManifest(manifest))
}
}
const testt = { containerId: 55, weight: 400, unit: "lb", hazmat: false }
processManifest(testt)
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36
Challenge Information:
Build a Cargo Manifest Validator - Build a Cargo Manifest Validator