Skip to content
Source
Sign inSign up
TanStack/table
Open History to see the last commit

utils.js

217 lines4.3 KB

1import React from 'react'
2import classnames from 'classnames'
3import * as ReactIs from 'react-is'
4​
5//
6export default {
7 get,
8 set,
9 takeRight,
10 last,
11 orderBy,
12 range,
13 remove,
14 clone,
15 getFirstDefined,
16 sum,
17 makeTemplateComponent,
18 groupBy,
19 isArray,
20 splitProps,
21 compactObject,
22 isSortingDesc,
23 normalizeComponent,
24 asPx,
26​
27function get (obj, path, def) {
28 if (!path) {
29 return obj
30 }
31 const pathObj = makePathArray(path)
32 let val
33 try {
34 val = pathObj.reduce((current, pathPart) => current[pathPart], obj)
35 } catch (e) {
36 // continue regardless of error
37 }
38 return typeof val !== 'undefined' ? val : def
40​
41function set (obj = {}, path, value) {
42 const keys = makePathArray(path)
43 let keyPart
44 let cursor = obj
45 while ((keyPart = keys.shift()) && keys.length) {
46 if (!cursor[keyPart]) {
47 cursor[keyPart] = {}
48 }
49 cursor = cursor[keyPart]
50 }
51 cursor[keyPart] = value
52 return obj
54​
55function takeRight (arr, n) {
56 const start = n > arr.length ? 0 : arr.length - n
57 return arr.slice(start)
59​
60function last (arr) {
61 return arr[arr.length - 1]
63​
64function range (n) {
65 const arr = []
66 for (let i = 0; i < n; i += 1) {
67 arr.push(n)
68 }
69 return arr
71​
72function orderBy (arr, funcs, dirs, indexKey) {
73 return arr.sort((rowA, rowB) => {
74 for (let i = 0; i < funcs.length; i += 1) {
75 const comp = funcs[i]
76 const desc = dirs[i] === false || dirs[i] === 'desc'
77 const sortInt = comp(rowA, rowB)
78 if (sortInt) {
79 return desc ? -sortInt : sortInt
80 }
81 }
82 // Use the row index for tie breakers
83 return dirs[0] ? rowA[indexKey] - rowB[indexKey] : rowB[indexKey] - rowA[indexKey]
84 })
86​
87function remove (a, b) {
88 return a.filter((o, i) => {
89 const r = b(o)
90 if (r) {
91 a.splice(i, 1)
92 return true
93 }
94 return false
95 })
97​
98function clone (a) {
99 try {
100 return JSON.parse(
101 JSON.stringify(a, (key, value) => {
102 if (typeof value === 'function') {
103 return value.toString()
104 }
105 return value
106 })
107 )
108 } catch (e) {
109 return a
110 }
112​
113function getFirstDefined (...args) {
114 for (let i = 0; i < args.length; i += 1) {
115 if (typeof args[i] !== 'undefined') {
116 return args[i]
117 }
118 }
120​
121function sum (arr) {
122 return arr.reduce((a, b) => a + b, 0)
124​
125function makeTemplateComponent (compClass, displayName) {
126 if (!displayName) {
127 throw new Error('No displayName found for template component:', compClass)
128 }
129 const cmp = ({ children, className, ...rest }) => (
130 <div className={classnames(compClass, className)} {...rest}>
131 {children}
132 </div>
133 )
134 cmp.displayName = displayName
135 return cmp
137​
138function groupBy (xs, key) {
139 return xs.reduce((rv, x, i) => {
140 const resKey = typeof key === 'function' ? key(x, i) : x[key]
141 rv[resKey] = isArray(rv[resKey]) ? rv[resKey] : []
142 rv[resKey].push(x)
143 return rv
144 }, {})
146​
147function asPx (value) {
148 value = Number(value)
149 return Number.isNaN(value) ? null : `${value}px`
151​
152function isArray (a) {
153 return Array.isArray(a)
155​
156// ########################################################################
157// Non-exported Helpers
158// ########################################################################
159​
160function makePathArray (obj) {
161 return flattenDeep(obj)
162 .join('.')
163 .replace(/\[/g, '.')
164 .replace(/\]/g, '')
165 .split('.')
167​
168function flattenDeep (arr, newArr = []) {
169 if (!isArray(arr)) {
170 newArr.push(arr)
171 } else {
172 for (let i = 0; i < arr.length; i += 1) {
173 flattenDeep(arr[i], newArr)
174 }
175 }
176 return newArr
178​
179function splitProps ({ className, style, ...rest }) {
180 return {
181 className,
182 style,
183 rest: rest || {},
184 }
186​
187function compactObject (obj) {
188 const newObj = {}
189 if (obj) {
190 Object.keys(obj).map(key => {
191 if (
192 Object.prototype.hasOwnProperty.call(obj, key) &&
193 obj[key] !== undefined &&
194 typeof obj[key] !== 'undefined'
195 ) {
196 newObj[key] = obj[key]
197 }
198 return true
199 })
200 }
201 return newObj
203​
204function isSortingDesc (d) {
205 return !!(d.sort === 'desc' || d.desc === true || d.asc === false)
207​
208function normalizeComponent (Comp, props, fallback = Comp) {
209 if (ReactIs.isElement(Comp) || typeof Comp === 'string') {
210 return Comp
211 } else if (ReactIs.isValidElementType(Comp)) {
212 return <Comp {...props} />
213 }
214​
215 return fallback
217​