Browse Source

ref(toArray): Introduce a `toArray()` helper function and use it (#41507)

I noticed a few spots where we ensure that a value is an array; but
there's a few different ways that folks spell it out.
So I created a simple helper method to do it, and hopefully make things
more readable in the process.
Ryan Albrecht 2 years ago
parent
commit
e2f6d7fe42

+ 2 - 3
static/app/components/charts/components/tooltip.tsx

@@ -7,6 +7,7 @@ import moment from 'moment';
 import BaseChart from 'sentry/components/charts/baseChart';
 import {DataPoint} from 'sentry/types/echarts';
 import {getFormattedDate, getTimeFormat} from 'sentry/utils/dates';
+import toArray from 'sentry/utils/toArray';
 
 import {truncationFormatter} from '../utils';
 
@@ -182,9 +183,7 @@ function getFormatter({
       ].join('');
     }
 
-    const seriesParams = Array.isArray(seriesParamsOrParam)
-      ? seriesParamsOrParam
-      : [seriesParamsOrParam];
+    const seriesParams = toArray(seriesParamsOrParam);
 
     // If axis, timestamp comes from axis, otherwise for a single item it is defined in the data attribute.
     // The data attribute is usually a list of [name, value] but can also be an object of {name, value} when

+ 2 - 1
static/app/components/charts/eventsGeoRequest.tsx

@@ -6,6 +6,7 @@ import {getUtcDateString} from 'sentry/utils/dates';
 import {TableData, TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
 import EventView from 'sentry/utils/discover/eventView';
 import {doDiscoverQuery} from 'sentry/utils/discover/genericDiscoverQuery';
+import toArray from 'sentry/utils/toArray';
 
 interface ChildrenRenderProps {
   errored: boolean;
@@ -47,7 +48,7 @@ const EventsGeoRequest = ({
     id: undefined,
     name: '',
     version: 2,
-    fields: Array.isArray(yAxis) ? yAxis : [yAxis],
+    fields: toArray(yAxis),
     query,
     orderby: orderby ?? '',
     projects,

+ 2 - 1
static/app/components/charts/percentageAreaChart.tsx

@@ -3,6 +3,7 @@ import type {LineSeriesOption} from 'echarts';
 import moment from 'moment';
 
 import {Series, SeriesDataUnit} from 'sentry/types/echarts';
+import toArray from 'sentry/utils/toArray';
 
 import AreaSeries from './series/areaSeries';
 import BaseChart from './baseChart';
@@ -70,7 +71,7 @@ export default class PercentageAreaChart extends Component<Props> {
         tooltip={{
           formatter: seriesParams => {
             // `seriesParams` can be an array or an object :/
-            const series = Array.isArray(seriesParams) ? seriesParams : [seriesParams];
+            const series = toArray(seriesParams);
 
             // Filter series that have 0 counts
             const date =

+ 2 - 1
static/app/components/compactSelect.tsx

@@ -19,6 +19,7 @@ import LoadingIndicator from 'sentry/components/loadingIndicator';
 import {Overlay, PositionWrapper} from 'sentry/components/overlay';
 import space from 'sentry/styles/space';
 import {FormSize} from 'sentry/utils/theme';
+import toArray from 'sentry/utils/toArray';
 import useOverlay, {UseOverlayProps} from 'sentry/utils/useOverlay';
 
 interface Props<OptionType extends OptionTypeBase, MultipleType extends boolean>
@@ -200,7 +201,7 @@ function CompactSelect<
   // Keep track of the default trigger label when the value changes
   const defaultTriggerLabel = useMemo(() => {
     const newValue = valueProp ?? internalValue;
-    const valueSet = Array.isArray(newValue) ? newValue : [newValue];
+    const valueSet = toArray(newValue);
     const selectedOptions = valueSet
       .map(val => getSelectedOptions<OptionType, MultipleType>(options, val))
       .flat();

+ 2 - 1
static/app/components/events/interfaces/performance/spanCountChart.tsx

@@ -12,6 +12,7 @@ import SpanCountHistogramQuery from 'sentry/utils/performance/histogram/spanCoun
 import {HistogramData} from 'sentry/utils/performance/histogram/types';
 import {formatHistogramData} from 'sentry/utils/performance/histogram/utils';
 import theme from 'sentry/utils/theme';
+import toArray from 'sentry/utils/toArray';
 
 interface Props {
   event: EventError;
@@ -52,7 +53,7 @@ export function SpanCountChart({issue, event, location, organization}: Props) {
     const colors = [theme.charts.previousPeriod, ...theme.charts.getColorPalette(4)];
     const tooltip = {
       formatter(series) {
-        const seriesData = Array.isArray(series) ? series : [series];
+        const seriesData = toArray(series);
         let contents: string[] = [];
 
         contents = seriesData.map(item => {

+ 2 - 3
static/app/components/hotkeysLabel.tsx

@@ -2,6 +2,7 @@ import styled from '@emotion/styled';
 
 import space from 'sentry/styles/space';
 import {getKeyCode} from 'sentry/utils/getKeyCode';
+import toArray from 'sentry/utils/toArray';
 
 const macModifiers = {
   18: '⌥',
@@ -58,9 +59,7 @@ type Props = {
 
 const HotkeysLabel = ({value, forcePlatform}: Props) => {
   // Split by commas and then split by +, but allow escaped /+
-  const hotkeySets = (Array.isArray(value) ? value : [value]).map(o =>
-    o.trim().split('+')
-  );
+  const hotkeySets = toArray(value).map(o => o.trim().split('+'));
 
   const isMac = forcePlatform
     ? forcePlatform === 'macos'

+ 2 - 5
static/app/components/organizations/pageFilters/parse.tsx

@@ -6,6 +6,7 @@ import {DATE_TIME_KEYS, URL_PARAM} from 'sentry/constants/pageFilters';
 import {IntervalPeriod, PageFilters} from 'sentry/types';
 import {defined} from 'sentry/utils';
 import {getUtcToLocalDateObject} from 'sentry/utils/dates';
+import toArray from 'sentry/utils/toArray';
 
 import {PageFiltersState} from './types';
 
@@ -146,11 +147,7 @@ function getEnvironment(maybe: ParamValue) {
     return undefined;
   }
 
-  if (Array.isArray(maybe)) {
-    return maybe;
-  }
-
-  return [maybe];
+  return toArray(maybe);
 }
 
 type InputParams = {

+ 2 - 1
static/app/locale.tsx

@@ -6,6 +6,7 @@ import isString from 'lodash/isString';
 import {sprintf} from 'sprintf-js';
 
 import localStorage from 'sentry/utils/localStorage';
+import toArray from 'sentry/utils/toArray';
 
 const markerStyles = {
   background: '#ff801790',
@@ -285,7 +286,7 @@ function mark(node: React.ReactNode): string {
     ref: null,
     props: {
       style: markerStyles,
-      children: Array.isArray(node) ? node : [node],
+      children: toArray(node),
     },
     _owner: null,
     _store: {},

+ 3 - 6
static/app/stores/groupStore.tsx

@@ -12,6 +12,7 @@ import {
   GroupStats,
 } from 'sentry/types';
 import RequestError from 'sentry/utils/requestError/requestError';
+import toArray from 'sentry/utils/toArray';
 
 import SelectedGroupStore from './selectedGroupStore';
 import {CommonStoreDefinition} from './types';
@@ -147,9 +148,7 @@ const storeConfig: GroupStoreDefinition = {
    * If any items already exist, they will merged into the existing item index.
    */
   add(items) {
-    if (!Array.isArray(items)) {
-      items = [items];
-    }
+    items = toArray(items);
     const newItems = this.mergeItems(items);
 
     this.items = [...this.items, ...newItems];
@@ -162,9 +161,7 @@ const storeConfig: GroupStoreDefinition = {
    * If any items already exist, they will be moved to the front in the order provided.
    */
   addToFront(items) {
-    if (!Array.isArray(items)) {
-      items = [items];
-    }
+    items = toArray(items);
     const itemMap = items.reduce((acc, item) => ({...acc, [item.id]: item}), {});
 
     this.items = [...items, ...this.items.filter(item => !itemMap[item.id])];

+ 2 - 1
static/app/stores/groupingStore.tsx

@@ -10,6 +10,7 @@ import {
 import {Client} from 'sentry/api';
 import {Group, Organization, Project} from 'sentry/types';
 import {Event} from 'sentry/types/event';
+import toArray from 'sentry/utils/toArray';
 
 import {CommonStoreDefinition} from './types';
 
@@ -228,7 +229,7 @@ const storeConfig: GroupingStoreDefinition = {
   },
 
   setStateForId(map, idOrIds, newState) {
-    const ids = Array.isArray(idOrIds) ? idOrIds : [idOrIds];
+    const ids = toArray(idOrIds);
 
     return ids.map(id => {
       const state = (map.has(id) && map.get(id)) || {};

Some files were not shown because too many files changed in this diff