enterpriserulesengine.go 1.09 KB
Newer Older
Carlos Davide's avatar
Carlos Davide committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
package day22

import (
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"os"
)

const CONFIG_PATH_ENV_VAR = "DAY22_CONFIG_PATH"

// FizzBuzz needs to be lazily initialized due to the use of `os.Env`.
// See test harness.
// var FizzBuzz func(n int) string = MakeXMLRulesApplicator()

func MakeXMLRulesApplicator() func(int) string {

	path := os.Getenv(CONFIG_PATH_ENV_VAR)
	config := LoadConfig(LoadConfigFileBytes(path))
	rules := config.Rules

	return func(n int) string {
		s := ""

		for _, r := range rules {
			if n%r.Divisor == 0 {
				s = s + r.Part
			}
		}

		if s == "" {
			return fmt.Sprint(n)
		}

		return s
	}
}

func LoadConfig(configBytes []byte) Config {
	config := Config{}

	err := xml.Unmarshal(configBytes, &config)
	if err != nil {
		panic(err)
	}

	return config
}

func LoadConfigFileBytes(path string) []byte {
	configBytes, err := ioutil.ReadFile(path)
	if err != nil {
		panic(err)
	}

	return configBytes
}

type Config struct {
	XMLName xml.Name `xml:"config"`
	Rules   []Rule   `xml:"rules>rule"`
}

type Rule struct {
	Divisor int    `xml:"divisor,attr"`
	Part    string `xml:"part,attr"`
}