-1

I wan't to translate some code from JS to C# but can't really imagine one part...

function getHisto(pixels) {
        var histosize = 1 << (3 * sigbits),
            histo = new Array(histosize),
            index, rval, gval, bval;
        pixels.forEach(function(pixel) {
            rval = pixel[0] >> rshift;
            gval = pixel[1] >> rshift;
            bval = pixel[2] >> rshift;
            index = getColorIndex(rval, gval, bval);
            histo[index] = (histo[index] || 0) + 1;
        });
        return histo;
    }

what exactly have can I expect from histo[]? I don't understand that line:

histo[index] = (histo[index] || 0) + 1;

If you need any additional information I'll try to give it.

Edit 1: I specifically meant histo[index] || 0

chrosey
  • 220
  • 3
  • 15

4 Answers4

1

The line histo[index] = (histo[index] || 0) + 1;

Is adding to the array and working out where to put it via the current index + 1 or 0 + 1.

Basically the or (||) handles the edge case of it being the first one added to histo.

NikolaiDante
  • 18,469
  • 14
  • 77
  • 117
1

The line

histo[index] = (histo[index] || 0) + 1;

is a shortcut for achieving this:

if (!histo[index]) { 
    histo[index] = 0; 
}
histo[index] = histo[index] + 1;

Which might make more sense to you.

See this answer for comparison between the almost equivalent ?? in C# and || in JS

Community
  • 1
  • 1
ekuusela
  • 5,034
  • 1
  • 25
  • 43
1

The square-bracket notation is the same as in C#, it's array access by index.

Take a look at this tutorial on MSDN.

For example. If you have an array with two items in it:

// javascript
var x = ["a", "b"];

// C#
var y = string[] {"a", "b"};

The first item is at index 0 and the second is at index 1. You can then access each item using the square bracket notation:

var first = x[0];
var second = x[1];
Greg B
  • 14,597
  • 18
  • 87
  • 141
1

|| is a Logical-OR operator in JavaScript

The equivalent to replace this in C#, would be a ?? Null-Coalesce operator

So basically in C#, your line would look like this.

histo[index] = (histo[index] ?? 0) + 1;
choz
  • 17,242
  • 4
  • 53
  • 73