Skip to content

Instantly share code, notes, and snippets.

@andreconghau
Created June 1, 2022 10:01
Show Gist options
  • Save andreconghau/6208c04b396e50d3f39c5e4220917720 to your computer and use it in GitHub Desktop.
Save andreconghau/6208c04b396e50d3f39c5e4220917720 to your computer and use it in GitHub Desktop.
Instagram How to convert short code to media id two ways
const bigint = require('big-integer')
const lower = 'abcdefghijklmnopqrstuvwxyz';
const upper = lower.toUpperCase();
const numbers = '0123456789'
const ig_alphabet = upper + lower + numbers + '-_'
const bigint_alphabet = numbers + lower
function toShortcode(longid) {
const o = bigint(longid).toString(64)
return o.replace(/<(\d+)>|(\w)/g, (m, m1, m2) => {
return ig_alphabet.charAt((m1)
? parseInt(m1)
: bigint_alphabet.indexOf(m2))
});
}
function fromShortcode(shortcode) {
const o = shortcode.replace(/\S/g, m => {
const c = ig_alphabet.indexOf(m)
const b = bigint_alphabet.charAt(c)
return (b != "") ? b : `<${c}>`
})
return bigint(o, 64).toString(10)
}
console.log('2850692389359545326', toShortcode('2850692389359545326')); // s.b. 'ybyPRoQWzX'
console.log('CePsZ_fr2vu', fromShortcode('CePsZ_fr2vu')); // s.b. '908540701891980503'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment