Build a Cargo Manifest Validator - Build a Cargo Manifest Validator

Tell us what’s happening:

Всем доброго дня!
Подскажите, пожалуйста, никаких образом не хочет выполняться 15-й пункт. Через ИИ прогонял, сам голову ломаю и не могу понять в чем проблема. При вводе данных выдает необходимые параметры, а по факту тест не пропускает 15-й пункт как выполненный.

  1. Если входной объект манифеста недействителен, ваша validateManifestфункция должна вернуть объект, описывающий отсутствующие и/или недействительные свойства.

Your code so far

function normalizeUnits(manifest) {
    const newManifest = { ...manifest };
    if (newManifest.unit === "lb") {
        newManifest.weight = newManifest.weight * 0.45;
        newManifest.unit = "kg";
    }
    return newManifest;
}

function validateManifest(manifest) {
    // 1. Если передан не объект — всё Missing
    if (typeof manifest !== 'object' || manifest === null) {
        return {
            containerId: "Missing",
            destination: "Missing",
            weight: "Missing",
            unit: "Missing",
            hazmat: "Missing"
        };
    }

    const errors = {};

    // Безопасная проверка собственного свойства (работает даже с Object.create(null))
    const hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty);

    // containerId
    if (!hasOwn(manifest, 'containerId')) {
        errors.containerId = "Missing";
    } else {
        const v = manifest.containerId;
        if (typeof v !== 'number' || !Number.isInteger(v) || v <= 0) {
            errors.containerId = "Invalid";
        }
    }

    // destination
    if (!hasOwn(manifest, 'destination')) {
        errors.destination = "Missing";
    } else {
        const v = manifest.destination;
        if (typeof v !== 'string') {
            errors.destination = "Invalid";
        } else if (v.trim() === '') {
            errors.destination = "Invalid";
        }
    }

    // weight
    if (!hasOwn(manifest, 'weight')) {
        errors.weight = "Missing";
    } else {
        const v = manifest.weight;
        if (typeof v !== 'number' || Number.isNaN(v) || v <= 0) {
            errors.weight = "Invalid";
        }
    }

    // unit
    if (!hasOwn(manifest, 'unit')) {
        errors.unit = "Missing";
    } else {
        const v = manifest.unit;
        if (typeof v !== 'string') {
            errors.unit = "Invalid";
        } else {
            const lowered = v.trim().toLowerCase();
            if (lowered !== 'kg' && lowered !== 'lb') {
                errors.unit = "Invalid";
            }
        }
    }

    // hazmat
    if (!hasOwn(manifest, 'hazmat')) {
        errors.hazmat = "Missing";
    } else {
        const v = manifest.hazmat;
        if (typeof v !== 'boolean') {
            errors.hazmat = "Invalid";
        }
    }

    return errors;
}

function processManifest(manifest) {
    const errors = validateManifest(manifest);
    if (Object.keys(errors).length === 0) {
        console.log(`Validation success: ${manifest.containerId}`);
        const normalized = normalizeUnits(manifest);
        console.log(`Total weight: ${normalized.weight} kg`);
    } else {
        console.log(`Validation error: ${manifest.containerId}`);
        console.log(errors);
    }
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36

Challenge Information:

Build a Cargo Manifest Validator - Build a Cargo Manifest Validator

GitHub Link: freeCodeCamp/curriculum/challenges/english/blocks/lab-cargo-manifest-validator/69a56b5069ca99f7317e6e19.md at main · freeCodeCamp/freeCodeCamp · GitHub

Welcome to the forum @alexmadbestseller,

We need to see your code to help you.


If you have a question about a specific challenge as it relates to your written code for that challenge and need some help, click the Help button located on the challenge.

The Help button will create a new topic with all code you have written and include a link to the challenge also. You will still be able to ask any questions in the post before submitting it to the forum.

Thank you.


Happy coding

function normalizeUnits(manifest) {

    const newManifest = { ...manifest };

    if (newManifest.unit === "lb") {

        newManifest.weight = newManifest.weight \* 0.45;

        newManifest.unit = "kg";

    }

    return newManifest;

}



function validateManifest(manifest) {

    // 1. Если передан не объект — всё Missing

    if (typeof manifest !== 'object' || manifest === null) {

        return {

            containerId: "Missing",

            destination: "Missing",

            weight: "Missing",

            unit: "Missing",

            hazmat: "Missing"

        };

    }



    const errors = {};



    // Безопасная проверка собственного свойства (работает даже с Object.create(null))

    const hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty);



    // containerId

    if (!hasOwn(manifest, 'containerId')) {

        errors.containerId = "Missing";

    } else {

        const v = manifest.containerId;

        if (typeof v !== 'number' || !Number.isInteger(v) || v <= 0) {

            errors.containerId = "Invalid";

        }

    }



    // destination

    if (!hasOwn(manifest, 'destination')) {

        errors.destination = "Missing";

    } else {

        const v = manifest.destination;

        if (typeof v !== 'string') {

            errors.destination = "Invalid";

        } else if (v.trim() === '') {

            errors.destination = "Invalid";

        }

    }



    // weight

    if (!hasOwn(manifest, 'weight')) {

        errors.weight = "Missing";

    } else {

        const v = manifest.weight;

        if (typeof v !== 'number' || Number.isNaN(v) || v <= 0) {

            errors.weight = "Invalid";

        }

    }



    // unit

    if (!hasOwn(manifest, 'unit')) {

        errors.unit = "Missing";

    } else {

        const v = manifest.unit;

        if (typeof v !== 'string') {

            errors.unit = "Invalid";

        } else {

            const lowered = v.trim().toLowerCase();

            if (lowered !== 'kg' && lowered !== 'lb') {

                errors.unit = "Invalid";

            }

        }

    }



    // hazmat

    if (!hasOwn(manifest, 'hazmat')) {

        errors.hazmat = "Missing";

    } else {

        const v = manifest.hazmat;

        if (typeof v !== 'boolean') {

            errors.hazmat = "Invalid";

        }

    }



    return errors;

}



function processManifest(manifest) {

    const errors = validateManifest(manifest);

    if (Object.keys(errors).length === 0) {

        console.log(\`Validation success: ${manifest.containerId}\`);

        const normalized = normalizeUnits(manifest);

        console.log(\`Total weight: ${normalized.weight} kg\`);

    } else {

        console.log(\`Validation error: ${manifest.containerId}\`);

        console.log(errors);

    }

}

I’ve edited your post to correctly format the code. In the future, please use this reference for that:


There are two ways you can format your code to make it easier to read and test:

  1. After you copy/paste your code into the editor, select it by dragging your cursor over it then click the (</>) button in the toolbar to automatically wrap your code in backticks. (You can click on the animated demo image below to enlarge it.)

  1. Manually add three backticks on a new line above your code and on a new line after your code. Note that a backtick is NOT the same as a single quote('). To find the backtick key on your keyboard, see this post.

To see changes to your post as you make them, you can click the (M+) button on the toolbar to bring up the rich text editor:


Thank you.

Does it make sense to manipulate the unit value before you validate it?

Happy coding

В данном примере предложена версия программы в не самом оптимальном варианте, поскольку в неоднократных попытках реализации 15-го пункта и учета возможных исходов поведения программы - успешных результатов, увы, не достигнуто.

So, you think a unit value of " KG " should be valid?