1
\$\begingroup\$

Working codepen: http://codepen.io/leongaban/pen/oxwLzE?editors=1010

The function below takes in user entered text through the cli: V=patch gulp build

It then checks for the last version of the build folder, then iterates the appropriate version number.

Hoping to condense all the if/else into more functional code.

lastVersion starts as an empty string var lastVersion = '';

The ver value that is passed into this function from the user will be 1 of these commands:

  • V=major gulp build
  • V=minor gulp build
  • V=patch gulp build

So ver will be major, minor or patch...


function generateNextVersion(ver) {
    var major, minor, patch;
    var versionArray = lastVersion.split('.');

    major = parseInt(versionArray[0]);
    minor = parseInt(versionArray[1]);
    patch = parseInt(versionArray[2]);

    if (ver === 'major') {
        major = parseInt(versionArray[0]) + 1;
    }
    else if (ver === 'minor') {
        minor = parseInt(versionArray[1]) + 1;
    }
    else if (ver === 'patch') {
        patch = parseInt(versionArray[2]) + 1;
    }

    version = major + '.' + minor + '.' + patch;

    if (ver === '' || ver === undefined) {
        version = '0.0.0';
    }

    gutil.log(gutil.colors.blue.bold('##################################################'));
    gutil.log(gutil.colors.blue.bold('         Building Dashboard version '+version));
    gutil.log(gutil.colors.green.bold('~~           All change is detectable           ~~'));
    gutil.log(gutil.colors.blue.bold('##################################################'));
}
\$\endgroup\$
2
  • \$\begingroup\$ What is lastVersion? We are missing something here, it'd be helpful if you post a working demo. \$\endgroup\$
    – elclanrs
    Mar 25, 2016 at 20:18
  • \$\begingroup\$ Added additional info, this is a gulpfile process, just created a codepen here: codepen.io/leongaban/pen/oxwLzE?editors=1010 \$\endgroup\$
    – Leon Gaban
    Mar 25, 2016 at 20:30

1 Answer 1

1
\$\begingroup\$

The first thing that I see is that:

    major = parseInt(versionArray[0]) + 1;

Is a bit redundant. You already say:

major = parseInt(versionArray[0]);

Just do:

major += 1;

(This is similar for all the major, minor and patch statements)

You can also use a switch-case instead of if statements so instead of:

if (ver === 'major') {
    major = parseInt(versionArray[0]) + 1;
}
else if (ver === 'minor') {
    minor = parseInt(versionArray[1]) + 1;
}
else if (ver === 'patch') {
    patch = parseInt(versionArray[2]) + 1;
}

You have:

switch (ver) {
    case 'major':
        major += 1;
        break;
    case 'minor':
        minor += 1;
        break;
    case 'patch':
        patch += 1;
        break;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.