/ walking bear:D / A use case of Javascript tilde operator

A use case of Javascript tilde operator

2017-04-27 posted in [筆記]

用例 use case 前面應該用 ‘a’ 吧?! 在查看 socket.io socket.js 的 source code,看到幾個有趣的用例:

Socket.prototype.emit = function(ev){
  if (~exports.events.indexOf(ev)) {
    emit.apply(this, arguments);
  } else {
    var args = Array.prototype.slice.call(arguments);
    ...
  }
  ...
}

tilde ~ operator 在 C 語言的用法是 binary NOT,舉例來說:

~(00000001) = 11111110        // 原數值 1,經過 invertor 操作變成 -2
~(00001111) = 11110000        // 原數值 15,經過 invertor 操作變成 -16
~(10101010) = 01010101        // 

將每個 bit 去做 inversion 的動作(好濫的中文),google 到一篇文章: The Great Mystery of the Tilde(~) ,提供了一個怪怪但有趣的解釋:將原數值加上 1,再乘以 -1,如下例:

console.log(~-2); // 1
console.log(~-1); // 0
console.log(~0);  // -1
console.log(~1);  // -2
console.log(~2);  // -3

那上面 ~exports.events.indexOf(ev) 應該怎樣解讀呢? 關鍵在於 indexOf() 的回傳值,C/C++ 的 Array 是從 0 開始計數,indexOf() 如果在 Array 找不到符合條件的 item,則回傳 -1-1 經過 operator~ 則會神奇地變 0,在邏輯判斷中則是 false

if (~exports.events.indexOf(ev)) {
    // 在 events 中找到符合 ev 的 item
} else {
    // 沒找到!
}

that’s it, a 2-cent tip of a use case. . reply_count: 0 get_replies : 0 .

walking bear:DRSS feed

关于

wkliang

Clarke's Three Laws:

  • When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong.
  • The only way of discovering the limits of the possible is to venture a little way past them into the impossible.
  • Any sufficiently advanced technology is indistinguishable from magic.
  • 版权申明

    知识共享许可协议

    Fork me on GitHub

    Powered by

    Disqus, GitHub, Google Custom Search, Gravatar, HighlightJS, jekyll