 # rootulp's solution

## to Hexadecimal in the CoffeeScript Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

#### Note:

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 .
``````

## Source

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')

it "hex 1 is decimal 1", ->
expect(hex.toDecimal()).toEqual(1)

xit "hex c is decimal 12", ->
expect(hex.toDecimal()).toEqual(12)

xit "hex 10 is decimal 16", ->
expect(hex.toDecimal()).toEqual(16)

xit "hex af is decimal 175", ->
expect(hex.toDecimal()).toEqual(175)

xit "hex 100 is decimal 256", ->
expect(hex.toDecimal()).toEqual(256)

xit "hex 19ace is decimal 105166", ->
expect(hex.toDecimal()).toEqual(105166)

xit "invalid hex is decimal 0", ->
expect(hex.toDecimal()).toEqual(0)

xit "black", ->
expect(hex.toDecimal()).toEqual(0)

xit "white", ->
expect(hex.toDecimal()).toEqual(16777215)

xit "yellow", ->
expect(hex.toDecimal()).toEqual(16776960)``````
``````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])
result

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