Skip to content

Instantly share code, notes, and snippets.

@nazoking
Created May 4, 2017 17:27
Show Gist options
  • Save nazoking/502e33be6137db51ff2d75b3cff11347 to your computer and use it in GitHub Desktop.
Save nazoking/502e33be6137db51ff2d75b3cff11347 to your computer and use it in GitHub Desktop.
class Repeater{
static tracker_collect(tracker){
switch(type(tracker)){
case 'function':
return tracker;
case 'undefined':
case 'null':
return (value, index, list) => value;
case 'number':
case 'string':
return (value, index, list) => value[tracker];
default:
throw Error(`unknown type as tracker ${type(tracker)}:${tracker}`);
}
}
constructor(tracker, generator, sweeper){
this.last = new Map();
this.tracker = tracker_collect(tracker);
this.generator = generator || ((value, index, list, key) => ({}));
this.sweeper = sweeper || ((state, key) => true);
}
repeat(list){
var next = new Map();
var ret = list.map((value, index, list) => {
var key = this.tracker(value, index, list);
if(next.has(key)){
throw Error(`key duplicate ${key}`);
}
var state;
if(this.last.has(key)){
state = this.last.get(key);
}else{
state = this.generator(value, index, list, key);
}
next.set(key, state);
return {state, key, value, index, list};
});
this.last
.filter((state, key) => !next.has(key) && !this.sweeper(state, key))
.forEach(() => next.set(key, state));
this.last = next;
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment