Skip to content

Instantly share code, notes, and snippets.

View alexkhismatulin's full-sized avatar

Alex Khismatulin alexkhismatulin

View GitHub Profile
@alexkhismatulin
alexkhismatulin / when-you-need-a-semicolon.js
Last active May 14, 2019 14:47
The case when you do need a semicolon in JavaScript. Check it out in StackBlitz demo: https://stackblitz.com/edit/when-you-need-a-semicolon
const items = [1, 2, 3]
try {
// you need a semicolon after following line to make it work
items.shift()
(items.length && items[0] === 2) && items.unshift(1)
} catch(e) {
console.error(e)
}
@alexkhismatulin
alexkhismatulin / groupBy.js
Created May 13, 2019 16:43
Groups array entries based on given path. Uses getProperty function (https://gist.github.com/alexkhismatulin/0dee70114e597a32bcd59c6acc934d79)
const groupBy = (arr, path) => {
if (!path || typeof path !== "string") return {}
return Object.keys(arr).reduce((accum, key) => {
const value = getProperty(arr[key], path)
if (accum[value]) return { ...accum, [value]: [...accum[value], arr[key]] }
return { ...accum, [value]: [arr[key]] }
}, {})
@alexkhismatulin
alexkhismatulin / getProperty.js
Created May 13, 2019 16:35
A simple errors-safe function allowing to access properties of objects/arrays by string key like
const getProperty = (obj, path, defaultValue) => {
const tokens = path.split(/[.[\]]+/g).filter(Boolean)
if (!obj || typeof obj !== "object") return defaultValue
if (tokens.length === 1) {
return (obj[tokens[0]] === undefined) ? defaultValue : obj[tokens[0]]
}
return getProperty(obj[tokens[0]], tokens.slice(1).join("."), defaultValue)
@alexkhismatulin
alexkhismatulin / pick-omit.js
Created May 13, 2019 16:27
A pair of tools allowing to pick a set of properties from object or get an object without passed list of properties
const match = (fields, key) => {
if (["string", "number"].indexOf(typeof fields) !== -1) return fields === key
if (fields.indexOf) return fields.indexOf(key) !== -1
return false
}
const omit = (obj, fields) => Object.keys(obj).reduce((accum, propName) => {
if (match(fields, propName)) return accum
return { ...accum, [propName]: obj[propName] }
@alexkhismatulin
alexkhismatulin / simple-clone-deep.js
Created January 24, 2019 17:45
Simple deep cloning function. Works fine with primitive objects/arrays, doesn't work properly with class instances and objects with custom prototypes.
const isObject = value => typeof value === "object"
const cloneDeep = (value) => {
if (!value || !isObject(value)) return value
if (Array.isArray(value)) return value.map(item => cloneDeep(item))
return Object.keys(value).reduce((accum, propName) => {
const propValue = value[propName]