2

I'm trying to execute this piece of code in the most elegant way:

if (internalTableName in self.columnMap &&
    internalColumnName in self.columnMap[internalTableName]) {
    console.error('dupelicates');
}
else {
    try {
        self.columnMap[internalTableName][internalColumnName] = logicalColumnName;
    } catch (err) {
        self.columnMap[internalTableName] = {};
        self.columnMap[internalTableName][internalColumnName] = logicalColumnName;
    }
}

I could turn the try/catch block to:

if (internalTableName in self.columnMap &&
    internalColumnName in self.columnMap[internalTableName]) {
    console.error('dupelicates');
}
else {
    if (internalTableName in self.columnMap) {
        self.columnMap[internalTableName][internalColumnName] = logicalColumnName;
    }
    else {
        self.columnMap[internalTableName] = {};
        self.columnMap[internalTableName][internalColumnName] = logicalColumnName;

    }
}

I was wondering if Javascript offers some operators for checking nullity that could make this logic be written in a more elegant way and less IF clauses.

Thanks

johni
  • 5,034
  • 5
  • 38
  • 65
  • @torazaburo I don't think it's a dupe of that, as this question is about setting not about getting the deep property. And it needs a special case for already-existing properties. – Bergi Dec 22 '15 at 15:36

2 Answers2

3

The common pattern is using the || operator:

self.columnMap[internalTableName] = self.columnMap[internalTableName] || {};
self.columnMap[internalTableName][internalColumnName] = logicalColumnName;
epascarello
  • 195,511
  • 20
  • 184
  • 225
1

I think what you are looking for is

if (!(internalTableName in self.columnMap))
    self.columnMap[internalTableName] = {};
if (!(internalColumnName in self.columnMap[internalTableName]))
    self.columnMap[internalTableName][internalColumnName] = logicalColumnName;
else
    console.error('duplicates');

You could shorten it a bit with a helper variable and by checking for empty properties by simple falsyness:

var table = self.columnMap[internalTableName] || (self.columnMap[internalTableName] = {});
if (!table[internalColumnName])
    table[internalColumnName] = logicalColumnName;
else
    console.error('duplicates');
Bergi
  • 572,313
  • 128
  • 898
  • 1,281