How do I create a URL shortener?

后端 未结 30 2621
我寻月下人不归
我寻月下人不归 2020-11-22 05:11

I want to create a URL shortener service where you can write a long URL into an input field and the service shortens the URL to \"http://www.example.org/abcdef\

30条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 05:20

    Implementation in Scala:

    class Encoder(alphabet: String) extends (Long => String) {
    
      val Base = alphabet.size
    
      override def apply(number: Long) = {
        def encode(current: Long): List[Int] = {
          if (current == 0) Nil
          else (current % Base).toInt :: encode(current / Base)
        }
        encode(number).reverse
          .map(current => alphabet.charAt(current)).mkString
      }
    }
    
    class Decoder(alphabet: String) extends (String => Long) {
    
      val Base = alphabet.size
    
      override def apply(string: String) = {
        def decode(current: Long, encodedPart: String): Long = {
          if (encodedPart.size == 0) current
          else decode(current * Base + alphabet.indexOf(encodedPart.head),encodedPart.tail)
        }
        decode(0,string)
      }
    }
    

    Test example with Scala test:

    import org.scalatest.{FlatSpec, Matchers}
    
    class DecoderAndEncoderTest extends FlatSpec with Matchers {
    
      val Alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    
      "A number with base 10" should "be correctly encoded into base 62 string" in {
        val encoder = new Encoder(Alphabet)
        encoder(127) should be ("cd")
        encoder(543513414) should be ("KWGPy")
      }
    
      "A base 62 string" should "be correctly decoded into a number with base 10" in {
        val decoder = new Decoder(Alphabet)
        decoder("cd") should be (127)
        decoder("KWGPy") should be (543513414)
      }
    
    }
    

提交回复
热议问题