@yagni-js/yagni-router
Version:
yagni-js router
42 lines (35 loc) • 938 B
JavaScript
import { match, pickPath, call, pick, pipe, ifElse, or, isNil, isEmpty, always, identity, slice, first } from '@yagni-js/yagni';
function url(path, handler) {
return {path: path, handler: handler, match: match(path)};
}
const getHash = pickPath(['target', 'location', 'hash']);
function matcher(routes) {
return function (hash) {
return routes.reduce(
function (acc, route) {
const match = route.match(hash);
return match ? acc.concat({match: match, handler: route.handler}) : acc;
},
[]
);
};
}
const callHandler = call(pick('handler'), pick('match'));
function hashRouter(routes) {
return pipe([
getHash,
ifElse(
or(isNil, isEmpty),
always('#'),
identity
),
slice(1), // strip # from hash
matcher(routes),
ifElse(
isEmpty,
identity,
pipe([first, callHandler])
)
]);
}
export { hashRouter, url };