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,342
  • 6
  • 42
  • 70
  • @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

3 Answers3

3

The common pattern is using the || operator:

self.columnMap[internalTableName] = self.columnMap[internalTableName] || {};
self.columnMap[internalTableName][internalColumnName] = logicalColumnName;
epascarello
  • 204,599
  • 20
  • 195
  • 236
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
  • 630,263
  • 148
  • 957
  • 1,375
0

Starting with JS version ES2020 you can use a nullish coalescing assignment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_assignment

const a = { duration: 50 };

a.duration ??= 10;
console.log(a.duration);
// Expected output: 50

a.speed ??= 25;
console.log(a.speed);
// Expected output: 25
teh.fonsi
  • 3,040
  • 2
  • 27
  • 22