Created
June 10, 2020 10:13
-
-
Save takumifukasawa/2caee156bee2406d39e481553c82d704 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
// # arg | |
// sequence: array | |
// [ | |
// { time: number, exec: function }, | |
// { time: number, exec: function }, | |
// ... | |
// ] | |
// | |
// # usage | |
// const sampleTimeline = timeline(sequence); | |
// sampleTimeline.exec(time); | |
// | |
// TOOD: sequenceはcopyしてからsortする | |
// | |
export default function timeline(sequence) { | |
sequence.sort((a, b) => { | |
if (a.time < b.time) return -1 | |
if (a.time > b.time) return 1 | |
return 0 | |
}) | |
const exec = t => { | |
// guard | |
if (sequence.length < 1) return | |
let spliceIndex = 0 | |
for (let i = 0; i < sequence.length; i++) { | |
const { time } = sequence[i] | |
if (t > time) spliceIndex = i + 1 | |
} | |
// no target | |
if (spliceIndex < 1) { | |
return | |
} | |
const executionTargets = sequence.splice(0, spliceIndex) | |
for (let i = 0; i < executionTargets.length; i++) { | |
executionTargets[i].exec(t) | |
} | |
} | |
return { | |
exec, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment