Skip to content

Instantly share code, notes, and snippets.

@papayankey
papayankey / slice_tricks.md
Created August 5, 2022 08:11 — forked from GimmyHchs/slice_tricks.md
[Go SliceTricks] golang slice tricks #go

Since the introduction of the append built-in, most of the functionality of the container/vector package, which was removed in Go 1, can be replicated using append and copy.

Here are the vector methods and their slice-manipulation analogues:

AppendVector

a = append(a, b...)

Copy

Semantic Commit Messages

See how a minor change to your commit message style can make you a better programmer.

Format: <type>(<scope>): <subject>

<scope> is optional

Example

func RemainderSorting(s []string, divisor int) []string {
if len(s) == 0 {
return s
}
sort(s, divisor)
return s
}
func sort(s []string, m int) {
// sort by remainder
@papayankey
papayankey / PatternMatching.ts
Last active July 21, 2022 08:59
Pattern matching using discriminate union
// Discriminated Union ( pattern matching )
type Operator = 'add' | 'sub' | 'mul' | 'div';
type Num = {
kind: 'number'
value: number
}
type Operation = {
@papayankey
papayankey / count-by.ts
Created October 26, 2020 03:32
count array of objects by specified key
function countBy<T extends { [key: string]: any }, K extends keyof T>(
collection: T[],
key: K
) {
return Object.values(collection).reduce(
(accum: { [key: string]: any }, curr) => {
accum[curr[key]] =
accum[curr[key]] !== undefined ? (accum[curr[key]] += 1) : 1;
return accum;
},
@papayankey
papayankey / group-by.ts
Created October 26, 2020 03:30
group array of objects by specified key
function groupBy<T extends { [key: string]: any }, K extends keyof T>(
collection: T[],
key: K
) {
return Object.values(collection).reduce(
(accum: { [key: string]: any }, curr) => {
accum[curr[key]] =
accum[curr[key]] !== undefined ? [...accum[curr[key]], curr] : [curr];
return accum;
},
@papayankey
papayankey / object-filter.js
Created March 15, 2020 11:02
object property filter or picker with support for nested objects
let toString = Object.prototype.toString;
// strict object check
function isObject(value) {
return toString.call(value) === '[object Object]';
}
// strict array check
function isArray(value) {
return toString.call(value) === '[object Array]';