Last active
February 22, 2017 15:05
-
-
Save micahnz/53f4cf8459e19b8831a94a32dcd867fd 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
// | |
import semver from 'semver'; | |
// | |
export function createAction(type) { | |
const versions = []; | |
const map = {}; | |
// | |
function actionCreator(userRange) { | |
const range = semver.validRange(userRange); | |
if (range === null) { | |
throw new Error(`"${userRange}" is not a valid semantic version range"`); | |
} | |
const version = semver.maxSatisfying(versions, range); | |
if (version === null) { | |
throw new Error(`no action creator was found for "${range}""`); | |
} | |
return map[version]; | |
} | |
// | |
actionCreator.addVersion = (userVersion, fn) => { | |
const version = semver.valid(userVersion); | |
if (version === null) { | |
throw new Error(`"${userVersion}" is not a valid semantic version"`); | |
} | |
if (versions.indexOf(version) !== -1) { | |
throw new Error(`an action creator with version "${version}" already exists"`); | |
} | |
// | |
function versionedActionCreator(...args) { | |
const action = fn(...args); | |
// | |
return { | |
type, | |
...action, | |
meta: { | |
...action.meta, | |
version, | |
}, | |
}; | |
} | |
// | |
versions.push(version); | |
map[version] = versionedActionCreator; | |
// | |
return actionCreator; | |
}; | |
// | |
return actionCreator; | |
} | |
// | |
export default createAction; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment