maxisme75
maxisme75

Reputation: 137

Why do the author use a tilde before file?

I'm learning node and express programming and find a very good example at: https://github.com/madhums/node-express-mongoose-demo

But I find a line and not fully understand.

// Bootstrap models
var models_path = __dirname + '/app/models';
fs.readdirSync(models_path).forEach(function (file) {
    if (~file.indexOf('.js')) require(models_path + '/' + file)
})

On the 4th line before file, there is a tilde( ~ )operator. I consult the javascript book, and it just says it's a bitwise NOT.

Why author use tilde here? If not using tilde, can I have other way to express the same thing?

Thank you!

Upvotes: 2

Views: 484

Answers (2)

Nikolay Lukyanchuk
Nikolay Lukyanchuk

Reputation: 874

This statement help include only .js files into project. We can replace this statment with, this expression

 if (file.indexOf('.js') !== -1) require(models_path + '/' + file)

for your example https://github.com/madhums/node-express-mongoose-demo let's see we have 2 files into /app/models/ : article.js and user.js

for acticle.js

if (~('acticle.js'.indexOf('.js'))) // -8 TRUE
if ('acticle.js'.indexOf('.js')) // 7   TRUE

for user.js

if (~('user.js'.indexOf('.js'))) // -5 TRUE
if ('user.js'.indexOf('.js')) // 4   TRUE

And in our case this values is equieal to TRUE, and this files will be included.

this statment ~file.indexOf('.js') solve problem when we have file without name like '.js'

if ('.js'.indexOf('.js')) // 0 FALSE but file exists and have .js extension
if (~('.js'.indexOf('.js'))) // -1 TRUE

As you can see. It will be included into project.

Upvotes: 1

micnic
micnic

Reputation: 11245

Tilde is the bitwise not operator. The .indexOf() method returns the index of the found match in a string (or in an array) or -1 if the substring was not found.

Because 0 == false tilde may be used to transform -1 in 0 and viceversa:

> ~1
-2
> ~0
-1
> ~-1
0

~file.indexOf('.js') is equivalent to file.indexOf('.js') === -1 or file.indexOf('.js') < 0. The last two examples are more clear to understand that the first one.

Upvotes: 3

Related Questions