repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
LafTools | github_2023 | work7z | typescript | ToCamelCase.constructor | constructor() {
super();
this.name = "To Camel case";
this.module = "Code";
// this.description =
// "Converts the input string to camel case.\n<br><br>\nCamel case is all lower case except letters after word boundaries which are uppercase.\n<br><br>\ne.g. thisIsCamelCase\n<br><br>\n'Attempt to be context aware' will make the operation attempt to nicely transform variable and function names.";
// this.infoURL = "https://wikipedia.org/wiki/Camel_case";
this.inputType = "string";
this.outputType = "string";
this.args = [
{
name: "Attempt to be context aware",
type: "boolean",
value: false,
},
];
} | /**
* ToCamelCase constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToCamelCase.tsx#L52-L69 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToCamelCase.run | run(input, args) {
const smart = args[0];
if (smart) {
return replaceVariableNames(input, camelCase);
} else {
return camelCase(input);
}
} | /**
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToCamelCase.tsx#L76-L84 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToCharcode.constructor | constructor() {
super();
this.name = "To Charcode";
this.module = "Default";
// this.description =
// "Converts text to its unicode character code equivalent.<br><br>e.g. <code>Γειά σου</code> becomes <code>0393 03b5 03b9 03ac 20 03c3 03bf 03c5</code>";
// this.infoURL = "https://wikipedia.org/wiki/Plane_(Unicode)";
this.inputType = "string";
this.outputType = "string";
this.args = [
{
name: "Delimiter",
type: "option",
value: DELIM_OPTIONS,
},
{
name: "Base",
type: "number",
value: 16,
},
];
} | /**
* ToCharcode constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToCharcode.tsx#L64-L86 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToCharcode.run | run(input, args) {
const delim = Utils.charRep(args[0] || "Space"),
base = args[1];
let output = "",
padding,
ordinal;
if (base < 2 || base > 36) {
throw new OperationError("Error: Base argument must be between 2 and 36");
}
const charcode = Utils.strToCharcode(input);
for (let i = 0; i < charcode.length; i++) {
ordinal = charcode[i];
if (base === 16) {
if (ordinal < 256) padding = 2;
else if (ordinal < 65536) padding = 4;
else if (ordinal < 16777216) padding = 6;
else if (ordinal < 4294967296) padding = 8;
else padding = 2;
// TODO: Fix this
// if (padding > 2 && isWorkerEnvironment())
// self.setOption("attemptHighlight", false);
output += Utils.hex(ordinal, padding) + delim;
} else {
// if (isWorkerEnvironment()) self.setOption("attemptHighlight", false);
output += ordinal.toString(base) + delim;
}
}
return output.slice(0, -delim.length);
} | /**
* @param {string} input
* @param {Object[]} args
* @returns {string}
*
* @throws {OperationError} if base argument out of range
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToCharcode.tsx#L95-L129 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToDecimal.constructor | constructor() {
super();
this.name = "To Decimal";
this.module = "Default";
// this.description =
// "Converts the input data to an ordinal integer array.<br><br>e.g. <code>Hello</code> becomes <code>72 101 108 108 111</code>";
this.inputType = "ArrayBuffer";
this.outputType = "string";
this.args = [
{
name: "Delimiter",
type: "option",
value: DELIM_OPTIONS,
},
{
name: "Support signed values",
type: "boolean",
value: false,
},
];
} | /**
* ToDecimal constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToDecimal.tsx#L56-L77 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToDecimal.run | run(input, args) {
input = new Uint8Array(input);
const delim = Utils.charRep(args[0]),
signed = args[1];
if (signed) {
input = input.map((v) => (v > 0x7f ? v - 0xff - 1 : v));
}
return input.join(delim);
} | /**
* @param {ArrayBuffer} input
* @param {Object[]} args
* @returns {string}
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToDecimal.tsx#L84-L92 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToHTMLEntity.constructor | constructor() {
super();
this.name = "To HTML Entity";
this.module = "Encodings";
// this.description =
// "Converts characters to HTML entities<br><br>e.g. <code>&</code> becomes <code>&<span>amp;</span></code>";
// this.infoURL =
// "https://wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references";
this.inputType = "string";
this.outputType = "string";
this.args = [
{
name: Dot("tpjs2gJDt", "Convert all characters"),
type: "boolean",
value: false,
},
{
name: Dot("Kd4QkQG2F", "Convert to"),
type: "option",
value: ["Named entities", "Numeric entities", "Hex entities"],
},
];
} | /**
* ToHTMLEntity constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToHTMLEntity.tsx#L60-L83 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToHTMLEntity.run | run(input, args) {
const convertAll = args[0],
numeric = args[1] === "Numeric entities",
hexa = args[1] === "Hex entities";
const charcodes = Utils.strToCharcode(input);
let output = "";
for (let i = 0; i < charcodes.length; i++) {
if (convertAll && numeric) {
output += "&#" + charcodes[i] + ";";
} else if (convertAll && hexa) {
output += "&#x" + Utils.hex(charcodes[i]) + ";";
} else if (convertAll) {
output += byteToEntity[charcodes[i]] || "&#" + charcodes[i] + ";";
} else if (numeric) {
if (charcodes[i] > 255 || charcodes[i] in byteToEntity) {
output += "&#" + charcodes[i] + ";";
} else {
output += Utils.chr(charcodes[i]);
}
} else if (hexa) {
if (charcodes[i] > 255 || charcodes[i] in byteToEntity) {
output += "&#x" + Utils.hex(charcodes[i]) + ";";
} else {
output += Utils.chr(charcodes[i]);
}
} else {
output +=
byteToEntity[charcodes[i]] ||
(charcodes[i] > 255
? "&#" + charcodes[i] + ";"
: Utils.chr(charcodes[i]));
}
}
return output;
} | /**
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToHTMLEntity.tsx#L90-L126 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToHex.constructor | constructor() {
super();
this.module = "Default";
this.inputType = "ArrayBuffer";
this.outputType = "string";
this.args = [
{
name: "Delimiter",
type: "option",
value: TO_HEX_DELIM_OPTIONS,
},
{
name: "Bytes per line",
type: "number",
value: 0,
},
];
} | /**
* ToHex constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToHex.tsx#L75-L93 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToHex.run | run(input, args) {
let delim, comma;
if (args[0] === "0x with comma") {
delim = "0x";
comma = ",";
} else {
delim = Utils.charRep(args[0] || "Space");
}
const lineSize = args[1];
return toHex(new Uint8Array(input), delim, 2, comma, lineSize);
} | /**
* @param {ArrayBuffer} input
* @param {Object[]} args
* @returns {string}
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToHex.tsx#L100-L111 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToHex.highlight | highlight(pos, args) {
let delim,
commaLen = 0;
if (args[0] === "0x with comma") {
delim = "0x";
commaLen = 1;
} else {
delim = Utils.charRep(args[0] || "Space");
}
const lineSize: any = args[1],
len = delim.length + commaLen;
const countLF = function (p: number) {
// Count the number of LFs from 0 upto p
return ((p / lineSize) | 0) - (p as any >= lineSize as any && p % lineSize === 0);
};
pos[0].start = pos[0].start * (2 + len) + countLF(pos[0].start);
pos[0].end = pos[0].end * (2 + len) + countLF(pos[0].end);
// if the delimiters are not prepended, trim the trailing delimiter
if (!(delim === "0x" || delim === "\\x")) {
pos[0].end -= delim.length;
}
// if there is comma, trim the trailing comma
pos[0].end -= commaLen;
return pos;
} | /**
* Highlight to Hex
*
* @param {Object[]} pos
* @param {number} pos[].start
* @param {number} pos[].end
* @param {Object[]} args
* @returns {Object[]} pos
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToHex.tsx#L122-L150 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToHex.highlightReverse | highlightReverse(pos, args) {
let delim,
commaLen = 0;
if (args[0] === "0x with comma") {
delim = "0x";
commaLen = 1;
} else {
delim = Utils.charRep(args[0] || "Space");
}
const lineSize = args[1],
len = delim.length + commaLen,
width = len + 2;
const countLF = function (p) {
// Count the number of LFs from 0 up to p
const lineLength = width * lineSize;
return ((p / lineLength) | 0) - (p >= lineLength as any && p % lineLength === 0);
};
pos[0].start =
pos[0].start === 0
? 0
: Math.round((pos[0].start - countLF(pos[0].start)) / width);
pos[0].end =
pos[0].end === 0
? 0
: Math.ceil((pos[0].end - countLF(pos[0].end)) / width);
return pos;
} | /**
* Highlight from Hex
*
* @param {Object[]} pos
* @param {number} pos[].start
* @param {number} pos[].end
* @param {Object[]} args
* @returns {Object[]} pos
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToHex.tsx#L161-L190 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToHexdump.constructor | constructor() {
super();
this.name = "To Hexdump";
this.module = "Default";
this.inputType = "ArrayBuffer";
this.outputType = "string";
this.args = [
{
name: "Width",
type: "number",
value: 16,
min: 1,
},
{
name: "Upper case hex",
type: "boolean",
value: false,
},
{
name: "Include final length",
type: "boolean",
value: false,
},
{
name: "UNIX format",
type: "boolean",
value: false,
},
];
} | /**
* ToHexdump constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToHexdump.tsx#L70-L100 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToHexdump.run | run(input, args) {
const data = new Uint8Array(input);
const [length, upperCase, includeFinalLength, unixFormat] = args;
const padding = 2;
if (length < 1 || Math.round(length) !== length)
throw new OperationError("Width must be a positive integer");
const lines: any[] = [];
for (let i = 0; i < data.length; i += length) {
let lineNo = Utils.hex(i, 8);
const buff = data.slice(i, i + length);
const hex: any[] = [];
buff.forEach((b) => hex.push(Utils.hex(b, padding)));
let hexStr = hex.join(" ").padEnd(length * (padding + 1), " ");
const ascii = Utils.printable(
Utils.byteArrayToChars(buff),
false,
unixFormat,
);
const asciiStr = ascii.padEnd(buff.length, " ");
if (upperCase) {
hexStr = hexStr.toUpperCase();
lineNo = lineNo.toUpperCase();
}
lines.push(`${lineNo} ${hexStr} |${asciiStr}|`);
if (includeFinalLength && i + buff.length === data.length) {
lines.push(Utils.hex(i + buff.length, 8));
}
}
return lines.join("\n");
} | /**
* @param {ArrayBuffer} input
* @param {Object[]} args
* @returns {string}
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToHexdump.tsx#L107-L144 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToHexdump.highlight | highlight(pos, args) {
// Calculate overall selection
const w = args[0] || 16,
width = 14 + w * 4;
let line = Math.floor(pos[0].start / w),
offset = pos[0].start % w,
start = 0,
end = 0;
pos[0].start = line * width + 10 + offset * 3;
line = Math.floor(pos[0].end / w);
offset = pos[0].end % w;
if (offset === 0) {
line--;
offset = w;
}
pos[0].end = line * width + 10 + offset * 3 - 1;
// Set up multiple selections for bytes
let startLineNum = Math.floor(pos[0].start / width);
const endLineNum = Math.floor(pos[0].end / width);
if (startLineNum === endLineNum) {
pos.push(pos[0]);
} else {
start = pos[0].start;
end = (startLineNum + 1) * width - w - 5;
pos.push({ start: start, end: end });
while (end < pos[0].end) {
startLineNum++;
start = startLineNum * width + 10;
end = (startLineNum + 1) * width - w - 5;
if (end > pos[0].end) end = pos[0].end;
pos.push({ start: start, end: end });
}
}
// Set up multiple selections for ASCII
const len = pos.length;
let lineNum = 0;
start = 0;
end = 0;
for (let i = 1; i < len; i++) {
lineNum = Math.floor(pos[i].start / width);
start =
(pos[i].start - lineNum * width - 10) / 3 +
(width - w - 2) +
lineNum * width;
end =
(pos[i].end + 1 - lineNum * width - 10) / 3 +
(width - w - 2) +
lineNum * width;
pos.push({ start: start, end: end });
}
return pos;
} | /**
* Highlight To Hexdump
*
* @param {Object[]} pos
* @param {number} pos[].start
* @param {number} pos[].end
* @param {Object[]} args
* @returns {Object[]} pos
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToHexdump.tsx#L155-L211 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToHexdump.highlightReverse | highlightReverse(pos, args) {
const w = args[0] || 16;
const width = 14 + w * 4;
let line = Math.floor(pos[0].start / width);
let offset = pos[0].start % width;
if (offset < 10) {
// In line number section
pos[0].start = line * w;
} else if (offset > 10 + w * 3) {
// In ASCII section
pos[0].start = (line + 1) * w;
} else {
// In byte section
pos[0].start = line * w + Math.floor((offset - 10) / 3);
}
line = Math.floor(pos[0].end / width);
offset = pos[0].end % width;
if (offset < 10) {
// In line number section
pos[0].end = line * w;
} else if (offset > 10 + w * 3) {
// In ASCII section
pos[0].end = (line + 1) * w;
} else {
// In byte section
pos[0].end = line * w + Math.ceil((offset - 10) / 3);
}
return pos;
} | /**
* Highlight To Hexdump in reverse
*
* @param {Object[]} pos
* @param {number} pos[].start
* @param {number} pos[].end
* @param {Object[]} args
* @returns {Object[]} pos
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToHexdump.tsx#L222-L255 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToKebabCase.constructor | constructor() {
super();
this.name = "To Kebab case";
this.module = "Code";
// this.description =
// "Converts the input string to kebab case.\n<br><br>\nKebab case is all lower case with dashes as word boundaries.\n<br><br>\ne.g. this-is-kebab-case\n<br><br>\n'Attempt to be context aware' will make the operation attempt to nicely transform variable and function names.";
// this.infoURL = "https://wikipedia.org/wiki/Kebab_case";
this.inputType = "string";
this.outputType = "string";
this.args = [
{
name: Dot("GSgmYW7Qv", "Attempt to be context aware"),
type: "boolean",
value: false,
},
];
} | /**
* ToKebabCase constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToKebabCase.tsx#L52-L69 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToKebabCase.run | run(input, args) {
const smart = args[0];
if (smart) {
return replaceVariableNames(input, kebabCase);
} else {
return kebabCase(input);
}
} | /**
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToKebabCase.tsx#L76-L84 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToLowerCase.constructor | constructor() {
super();
this.name = "To Lower case";
this.module = "Default";
// this.description = "Converts every character in the input to lower case.";
this.inputType = "string";
this.outputType = "string";
this.args = [];
} | /**
* ToLowerCase constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToLowerCase.tsx#L45-L54 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToLowerCase.run | run(input, args) {
return input.toLowerCase();
} | /**
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToLowerCase.tsx#L61-L63 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToLowerCase.highlight | highlight(pos, args) {
return pos;
} | /**
* Highlight To Lower case
*
* @param {Object[]} pos
* @param {number} pos[].start
* @param {number} pos[].end
* @param {Object[]} args
* @returns {Object[]} pos
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToLowerCase.tsx#L74-L76 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToLowerCase.highlightReverse | highlightReverse(pos, args) {
return pos;
} | /**
* Highlight To Lower case in reverse
*
* @param {Object[]} pos
* @param {number} pos[].start
* @param {number} pos[].end
* @param {Object[]} args
* @returns {Object[]} pos
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToLowerCase.tsx#L87-L89 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToMessagePack.constructor | constructor() {
super();
this.name = "To MessagePack";
this.module = "Code";
// this.description =
// "Converts JSON to MessagePack encoded byte buffer. MessagePack is a computer data interchange format. It is a binary form for representing simple data structures like arrays and associative arrays.";
// this.infoURL = "https://wikipedia.org/wiki/MessagePack";
this.inputType = "JSON";
this.outputType = "ArrayBuffer";
this.args = [];
} | /**
* ToMessagePack constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToMessagePack.tsx#L47-L58 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToMessagePack.run | run(input, args) {
try {
if (isWorkerEnvironment()) {
return notepack.encode(input);
} else {
const res = notepack.encode(input);
// Safely convert from Node Buffer to ArrayBuffer using the correct view of the data
return new Uint8Array(res).buffer;
}
} catch (err) {
throw new OperationError(`Could not encode JSON to MessagePack: ${err}`);
}
} | /**
* @param {JSON} input
* @param {Object[]} args
* @returns {ArrayBuffer}
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToMessagePack.tsx#L65-L77 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToMorseCode.constructor | constructor() {
super();
this.name = "To Morse Code";
this.module = "Default";
// this.description =
// "Translates alphanumeric characters into International Morse Code.<br><br>Ignores non-Morse characters.<br><br>e.g. <code>SOS</code> becomes <code>... --- ...</code>";
// this.infoURL = "https://wikipedia.org/wiki/Morse_code";
this.inputType = "string";
this.outputType = "string";
this.args = [
{
name: "Format options",
type: "option",
value: ["-/.", "_/.", "Dash/Dot", "DASH/DOT", "dash/dot"],
},
{
name: "Letter delimiter",
type: "option",
value: LETTER_DELIM_OPTIONS,
},
{
name: "Word delimiter",
type: "option",
value: WORD_DELIM_OPTIONS,
},
];
} | /**
* ToMorseCode constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToMorseCode.tsx#L65-L92 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToMorseCode.run | run(input, args) {
const format = args[0].split("/");
const dash = format[0];
const dot = format[1];
const letterDelim = Utils.charRep(args[1]);
const wordDelim = Utils.charRep(args[2]);
input = input.split(/\r?\n/);
input = Array.prototype.map.call(input, function (line) {
let words = line.split(/ +/);
words = Array.prototype.map.call(words, function (word) {
const letters = Array.prototype.map.call(word, function (character) {
const letter = character.toUpperCase();
if (typeof MORSE_TABLE[letter] == "undefined") {
return "";
}
return MORSE_TABLE[letter];
});
return letters.join("<ld>");
});
line = words.join("<wd>");
return line;
});
input = input.join("\n");
input = input.replace(/<dash>|<dot>|<ld>|<wd>/g, function (match) {
switch (match) {
case "<dash>":
return dash;
case "<dot>":
return dot;
case "<ld>":
return letterDelim;
case "<wd>":
return wordDelim;
}
});
return input;
} | /**
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToMorseCode.tsx#L99-L141 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToOctal.constructor | constructor() {
super();
this.name = "To Octal";
this.module = "Default";
// this.description =
// "Converts the input string to octal bytes separated by the specified delimiter.<br><br>e.g. The UTF-8 encoded string <code>Γειά σου</code> becomes <code>316 223 316 265 316 271 316 254 40 317 203 316 277 317 205</code>";
// this.infoURL = "https://wikipedia.org/wiki/Octal";
this.inputType = "byteArray";
this.outputType = "string";
this.args = [
{
name: "Delimiter",
type: "option",
value: DELIM_OPTIONS,
},
];
} | /**
* ToOctal constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToOctal.tsx#L52-L69 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToOctal.run | run(input, args) {
const delim = Utils.charRep(args[0] || "Space");
return input.map((val) => val.toString(8)).join(delim);
} | /**
* @param {byteArray} input
* @param {Object[]} args
* @returns {string}
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToOctal.tsx#L76-L79 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToSnakeCase.constructor | constructor() {
super();
this.name = "To Snake case";
this.module = "Code";
// this.description =
// "Converts the input string to snake case.\n<br><br>\nSnake case is all lower case with underscores as word boundaries.\n<br><br>\ne.g. this_is_snake_case\n<br><br>\n'Attempt to be context aware' will make the operation attempt to nicely transform variable and function names.";
// this.infoURL = "https://wikipedia.org/wiki/Snake_case";
this.inputType = "string";
this.outputType = "string";
this.args = [
{
name: "Attempt to be context aware",
type: "boolean",
value: false,
},
];
} | /**
* ToSnakeCase constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToSnakeCase.tsx#L52-L69 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToSnakeCase.run | run(input, args) {
const smart = args[0];
if (smart) {
return replaceVariableNames(input, snakeCase);
} else {
return snakeCase(input);
}
} | /**
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToSnakeCase.tsx#L76-L84 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToUpperCase.constructor | constructor() {
super();
this.name = "To Upper case";
this.module = "Default";
// this.description =
// "Converts the input string to upper case, optionally limiting scope to only the first character in each word, sentence or paragraph.";
this.inputType = "string";
this.outputType = "string";
this.args = [
{
name: "Scope",
type: "option",
value: ["All", "Word", "Sentence", "Paragraph"],
},
];
} | /**
* ToUpperCase constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToUpperCase.tsx#L53-L69 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToUpperCase.run | run(input, args) {
if (!args || args.length === 0) {
throw new OperationError("No capitalization scope was provided.");
}
const scope = args[0];
if (scope === "All") {
return input.toUpperCase();
}
const scopeRegex = {
Word: /(\b\w)/gi,
Sentence: /(?:\.|^)\s*(\b\w)/gi,
Paragraph: /(?:\n|^)\s*(\b\w)/gi,
}[scope];
if (scopeRegex === undefined) {
throw new OperationError("Unrecognized capitalization scope");
}
// Use the regex to capitalize the input
return input.replace(scopeRegex, function (m) {
return m.toUpperCase();
});
} | /**
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToUpperCase.tsx#L76-L101 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToUpperCase.highlight | highlight(pos, args) {
return pos;
} | /**
* Highlight To Upper case
*
* @param {Object[]} pos
* @param {number} pos[].start
* @param {number} pos[].end
* @param {Object[]} args
* @returns {Object[]} pos
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToUpperCase.tsx#L112-L114 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | ToUpperCase.highlightReverse | highlightReverse(pos, args) {
return pos;
} | /**
* Highlight To Upper case in reverse
*
* @param {Object[]} pos
* @param {number} pos[].start
* @param {number} pos[].end
* @param {Object[]} args
* @returns {Object[]} pos
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/ToUpperCase.tsx#L125-L127 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | TypeScriptBeautify.constructor | constructor() {
super();
this.module = "Code";
this.inputType = "string";
this.outputType = "string";
this.args = [
];
} | /**
* MarkdownBeautify constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/TypeScriptBeautify.tsx#L53-L61 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | URLDecode.constructor | constructor() {
super();
this.name = "URL Decode";
this.module = "URL";
// this.description =
// "Converts URI/URL percent-encoded characters back to their raw values.<br><br>e.g. <code>%3d</code> becomes <code>=</code>";
// this.infoURL = "https://wikipedia.org/wiki/Percent-encoding";
this.inputType = "string";
this.outputType = "string";
this.args = [];
this.checks = [
{
pattern: ".*(?:%[\\da-f]{2}.*){4}",
flags: "i",
args: [],
},
];
} | /**
* URLDecode constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/URLDecode.tsx#L46-L64 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | URLDecode.run | run(input, args) {
const data = input.replace(/\+/g, "%20");
try {
return decodeURIComponent(data);
} catch (err) {
return unescape(data);
}
} | /**
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/URLDecode.tsx#L71-L78 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | URLEncode.getOptDetail | public getOptDetail(): OptDetail {
return {
// provide information
relatedID: 'url',
config: {
"module": "Default",
"description": "Encodes problematic characters into percent-encoding, a format supported by URIs/URLs.<br><br>e.g. <code>=</code> becomes <code>%3d</code>",
"infoURL": "https://wikipedia.org/wiki/Percent-encoding",
"inputType": "string",
"outputType": "string",
"flowControl": false,
"manualBake": false,
"args": [
{
"name": Dot("e7Afj0xo2", "Encode all special chars"),
"type": "boolean",
"value": false,
},
]
},
optName: Dot("btUdVQx8duc", "{0} Encode", 'URL'),
optDescription: Dot("btUVqx8uc", "Encodes problematic characters into percent-encoding, a format supported by URIs/URLs."),
exampleInput: "test 12345",
exampleOutput: "test%2012345",
infoURL: "https://wikipedia.org/wiki/Percent-encoding",
nousenouseID: "urlencode",
}
} | // impl getOptDetail | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/URLEncode.tsx#L23-L50 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | URLEncode.constructor | constructor() {
super();
this.name = "URL Encode";
this.module = "URL";
// this.description =
// "Encodes problematic characters into percent-encoding, a format supported by URIs/URLs.<br><br>e.g. <code>=</code> becomes <code>%3d</code>";
// this.infoURL = "https://wikipedia.org/wiki/Percent-encoding";
this.inputType = "string";
this.outputType = "string";
this.args = [
{
name: Dot("0NSerY3oe", "Encode all special chars"),
type: "boolean",
value: false,
},
];
} | /**
* URLEncode constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/URLEncode.tsx#L55-L72 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | URLEncode.run | run(input, args) {
const encodeAll = args[0];
return encodeAll ? this.encodeAllChars(input) : encodeURI(input);
} | /**
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/URLEncode.tsx#L79-L82 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | URLEncode.encodeAllChars | encodeAllChars(str) {
// TODO Do this programmatically
return encodeURIComponent(str)
.replace(/!/g, "%21")
.replace(/#/g, "%23")
.replace(/'/g, "%27")
.replace(/\(/g, "%28")
.replace(/\)/g, "%29")
.replace(/\*/g, "%2A")
.replace(/-/g, "%2D")
.replace(/\./g, "%2E")
.replace(/_/g, "%5F")
.replace(/~/g, "%7E");
} | /**
* Encode characters in URL outside of encodeURI() function spec
*
* @param {string} str
* @returns {string}
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/URLEncode.tsx#L90-L103 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | XMLBeautify.constructor | constructor() {
super();
this.module = "Code";
this.inputType = "string";
this.outputType = "string";
this.args = [
{
"name": Dot("isti", "Indent string"),
"type": "binaryShortString",
"value": "\\t"
}
];
} | /**
* XMLBeautify constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/XMLBeautify.tsx#L68-L82 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | XMLBeautify.run | run(input, args) {
const indentStr = args[0];
return vkbeautify.xml(input, indentStr);
} | /**
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/XMLBeautify.tsx#L89-L93 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | XMLMinify.constructor | constructor() {
super();
this.module = "Code";
this.inputType = "string";
this.outputType = "string";
this.args = [
{
name: "Preserve comments",
type: "boolean",
value: false,
},
];
} | /**
* XMLMinify constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/XMLMinify.tsx#L65-L79 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | XMLMinify.run | run(input, args) {
const preserveComments = args[0];
return vkbeautify.xmlmin(input, preserveComments);
} | /**
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/XMLMinify.tsx#L86-L89 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | XMLToJSON.constructor | constructor() {
super();
this.name = "XML to JSON";
this.module = "Default";
this.inputType = "JSON";
this.outputType = "string";
this.args = [
];
} | /**
* XMLToJSON constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/XMLToJSON.tsx#L46-L56 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | XMLToJSON.run | run(input, args) {
let val = xmlutils.json2xml.getRawJsonFromStructXml(input)
return val
} | /**
* @param {JSON} input
* @param {Object[]} args
* @returns {string}
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/XMLToJSON.tsx#L67-L70 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | YamlBeautify.constructor | constructor() {
super();
this.module = "Code";
this.inputType = "string";
this.outputType = "string";
this.args = [
// {
// "name": Dot("isti", "Indent string"),
// "type": "binaryShortString",
// "value": " "
// }
];
} | /**
* YamlBeautify constructor
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/YAMLBeautify.tsx#L69-L83 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | YamlBeautify.run | run(input, args) {
const indentStr = args[0];
let exts = {
parser: "yaml",
plugins: [parserYaml],
}
let results = prettier.format(input, exts);
return results;
} | /**
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/ | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/impl/conversion/YAMLBeautify.tsx#L90-L99 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | getXmlFactory | function getXmlFactory() {
function _getAllAttr(node) {
var attributes = node.attributes;
if (node.hasAttributes() === false) {
return {};
}
var result = {};
for (let attr of attributes) {
result[attr.name] = attr.value;
}
return result;
}
function _getContent(node) {
let html = node.innerHTML;
if (_.isNil(html)) {
return "";
}
return html;
}
function _getTagName(node) {
return node.tagName;
}
function _getChildren(parent) {
var childNodes = parent.childNodes;
var children: any = [];
for (let child of childNodes) {
if (child.nodeType !== 1) {
continue;
} else {
children.push(child);
}
}
return children;
}
function _getEachNodeInfo(child) {
var eachChildInfo: any = {
tagName: _getTagName(child),
attr: _getAllAttr(child),
};
var subChildren = _getChildren(child);
if (subChildren.length !== 0) {
eachChildInfo.children = _getChildrenList(subChildren);
}
if (_.isNil(eachChildInfo.children)) {
eachChildInfo.content = _getContent(child);
}
return eachChildInfo;
}
function _getChildrenList(children) {
var resultArr: any[] = [];
for (var child of children) {
let eachChildInfo: any = _getEachNodeInfo(child);
resultArr.push(eachChildInfo);
}
return resultArr;
}
function _renderXMLTree(parent) {
var parentEle = document.createElement(parent.tagName);
//append attributes
if (parent.attr) {
var attributes = parent.attr;
for (var attrName in attributes) {
var attrVal = attributes[attrName];
parentEle.setAttribute(attrName, attrVal);
}
}
if (!_.isNil(parent.children)) {
var children = parent.children;
for (var child of children) {
parentEle.appendChild(_renderXMLTree(child));
}
} else {
if (!_.isNil(parent.content)) {
parentEle.appendChild(document.createTextNode(parent.content));
}
}
return parentEle;
}
function getXmlObject(xmlString) {
// return $(xmlString)[0];
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, "text/xml");
return xmlDoc;
}
let crtref = {
xml2json: {
getStructJsonFromRawXml(xmlString) {
var doc = getXmlObject(xmlString);
if (_.isNil(doc)) {
return {};
}
return _getEachNodeInfo(doc.childNodes[0]);
},
getRawXmlFromStructJson(json) {
return _renderXMLTree(json);
},
},
json2xml: {
getStructXmlFromRawJson(rawJson) {
let crtRootName = "root";
let crtLayer = utils.createJsonMetaLayerData({ rawdata: rawJson });
let xmlStyleFormatLayer = crtref.reFormatXmlStyleFromRawLayer(
crtLayer.value,
);
xmlStyleFormatLayer = {
tagName: crtRootName,
children: xmlStyleFormatLayer,
};
let rawXml =
crtref.xml2json.getRawXmlFromStructJson(xmlStyleFormatLayer);
// let finxmlstr = new XML(rawXml).toXMLString(); //
let finxmlstr = `<?xml version="1.0" encoding="utf-8" ?>\n${rawXml.outerHTML}`;
// finxmlstr = utils.formatxml(finxmlstr);
return finxmlstr;
},
getRawJsonFromStructXml(structXml) {
let crtStructJson = crtref.xml2json.getStructJsonFromRawXml(structXml);
let crtFinalJson = crtref.flatternStructJsonToKV(crtStructJson);
return crtFinalJson;
},
},
flatternStructJsonToKV(crtJson, obj = {}) {
let { tagName, children, attr, content } = crtJson;
if (notempty(children)) {
let subObj = {};
obj[tagName] = subObj;
for (let idx in children) {
let item = children[idx];
crtref.flatternStructJsonToKV(item, subObj);
}
if (notempty(content)) {
obj[tagName + "_text"] = content;
}
} else {
obj[tagName] = content;
}
if (notempty(attr)) {
obj[tagName + "_attr"] = attr;
}
return obj;
},
reFormatXmlStyleFromRawLayer(layerArr) {
let finReturnArr: any = [];
if (_.isNil(layerArr) || !utils.isArray(layerArr)) {
return layerArr;
}
for (let i = 0; i < layerArr.length; i++) {
let crtLayerObject = layerArr[i];
let { type, key, value, leaf } = crtLayerObject;
let crtXmlReturnObj: any = {
tagName: key,
attr: {},
};
let shouldSkipFinAdd = false;
if (leaf) {
crtXmlReturnObj.content = value;
} else {
let finChildrenForTmp = crtref.reFormatXmlStyleFromRawLayer(value);
if (type == "Array") {
shouldSkipFinAdd = true;
console.log("finChildrenForTmp", finChildrenForTmp);
for (let eachChild of finChildrenForTmp) {
finReturnArr.push(
_.merge({}, crtXmlReturnObj, {
children: eachChild.children,
}),
);
}
} else {
crtXmlReturnObj.children = finChildrenForTmp;
}
}
finReturnArr.push(crtXmlReturnObj);
}
return finReturnArr;
},
};
return crtref;
} | // xml | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/impl/tools/other/xmlutils.ts#L118-L304 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | checkDefaultsDeep | function checkDefaultsDeep(
value: any,
srcValue: any,
key: string,
object: any,
source: any
) {
if (_.isNil(value)) {
return srcValue;
}
if (_.isArray(value) || _.isArray(srcValue)) {
return value;
}
return value;
} | // _.defaultsDeep(newState, state); | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/[lang]/client/src/utils/SyncStateUtils.tsx#L59-L73 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
LafTools | github_2023 | work7z | typescript | setTheme | let setTheme = (theme: ThemeType) => {
localStorage.setItem(key, theme)
handleTheme(theme)
_setTheme(theme)
} | // let [theme, _setTheme] = useState<ThemeType>( | https://github.com/work7z/LafTools/blob/ec1910c3ddf2827b529e4e1f0bed06d762f33b4a/modules/web2/app/__CORE__/components/LightDarkButton/theme.tsx#L33-L37 | ec1910c3ddf2827b529e4e1f0bed06d762f33b4a |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | RestaurantService.registerRestaurant | async registerRestaurant(registerDto: RegisterDto, response: Response) {
const { name, country, city, address, email, phone_number, password } =
registerDto as Restaurant;
const isEmailExist = await this.prisma.restaurant.findUnique({
where: {
email,
},
});
if (isEmailExist) {
throw new BadRequestException(
"Restaurant already exist with this email!"
);
}
const usersWithPhoneNumber = await this.prisma.restaurant.findUnique({
where: {
phone_number,
},
});
if (usersWithPhoneNumber) {
throw new BadRequestException(
"Restaurant already exist with this phone number!"
);
}
const hashedPassword = await bcrypt.hash(password, 10);
const restaurant: Restaurant = {
name,
country,
city,
address,
email,
phone_number,
password: hashedPassword,
};
const activationToken = await this.createActivationToken(restaurant);
const client_side_uri = this.configService.get<string>("CLIENT_SIDE_URI");
const activation_token = `${client_side_uri}/activate-account/${activationToken}`;
await this.emailService.sendMail({
email,
subject: "Activate your restaurant account!",
template: "./activation-mail",
name,
activation_token,
});
return {
message: "Please check your email to activate your account",
response,
};
} | // register restaurant service | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-restuarants/src/restaurant.service.ts#L31-L88 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | RestaurantService.createActivationToken | async createActivationToken(restaurant: Restaurant) {
const activationToken = this.jwtService.sign(
{
restaurant,
},
{
secret: this.configService.get<string>("JWT_SECRET_KEY"),
expiresIn: "5m",
}
);
return activationToken;
} | // create activation token | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-restuarants/src/restaurant.service.ts#L91-L102 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | RestaurantService.activateRestaurant | async activateRestaurant(activationDto: ActivationDto, response: Response) {
const { activationToken } = activationDto;
const newRestaurant: {
exp: number;
restaurant: Restaurant;
activationToken: string;
} = this.jwtService.verify(activationToken, {
secret: this.configService.get<string>("JWT_SECRET_KEY"),
} as JwtVerifyOptions);
if (newRestaurant?.exp * 1000 < Date.now()) {
throw new BadRequestException("Invalid activation code");
}
const { name, country, city, phone_number, password, email, address } =
newRestaurant.restaurant;
const existRestaurant = await this.prisma.restaurant.findUnique({
where: {
email,
},
});
if (existRestaurant) {
throw new BadRequestException(
"Restaurant already exist with this email!"
);
}
const restaurant = await this.prisma.restaurant.create({
data: {
name,
email,
address,
country,
city,
phone_number,
password,
},
});
return { restaurant, response };
} | // activation restaurant | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-restuarants/src/restaurant.service.ts#L105-L148 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | RestaurantService.LoginRestuarant | async LoginRestuarant(loginDto: LoginDto) {
const { email, password } = loginDto;
const restaurant = await this.prisma.restaurant.findUnique({
where: {
email,
},
});
if (
restaurant &&
(await this.comparePassword(password, restaurant.password))
) {
const tokenSender = new TokenSender(this.configService, this.jwtService);
return tokenSender.sendToken(restaurant);
} else {
return {
user: null,
accessToken: null,
refreshToken: null,
error: {
message: "Invalid email or password",
},
};
}
} | // Login restaurant | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-restuarants/src/restaurant.service.ts#L151-L176 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | RestaurantService.comparePassword | async comparePassword(
password: string,
hashedPassword: string
): Promise<boolean> {
return await bcrypt.compare(password, hashedPassword);
} | // compare with hashed password | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-restuarants/src/restaurant.service.ts#L179-L184 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | RestaurantService.getLoggedInRestaurant | async getLoggedInRestaurant(req: any) {
const restaurant = req.restaurant;
const refreshToken = req.refreshtoken;
const accessToken = req.accesstoken;
return { restaurant, accessToken, refreshToken };
} | // get logged in restaurant | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-restuarants/src/restaurant.service.ts#L187-L192 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | RestaurantService.Logout | async Logout(req: any) {
req.restaurant = null;
req.refreshtoken = null;
req.accesstoken = null;
return { message: "Logged out successfully!" };
} | // log out restaurant | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-restuarants/src/restaurant.service.ts#L195-L200 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | FoodsService.createFood | async createFood(createFoodDto: CreateFoodDto, req: any, response: Response) {
try {
const { name, description, price, estimatedPrice, category, images } =
createFoodDto as Food;
const restaurantId = req.restaurant?.id;
let foodImages: Images | any = [];
for (const image of images) {
if (typeof image === "string") {
const data = await this.cloudinaryService.upload(image);
foodImages.push({
public_id: data.public_id,
url: data.secure_url,
});
}
}
const foodData = {
name,
description,
price,
estimatedPrice,
category,
images: {
create: foodImages.map(
(image: { public_id: string; url: string }) => ({
public_id: image.public_id,
url: image.url,
})
),
},
restaurantId,
};
await this.prisma.foods.create({
data: foodData,
});
return { message: "Food Created Successfully!" };
} catch (error) {
return { message: error };
}
} | // create food | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-restuarants/src/foods/foods.service.ts#L32-L75 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | FoodsService.getLoggedInRestuarantFood | async getLoggedInRestuarantFood(req: any, res: Response) {
const restaurantId = req.restaurant?.id;
const foods = await this.prisma.foods.findMany({
where: {
restaurantId,
},
include: {
images: true,
restaurant: true,
},
orderBy: {
createdAt: "desc",
},
});
return { foods };
} | // get all restaurant foods | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-restuarants/src/foods/foods.service.ts#L78-L94 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | FoodsService.deleteFood | async deleteFood(deleteFoodDto: DeleteFoodDto, req: any) {
const restaurantId = req.restaurant?.id;
const food = await this.prisma.foods.findUnique({
where: {
id: deleteFoodDto.id,
},
include: {
restaurant: true,
images: true,
},
});
if (food.restaurant.id !== restaurantId) {
throw Error("Only Restaurant owner can delete food!");
}
// Manually delete the related images
await this.prisma.images.deleteMany({
where: {
foodId: deleteFoodDto.id,
},
});
await this.prisma.foods.delete({
where: {
id: deleteFoodDto.id,
},
});
return { message: "Food Deleted successfully!" };
} | // delete foods of a restaurant | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-restuarants/src/foods/foods.service.ts#L97-L128 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | UsersService.register | async register(registerDto: RegisterDto, response: Response) {
const { name, email, password, phone_number } = registerDto;
const isEmailExist = await this.prisma.user.findUnique({
where: {
email,
},
});
if (isEmailExist) {
throw new BadRequestException('User already exist with this email!');
}
const phoneNumbersToCheck = [phone_number];
const usersWithPhoneNumber = await this.prisma.user.findMany({
where: {
phone_number: {
not: null,
in: phoneNumbersToCheck,
},
},
});
if (usersWithPhoneNumber.length > 0) {
throw new BadRequestException(
'User already exist with this phone number!',
);
}
const hashedPassword = await bcrypt.hash(password, 10);
const user = {
name,
email,
password: hashedPassword,
phone_number,
};
const activationToken = await this.createActivationToken(user);
const activationCode = activationToken.activationCode;
const activation_token = activationToken.token;
await this.emailService.sendMail({
email,
subject: 'Activate your account!',
template: './activation-mail',
name,
activationCode,
});
return { activation_token, response };
} | // register user service | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-users/src/user.service.ts#L34-L87 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | UsersService.createActivationToken | async createActivationToken(user: UserData) {
const activationCode = Math.floor(1000 + Math.random() * 9000).toString();
const token = this.jwtService.sign(
{
user,
activationCode,
},
{
secret: this.configService.get<string>('ACTIVATION_SECRET'),
expiresIn: '5m',
},
);
return { token, activationCode };
} | // create activation token | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-users/src/user.service.ts#L90-L104 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | UsersService.activateUser | async activateUser(activationDto: ActivationDto, response: Response) {
const { activationToken, activationCode } = activationDto;
const newUser: { user: UserData; activationCode: string } =
this.jwtService.verify(activationToken, {
secret: this.configService.get<string>('ACTIVATION_SECRET'),
} as JwtVerifyOptions) as { user: UserData; activationCode: string };
if (newUser.activationCode !== activationCode) {
throw new BadRequestException('Invalid activation code');
}
const { name, email, password, phone_number } = newUser.user;
const existUser = await this.prisma.user.findUnique({
where: {
email,
},
});
if (existUser) {
throw new BadRequestException('User already exist with this email!');
}
const user = await this.prisma.user.create({
data: {
name,
email,
password,
phone_number,
},
});
return { user, response };
} | // activation user | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-users/src/user.service.ts#L107-L141 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | UsersService.Login | async Login(loginDto: LoginDto) {
const { email, password } = loginDto;
const user = await this.prisma.user.findUnique({
where: {
email,
},
});
if (user && (await this.comparePassword(password, user.password))) {
const tokenSender = new TokenSender(this.configService, this.jwtService);
return tokenSender.sendToken(user);
} else {
return {
user: null,
accessToken: null,
refreshToken: null,
error: {
message: 'Invalid email or password',
},
};
}
} | // Login service | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-users/src/user.service.ts#L144-L165 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | UsersService.comparePassword | async comparePassword(
password: string,
hashedPassword: string,
): Promise<boolean> {
return await bcrypt.compare(password, hashedPassword);
} | // compare with hashed password | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-users/src/user.service.ts#L168-L173 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | UsersService.generateForgotPasswordLink | async generateForgotPasswordLink(user: User) {
const forgotPasswordToken = this.jwtService.sign(
{
user,
},
{
secret: this.configService.get<string>('FORGOT_PASSWORD_SECRET'),
expiresIn: '5m',
},
);
return forgotPasswordToken;
} | // generate forgot password link | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-users/src/user.service.ts#L176-L187 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | UsersService.forgotPassword | async forgotPassword(forgotPasswordDto: ForgotPasswordDto) {
const { email } = forgotPasswordDto;
const user = await this.prisma.user.findUnique({
where: {
email,
},
});
if (!user) {
throw new BadRequestException('User not found with this email!');
}
const forgotPasswordToken = await this.generateForgotPasswordLink(user);
const resetPasswordUrl =
this.configService.get<string>('CLIENT_SIDE_URI') +
`/reset-password?verify=${forgotPasswordToken}`;
await this.emailService.sendMail({
email,
subject: 'Reset your Password!',
template: './forgot-password',
name: user.name,
activationCode: resetPasswordUrl,
});
return { message: `Your forgot password request succesful!` };
} | // forgot password | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-users/src/user.service.ts#L190-L216 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | UsersService.resetPassword | async resetPassword(resetPasswordDto: ResetPasswordDto) {
const { password, activationToken } = resetPasswordDto;
const decoded = await this.jwtService.decode(activationToken);
if (!decoded || decoded?.exp * 1000 < Date.now()) {
throw new BadRequestException('Invalid token!');
}
const hashedPassword = await bcrypt.hash(password, 10);
const user = await this.prisma.user.update({
where: {
id: decoded.user.id,
},
data: {
password: hashedPassword,
},
});
return { user };
} | // reset password | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-users/src/user.service.ts#L219-L240 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | UsersService.getLoggedInUser | async getLoggedInUser(req: any) {
const user = req.user;
const refreshToken = req.refreshtoken;
const accessToken = req.accesstoken;
return { user, refreshToken, accessToken };
} | // eslint-disable-next-line @typescript-eslint/no-explicit-any | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-users/src/user.service.ts#L244-L249 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | UsersService.Logout | async Logout(req: any) {
req.user = null;
req.refreshtoken = null;
req.accesstoken = null;
return { message: 'Logged out successfully!' };
} | // eslint-disable-next-line @typescript-eslint/no-explicit-any | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-users/src/user.service.ts#L253-L258 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | UsersService.getUsers | async getUsers() {
return this.prisma.user.findMany({});
} | // get all users service | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-users/src/user.service.ts#L261-L263 | c26ac7f3873ee965a367d1836386686f5336bacf |
Food-Delivery-WebApp | github_2023 | shahriarsajeeb | typescript | AuthGuard.updateAccessToken | private async updateAccessToken(req: any): Promise<void> {
try {
const refreshTokenData = req.headers.refreshtoken as string;
const decoded = this.jwtService.decode(refreshTokenData);
const expirationTime = decoded.exp * 1000;
if (expirationTime < Date.now()) {
throw new UnauthorizedException(
'Please login to access this resource!',
);
}
const user = await this.prisma.user.findUnique({
where: {
id: decoded.id,
},
});
const accessToken = this.jwtService.sign(
{ id: user.id },
{
secret: this.config.get<string>('ACCESS_TOKEN_SECRET'),
expiresIn: '5m',
},
);
const refreshToken = this.jwtService.sign(
{ id: user.id },
{
secret: this.config.get<string>('REFRESH_TOKEN_SECRET'),
expiresIn: '7d',
},
);
req.accesstoken = accessToken;
req.refreshtoken = refreshToken;
req.user = user;
} catch (error) {
throw new UnauthorizedException(error.message);
}
} | // eslint-disable-next-line @typescript-eslint/no-explicit-any | https://github.com/shahriarsajeeb/Food-Delivery-WebApp/blob/c26ac7f3873ee965a367d1836386686f5336bacf/apps/api-users/src/guards/auth.guard.ts#L45-L87 | c26ac7f3873ee965a367d1836386686f5336bacf |
OpenAssistantGPT | github_2023 | OpenAssistantGPT | typescript | concatChunks | function concatChunks(chunks: Uint8Array[], totalLength: number) {
const concatenatedChunks = new Uint8Array(totalLength);
let offset = 0;
for (const chunk of chunks) {
concatenatedChunks.set(chunk, offset);
offset += chunk.length;
}
chunks.length = 0;
return concatenatedChunks;
} | // concatenates all the chunks into a single Uint8Array | https://github.com/OpenAssistantGPT/OpenAssistantGPT/blob/644f2a5f68125d8bdbd72b6d20b0f19ced1bb2bc/lib/read-data-stream.ts#L6-L17 | 644f2a5f68125d8bdbd72b6d20b0f19ced1bb2bc |
hsr-optimizer | github_2023 | fribbels | typescript | readBuffer | async function readBuffer(offset: number, gpuReadBuffer: GPUBuffer, gpuContext: GpuExecutionContext, elementOffset: number = 0) {
await gpuReadBuffer.mapAsync(GPUMapMode.READ, elementOffset)
const arrayBuffer = gpuReadBuffer.getMappedRange(elementOffset * 4)
const array = new Float32Array(arrayBuffer)
const resultsQueue = gpuContext.resultsQueue
let top = resultsQueue.top()?.value ?? 0
let limit = gpuContext.BLOCK_SIZE * gpuContext.CYCLES_PER_INVOCATION - elementOffset
const maxPermNumber = offset + gpuContext.BLOCK_SIZE * gpuContext.CYCLES_PER_INVOCATION - elementOffset
const diff = gpuContext.permutations - maxPermNumber
if (diff < 0) {
limit += diff
}
const indexOffset = offset + elementOffset
if (resultsQueue.size() >= gpuContext.RESULTS_LIMIT) {
for (let j = limit - 1; j >= 0; j--) {
const value = array[j]
if (value < 0) {
j += value + 1
continue
}
if (value <= top) continue
top = resultsQueue.fixedSizePushOvercapped({
index: indexOffset + j,
value: value,
}).value
}
} else {
for (let j = limit - 1; j >= 0; j--) {
const value = array[j]
if (value < 0) {
j += value + 1
continue
}
if (value <= top && resultsQueue.size() >= gpuContext.RESULTS_LIMIT) {
continue
}
resultsQueue.fixedSizePush({
index: indexOffset + j,
value: value,
})
top = resultsQueue.top()!.value
}
}
if (gpuContext.DEBUG) {
debugWebgpuOutput(gpuContext, arrayBuffer)
}
} | // eslint-disable-next-line | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/gpu/webgpuOptimizer.ts#L110-L164 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | getHash | function getHash(key: string) {
let hash1 = 5381
let hash2 = 5381
for (let i = 0; i < key.length; i += 2) {
hash1 = Math.imul((hash1 << 5) + hash1, 1) ^ key.charCodeAt(i)
if (i === key.length - 1)
break
hash2 = Math.imul((hash2 << 5) + hash2, 1) ^ key.charCodeAt(i + 1)
}
return Math.imul(hash1 + Math.imul(hash2, 1566083941), 1)
} | // from the readme on Dim's old github repo | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/i18n/generateTranslations.ts#L302-L312 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | readCharacterV3 | function readCharacterV3(character: V4ParserCharacter & {
key: string
},
lightCones: (V4ParserLightCone & {
key: string
})[],
trailblazer,
path) {
let lightCone: (V4ParserLightCone & {
key: string
}) | undefined
if (lightCones) {
if (character.key.startsWith('Trailblazer')) {
lightCone = lightCones.find((x) => x.location === character.key)
|| lightCones.find((x) => x.location.startsWith('Trailblazer'))
} else {
lightCone = lightCones.find((x) => x.location === character.key)
}
}
let characterId
if (character.key.startsWith('Trailblazer')) {
characterId = getTrailblazerId(character.key, trailblazer, path)
} else {
characterId = characterList.find((x) => x.name === character.key)?.id
}
const lcKey = lightCone?.key
const lightConeId = lightConeList.find((x) => x.name === lcKey)?.id
if (!characterId) return null
return {
characterId: characterId,
characterLevel: character.level || 80,
characterEidolon: character.eidolon || 0,
lightCone: lightConeId || null,
lightConeLevel: lightCone?.level || 80,
lightConeSuperimposition: lightCone?.superimposition || 1,
}
} | // ================================================== V3 ================================================== | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/importer/kelzFormatParser.tsx#L179-L219 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | readCharacterV4 | function readCharacterV4(character: V4ParserCharacter, lightCones: V4ParserLightCone[]) {
let lightCone: V4ParserLightCone | undefined
if (lightCones) {
// TODO: don't search on an array
lightCone = lightCones.find((x) => x.location === character.id)
}
const characterId = character.id
const lightConeId = lightCone?.id
if (!characterId) return null
return {
characterId: characterId,
characterLevel: character.level || 80,
characterEidolon: character.eidolon || 0,
lightCone: lightConeId || null,
lightConeLevel: lightCone?.level || 80,
lightConeSuperimposition: lightCone?.superimposition || 1,
}
} | // ================================================== V4 ================================================== | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/importer/kelzFormatParser.tsx#L257-L278 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | FixedSizePriorityQueue.fixedSizePushOvercapped | fixedSizePushOvercapped(item: T): T {
this.push(item)
return this.pop()!
} | // If we already know the queue is full, skip the checks | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/optimization/fixedSizePriorityQueue.ts#L29-L32 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | relicSetAllowListToIndices | function relicSetAllowListToIndices(arr: number[]) {
const out: number[] = []
for (let i = 0; i < arr.length; i++) {
while (arr[i]) {
arr[i]--
out.push(i)
}
}
return out
} | // [0, 0, 0, 2, 0, 2] => [3, 3, 5, 5] | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/optimization/relicSetSolver.ts#L79-L89 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | fillRelicSetArrPossibilities | function fillRelicSetArrPossibilities(arr: number[], len: number) {
const out: number[][] = []
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
const newArr: number[] = Utils.arrayOfZeroes(4)
newArr[0] = arr[0]
newArr[1] = arr[1]
newArr[2] = i
newArr[3] = j
out.push(newArr)
}
}
return out
} | // [5, 5] => [[5,5,0,0], [5,5,0,1], [5,5,1,1], [5,5,1,2], ...] | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/optimization/relicSetSolver.ts#L92-L107 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | convertRelicSetIndicesTo1D | function convertRelicSetIndicesTo1D(setIndices: number[][]) {
const len = Constants.SetsRelicsNames.length
if (setIndices.length == 0) {
return Utils.arrayOfValue(Math.pow(len, 4), 1)
}
const arr = Utils.arrayOfZeroes(Math.pow(len, 4))
for (let i = 0; i < setIndices.length; i++) {
const y = setIndices[i] // [5,5,2,3]
const permutations = permutator(y)
for (const x of permutations) {
const index1D = x[0] + x[1] * Math.pow(len, 1) + x[2] * Math.pow(len, 2) + x[3] * Math.pow(len, 3)
arr[index1D] = 1
}
}
return arr
} | // [[5,5,0,0], [5,5,0,1], [5,5,1,1], [5,5,1,2], ...] => [0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0..] | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/optimization/relicSetSolver.ts#L110-L128 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | sortSubstats | function sortSubstats(relic: Relic) {
relic.substats = relic.substats.sort((a, b) => substatToOrder[a.stat] - substatToOrder[b.stat])
} | // Relic substats are always sorted in the predefined order above when the user logs out. | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicAugmenter.ts#L71-L73 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | fixAugmentedStats | function fixAugmentedStats(relics: Relic[]) {
return relics.map((relic) => {
for (const stat of Object.values(Constants.Stats)) {
if (!relic.augmentedStats) continue
relic.augmentedStats[stat] = relic.augmentedStats[stat] || 0
if (!Utils.isFlat(stat)) {
if (relic.augmentedStats.mainStat == stat) {
relic.augmentedStats.mainValue = relic.augmentedStats.mainValue / 100
}
relic.augmentedStats[stat] = relic.augmentedStats[stat] / 100
}
}
return relic
})
} | // Changes the augmented stats percents to decimals | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicAugmenter.ts#L76-L91 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | search | function search(sum: number, counts: StatRolls, index: number): void {
if (index === Object.keys(incrementOptions).length) {
if (Math.abs(sum - currentStat) < Math.abs(closestSum - currentStat)) {
closestSum = sum
closestCounts = { ...counts }
}
return
}
const increment: keyof IncrementOptions = Object.keys(incrementOptions)[index] as keyof IncrementOptions
for (let i = 0; sum + i * incrementOptions[increment] <= currentStat + 0.01; i++) {
counts[increment] = i
search(sum + i * incrementOptions[increment], counts, index + 1)
}
} | // TODO: There is a bug in this where it potentially overcounts the number of rolls when ambiguous. | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicRollGrader.ts#L23-L37 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | RelicScorer.scoreFutureRelic | static scoreFutureRelic(relic: Relic, characterId: CharacterId, withMeta: boolean = false) {
return new RelicScorer().getFutureRelicScore(relic, characterId, withMeta)
} | /**
* returns the current score of the relic, as well as the best, worst, and average scores when at max enhance\
* meta field includes the ideal added and/or upgraded substats for the relic
*/ | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L138-L140 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | RelicScorer.scoreCurrentRelic | static scoreCurrentRelic(relic: Relic, id: CharacterId): RelicScoringResult {
return new RelicScorer().getCurrentRelicScore(relic, id)
} | /**
* returns the current score, mainstat score, and rating for the relic\
* additionally returns the part, and scoring metadata
*/ | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L146-L148 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | RelicScorer.scoreCharacterWithRelics | static scoreCharacterWithRelics(character: Character, relics: Relic[]) {
return new RelicScorer().scoreCharacterWithRelics(character, relics)
} | /**
* returns a score (number) and rating (string) for the character, and the scored relics
* @param character character object to score
* @param relics relics to score against the character
*/ | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L155-L157 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | RelicScorer.scoreCharacter | static scoreCharacter(character: Character) {
return new RelicScorer().scoreCharacter(character)
} | /**
* returns a score (number) and rating (string) for the character, and the scored equipped relics
* @param character character object to score
*/ | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L163-L165 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | RelicScorer.scoreRelicPotential | static scoreRelicPotential(relic: Relic, characterId: CharacterId, withMeta: boolean = false) {
return new RelicScorer().scoreRelicPotential(relic, characterId, withMeta)
} | /**
* evaluates the max, min, and avg potential optimalities of a relic
* @param relic relic to evaluate
* @param characterId id of character to evaluate against
* @param withMeta whether or not to include the character scoringMetadata in the return
*/ | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L173-L175 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | RelicScorer.getRelicScoreMeta | getRelicScoreMeta(id: CharacterId): ScoringMetadata {
let scoringMetadata = this.characterRelicScoreMetas.get(id)
if (scoringMetadata) return scoringMetadata
scoringMetadata = Utils.clone(DB.getScoringMetadata(id)) as ScoringMetadata
const defaultScoringMetadata = DB.getMetadata().characters[id].scoringMetadata
scoringMetadata.category = getScoreCategory(defaultScoringMetadata, { stats: scoringMetadata.stats })
scoringMetadata.stats[Constants.Stats.HP] = scoringMetadata.stats[Constants.Stats.HP_P] * flatStatScaling.HP
scoringMetadata.stats[Constants.Stats.ATK] = scoringMetadata.stats[Constants.Stats.ATK_P] * flatStatScaling.ATK
scoringMetadata.stats[Constants.Stats.DEF] = scoringMetadata.stats[Constants.Stats.DEF_P] * flatStatScaling.DEF
// Object.entries strips type information down to primitive types :/ (e.g. here StatsValues becomes string)
// @ts-ignore
scoringMetadata.sortedSubstats = (Object.entries(scoringMetadata.stats) as [SubStats, number][])
.filter((x) => possibleSubstats.has(x[0]))
.sort((a, b) => {
return b[1] * normalization[b[0]] * SubStatValues[b[0]][5].high - a[1] * normalization[a[0]] * SubStatValues[a[0]][5].high
})
scoringMetadata.groupedSubstats = new Map()
for (const [stat, weight] of scoringMetadata.sortedSubstats) {
if (!scoringMetadata.groupedSubstats.has(weight)) {
scoringMetadata.groupedSubstats.set(weight, [])
}
scoringMetadata.groupedSubstats.get(weight)!.push(stat)
}
for (const stats of scoringMetadata.groupedSubstats.values()) {
stats.sort()
}
let weightedDmgTypes = 0
Object.entries(scoringMetadata.stats).forEach(([stat, value]) => {
// @ts-ignore
if (dmgMainstats.includes(stat) && value) weightedDmgTypes++
})
let validDmgMains = 0
scoringMetadata.parts.PlanarSphere.forEach((mainstat) => {
// @ts-ignore
if (dmgMainstats.includes(mainstat)) validDmgMains++
})
if (weightedDmgTypes < 2 && validDmgMains < 2) {
// if they only have 0 / 1 weighted dmg mainstat, we can cheat as their ideal orbs will all score the same
//
const hashParts = [
scoringMetadata.parts.Head,
scoringMetadata.parts.Hands,
scoringMetadata.parts.Body,
scoringMetadata.parts.Feet,
// @ts-ignore
scoringMetadata.parts.PlanarSphere.filter((x) => !dmgMainstats.includes(x)),
scoringMetadata.parts.LinkRope,
]
scoringMetadata.greedyHash = TsUtils.objectHash({ sortedSubstats: scoringMetadata.sortedSubstats, parts: hashParts })
scoringMetadata.hash = TsUtils.objectHash({ ...scoringMetadata.stats, ...scoringMetadata.parts })
} else {
scoringMetadata.greedyHash = TsUtils.objectHash({ stats: scoringMetadata.stats, parts: scoringMetadata.parts })
scoringMetadata.hash = scoringMetadata.greedyHash
}
this.characterRelicScoreMetas.set(id, scoringMetadata)
return scoringMetadata
} | /**
* returns the scoring metadata for the given character
* @param id id of the character who's scoring data is wanted
*/ | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L181-L242 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | RelicScorer.substatScore | substatScore(relic: Relic, id: CharacterId) {
const scoringMetadata = this.getRelicScoreMeta(id)
if (!scoringMetadata || !id || !relic) {
console.warn('substatScore() called but missing 1 or more arguments. relic:', relic, 'meta:', scoringMetadata, 'id:', id)
return {
score: 0,
mainStatScore: 0,
scoringMetadata,
part: relic?.part,
}
}
const weights = scoringMetadata.stats
let score = 0
for (const substat of relic.substats) {
score += substat.value * (weights[substat.stat] || 0) * normalization[substat.stat]
}
const mainStatScore = ((stat, grade, part, metaParts) => {
if (part == Parts.Head || part == Parts.Hands) return 0
let max
switch (grade) {
case 2:
max = 12.8562
break
case 3:
max = 25.8165
break
case 4:
max = 43.1304
break
default:
max = 64.8
}
return max * (metaParts[part].includes(stat) ? 1 : weights[stat])
})(relic.main.stat, relic.grade, relic.part, scoringMetadata.parts)
return {
score,
mainStatScore,
part: relic.part,
scoringMetadata,
}
} | /**
* returns the substat score of the given relic, does not include mainstat bonus
*/ | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L296-L336 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | RelicScorer.scoreOptimalRelic | scoreOptimalRelic(part: Parts, mainstat: MainStats, id: CharacterId) {
let maxScore: number = 0
let fake: Relic
const meta = this.getRelicScoreMeta(id)
const handlingCase = getHandlingCase(meta)
switch (handlingCase) {
case relicPotentialCases.NONE:
maxScore = Infinity// force relic potential and score to be 0 if all substats have 0 weight
break
case relicPotentialCases.HP:
// falls through
case relicPotentialCases.ATK:
// falls through
case relicPotentialCases.DEF: { // same assumption as SINGLE_STAT but needs special handling as there are technically 2 weighted stats here
let substats: subStat[] = []
const stat1 = meta.sortedSubstats[0][0]
const stat2 = meta.sortedSubstats[1][0]
if (part == Constants.Parts.Head && handlingCase == relicPotentialCases.HP
|| part == Constants.Parts.Hands && handlingCase == relicPotentialCases.ATK
) { // we assume % will always score better than flat, hoyo pls no punish
substats = generateSubStats(5, { stat: stat1, value: SubStatValues[stat1][5].high * 6 })
} else {
substats = generateSubStats(5, { stat: stat1, value: SubStatValues[stat1][5].high * 6 }, { stat: stat2, value: SubStatValues[stat2][5].high })
}
fake = fakeRelic(5, 15, part, Constants.Stats.HP_P, substats)// mainstat doesn't influence relevant scoring, just hardcode something in
maxScore = this.substatScore(fake, id).score
}
break
case relicPotentialCases.SINGLE_STAT: { // assume intended use is maximising value in singular weighted stat as substat -> score = score of 6 high rolls
const stat = meta.sortedSubstats[0][0]
const substats = generateSubStats(5, { stat: stat, value: SubStatValues[stat][5].high * 6 })
maxScore = this.substatScore(fakeRelic(5, 15, part, Constants.Stats.HP_P, substats), id).score
}
break
case relicPotentialCases.NORMAL: { // standard handling
let mainStat = '' as MainStats
const optimalMainStats = meta.parts[part] || []
// list of stats, sorted by weight as mainstat in decreasing order
if (optimalMainStats.includes(mainstat) || meta.stats[mainstat] == 1 || !Utils.hasMainStat(part)) {
mainStat = mainstat
} else {
const scoreEntries = (Object.entries(meta.stats) as [StatsValues, number][])
.map((entry) => {
if (optimalMainStats.includes(entry[0]) || meta.stats[entry[0]] == 1) {
return [entry[0], 1] as [StatsValues, number]
} else return [entry[0], entry[1]] as [StatsValues, number]
})
.sort((a, b) => {
// we give the mainstat only stats a score of 6.48 * weight simply to get them in the right area
// the exact score does not matter as long as the final array is still sorted by weight
// @ts-ignore
const scoreA = !possibleSubstats.has(a[0]) ? a[1] * 6.48 : a[1] * normalization[a[0] as SubStats] * SubStatValues[a[0] as SubStats][5].high
// @ts-ignore
const scoreB = !possibleSubstats.has(b[0]) ? b[1] * 6.48 : b[1] * normalization[b[0] as SubStats] * SubStatValues[b[0] as SubStats][5].high
return scoreB - scoreA
})
/*
* Need the specific optimal mainstat to remove it from possible substats. Find it by
* - finding the highest multiplier mainstat of those valid for this relic
* - looking at all stats with this exact multiplier and biasing towards
* 1 - ideal mainstats and
* 2 - mainstats that can't be substats in that order
*/
// First candidate (i.e. has the highest weight)
const possibleMainStats = PartsMainStats[part] as MainStats[]
// @ts-ignore typescript wants name to have the same type as the elements of possibleMainStats
const mainStatIndex = scoreEntries.findIndex(([name, _weight]) => possibleMainStats.includes(name))
const mainStatWeight = scoreEntries[mainStatIndex][1]
mainStat = scoreEntries[mainStatIndex][0] as MainStats
// Worst case, will be overwritten by true values on first loop iteration
let isIdeal = false
let isSubstat = true
// look at all stats of weight equal to the highest weight stat and find any 'better' mainstats
for (let i = mainStatIndex; i < scoreEntries.length; i++) {
const [name, weight] = scoreEntries[i]
if (weight != mainStatWeight) break// sorted by weight, weight no longer equal means all following will be lesser
// @ts-ignore typescript wants name to have the same type as the elements of possibleMainStats
if (!possibleMainStats.includes(name)) continue// check for possible mainstat
const newIsIdeal = optimalMainStats.includes(name)
// @ts-ignore typescript wants name to have the same type as the elements of possibleSubstats
const newIsSubstat = possibleSubstats.has(name)
if (isIdeal && !newIsIdeal) continue// prefer ideal mainstats
if (!isSubstat && newIsSubstat) continue// prefer mainstats that can't be substats
if (isIdeal === newIsIdeal && isSubstat == newIsSubstat) continue
mainStat = name as MainStats
isIdeal = newIsIdeal
isSubstat = newIsSubstat
}
}
const substatScoreEntries = meta.sortedSubstats.filter(([name, _]) => name !== mainStat)
const substats = substatScoreEntries.slice(0, 4)
const subs = generateSubStats(
5, { stat: substats[0][0], value: SubStatValues[substats[0][0]][5].high * 6 }, { stat: substats[1][0], value: SubStatValues[substats[1][0]][5].high }
, { stat: substats[2][0], value: SubStatValues[substats[2][0]][5].high }, { stat: substats[3][0], value: SubStatValues[substats[3][0]][5].high },
)
fake = fakeRelic(5, 15, part, mainStat, subs)
maxScore = this.substatScore(fake, id).score
}
break
}
return maxScore
} | /**
* returns the substat score for the ideal relic\
* handles special cases scoring for when only 1 stat has been weighted by the user
*/ | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L342-L444 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | RelicScorer.scoreFutureRelic | scoreFutureRelic(relic: Relic, id: CharacterId, withMeta: boolean = false) {
if (!id || !relic) {
console.warn('scoreFutureRelic() called but lacking arguments')
return {
current: 0,
best: 0,
average: 0,
worst: 0,
rerollAvg: 0,
idealScore: 1,
meta: {
bestAddedStats: [''],
bestUpgradedStats: [''],
},
substatScore: {
best: 0,
average: 0,
worst: 0,
},
} as FutureScoringResult
}
const meta = this.getRelicScoreMeta(id)
if (!meta.sortedSubstats[0][0]) return { // 0 weighted substats
current: 0,
best: 0,
average: 0,
worst: 0,
rerollAvg: 0,
idealScore: 1,
meta: {
bestAddedStats: [''],
bestUpgradedStats: [''],
},
substatScore: {
best: 0,
average: 0,
worst: 0,
},
} as FutureScoringResult
const maxMainstat = (() => {
switch (relic.grade as 2 | 3 | 4 | 5) {
case 2:
return 12.8562
case 3:
return 25.8165
case 4:
return 43.1304
case 5:
return 64.8
}
})()
const mainstatDeduction = (() => {
if (Utils.hasMainStat(relic.part)) {
return (getMainStatWeight(relic, meta) - 1) * maxMainstat
} else return 0
})()
const availableSubstats = meta.sortedSubstats.filter((x) => x[0] != relic.main.stat && !relic.substats.map((x) => x.stat).includes(x[0]))
const remainingRolls = Math.ceil((maxEnhance(relic.grade as 2 | 3 | 4 | 5) - relic.enhance) / 3) - (4 - relic.substats.length)
const mainstatBonus = mainStatBonus(relic.part, relic.main.stat, meta)
const idealScore = this.getOptimalPartScore(relic.part, relic.main.stat, id)
const current = Math.max(0, (this.substatScore(relic, id).score + mainstatBonus) / idealScore * 100 * percentToScore + mainstatDeduction)
// evaluate the best possible outcome
const bestSubstats: { stat: SubStats; value: number }[] = [{ stat: 'HP', value: 0 }, { stat: 'HP', value: 0 }, { stat: 'HP', value: 0 }, { stat: 'HP', value: 0 }]
for (let i = 0; i < relic.substats.length; i++) { // we pass values instead of references to avoid accidentally modifying the actual relic
bestSubstats[i].stat = relic.substats[i].stat
bestSubstats[i].value = relic.substats[i].value
}// after copying over existing lines, supplement to 4 lines if necessary
for (let i = relic.substats.length; i < 4; i++) {
const stat = availableSubstats[i - relic.substats.length][0]
bestSubstats[i].stat = stat
bestSubstats[i].value = SubStatValues[stat][5].high
}
const bestSub = findHighestWeight(bestSubstats, meta)
bestSubstats[bestSub.index].value += remainingRolls * SubStatValues[bestSub.stat][relic.grade as 2 | 3 | 4 | 5].high
let fake = fakeRelic(relic.grade, maxEnhance(relic.grade as 2 | 3 | 4 | 5), relic.part, relic.main.stat, generateSubStats(
5, bestSubstats[0], bestSubstats[1], bestSubstats[2], bestSubstats[3],
))
const best = Math.max(0, (this.substatScore(fake, id).score + mainstatDeduction) / idealScore * 100 * percentToScore + mainstatBonus)
// evaluate average outcome
const averageSubstats: { stat: SubStats; value: number }[] = [{ stat: 'HP', value: 0 }, { stat: 'HP', value: 0 }, { stat: 'HP', value: 0 }, { stat: 'HP', value: 0 }]
for (let i = 0; i < relic.substats.length; i++) { // we pass values instead of references to avoid accidentally modifying the actual relic
averageSubstats[i].stat = relic.substats[i].stat
averageSubstats[i].value = relic.substats[i].value + remainingRolls / 4 * SubStatValues[averageSubstats[i].stat][relic.grade as 2 | 3 | 4 | 5].mid
}
/*
* We want to use the score() function to score relics for maximum accuracy (and easier maintainability potentially)
* How do we score a relic with unknown substats?
* One option would be to score all possible relics and take the average score (ew, slow, expensive)
* Instead, we calculate the average score of the possible new line (using a mid-roll)
* We then choose a substat to camouflage as so that the score() function is able to handle the relic
* We divide the average score of 1 mid-roll we calculated earlier by the weight and normalization of the chosen camouflage stat
* We then multiply this by the number of rolls our filler stat will have
* This way, when the score() function evaluates our relic, all the additional lines will score their expected average score
* average score of 1 mid-roll = avg(weight * normalization * mid-roll)
* avg score = avg(weight * norm * mid roll) * rolls
* AND
* avg score = value * weight * scaling
* Therefore
* value = avg(weight * norm * mid roll) * rolls / (weight * scaling)
* value = average score of 1 mid-roll * rolls / (weight * scaling)
*/
let averageScore = 0
for (const pair of availableSubstats) {
const [stat, weight] = pair
averageScore += SubStatValues[stat][relic.grade as 2 | 3 | 4 | 5].mid * weight * normalization[stat]
}
averageScore = averageScore / availableSubstats.length
for (let i = relic.substats.length; i < 4; i++) {
averageSubstats[i].stat = meta.sortedSubstats[0][0]
averageSubstats[i].value = averageScore * (1 + remainingRolls / 4) / (normalization[meta.sortedSubstats[0][0]] * meta.sortedSubstats[0][1])
}
fake = fakeRelic(relic.grade, maxEnhance(relic.grade as 2 | 3 | 4 | 5), relic.part, relic.main.stat, generateSubStats(
5, averageSubstats[0], averageSubstats[1], averageSubstats[2], averageSubstats[3],
))
const average = Math.max(0, (this.substatScore(fake, id).score + mainstatDeduction) / idealScore * 100 * percentToScore + mainstatBonus)
// evaluate the worst possible outcome
availableSubstats.reverse()
const worstSubstats: { stat: SubStats; value: number }[] = [{ stat: 'HP', value: 0 }, { stat: 'HP', value: 0 }, { stat: 'HP', value: 0 }, { stat: 'HP', value: 0 }]
for (let i = 0; i < relic.substats.length; i++) { // we pass values instead of references to avoid accidentally modifying the actual relic
worstSubstats[i].stat = relic.substats[i].stat
worstSubstats[i].value = relic.substats[i].value
}// after copying over existing lines, supplement to 4 lines if necessary
for (let i = relic.substats.length; i < 4; i++) {
const stat = availableSubstats[i - relic.substats.length][0]
worstSubstats[i].stat = stat
worstSubstats[i].value = SubStatValues[stat][5].high
}
const worstSub = findLowestWeight(worstSubstats, meta)
worstSubstats[worstSub.index].value += SubStatValues[worstSub.stat][relic.grade as 2 | 3 | 4 | 5].low * remainingRolls
fake = fakeRelic(relic.grade, maxEnhance(relic.grade as 2 | 3 | 4 | 5), relic.part, relic.main.stat, generateSubStats(
5, worstSubstats[0], worstSubstats[1], worstSubstats[2], worstSubstats[3],
))
const worst = Math.max(0, (this.substatScore(fake, id).score + mainstatDeduction) / idealScore * 100 * percentToScore + mainstatBonus)
let levelupMetadata: {
bestAddedStats: SubStats[]
bestUpgradedStats: SubStats[]
} | undefined = undefined
if (withMeta) {
const bestAddedStats: SubStats[] = []
if (relic.substats.length < 4) {
for (const [stat, weight] of availableSubstats) {
if (weight >= availableSubstats[availableSubstats.length - 1][1]) {
bestAddedStats.push(stat)
}
}
}
const candidateSubstats: [SubStats, number][] = meta.sortedSubstats.filter((x) => relic.main.stat !== x[0])// All substats that could possibly exist on the relic
const bestUpgradedStats: SubStats[] = [] // Array of all substats possibly on relic sharing highest weight
const validUpgrades: Record<SubStats, object | true | undefined> = {
...arrayToMap(relic.substats, 'stat'),
...stringArrayToMap(bestAddedStats),
}
const upgradeCandidates: [SubStats, number][] = candidateSubstats.filter((candidateSubstats) => validUpgrades[candidateSubstats[0]])
const bestWeight = upgradeCandidates[0][1]
for (const [stat, weight] of upgradeCandidates) {
if (validUpgrades[stat] && weight >= bestWeight) {
bestUpgradedStats.push(stat)
}
}
bestAddedStats.forEach((s, i) => bestAddedStats[i] = i18next.t(`common:Stats.${s}`))
bestUpgradedStats.forEach((s, i) => bestUpgradedStats[i] = i18next.t(`common:Stats.${s}`))
levelupMetadata = {
bestAddedStats: bestAddedStats,
bestUpgradedStats: bestUpgradedStats,
}
}
let rerollValue = 0
let rerollAvg = 0
if (relic.grade >= 5 && relic.substats.length == 4) {
const currentRolls = TsUtils.sumArray(relic.substats.map((x) => x.addedRolls ?? 0))
const remainingRolls = Math.ceil((15 - relic.enhance) / 3)
const totalRolls = Math.min(currentRolls + remainingRolls, 5)
for (const substat of relic.substats) {
const stat = substat.stat
const value = SubStatValues[stat][5].high * meta.stats[stat] * normalization[stat]
if (stat == bestSub.stat) {
rerollValue += value * (totalRolls + 1)
} else {
rerollValue += value
}
if (totalRolls >= 5) {
rerollAvg += value * 2.25
} else {
rerollAvg += value * 2
}
}
// These are reroll max potentials - Disabled for now
// rerollValue = Math.min(rerollValue, idealScore)
// rerollValue = (rerollValue + mainstatDeduction) / idealScore * 100 * percentToScore + mainstatBonus
// There is a case where a stat with less than 1 weight is the main stat, in which case the reroll value will exceed the ideal score, cap it
rerollAvg = Math.min(rerollAvg, idealScore)
rerollAvg = (rerollAvg + mainstatDeduction) / idealScore * 100 * percentToScore + mainstatBonus
}
return {
current,
best,
average,
worst,
rerollAvg,
meta: levelupMetadata,
} as FutureScoringResult
} | /**
* returns the current score of the relic, as well as the best, worst, and average scores when at max enhance\
* meta field includes the ideal added and/or upgraded substats for the relic
*/ | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L450-L667 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | RelicScorer.scoreCurrentRelic | scoreCurrentRelic(relic: Relic, id: CharacterId): RelicScoringResult {
if (!relic) {
// console.warn('scoreCurrentRelic called but no relic given for character', id ?? '????')
return {
score: '',
rating: '',
mainStatScore: 0,
}
}
if (!id) {
console.warn('scoreCurrentRelic called but lacking character', relic)
return {
score: '',
rating: '',
mainStatScore: 0,
}
}
const meta = this.getRelicScoreMeta(id)
const part = relic.part
const mainstatBonus = mainStatBonus(relic.part, relic.main.stat, meta)
const substatScore = this.substatScore(relic, id)
const idealScore = this.getOptimalPartScore(part, relic.main.stat, id)
const score = substatScore.score / idealScore * 100 * percentToScore + mainstatBonus
const rating = scoreToRating(score, substatScore, relic)
const mainStatScore = substatScore.mainStatScore
return {
score: score.toFixed(1),
rating,
mainStatScore,
part,
meta,
}
} | /**
* returns the current score, mainstat score, and rating for the relic\
* additionally returns the part, and scoring metadata
*/ | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L673-L705 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | RelicScorer.scoreCharacterWithRelics | scoreCharacterWithRelics(character: Character, relics: Relic[]): {
relics: object[]
totalScore: number
totalRating: string
} {
if (!character?.id) {
console.warn('scoreCharacterWithRelics called but no character given')
return {
relics: [],
totalScore: 0,
totalRating: '?',
}
}
const scoredRelics = relics.map((x) => this.getCurrentRelicScore(x, character.id))
let totalScore = 0
for (const relic of scoredRelics) {
totalScore += Number(relic.score) + Number(relic.mainStatScore)
}
const missingSets = 3 - countPairs(relics.filter((x) => x != undefined).map((x) => x.set))
totalScore = Math.max(0, totalScore - missingSets * 3 * minRollValue)
const totalRating = scoreToRating((totalScore - 4 * 64.8) / 6)
return {
relics: scoredRelics,
totalScore,
totalRating,
}
} | /**
* returns a score (number) and rating (string) for the character, and the scored relics
* @param character character object to score
* @param relics relics to score against the character
*/ | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L712-L739 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | RelicScorer.scoreCharacter | scoreCharacter(character: Character) {
if (!character) return {}
const relicsById = window.store.getState().relicsById
const relics: Relic[] = Object.values(character.equipped).map((x) => relicsById[x ?? ''])
return this.scoreCharacterWithRelics(character, relics)
} | /**
* returns a score (number) and rating (string) for the character, and the scored equipped relics
* @param character character object to score
*/ | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L745-L750 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | RelicScorer.scoreRelicPotential | scoreRelicPotential(relic: Relic, id: CharacterId, withMeta: boolean = false) {
const meta = this.getRelicScoreMeta(id)
const mainstatBonus = mainStatBonus(relic.part, relic.main.stat, meta)
const futureScore = this.getFutureRelicScore(relic, id, withMeta)
return {
bestPct: Math.max(0, futureScore.best - mainstatBonus) / percentToScore,
averagePct: Math.max(0, futureScore.average - mainstatBonus) / percentToScore,
worstPct: Math.max(0, futureScore.worst - mainstatBonus) / percentToScore,
rerollAvgPct: Math.max(0, futureScore.rerollAvg - mainstatBonus) / percentToScore,
meta: futureScore.meta,
}
} | // linear relation between score and potential makes this very easy now | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L759-L771 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | fakeRelic | function fakeRelic(grade: RelicGrade, enhance: RelicEnhance, part: string, mainstat: string, substats: subStat[]): Relic {
return {
enhance: enhance,
grade: grade,
part: part,
main: {
stat: mainstat,
value: MainStatsValues[mainstat][grade].base + MainStatsValues[mainstat][grade].increment * enhance,
},
substats: substats,
} as Relic
} | /**
* creates a fake relic that can be submitted for scoring
* @param grade relic rarity
* @param enhance relic level
* @param part relic slot
* @param mainstat relic primary stat
* @param substats array of substats, recommended to obtain via generateSubStats()
*/ | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L810-L821 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.