Add is.domElement() (#11)

This commit is contained in:
Melvin 2017-10-07 09:19:11 -07:00 committed by Sindre Sorhus
parent 6268253ec6
commit 75ac3cd574
4 changed files with 42 additions and 1 deletions

View file

@ -161,6 +161,18 @@ is.inRange = (x, range) => {
throw new TypeError(`Invalid range: ${util.inspect(range)}`);
};
const NODE_TYPE_ELEMENT = 1;
const DOM_PROPERTIES_TO_CHECK = [
'innerHTML',
'ownerDocument',
'style',
'attributes',
'nodeValue'
];
is.domElement = x => is.object(x) && x.nodeType === NODE_TYPE_ELEMENT && is.string(x.nodeName) &&
!is.plainObject(x) && DOM_PROPERTIES_TO_CHECK.every(property => property in x);
is.infinite = x => x === Infinity || x === -Infinity;
const isEmptyStringOrArray = x => (is.string(x) || is.array(x)) && x.length === 0;

View file

@ -44,6 +44,7 @@
],
"devDependencies": {
"ava": "*",
"jsdom": "^9.12.0",
"xo": "*"
}
}

View file

@ -145,11 +145,14 @@ Check if `value` (number) is in the range of `0` to `upperBound`.
is.inRange(3, 10);
```
##### .domElement(value)
Returns `true` if `value` is a DOM Element.
##### .infinite(value)
Check if `value` is `Infinity` or `-Infinity`.
##### .empty(value)
Returns `true` if `value` is falsy or an empty string, array, object, map, or set.

25
test.js
View file

@ -1,5 +1,6 @@
import util from 'util';
import test from 'ava';
import {jsdom} from 'jsdom';
import m from '.';
const isNode8orHigher = Number(process.versions.node.split('.')[0]) >= 8;
@ -7,6 +8,9 @@ const isNode8orHigher = Number(process.versions.node.split('.')[0]) >= 8;
const PromiseSubclassFixture = class extends Promise {};
const ErrorSubclassFixture = class extends Error {};
const document = jsdom();
const createDomElement = el => document.createElement(el);
const types = new Map([
['undefined', undefined],
['null', null],
@ -90,6 +94,22 @@ const types = new Map([
new Object() // eslint-disable-line no-new-object
]],
['integer', 6],
['domElement', [
'div',
'input',
'span',
'img',
'canvas',
'script'
].map(createDomElement)],
['non-domElements', [
document.createTextNode('data'),
document.createProcessingInstruction('xml-stylesheet', 'href="mycss.css" type="text/css"'),
document.createComment('This is a comment'),
document,
document.implementation.createDocumentType('svg:svg', '-//W3C//DTD SVG 1.1//EN', 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'),
document.createDocumentFragment()
]],
['infinite', [
Infinity,
-Infinity
@ -370,6 +390,11 @@ test('is.inRange', t => {
});
});
test('is.domElement', t => {
testType(t, 'domElement');
t.false(m.domElement({nodeType: 1, nodeName: 'div'}));
});
test('is.infinite', t => {
testType(t, 'infinite', ['number']);
});