jsos
college code for operating system fundamentals in js
git clone https://9o.is/git/jsos.git
utils.js
(2644B)
1 /* --------
2 Utils.js
3
4 Utility functions.
5 -------- */
6
7 /*
8 * Removes leading and trailing spaces.
9 */
10 function trim(str) {
11 return str.replace(/^\s+ | \s+$/g, "");
12 }
13
14 /*
15 * Rotates each character of a string to the thirteenth spot.
16 * ie. a to n and z to m.
17 */
18 function rot13(str) {
19 var retVal = "";
20 for (var i in str) {
21 var ch = str[i];
22 var code = 0;
23 if ("abcedfghijklmABCDEFGHIJKLM".indexOf(ch) >= 0) {
24 code = str.charCodeAt(i) + 13;
25 retVal = retVal + String.fromCharCode(code);
26 } else if ("nopqrstuvwxyzNOPQRSTUVWXYZ".indexOf(ch) >= 0) {
27 code = str.charCodeAt(i) - 13;
28 retVal = retVal + String.fromCharCode(code);
29 } else {
30 retVal = retVal + ch;
31 }
32 }
33 return retVal;
34 }
35
36 /*
37 * Matches hex pattern. ie. FF 00 5G 8D 98
38 */
39 function isValidHex(str) {
40 for (var i in str) {
41 var ch = str[i];
42 if ("abcedfABCDEF0123456789 ".indexOf(ch) < 0) {
43 return false;
44 }
45 }
46 return true;
47 }
48
49 /*
50 * Matches hex byte. ie. FF or 8D etc
51 */
52 function isValidHexByte(str) {
53 if(str.length > 2 || str.length < 1) return false;
54 for (var i in str) {
55 var ch = str[i];
56 if ("abcedfABCDEF0123456789".indexOf(ch) < 0) {
57 return false;
58 }
59 }
60 return true;
61 }
62
63 /*
64 * Padding string hex values
65 * ie. If size is 4 and hex string is 'a8'
66 * result will be '00a8'.
67 */
68 function pad(hex, size) {
69 hex = hex.toString();
70 while(hex.length < size)
71 hex = '0'+hex;
72 return hex;
73 }
74
75 /*
76 * Checks if the value is a valid byte or a value
77 * of 0 to 255.
78 */
79 function isByte(value) {
80 return isInt(value) && value > -1 && value < 256;
81 }
82
83 /*
84 * Checks if input is a string type.
85 */
86 function isString(input){
87 return typeof(input)=='string';
88 }
89
90 /*
91 * Converts a number to an ASCII character.
92 */
93 function hex2ASCII(num) {
94 if(num==0) return null;
95 var hex = num.toString(16);
96 var str = '';
97 for (var i=0; i<hex.length; i+=2)
98 str += String.
99 fromCharCode(parseInt(hex.substr(i, 2), 16));
100 return str;
101 }
102
103 /*
104 * Converts ASCII character to a number.
105 */
106 function ascii2hex(pStr) {
107 var tempstr = [];
108 for (a=0; a<pStr.length; a++) {
109 tempstr[a] = pStr.charCodeAt(a).toString(16);
110 }
111 return tempstr;
112 }
113
114 /*
115 * Converts a string to array. Each array element is
116 * a string character.
117 */
118 function string2Array(string) {
119 string = string.toString();
120 var arr = [];
121 for(i=0; i<string.length; i++)
122 arr[i] = string.substring(i,i+1);
123 return arr;
124 }
125
126 /*
127 * Checks if the value is an integer.
128 */
129 function isInt(value){
130 return ((parseFloat(value) == parseInt(value))
131 && !isNaN(value))
132 }