| Total Complexity | 6 |
| Complexity/F | 2 |
| Lines of Code | 70 |
| Function Count | 3 |
| Duplicated Lines | 0 |
| Ratio | 0 % |
| Changes | 2 | ||
| Bugs | 0 | Features | 1 |
| 1 | "use strict"; |
||
| 2 | |||
| 3 | var fs = require('fs'); |
||
| 4 | |||
| 5 | // Expose `Config` |
||
| 6 | |||
| 7 | module.exports = Config; |
||
| 8 | |||
| 9 | /** |
||
| 10 | * Set up Config with `configPath` |
||
| 11 | * which is responsible for loading and parsing config file. |
||
| 12 | * |
||
| 13 | * @param {Object} configPath |
||
| 14 | * @return {Object} |
||
| 15 | * @api public |
||
| 16 | */ |
||
| 17 | |||
| 18 | function Config(configPath) { |
||
| 19 | this.configPath = configPath; // Save config file path |
||
| 20 | this.raw = readFile(this.configPath); // Save config string |
||
| 21 | this.parsed = parseConfig(this.raw); // Config as an object |
||
| 22 | |||
| 23 | return this.parsed; // return as an object |
||
| 24 | } |
||
| 25 | |||
| 26 | |||
| 27 | /** |
||
| 28 | * Read config file and return output |
||
| 29 | * |
||
| 30 | * @param {String} configPath |
||
| 31 | * @return {String} |
||
| 32 | * @api protected |
||
| 33 | */ |
||
| 34 | |||
| 35 | function readFile(configPath) { |
||
| 36 | try { |
||
| 37 | return fs.readFileSync(configPath, "utf-8"); |
||
| 38 | } |
||
| 39 | catch (err) { |
||
| 40 | throw err; |
||
| 41 | } |
||
| 42 | } |
||
| 43 | |||
| 44 | /** |
||
| 45 | * Return configuration file's content as a formatted object |
||
| 46 | * |
||
| 47 | * @param {String} configStr |
||
| 48 | * @return {Object} |
||
| 49 | * @api protected |
||
| 50 | */ |
||
| 51 | |||
| 52 | function parseConfig(configStr) { |
||
| 53 | var config = {}; |
||
| 54 | var lines = configStr.split('\r\n'); // Split lines |
||
| 55 | var lastCellLine = lines[0].split(' '); // Save first line |
||
| 56 | var mowers_lines = lines.splice(1, lines.length-1); // Array of mowers |
||
| 57 | config.topRightPos = {x:parseInt(lastCellLine[0]), y:parseInt(lastCellLine[1])}; // Define first line in config object |
||
| 58 | config.mowers = []; |
||
| 59 | for(var i=0; i<mowers_lines.length; i++) { |
||
| 60 | if(i%2){ |
||
| 61 | var position = mowers_lines[i-1].split(' '); |
||
| 62 | config.mowers.push({ |
||
| 63 | pos:{x:parseInt(position[0]), y:parseInt(position[1])}, |
||
| 64 | cardinal:position[2], |
||
| 65 | instructions:mowers_lines[i].split('') |
||
| 66 | }); |
||
| 67 | } |
||
| 68 | } |
||
| 69 | return config; |
||
| 70 | } |