Last active
October 20, 2017 21:55
-
-
Save ufocoder/6b31fd7ce5252fa32509e44496b0ce7b to your computer and use it in GitHub Desktop.
Roman Number array creation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = { | |
createArray: (begin, end) => { | |
const result = [] | |
for (let i = begin; i<end+1; i++){ | |
result.push(i) | |
} | |
return result | |
}, | |
fromRoman: (_str) => { | |
var str = _str.toString() | |
var result = 0 | |
var decimal = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] | |
var roman = ["M", "CM","D","CD","C", "XC", "L", "XL", "X","IX","V","IV","I"] | |
for (var i = 0; i <= decimal.length; i++) { | |
while (str.indexOf(roman[i]) === 0) { | |
result += decimal[i] | |
str = str.replace(roman[i],'') | |
} | |
} | |
return result; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Roman numbers array | |
* | |
* 0..IV -> [0, 1, 2, 3, 4] | |
* 0..V -> [0, 1, 2, 3, 4, 5] | |
* 0..X -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
*/ | |
const assert = require('assert') | |
const {fromRoman, createArray} = require('./helpers') | |
// tests for `fromRoman` help function | |
assert.equal(fromRoman('II'), 2) | |
assert.equal(fromRoman('IV'), 4) | |
// test for `createArray` help function | |
assert.deepEqual(createArray(4, 6), [4, 5, 6]) | |
const proxyHandler = { | |
get: function(target, name, receiver) { | |
const romanValue = fromRoman(name); | |
if (romanValue) { | |
return createArray(receiver.valueOf(), romanValue) | |
} else { | |
return target[name] | |
} | |
} | |
} | |
Number.prototype.__proto__ = new Proxy(Number.prototype.__proto__, proxyHandler) | |
assert.deepEqual(0..IV, [0, 1, 2, 3, 4,]) | |
assert.deepEqual(0..V, [0, 1, 2, 3, 4, 5]) | |
assert.deepEqual(0..X, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment