Skip to content

Instantly share code, notes, and snippets.

@iceener
iceener / private-fields.js
Created April 17, 2020 16:43
TypeScript 01-finished
class Avenger {
constructor(name) {
this.name = name;
}
}
const hero = new Avenger("Steve Rogers");
hero.name; /*?*/
// Destructuring
const args = [1, 2, 3, 4];
const [a, b, c, d] = args;
console.log(a, b, c, d);
const coords = { x: 1, y: 10 };
const { x: horizontal, y } = coords;
horizontal; /*?*/
y; /*?*/
// Array to CSV data
const csvContent = result.map(e => e.join(",")).join("\n");
copy(csvContent)
// Capitalize all words of a string
function capitalize(string) {
return string.replace(/\b[a-z]/g, (char) => char.toUpperCase());
}
capitalize('overment rocks!');
// Uppercase first letter of a string
function ucFirst(string) {
return string.charAt(0).toUppercase() + string.slice(1);
}
// Get URL params
const getParameters = () =>
window.location.search
.slice(1)
.url.split('&')
.reduce(function _reduce(/*Object*/ obj, /*String*/ str) {
str = str.split('=');
obj[str[0]] = decodeURIComponent(str[1]);
return obj;
}, {});
// Pipe function composition
const pipeAsyncFunctions = (...fns) => (input) => fns.reduce((chain, func) => chain.then(func), Promise.resolve(input));
// Usage
pipeAsyncFunctions(fn1, fn2)(input).then(result => console.log(result));
// Object to Query String
const obj = { foo: 'bar', baz: 'qux' }
const queryString = new URLSearchParams(obj).toString()
// foo=bar&baz=qux
// Rename object keys
const renameKeys = (keysMap, obj) =>
Object.keys(obj).reduce(
(acc, key) => ({
...acc,
...{ [keysMap[key] || key]: obj[key] },
}),
{}
);
// CSV to JSON
const CSVToJSON = (data, delimiter = ',') => {
const titles = data.slice(0, data.indexOf('\n')).split(delimiter);
return data
.slice(data.indexOf('\n') + 1)
.split('\n')
.map(v => {
const values = v.split(delimiter);
return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {});
});