Last active
December 20, 2017 19:47
-
-
Save skiano/be2059dfafa9d3fb0935d6d150c716e9 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
const createCursor = (directions, onMove) => { | |
const dirKeys = Object.keys(directions); | |
const cursor = {}; | |
let location = 0; | |
cursor.max = 1000; | |
cursor.get = () => location; | |
cursor.set = nextLocation => { | |
if (onMove) onMove(nextLocation, location); | |
location = nextLocation; | |
return cursor; | |
}; | |
Object.keys(directions).forEach(key => { | |
cursor[key] = predicate => { | |
let nextLocation = location; | |
if (predicate) { | |
let i = 0; | |
do { | |
nextLocation = directions[key](nextLocation); | |
if (i++ > cursor.max) { | |
throw new Error('cursor exceeded max: ' + cursor.max); | |
} | |
} while (!predicate(nextLocation)); | |
} else { | |
nextLocation = directions[key](nextLocation); | |
} | |
return cursor.set(nextLocation); | |
}; | |
}); | |
return cursor; | |
}; | |
const list = ['A', 'B', 'C']; | |
const listCursor = createCursor( | |
{ | |
next: idx => idx + 1, | |
prev: idx => idx - 1, | |
}, | |
location => { | |
console.log(location); | |
} | |
); | |
console.log(3 % 3); | |
const by3 = v => v % 3 === 0; | |
listCursor | |
.next() | |
.next() | |
.next() | |
.next(by3) | |
.next(by3) | |
.prev() | |
.set(26) | |
.prev(by3) | |
.prev(by3) | |
.next(by3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment