lodash#isArray TypeScript Examples

The following examples show how to use lodash#isArray. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.tsx    From XFlow with MIT License 7 votes vote down vote up
registerCustomNode = (panelConfigs?: IRegisterNode | IRegisterNode[]) => {
  const registerNodes: IRegisterNode[] = (
    panelConfigs ? (isArray(panelConfigs) ? panelConfigs : [panelConfigs]) : []
  ) as IRegisterNode[]
  let nodes = []
  registerNodes.forEach(item => {
    nodes = nodes.concat(
      item.nodes.map(node => ({
        ...node,
        parentKey: item.key,
      })),
    )
  })

  if (nodes.length) {
    setProps({
      registerNode: nodes,
    })
  }
  const graphConfig = getProps('graphConfig')
  const registerNode = getProps('registerNode')
  if (!graphConfig || !registerNode?.length) {
    return
  }
  registerNode.forEach(item => {
    const { name, component } = item
    graphConfig.setNodeRender(name, component)
  })
}
Example #2
Source File: utils.ts    From yforms with MIT License 7 votes vote down vote up
export function submitFormatValues(
  values: KeyValue,
  formatFieldsValue?: FormatFieldsValue[],
): KeyValue {
  const _values = mergeWithDom({}, values);
  const list: FormatFieldsValue[] = sortBy(formatFieldsValue, (item) => {
    if (!item) return;
    if (isArray(item.name)) {
      return -item.name.length;
    }
    return -`${item.name}`.length;
  }).filter((x) => x);
  forEach(list, (item) => {
    const { name, format } = item;
    if (name && format) {
      const parentValue = getParentNameData(values, name);
      // 如果上一级是 undefined,则不处理该字段。(List add 会生成空对象)
      if (parentValue === undefined) return;
      try {
        set(_values, name, format(get(values, name), parentValue, values));
      } catch (error) {
        // 如果 format 代码报错这里抛出异常
        // eslint-disable-next-line no-console
        console.error(error);
        warning(false, error);
      }
    }
  });
  return _values;
}
Example #3
Source File: utils.ts    From erda-ui with GNU Affero General Public License v3.0 7 votes vote down vote up
getNodeByPath = ({ treeData, eventKey, valueKey }: IFunc): any => {
  if (!eventKey) {
    return '';
  }
  const list = eventKey.split('-').join(' children ').split(' ');
  if (valueKey) list.push(valueKey);
  return reduce(
    list,
    (result, singleKey) => {
      if (!result) {
        // 第一次
        const firstKey = get(treeData, [0, 'key']);
        if (firstKey === singleKey) {
          return get(treeData, [0]);
        }
      } else if (singleKey === 'children') {
        // 子节点则继续返回
        return get(result, ['children']);
      } else if (isArray(result)) {
        // 获取children中匹配的node
        return find(result, ({ id }: any) => `${id}` === singleKey);
      }
      // 最终单个节点的某个字段,比如key、title、id等
      return get(result, [singleKey]);
    },
    '',
  );
}
Example #4
Source File: utility.service.ts    From fyle-mobile-app with MIT License 7 votes vote down vote up
traverse(x, callback) {
    const that = this;
    if (isArray(x)) {
      return that.traverseArray(x, callback);
    } else if (typeof x === 'object' && x !== null && !(x instanceof Date)) {
      return that.traverseObject(x, callback);
    } else {
      return callback(x);
    }
  }
Example #5
Source File: utils.tsx    From gant-design with MIT License 7 votes vote down vote up
getTransData = (columns, data) => {
  const res = [];
  const setPropertyType = currentColumn => {
    if (!currentColumn || !get(currentColumn, 'fieldName')) {
      return;
    }
    if (isArray(currentColumn.children)) {
      currentColumn.children.forEach((c: any) => {
        setPropertyType(c);
      });
      return;
    }
    const { fieldName, title, props, componentType } = currentColumn;
    res.push({
      fieldName,
      label: title,
      value: get(data, fieldName),
    });
  };
  columns.forEach(column => {
    setPropertyType(column);
  });
  return res;
}
Example #6
Source File: util.ts    From gio-design with Apache License 2.0 7 votes vote down vote up
callbackOnOverflow = (params: Pick<ListProps, 'model' | 'max' | 'value' | 'onMultipleOverflow'>): void => {
  const { max, model, value, onMultipleOverflow } = params;
  // prettier-ignore
  if (
    model === 'multiple' &&
    Array.isArray(value) &&
    max !== undefined &&
    value.length >= max &&
    onMultipleOverflow
  ) {
    onMultipleOverflow(value);
  }
}
Example #7
Source File: Menu.tsx    From binaural-meet with GNU General Public License v3.0 6 votes vote down vote up
function importItems(ev: React.ChangeEvent<HTMLInputElement>, contents: SharedContents) {
  const files = ev.currentTarget?.files
  if (files && files.length) {
    files[0].text().then((text) => {
      const items = JSON.parse(text)
      if (isArray(items)) {
        items.forEach((item) => {
          const content = extractContentData(item as ISharedContent)
          if (content.type === 'screen' || content.type === 'camera') { return }
          const newContent = createContent()
          Object.assign(newContent, content)
          contents.addLocalContent(newContent)
        })
      }
    })
  }
}
Example #8
Source File: selector.ts    From redux-with-domain with MIT License 6 votes vote down vote up
function _transformSelectors(namespace, selectors, initialState) {
  const globalizeSelector = (selector, key) => (...params) => {
    if (isArray(params) && params.length > 1 && params[0] === currentState) {
      params.shift()
    }
    const stateValue = _getStateValue(
      key,
      currentState,
      namespace,
      initialState
    )

    const res = selector(stateValue, {
      payload: params.length === 1 ? params[0] : params
    })

    return res
  }

  return mapValues(selectors, globalizeSelector)
}
Example #9
Source File: convert.ts    From ui5-language-assistant with Apache License 2.0 6 votes vote down vote up
function convertAggregation(
  libName: string,
  jsonAggregation: apiJson.Ui5Aggregation,
  parent: model.UI5Class
): model.UI5Aggregation {
  const meta = convertMeta(libName, jsonAggregation);
  const aggregation: model.UI5Aggregation = {
    kind: "UI5Aggregation",
    ...meta,
    name: jsonAggregation.name,
    parent: parent,
    type:
      jsonAggregation.type === undefined
        ? undefined
        : {
            kind: "UnresolvedType",
            name: jsonAggregation.type,
          },
    altTypes: isArray(jsonAggregation.altTypes)
      ? map(jsonAggregation.altTypes, (_) => ({
          kind: "UnresolvedType",
          name: _,
        }))
      : [],
    cardinality: jsonAggregation.cardinality ?? "0..n",
  };
  return aggregation;
}
Example #10
Source File: pivot-facet.ts    From S2 with MIT License 6 votes vote down vote up
private getColLabelLength(col: Node) {
    // 如果 label 字段形如 "["xx","xxx"]",直接获取其长度
    const labels = safeJsonParse(col?.value);
    if (isArray(labels)) {
      return labels.length;
    }

    // 否则动态采样前50条数据,如果数据value是数组类型,获取其长度
    const { dataSet } = this.cfg;
    const multiData = dataSet.getMultiData(
      col.query,
      col.isTotals || col.isTotalMeasure,
    );
    // 采样前50,根据指标个数获取单元格列宽
    const demoData = multiData?.slice(0, 50) ?? [];
    const lengths = [];
    forEach(demoData, (value) => {
      forIn(value, (v: MultiData) => {
        if (isObject(v) && v?.values) {
          lengths.push(size(v?.values[0]));
        }
      });
    });
    return max(lengths) || 1;
  }
Example #11
Source File: Template.tsx    From easy-email with MIT License 6 votes vote down vote up
export function Template(props: TemplateProps) {
  let formatChildren = props.children;

  if (Array.isArray(formatChildren)) {
    formatChildren = flatMap(formatChildren);
  }

  return (
    <MjmlBlock
      attributes={omit(props, ['data', 'children', 'value'])}
      type={BasicType.TEMPLATE}
      value={{ idx: props.idx }}
    >
      {formatChildren}
    </MjmlBlock>
  );
}
Example #12
Source File: ParamInfo.tsx    From hub with Apache License 2.0 6 votes vote down vote up
Link: ElementType = (data: LinkProps) => {
  const linkIcon =
    data.children && isArray(data.children) && data.children[0] === 'iconLink' ? (
      <FiExternalLink className={`position-relative ${styles.linkIcon}`} />
    ) : undefined;

  return (
    <a href={data.href} target={data.target} rel="noopener noreferrer" className="d-inline-block text-dark">
      {linkIcon || data.children}
    </a>
  );
}
Example #13
Source File: helper.ts    From backstage with Apache License 2.0 6 votes vote down vote up
export function generateExampleOutput(schema: Schema): unknown {
  const { examples } = schema as { examples?: unknown };
  if (examples && Array.isArray(examples)) {
    return examples[0];
  }
  if (schema.type === 'object') {
    return Object.fromEntries(
      Object.entries(schema.properties ?? {}).map(([key, value]) => [
        key,
        generateExampleOutput(value),
      ]),
    );
  } else if (schema.type === 'array') {
    const [firstSchema] = [schema.items]?.flat();
    if (firstSchema) {
      return [generateExampleOutput(firstSchema)];
    }
    return [];
  } else if (schema.type === 'string') {
    return '<example>';
  } else if (schema.type === 'number') {
    return 0;
  } else if (schema.type === 'boolean') {
    return false;
  }
  return '<unknown>';
}
Example #14
Source File: number-set.ts    From dyngoose with ISC License 6 votes vote down vote up
toDynamo(values: Value): DynamoDB.AttributeValue {
    if (!isArray(values) || !every(values, isNumber)) {
      throw new ValidationError(`Expected ${this.propertyName} to be an array of numbers`)
    }

    // dynamodb does not allow sets to contain duplicate values, so ensure uniqueness here
    return {
      NS: uniq(values.map((value) => numberToString(value))),
    }
  }
Example #15
Source File: api.ts    From brick-design with MIT License 6 votes vote down vote up
function responseAdaptor(ret: any, api: ApiObject) {
  let hasStatusField = true;
  if (!ret) {
    throw new Error('Response is empty!');
  } else if (!has(ret, 'status')) {
    hasStatusField = false;
  }
  const result = ret.data || ret.result;
  const payload: Payload = {
    ok: hasStatusField === false || ret.status == 0,
    status: hasStatusField === false ? 0 : ret.status,
    msg: ret.msg || ret.message,
    msgTimeout: ret.msgTimeout,
    data: Array.isArray(result) ? { items: result } : result, // 兼容直接返回数据的情况
    isNotState: api.isNotState,
    isPageState: api.isPageState,
  };

  if (payload.status == 422) {
    payload.errors = ret.errors;
  }

  if (payload.ok && api.responseData) {
    payload.data = dataMapping(
      api.responseData,
      createObject({ api }, payload.data || {}),
    );
  }
  return payload;
}
Example #16
Source File: commands.ts    From o7 with MIT License 6 votes vote down vote up
// Just a quick check, things can still be wrong.
function isValid(command: Command, path: string) {
  if (!command.name || typeof command.name !== 'string') {
    console.error(`Invalid command at ${path}; 'name' is undefined or not a string.`);
    return false;
  }

  if (!command.alias || !isArray(command.alias) || isEmpty(command.alias)) {
    console.error(`Invalid command at ${path}; 'alias' is undefined, not an array, or empty.`);
    return false;
  }

  if (!command.handler || typeof command.handler !== 'function') {
    console.error(`Invalid command at ${path}; 'handler' is undefined or not a function.`);
    return false;
  }
  return true;
}
Example #17
Source File: ItemsTypeModify.tsx    From yforms with MIT License 6 votes vote down vote up
checkboxGroupModify: YFormFieldBaseProps<YCheckGroupProps>['modifyProps'] = ({
  itemProps,
  componentProps,
}) => {
  const { options } = componentProps;
  return {
    itemProps: {
      viewProps: {
        format: (value, pureValue) => {
          if (value && isArray(value)) {
            const list = [];
            forEach(options, (item) => {
              if (includes(value, item.id)) {
                list.push(item.name);
              }
            });
            if (pureValue) {
              if (isArray(value)) {
                return map(value, (item) => item).join('-');
              }
              return value;
            }
            return map(list, (item, index) => <Tag key={index}>{item}</Tag>);
          }
        },
      },
      ...itemProps,
    },
  };
}
Example #18
Source File: index.tsx    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
// istanbul ignore next
  private _getSelectedRowsWithChildren = (
    row: Record<string, any>
  ): Record<string, any>[] => {
    const result: Record<string, any>[] = [];
    if (
      !isEmpty(row[this.childrenColumnName]) &&
      isArray(row[this.childrenColumnName])
    ) {
      forEach(row[this.childrenColumnName], (item) => {
        result.push(item);
        result.push(...this._getSelectedRowsWithChildren(item));
      });
    }
    return result;
  };
Example #19
Source File: paramsSerializer.ts    From linkedin-private-api with MIT License 6 votes vote down vote up
paramsSerializer = (params: Record<string, string | Record<string, string>>): string => {
  const encodedParams = mapValues(params, value => {
    if (!isArray(value) && !isPlainObject(value)) {
      return value.toString();
    }

    if (isArray(value)) {
      return `List(${value.join(',')})`;
    }

    const encodedList = reduce(
      value as Record<string, string>,
      (res, filterVal, filterKey) => `${res}${res ? ',' : ''}${encodeFilter(filterVal, filterKey)}`,
      '',
    );

    return `List(${encodedList})`;
  });

  return stringify(encodedParams, undefined, undefined, {
    encodeURIComponent: uri => uri,
  });
}
Example #20
Source File: index.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
getInitConditions = <T extends ConditionType>(conditions: Array<ICondition<T>>, valueMap: Obj) => {
  const showIndexArr = map(conditions, 'showIndex');
  const maxShowIndex = max(showIndexArr) as number;
  let curMax = maxShowIndex;
  const reConditions = map(conditions, (item) => {
    const curValue = valueMap[item.key];
    // 有值默认展示
    if ((!has(item, 'showIndex') && curValue !== undefined) || (isArray(curValue) && !isEmpty(curValue))) {
      curMax += 1;
      return { ...item, showIndex: curMax };
    }
    return { ...item };
  });
  return reConditions;
}
Example #21
Source File: index.tsx    From gant-design with MIT License 6 votes vote down vote up
getFormSchema = columns => {
  const schema = {
    type: 'object',
    propertyType: {},
  };
  const setPropertyType = currentColumn => {
    if (!currentColumn || !get(currentColumn, 'fieldName')) {
      return;
    }
    if (isArray(currentColumn.children)) {
      currentColumn.children.forEach((c: any) => {
        setPropertyType(c);
      });
      return;
    }
    const { fieldName, title, props, componentType } = currentColumn;
    set(schema, `propertyType.${fieldName}`, {
      title,
      type: 'string',
      componentType,
      props,
    });
  };
  columns.forEach(column => {
    setPropertyType(column);
  });
  return schema;
}
Example #22
Source File: get-all-archives.ts    From js-client with MIT License 6 votes vote down vote up
makeGetKitArchives = (context: APIContext) => {
	const getAllScheduledTasks = makeGetAllScheduledTasks(context);

	return async (): Promise<Array<KitArchive>> => {
		const path = '/api/kits/build/history';
		const url = buildURL(path, { ...context, protocol: 'http' });

		const req = buildHTTPRequestWithAuthFromContext(context);

		const raw = await context.fetch(url, { ...req, method: 'GET' });
		const rawRes = await parseJSONResponse<Array<RawKitArchive>>(raw);

		const scheduledTasks = await getAllScheduledTasks();
		return isArray(rawRes) ? Promise.all(rawRes.map(rawKitArchive => toKitArchive(rawKitArchive, scheduledTasks))) : [];
	};
}
Example #23
Source File: util.ts    From gio-design with Apache License 2.0 6 votes vote down vote up
selectStatus = (value?: string | number, values?: MaybeArray<string | number>) => {
  if (!isNil(value)) {
    return isArray(values) ? (values as (string | number)[])?.indexOf(value) !== -1 : values === value;
  }
  return false;
}
Example #24
Source File: helpers.ts    From leda with MIT License 6 votes vote down vote up
filterData = ({
  data,
  filterRule,
  filterValue,
  searchFields,
  textField,
}: FilterDataProps): DropDownSelectProps['data'] => {
  if (!data) return undefined;

  const filteredData = data.filter((item) => {
    const isValueMatchingTextField = filterSuggestionByRule(getText(item, textField), filterValue ?? '', filterRule);

    if (isArray(searchFields) && textField && isObject(item)) {
      const isValueMatchingSearchFields = searchFields.some((searchField) => {
        if (item[searchField] === undefined) return false;
        return filterSuggestionByRule(item[searchField].toString(), filterValue ?? '', filterRule);
      });
      return isValueMatchingTextField || isValueMatchingSearchFields;
    }

    return isValueMatchingTextField;
  });

  if (filteredData.length === 0) return undefined;

  return filteredData;
}
Example #25
Source File: list-sources.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
fetchPluginVersions = async (versionsUrl: string): Promise<List<IDbmsPluginVersion> | null> => {
    const response = await requestJson(versionsUrl).catch(() => null);

    if (!isArray(response)) {
        return null;
    }

    return List.of(response).mapEach((version) => new DbmsPluginVersionModel(version));
}
Example #26
Source File: useDateRangeSearch.ts    From condo with MIT License 6 votes vote down vote up
useDateRangeSearch = <F> (
    filterKey: string,
    loading: boolean,
): [null | DayJSRangeType, (search: DayJSRangeType) => void] => {
    const router = useRouter()
    const filtersFromQuery = getFiltersFromQuery<F>(router.query)
    const searchValueFromQuery = get(filtersFromQuery, filterKey, null)
    const dateRange: DayJSRangeType = isArray(searchValueFromQuery)
        ? [dayjs(searchValueFromQuery[0]), dayjs(searchValueFromQuery[1])]
        : null

    const searchChange = useCallback(
        debounce(
            async (searchString) => {
                await updateQuery(router, {
                    ...filtersFromQuery,
                    [filterKey]: searchString,
                })
            },
            400,
        ),
        [loading, searchValueFromQuery],
    )

    const handleSearchChange = (value: DayJSRangeType): void => {
        searchChange(value)
    }

    return [dateRange, handleSearchChange]
}
Example #27
Source File: StorageTask.ts    From guardian with Apache License 2.0 6 votes vote down vote up
async start<T extends BaseSubstrateGuardian>(guardian: T) {
    const { apiRx } = await guardian.isReady();

    const { name, args } = this.arguments;

    if (isArray(name)) {
      return from(name).pipe(mergeMap((name) => createCall(apiRx, name)));
    }
    return createCall(apiRx, name, isArray(args) ? args : [args]);
  }
Example #28
Source File: extract-error.ts    From querybook with Apache License 2.0 6 votes vote down vote up
export function extractFormikError(rootErrors: Record<string, any>): string[] {
    const errorDescriptions = [];

    const helper = (errors: any, path: string = '') => {
        if (isString(errors)) {
            errorDescriptions.push(`${path}: ${errors}`);
            return;
        }
        if (isObject(errors) || isArray(errors)) {
            // It can be an array, object, or string
            for (const [parentName, childErrors] of Object.entries(errors)) {
                helper(
                    childErrors,
                    path ? path + '.' + parentName : parentName
                );
            }
        }
    };

    helper(rootErrors);

    return errorDescriptions;
}
Example #29
Source File: processDataFrame.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
function convertTableToDataFrame(table: TableData): DataFrame {
  const fields = table.columns.map(c => {
    const { text, ...disp } = c;
    return {
      name: text, // rename 'text' to the 'name' field
      config: (disp || {}) as FieldConfig,
      values: new ArrayVector(),
      type: FieldType.other,
    };
  });

  if (!isArray(table.rows)) {
    throw new Error(`Expected table rows to be array, got ${typeof table.rows}.`);
  }

  for (const row of table.rows) {
    for (let i = 0; i < fields.length; i++) {
      fields[i].values.buffer.push(row[i]);
    }
  }

  for (const f of fields) {
    const t = guessFieldTypeForField(f);
    if (t) {
      f.type = t;
    }
  }

  return {
    fields,
    refId: table.refId,
    meta: table.meta,
    name: table.name,
    length: table.rows.length,
  };
}