filter-value
Version:
Data engine is small data management lib for some sort and filter.
495 lines (429 loc) • 13 kB
JavaScript
/** @license Engine v3.1.1
* filter-value.development.js
*
* Copyright Jan Silhan
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
;
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.FilterValue = factory());
}(this, (function () { 'use strict';
/* eslint-disable */
function warnFunction() {
var _console2;
(_console2 = console).warn.apply(_console2, arguments);
}
function errorFunction() {
var _console3;
var _ref = new Error(),
stack = _ref.stack;
(_console3 = console).error.apply(_console3, [stack, '\n'].concat(Array.prototype.slice.call(arguments)));
}
function noop() {}
var warn = noop;
var error = noop;
{
error = errorFunction;
warn = warnFunction;
}
var basicCompare = function (item) {
return function (toCompare) {
return item === toCompare;
};
};
var dateCompare = function (item) {
return function (toCompare) {
var compareDate = toCompare;
if (!toCompare.getTime) {
compareDate = new Date(toCompare);
}
return item.getTime() === compareDate.getTime();
};
};
var arrayCompare = function (item) {
return function (toCompare) {
return item.some(function (itm) {
return itm.compare(toCompare);
});
};
};
var regexpCompare = function (item) {
return function (toCompare) {
return item.test("" + toCompare);
};
};
var funcCompare = function (item) {
return function (toCompare) {
return item(toCompare);
};
};
function isBetween(fromRange, toRange, toCompare) {
if (fromRange && toRange) return fromRange <= toCompare && toRange >= toCompare;
if (fromRange) return fromRange <= toCompare;
return toRange >= toCompare;
}
function isTimeBetween(fromRange, toRange, toCompare) {
var compareDate = toCompare;
if (!toCompare.getTime) {
compareDate = new Date(toCompare);
}
if (fromRange && toRange) {
return fromRange.getTime() <= compareDate.getTime() && toRange.getTime() >= compareDate.getTime();
}
if (fromRange) return fromRange.getTime() <= compareDate.getTime();
return toRange.getTime() >= compareDate.getTime();
}
/**
* Compares range
*
* @param {any} toCompare item which will be compared
* @memberOf FilterValue
*/
var rangeCompare = function (item) {
var type = item.from ? typeof item.from : typeof item.to;
if (type !== 'object') return function (toCompare) {
return isBetween(item.from, item.to, toCompare);
};
return function (toCompare) {
return isTimeBetween(item.from, item.to, toCompare);
};
};
var booleanRetype = function (item) {
return !!item;
};
var stringRetype = function (item) {
return "" + item;
};
// eslint-disable-next-line
/**
* Try to retype to number
*
* @param {any} item which should be retyped
* @return {number} retyped number
* @memberOf FilterValue
*/
var numberRetype = function (item) {
return parseFloat(item);
};
var specials = ['-', '[', ']', '/', '{', '}', '(', ')', '*', '+', '?', '.', '\\', '^', '$', '|'];
var regex = RegExp('[' + specials.join('\\') + ']', 'g');
/**
* Replacing unwanted characters with \
*
* @param {string} string string which you want to escape
* @returns {string} escaped values
*/
function regexEscape(string) {
return string.replace(regex, '\\$&');
}
var regexpRetype = function (item) {
return new RegExp(regexEscape('' + item), 'i');
};
var dateRetype = function (item) {
try {
var date = new Date(item);
if (!isNaN(date.getTime())) return date;
throw new TypeError(item + ' does not have format to parse with native function!');
} catch (e) {
error(item + ' does not have format to parse with native function!');
throw e;
}
};
var number = 'number';
var string = 'string';
var boolean = 'boolean';
var fce = 'function';
var regexp = 'regexp';
var date = 'date';
var staticTypes = [number, string, boolean, regexp, date];
var primitiveTypes = {
number: number,
string: string,
boolean: boolean,
'function': fce
};
/**
* Basic types of testable items.
* Enum for data types
*/
var types = {
boolean: basicCompare,
string: basicCompare,
number: basicCompare,
'null': basicCompare,
date: dateCompare,
array: arrayCompare,
regexp: regexpCompare,
'function': funcCompare,
range: rangeCompare
};
var retype = {
number: numberRetype,
string: stringRetype,
boolean: booleanRetype,
regexp: regexpRetype,
date: dateRetype
};
/**
* Checking for primitive types detectable with typeof
*
*
* @returns {string|null} name of primitive type or null
* @memberOf FilterValue
*/
var checkPrimitiveType = function (item) {
return primitiveTypes[typeof item] || null;
};
/**
* checkBasicTypes checking basic types
*
* @param {any} item
* @return {string/null} name of type if exist
* @memberOf FilterValue
*/
var checkRangeAbleTypes = function (item) {
switch (typeof item) {
case 'string':
return 'string';
case 'number':
return 'number';
case 'object':
if (item instanceof Date) {
return 'date';
}
return null;
default:
return null;
}
};
/**
* Validation if possible to static type item
* @param {any} item
* @return {boolean} true when it's possible to retype
* @memberOf FilterValue
*/
var validStaticType = function (item) {
return staticTypes.some(function (key) {
return key === item;
});
};
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// eslint-disable-next-line
// import { types, retype } from './constants/types';
var FilterValue = function () {
/**
* Creates an instance of FilterValue.
* string, number, regexp, function, array of items mentioned before
*
* @param {string} name - name of filter
* @param {any} item - value
* @param {string} type - type of item
* @memberOf FilterValue
*/
function FilterValue() {
var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var item = arguments[1];
var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
_classCallCheck(this, FilterValue);
_initialiseProps.call(this);
this.originalItem = null;
this.Name = name;
if (type !== null) {
this.Type = type;
}
if (item !== undefined) {
this.Value = item;
}
}
/**
* Preparing item for right validation.
* @private
* @param {any} item - filter value!
*
* @return {Array/any} right element.
* @memberOf FilterValue
*/
FilterValue.prototype.prepareItem = function prepareItem(item) {
switch (this.type) {
case 'array':
if (Array.isArray(item[item.length - 1])) {
error('Multi dimensional array is not supported!');
throw new TypeError('Multi dimensional array is not supported!');
}
return item.map(function (value) {
return new FilterValue(item.Name, value);
});
default:
return item;
}
};
/**
* Setter for name
*
* @param {string} name new name
* @memberOf FilterValue
*/
_createClass(FilterValue, [{
key: 'Name',
set: function (name) {
if (typeof name === 'string') {
this.name = name;
}
}
/**
* Getter for name
*
* @readonly
* @return {string} name
* @memberOf FilterValue
*/
,
get: function () {
return this.name;
}
/**
* Setter for type
*
* @param {string} type new static type
*
* @memberOf FilterValue
*/
}, {
key: 'Type',
set: function (type) {
if (validStaticType(type)) {
this.staticType = type;
return;
}
this.staticType = null;
throw new TypeError(type + ' is not supported. Cannot set static type');
}
/**
* Getter for type
*
* @returns {string} Static type
* @memberOf FilterValue
*/
,
get: function () {
return this.staticType;
}
/**
* getter for internal type
* @private
* @returns {string} type
*/
}, {
key: 'InternalType',
get: function () {
return this.type;
}
/**
* Remove static Type
*
* @memberOf FilterValue
*/
}, {
key: 'Value',
/** Setter for new value
* Update filter value
*
* @param {any} item new item
* @memberOf FilterValue
*/
set: function (item) {
this.originalItem = item;
var newItem = item;
if (this.staticType) {
try {
newItem = retype[this.staticType](item);
} catch (e) {
error(e);
throw new TypeError(item + ' cannot by typed to ' + this.staticType);
}
}
this.type = this.checkValidity(newItem);
if (this.type) {
this.item = this.prepareItem(newItem);
this.compareFunc = types[this.type](this.item);
} else {
warn('Possible types are Date, string, RegExp, number, function, Array<string, RegExp, number, null, function>. Array can have mixed values.');
throw new TypeError(item + ' is not supported. Use custom function!');
}
}
/**
* Getter for original value
* @returns {any} original item
*/
,
get: function () {
return this.item;
}
/**
* Getter for original value passed to setter
* @returns {any} value set by user
*/
}, {
key: 'original',
get: function () {
return this.originalItem;
}
/**
* Applying filter to item which will return true/false. True when it should be ignored.
* @private
* @param {any} toCompare - item which will be compared.
* @memberOf FilterValue
*/
/**
* Checking validity of supported types
* valid types are
* null, string, number, regexp, function, array of items mentioned before!
* @private
* @param {any} item
* @return {string|null} return type or null
* @memberOf FilterValue
*/
}]);
return FilterValue;
}();
FilterValue.regexpEscape = regexEscape;
var _initialiseProps = function () {
var _this = this;
this.staticType = null;
this.removeType = function () {
_this.staticType = null;
};
this.compare = function (toCompare) {
return _this.compareFunc(toCompare);
};
this.checkValidity = function (item) {
var type = checkPrimitiveType(item);
if (type) {
return type;
}
if (item === null) {
return 'null';
} else if (Array.isArray(item)) {
return 'array';
} else if (item instanceof RegExp) {
return 'regexp';
} else if (item instanceof Date) {
return 'date';
} else if ((item.from || item.to) && (checkRangeAbleTypes(item.from) || checkRangeAbleTypes(item.to))) {
return 'range';
}
return null;
};
};
var filterValue = Object.freeze({
default: FilterValue
});
var FilterValue$2 = ( filterValue && FilterValue ) || filterValue;
var filterValue$1 = FilterValue$2['default'] ? FilterValue$2['default'] : FilterValue$2;
return filterValue$1;
})));