Created
January 21, 2018 20:11
-
-
Save feliperohdee/b462af193e6e2162eefb83f2b81b7e4a to your computer and use it in GitHub Desktop.
safe get/set properties
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
export function get(fn, defaultValue = null, args) { | |
try { | |
const result = fn(args); | |
return result !== undefined && result !== null ? result : defaultValue; | |
} catch (e) { | |
return defaultValue; | |
} | |
} | |
export function set(object, path, value) { | |
const string = isString(path); | |
const length = path.length; | |
if (string || path.length) { | |
object[string ? path : path[0]] = value; | |
} else { | |
object[path[0]] = reduceRight(path, (reduction, token, index) => { | |
if (index === path.length - 1) { | |
return value; | |
} | |
return { | |
[path[index + 1]]: reduction | |
}; | |
}, {}); | |
} | |
return object; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment