Skip to content

Instantly share code, notes, and snippets.

@feliperohdee
Created January 21, 2018 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feliperohdee/b462af193e6e2162eefb83f2b81b7e4a to your computer and use it in GitHub Desktop.
Save feliperohdee/b462af193e6e2162eefb83f2b81b7e4a to your computer and use it in GitHub Desktop.
safe get/set properties
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