Skip to content

Instantly share code, notes, and snippets.

@Apmyp
Created April 11, 2020 08:17
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 Apmyp/0f3426dc7f23501f70faf4bb94a4e68c to your computer and use it in GitHub Desktop.
Save Apmyp/0f3426dc7f23501f70faf4bb94a4e68c to your computer and use it in GitHub Desktop.
Shorten your ids by converting them to base n number system

How shortener feature works

I have to make a system which can give us short version of URL and a way to track clicks.

This gist is about how I solved the first part of problem: as short as possible URL.

First things first. If we talk about system which handle URLs then we should have a table in database.

Example table of URLs:

ID URL
1 https://example.com/
2 https://reddit.com/
174579021 https://random.cat/

My solution is to convert urls ID into base-n number system. This way allows to leave the database table as it is.

For example if we convert last url ID 174579021 to base 16 we will get A67DD4D. But if we convert the same ID to base 64 with custom chars (from javascript example below) we will get 9OxpC.

Now I can implement simple action /:convertedID , convert ID back to decimal and search the ID through primary key.

Benefits:

  • DB table remains the same
  • User sees pseudo-random (because of converted primary key) short link
  • No one cannot search through other links until they know char set

About author

Channel Author
Telegram userpic Apmyp userpic
@Apmyp
Copy link
Author

Apmyp commented Apr 11, 2020

function shortener() {
  const chars = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'.split('');
  const count = chars.length;
  
  function encode(num) {
    if ( num === 0 ) {
      return "";
    } else if ( num > 0 ) {
      return encode(parseInt(num / count, 10)) + chars[num % count];
    }
  }
  
  function decode(str) {
    return str.split('').reduce((num, val) => { 
      return num * count + chars.indexOf(val);
    }, 0);
  }

	return {
  	encode,
    decode
  };
}

export { shortener };

@Apmyp
Copy link
Author

Apmyp commented Apr 11, 2020

import { shortener } from "./shorten.js";

const { encode, decode } = shortener();

encode(1233); // => 'IG'
decode(encode(1233)); // => 1233

encode(112233); // => 'QOd'
decode(encode(112233)); // => 112233

encode(1000000000); // => 'vagc-'
decode(encode(1000000000)); // => 1000000000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment