From abac9e4c784db9b6f04f12e38c15e72316e4aca6 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 28 Jan 2018 14:44:40 +0200 Subject: [PATCH] Add attempt --- snippets/attempt.md | 22 ++++++++++++++++++++++ tag_database | 1 + 2 files changed, 23 insertions(+) create mode 100644 snippets/attempt.md diff --git a/snippets/attempt.md b/snippets/attempt.md new file mode 100644 index 000000000..c3dae169e --- /dev/null +++ b/snippets/attempt.md @@ -0,0 +1,22 @@ +### attempt + +Attempts to invoke a function with the provided arguments, returning either the result or the caught error object. + +Use a `try... catch` block to return either the result of the function or an appropriate error. + +```js +const attempt = (fn, ...args) => { + try { + return fn(args); + } catch (e) { + return e instanceof Error ? e : new Error(e); + } +}; +``` + +```js +var elements = attempt(function(selector) { + return document.querySelectorAll(selector); +}, '>_>'); +if (elements instanceof Error) elements = []; // elements = [] +``` diff --git a/tag_database b/tag_database index 4e52b9a38..a556e5be3 100644 --- a/tag_database +++ b/tag_database @@ -2,6 +2,7 @@ anagrams:string,recursion arrayToHtmlList:browser,array ary:adapter,function atob:node,string,utility +attempt:function average:math,array averageBy:math,array,function bind:function,object