Calculates the current date constellation

Calculates the current date constellation

Start Month number constellation The end of the month number Time interval
12 22 Capricorn 1 19 12/22 - 1/19
1 20 Aquarius 2 18 1/20 - 2/18
2 19 Pisces 3 20 2/19 - 3/20
3 21 Aries 4 20 3/22 - 4/20
4 21 Taurus 5 20 4/22 - 5/20
5 21 Gemini 6 21 5/22 - 6/21
6 22 Cancer 7 22 6/22 - 7/22
7 23 Leo 8 22 7/22 - 8/22
8 23 Virgo 9 22 8/22 - 9/22
9 23 Libra 10 22 9/22 - 10/22
10 23 Scorpio 11 21 10/22 - 11/21
11 22 Sagittarius 12 21 11/22 - 12/21
12 22 Capricorn 1 19 12/22 - 1/19

Design storage structure

1.用一个数组来存储各个星座起始月与年份的对应关系,序号代表具体月份所对应的星座,0代表12月,1代表1月,-1代表12月
c = [摩羯,水瓶, 双鱼,白羊,金牛,双子,巨蟹,狮子,处女,天秤,天蝎,射手,摩羯]

2.用另外一个数组来存储年份与各个星座起始日期的对应关系,12.22是摩羯座的起始日期
Date = [22, 20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22]

The formula

1.如果当前的号数小于当前月份所对应的起始日期的号数,那我们的当前月数就要减1,如果是大于等于就直接使用当前月份即可

2.假如我们将 2月18号 水瓶座传入Date数组,2月份是双鱼座的开始的月份,拿到的日期就是19号,18<19说明当前号的起始月份不再当前月,所以用2 - 1,得到水瓶座的起始月在1月份。假如传入的是2月19号,19 == 19刚好是双鱼座的起始日期,在当前月大于的号也是属于双鱼座,所以返回当前月份2即可

3.startMonth = month - [ day < Date[month] ? 1 : 0]

4.有了起始月份就可以找到对应的星座了
c = [摩羯,水瓶, 双鱼,白羊,金牛,双子,巨蟹,狮子,处女,天秤,天蝎,射手,摩羯]
c[startMonth]

Optimization of an array of dates

1.将数组的存储方式转换为字符串的存储方式,所以必须将日期列表中存储的起始号,变成个位数,起始日期中最小为19(双鱼座),最大为23(狮子座)

day < Date[month]
=> day - x < Date[month] - x

令y = Date[month]-x,计算x+y=19与x+y=23的交集,算出x的交集为14-19,x取最小14就可以y变成个位数
x Y x + y = 19 x Y x + y = 23
10 9 14 9
11 8 15 8
12 7 16 7
13 6 17 6
14 5 18 5
15 4 19 4
16 3 20 3
17 2 21 2
18 1 22 1
19 0 23 0
Date = [22, 20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22]
让Date - 14 将结果存入字符串'865778999988'

利用隐式转换,如果day是起始月就返回True否则就返回False,如果day小于当前月所对应的起始星座,说明他的起始月在上个月True会转换为1,得到month-1,如果不小于False会转换为0,month-0还是得到当前month
month - (day - 14 < '865778999988'.charAt(month))

function getHoroscope(date) {
      let c = ['摩羯','水瓶','双鱼','白羊','金牛','双子','巨蟹','狮子','处女','天秤','天蝎','射手','摩羯']
      date=new Date(date);
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let startMonth = month - (day - 14 < '865778999988'.charAt(month));
      return c[startMonth]+'座';
    },
    
const date = new Date(2019,9,14);

Guess you like

Origin www.cnblogs.com/pluslius/p/11520780.html
Recommended