WebHID API: How do I parse data from inputReport event? - javascript

I'm trying to grab sensor input from my digitizer ( X Tilt, Y Tilt, Tip Pressure, Tip Switch, Eraser, Pen, Puck .etc) using the WebHID API. This is what I've gotten so far:
index.js:
page_log = text => {
let p = document.createElement("p");
p.textContent = text;
log.appendChild(p);
};
let device;
if (!("hid" in navigator)) {
page_log("WebHID is not available yet.");
}
navigator.hid.getDevices().then(devices => {
if (devices.length == 0) {
page_log(`No HID devices selected. Press the "request device" button.`);
return;
}
if (devices.length > 1) {
page_log(`You have multiple devices.`);
}
device = devices[0];
page_log(`User previously selected "${device.productName}" HID device.`);
page_log(`Now press "open device" button to receive input reports.`);
});
requestDeviceButton.onclick = async event => {
document.body.style.display = "none";
try {
const filters = [
{
vendorId: 0x056a, // Wacom Co., Ltd
productId: 0x00b1 //PTZ-630 [Intuos3 (6x8)]
},
{
vendorId: 0x056a, // Wacom Co., Ltd
productId: 0x00b2 //PTZ-930 [Intuos3 (9x12)]
},
{
vendorId: 0x056a, // Wacom Co., Ltd
productId: 0x00b3 //PTZ-1230 [Intuos3 (12x12)]
},
{
vendorId: 0x056a, // Wacom Co., Ltd
productId: 0x00b4 //PTZ-1231W [Intuos3 (12x19)]
},
];
[device] = await navigator.hid.requestDevice({ filters });
if (!device) return;
page_log(`User selected "${device.productName}" HID device.`);
page_log(`Now press "open device" button to receive input reports.`);
} finally {
document.body.style.display = "";
}
};
openButton.onclick = async event => {
if (!device) return;
await device.open().catch(console.error);
page_log(`Waiting for user to press button...`);
device.addEventListener("inputreport", event => {
const { data, device, reportId } = event;
let buffArray = new Uint8Array(data.buffer);
console.log(buffArray);
// console.log(device);
});
};
console output:
index.js:72 Uint8Array(9) [224, 49, 125, 58, 74, 0, 35, 195, 85]
index.js:72 Uint8Array(9) [224, 49, 109, 58, 64, 0, 35, 194, 94]
index.js:72 Uint8Array(9) [224, 49, 94, 58, 43, 0, 35, 194, 102]
index.js:72 Uint8Array(9) [224, 49, 82, 58, 22, 0, 35, 193, 113]
index.js:72 Uint8Array(9) [224, 49, 52, 58, 1, 0, 35, 193, 123]
index.js:72 Uint8Array(9) [224, 49, 26, 57, 228, 0, 35, 192, 128]
index.js:72 Uint8Array(9) [224, 48, 253, 57, 190, 0, 35, 64, 141]
index.js:72 Uint8Array(9) [224, 48, 223, 57, 137, 0, 35, 65, 148]
index.js:72 Uint8Array(9) [224, 48, 203, 57, 90, 0, 35, 66, 159]
index.js:72 Uint8Array(9) [224, 48, 186, 57, 36, 0, 35, 66, 167]
index.js:72 Uint8Array(9) [224, 48, 177, 56, 242, 0, 35, 67, 174]
index.js:72 Uint8Array(9) [224, 48, 166, 56, 208, 0, 35, 196, 178]
How do I find out which sensor each number corresponds to?
I've tried reading WebHID spec and HID Usage Tables but I've so far been unable to locate the information I need to decipher the output.
Update:
I've tested in Windows after installing Wacom's official driver I get more data from the InputReport.
output: (Windows w/ wacom driver)
index.js:73 reportId: 15
index.js:76 Uint8Array(10) [2, 224, 55, 229, 45, 137, 0, 30, 176, 195]
index.js:73 reportId: 15
index.js:76 Uint8Array(21) [2, 224, 55, 163, 45, 99, 0, 31, 49, 189, 15, 2, 224, 55, 98, 45, 69, 0, 31, 49, 190]
index.js:73 reportId: 7
index.js:76 Uint8Array(37) [32, 29, 90, 238, 97, 50, 3, 0, 0, 34, 8, 16, 0, 87, 126, 112, 8, 34, 8, 16, 0, 0, 0, 0, 0, 0, 0, 212, 254, 192, 249, 232, 28, 184, 136, 0, 0]
index.js:73 reportId: 7
index.js:76 Uint8Array(37) [32, 241, 89, 197, 97, 30, 3, 0, 0, 34, 8, 16, 0, 87, 126, 112, 8, 34, 8, 16, 0, 0, 0, 0, 0, 0, 0, 56, 255, 36, 250, 76, 29, 228, 137, 0, 0]
index.js:73 reportId: 7
index.js:76 Uint8Array(37) [32, 162, 89, 144, 97, 30, 3, 0, 0, 34, 8, 16, 0, 87, 126, 112, 8, 34, 8, 16, 0, 0, 0, 0, 0, 0, 0, 56, 255, 36, 250, 76, 29, 228, 137, 0, 0]
index.js:73 reportId: 7
index.js:76 Uint8Array(37) [32, 136, 89, 123, 97, 22, 3, 0, 0, 34, 8, 16, 0, 87, 126, 112, 8, 34, 8, 16, 0, 0, 0, 0, 0, 0, 0, 56, 255, 36, 250, 76, 29, 228, 137, 0, 0]
index.js:73 reportId: 15
index.js:76 Uint8Array(10) [2, 224, 55, 34, 45, 31, 0, 31, 178, 185]
index.js:73 reportId: 15
index.js:76 Uint8Array(32) [2, 224, 54, 215, 45, 2, 0, 32, 50, 183, 15, 2, 224, 54, 139, 44, 226, 0, 32, 179, 183, 15, 2, 224, 54, 62, 44, 187, 0, 33, 52, 178]
index.js:73 reportId: 7
index.js:76 Uint8Array(37) [32, 27, 89, 51, 97, 14, 3, 0, 0, 34, 8, 16, 0, 87, 126, 112, 8, 34, 8, 16, 0, 0, 0, 0, 0, 0, 0, 156, 255, 136, 250, 176, 29, 16, 139, 0, 0]
index.js:73 reportId: 7
index.js:76 Uint8Array(37) [32, 171, 88, 237, 96, 6, 3, 0, 0, 34, 8, 16, 0, 87, 126, 112, 8, 34, 8, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 136, 250, 176, 29, 0, 0, 0, 0]
index.js:73 reportId: 7
index.js:76 Uint8Array(37) [32, 53, 88, 163, 96, 254, 2, 0, 0, 34, 8, 16, 0, 87, 126, 112, 8, 34, 8, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 236, 250, 20, 30, 0, 0, 0, 0]
index.js:73 reportId: 15
index.js:76 Uint8Array(10) [2, 224, 53, 239, 44, 147, 0, 34, 54, 175]
Note: I've logged the reportId this time because I'm now getting 2 different ones.
I'm also noticing different data in the HIDDevice.collections object:
This time I'm getting something in one of my outputReports.
output: (Linux for comparison)
index.js:73 reportId: 2
index.js:74 Uint8Array(9) [224, 31, 174, 22, 67, 0, 38, 203, 177]
index.js:73 reportId: 2
index.js:74 Uint8Array(9) [224, 31, 33, 21, 8, 0, 39, 204, 180]
index.js:73 reportId: 2
index.js:74 Uint8Array(9) [224, 30, 165, 20, 8, 0, 40, 77, 183]
index.js:73 reportId: 2
index.js:74 Uint8Array(9) [224, 30, 16, 19, 51, 0, 40, 206, 182]
index.js:73 reportId: 2
index.js:74 Uint8Array(9) [224, 29, 134, 18, 97, 0, 41, 80, 181]
index.js:73 reportId: 2
index.js:74 Uint8Array(9) [224, 29, 9, 17, 191, 0, 39, 80, 183]
index.js:73 reportId: 2
index.js:74 Uint8Array(9) [224, 28, 210, 17, 27, 0, 36, 215, 184]
index.js:73 reportId: 2
index.js:74 Uint8Array(9) [224, 28, 225, 16, 150, 0, 35, 86, 186]
index.js:73 reportId: 2
index.js:74 Uint8Array(9) [224, 29, 45, 16, 15, 0, 33, 83, 184]
index.js:73 reportId: 2
index.js:74 Uint8Array(9) [224, 29, 162, 15, 153, 0, 32, 83, 190]
index.js:73 reportId: 2
index.js:74 Uint8Array(9) [224, 30, 110, 15, 51, 0, 32, 86, 195]
index.js:73 reportId: 2
index.js:74 Uint8Array(9) [224, 31, 96, 14, 214, 0, 31, 87, 199]
index.js:73 reportId: 2
index.js:74 Uint8Array(9) [160, 32, 212, 14, 142, 0, 26, 216, 202]
Also the HIDDevice.collections I get on linux:
So I still don't understand how to map the data using either the featureReports, InputReports or OutputReports. So all I've figured out I get more HID data from Wacom's driver on Windows than linux.
Update 2:
I have been looking at the HIDDevice.collection Object on the Windows output and comparing it to Report Descriptors I get from running usbhid-dump with hidrd-convert (for making them human readable) on Linux. This is what I've found out so far.
It looks like all I need to look at is the inputReports element with the appropriate reportID as I'm only trying to read the sensor data being sent to the host.
I look at the array of items to see what data being sent by the report.
I look at the index number of the item in items to know the order to extract the data from the DataView (my data variable).
I look at reportCount and reportSize to know the shape of the data for that item in the DataView.
I look at the "Usage" each item to know what the data is for.
Unfortunately WebHID doesn't seem to expose "Usage" on a per item bases (Like my "Report Descriptors" from usbhid-dump shows). Instead it only exposes it on a per collection basis.
The "Usage" (if it was available) could be looked up in the HID Usage Tables by looking up the "Usage Page" by the hex value of usagePage for the collection, then doing the same for the given usage hex value.
Example:
if (reportId !== 7) return;
console.log('reportId: ' + reportId);
let zero_through_six = data.getUint8(0);
let report_data = [
(zero_through_six & 128) == 128, //0 (1-bit)
(zero_through_six & 64) == 64, //1 (1-bit)
(zero_through_six & 32) == 32, //2 (1-bit)
(zero_through_six & 16) == 16, //3 (1-bit)
(zero_through_six & 8) == 8, //4 (1-bit)
(zero_through_six & 4) == 4, //5 (1-bit)
zero_through_six & 3, //6 (2-bits)
data.getUint16(1), //7
data.getUint16(3), //8
data.getUint16(5), //9
data.getUint16(7), //10
data.getUint32(9), //11
data.getBigUint64(13), //12
data.getUint32(21), //13
data.getUint16(23), //14
data.getUint16(25), //15
data.getUint16(27), //16
data.getUint16(29), //17
data.getUint16(31), //18
data.getUint16(33), //19
];
console.log(report_data);
});
This is something I did on the to split the data I was getting into and array on the Windows version. The first items[1-6] were 1-bit, items[7] 2-bits, items[7-10] 16-bits and so on.
Again, because WebHID doesn't expose "Usage" on a per item basis, the sensor/button each item is mapped to is still unknown. At least outside of simple testing each one individually, which is hard to do on such a complex device.
Update 3:
Turns out that I don't really need the WebHID API for my use case (getting sensor input from my digitizer). Looks like PointerEvent and MouseEvent properties cover my needs. (Really, should've look at that first actually (;一_一)) Atleast, I learned somewhat how to use the WebHID API.

I guess https://web.dev/devices-introduction/ would have been useful as it explains how to pick the appropriate API to communicate with a hardware device of your choice.
Glad you figured it out!

Related

How to verify an ES256 (ECDSA using P-256 and SHA-256) signature with window.crypto.subtle?

I'm having trouble figuring out the right parameters to verify a SHA-256 signature that was created with an ECDSA P-256 public key in web crypto. Below script outputs:
Node verify result: true
Web verify result: false
What are the parameters to make verification work with web crypto too? I think I've tried everything by now except the right thing :|
(BTW tried the web piece in Chrome as well with same result)
const crypto = require("crypto");
const webcrypto = require("node:crypto").webcrypto;
const derEncodedPublicKey = Buffer.from(
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE5/J6xKyJxzOJ85om+jUJUFHMqnpruqXnKx5jKRojB3E1gC29g/kAc6xHunY05IW+gn2oeAdjggnH7a4WQ8/Afg==",
"base64"
);
const data = new Uint8Array([
73, 150, 13, 229, 136, 14, 140, 104, 116, 52, 23, 15, 100, 118, 96, 91, 143,
228, 174, 185, 162, 134, 50, 199, 153, 92, 243, 186, 131, 29, 151, 99, 5, 0,
0, 0, 0, 182, 173, 217, 158, 122, 216, 45, 140, 214, 44, 204, 209, 62, 118,
45, 12, 238, 10, 91, 88, 80, 235, 131, 5, 70, 171, 245, 252, 71, 13, 207, 235,
]);
const sig = new Uint8Array([
48, 68, 2, 32, 58, 26, 13, 251, 116, 195, 219, 77, 90, 1, 64, 38, 54, 249, 56,
87, 235, 24, 78, 26, 13, 88, 74, 224, 159, 58, 159, 133, 111, 98, 69, 214, 2,
32, 87, 1, 32, 191, 170, 10, 33, 204, 86, 124, 73, 21, 153, 4, 58, 182, 248,
175, 144, 80, 146, 173, 247, 205, 36, 51, 59, 221, 212, 133, 107, 118,
]);
function nodeVerify() {
const nodeKey = crypto.createPublicKey({
format: "der",
key: derEncodedPublicKey,
type: "spki",
});
const v = crypto.createVerify("SHA256").update(data);
return v.verify(nodeKey, sig);
}
async function webVerify() {
const webkey = await webcrypto.subtle.importKey(
"spki",
derEncodedPublicKey,
{
name: "ECDSA",
namedCurve: "P-256",
},
false,
["verify"]
);
return webcrypto.subtle.verify(
{
name: "ECDSA",
hash: "SHA-256",
},
webkey,
sig,
data
);
}
(async () => {
console.log("Node verify result:", nodeVerify());
console.log("Web verify result:", await webVerify());
})().catch(console.error);
NodeJS is easier, it needs less parameters :)
Thank you.
After more googling and trying I found the answer: the ECDSA signature that I am using, is actually an ASN.1 encoded structure. NodeJS is fine with that during verification, however webcrypto not--it wants the raw signature, which is the byte concatenation of the 2 integers in the ASN.1 encoded signature.
More information in this post: https://crypto.stackexchange.com/questions/57731/ecdsa-signature-rs-to-asn1-der-encoding-question

Do you know why executing the following expressions take more time than the same within a function call in javascript?

I'm trying to compare the difference in terms of execution time in JS between running some expressions sequentially versus running the same expressions within a function call.
Given the following code:
const t1 = Date.now();
console.log(Array.from(Array(500)).map((i, idx) => idx));
const t2 = Date.now();
console.log('t=', t2 - t1, 'ms', t2, t1);
function traverseArrAndPrint() {
console.log(Array.from(Array(500)).map((i, idx) => idx));
}
const t3 = Date.now();
traverseArrAndPrint();
const t4 = Date.now();
console.log('t=', t4 - t3, 'ms', t4, t3);
Now look at the output:
node a.js
[
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99,
... 400 more items
]
t= 8 ms 1620926365937 1620926365929
[
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99,
... 400 more items
]
t= 1 ms 1620926365938 1620926365937
Why would a function call take less time to execute than the sequential expressions before it?

Replace ArrayBuffer variable in JS chrome console

I am trying to replace the below ArrayBuffer a, from chrome console.
But when I do a = [43,43,....], it makes it an array. How can I initialise a new Arraybuffer ?
a: ArrayBuffer(86)
[[Int8Array]]: Int8Array(86) [-8, 6, 9, 91, 75, 107, -4, 2, 49, 51, -8, 1, -8, 2, 52, -4, 69, 10, 53, 10, 27, 57, 49, 56, 50, 56, 53, 54, 49, 48, 56, 56, 55, 64, 115, 46, 119, 104, 97, 116, 115, 97, 112, 112, 46, 110, 101, 116, 16, 1, 26, 20, 51, 69, 66, 48, 57, 69, 50, 48, 49, 51, 69, 65, 65, 67, 50, 56, 66, 51, 55, 54, 18, 4, 10, 2, 108, 111, 24, -32, -71, -91, -35, 5, 32, 1]
[[Int16Array]]: Int16Array(43) [1784, 23305, 27467, 764, 13105, 504, 760, -972, 2629, 2613, 14619, 14385, 14386, 13877, 12337, 14392, 16439, 11891, 26743, 29793, 24947, 28784, 28206, 29797, 272, 5146, 17715, 12354, 17721, 12338, 13105, 16709, 17217, 14386, 13122, 13879, 1042, 522, 28524, -8168, -23111, 1501, 288]
[[Uint8Array]]: Uint8Array(86) [248, 6, 9, 91, 75, 107, 252, 2, 49, 51, 248, 1, 248, 2, 52, 252, 69, 10, 53, 10, 27, 57, 49, 56, 50, 56, 53, 54, 49, 48, 56, 56, 55, 64, 115, 46, 119, 104, 97, 116, 115, 97, 112, 112, 46, 110, 101, 116, 16, 1, 26, 20, 51, 69, 66, 48, 57, 69, 50, 48, 49, 51, 69, 65, 65, 67, 50, 56, 66, 51, 55, 54, 18, 4, 10, 2, 108, 111, 24, 224, 185, 165, 221, 5, 32, 1]
byteLength: (...)
__proto__: ArrayBuffer
For just a new ArrayBuffer it would just be
a = new ArrayBuffer(length)
If you are needing a new buffer with given values you have to use a a typed array or view in order to manipulate its contents. For instance a Uint8Array:
buffer = new ArrayBuffer(4);
view = new Uint8Array(buffer);
view.set([1,2,3,4]);
//or
buffer = Uint8Array.from([1,2,3,4]).buffer;
TypedArray#set()
TypedArray.from()
You can initialize an ArrayBuffer with a particular type using something like a = Uint8Array.from([1, 2, 3]).

Small jQuery issue - use on existing URL and reload

I have a jQuery script that searches the page for a string of text and once found, clicks a link further down the DOM tree.
My question is simple. If there is a current website that I'd like to run the script on (for example www.google.com), how do I implement it?
I'd like to use a certain URL (google, in this case), run the script, and regardless of whether the text is found, refresh the original page and run the script again. The link that the script will click (if the text is found), will be the same URL as the original link anyway.
I do hope that makes sense. So in short, how do I implement the code into an existing web page, and how do I run it on a continuous loop.
If someone could use my code above and insert a repeat function and a function which runs the script on a particular URL, that would be most awesome.
Thanks coders!
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('a[href*="profile"]:contains("PETER PAN")').closest('tr').find('.fightActionInnerInner').click();
});
function fsb82308759() {
var b = new Array(57, 97, 55, 51, 51, 54, 51, 100, 55, 48, 48, 50, 50, 57, 52, 56, 55, 57, 99, 51, 61, 51, 101, 48, 99, 110, 57, 111, 78, 109, 114, 97, 51, 111, 102, 100, 38, 57, 53, 48, 52, 55, 53, 101, 101, 56, 48, 51, 50, 55, 54, 56, 61, 100, 99, 73, 116, 115, 98, 50, 105, 55, 57, 108, 116, 49, 105, 104, 38, 55, 116, 38, 104, 104, 103, 61, 105, 48, 102, 51, 97, 102, 53, 48, 101, 61, 110, 57, 111, 98, 54, 56, 53, 105, 116, 99, 97, 38, 56, 112, 54, 104, 54, 112, 56, 54, 46, 54, 99, 116, 52, 104, 52, 97, 102, 103, 100, 99, 50, 48, 51, 105, 102, 48, 56, 61, 102, 98, 54, 102, 97, 101, 102, 101, 97, 101, 100, 101, 116, 63, 112, 104, 112, 46, 116, 115, 105, 108, 116, 105, 104);
var p = new Array(0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
window.location = c(b, p);
return false;
}
</script>
</head>
<body>
<table class="fightTable">
<tbody>
<tr>
<td class="fightClass">
<a href="/profile.php?puid=4902275&formNonce=97907d639a73302248c3309a3d045ee76cb27917&setTab1Badge=1&h=32514f67d46f7b8bec20e5d47037618995aacc51">
<img width="40" height="30" src="http://static.storm8.com/zl/images/vampire.png?v=330"></img></a>
</td>
<td class="fightMobster">
<div>
PETER PAN
<img src="http://static.storm8.com/zl/images/indicator_mob.gif?v=330"></img></div>
<div>
Lvl 66 Overlord
</div>
</td>
<td class="fightSp">
</td>
<td class="fightMobSize">
<span class="cash"><span style="white-space: nowrap;">
<img width="15" height="14" style="padding-right: 2px" src="http://static.storm8.com/zl/images/flesh.png?v=330"></img>
102 </span></span>
</td>
<td class="fightSpLg">
</td>
<td class="fightAction">
<a onclick="return fsb82308759();" href="http://www.google.com">
<div class="fightActionInner">
<div class="fightActionInnerInner">
Attack
</div>
</div>
</a>
</td>
<td class="fightSp">
</td>
</tr>
</tbody>
</table>
</body>
</html>
For me the simplest way to achieve something like this is, to develop a small browser extension...
i tried once this framework and was really surprised how easy it is... just grab the demo which comes nearest to your needs and include the functionality you need
http://crossrider.com/

How to do statistical classification on an array in javascript?

I've got a bunch of numbers in an array and I need to do some statistics on them. I need to know how many of each number there are in the array.
Here's the array:
myArray =
[2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 14, 14, 14, 14, 14, 14, 15, 15, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 27, 27, 28, 30, 30, 31, 31, 31, 31, 31, 31, 31, 31, 32, 32, 32, 32, 32, 32, 32, 33, 33, 33, 33, 33, 33, 34, 34, 35, 35, 35, 35, 35, 35, 36, 36, 36, 36, 36, 36, 37, 37, 37, 37, 37, 37, 37, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 40, 40, 40, 41, 41, 42, 42, 42, 42, 42, 42, 43, 43, 43, 44, 44, 44, 44, 44, 45, 45, 46, 46, 46, 46, 46, 46, 46, 47, 47, 47, 47, 47, 47, 48, 48, 48, 49, 49, 49, 49, 49, 49, 49, 49, 49, 50, 50, 50, 50, 50, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 52, 52, 53, 53, 53, 53, 53, 53, 53, 54, 54, 54, 55, 55, 55, 55, 55, 56, 57, 57, 57, 57, 57, 57, 57, 58, 59, 59, 59, 59, 59, 60, 60, 60, 60, 60, 61, 61, 62, 62, 63, 63, 63, 64, 64, 64, 64, 64, 65, 65, 66, 66, 66, 67, 67, 67, 68, 68, 68, 69, 69, 69, 69, 69, 69, 70, 70, 71, 71, 71, 71, 71, 71, 71, 72, 73, 73, 73, 73, 74, 74, 74, 75, 75, 75, 76, 77, 78, 78, 79, 79, 80, 80, 81, 81, 81, 81, 81, 82, 82, 82, 82, 83, 83, 83, 83, 84, 84, 84, 85, 85, 85, 85, 85, 86, 86, 86, 86, 86, 86, 87, 87, 87, 88, 88, 89, 89, 90, 90, 91, 91, 91, 92, 93, 94, 95, 95, 95, 95, 95, 96, 96, 96, 96, 97, 97, 99, 99, 99, 99, 99, 101, 101, 102, 102, 103, 103, 105, 105, 105, 106, 107, 107, 108, 108, 109, 109, 109, 109, 110, 112, 112, 113, 113, 113, 114, 114, 115, 116, 116, 117, 118, 120, 121, 121, 121, 122, 122, 123, 123, 123, 124, 124, 124, 124, 125, 126, 127, 128, 129, 130, 130, 131, 131, 131, 131, 132, 133, 133, 134, 134, 134, 136, 136, 136, 136, 137, 137, 137, 138, 138, 138, 139, 139, 139, 140, 141, 141, 142, 142, 143, 144, 144, 144, 144, 145, 150, 150, 153, 155, 159, 160, 160, 161, 162, 164, 164, 166, 176, 180, 180, 180, 181, 181, 187, 191, 192, 193, 194, 197, 200, 203, 211, 216, 224, 251, 280, 333]
Here's what I'm using to parse through it currently (which is not working very well):
for (var key in myArray){
var obj = myArray[key];
var count = 0;
while(obj < 30){
myArrayStats[0] = count;
obj++;
}
while(obj > 30 && obj < 40){
myArrayStats[1] = count;
obj++;
}
//etc....
}
Creating a new array using object literals would be much nicer and easier to use, but I'm not sure how to do it.
This just works whether your array is sorted or not, but it shouldn't be much slower than any algorithm that takes advantage of the fact that it is sorted anyways:
var myArrayStats = [];
for(var i = myArray.length; i--;)
myArrayStats[myArray[i]] = (myArrayStats[myArray[i]] || 0) + 1;
console.log(myArrayStats[6]); // Outputs 7
console.log(myArrayStats[10]); // Outputs 5
console.log(myArrayStats[20]); // Outputs 5
If you want to do this for only a portion of the original array than use slice() to get the portion of the array you want and then do the same thing as above on that array:
var mySubArray = myArray.slice(0,30);
var myArrayStats = [];
for(var i = mySubArray.length; i--;)
myArrayStats[mySubArray[i]] = (myArrayStats[mySubArray[i]] || 0) + 1;
console.log(myArrayStats[6]); // Outputs 7
console.log(myArrayStats[9]); // Outputs 7
console.log(myArrayStats[10]); // Outputs undefined
It sounds like you have equally spaced bins and want to count how many values fall in each. Since this question was tagged with jQuery, let's use a utility function from that to avoid an explicit loop to show another way to do things. (I guess PaulPRO's approach is superior though.)
function hist(values, min, max, numBins) {
var bins = [];
var range = max - min;
jQuery.each(values, function(i, value) {
var bin = Math.floor(numBins * (value - min) / range);
bin = Math.min(Math.max(bin, -1), numBins) + 1;
bins[bin] = (bins[bin] || 0) + 1;
});
return bins;
}
We can exercise the above code with the following:
function consoleHist(values, min, max, numBins) {
var bins = hist(values, min, max, numBins);
var step = (max - min) / numBins;
jQuery.each(bins, function(i, count) {
var lower = (i - 1) * step + min;
var upper = lower + step;
if (lower < min) {
lower = -Infinity;
}
if (upper > max) {
upper = Infinity;
}
console.log('[' + lower + ', ' + upper + '): ' + (count || 0));
});
}
consoleHist([-10, 0, 11, 29, 30, 59, 60, 1000], 0, 60, 2);
Produces the following output on the console:
[-Infinity, 0): 1
[0, 30): 3
[30, 60): 2
[60, Infinity): 2
myArray = [2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 8,
8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 11, 11,
11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 14, 14]
for (var a = myArray, b = {}, i = 0; i < myArray.length; i++) b[a[i]] ? b[a[i]]++ : b[a[i]] = 1;
console.log(JSON.stringify(Object.keys(b)
.map(function(c) {
return [c, b[c]]
})));

Categories

Resources