diff --git a/snippets/isArrayLike.md b/snippets/isArrayLike.md new file mode 100644 index 000000000..83c8acb81 --- /dev/null +++ b/snippets/isArrayLike.md @@ -0,0 +1,23 @@ +### isArrayLike + +Checks if the provided argument is array-like (i.e. is iterable). + +Use `Array.from()` and a `try... catch` block to check if the provided argument is array-like. + +```js +const isArrayLike = arr => { + try{ + Array.from(arr); + return true; + } + catch(e){ + return false; + } +} +``` + +```js +isArrayLike(document.querySelector('.className')) // true +isArrayLike('abc') // true +isArrayLike(null) // false +``` diff --git a/snippets/isValidJSON.md b/snippets/isValidJSON.md new file mode 100644 index 000000000..56211961b --- /dev/null +++ b/snippets/isValidJSON.md @@ -0,0 +1,22 @@ +### isValidJSON + +Checks if the provided argument is a valid JSON. + +Use `JSON.parse()` and a `try... catch` block to check if the provided argument is a valid JSON. + +```js +const isValidJSON = obj => { + try{ + JSON.parse(obj); + return true; + } + catch(e){ + return false; + } +} +``` + +```js +isValidJSON('{"name":"Adam","age":20}'); // true +isValidJSON('{"name":"Adam",age:"20"}'); // false +```