Created
May 4, 2017 17:27
-
-
Save nazoking/502e33be6137db51ff2d75b3cff11347 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
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