Created
November 6, 2015 19:00
Revisions
-
knation created this gist
Nov 6, 2015 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,61 @@ /** * The regex for a SF ID. * @type {RegExp} * @const */ var ID_REGEX = /^[0-9a-zA-Z]{15}([0-9a-zA-Z]{3})?$/; /** * Array used to expand a SF ID from 15 to 18 characters. * @type {Array.<String>} * @const */ var ID_EXPAND_ARRAY = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5']; /** * Constructor for SalesforceId object. * @param {String} id * @this {SalesforceId} */ function SalesforceId(id) { this.id = id; } /** * Checks the ID to make sure its format is valid for Salesforce. * @this {SalesforceId} * @return {Boolean} */ SalesforceId.prototype.isValid = function() { return ID_REGEX.test(this.id); }; /** * Creates an 18-character ID if not already. If invalid, returns null. * @this {SalesforceId} * @return {?String} */ SalesforceId.prototype.expand = function() { if (!this.isValid(this.id)) { // Return null if invalid return null; } else if (this.id.length === 18) { // Return as-is if already 18 chars return this.id; } else { var chunks = [this.id.substr(0, 5), this.id.substr(5, 5), this.id.substr(10, 5)] , chunkBits = ['','','']; for (var i=0;i<chunks[0].length;i++) chunkBits[0] = (/[A-Z]/.test(chunks[0].substr(i, 1)) ? '1' : '0') + chunkBits[0]; for (var i=0;i<chunks[1].length;i++) chunkBits[1] = (/[A-Z]/.test(chunks[1].substr(i, 1)) ? '1' : '0') + chunkBits[1]; for (var i=0;i<chunks[2].length;i++) chunkBits[2] = (/[A-Z]/.test(chunks[2].substr(i, 1)) ? '1' : '0') + chunkBits[2]; chunkBits[0] = parseInt(chunkBits[0], 2); chunkBits[1] = parseInt(chunkBits[1], 2); chunkBits[2] = parseInt(chunkBits[2], 2); return this.id + ID_EXPAND_ARRAY[chunkBits[0]] + ID_EXPAND_ARRAY[chunkBits[1]] + ID_EXPAND_ARRAY[chunkBits[2]]; } };