Created
January 26, 2018 18:01
-
-
Save pl12133/9eddd46fc0c00123ce81b4710c772a6c to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { h } from 'preact'; | |
function lastChild(arr) { | |
return arr && arr.length ? arr[arr.length - 1] : undefined; | |
} | |
function get(obj, key, def, p) { | |
p = 0; | |
key = key.split ? key.split('.') : key; | |
while (obj && p<key.length) obj = obj[key[p++]]; | |
return obj===undefined ? def : obj; | |
} | |
function withObject(getObj) { | |
if (getObj && typeof getObj === 'object') { | |
let obj = getObj; | |
getObj = () => obj; | |
} | |
function mapper(obj, mapToProps) { | |
let key, props = {}; | |
if (!mapToProps) { return props; } | |
if (typeof mapToProps === 'string') { | |
let paths = mapToProps.split(','); | |
for (key in paths) { | |
let path = paths[key]; | |
let prop = lastChild(path.split('.')); | |
props[prop] = get(obj, path); | |
} | |
return props; | |
} | |
if (typeof mapToProps === 'object') { | |
for (key in mapToProps) { | |
props[key] = mapper(obj, mapToProps[key]); | |
} | |
return props; | |
} | |
if (typeof mapToProps === 'function') { | |
return mapToProps(obj); | |
} | |
} | |
return (mapToProps) => (Child) => (props, state, context) => ( | |
h(Child, Object.assign({}, mapper(getObj(props, context), mapToProps), props)) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment