How to build a Chinese Zodiac Algorithm (Bonus Western Zodiac)

The secret to building a Chinese zodiac algorithm is realizing that if you take a birth year, subtract four and divide that number by 12, you will get a number between 0–11. Using that number you can figure out the corresponding Animal with this order (using array logic-meaning the first index is 0): Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog and Pig. As explained above, first we begin with a variable of year, (please note all functions below are written in fat array syntax). On line 46, our switch statement takes the year, subtracts 4 and divides that number by 12. Each of our case statements hold a number with corresponding animal, description, picture, best matches, and best to avoid signs.

Since this is on react, you can see on line 134 the animal and other info are added to state. Just as the birth year was entered into state before this function was called.

When rendering best matches and better to avoid arrays, make sure to spread them out with commas as show bellow on lines 16 and 17.

Since year is not important for wester zodiac, this algorithm simply takes in month and date. As you can see things get a little more messy on this problem. This time we are using a switch statement along with an if else statement to first determine our month, then date of birth.

Next on line 297 we call our below function loadSign, which is a switch statement that adds a ‘fortune’ to state, as line 298 adds our sign to state.

This is a big simpler to render, as seen below we have a conditional render so if there is no sign provided our component will return ‘No Sign Yet.’ If there is a sign, we will simply see the fortune we pushed into state when we called the loadSign function, which in retrospect should have been called loadFortune.

Click here to check out the full code.

Cat nerd and Web Developer