Tuesday, December 31, 2019

Simple 2d car physics with JavaScript

Comments

from Hacker News https://ift.tt/2SLLn6r

Sam Altman and Andrew Yang talk UBI


  • The presidential candidate Andrew Yang held a fundraiser attended by tech workers in San Francisco at the house of the tech investor Sam Altman, a supporter.
  • Altman and Yang talked about their shared interest in universal basic income and the argument against breaking up big tech. Yang called proposals espoused by Sens. Elizabeth Warren and Bernie Sanders "a knee-jerk 20th-century approach to much more nuanced problems."
  • The former tech executive running for the 2020 Democratic presidential nomination has supporters in Silicon Valley, where employees from Google, Apple, and Facebook have donated large sums to his campaign.
  • Visit Business Insider's homepage for more stories.

The presidential hopeful Andrew Yang may have been born in New York, but the mood at a money-raising event in Silicon Valley this week was that of a homecoming.

The Yang Gang's biggest spenders in San Francisco gathered for a fundraiser on Wednesday afternoon, where the top ticket cost $5,600. The tech investor Sam Altman hosted the luncheon at his home not far from the tech hub's downtown. The living room filled with Yang supporters, wearing jeans and suit jackets and hats that said "math," a cheeky campaign slogan the candidate wore on his lapel in place of an American flag pin.

"There's this notion that techies are averse to any sort of conversation about guidelines on technology, and that hasn't been my experience," said Yang, sitting at the front of the room during a half-hour chat with the host. "The technologists I've talked to, they're pretty reasonable."

Yang's support is in single-digit percentages in several national polls, but the entrepreneur has rallied a group of tech workers who support him, knowing fully that his signature campaign promise is centered on taxing their employers. The presidential candidate wants to give $1,000 a month to every adult American with no strings attached, a so-called universal basic income that Yang plans to pay for in part with a new value-added tax on goods and services.

A wide-ranging discussion covered the fundamentals of universal basic income, the path to modernizing the federal government, and the argument against breaking up big tech.

Yang said he "wouldn't lead with" breaking up big tech as a solution to society's woes, which got a laugh.

"It's just false that if we were to break up Amazon into four mini-Amazons, that all the malls and mainstream stores would reopen," Yang said. "They would not. And many of these marketplaces gravitate toward one or two winners ... No one's using Bing because no one wants to use the fourth-best search engine."

He added: "To me, the DC-break-up-big-tech approach is unfortunately just a knee-jerk 20th-century approach to much more nuanced problems. Do I think that consolidation has gone overboard in tech? Yes. Do I think that now the business model of a startup is to get acquired by one of the behemoths and not try to displace them over time? Yes. Does that stifle innovation and some level of creativity and competition? Yes.

"So these are real problems, but you can't take a sledgehammer to these problems like it's all going to be fixed if I treat you like a railroad. You don't solve these problems by treating them like an oil company."

He said a more sophisticated solution involved an "active partnership" with the tech companies.

'The best thing we can do would be to knight a group of young people'

After the floor opened for questions, a Google software engineer who said he worked in a senator's office when he was younger asked about modernizing the technology that politicians used to help them work smarter. He recalled the pains of recording data in spreadsheets.

"What you don't want to do is you don't want to pretend you can transform that kind of culture, unilaterally, overnight," Yang said. "In a way, the best thing we can do would be to knight a group of young people like yourself to just to go into various offices and say, 'Hey, look, they're just there as a resource.'"

Tickets for the event at Altman's home, which included a lunch of charcuterie and cucumber sandwiches, started at $2,000. A VIP pass costs $2,800 a pop, while the "max donor" contribution was $5,600. These funds will fuel Yang's campaign committee and marketing.

A screenshot of the invitation to an Andrew Yang fundraiser at Sam Altman's house.
ActBlue

The topic of universal basic income, an idea so near to Yang that his campaign's website at the start was "ubi2020.com," came up throughout the event. Its host, Altman, the former head of the startup accelerator Y Combinator, is tech's loudest supporter of universal basic income. In the past few years he led a modest pilot program that gave free cash to people in Oakland, California. Yang joked onstage that "it's harder to give people free money than you think."

"The way I think about it is, if you have a population that's living paycheck to paycheck — and 70% of Americans are living paycheck to paycheck," Yang said, "and then you come and say, 'Hey, the magical Asian man wants to give everyone $1,000 a month,' it does not jive with their time-money trade-offs that they're making all the time, because to them, they have this lived experience where money is very, very scarce."

Yang has said he plans to finance the cheerfully named "freedom dividend" by creating a tax on financial transactions, among other taxes. A value-added tax is similar to a sales tax, but it gets collected at every point of the supply chain. For example, if Amazon buys a server for its cloud-computing business, it pays a tax on the server. When it buys power, it pays a tax on the power. The tech giant goes on to sell that rackspace, and the end user pays a tax on the price of the computing minus the tax on the server and the power, so as to avoid double taxation.

An analysis by the nonpartisan research group Tax Foundation has cast doubt that Yang's proposed value-added tax of 10% would cover the cost of universal basic income for 236 million adult Americans.

Shayanne Gal/Business Insider

His plan hasn't turned off all employees at the companies that Yang wants to tax.

Andrew Marshall, a software engineer who previously worked at Google, started supporting the candidate in February because he was interested in Yang's ideas around universal basic income. He said after the event that it's unfair to say the value-added tax would affect only companies like Google and Amazon.

"We can't leverage all of our hopes and dreams on Amazon to fix everything," Marshall said.

The Center for Responsive Politics, whose website OpenSecrets.org tracks federal campaign spending, lists the companies whose public action committees, employees, or owners have contributed the most to Yang's campaign. Google's parent company, Alphabet, tops the heap, followed by Amazon, Microsoft, the University of California, and Facebook.

Yang counts some big names among his supporters, though they were absent from the event. Jack Dorsey, the cofounder and CEO of both Twitter and Square, has contributed to Yang's campaign; James Monsees, who helped create Juul, and the Twitch cofounder and executive Kevin Lin are also donors.

The long-shot candidate reported one of the biggest improvements on recent fundraising. His campaign pulled in $10 million in the third quarter, a $7.2 million increase over their second-quarter haul.



from Hacker News https://ift.tt/2Xe1iL4

The Lost History of the ‘City’ of Brooklyn

Brooklyn: The Once and Future City, Thomas Campanella, Princeton University Press, 550 pages.

Cornell Professor Thomas Campanella’s new book is not only the best history of Brooklyn, it’s one of the most entertaining works published this year, suffuse with fantastic tales of the achievements, iniquities, and dreams of its famous neighbor. “Brooklyn may be a brand known around the world, but it is also terra incognita,” Campanella writes, “a terrain long lost in the thermonuclear glow of Manhattan, possibly the most navel-gazed city in the world outside of Rome and the subject of dozens of good books.”

This article appears in the January/February 2020 issue.

In the 1897 referendum that merged the city into the five boroughs of Greater New York, Brooklyn just barely assented to its subaltern status—passing there by a paltry 277 votes. To this point it had competed very capably with its fancier neighbor across the river, but its official assumption by the city seemed to only accentuate Brooklyn’s wilder and more outlandish tendencies. So with Manhattan inheriting the crown, Brooklyn turned to the traditionally wilder tracks of younger sons. “Conditional proximity, for lack of a better term, made Brooklyn a displacement zone of sorts, a site for peoples and practices untenable in the heart of town—suspect religions, racial outcasts, citizen non-conformists, and later, dirty industrial operations and morally polluting amusements.”

Campanella’s book doesn’t presume to be comprehensive history, but its episodic chapters will leave you with many more facts about Brooklyn than you currently possess, and add more texture to familiar urban geography than first meets the eye.

In one early example, Brooklyn contains Gravesend, a colonial 17th-century community founded by Deborah Moody, a New England Anabaptist expelled from Massachusetts but welcomed to New Netherland—sort of. She was granted some land in then-distant Long Island, where she founded an early master-planned community, an enclave of religious toleration whose street grid still vestigially girds Southern Brooklyn. Relics of the Battle of Brooklyn, the largest naval operation since the Spanish Armada and one of the largest battles of the 18th-century American Revolution, similarly lurk amidst the borough’s 19th-century landmark Brownstone townhouses. 

Speaking of that symbol of Brownstone Brooklyn, its excellent physical assets are a bit more familiar, but ably told here by Campanella. Today’s borough still benefits from the then-independent city’s determination to outdo Manhattan’s Central Park in hiring Frederick Law Olmsted, who produced a larger and finer park in Brooklyn. Prospect Park emerged a masterpiece but is only part of the story, with Olmsted creating linked boulevard projects of the Coney Island and Eastern Parkways (and the partially-executed Shore Road Parkway).

***

For all its achievements, Brooklyn’s ambitions have often been larger than its means, and the book is replete with grand schemes only partially executed or not at all. A monumental plaza at the convergence of the Brooklyn and Manhattan Bridges is unfortunately the stuff of fantasy, as was a proposal for a gargantuan marine park, planned for 1,840 acres (larger than both Central and Prospect Parks combined). Typically modest and affordable ideas included a two-mile formal canal, on a site that consisted mainly of marshland. Naturally this wasn’t built, but the bulkhead line of the grand harbor remains visible at low tide.

Just nearby was the site of another planned 1914 boondoggle, “one of the most heroically misguided infrastructure projects ever proposed,” which was creating a shipping harbor in Jamaica Bay. Observing the insufficiency of usable shipping space both in Manhattan and in Brooklyn along New York Harbor, city dreamers looked to the seemingly capacious bay, in which they hoped to build one of the largest harbors on earth. That wasn’t all; the plan involved a canal across Queens to the Long Island Sound. There were a few ways to do this, none of them easy. One would have required multiple locks in order to traverse a height of 100 feet above sea level; the other was a “canal tunnel.” In any case, the project would have had to accommodate a three-hour difference in tidal timing between the sound and the ocean, which entailed six-foot differences in their height. 

There was still another catch. All of these plans attracted acclaim without considering the fact that Jamaica Bay is catastrophically ill-suited for use as a harbor, as it’s mainly shallow and full of shifting sand not far beneath its surface. This was hardly news. As Campanella writes, “Revolutionary-era charts with soundings for all New York Harbor and the Hudson and East rivers give none for Jamaica Bay—damning evidence indeed of its lack of suitability for maritime use.”

Not far away, other less grand infrastructure plans flourished. Grand resort hotels sat near to racetracks (the largest of which, Sheepshead Bay, was the most profitable in the country in 1905), and fabled amusement parks such as Luna Park and Dreamland make any Coney Island-style contemporary entertainment look tame. These pleasure grounds were all buttressed by a foundation of truly titanic graft and corruption—one man, John Y. McKane, was Gravesend town constable, commissioner of common lands, chief of police, as well as president of the Town Board, Board of Health, Police Board, and Water Board for much of the 1870s and 1880s. His Caligulan rule didn’t terminate in jail for well over two decades, but did increase the stock of local saloons to over 700. “His administration was also responsible for turning a once-lovely place for a family outing into an unholy warren of gambling dens, whorehouses….” 

Pleasure island did not lack for Pinnochios, of course. Perhaps the most entertaining—and shocking— story in the book is that of a “steampunk orb” slated for Coney Island’s Steeplechase Park. The brainchild of St. Louis swindler-fantasist Samuel Friede, it was a globe-shaped tower slated to contain an “Aerial Hippodrome,” “continuous four-ring circus,” “aerial palm garden,” ballroom, cafe, and weather observatory. It was to stand 700 feet high and 900 feet wide, accessed by 10 elevators. 

It’s probably no surprise that there were disputes between the builder and the park’s owner—or that the head of finances for the tower was embezzling as many dollars as he could pocket. Or that the foundation for the tower was sunk considerably short of the depth necessary to support its projected height. This is all familiar to those now-seasoned observers of fraud, but others might raise an additional eyebrow. The Globe Tower Company’s vice president, one Edward A. Langan, also happened to be the chief inspector of elevators for the Brooklyn Bureau of Buildings. This monumental conflict of interest wasn’t enough to result in any serious threat to his position until a few more details emerged of his civic practices:

“The truth also came out about Langan’s uncanny knack for selling Globe Tower stock. He simply forced applicants for building bureau permits or approvals to buy a cartload of Globe Tower stock before he would sign off on anything.”

A series of laws severely restricting racetrack gambling took effect in 1908, largely due to New York Governor Charles Evans Hughes (most notable for losing the presidency to Woodrow Wilson in 1916). He cleared the Augean stables but hobbled the rest of this entertainment district, and the lame remnants were taken out and shot in stages. By September 1910 all racetracks had closed, and Coney Island’s three principal grand hotels shuttered in 1911, 1916, and 1924. Some other amusements persisted, such as the wooden-tracked Sheepshead Bay Motor Speedway, but the golden age was over, for better or worse.

A few miles away in Jamaica Bay (and in the path of misbegotten harbor schemes) was one of the most revolting places in the metropolitan area. In the city’s rendering works on the appropriately named Barren Island was a destination for the unlucky horse, dog, fish, and occasionally larger circus animal. This fragrant location boiled down countless animals and their waste, processing 1.8 million pounds of dung at its peak. Campanella notes drolly that there was no trash collection on this island, a basically lawless place that emitted vile scents for miles (along with all of its grisly effluent draining into Jamaica Bay) and was the focus of several campaigns until it finally closed in 1920. 

Barren Island then became the site of one of New York’s first modern airports, the quite advanced Floyd Bennett Field, which languished with unpopular commercial flights from the start for a forgotten reason: the early importance of airmail to profitability, which was routed through the more convenient Newark Airport.

And there’s still much more: the repeat misfortunes of the postwar period, which involved massive job and population loss along with the flight of the fabled Dodgers baseball team, closure of the Brooklyn Eagle newspaper and many other core institutions, all coupled with especially destructive highway and urban renewal projects. “No city would suffer more in the name of urban renewal than New York, and nowhere was the devastation greater than Brooklyn.” Even if the smelly rendering works was long closed, Brooklyn was a dumping ground for undesirable features—alternately neglected and mangled with thoughtless plans, as New York concentrated attractions and employment in its imperial center of Manhattan, leaving the borough to wither. 

Yet that’s no longer the case. Brooklyn has turned a corner, with neighborhoods that rival the cost of almost any in Manhattan; today, Brooklyn t-shirts sell briskly around the world. It now also at last has a book worthy of itself—this one. 

Anthony Paletta has contributed to The Wall Street Journal, The Weekly Standard, The Guardian, and numerous other publications. He lives in Brooklyn.



from Hacker News https://ift.tt/2MbuoX4

Calculate the day of the week for any date in your head

Doomsday Algorithm

The Doomsday Algorithm gives the day of the week for any date (and you can do it in your head)

Added 1994-02-22, Updated 2019-02-28 with examples for 2019

Overview

The Doomsday Algorithm is presented in the following sections.

  • February 28 or 29: Doomsday is the last day of February
  • Even Months: April, June, August, October, and December (months 4, 6, 8, 10, and 12)
  • Odd Months: March, May, July, September, and November (months 3, 5, 7, 9, and 11)
  • 2018 Calendar: the current year calendar, highlighting the Doomsday in each month
  • Other Years: how to apply the Doomsday Algorithm to other years in the 1900s and 2000s
  • Other Centuries: extending the Doomsday Algorithm to other centuries
  • The Hand: Dr. Conway's shortcut method
  • Origins: the creation of the Doomsday Algorithm by Dr. John Horton Conway
  • Links: Doomsday Algorithm resources on the Web for additional information

Have fun!

February 28 or 29

To use the Doomsday Algorithm in any year, we first need to know the Doomsday for that year.

Doomsday is February 28 or 29. In other words, Doomsday is always the last day of February. In normal years, Doomsday is February 28, and in leap years, Doomsday is February 29.

In 2019, which is not a leap year, the last day of February is Thursday the 28th.

Once we know Doomsday, it's pretty easy to get the day of the week for any day in February. This is done by adding and subtracting, using multiples of 7, and you should be comfortable doing this in your head, otherwise the rest of the algorithm will give you trouble! Luckily, most people, through practice or whatever, are good at mentally picturing a month if they have something to anchor it on, and Doomsday is this anchor. For February, it's always the 28th in normal years, and the 29th in leap years.

Example: what is this year's Valentine's Day, February 14th?
Answer: Doomsday 2019 is Thursday the 28th of February. So one week earlier, the 21st is also Thursday. Another week earlier is Thursday the 14th. So Valentine's Day 2019 is Thursday.

Example: what is this year's Groundhog day, February 2nd?
Answer: Doomsday 2019 is Thursday the 28th of February... then subtracting 7 for each week going backwards, we have Thursday the 21st... Thursday the 14th... Thursday the 7th... and then we have to go five days back, to get from the 7th to the 2nd.

If going back five days in your head is difficult—and it often is, especially looking back over a weekend—there's a little trick we can use here. Going two days forward gives the same day of the week as five days back. So if February 7th is Thursday, then two days forward is Saturday the 9th, which is the same day of the week as Saturday the 2nd. So Groundhog day in 2019 is Saturday. Remember, all we're after is the day of the week, so "-5" is the same as "+2" but "+2" is usually easier to do.

If it helps, you can review the above two examples using this calendar for February 2019 —

 2.Feb(28th/non-leap)
 Su Mo Tu We Th Fr Sa 
 1 2 
 3 4 5 6 7 8 9 
 10 11 12 13 14 15 16 
 17 18 19 20 21 22 23 
 24 25 26 27 28 

Return to top

Even Months

Okay, the last day of February is Doomsday. Once we know what day of the week Doomsday is, we immediately know the day of the week of certain other days in the year. There are actually 52 (or 53) other days which are all on the same day of the week as "the" Doomsday at the end of February, but there's a special one each month which we will now learn.

Each month has a special day which we remember, because it is on the same day of the week as the Doomsday which is at the end of February. We call these the Doomsdays for their months. Just keep in mind that the entire year is determined by the Doomsday at the end of February, and that all the other Doomsdays within the year are on the same day of the week.

Let's begin with the even months. These are months 2, 4, 6, 8, 10, and 12, i.e. February, April, June, August, October, and December. Actually, we never do February this way, because it's special, and we've already covered it.

For even months (not including February), the Nth of that month is a Doomsday. In other words, it's the same day of the week as the last day in February. This is a delightful coincidence, and it's so easy to remember:

  • April 4th is a Doomsday
  • June 6th is a Doomsday
  • August 8th is a Doomsday
  • October 10th is a Doomsday
  • December 12th is a Doomsday

Neat, eh? Now we can simply work our way around any even month based on its Doomsday.

Example: what is this year's Christmas Day, December 25th?
Answer: Doomsday 2019 is Thursday. Then December (even month) 12th is the Doomsday for December, so it's also Thursday. Two weeks later, December 26th is also Thursday, so Christmas, the day before, is Wednesday December 25th. Easy! In fact, after you do the Doomsday algorithm often enough, you just start remembering things like Christmas is always the day before Doomsday.

Example: what is this year's Halloween, October 31st?
Answer: Doomsday 2019 is Thursday. So October (even) 10th is Thursday. Then three weeks (21 days) later is Thursday, October 31st. Easy! In fact, after you do the Doomsday algorithm often enough, you just start remembering things like Halloween is always Doomsday.

Example: what is this year's Canadian Thanksgiving Day, the second Monday in October?
Answer: Doomsday 2019 is Thursday. So October (even) 10th is Thursday. A week earlier is Thursday October 3rd, and two days before that is Tuesday the 1st. So that means the first Monday of October is the 7th, and the second Monday in October, Canadian Thanksgiving (also Columbus Day in the US), is Monday, October 14th in 2019.

Return to top

Odd Months

Now let's do the odd months—months 1, 3, 5, 7, 9, and 11, i.e. January, March, May, July, September, and November. Skip January and March for a moment, and concentrate on 5, 7, 9, and 11.

Consider the following mnemonic phrase:

I work 9-5 at the 7-11

"Nine to five" is a common working day (9 a.m. to 5 p.m.) while 7-Eleven is a chain of convenience stores. This mnemonic phrase should help you remember:

  • for the 9th month, Doomsday is the 5th
  • for the 5th month, Doomsday is the 9th
  • for the 7th month, Doomsday is the 11th
  • for the 11th month, Doomsday is the 7th

This gives us Doomsday for May, July, September, and November. Now we just work our way around again within each month, using the Doomsday for that month.

Example: what day is this year's July 4th?
Answer: Doomsday 2019 is Thursday, so the Doomsday for July (7th month) is the 11th, also a Thursday. So one week earlier, July 4th is also Thursday. In fact, after you do the Doomsday algorithm often enough, you just start remembering things like July 4th is always Doomsday.

Example: what is this year's Labour Day, the first Monday of September?
Answer: Doomsday 2019 is Thursday. September (9th month) 5th is Thursday. To o back to Monday, we go back 3 days. So Labour Day in 2019, the first Monday of September, is September 2nd.

Now March.

Doomsday, the last day of February, is often also called the "0th" of March. You might have to think about that for a moment, until you realize that the next day is the 1st of March. So if the "0th" of March is Doomsday, then the 7th of March, exactly one week after the last day of February, no matter whether it's the 28th or 29th, is also Doomsday.

Example: what day is this year's St. Patrick's Day, March 17th?
Answer: Doomsday 2019 is Thursday, which we know is the "0th" of March. So a week later, March 7th is Thursday. March 14th is Thursday. Now we go three days forward, to get to Sunday, March 17th.

An alternate, simpler method for March is to use Pi Day, which is March 14th, i.e. 3/14 using month/day numbers. Pi Day is always Doomsday.

Finally, we have to be able to do January.

The easiest way to calculate January's Doomsday was described to me by reader Bob Goddard:

It's January 3rd three years out of four, the non-leap years. It's January 4th only in the fourth year, the years divisible by 4.

This is so much simpler than what I had before (which involved January 31st and "January 32nd").

Example: what is this year's New Year's Day (January 1st)?
Answer: Doomsday 2019 is Thursday, and since 2019 is not a leap year, January 3rd is Thursday. Go back 2 days, and January 1st is Tuesday. Simple, eh? Thanks, Bob.

Another way to calculate January's Doomsday was sent to me by reader Roman Weil. It's actually due to his son Sandy Weil, who is the Director of Football Analytics for the Baltimore Ravens:

A January trick: Instead of associating January with the new year, associate it with the old. That is, think of Jan 2019 as being part of 2018. In that case, Pi Days in January are 1/2 and 1/23. So in 2019, 1/2 and 1/23 are Wednesdays, which is the Pi Day of 2018. You will find, if you are like me, that when you think about January, it's more often about 'next January' than about 'last January,' so putting January at the end of the current year will solve most of your January issues.

Sandy here refers to "Pi Days" which is another name for Doomsdays—this is further discussed in Origins. The mnemonic part of Sandy's trick is that 1/2 and 1/23 sound like "one two" and "one two three."

Return to top

2019 Calendar

If you've worked your way through the rules but have trouble remembering them, it may help to see the Doomsdays in calendar form. Here's the Doomsday Calendar for 2019 with all the Doomsdays highlighted:

Doomsday Calendar for 2019

  1.Jan(3rd/nonleap)   2.Feb(28th/nonleap)
 Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
 1 2 3 4 5 1 2
 6 7 8 9 10 11 12 3 4 5 6 7 8 9
 13 14 15 16 17 18 19 10 11 12 13 14 15 16
 20 21 22 23 24 25 26 17 18 19 20 21 22 23
 27 28 29 30 31 24 25 26 27 28 
 
  3.Mar(7th)   4.Apr(4th) 
 Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
 1 2 1 2 3 4 5 6
 3 4 5 6 7 8 9 7 8 9 10 11 12 13
 10 11 12 13 14 15 16 14 15 16 17 18 19 20
 17 18 19 20 21 22 23 21 22 23 24 25 26 27
 24 25 26 27 28 29 30 28 29 30
 31
 
  5.May(9th)   6.Jun(6th) 
 Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
 1 2 3 4 1
 5 6 7 8 9 10 11 2 3 4 5 6 7 8
 12 13 14 15 16 17 18 9 10 11 12 13 14 15
 19 20 21 22 23 24 25 16 17 18 19 20 21 22
 26 27 28 29 30 31 23 24 25 26 27 28 29
 30
 
  7.Jul(11th)   8.Aug(8th) 
 Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
 1 2 3 4 5 6 1 2 3
 7 8 9 10 11 12 13 4 5 6 7 8 9 10
 14 15 16 17 18 19 20 11 12 13 14 15 16 17 
 21 22 23 24 25 26 27 18 19 20 21 22 23 24
 28 29 30 31 25 26 27 28 29 30 31
 
  9.Sep(5th)   10.Oct(10th) 
 Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
 1 2 3 4 5 6 7 1 2 3 4 5
 8 9 10 11 12 13 14 6 7 8 9 10 11 12 
 15 16 17 18 19 20 21 13 14 15 16 17 18 19
 22 23 24 25 26 27 28 20 21 22 23 24 25 26
 29 30 27 28 29 30 31
 
  11.Nov(7th)   12.Dec(12th) 
 Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
 1 2 1 2 3 4 5 6 7
 3 4 5 6 7 8 9 8 9 10 11 12 13 14
 10 11 12 13 14 15 16 15 16 17 18 19 20 21
 17 18 19 20 21 22 23 22 23 24 25 26 27 28
 24 25 26 27 28 29 30 29 30 31

Previous Doomsday Calendars

Here are links to single-page versions of the Doomsday Calendar (the first two are actually GIFs; sorry 'bout that) suitable for printing:

Return to top

Other Years

Okay, we can do 2019. What about other years? If Doomsday is Thursday this year, what was it last year, in 2018?

Well, you could go look it up in a calendar, but let me tell you it was a Wednesday. Doomsday advances by one day each year because 365 divided by 7 leaves 1 remainder. Doomsday advances two days each leap year, and we'll come back to more on that in a moment.

Let's work a couple of examples for last year, 2018, when Doomsday was Wednesday.

Example: what day was New Year's Eve last year?
Answer: Start with Doomsday for last year -- Doomsday 2018 was Wednesday. December (even) 12th was Wednesday, and so was the 26th. Five days later, December 31st, was Monday. Or, if you're starting to get the hang of this, instead of "Wednesday + 5 = Monday," you'll think "Wednesday - 2 = Monday," which seems just a wee bit easier. Remember, all we're looking for is the day of the week. So New Year's Eve last year, 2018, was Monday.

Example: what day of the week was New Year's Eve, 2017?
Answer: Since we were just doing examples for last year, let's try New Year's Eve, 2017 by going backwards from January 1st, 2018. Now, Doomsday 2018 was Wednesday, and since 2018 was not a leap year, that means that January 3rd, 2018 was Wednesday. So then January 1st, 2018 was 2 days earlier, i.e. Monday. Finally, this means that the day before, New Year's Eve, December 31st, 2017, was Sunday.

The Doomsday Algorithm is often used with people's birthdays. In order to do the Doomsday algorithm for any year in the 1900's, when most of us were born, we need to memorize the fact that Doomsday for 1900 is Wednesday. Then we do a calculation based on the number of years since 1900.

First, look at the following chart of Doomsdays:

  Sun Mon Tue Wed Thu Fri Sat
 1900 1901 1902 1903
 ---- 1904 1905 1906 1907 ---- 1908
 1909 1910 1911 ---- 1912 1913 1914
 1915 ---- 1916 1917 1918 1919 ----
 1920 1921 1922 1923 ---- 1924 1925
 1926 1927 ---- 1928 1929 1930 1931
 ---- 1932 1933 1934 1935 ---- 1936
 1937 1938 1939 ---- 1940 1941 1942
 1943 ---- 1944 1945 1946 1947 ----
 1948 1949 1950 1951 ---- 1952 1953
 1954 1955 ---- 1956 1957 1958 1959
 ---- 1960 1961 1962 1963 ---- 1964
 1965 1966 1967 ---- 1968 1969 1970
 1971 ---- 1972 1973 1974 1975 ----
 1976 1977 1978 1979 ---- 1980 1981
 1982 1983 ---- 1984 1985 1986 1987
 ---- 1988 1989 1990 1991 ---- 1992
 1993 1994 1995 ---- 1996 1997 1998
 1999 ---- 2000 ...

Notice that Doomsday 1900 is Wednesday. This is the anchor for all the years in the 1900's. (Notice also that 1900 is not a leap year, so Doomsday 1900 is February 28th.) How do we remember 1900=Wednesday? Dr. Conway (see Origins) suggests the mnemonic "We-in-dis-day", indicative of the fact that most of us were born in the 1900's.

Now every twelve years, Doomsday advances by one. Check for yourself. In the chart above, pick a year and look ahead twelve years—down two rows and over one day. This leads to the following rule...

For any year 19YY, using the YY part of the year, calculate:

  1. the number of 12's in the YY part of the year
  2. the remainder of step 1
  3. the number of 4's in the remainder of step 1

Feel free to throw out multiples of 7 along the way if you find this easy to do.

Now we need to add the result of our calculation to 1900=Wednesday to get the Doomsday for that year. We do by this treating Wednesday as day 4. Quite easy to remember, since that's Wednesday's day of the week in the normal Sunday-to-Saturday calendar.

Example: what is Doomsday 1929?
Answer:

  1. 29 divided by 12 is 2
  2. ... remainder 5
  3. 5 divided by 4 is 1

Adding these up, we get 5+2+1=8, and we can throw out a 7 to get 1. Finally, this 1 has to be added to 1900=Wednesday, so Doomsday for 1929 is Thursday.

Example: what is Doomsday 1999?
Answer:

  1. 99 divided by 12 is 8
  2. ... remainder 3
  3. and of course 3 divided by 4 is 0

Adding these up, we get 8+3+0=11 i.e. 4. This has to be added to 1900=Wednesday, so Doomsday for 1999 is Sunday.

We should now be able to do any day in the 1900's in our head. Let's do a couple more examples...

Example: what day of the week was November 27, 1982?
Answer: 82 / 12 = 6 ... remainder 10 ... 10 / 4 = 2 ... 6 + 10 + 2 = 18 which is 4 days to be added to Wednesday (for 1900) ... so Doomsday 1982 was Sunday ... November(11) 7th was Sunday, 28th was Sunday ... November 27th 1982 was Saturday; that was the day the Doomsday Algorithm was featured on Quirks and Quarks (see Origins).

Example: what day of the week was July 20, 1969? (the date of the first landing of humans on the Moon)
Answer: 69 / 12 = 5 ... remainder 9 ... 9 / 4 = 2 ... 5 + 9 + 2 = 16 which is 2 days to be added to Wednesday (for 1900) ... so Doomsday 1969 was Friday ... July(7) 11th is Friday, 18th is Friday ... July 20th 1969 was Sunday

Increased Speed

Dr. Sidney Graham sent me the following:

Do you know Conway's method for "increased speed"? Basically, the trick is to memorize the list:

6, 11.5, 17, 23, 28, 34, ...., 84, 90, 95.5

These are the years in a century that have the same doomsday as the century year, i.e. Doomsday1900 = Doomsday1906 = Doomsday1917 etc.

The "11.5" refers to the fact that Doomsday1911 = Doomsday1900 - 1 and Doomsday1912 = Doomsday1900 + 1.

This list of years can be seen in the above table in the column under 1900. Here's that column again, all by itself:

 Sun Mon Tue Wed Thu Fri Sat
 1900
 06
 11 -- 12
 17
 23
 28
 34
 39 -- 40
 45
 51
 56
 62
 67 -- 68
 73
 79
 84
 90
 95 -- 96

Obviously, if you can memorize this list, you can increase the speed of your calculations. For some of us, that's a big IF; it reminds me of a comment someone made when first shown the entire Doomsday Algorithm:

Find the day of the week for any year in history in your head? Maybe, but only if one of the steps included in my head is telling myself "Remember where you put the printout of that page."

In any case, let's have a couple of examples:

Example: what day of the week was August 13, 1971
Answer: "67.5" means 1968 = Doomsday + 1 ... thus 1971 is Doomsday + 4 = Sunday ... August(8) 8th is Doomsday ... August 13th 1971 was a Friday

Example: what day of the week was December 24, 1973?
Answer: 73 = Doomsday ... thus 1973 is Wednesday ... December(12) 12th is Doomsday ... December 24th 1973 was a Monday

Return to top

Other Centuries

Previously, we learned that Doomsday for 1900 was Wednesday. What is Doomsday for other centuries?

Let's start with the 21st century, i.e. the 2000's.

The 2000's

Well, it turns out the 2000's are real easy. Recall the chart we were looking at earlier. Here it is again, extended into the 2000's a few years...

  Sun Mon Tue Wed Thu Fri Sat
 1999 ---- 2000 2001 2002 2003 ----
 2004 2005 2006 2007 ---- 2008 2009
 2010 2011 ---- 2012 2013 2014 2015
 ---- 2016 2017 2018 2019 ...

Notice that Doomsday for 2000 is Tuesday, i.e. "2000=Tue". This is the mnemonic that helps us anchor the other years in this century.

Remember the formula we learned for the 1900's, where we got the multiples of 12, kept the remainder, and added the number of 4's in the remainder? That still works, we just apply it to this century with Tuesday as the Doomsday for the 2000's.

Let's work through a couple of examples.

Example: what day of the week is May 29, 2017? (That would have been John F. Kennedy's 100th birthday, had he lived.)
Answer: 17 / 12 = 1 ... remainder 5 ... 5 / 4 is 1 ... 1 + 5 + 1 = 7 which is 7=0 days to be added to Tuesday (for the 2000's) ... Doomsday 2017 is Tuesday (which the chart above confirms) ... May(5) 9th is Tuesday, 23rd is Tuesday ... May 29th, 2017 is Monday.

Example: what day of the week is July 20, 2069? (That will be the 100th anniversary of the Apollo 11 moon landing.)
Answer: 69 / 12 = 5 ... remainder 9 ... 9 / 4 is 2 ... 5 + 9 + 2 = 16 which is 2 days to be added to Tuesday (for the 2000's) ... Doomsday 2069 is Thursday ... July(7) 11th is Thursday ... July 18th is Thursday, so July 20th, 2069 is Saturday.

Other Centuries

Let's construct another chart of years, extending backwards and forwards from the previous chart, except we want it to cover a bigger range of years. Let's show only those rows with a century year:

  Sun Mon Tue Wed Thu Fri Sat
 1599 1600 1601 1602 1603
 1700 1701 1702 1703 1704 1705
 1796 1797 1798 1799 1800 1801
 1897 1898 1899 1900 1901 1902 1903
 1999 2000 2001 2002 2003
 2100 2101 2102 2103 2104 2105
 2196 2197 2198 2199 2200 2201
 2297 2298 2299 2300 2301 2302 2303
 2399 2400 2401 2402 2403
 2500 2501 2502 2503 2504 2505

Examine this chart carefully, until you convince yourself that it is behaving exactly as you would expect for leap century years and non-leap century years. Remember the rule for determining a leap year:

  • if it's divisible by 4, it is a leap year,
    • unless it's divisible by 100, then it's not a leap year,
      • unless it's divisible by 400, then it is a leap year

Each normal year advances Doomsday by one day. Each leap year advances Doomsday by two days. Now look at the century years again:

 Sun Mon Tue Wed Thu Fri Sat
 1700 1600
 2100 2000 1900 1800
 2500 2400 2300 2200

What's the best way to memorize century Doomsdays? I'm not sure. Here's what I use. Notice that century Doomsdays fall only on "Sun-Tue-Wed-Fri". I say this as "Son to wed Friday", thinking of my own (second) son and how pleased I would be if he were indeed getting married this Friday (my first son got married on a Saturday in 2003).

Combine "Sun-Tue-Wed-Fri" with Dr. Conway's "We-in-dis-day" for 1900=Wednesday and "2000=Tuesday", and I can reconstruct the chart mentally. The tricky part is that the years go right to left in each row, but 2000=Tue and 1900=Wed help with this. The easy part is that if you can get just that one row, with 2000=Tue and 1900=Wed in it, then the other years have the same Doomsday, plus or minus 400 years.

Example: what day of the week is Canada's 300th birthday, July 1st, 2167?
Answer: 67 / 12 = 5 ... remainder 7 ... 7 / 4 = 1 ... 5 + 7 + 1 = 13 i.e. 6 ... 6 + 2100=Sunday = Saturday ... July(7) 11th is a Saturday, so July 1st, 2167, is Wednesday.

Return to top

The Hand

Dr. Conway now teaches the Doomsday algorithm, complete with Century adjustment, using a very simple visual aid—your hand.

 _____
 ____/ ___)____ <-- 1
 _______) <-- 2
 ________) <-- 3
 ____ _______) <-- 4
 \________) <-- 5

1 -- Doomsday Difference
2 -- Century Day
3 -- number of DOZENS
4 -- remainder
5 -- number of 4s in remainder

The Doomsday Difference is the difference between the required date and a nearby Doomsday, recorded as so many days "on" (i.e. to be added) or "off" (subtracted) from that Doomsday.

Recall a couple of the examples we've covered:

  • July 4th is always Doomsday, i.e. the Doomsday Difference is 0

  • Christmas, December 25th, is always "1 off" Doomsday

Be careful with the Doomsday Difference for dates in January and February. (Thanks to Bob Goddard for pointing this out.) In a leap year, we must subtract 1 from the Doomsday Difference for January and February dates:

  • Valentine's Day, February 14, is always "1 off" Doomsday in leap years, when Doomsday is February 29th; in ordinary years, the Doomsday Difference for Valentine's Day is 0

  • Groundhog Day, February 2, is only "1 on" Doomsday in leap years, when Doomsday is February 29th; in ordinary years, the Doomsday Difference for Groundhog Day is "2 on"

  • New Year's Day, January 1, is always "3 off" Doomsday in leap years, when Doomsday is the 4th of January; in ordinary years, the Doomsday Difference for New Year's Day is "2 off"

Examples using the hand

Here, in his own description, is how Dr. Conway would calculate the day of the week for Pearl Harbor Day, December 7th, 1941.

The various numbers to be attached to the hand are (reading from the thumb):

  • "2 on" (for Dec 7)
  • "Wednesday" (for 1900)
  • "3 dozen" (getting us to 1936)
  • "5 remainder" (number of years after 1936)
  • "and 1" (since one of those 5 years was a leap year).

Don't start adding these up until you've formed them all, and then proceed as far as possible by cancelling first 14s, then 7s. To make sure we haven't forgotten them, let's say:

" 2, Wed, 3, 5, 1 "

(touching the appropriate digits as we do so), and then cancel that 2+5=7 (and folding down the thumb and ring finger) to get

"Wed, 3 and 1 " = Wed + 4 = Sun

I also advise use of my mnemonic names for weekdays, namely:

NUNday, ONEday, TWOSday, tWEBLESday, FOURSday, FIVEday, SIXurday, SE'ENday

which can be pronounced so that they both sound like numbers and weekdays, and so help you do the addition, for example

" TREBLES, 3 and 1 = SEVENday " (Sunday)

in the above case.

The nice part about Dr. Conway's Hand is that we do the calculations in the same order we usually say the date -- month/day, then century/year. For example, for August 4, 1997, we do August 4, then 19, then 97.

Example: what day is August 4, 1997? Answer:

 _____
 ____/ ___)____ <-- 4 off (Aug 4)
 _______) <-- Wed (for 1900)
 ________) <-- 8 DOZENS
 ____ _______) <-- remainder 1
 \________) <-- and 0

which is "4 off, tWEBLESday, 8, 1" or -4+3+8+1 which is 1, so August 4, 1997 is a Monday.

Finally, one last warning: Watch out for Gregorian versus Julian dates. The Doomsday algorithm described up to this point covers only Gregorian dates.

Example: what day was September 14, 1752?
Answer:

 _____
 ____/ ___)____ <-- 2 on (Sep 14)
 _______) <-- Sun (for 1700)
 ________) <-- 4 DOZENS
 ____ _______) <-- remainder 4
 \________) <-- and 1

which is "2, Sun, 4, 4, 1" and we can throw out the 2, a 4 and the 1 to get 4 on Sunday, so September 14, 1752 was a Thursday.

That was a trick question, sort of. September 14, 1752 was the first day of the Gregorian calendar in England and its colonies. (The Gregorian calendar was originally adopted in parts of Europe in 1583). So September 1752 actually looked like this:

Sun Mon Tue Wed Thu Fri Sat
 1 2 14 15 16
 17 18 19 20 21 22 23
 24 25 26 27 28 29 30

Neat, eh?

Return to top

Origins

The Doomsday algorithm was created by John Horton Conway, an eminent mathematician, perhaps best known as the inventor of the Game of Life.

I first heard about the Doomsday algorithm on November 27, 1982, on a CBC Radio program called Quirks and Quarks. Dr. Conway was interviewed by Jay Ingram, who later worked at Discovery Canada and has recently released a new book called The End of Memory. Anyhow, back in those days Quirks and Quarks occasionally made typed transcripts available, and I sent away for one.

Dr. Conway had just published a book that year (co-authored by Elwyn R. Berlekamp and Richard K. Guy) called Winning Ways For Your Mathematical Plays, Volume 2: Games in Particular, Academic Press, London, 1982, ISBN 01-12-091102-7. The Doomsday algorithm is on pages 795-797, and the rest of the book is mainly about games, with substantial emphasis on their mathematical underpinnings.

In the original version of the Doomsday algorithm, the odd months were a bit harder to remember than "I work from 9-5 at the 7-11." You had to remember if the odd month was a long month or a short month. The 3rd, 5th, and 7th months are "long" because March, May, and July have 31 days, while the 9th and 11th months are "short" because September and November have only 30 days. You could remember "30 days hath September... and November" (but be careful because this old rhyme includes April and June which are even months). Anyway, for long odd months, Doomsday is the (N+4)th, while for short odd months, Doomsday is the (N-4)th. The mnemonic was long=add, short=subtract. Thus:

  • March (3rd month, long) 3+4=7th is Doomsday
  • May (5th month, long) 5+4=9th is Doomsday
  • July (7th month, long) 7+4=11th is Doomsday
  • September (9th month, short) 9-4=5th is Doomsday
  • November (11th month, short) 11-4=7th is Doomsday

I'd agree that it's easier to remember "I work from 9-5 at the 7-11" together with "March 0th=7th".

Additional background

For more on the development of the Doomsday Algorithm, see Doomsday Timeline.

The Second Doomsday Lesson describes a 2010 meeting with Dr. Conway in which he explains the "Hand" method on the back of a napkin (picture included).

Pi Days

I recently received the following email from reader Roman Weil, currently teaching at Princeton.

I've been teaching Doomsday Rule for about fifteen years because I can show students the first day of class what my exam questions are like-working backwards. If Thanksgiving Thursday is November 27 in a Leap Year, what is the day of the week of Feb. 28 that year?

Students can think they have mastered the rule and still not answer the question. I can show them up front that directionally correct doesn't cut it; thorough mastery is needed. Doomsday is a good way to get them there on the first day.

Students invariable ask why the name. When I taught at Princeton five years ago, I asked my old college roommate to get to John Conway and ask. To my surprise it took 3, not 2, degrees of separation to get to him. He said he wanted the name to end in "-day" and "Dooms" popped into his head.

About a decade ago, one of my adult students said his family had used the rule for years and called it Pi Day, because 3.14 is a one, too. From then, I call it Pi Day, because it's easier to explain the etymology.

Thanks so much, Roman. Delighted to have this background.

In case it wasn't obvious, "Pi day" refers to March 14th because 3.14 are the first significant digits of π. And of course March 14th is always a Doomsday.

Note: Roman also included a January trick by his son Sandy Weil which is mentioned in Odd Months.

Return to top

The following web sites are about or include descriptions of Dr. Conway's Doomsday algorithm.

For more information about Dr. Conway, see:

  • John Horton Conway: the world's most charismatic mathematician. "John Horton Conway is a cross between Archimedes, Mick Jagger and Salvador Dalí. For many years, he worried that his obsession with playing silly games was ruining his career — until he realised that it could lead to extraordinary discoveries." Story by Siobhan Roberts, author of Genius at Play, The Curious Mind of John Horton Conway published by Bloomsbury, 2015.

  • Inside the mind of 'mathemagician' John Horton Conway. In this Toronto Star excerpt from her biography, Genius at Play, author Siobhan Roberts introduces readers to a distinguished scholar who claims never to have worked a day in his life.

  • Interview with John Horton Conway (PDF). Edited version of an interview with John Horton Conway conducted in July 2011 at the first International Mathematical Summer School for Students at Jacobs University, Bremen, Germany

  • Not Just Fun and Games April 1999 Scientific American profile of John H. Conway. (Note: this article is now available online only if you purchase the digital edition.)

  • Charles Seife's Mathemagician -- an amusing article about John Horton Conway.

  • John Conway's Game of Life by Stephen Stuart -- an interactive version that you can play via your web browser.

Interesting calendar links

For links to other calendar sites, see my Calendar Links page; CAUTION, this page of links has not been updated since 2003!


KaBoL logo The Doomsday Algorithm was "latest link in the braid" for the week of April 6-12, 1999.

"This page will teach you a simple algorithm to calculate mentally the day of the week corresponding to any given date. Give it a try, it's quite rewarding! The page features clear instructions, examples, and mnemonic tricks."

KaBoL is a "cool math site of the week" service to the mathematics community provided by the Canadian Mathematical Society.

Return to top



from Hacker News https://ift.tt/1iGXZiV

