Skip to content

Instantly share code, notes, and snippets.

View jpitchardu's full-sized avatar
🕶️

J. Pichardo jpitchardu

🕶️
View GitHub Profile
@jpitchardu
jpitchardu / test.go
Last active May 6, 2024 03:28
Go Result type
func ConnectToDB() result.Result[sql.DB] {
psqlInfo := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
return result.NewResult(sql.Open("postgres", psqlInfo)).Try(func(db *sql.DB) error {
return db.Ping()
}).IfOk(func() {
fmt.Println("Successfully connected to database!")
})
}
@jpitchardu
jpitchardu / optional-chaining.js
Created May 23, 2018 16:42
TC39 Optional Chaining Proposal
obj?.arrayProp?[0]?.someProp?.someFunc?.();
@jpitchardu
jpitchardu / optional.js
Created May 23, 2018 16:40
Optional functionality in js using proxies
function optional(obj, evalFunc, def) {
const handler = {
get: function(target, prop, receiver) {
const res = Reflect.get(...arguments);
return typeof res === "object" ? proxify(res) : res != null ? res : def;
}
};
const proxify = target => {
return new Proxy(target, handler);
};
@jpitchardu
jpitchardu / lodash-get.js
Created May 23, 2018 16:38
lodashJS._get example
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c'); // => 3
_.get(object, ['a', '0', 'b', 'c']); // => 3
_.get(object, 'a.b.c', 'default'); // => 'default'
@jpitchardu
jpitchardu / optional-regex.js
Created May 23, 2018 16:37
Null-safe with regex in javascript
function optionalAccess(obj, path, def) {
const propNames = path.replace(/\]|\)/, "").split(/\.|\[|\(/);
return propNames.reduce((acc, prop) => acc[prop] || def, obj);
}
const obj = {
items: [
{ hello: "Hello" }
]
};
@jpitchardu
jpitchardu / optional-regex.js
Created May 23, 2018 16:37
Null-safe with regex in javascript
function optionalAccess(obj, path, def) {
const propNames = path.replace(/\]|\)/, "").split(/\.|\[|\(/);
return propNames.reduce((acc, prop) => acc[prop] || def, obj);
}
const obj = {
items: [
{ hello: "Hello" }
]
};
@jpitchardu
jpitchardu / deep-null.js
Created May 23, 2018 16:32
Deep null-check in javascript
console.log( obj && obj.prop1 && obj.prop1.prop2 && obj.prop1.prop2.prop3 ); // => undefined
@jpitchardu
jpitchardu / null-condition.js
Created May 23, 2018 16:31
Null-Conditional in JS
let obj;
console.log(obj && obj.someProp); // Prints undefined
@jpitchardu
jpitchardu / type-error.js
Created May 23, 2018 16:31
Type Error in JS
let obj;
console.log(obj.someProp); // => TypeError: Cannot read property 'someProp' of undefined
obj = null;
console.log(obj.someProp); // => TypeError: Cannot read property 'someProp' of null
@jpitchardu
jpitchardu / null-coalescence.cs
Created May 23, 2018 16:29
Null Coalescence in C#
SomeClass obj;
obj?.prop1?.prop2?.prop3 ?? "SomeDefaultValue";