Created
April 9, 2020 07:32
-
-
Save XianYeeXing/a8522040ecfa7045d5a2e03fc4a55fb3 to your computer and use it in GitHub Desktop.
不斷地取出與上一次不重複的元素
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* EXAMPLE: | |
* const factory = require('no-coflict-series'); | |
* | |
* const series = factory([1, 4, 3, 2, 7]); | |
* | |
* console.log( series.next() ); | |
* console.log( series.next() ); | |
* console.log( series.next() ); | |
* console.log( series.next() ); | |
* console.log( series.next() ); | |
* | |
* console.log( series.dump() ); | |
* | |
*/ | |
const {shuffle} = require('lodash'); | |
module.exports = arr => { | |
const len = arr.length; | |
let idx = 0; | |
arr = shuffle(arr); | |
const next = () => { | |
let ret = arr[idx]; | |
if(idx === len - 2) { | |
const arrClone = [...arr]; | |
const last = arrClone.pop(); | |
arr = [last, ...shuffle(arrClone)]; | |
idx = 0; | |
} else { | |
idx += 1; | |
} | |
return ret; | |
} | |
return { | |
next, | |
dump() { return arr }, | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment