const getType = v =>
(v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name);
getType(new Set([1, 2, 3])); // 'Set'
const isUndefined = val => val === undefined;
isUndefined(undefined); // true
const isNil = val => val === undefined || val === null;
isNil(null); // true
isNil(undefined); // true
isNil(''); // false
const isNull = val => val === null;
isNull(null); // true
const isSymbol = val => typeof val === 'symbol';
isSymbol(Symbol('x')); // true
const randomBoolean = () => Math.random() >= 0.5;
randomBoolean(); // true
const isBoolean = val => typeof val === 'boolean';
isBoolean(null); // false
isBoolean(false); // true
const isPlainObject = val =>
!!val && typeof val === 'object' && val.constructor === Object;
isPlainObject({ a: 1 }); // true
isPlainObject(new Map()); // false
const isObjectLike = val => val !== null && typeof val === 'object';
isObjectLike({}); // true
isObjectLike([1, 2, 3]); // true
isObjectLike(x => x); // false
isObjectLike(null); // false
const isObject = obj => obj === Object(obj);
isObject([1, 2, 3, 4]); // true
isObject([]); // true
isObject(['Hello!']); // true
isObject({ a: 1 }); // true
isObject({}); // true
isObject(true); // false
const mask = (cc, num = 4, mask = '*') =>
`${cc}`.slice(-num).padStart(`${cc}`.length, mask);
mask(1234567890); // '******7890'
mask(1234567890, 3); // '*******890'
mask(1234567890, -4, '$'); // '$$$$567890'
const is = (type, val) => ![, null].includes(val) && val.constructor === type;
is(Array, [1]); // true
is(ArrayBuffer, new ArrayBuffer()); // true
is(Map, new Map()); // true
is(RegExp, /./g); // true
is(Set, new Set()); // true
is(WeakMap, new WeakMap()); // true
is(WeakSet, new WeakSet()); // true
is(String, ''); // true
is(String, new String('')); // true
is(Number, 1); // true
is(Number, new Number(1)); // true
is(Boolean, true); // true
is(Boolean, new Boolean(true)); // true
const isStream = val =>
val !== null && typeof val === 'object' && typeof val.pipe === 'function';
const fs = require('fs');
isStream(fs.createReadStream('test.txt')); // true
class PrimitiveNumber {
static [Symbol.hasInstance] = x => typeof x === 'number';
}
123 instanceof PrimitiveNumber; // true
class PrimitiveString {
static [Symbol.hasInstance] = x => typeof x === 'string';
}
'abc' instanceof PrimitiveString; // true
class PrimitiveBoolean {
static [Symbol.hasInstance] = x => typeof x === 'boolean';
}
false instanceof PrimitiveBoolean; // true
class PrimitiveSymbol {
static [Symbol.hasInstance] = x => typeof x === 'symbol';
}
Symbol.iterator instanceof PrimitiveSymbol; // true
class PrimitiveNull {
static [Symbol.hasInstance] = x => x === null;
}
null instanceof PrimitiveNull; // true
class PrimitiveUndefined {
static [Symbol.hasInstance] = x => x === undefined;
}
undefined instanceof PrimitiveUndefined; // true
JavaScriptВычисления
JavaScript