Created
May 18, 2020 23:06
-
-
Save pilotpirxie/2e0b3fa04288ae836e72901a638fdb95 to your computer and use it in GitHub Desktop.
Well-known Symbol.iterator example with roman numerals
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
const tab = [1, 7, 14, 4]; | |
tab[Symbol.iterator] = function () { | |
let index = 0; | |
const total = this.length; | |
const values = this; | |
return { | |
next() { | |
const romanize = num => { | |
const dec = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; | |
const rom = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]; | |
let output = ""; | |
for (let i = 0; i < dec.length; i++) { | |
while (dec[i] <= num) { | |
output += rom[i]; | |
num -= dec[i]; | |
} | |
} | |
return output; | |
}; | |
return index++ < total ? { | |
done: false, | |
value: romanize(values[index - 1]) | |
} : { | |
done: true | |
}; | |
} | |
}; | |
}; | |
for (let num of tab) { | |
console.log(num); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment