Created
March 17, 2015 19:06
-
-
Save jgillman/8c7f80a5ccac453424cf to your computer and use it in GitHub Desktop.
Check the validity of a FedEx tracking number based on their 2011 spec
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Depends on ECMAScript 6 for the `map` and `reduce` functions. They are | |
// easily replaced with a library like Lodash or Underscore. | |
var FedExChecker = (function() { | |
'use strict'; | |
var CHECK_WEIGHT_ARRAY, TRACKING_NUMBER_MAX_LENGTH, digitsToArray; | |
function FedExChecker() {} | |
digitsToArray = function( _num ) { | |
return _num.toString().split('').map( function( digit ) { | |
return parseInt( digit, 10 ); | |
}); | |
}; | |
CHECK_WEIGHT_ARRAY = [1,3,7]; | |
TRACKING_NUMBER_MAX_LENGTH = 14 | |
FedExChecker.prototype.isValid = function( _code ) { | |
var codeArray, checkDigit, weightedArray, weightedSum; | |
codeArray = digitsToArray( _code ) | |
if ( codeArray.length < 12 ) { | |
throw new Error('tracking code cannot be less than 12 digits'); | |
} | |
// Array-ize the tracking code and grab the last 14 digits | |
codeArray = codeArray.slice( TRACKING_NUMBER_MAX_LENGTH * -1 ); | |
// Remove and store the checkDigit from the tracking code | |
checkDigit = codeArray.pop(); | |
// Reverse codeArray for mapping weight | |
codeArray = codeArray.reverse(); | |
// Calculate the code array with weights | |
weightedArray = codeArray.map( function( currentValue, index ) { | |
var currentWeight = CHECK_WEIGHT_ARRAY[index % CHECK_WEIGHT_ARRAY.length]; | |
return currentValue * currentWeight; | |
}); | |
// Sum the weighed numbers array | |
weightedSum = weightedArray.reduce( function( previousValue, currentValue ) { | |
return previousValue + currentValue; | |
}); | |
return (weightedSum % 11) % 10 === checkDigit; | |
}; | |
return FedExChecker; | |
})(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
checker = new FedExChecker(); | |
// Providing a well formed FedEx tracking code | |
checker.isValid(00790112586297); | |
// true | |
// Changing the code by one digit (fat fingered user) | |
checker.isValid(00790112586287); | |
// false | |
// Accepts full FedEx barcode | |
checker.isValid(147701408120018034000790112586297); | |
// true | |
// Rejects codes that are too short | |
checker.isValid(79011258629); | |
// Error: tracking code cannot be less than 12 digits |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment