UNPKG

itemsjs

Version:

Created to perform fast search on small json dataset (up to 1000 elements).

105 lines (84 loc) 2.44 kB
"use strict"; var _ = require('./../vendor/lodash'); var helpers = require('./helpers'); var FastBitSet = require('fastbitset'); /** * responsible for making faceted search */ var Facets = function Facets(items, config) { var _this = this; config = config || {}; this.items = items; this.config = config; this.facets = helpers.index(items, _.keys(config)); this._items_map = {}; this._ids = []; var i = 1; _.map(items, function (item) { _this._ids.push(i); _this._items_map[i] = item; item._id = i; ++i; }); this.ids_map = {}; if (items) { items.forEach(function (v) { if (v.id && v._id) { _this.ids_map[v.id] = v._id; } }); } this._bits_ids = new FastBitSet(this._ids); }; Facets.prototype = { items: function items() { return this.items; }, bits_ids: function bits_ids(ids) { if (ids) { return new FastBitSet(ids); } return this._bits_ids; }, internal_ids_from_ids_map: function internal_ids_from_ids_map(ids) { var _this2 = this; return ids.map(function (v) { return _this2.ids_map[v]; }); }, index: function index() { return this.facets; }, get_item: function get_item(_id) { return this._items_map[_id]; }, /* * * ids is optional only when there is query */ search: function search(input, data) { var config = this.config; data = data || {}; // consider removing clone var temp_facet = _.clone(this.facets); temp_facet.not_ids = helpers.facets_ids(temp_facet['bits_data'], input.not_filters, config); var filters = helpers.input_to_facet_filters(input, config); var temp_data = helpers.matrix(this.facets, filters); temp_facet['bits_data_temp'] = temp_data['bits_data_temp']; _.mapValues(temp_facet['bits_data_temp'], function (values, key) { _.mapValues(temp_facet['bits_data_temp'][key], function (facet_indexes, key2) { if (data.query_ids) { temp_facet['bits_data_temp'][key][key2] = data.query_ids.new_intersection(temp_facet['bits_data_temp'][key][key2]); } if (data.test) { temp_facet['data'][key][key2] = temp_facet['bits_data_temp'][key][key2].array(); } }); }); /** * calculating ids */ temp_facet.ids = helpers.facets_ids(temp_facet['bits_data_temp'], input.filters, config); return temp_facet; } }; module.exports = Facets;