Created
February 20, 2018 04:50
-
-
Save jeriley/10bbd072e451850d3f78fc7dab4eb308 to your computer and use it in GitHub Desktop.
Salesforce ID checksum ... now in typescript!
This file contains 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
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; | |
} | |
} |
This file contains 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
// 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