Typescript / Javascript
Arrays
Create an array from 0 to n-1
let x = [...Array(n).keys()];
Create a m x n array with a default value
const defaultValue = 0;
let x = Array.from(Array(m), () => Array.from(Array(n), () => defaultValue));
Objects
Access a nested object using the dot notation
const get = (obj: object, key: string, sep: string = ".") =>
key
.split(sep)
.reduce(
(value: Record<string, any> | undefined, key: string) => value?.[key],
obj
);
const obj = {
a: {
b: 1,
c: { d: 2, e: 3 },
},
};
console.log(get(obj, "a.c.d"));
Flatten a nested object with given separator
const flatten = (obj: object, sep: string = ".") =>
Object.fromEntries(
Object.entries(obj)
.map(([key, value]): [string, any][] =>
"object" === typeof value
? Object.entries(flatten(value)).map(([k, v]) => [
[key, k].join(sep),
v,
])
: [[key, value]]
)
.flat()
);
const obj = {
a: {
b: 1,
c: { d: 2, e: 3 },
},
};
console.log(flatten(obj));
Encode/decode
Encode a string to Run Length Encoding (RLE)
function encodeRLE(input: string) {
let output = "";
const match = input.match(/(.)\1*/g);
if (match !== null) {
match.forEach((s) => {
if (s.length > 1) {
output += s.length.toString();
}
output += s[0];
});
}
return output;
}
Decode a string from Run Length Encoding (RLE)
function decodeRLE(input: string) {
let output = input.replace(/([0-9]+)([^0-9])/g, (match, p1, p2) => {
return p2.repeat(parseInt(p1));
});
return output;
}