Reasons to Learn Redux as a JavaScript Developer


Redux has been with us for a while now. What has gone public 2015 -- demonstrated by Dan Abramov in his infamous talk about time travel -- suddenly turned into many JavaScript developer's day to day business. Especially React developers were hit hard by this phenomenon, because it gave everyone a clear path on how to deal with state management.

One year later, Dan Abramov gave a recap on what made Redux successful in the first place. Both talks are super insightful on how a problem can be solved with a piece of technology and what makes this technological lasting after all. Lots of JavaScript libraries come and go. But Redux managed to stay with us.

However, I believe there is more than just one successful library. Redux is a whole mindset shift for many people in the JavaScript community, who literally grew up with only web development, but never heard about function composition or immutability before. Whether Redux stays with us for a few more years or makes place for other state management libraries, it leaves a great legacy on how we develop modern web applications.

Everything has a clear Purpose

If someone would ask me for one short representation of Redux, it would be:


State => View

If it needs more explanation, I would extend it into:


Action => Reducer(s) => Store => View

If there is more context needed, one could extend it into a repeating loop:


Action => Reducer(s) => Store => View => User Interaction => Action ...

That's all of Redux (State) in context of a library like React (View). Every part in the chain has its task. Everything is clearly separated from each other and serves a purpose for the greater goal: state management.

However, too many people associate Redux tightly with React. Once they start learning React, they go all-in by combining React with Redux from the start which demotivates lots of developers with its complexity. However, Redux in a nutshell isn't that complex, if just considering Redux, because after all, it's just a state container (object) which holds state; with an API that enables one

  • to manipulate the state
  • to receive the state
  • to listen to state changes

Let's recap all parts of Redux briefly in JS. This is a Redux Reducer that acts on two Redux Actions which has no dependencies on the Redux library at all:


function reducer(state, action) {
switch(action.type) {
case 'TODO_ADD' : {
return applyAddTodo(state, action);
}
case 'TODO_TOGGLE' : {
return applyToggleTodo(state, action);
}
default : return state;
}
}

function applyAddTodo(state, action) {
return state.concat(action.todo);
}

function applyToggleTodo(state, action) {
return state.map(todo =>
todo.id === action.todo.id
? { ...todo, completed: !todo.completed }
: todo
);
}

The Redux store which knows about the Redux Reducer:


import { createStore } from 'redux';

const store = createStore(reducer, []);

Then, the Redux Store offers a small API surface to interact with it -- e.g. dispatching a Redux Action:


store.dispatch({
type: 'TODO_ADD',
todo: { id: '0', name: 'learn redux', completed: false },
});

Finally, in JavaScript, you can listen to changes with the Redux Store:


store.subscribe(() => {
console.log(store.getState());
});

That's Redux in a nutshell with all its fragments: Action, Reducer, Store. There is no React and no View yet. The View could be considered as the console.log. If you didn't learn Redux yet, feel free to check out this long read React + Redux tutorial which teaches Redux before it integrates into React.

Redux's Actions, Reducers, Store have all their mandatory place in the Redux toolchain. If there needs to be syntax sugar on top, one can add Action Creators and Selectors. All you need to get started is the redux library to create the Redux Store. Everything else is just JavaScript. Also there is nothing to see about a library like React yet. It's clearly separated with its own library -- react-redux -- and ecosystem.

I believe Redux has taught us a great deal about separating things into atomic parts. Within the library -- with its Actions, Reducers and Store -- everything has its purpose and clear API, but also outside of the library with all the bindings for different frameworks like React and Angular. It gave everyone contributing to the ecosystem the master plan on how things should be done with clear constraints and a simple API.

Immutability

Immutability wasn't a huge deal in the JavaScript landscape before Redux. Performing mutations on variables was everyone's usual business. However, with the introduction of the modern frontend frameworks and scaling web applications, many people felt the pain of passing around mutable information. Changing a variable at one place meant unforeseen side-effects at another place in your application.

In Redux everything in the state container should be treated as immutable data structure -- which isn't enforced though. If you are adding an entry to an array, with Redux one got used to JavaScript functions which treat your data structures as immutable:


// do
const newState = state.concat(action.todo);

// don't
state.push(action.todo);

There are various array and object functions which return new arrays/objects -- keeping them immutable -- instead of mutating them. Also recent language additions helped a lot to facilitate this new mindset:


const toggledTodo = { ...todo, completed: !todo.completed };

People started to think about these nuances regarding immutable data structures in JavaScript -- which had superior benefits for the overall JavaScript development experience. No more leaking variables which were mutated at various places in one's application.

Pure Functions

Almost identical to immutability, pure functions weren't discussed as heavily before Redux got introduced in the JavaScript ecosystem. It was more of a suggestion that functions should be pure, but never been taken super serious by web developers.


// action creator returning an action

function addTodo(todo) {
return {
type: 'TODO_ADD',
todo,
};
}

const action = addTodo({
id: '0',
name: 'learn redux',
completed: false
});

store.dispatch(action);

With Redux the mindset shifted and people started to avoid having side-effects in their functions, to please the Redux philosophy, but also to ensure better testability and to avoid unforeseen breaches of their functions in the long run.


(Input) => Output

A Redux Action is just an operator on the present state whereas a Redux Reducer takes this action to modify the state from one representation to the next representation. There is no remote API call or other task in between. It always follows one function signature:


(Current State, Action) => New State

That's the secret which made Redux Reducers and in general the Redux state management highly predictable. One action leads to a new state based on the action's information and the current state. The Redux store is only the container for this state.

Thinking in Functions

With Redux gaining popularity, functions were considered more first-class citizens in JavaScript than ever. Not only the concept of pure functions got passed from developer to developer, but also other concepts like higher-order functions and function composition gained popularity.


function toggleTodo(action) {
return function(todo) {
return todo.id === action.todo.id
? { ...todo, completed: !todo.completed }
: todo;
};
}

function applyToggleTodo(state, action) {
return state.map(toggleTodo(action));
}

All of these concepts contributed to the fact that JavaScript developers got more and more introduced to the paradigm of functional programming. Obviously these concepts didn't originate with Redux, but they were taken into the eyesight of many developers who only started to learn JavaScript or who had only used JavaScript in their career so far.

JavaScript ES6

It was just a timing coincidence that JavaScript ES6 got introduced the same time when Redux gained traction. JavaScript ES6 brought developers new features that just played into Redux's hands. For instance, functions could be expressed with arrow functions instead of bulky function statements and bodies:


const toggleTodo = action => todo =>
todo.id === action.todo.id
? { ...todo, completed: !todo.completed }
: todo;

const applyToggleTodo = (state, action) =>
state.map(toggleTodo(action));

JavaScript ES6 made many expression more concise. Creating a new object out of another object with keeping the data structure immutable could be achieved with JavaScript's new spread operator:


const toggledTodo = {
...todo,
completed: !todo.completed,
};

It was just a wonderful addition to JavaScript which made many libraries like Redux, but also React, flourish.

Unidirectional Data Flow

Redux already adds lots of predictability to modern state management by just taking apart all the fragments -- that are mandatory to perform state changes -- and by giving them clear purposes and APIs.


Action => Reducer(s) => Store

However, another great factor was the unidirectional data flow which got primarily introduced in React and its preceding state management libraries (see Flux), but was embraced by Redux for a predictable state management flow as well.


View => Interaction => Action => Reducer(s) => Store => Updated View

There is a clear unidirectional data flow. One can see who is responsible:

  • Who starts the chain of state manipulation (e.g. user interaction).
  • Who manipulates the state (reducer) with which information (action, current state).
  • Who is affected by the state manipulation (e.g. UI re-render).

1) Interaction in View =>
2) State Manipulation =>
3) Updated View =>
1) Interaction in View =>
...

Learning about information flow is considered a great asset for every developer. There are no unpredictable side-effects in between with a clear architecture -- due to pure functions and immutable data structures -- and there are no bi/multi directional data flows which are difficult to follow -- which has been a topic before where other frameworks failed. Everything moves towards one direction and ultimately results in a predictable state management loop.

Thinking in Events, not Setters

Often people mistake Redux as a simple setter/getter concept. The UI dispatches an action; which goes through a reducer; which ultimately sets a new state in the Redux store. The subscribed UI receives an update from the Redux store and re-renders based on the new state.


// that's not Redux

store.setState({
id: '0',
name: 'learn redux',
completed: false
});

However, that's not giving Redux the full credit for what it is, because it is a sophisticated event-driven concept (see Event Sourcing or CQRS). It has reducers in between which decide for themselves whether they are affected by an incoming action or not. It moves the perspective from

  • explicit to implicit state manipulation
  • setters to events
  • one-purpose reducers to multi-purpose reducers
  • narrow minded reducers to open minded reducers

Especially the last two facts should be considered by ever developer to make use of Redux's full potential, because suddenly reducers operate on a higher abstraction level than common setters and act on the same actions as other reducers in your application:


import { createStore, combineReducers } from 'redux';

function todoReducer(state, action) {
switch(action.type) {
case 'TODO_ADD' : {
return applyAddTodo(state, action);
}
case 'TODO_TOGGLE' : {
return applyToggleTodo(state, action);
}
default : return state;
}
}

function statisticReducer(state, action) {
switch(action.type) {
case 'TODO_ADD' : {
return applyCalculateTodos(state, action);
}
default : return state;
}
}

const rootReducer = combineReducers({
todos: todoReducer,
statistics: statisticReducer,
});

const store = createStore(rootReducer, []);

Note: Keeping in mind that the given example is not perfect here, because any sorts of statistics computed based on the todo entities could be calculated on the fly by having all todos available from the state and calculating their statistics with the right selector just in time.

Redux gives a great demonstration of event driven systems for any web developer who hasn't seen one before. Just by looking at how actions, reducers and the store work together, it gives people lots of insights how event-driven systems in other applications are doing there thing.

Domain-Driven Design

Domain-driven design (DDD) isn't a thing in Redux itself, and may be a bit far fetched here arguably, but once you get beyond a small-sized application, every developer or team of developers has to think about how to split up state/reducers into their domains when using Redux.

You may end up with reducers for (A) various entities (e.g. todos, users) that are fetched from a remote API, (B) filters (e.g. show all incomplete todos, show all active users) and (C) statistics (e.g. calculate the number of completed todos by active users).


import { createStore, combineReducers } from 'redux';

...

const rootReducer = combineReducers({
todos: todoReducer, // (A)
users: userReducer, // (A)
filter: filterReducer, // (B)
statistics: statisticReducer, // (C)
});

const store = createStore(rootReducer, []);

Whether people think about domain-driven design when they see this kind of domain clustering doesn't matter, but what matters is that they unconsciously start to think in domains and how to encapsulate them in their places with clear APIs to the outside.

Even though it may not be domain-driven design how it's taught in the books, it opens up a developer's mind for these kind of concepts which are mainly showing up in other programming languages.

Innovative Ecosystem

Once you started to use Redux, you are likely to meet selectors and actions creators too:


Action Creator => Action => Reducer(s) => Store => Selector => View

These are only two more concepts for Redux to give every part of it a more distinct role in the whole toolchain. Whereas a Action Creator creates an action object, a Selector selects only a slice of your state to make it available to your UI:


// action creator

function addTodo(todo) {
return {
type: 'TODO_ADD',
todo,
};
}

// selector

function getCompletedTodos(state) {
return state.filter(todo => todo.completed);
}

Beyond these concepts you will most likely meet other popular libraries from the Redux ecosystem such as Redux Saga or Redux Observables -- which both handle side-effects in Redux as middleware. Each of them introduces a new concept to Redux, which are not heavily used at all in JavaScript: generators and observables.


// Redux Saga

function* fetchUser(action) {
try {
const user = yield call(Api.fetchUser, action.payload.userId);
yield put({ type: 'USER_FETCH_SUCCEEDED', user: user });
} catch (e) {
yield put({ type: 'USER_FETCH_FAILED', message: e.message });
}
}

function* userWatcher() {
yield takeEvery('USER_FETCH_REQUESTED', fetchUser);
}

That's another aspect which made Redux successful: its ecosystem. The concept of Redux is just the core, but its API design and simplicity of just using JavaScript left other developers lots of opportunities to opt-in into its world. This led to library authors exploring new concepts, such as generators or observables, and bringing them to the attention of more developers.


// Redux Observable

const pingEpic = action$ => action$.pipe(
filter(action => action.type === 'PING'),
delay(1000),
mapTo({ type: 'PONG' })
);

dispatch({ type: 'PING' });

Redux with its ecosystem broadened the horizon for many JavaScript developers; giving them the tools for exploring what's possible with their programming language of choice. Also other state management library authors draw inspiration from everything that's going on in Redux's ecosystem making it the perfect blueprint for a flourishing ecosystem.

KISS

It's a common theme: Learning Redux is overwhelming when starting out with everything at once. There are ...

  • actions
  • reducers
  • Redux store
  • connecting it to React
  • combining reducers
  • middleware
  • action creators
  • selectors
  • generators/observables

However, all of this depends on how newcomers to Redux structure their learning experience. When you resume this article to the very beginning, one can see that Redux is only the following in its core:


Action => Reducer(s) => Store

That's all to it. Redux is Keep it simple, stupid. There is no hidden magic, 99% of it is pure JavaScript expressed in actions and reducers. Only the Redux store API offers a small surface area for ...


// dispatching actions
store.dispatch(myAction);

// subscribing to state updates
store.subscribe(() => {
// do something, e.g. re-render UI
});

// getting the state
store.getState();

There isn't more to Redux. KISS should be applied to learning Redux as well. Start with its core concepts, not worrying about selectors, sagas and React. Then move forward from there once you feel comfortable. Don't throw too much stuff on top if you feels it's too much of a burden.

After all, KISS is an important lesson for everyone who has used Redux. If one decides to create their own library, then KISS. If one decides to build a React component, then KISS. If one decides to open up an API, then KISS. After all, this is what made Redux popular. It solved only one problem, but it solved it amazingly good.

Don't Brag; Be Humble

Everyone who follows the creators and team behind Redux can see them being super humble. There exists a blog post by Dan Abramov suggesting that you may not need Redux for your application. All these people behind the library are great role models for the JavaScript community.

I think on a non-technical level, everyone can learn something from these personality traits. Give helpful advice when someone asks you. Don't brag about your stuff. Consider opinions by other people. Don't throw your favorite framework in another person's face. We are all just human beings, so let's support each other in order to develop amazing things in JavaScript!

Redux makes one a better JavaScript Developer

Taken all the previous points into account, I believe Redux makes everyone a better JavaScript developer. People start to think in functions, in higher-order functions or composable functions or concise functions, consider immutable data structures, pure functions, and domains in their application, and stay on the shoulders of giants when contributing to the ecosystem by following their role models. Maybe the no bragging and humble attitude rubs off to the one or other person as well :-) Overall, it makes everyone a better developer.

I believe Redux's legacy was greatly influenced through timing. There were many people out there who "only" knew JavaScript as their programming language, maybe started just recently with it as their first language, and never got introduced to broader programming concepts and techniques like immutability, functional programming, domain-driven design or generators. With Redux at their hands, they learned a great deal about all these things. Even though Redux may go away in the future, I would recommend to everyone who is new to JavaScript to learn it just for the sake of all the benefits that are coming with learning it.



from Hacker News https://ift.tt/2np0hlz