Playlist Algorithm

node v8.17.0
version: 1.0.0
endpointsharetweet
const chai = require('chai'); const expect = chai.expect; let currentTime = 1; function now() { return currentTime; } const LOOP_MAX = 10000; function getCurrentTrackState(playlist) { let startPoint = playlist[0].addedAt; let currentPoint = playlist[0].addedAt; let loopIteration = 0; let i = 0; while (true) { const track = playlist[i]; loopIteration++; if (loopIteration > LOOP_MAX) { throw new Error(`Max iterations reached: ${currentPoint}`); } if (track.addedAt <= currentPoint) { currentPoint += track.length; if (currentPoint > now()) { return { currentTrack: track, currentTrackOffset: now() - (currentPoint - track.length), nextTrack: playlist[(i + 1) % playlist.length] } } else { i = (i + 1) % playlist.length; } } else { // Reset i to 0 (-1 + 1 for the end of the loop) i = 0; } } }
/* For playlist a: 1, b: 2 c: 1 was added at time 5 Correctly played 11111111 012345678901234567 ab ab cab cab c... c Currently played 11111111 012345678901234567 ab abbcab cab... c ab cab <-- what the calculation is thinking when it adds c and recalculates what should be playing */
const playlist1 = [{ addedAt: 1, uri: "a", length: 1 }, { addedAt: 1, uri: "b", length: 2 }, { addedAt: 5, uri: "c", length: 1 }]; currentTime = 6; var results = getCurrentTrackState(playlist1); expect(results.currentTrack.uri).to.equal("b"); expect(results.nextTrack.uri).to.equal("c"); expect(results.currentTrackOffset).to.equal(1); 1;
const playlist2 = [{ addedAt: 1, uri: "a", length: 1 }]; currentTime = 6; var results = getCurrentTrackState(playlist2); expect(results.currentTrack.uri).to.equal("a"); expect(results.nextTrack.uri).to.equal("a"); expect(results.currentTrackOffset).to.equal(0); 1;
Loading…

no comments

    sign in to comment