diff --git a/lib/table.js b/lib/table.js index e6c6dee..4c25092 100644 --- a/lib/table.js +++ b/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; }; diff --git a/package.json b/package.json index 41b2c74..f7fe701 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ }, "main": "lib/", "scripts": { - "test": "./node_modules/.bin/mocha" + "test": "NODE_ENV=test ./node_modules/.bin/mocha" }, "engines": { "node": "*" diff --git a/test/table-tests.js b/test/table-tests.js index 575b960..e3f2ab5 100644 --- a/test/table-tests.js +++ b/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); +});