-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumericalencoding.js
96 lines (93 loc) · 2.96 KB
/
numericalencoding.js
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
// https://github.com/CS2627883/Turbowarp-Encoding-Extension/blob/main/Encoding.js
(function(Scratch) {
'use strict';
class NumericalEncodingExtension {
maxcharlength = 6; // There are 149,186 unicode characters, so the maximum character code length is 6
encoded = 0;
decoded = 0;
getInfo() {
return {
id: 'cs2627883NumericalEncoding',
name: 'Numerical Encoding',
blocks: [{
opcode: 'NumericalEncode',
blockType: Scratch.BlockType.COMMAND,
text: 'Encode [DATA] to numbers',
arguments: {
DATA: {
type: Scratch.ArgumentType.STRING,
defaultValue: 'Hello!'
}
}
},
{
opcode: 'NumericalDecode',
blockType: Scratch.BlockType.COMMAND,
text: 'Decode [ENCODED] back to text',
arguments: {
ENCODED: {
type: Scratch.ArgumentType.STRING,
defaultValue: '000072000101000108000108000111000033' //Encoded "Hello!"
}
}
},
{
opcode: 'GetNumericalEncoded',
blockType: Scratch.BlockType.REPORTER,
text: 'encoded',
},
{
opcode: 'GetNumericalDecoded',
blockType: Scratch.BlockType.REPORTER,
text: 'decoded',
}
]
};
}
NumericalEncode(args) {
const toencode = String(args.DATA);
var encoded = "";
for (let i = 0; i < toencode.length; ++i) {
// Get char code of character
var encodedchar = String(toencode.charCodeAt(i));
// Pad encodedchar with 0s to ensure all encodedchars are the same length
encodedchar = "0".repeat(this.maxcharlength - encodedchar.length) + encodedchar;
encoded += encodedchar;
}
this.encoded = encoded;
}
NumericalDecode(args) {
const todecode = String(args.ENCODED);
if (todecode == "") {
this.decoded = "";
return;
}
var decoded = "";
// Create regex to split by char length
const regex = new RegExp('.{1,' + this.maxcharlength + '}', 'g');
// Split into array of characters
var encodedchars = todecode.match(regex);
for (let i = 0; i < encodedchars.length; i++) {
// Get character from char code
var decodedchar = String.fromCharCode(encodedchars[i]);
decoded += decodedchar;
}
this.decoded = decoded;
}
GetNumericalEncoded(args) {
return this.encoded;
}
GetNumericalDecoded(args) {
return this.decoded;
}
}
// Test Code
/*
encoding = new NumericalEncodingExtension();
encodingNumericalEncode({"DATA": 'Hello!'});
console.log(encoding.GetNumericalEncoded())
encoding.NumericalDecode({"ENCODED": encoding.GetNumericalEncoded()});
console.log(encoding.GetNumericalDecoded());
*/
Scratch.extensions.register(new NumericalEncodingExtension());
})(Scratch);