Skip to content

Instantly share code, notes, and snippets.

@XianYeeXing
Created April 9, 2020 07:32
Show Gist options
  • Save XianYeeXing/a8522040ecfa7045d5a2e03fc4a55fb3 to your computer and use it in GitHub Desktop.
Save XianYeeXing/a8522040ecfa7045d5a2e03fc4a55fb3 to your computer and use it in GitHub Desktop.
不斷地取出與上一次不重複的元素
/**
* 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