Skip to content

Instantly share code, notes, and snippets.

@ktilcu
Created October 26, 2018 03:25
Show Gist options
  • Select an option

  • Save ktilcu/cf5474dfce9b3caf0f74298cb9f3e769 to your computer and use it in GitHub Desktop.

Select an option

Save ktilcu/cf5474dfce9b3caf0f74298cb9f3e769 to your computer and use it in GitHub Desktop.
utils
function isJson(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}
function getOr(def, path, obj) {
return path.reduce(function(target, key) {
return target && target[key] !== undefined ? target[key] : def;
}, obj);
}
function pathExists(path, obj) {
return (
path.reduce(function(target, key) {
return target && target.hasOwnProperty(key) ? target[key] : false;
}, obj) !== false
);
}
function propOr(fallback, prop, obj) {
return propExists(prop, obj) ? obj[prop] : fallback;
}
function propExists(prop, obj = {}) {
return obj.hasOwnProperty(prop);
}
function clone(obj) {
JSON.parse(JSON.stringify(obj));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment