Skip to content

Instantly share code, notes, and snippets.

@gaurangrshah
Created November 3, 2020 21:14
Show Gist options
  • Save gaurangrshah/2147a54ce8bf1aa2206b2bdacdccf4f4 to your computer and use it in GitHub Desktop.
Save gaurangrshah/2147a54ce8bf1aa2206b2bdacdccf4f4 to your computer and use it in GitHub Desktop.
#utils #tools
export * from "./react-tools"
export * from "./slugify"
export * from "./tools"
export * from "./truncate"
import React from "react"
export const MapChildren = ({ kids, newProps }) => {
return React.Children.map(kids || null, (child, i) => (
<child.type {...child.props} key={i} {...newProps} />
))
}
export const mapChildren = (debug = false, kids, newProps, Wrapper) => {
// console.log('🐞 🗺 👶 running mapChildren')
return (
kids &&
React.Children.map(kids || null, (child, i) =>
Wrapper ? (
<Wrapper key={`wrapper-${debug && "debug"}-${i}`}>
<child.type {...child.props} {...newProps} />
{debug &&
console.table({
ctx: "🐞🗺 👶 🎁",
childProps: child?.props,
childType: child?.type,
debug: debug,
extra: Wrapper,
})}
</Wrapper>
) : (
<>
<child.type {...child.props} key={i} {...newProps} />
{debug &&
console.table({
ctx: "🐞🗺 👶:",
childProps: child.props,
childType: child.type,
debug: debug,
})}
</>
)
)
)
}
/* eslint-disable */
export function slugify(text) {
const from = "ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;"
const to = "aaaaaeeeeeiiiiooooouuuunc------"
const newText = text
.split("")
.map((letter, i) =>
letter.replace(new RegExp(from.charAt(i), "g"), to.charAt(i))
)
return newText
.toString() // Cast to string
.toLowerCase() // Convert the string to lowercase letters
.trim() // Remove whitespace from both sides of a string
.replace(/\s+/g, "-") // Replace spaces with -
.replace(/&/g, "-y-") // Replace & with 'and'
.replace(/[^\w\-]+/g, "") // Remove all non-word chars
.replace(/\-\-+/g, "-") // Replace multiple - with single -
}
//https://gist.github.com/codeguy/6684588
/* eslint-disable */
/**********************************
* * Enironment helpers
* ********************************
*/
export const isApiSupported = api => api in window
// if (!isApiSupported('IntersectionObserver')) {}
export const isClient = typeof window === "object"
export const isSSR = typeof window === "undefined"
export const isDev =
process &&
process.env &&
(!process.env.NODE_ENV || process.env.NODE_ENV === "development")
/**********************************
* * Typography Helpers
* see "./truncate" for more
* see "./slugify" for more
* ********************************
*/
export const getFontSize = () =>
!isSSR &&
parseFloat(
getComputedStyle(document.body, null).fontSize.replace(/[^\d]/g, "")
)
export const convertEmToPx = val => val.replace("em", "") * getFontSize() + "px"
export const capitalize = string =>
string.replace(/\b\w/g, c => c.toUpperCase())
//https://attacomsian.com/blog/string-capitalize-javascript
/**********************************
* * Convenience Functions
* ********************************
*/
export function shortid() {
//http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
return (
Math.random().toString(36).substring(2, 15) +
Math.random().toString(36).substring(2, 15)
)
}
export function formatNumber(num) {
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
}
export const randomNumGen = (
// array of random nums
num, // number of random numbers to generate
limit = 100 // highest number possible
) => Array.from(Array(num)).map(() => Math.floor(Math.random() * limit))
export const isExternal = string => {
const urlregex = /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/
return urlregex.test(string)
}
export const randomConditional = (probability, { truthy, falsy }) =>
Math.random() >= probability ? truthy : falsy
export const hidden = [`none`, `none`, `block`]
/**********************************
* * Array Operations
* ********************************
*/
export const makeArray = string => {
const newArr = string.split(", ")
return newArr
}
export const doesInclude = (arr = [], idx = 0) => arr.includes(idx)
/**********************************
* * Object Operations
* ********************************
*/
export const mapObject = obj => {
return isObject(obj)
? Object.entries(obj).map((entry, i) => {
return isObject(entry) ? mapObject(entry) : entry
})
: obj
}
export const hasOwnProperty = (obj, prop) =>
obj ? Object.prototype.hasOwnProperty.call(obj, prop) : false
/**********************************
* * Conditional Checks
* ********************************
*/
export const isBoolean = arg => {
return typeof arg === "boolean"
}
export const isTruthy = (condition, setting) =>
condition && setting ? setting : !isBoolean(condition) && condition
export const isArray = obj => (Array.isArray(obj) ? true : false)
export const isNull = obj => (obj === null ? true : false)
export const isArrayOrNull = obj => (isNull(obj) && isArray(obj) ? true : false)
export const isObject = obj =>
obj !== null &&
typeof obj !== "string" &&
typeof obj !== "number" &&
!Array.isArray(obj) &&
typeof obj === "object"
? true
: false
/**********************************
* * Form Tools
* ********************************
*/
export function addDashes(target) {
let val = target.value.replace(/\D[^\.]/g, "")
target.value = val.slice(0, 3) + "-" + val.slice(3, 6) + "-" + val.slice(6)
// usage: addDashes(e.target)
}
export function truncateOnWord(str, limit) {
var trimmable =
"\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF"
var reg = new RegExp("(?=[" + trimmable + "])")
var words = str.split(reg)
var count = 0
return (
words
.filter(function (word) {
count += word.length
return count <= limit
})
.join("") + "..."
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment