Skip to content

Instantly share code, notes, and snippets.

@jeriley
Created February 20, 2018 04:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeriley/10bbd072e451850d3f78fc7dab4eb308 to your computer and use it in GitHub Desktop.
Save jeriley/10bbd072e451850d3f78fc7dab4eb308 to your computer and use it in GitHub Desktop.
Salesforce ID checksum ... now in typescript!
export class SalesforceChecksum
{
private lookup = {};
private checksumChars = Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZ012345");
constructor()
{
for (var i = 0; i < 32; i++)
{
let value = (i >>> 0).toString(2);
let bit = ('00000'+value).substring(value.length);
this.lookup[bit] = this.checksumChars[i];
}
}
public validCheckSum(salesforceId: string): boolean
{
if (salesforceId.length != 18)
return false;
var chunks = [
salesforceId.substring(0, 5),
salesforceId.substring(5, 10),
salesforceId.substring(10, 15)
];
let checksum = salesforceId.substring(15, 18);
let calculatedChecksum = "";
chunks.forEach(chunk => {
var reversed = chunk.split('').reverse();
var resultString = "";
for (var i = 0; i < reversed.length; i++)
{
if (!isNaN(reversed[i])){
resultString += "0";
}
else if (reversed[i] === reversed[i].toUpperCase()) {
resultString += "1";
}
else {
resultString += "0";
}
}
calculatedChecksum += this.lookup[resultString];
});
return checksum === calculatedChecksum;
}
}
// jasmine tests
import {SalesforceChecksum} from "../SalesforceChecksum";
describe('when checking if a string is a valid salesforce ID', function () {
let checksum = new SalesforceChecksum();
it("this one is valid", ()=> {
expect(checksum.validCheckSum("a0T5000000OV7X7EAL")).toBeTruthy();
});
it("and this one is valid", ()=> {
expect(checksum.validCheckSum("a0Q5000000IdZj4EAF")).toBeTruthy();
});
it("even this one is valid", ()=> {
expect(checksum.validCheckSum("a0Q5000000BlbfcEAB")).toBeTruthy();
});
it("but not this one is too short", ()=> {
expect(checksum.validCheckSum("a0T5000000")).toBeFalsy();
});
it("and this one is too long", ()=> {
expect(checksum.validCheckSum("a0T5000000123512dsadf")).toBeFalsy();
});
it("and this one isnt a valid checksum", ()=> {
expect(checksum.validCheckSum("a0T5000000OV7X7EAX")).toBeFalsy();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment