Skip to content

Instantly share code, notes, and snippets.

@sebastiandelaroche
Created June 4, 2021 16:20
Show Gist options
  • Save sebastiandelaroche/72f99744ac76935124c6ffac9581c447 to your computer and use it in GitHub Desktop.
Save sebastiandelaroche/72f99744ac76935124c6ffac9581c447 to your computer and use it in GitHub Desktop.
Provi Code Challenge
function decodeInt(text) {
const index = text.indexOf("e");
const integer = text.slice(1, index);
return [index + 1, integer];
}
function decodeString(text) {
const [textLength] = text.split(":");
const length = Number(textLength);
return [2 + length, text.slice(2, 2 + length)];
}
function decodeList(text) {
const list = [];
let currentChar;
let position = 1;
while (position < text.length) {
currentChar = text[position];
if (currentChar == "e") {
position += 1;
break;
}
const [_position, _result] = decode(text.slice(position));
list.push(_result);
position += _position;
}
return [position, list];
}
function decodeMap(text) {
const map = {};
let currentChar;
let position = 1;
while (position < text.length) {
currentChar = text[position];
if (currentChar == "e") {
position += 1;
break;
}
const [_position1, _keyName] = decode(text.slice(position));
const [_position2, _value] = decode(text.slice(position + _position1));
map[_keyName] = _value;
position += _position1 + _position2;
}
return [position, map];
}
function decode(text) {
let position = 0;
let result = [];
while (text.length > position) {
const letter = text[position];
switch (letter) {
case "i": {
const [_position, _result] = decodeInt(text.slice(position));
position += _position;
result = [_position, _result];
return result;
}
case "l": {
const [_position, _result] = decodeList(text.slice(position));
position += _position;
result = [_position, _result];
return result;
}
case "d": {
const [_position, _result] = decodeMap(text.slice(position));
position += _position;
result = [_position, _result];
return result;
}
default: {
const [_position, _result] = decodeString(text.slice(position));
position += _position;
result = [_position, _result];
return result;
}
}
}
return result;
}
function bencode(text) {
return decode(text)[1];
}
console.log("result -> ", bencode("i10e"));
console.log("result -> ", bencode("le"));
console.log("result -> ", bencode("li10ee"));
console.log("result -> ", bencode("li10ei15ee"));
console.log("result -> ", bencode("lleli8eee"));
console.log("result -> ", bencode("l4:star3:foxe"));
console.log("result -> ", bencode("d3:bar4:spam3:fooi42ee"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment