a few more helpers in common-util

pull/1/head
ansuz 5 years ago
parent e5b7c052bd
commit 84518c0775

@ -21,6 +21,10 @@
}; };
}; };
Util.clone = function (o) {
return JSON.parse(JSON.stringify(o));
};
Util.tryParse = function (s) { Util.tryParse = function (s) {
try { return JSON.parse(s); } catch (e) { return;} try { return JSON.parse(s); } catch (e) { return;}
}; };
@ -57,6 +61,44 @@
}; };
}; };
Util.response = function () {
var pending = {};
var timeouts = {};
var clear = function (id) {
clearTimeout(timeouts[id]);
delete timeouts[id];
delete pending[id];
};
var expect = function (id, fn, ms) {
if (typeof(id) !== 'string') { throw new Error("EXPECTED_STRING"); }
if (typeof(fn) !== 'function') { throw new Error("EXPECTED_CALLBACK"); }
pending[id] = fn;
if (typeof(ms) === 'number' && ms) {
timeouts[id] = setTimeout(function () {
if (typeof(pending[id]) === 'function') { pending[id]('TIMEOUT'); }
clear(id);
}, ms);
}
};
var handle = function (id, args) {
var fn = pending[id];
if (typeof(fn) !== 'function') { throw new Error("MISSING_CALLBACK"); }
pending[id].apply(null, Array.isArray(args)? args : [args]);
clear(id);
};
return {
expected: function (id) {
return Boolean(pending[id]);
},
expect: expect,
handle: handle,
};
};
Util.find = function (map, path) { Util.find = function (map, path) {
var l = path.length; var l = path.length;
for (var i = 0; i < l; i++) { for (var i = 0; i < l; i++) {
@ -98,21 +140,21 @@
return hexArray.join(""); return hexArray.join("");
}; };
Util.uint8ArrayToHex = function (a) { Util.uint8ArrayToHex = function (bytes) {
// call slice so Uint8Arrays work as expected var hexString = '';
return Array.prototype.slice.call(a).map(function (e) { for (var i = 0; i < bytes.length; i++) {
var n = Number(e & 0xff).toString(16); if (bytes[i] < 16) { hexString += '0'; }
if (n === 'NaN') { hexString += bytes[i].toString(16);
throw new Error('invalid input resulted in NaN');
} }
return hexString;
};
switch (n.length) { Util.hexToUint8Array = function (hexString) {
case 0: return '00'; // just being careful, shouldn't happen var bytes = new Uint8Array(Math.ceil(hexString.length / 2));
case 1: return '0' + n; for (var i = 0; i < bytes.length; i++) {
case 2: return n; bytes[i] = parseInt(hexString.substr(i * 2, 2), 16);
default: throw new Error('unexpected value');
} }
}).join(''); return bytes;
}; };
// given an array of Uint8Arrays, return a new Array with all their values // given an array of Uint8Arrays, return a new Array with all their values

Loading…
Cancel
Save