Skip to content
This repository was archived by the owner on Feb 11, 2021. It is now read-only.

Commit f808633

Browse files
committed
Disallow duplicate numbers.
This code checks new numbers to see if they've been previously added. Then ignores the number if it is already in a set.
1 parent 4ffdb0e commit f808633

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

examples/simple/reducers/index.js

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,20 +36,37 @@ const primesInitialState = {
3636
function primeState( state = primesInitialState, action ) {
3737
switch ( action.type ) {
3838
case ADD_PRIME:
39-
const primes = [ ...state.primes, action.number ];
39+
const primes = [ ...state.primes ];
40+
41+
// Only add it to the list if it's not been added before.
42+
if ( primes.indexOf( action.number ) === -1 ) {
43+
primes.push( action.number );
44+
}
4045

4146
return Object.assign( {}, state, {
4247
primes
4348
} );
4449
case ADD_NON_PRIME:
45-
const nonPrimes = [ ...state.nonPrimes, action.number ];
50+
const nonPrimes = [ ...state.nonPrimes ];
51+
52+
// Only add it to the list if it's not been added before.
53+
if ( nonPrimes.indexOf( action.number ) === -1 ) {
54+
nonPrimes.push( action.number );
55+
}
4656

4757
return Object.assign( {}, state, {
4858
nonPrimes
4959
} );
5060
case ADD_QUEUE_NUMBER:
5161
console.log("queueing number: " + action.number);
52-
const addedQueue = [ ...state.queue, action.number ];
62+
const addedQueue = [ ...state.queue ];
63+
64+
// Only add it to the queue if it's not been added before.
65+
if ( addedQueue.indexOf( action.number ) === -1 &&
66+
state.primes.indexOf( action.number ) === -1 &&
67+
state.nonPrimes.indexOf( action.number ) === -1 ) {
68+
addedQueue.push( action.number );
69+
}
5370

5471
return Object.assign( {}, state, {
5572
queue: addedQueue

0 commit comments

Comments
 (0)