Browse Source

- added createColumn that transforms input into a column

- added hasColumn that checks if there is already a column with a certain name
- use hasColumn everywhere
auto-join
Sascha Depold 12 years ago
parent
commit
f3bc8d2790
  1. 30
      lib/table.js
  2. 2
      package.json
  3. 21
      test/table-tests.js

30
lib/table.js

@ -21,7 +21,7 @@ Table.define = function(config) {
return table;
};
Table.prototype.addColumn = function(col) {
Table.prototype.createColumn = function(col) {
if(!(col instanceof Column)) {
if(typeof col === 'string') {
col = { name: col };
@ -31,19 +31,39 @@ Table.prototype.addColumn = function(col) {
col = new Column(col);
}
if(this[col.name]) {
return col;
};
Table.prototype.addColumn = function(col) {
col = this.createColumn(col);
if(this.hasColumn(col)) {
throw new Error('Table ' + this._name + ' already has column or property by the name of ' + col.name);
} else if(!!this[col.name] && (process.env.NODE_ENV !== 'test')) {
console.log('Please notice that you have just defined the column "' + col.name + '". In order to access it, you need to use "table.getColumn(\'' + col.name + '\');"!');
}
this.columns.push(col);
this[col.name] = col;
this[col.name] = this[col.name] || col;
return this;
};
Table.prototype.hasColumn = function(col) {
col = this.createColumn(col);
var cols = this.columns.filter(function(column) {
return column.name === col.name;
});
return cols.length > 0;
};
Table.prototype.getColumn = function(colName) {
var col = this[colName];
if(!col) {
var col = this.createColumn(colName);
if(!this.hasColumn(col)) {
throw new Error('Table ' + this._name + ' does not have a column named ' + colName);
}
return col;
};

2
package.json

@ -10,7 +10,7 @@
},
"main": "lib/",
"scripts": {
"test": "./node_modules/.bin/mocha"
"test": "NODE_ENV=test ./node_modules/.bin/mocha"
},
"engines": {
"node": "*"

21
test/table-tests.js

@ -97,3 +97,24 @@ test('table with dynamic column definition', function() {
assert.equal(table.columns.length, 1);
});
test('hasColumn', function() {
var table = Table.define({ name: 'foo', columns: [] });
assert.equal(table.hasColumn('baz'), false);
table.addColumn('baz');
assert.equal(table.hasColumn('baz'), true);
});
test('the column "from" does not overwrite the from method', function() {
var table = Table.define({ name: 'foo', columns: [] });
table.addColumn('from');
assert.equal(typeof table.from, 'function');
});
test('getColumn returns the from column', function() {
var table = Table.define({ name: 'foo', columns: [] });
table.addColumn('from');
assert(table.getColumn('from') instanceof Column);
});

Loading…
Cancel
Save