|
| 1 | +import { removeQueueNumber, addPrime, addNonPrime } from '../actions/primes'; |
| 2 | + |
| 3 | +export const CHECK_NEXT_PRIME = 'CHECK_NEXT_PRIME'; |
| 4 | + |
| 5 | +function createPrimesMiddleware() { |
| 6 | + return ( store ) => ( next ) => ( action ) => { |
| 7 | + switch ( action.type ) { |
| 8 | + case CHECK_NEXT_PRIME: |
| 9 | + const { queue } = store.getState().primeState; |
| 10 | + checkNextPrime( queue, store.dispatch ); |
| 11 | + return true; |
| 12 | + default: |
| 13 | + return next( action ); |
| 14 | + } |
| 15 | + }; |
| 16 | +} |
| 17 | + |
| 18 | +function checkNextPrime( queue, dispatch ) { |
| 19 | + if ( queue.length > 0 ) { |
| 20 | + const number = queue[0]; |
| 21 | + console.log( 'checking next number ' + number ); |
| 22 | + checkPrime( number ).then( |
| 23 | + ( isPrime ) => { |
| 24 | + if ( isPrime ) { |
| 25 | + console.log( 'number ' + number + ' is prime!' ); |
| 26 | + dispatch( addPrime( number ) ); |
| 27 | + } else { |
| 28 | + console.log( 'number ' + number + ' is not prime!' ); |
| 29 | + dispatch( addNonPrime( number ) ); |
| 30 | + } |
| 31 | + dispatch( removeQueueNumber( number ) ); |
| 32 | + } |
| 33 | + ); |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +function checkPrime( number ) { |
| 38 | + return new Promise( |
| 39 | + ( resolve, reject ) => { |
| 40 | + |
| 41 | + for ( let i = 0; i < number; i++ ) { |
| 42 | + if ( Number.isInteger( number / i ) ) { |
| 43 | + resolve( true ); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + // No numbers below this one divided cleanly, it's prime. |
| 48 | + resolve( false ); |
| 49 | + } |
| 50 | + ); |
| 51 | +} |
| 52 | + |
| 53 | +export function checkNextPrimeAction() { |
| 54 | + return { type: CHECK_NEXT_PRIME }; |
| 55 | +} |
| 56 | + |
| 57 | +export default createPrimesMiddleware; |
| 58 | + |
0 commit comments