Commit 5d3af8bd authored by Tristan Cavelier's avatar Tristan Cavelier

WIP: Great changes on complex queries

Change to a module compatible with nodejs, requirejs, web workers and classic
browsers. Provides classes Query, SimpleQuery, ComplexQuery. Documentation
comming soon.
parent 1c0444c6
......@@ -4,11 +4,27 @@
* http://www.gnu.org/licenses/lgpl.html
*/
(function (scope) {
/**
* Provides some function to use complex queries with item list
*
* @module complex_queries
*/
var complex_queries;
(function () {
"use strict";
Object.defineProperty(scope, "ComplexQueries", {
configurable: false,
enumerable: false,
writable: false,
value: {}
var to_export = {}, module_name = "complex_queries";
/**
* Add a secured (write permission denied) property to an object.
* @method defineProperty
* @param {Object} object The object to fill
* @param {String} key The object key where to store the property
* @param {Any} value The value to store
*/
function _export(key, value) {
Object.defineProperty(to_export, key, {
"configurable": false,
"enumerable": true,
"writable": false,
"value": value
});
}
// XXX
var ComplexQuery = newClass(Query, function () {
/**
* Filter the item list only if all the sub queries match this item according
* to the logical operator.
* See {{#crossLink "Query/exec:method"}}{{/crossLink}}
*/
this.exec = function () {
todo
};
});
todo
query_class_dict.complex = ComplexQuery;
_export("ComplexQuery", ComplexQuery);
}(jIO));
if (typeof define === "function" && define.amd) {
define(to_export);
} else if (typeof window === "object") {
Object.defineProperty(window, module_name, {
configurable: false,
enumerable: true,
writable: false,
value: to_export
});
} else if (typeof exports === "object") {
var i;
for (i in to_export) {
if (to_export.hasOwnProperty(i)) {
exports[i] = to_export[i];
}
}
} else {
complex_queries = to_export;
}
}());
Object.defineProperty(scope.ComplexQueries, "parse", {
configurable: false,
enumerable: false,
writable: false,
value: function (string) {
/**
* Parse a text request to a json query tree
* @method parseStringToObject
* @param {String} string The string to parse
* @return {Object} The json query tree
*/
function parseStringToObject(string) {
return result;
}
}
});
}; // parseStringToQuery
Object.defineProperty(scope.ComplexQueries,"query",{
configurable:false,enumerable:false,writable:false,
value: function (query, object_list) {
var wildcard_character = typeof query.wildcard_character === 'string' ?
query.wildcard_character : '%',
/**
* The query to use to filter a list of objects.
* This is an abstract class.
*
* @class Query
* @constructor
*/
var Query = newClass(function() {
/**
* Creates a new item list with matching item only
*
* @method exec
* @param {Array} item_list The list of object
* @param {Object} [option={}] Some operation option
* @param {String} [option.wildcard_character="%"] The wildcard character
* @return {Array} The new item list
*/
this.exec = function (item_list, option) {};
/**
* Test if an item matches this query
* @method match
* @param {Object} item The object to test
* @return {Boolean} true if match, false otherwise
*/
this.match = function (item, wildcard_character) {};
/**
* Convert this query to a parsable string.
* @method toString
* @return {String} The string version of this query
*/
this.toString = function () {};
/**
* Convert this query to an jsonable object in order to be remake thanks to
* QueryFactory class.
*
* @method serialized
* @return {Object} The jsonable object
*/
this.serialized = function () {};
}, {"static_methods": {
// XXX
"filterListSelect": function (select_option, list) {
list.forEach(function (item, index) {
var new_item = {};
select_option.forEach(function (key) {
new_item[key] = item[key];
});
list[index] = new_item;
});
},
// XXX
"sortOn": function (sort_on_option, list) {
var sort_index;
for (sort_index = sort_on_option.length - 1; sort_index >= 0;
sort_index += 1) {
list.sort(sortFunction(
sort_on_option[sort_index][0],
sort_on_option[sort_index][1]
));
}
},
"parseStringToQuery": parseStringToQuery
}});
_export("Query", Query);
function query(query, object_list) {
var wildcard_character = typeof query.wildcard_character === "string" ?
query.wildcard_character : "%",
// A list of methods according to operators
operator_actions = {
'=': function (value1, value2) {
value1 = '' + value1;
return value1.match (convertToRegexp (
"=": function (value1, value2) {
value1 = value1.toString();
return value1.match(convertToRegexp(
value2, wildcard_character
)) || false && true;
},
'!=': function (value1, value2) {
value1 = '' + value1;
return !(value1.match (convertToRegexp (
value1 = value1.toString();
return !(value1.match(convertToRegexp(
value2, wildcard_character
)));
},
......@@ -46,11 +116,11 @@ Object.defineProperty(scope.ComplexQueries,"query",{
return subString('^' + string.replace(
new RegExp(
'([\\{\\}\\(\\)\\^\\$\\&\\.\\*\\?\\\/\\+\\|\\[\\]\\-\\\\])'.
replace (wildcard_character?
'\\'+wildcard_character:undefined,''),
'g'
replace(wildcard_character ?
"\\" + wildcard_character : undefined, ""),
"g"
),
'\\$1'
"\\$1"
) + '$',(wildcard_character||undefined), '.*');
},
subString = function (string, substring, newsubstring) {
......@@ -58,18 +128,18 @@ Object.defineProperty(scope.ComplexQueries,"query",{
if (substring === undefined) {
return string;
}
while (1) {
var tmp = string.indexOf(substring,i);
while (true) {
var tmp = string.indexOf(substring, i);
if (tmp === -1) {
break;
}
for (; i < tmp; ++i) {
for (; i < tmp; i += 1) {
res += string[i];
}
res += newsubstring;
i += substring.length;
}
for (; i<string.length; ++i) {
for (; i < string.length; i += 1) {
res += string[i];
}
return res;
......@@ -182,5 +252,4 @@ Object.defineProperty(scope.ComplexQueries,"query",{
limit(result_list,query.filter.limit || []);
}
return result_list;
}
});
}
/*jslint indent: 2, maxlen: 80, sloppy: true, nomen: true */
/*global _export: true, ComplexQuery: true, SimpleQuery: true,
newClass: true,
sortFunction: true, convertSearchTextToRegExp: true */
// XXX
var query_class_dict = {}, query_factory = {};
newClass.apply(query_factory, [{
"secure_methods": true
}, function () {
// XXX
this.create = function (object) {
if (typeof object.type === "string" &&
query_class_dict[object.type]) {
return new query_class_dict[object.type](object);
}
return null;
};
}]); // end QueryFactory
_export("factory", query_factory);
Object.defineProperty(scope.ComplexQueries,"serialize",{
configurable:false,enumerable:false,writable:false,value:function(query){
var str_list = [], i;
if (query.type === 'complex') {
str_list.push ( '(' );
for (i=0; i<query.query_list.length; ++i) {
str_list.push( scope.ComplexQueries.serialize(query.query_list[i]) );
str_list.push( query.operator );
/*jslint indent: 2, maxlen: 80, sloppy: true, nomen: true */
/*global _export: true, to_export: true */
function objectToSearchText(query) {
var str_list = [];
if (query.type === "complex") {
str_list.push("(");
(query.query_list || []).forEach(function (sub_query) {
str_list.push(objectToSearchText(sub_query));
str_list.push(query.operator);
});
str_list.length -= 1;
str_list.push(")");
return str_list.join(" ");
}
str_list.length --;
str_list.push ( ')' );
return str_list.join(' ');
} else if (query.type === 'simple') {
return query.id + (query.id?': ':'') + query.operator + ' "' + query.value + '"';
if (query.type === "simple") {
return query.id + (query.id ? ": " : "") + (query.operator || "=") + ' "' +
query.value + '"';
}
return query;
}
});
throw new TypeError("This object is not a query");
}
_export("objectToSearchText", objectToSearchText);
/**
* The SimpleQuery inherits from Query, and compares one metadata value
*
* @class SimpleQuery
* @param {Object} [spec={}] The specifications
* @param {String} [spec.operator="="] The compare method to use
* @param {String} spec.key The metadata key
* @param {String} spec.value The value of the metadata to compare
* @param {String} [spec.wildcard_character="%"] The wildcard character
*/
var SimpleQuery = newClass(Query, function (spec) {
/**
* Operator to use to compare object values
*
* @property operator
* @type String
* @default "="
*/
this.operator = spec.operator || "=";
/**
* Key of the object which refers to the value to compare
*
* @property key
* @type String
*/
this.key = spec.key;
/**
* Value is used to do the comparison with the object value
*
* @property value
* @type String
*/
this.value = spec.value;
/**
* The wildcard character used to extend comparison action
*
* @property wildcard_character
* @type String
*/
this.wildcard_character = spec.wildcard_character || "%";
/**
* #crossLink "Query/exec:method"
*/
this.exec = function (item_list, option) {
var new_item_list = [];
item_list.forEach(function (item) {
if (!this.match(item, option.wildcard_character)) {
new_item_list.push(item);
}
});
if (option.sort_on) {
Query.sortOn(option.sort_on, new_item_list);
}
if (option.limit) {
new_item_list = new_item_list.slice(
option.limit[0],
option.limit[1] + option.limit[0] + 1
);
}
if (option.select_list) {
Query.filterListSelect(option.select_list, new_item_list);
}
return new_item_list;
};
/**
* #crossLink "Query/match:method"
*/
this.match = function (item, wildcard_character) {
this[this.operator](item[this.key], this.value, wildcard_character);
};
/**
* #crossLink "Query/toString:method"
*/
this.toString = function () {
return (this.key ? this.key + ": " : "") + (this.operator || "=") + ' "' +
this.value + '"';
};
/**
* #crossLink "Query/serialized:method"
*/
this.serialized = function () {
return {
"type": "simple",
"operator": this.operator,
"key": this.key,
"value": this.value
};
};
// XXX
this["="] = function (object_value, comparison_value,
wildcard_character) {
return convertSearchTextToRegExp(
comparison_value.toString(),
wildcard_character || this.wildcard_character
).test(object_value.toString());
};
// XXX
this["!="] = function (object_value, comparison_value,
wildcard_character) {
return !convertSearchTextToRegExp(
comparison_value.toString(),
wildcard_character || this.wildcard_character
).test(object_value.toString());
};
// XXX
this["<"] = function (object_value, comparison_value) {
return object_value < comparison_value;
};
// XXX
this["<="] = function (object_value, comparison_value) {
return object_value <= comparison_value;
};
// XXX
this[">"] = function (object_value, comparison_value) {
return object_value > comparison_value;
};
// XXX
this[">="] = function (object_value, comparison_value) {
return object_value >= comparison_value;
};
});
query_class_dict.simple = SimpleQuery;
_export("SimpleQuery", SimpleQuery);
/*jslint indent: 2, maxlen: 80, sloppy: true, nomen: true */
/*global _export: true */
#!/usr/bin/env node
// keywords: js, javascript, new class creator, generator
/**
* Create a class, manage inheritance, static methods,
* protected attributes and can hide methods or/and secure methods
*
* @method newClass
* @param {Class} Class Classes to inherit from (0..n)
* @param {Object} option Class option (0..n)
* @param {Boolean} [option.secure_methods=false] Make methods not configurable
* and not writable
* @param {Boolean} [option.hide_methods=false] Make methods not enumerable
* @param {Object} [option.static_methods={}] Add static methods
* @param {Function} constructor The new class constructor
* @return {Class} The new class
*/
function newClass() {
var j, k, constructors = [], option, new_class;
for (j = 0; j < arguments.length; j += 1) {
if (typeof arguments[j] === "function") {
constructors.push(arguments[j]);
} else if (typeof arguments[j] === "object") {
option = option || {};
for (k in arguments[j]) {
if (arguments[j].hasOwnProperty(k)) {
option[j] = arguments[j][k];
}
}
}
}
function postCreate(that) {
// modify the object according to 'option'
var key;
if (option) {
for (key in that) {
if (that.hasOwnProperty(key)) {
if (typeof that[key] === "function") {
Object.defineProperty(that, key, {
configurable: option.secure_methods ? false : true,
enumerable: option.hide_methods ? false : true,
writable: option.secure_methods ? false : true,
value: that[key]
});
}
}
}
}
}
new_class = function (spec, my) {
var i;
spec = spec || {};
my = my || {};
// don't use forEach !
for (i = 0; i < constructors.length; i += 1) {
constructors[i].apply(this, [spec, my]);
}
postCreate(this);
return this;
};
for (j in (option.static_methods || {})) {
if (option.static_methods.hasOwnProperty(j)) {
new_class[j] = option.static_methods[j];
}
}
postCreate(new_class);
return new_class;
}
/**
* Escapes regexp special chars from a string.
* @method regexpEscapeString
* @param {String} string The string to escape
* @return {String} The escaped string
*/
function regexpEscapeString(string) {
if (typeof string === "string") {
return string.replace(/([\\\.\$\[\]\(\)\{\}\^\?\*\+\-])/g, "\\$1");
}
}
_export("regexpEscapeString", regexpEscapeString);
/**
* Convert a search text to a regexp.
* @method convertSearchTextToRegExp
* @param {String} string The string to convert
* @param {String} [wildcard_character=undefined] The wildcard chararter
* @return {RegExp} The search text regexp
*/
function convertSearchTextToRegExp(string, wildcard_character) {
return new RegExp("^" + regexpEscapeString(string).replace(
regexpEscapeString(wildcard_character),
'.*'
) + "$");
}
_export("convertSearchTextToRegExp", convertSearchTextToRegExp);
// XXX
function sortFunction(key, way) {
if (way === 'descending') {
return function (a,b) {
return a[key] < b[key] ? 1 : a[key] > b[key] ? -1 : 0;
};
}
return function (a,b) {
return a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0;
};
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment