The Sieve of Eratosthenes is an ancient algorithm for finding prime numbers up to a given limit. As stated in Wikipedia. It is quite simple but awesome. As always I like simple solutions. It is not the fastest though - runs in O(NLog(LogN)) but it's robust enough. By the way, the fastest prime numbers generator is currently the Sieve of Atkin. So what do we in this article? We're going to create a simple page with one input that represents a given limit N and marks all prime numbers P (so that P <= N) on a sequence of numbers that is rendered using ReactJS. Why React? Well, one of the key React's feature is the Virtual DOM. Basically, once you update the model the engine renders only what's necessary and skips the elements that have not been updated. This is very powerful feature. For those folks who haven't heard much about React I recommend following video to make a better picture. The code OK, let's get to coding. The algorithm itself is pretty straightforward. Code Editor
When you check the project on GitHub you'll also notice the ugly initial array fill Code Editor
I know I could use the Array.prototype.fill() as part of ECMAScript 6 but since this particular function is not yet supported by all browser I'm gonna stick up with old loop method. The React's part is quite simple. We're gonna create 2 classes. One that represents the whole view elements and one that represents the dynamic array being rendered as a sequence of spans. Code Editor
The key method is handleSubmit. Notice the setState function that sets the model list array to a newly created array of booleans. If you start with limit of e.g. 100 and later increase the limit to e.g. 130 you'll nicely see how the previously rendered elements are staying intact. Only newly inserted prime numbers are being signalized by color animation. That's because React knows what changed in the model list array. The array view class is then very simple. Check it outAs usual the whole project is at your disposal on plunker and also GitHub. Enjoy. By the way - a good tip for online JSX compiling service - Babeljs.io.
0 Comments
Leave a Reply. |
AboutBlog about my programming experiments, tests and so on. Categories
All
Archives
November 2016
|