Skip to content
danstocker edited this page May 26, 2011 · 2 revisions

This is a reference for jOrder 1.2.

jOrder observes the prototypal object model.

Terms

  • flat table: Array of JavaScript objects each containing every field of the table as a key-value pair.
  • row ID: Array index within a flat table.
  • renumbered array: Array that doesn't have gaps in its indices.
  • grouped index: Opposite of unique index.

jOrder.table (data, options)

Version: 1.0

The table class represents a data table on which you can define indexes, perform search, sorting, aggregation and modifications while maintaining data integrity and maximum performance.

jOrder, invoked as a function returns a new jOrder.table object. Hence var table = jOrder.table(json) is equivalent to var table = jOrder(json).

  • json: Flat table that serves as the basis of the jOrder data table.
  • options:
    • renumber: Re-numbers row IDs. When set to true, row IDs in the resulting table will be re-numbered from 0, eliminating any 'holes' that may be in the indices of json. Default: false.

Example:

var json = [{ a: "foo", b: 1 }, { a: "bar", b: 2 }];
var table = jOrder.table(json);

Data manipulation

.index (name, fields, options)

Version: 1.0

When no parameters are specified, rebuilds all indexes on the table. When only name is specified, returns the index by that name. When fields is specified, then adds an index to the table by the given name, fields and options.

  • name: Name of the index. Must be unique. If there's an index on the table by the same name, it will be overwritten.

For the rest of the parameters, refer to the class jOrder.index.

table.index(), when used for adding index (i.e. both name and fields parameters are specified), returns a reference to the table object, allowing you to chain index additions to the same table.

Example:

table
    .index('name', ['a'], { ordered: true })
    .index('total', ['b'], { ordered: true, type: jOrder.number });

.reindex ()

Version: 1.0

Rebuilds all indexes on the table.

Returns reference to the table object.

.update (before, after, options)

Version: 1.0

Updates a row in the table.

Returns reference to the table object.

  • before: Current state of the row. The row is identified by the first index on the table, so this value must at least specify all the fields involved in that index. Also the first index is advised to be unique, otherwise the first row ID fitting the given values will be used. In case this parameter is null, the value specified in after will be inserted.
  • after: Full row after update. Must contain at least all the fields involved in all indexes on the table, otherwise updating the indexes will fail. In case this value is null or not specified the row specified in before will be deleted.
  • options: Version: 1.0.0.8
    • indexName: Name of index to use for identifying the row (s) to update. When none is specified, the first unique index is used. Default: none.

This before — after style update is necessary because you can update all unique fields, even the one(s) that serve as primary keys in the database. A more conventional style may be achieved using the following example.

var before = table.where([{ b: 'foo' }])[0];
var after = jOrder.deep(before);
after.b = 'fu';
table.update(before, after);

.insert (rows, options)

Version: 1.0

Inserts the specified rows into the table. Equivalent to calling .update(null, row) on each row in rows.

Returns reference to the table object.

  • rows: Array of rows to be inserted into the table.
  • options: Version: 1.0.0.8. See the options parameter of table.update().

.remove (rows, options)

Version: 1.0

Removes the specified rows from the table. Equivalent to calling .update(row, null) on each row in rows.

Returns reference to the table object.

  • rows: Array of rows to be removed from the table.
  • options: Version: 1.0.0.8. See the options parameter of table.update().

.clear ()

Version: 1.0

Resets table contents to the originally submitted data, and clears all indexes.

Returns reference to the table object.

Querying

.select (rowIds, options)

Version: 1.0

Selects the specified row IDs from the table and returns them as a new array, with the row IDs optionally renumbered.

  • rowIds: Row IDs (array index) to select from the tables.
  • options:
    • renumber: Whether or not to preserve row IDs (array indices) in the resulting set. Default: false.

.where (conditions, options)

Version: 1.0

Selects rows matching the conditions, optionally using a specific index.

Returns array of objects.

  • conditions: An array of objects defining the search conditions. Individual conditions are in OR relation with each other. Ideally each condition specifies all field values required by an existing index. E.g. this condition returns all rows where the field 'a' equals to either "foo" or "bar" [{ a: 'foo' }, { a: 'bar' }].
  • options:
    • indexName: Name of the index to use. This parameter a) helps distinguishing between indexes built on the same field (s); and b) results in faster search (not as big a difference as say, between using and not using an index at all).
    • renumber: Whether or not to preserve row IDs (array indices) in the resulting set. Default: false.
    • mode: Search mode. See the available options below.
    • offset: Index of first element to return from the matched set
    • limit: Total number of elements to return

Search modes:

  • jOrder.exact: Looks for exact matches. This is the default mode. Finding exact matches is the fastest. Condition syntax: [{ field1: value1 }, { field1: value2 }].
  • jOrder.range: Matches rows where the value of the given field falls between certain values. Equivalent to SQL's BETWEEN. Only the first field of the first condition is used. Condition syntax: [{ field: { lower: value1, upper: value2 } }].
  • jOrder.startof: Uses start-of partial matching to find the rows with the specified string. Equivalent to LIKE 'sometext%' in SQL. Only the first field of the first condition is used. Condition syntax: [{ field: string }].

Both jOrder.range and jOrder.startof require an ordered index defined on the fields in question to perform optimally.

Options offset and limit take effect only in case of range and free text search.

Examples:

// exact
hits = table.where([{ a: 'foo' }, { a: 'bar' }], { indexName: 'name' });
// range
hits = table.where([{ b: { lower: 1, upper: 2 } }], { mode: jOrder.range });
// start-of partial
hits = table.where([{ a: 'fo' }], { mode: jOrder.startof });

Note: You may use .where() in all three modes without previously defining an index. This will, however, have a negative impact on performance especially with large tables.

.aggregate (indexName, initCallback, iterateCallback)

Version: 1.0

General aggregation. Offers a flexible way to implement user-defined aggregation, but it iterates over the entire table linearly and is thus slow.

Returns array of objects.

For counting rows by value, see index.count().

  • indexName: Name of the grouped index on which the aggregation is performed.
  • initCallback(initial): Callback function that initializes the aggregated row. Receives the first row in the current group and should return the initial row.
  • iterateCallback(aggregated, next): Callback function implementing one iteration of the aggregation process. Receives the aggregated row and the next row in the group. Should return the aggregated row with the values of the next row applied.

Example:

var summed = table.aggregate('total',
function(initial) {
    initial.b = 0;
    return initial;
},
function(aggregated, next) {
    aggregated += next.b;
    return aggregated;
});

.orderby (fields, dir, options)

Version: 1.0

Orders the table by the given field (s) in the given direction.

Returns array of objects.

  • fields: Array of field names that define the index by which to order. If the fields don't match any index, ordering fails.
  • direction: jOrder.asc or jOrder.desc. Default: jOrder.asc.
  • options:
    • indexName: Specific index name to use for ordering.
    • offset: Version: 1.0.0.12. Starting row index from which to return the ordered set. Default: 0.
    • limit: Version: 1.0.0.12. Number of rows to return. Default: 1, as in, only the first row is returned.

Known issue: dir = jOrder.desc won't work in pre 1.2 versions unless offset and limit are specified (0 and 1000 for instance). See index.order() for details

Example:

var ordered = table.orderby(['b'], jOrder.desc, { indexName: 'total', limit: 2 }); // [{ a: "bar", b: 2 }, { a: "foo", b: 1 }]

.filter (selector, options)

Version: 1.0

Filters the table using a user defined selector callback function.

Returns array of objects.

  • selector: Callback function that receives the next row and returns a true or false. The next row will be included in the result if the selector returns true. Iterates over the entire table and therefore issues a warning regardless of the contents of selector.
  • options:
    • renumber: Whether or not to preserve row IDs (array indices) in the resulting set. Default: false.
    • offset: Starting row index from which to return the ordered set. Default: 0.
    • limit: Number of rows to return. When not specified, .filter() returns all rows starting from offset. Default: none.

Example:

var filtered = table.filter(function(next) { return 'foo' == next.a; }); // [{ a: "foo", b: 1 }]

.count ()

Version: 1.0

Counts the rows in the table. If there's at least one index on the table it issues a call to the .count() method of the first available index. Otherwise iterates over the table and therefore issues a warning.

Returns integer.

In pre 1.2 versions table.count() doesn't rely on index.

Getters

.flat ()

Version: 1.0

Returns a reference to the raw data buffer.

Warning: You can change the data buffer through the return value of this method. Either make sure it is used as read only, or issue a .reindex() after modifying the raw data.

Example:

var json = table.flat(); // [{ a: "foo", b: 1 }, { a: "bar", b: 2 }]

.first ()

Version: 1.0

Returns the first row of the table. Always use .first() to get the first row, since .flat() may not have a 0th element. It is very likely that table.flat()[0] is undefined where table.first() returns a valid row.

.column (field, options)

Version: 1.0

Returns an array with the contents of a single column, optionally re-numbered.

  • field: Name of the field for which the column will be returned.
  • options:
    • renumber: Whether or not the original indices of the rows should be preserved.

.ordered (fields)

Version: 1.0

Tells if the index built on the specified fields is ordered.

Returns boolean.

  • fields: Array of field names identifying an index.

grouped (fields)

Version: 1.0

Tells if the index built on the specified fields is grouped (non-unique).

Returns boolean.

  • fields: Array of field names identifying an index.

jOrder.index (flat, fields, options)

Version 1.0

The index class represents a table index. Table indexes are normally used in the context of jOrder.table instances, but can be used in themselves for simple lookup and low-level sorting functionality.

  • flat: Flat table the index is built upon.
  • fields: An array of field names to include in the index. The order of fields determine the behavior of the index.
  • options: An object describing the behavior of the index.
    • grouped: Whether the index is grouped (non-unique). Grouped indexes allow for aggregation. Default: false.
    • ordered: Whether the index holds order information on the covered fields. When a table is ordered by fields that have no ordered index assigned, a warning is issued in the JS console. Default: false.
    • type: Data type of the index.
    • build: Version: 1.2. Whether to build the index on initialization.

Index types define the behavior of the index.

  • jOrder.string: Values compare as text (important on sorting), e.g. "a" is lower than "ab", "1" is lower than "1.0". Distinct data values map 1:1 to index keys. This is the default index type.
  • jOrder.number: Values compare as numbers. ("1" and "1.0" are equal.) Distinct data values map 1:1 to index keys.
  • jOrder.text: Values compare as text but each value is broken down into individual words that are used as index keys. Index methods such as .range() may return objects with repeated values. (Which, when fed to table.select() are united again.)

Example:

var index = jOrder.index(json, ['a'], { grouped: true, ordered: true });

Manipulation

.add (row, rowId, lazy)

Version: 1.0

Adds one entry to the index based on the row and row ID provided.

Returns reference to the index object.

  • row: Data row from a flat data table containing the field value that will be the key of the next entry.
  • rowId: Array index of row in the flat table. Serves as the value of the next index entry.
  • lazy: Determines how the new entry is added to the (ordered) index. Has no effect on unordered indexes. Possible values:
    • truthy: the order remains inconsistent after calls. Must issue a call to index.reorder() after adding the last entry, otherwise the order will be corrupt.
    • falsey: the order is updated and the index is consistent after each call.

.remove (row, rowId)

Version: 1.0

Removes an entry from the index.

Returns reference to the index object.

  • row: Data row from a flat data table containing the field value that will be the key of the entry to remove.
  • rowId: Array index of row in the flat table. Optional, used only in case of grouped (non-unique) indexes.

.rebuild (lazy)

Version: 1.0

Rebuilds the index.

Returns reference to the index object.

  • lazy: Version: 1.2. Concerns ordered indexes only.
    • thruthy: index will be consistent only when all entries have been added.
    • falsey: index remains consistent throughout the rebuild process.

.unbuild ()

Version: 1.2

Clears the index.

Returns reference to the index object.

.compact ()

Deprecated

Version 1.0

In post 1.2 versions, issues a warning.

In pre 1.2 versions, removes orphan entries from the order.

Querying

.lookup (rows)

Version 1.0

Looks up the IDs of the specified rows.

Returns an array of integers.

  • rows: Array of rows from the flat table.

Example:

var ids = table.index('name').lookup([{ a: 'foo' }]); // [0]

.bsearch (value, type)

Version: 1.0

Performs a binary search on an ordered index. Finishes in log (n) steps.

Returns integer.

  • value: The indexed value we are looking for.
  • type: Whether the value in question will serve as start or end of a range. When type is jOrder.start, and the exact value is not present in the index, .bsearch() returns the next fitting element in the ordered list. Otherwise it returns the previous one.

.range (bounds, options)

Version: 1.0

Returns a range of row IDs where indexed values fall between the specified bounds.

  • bounds:
    • lower: Lower bound
    • upper: Upper bound
  • options:
    • offset: Index of first element to return from the matched set. Default: 0.
    • limit: Total number of elements to return. Default: 1.

.count (key)

Version: 1.2

Counts values within the index.

Returns integer.

  • key: The index key to look up (string). Made up from the values of the index's fields. When omitted, .count() returns the total number of rows.

Example:

var count_all = table.index('total').count(); // 2
var count_1 = table.index('total').count(1); // 1

Getters

.signature (row, strict)

Version 1.0

Returns the signature of the index (string), or validates a row against it. A signature is the concatenation of field names separated with an underscore.

  • row: Row object to validate against index signature.
  • strict: Direction of validation.
    • thruthy: all fields in row must be present in the index
    • falsey: all fields in index must be present in row

Example:

var sig = jOrder.index(json, ['a', 'b']).signature(); // 'a_b'

.flat ()

Version: 1.0

Returns a reference to the raw data buffer.

Warning: You can change the data buffer through the return value of this method. Changing the contents from the outside will corrupt the index. Issuing .rebuild() restores the corrupted index.

Example:

var index_grouped = table.index('name').flat(); // { 'foo': [0], 'bar': [1] }
var index_unique = table.index('total').flat(); // { '1': 0, '2': 1 }

.order (dir, options)

Version: 1.0

Returns the order of the index if it's ordered (array of integers).

  • dir: jOrder.asc or jOrder.desc. Default: jOrder.asc.
  • options:
    • offset: Index of first element to return from the matched set. Default: 0.
    • limit: Total number of elements to return. Default: 0.

Warning: When you don't pass offset or limit the function returns a reference to the original buffer. Changing the contents from the outside will corrupt the order. Issuing .reorder() on the index restores the corrupted order.

Example:

var order = table.index('name').order(); // [ 'foo', 'name' ]

.grouped ()

Version: 1.0

Tells whether the index is grouped (non-unique).

Returns boolean.

.ordered ()

Version: 1.0

Tells whether the index is ordered.

Returns boolean.

Constants

Version: 1.0

Environmental

  • jOrder.version: Deprecated. Undefined.
  • jOrder.name: "jOrder"

Ordering

  • jOrder.asc: Ascending order in ordering functions
  • jOrder.desc: Descending order in ordering functions

Index types

  • jOrder.string: String index type
  • jOrder.number: Numeric index type
  • jOrder.text: Text index type (field values broken down to words in index)
  • jOrder.array: Version: 1.1.0.14. Array index type (array items separate entries in index)

Ranges

  • jOrder.start: First element in a range
  • jOrder.end: Last element in a range

Search modes

  • jOrder.exact: Exact search
  • jOrder.range: Range search
  • jOrder.startof: Start-of partial search