Merge pull request #438 from kriadmin/master

[ADD : isArrayLike.md and isValidJSON.md]
This commit is contained in:
Angelos Chalaris
2017-12-31 15:05:29 +02:00
committed by GitHub
2 changed files with 45 additions and 0 deletions

23
snippets/isArrayLike.md Normal file
View File

@ -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
```

22
snippets/isValidJSON.md Normal file
View File

@ -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
```