Exercism v3 launches on Sept 1st 2021. Learn more! πŸš€πŸš€πŸš€
Avatar of rootulp

rootulp's solution

to Hexadecimal in the CoffeeScript Track

Published at Jul 13 2018 · 0 comments
Test suite


This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Convert a hexadecimal number, represented as a string (e.g. "10af8c"), to its decimal equivalent using first principles (i.e. no, you may not use built-in or external libraries to accomplish the conversion).

On the web we use hexadecimal to represent colors, e.g. green: 008000, teal: 008080, navy: 000080).

The program should handle invalid hexadecimal strings.

Refer to the Exercism CoffeScript page for getting started with CoffeeScript.

In order to run the test, you can run the test file from the exercise directory:

jasmine-node --coffee .


All of Computer Science http://www.wolframalpha.com/examples/NumberBases.html

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.


Hexadecimal = require('./hexadecimal')

describe "Hexadecimal", ->

  it "hex 1 is decimal 1", ->
    hex = new Hexadecimal("1")

  xit "hex c is decimal 12", ->
    hex = new Hexadecimal("c")

  xit "hex 10 is decimal 16", ->
    hex = new Hexadecimal("10")

  xit "hex af is decimal 175", ->
    hex = new Hexadecimal("af")

  xit "hex 100 is decimal 256", ->
    hex = new Hexadecimal("100")

  xit "hex 19ace is decimal 105166", ->
    hex = new Hexadecimal("19ace")

  xit "invalid hex is decimal 0", ->
    hex = new Hexadecimal("carrot")

  xit "black", ->
    hex = new Hexadecimal("000000")

  xit "white", ->
    hex = new Hexadecimal("ffffff")

  xit "yellow", ->
    hex = new Hexadecimal("ffff00")
module.exports = class Hexadecimal
  constructor: (str) ->
    @reverse_str = str.split('').reverse().join('')
    @CHAR_VALS =
      a: 10
      b: 11
      c: 12
      d: 13
      e: 14
      f: 15

  toDecimal: ->
    return 0 if (/[^a-f0-9]/).test(@reverse_str)

    result = 0
    for i in [0..@reverse_str.length - 1]
      result += (16 ** i) * @valFor(@reverse_str[i])

  valFor: (symbol) ->
    if @CHAR_VALS[symbol] then @CHAR_VALS[symbol] else symbol

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?