lodash#isFunction TypeScript Examples

The following examples show how to use lodash#isFunction. 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: pageModule.ts    From redux-with-domain with MIT License 6 votes vote down vote up
function initPageWatchers<
  State,
  Selectors,
  Reducers,
  Effects,
  Watchers,
  ActionCreators
>(
  module: PageModule,
  pkg: PageOptions<
    State,
    Selectors,
    Reducers,
    Effects,
    Watchers,
    ActionCreators
  >
) {
  const { namespace } = module

  if (isFunction(pkg.watchers)) {
    module.watchers = createPageWatchers(
      module.actions,
      module.selectors,
      pkg.watchers,
      getAuthCheck[PAGE_MODULE],
      namespace
    )
  }
}
Example #2
Source File: spread-sheet.ts    From S2 with MIT License 6 votes vote down vote up
public showTooltip<T = TooltipContentType>(
    showOptions: TooltipShowOptions<T>,
  ) {
    const { content, event } = showOptions;
    const cell = this.getCell(event?.target);
    const displayContent = isFunction(content)
      ? content(cell, showOptions)
      : content;

    this.tooltip.show?.({
      ...showOptions,
      content: displayContent,
    });
  }
Example #3
Source File: responseBuilder.ts    From ts-di-starter with MIT License 6 votes vote down vote up
/**
   * Use express response object to respond with data or error
   *
   * @param {object} response express response object
   * @param {Promise|Function} dataPromise promise that will resolve into a response or reject with an error
   * @param {number} [successCodeOverride] optionally override the success code specified in the error or the default OK
   * @param {number} [failureCodeOverride] optionally override the code specified in the error or the default 500
   * @returns {Promise<void>}
   */
  async respond(response, dataPromise, successCodeOverride?, failureCodeOverride?): Promise<void> {
    if (successCodeOverride && !Object.values(HTTP_STATUS).includes(successCodeOverride)) {
      log.error('successCodeOverride must be a valid HTTP code, ignoring');
      successCodeOverride = undefined;
    }

    if (failureCodeOverride && !Object.values(HTTP_STATUS).includes(failureCodeOverride)) {
      log.error('failureCodeOverride must be a valid HTTP code, ignoring');
      failureCodeOverride = undefined;
    }

    await Bluebird.try(() => (isFunction(dataPromise) ? dataPromise() : dataPromise))
      .then((data) => {
        // eslint-disable-next-line lodash/prefer-lodash-typecheck
        if (data instanceof Error) {
          return this.errorResponse(data, failureCodeOverride);
        }

        return this.okResponse(data, successCodeOverride);
      })
      .catch((error) => this.errorResponse(error, failureCodeOverride))
      .then((output) => response.status(output.code).json(output));
  }
Example #4
Source File: readonly-field.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
ReadonlyField = ({ renderData, style, className, value }: IProps) => {
  const realData = React.useMemo(() => {
    return renderData
      ? isFunction(renderData)
        ? renderData(value)
        : renderData
      : isPlainObject(value)
      ? JSON.stringify(value)
      : value
      ? value.toString()
      : '-';
  }, [renderData, value]);

  return (
    <div style={{ overflow: 'auto', ...style }} className={className}>
      {realData}
    </div>
  );
}
Example #5
Source File: useSelection.tsx    From gio-design with Apache License 2.0 6 votes vote down vote up
getRowKey = <RecordType,>(row: RecordType, rowKey?: TableProps<RecordType>['rowKey']): Key => {
  if (rowKey) {
    if (isFunction(rowKey)) {
      return rowKey(row);
    }
    if (isString(rowKey)) {
      if (isString(get(row, rowKey))) {
        return getRowAllKeys(row, rowKey);
      }
    }
  }
  return getRowAllKeys(row, 'key');
}
Example #6
Source File: index.tsx    From leda with MIT License 6 votes vote down vote up
A = React.forwardRef((props: AProps, ref?: React.Ref<ARefCurrent>): React.ReactElement | null => {
  const {
    children,
    href,
    onClick,
    shouldRender,
    ...restProps
  } = useProps(props);

  if (shouldRender === false) return null;

  const handleClick: CustomEventHandler<React.MouseEvent<HTMLAnchorElement>> = (ev) => {
    // если href не передали, то нужен preventDefault, иначе - нет
    if (!href) ev.preventDefault();

    if (isFunction(onClick)) onClick(ev);
  };

  return (
    <a
      {...restProps}
      href={href}
      onClick={handleClick}
      ref={ref && ((component) => bindFunctionalRef(component, ref, component && {
        wrapper: component,
      }))}
    >
      {children}
    </a>
  );
}) as React.FC<AProps>
Example #7
Source File: Utils.tsx    From kfp-tekton-backend with Apache License 2.0 6 votes vote down vote up
// TODO: add tests
export async function errorToMessage(error: any): Promise<string> {
  if (error instanceof Error) {
    return error.message;
  }

  if (error && error.text && isFunction(error.text)) {
    return await error.text();
  }

  return JSON.stringify(error) || '';
}
Example #8
Source File: utils.ts    From qiankun with MIT License 6 votes vote down vote up
/** 校验子应用导出的 生命周期 对象是否正确 */
export function validateExportLifecycle(exports: any) {
  const { bootstrap, mount, unmount } = exports ?? {};
  return isFunction(bootstrap) && isFunction(mount) && isFunction(unmount);
}
Example #9
Source File: gates.ts    From guardian with Apache License 2.0 6 votes vote down vote up
and =
  (...args: (boolean | Function)[]) =>
  (input: any) => {
    return args.reduce((acc, item) => {
      if (isFunction(item)) {
        return acc && item(input);
      } else {
        return acc && item;
      }
    }, true);
  }
Example #10
Source File: index.ts    From free-swagger with MIT License 6 votes vote down vote up
prompt = async (questions: any[]) => {
  const results: Record<string, any> = {}
  for (const question of questions) {
    const condition = question.when
    if (condition && !condition(results)) {
      continue
    }
    const normalizeQuestion = omit(question, 'when')
    if (isFunction(normalizeQuestion.default)) {
      normalizeQuestion.default = normalizeQuestion.default(results)
    }
    const answer = (await inquirer.prompt(normalizeQuestion)) as Record<
      string,
      any
    >
    results[question.name] = answer[question.name]
    await question.callback?.(answer[question.name], results)
  }
  return results
}
Example #11
Source File: watchers.ts    From redux-with-domain with MIT License 5 votes vote down vote up
export function createPageWatchers(
  actions,
  selectors,
  watchersOpt,
  checkAuth,
  namespace
) {
  let sagaEffects = effects
  let enhancer = generateSagaEnhancer({}, namespace)

  if (process.env.NODE_ENV === 'development') {
    sagaEffects = wrapEffectsFunc(checkAuth, namespace)
    enhancer = generateSagaEnhancer({}, namespace, checkAuth)
  }

  const watchers = watchersOpt({
    actions,
    selectors,
    enhancer,
    sagaEffects
  })
  const watcherFns: Function[] = []

  function takeWatch(value, key) {
    if (isArray(value)) {
      watcherFns.push(function*() {
        yield effects[value[1]](key, value[0])
      })
    }

    if (isFunction(value)) {
      watcherFns.push(function*() {
        yield effects.takeEvery(key, value)
      })
    }
  }

  forEach(watchers, (value, key) => {
    const keyArr = key.split(',')
    if (keyArr.length > 1) {
      keyArr.forEach(k => {
        takeWatch(value, k)
      })
    } else {
      takeWatch(value, key)
    }
  })
  return watcherFns
}
Example #12
Source File: convert.ts    From ui5-language-assistant with Apache License 2.0 5 votes vote down vote up
function convertClass(
  libName: string,
  symbol: apiJson.ClassSymbol
): model.UI5Class {
  const base = convertSymbol(libName, symbol);
  const clazz: model.UI5Class = {
    ...base,
    kind: "UI5Class",
    abstract: symbol.abstract ?? false,
    ctor: undefined,
    extends: undefined, // Filled later
    implements: [], // Filled later
    aggregations: [],
    associations: [],
    events: [],
    methods: [],
    properties: [],
    fields: [],
    defaultAggregation: undefined, // Filled later
  };

  if (symbol["ui5-metadata"] !== undefined) {
    clazz.aggregations = map(symbol["ui5-metadata"].aggregations, (_) =>
      convertAggregation(libName, _, clazz)
    );
    clazz.associations = map(symbol["ui5-metadata"].associations, (_) =>
      convertAssociation(libName, _, clazz)
    );
    clazz.properties = map(
      symbol["ui5-metadata"].properties,
      partial(convertProperty, libName, clazz)
    );
    // Add special settings (for example: "id" from ManagedObject)
    clazz.properties = clazz.properties.concat(
      map(
        symbol["ui5-metadata"].specialSettings,
        partial(convertProperty, libName, clazz)
      )
    );
  }

  // Due to unfortunate naming, if not defined in the json, symbol.constructor will be a javascript function
  clazz.ctor =
    symbol.constructor === undefined || isFunction(symbol.constructor)
      ? undefined
      : convertConstructor(libName, clazz, symbol.constructor);
  clazz.events = map(symbol.events, partial(convertEvent, libName, clazz));
  clazz.methods = map(symbol.methods, partial(convertMethod, libName, clazz));
  // The "properties" directly under the class symbol are displayed as "fields" in the SDK and are not considered properties
  clazz.fields = map(
    symbol.properties,
    partial(convertProperty, libName, clazz)
  );

  return clazz;
}
Example #13
Source File: table-data-set.ts    From S2 with MIT License 5 votes vote down vote up
//  sortFunc > sortBy > sortFieldId
  handleDimensionValuesSort = () => {
    each(this.sortParams, (item) => {
      const { sortFieldId, sortBy, sortFunc, sortMethod, query } = item;
      // 排序的前提
      if (!sortFieldId) return;

      let data = this.getMovableRows();

      const restData = [];
      if (query) {
        const scopedData = [];
        data.forEach((record) => {
          const keys = Object.keys(query);
          let inScope = true;
          for (let index = 0; index < keys.length; index++) {
            const k = keys[index];
            if (record[k] !== query[k]) {
              inScope = false;
              restData.push(record);
              break;
            }
          }

          if (inScope) {
            scopedData.push(record);
          }
        });
        data = scopedData;
      }

      let sortedData = data;

      if (sortFunc) {
        sortedData = sortFunc({
          ...item,
          data,
        }) as DataType[];
      } else if (sortBy && !isFunction(sortBy)) {
        const reversedSortBy = [...sortBy].reverse();
        sortedData = data.sort((a, b) => {
          const idxA = reversedSortBy.indexOf(a[sortFieldId]);
          const idxB = reversedSortBy.indexOf(b[sortFieldId]);

          return idxB - idxA;
        });
      } else if (isAscSort(sortMethod) || isDescSort(sortMethod)) {
        const func = isFunction(sortBy) ? sortBy : null;
        sortedData = orderBy(
          data,
          [func || sortFieldId],
          [sortMethod.toLocaleLowerCase() as boolean | 'asc' | 'desc'],
        );
      }

      if (restData.length) {
        sortedData = [...sortedData, ...restData];
      }

      // For frozen options
      this.displayData = [
        ...this.getStartRows(),
        ...sortedData,
        ...this.getEndRows(),
      ];
    });
  };
Example #14
Source File: index.tsx    From easy-email with MIT License 5 votes vote down vote up
BlocksProvider: React.FC<{}> = (props) => {
  const [focusIdx, setFocusIdx] = useState(getPageIdx());
  const [dragEnabled, setDragEnabled] = useState(false);
  const [initialized, setInitialized] = useState(false);
  const [collapsed, setCollapsed] = useState(true);
  const [activeTab, setActiveTab] = useState(ActiveTabKeys.EDIT);

  const onChangeTab: React.Dispatch<React.SetStateAction<ActiveTabKeys>> = useCallback((handler) => {
    if (isFunction(handler)) {
      setActiveTab((currentTab) => {
        const nextTab = handler(currentTab);
        const next = EventManager.exec(EventType.ACTIVE_TAB_CHANGE, { currentTab, nextTab });
        if (next) return nextTab;
        return currentTab;
      });
    }
    setActiveTab((currentTab) => {
      let nextTab = handler as ActiveTabKeys;
      const next = EventManager.exec(EventType.ACTIVE_TAB_CHANGE, { currentTab, nextTab });
      if (next) return nextTab;
      return currentTab;
    });
  }, []);

  return (
    <BlocksContext.Provider
      value={{
        initialized,
        setInitialized,
        focusIdx,
        setFocusIdx,
        dragEnabled,
        setDragEnabled,
        collapsed,
        setCollapsed,
        activeTab,
        setActiveTab: onChangeTab,
      }}
    >
      {props.children}
    </BlocksContext.Provider>
  );
}
Example #15
Source File: responseBuilder.ts    From ts-di-starter with MIT License 5 votes vote down vote up
/* eslint-disable sonarjs/cognitive-complexity */
  /**
   * Wrap controller function in response builder
   *
   * @param {Promise|Function} controllerFunction promise that will resolve into a response or reject with an error
   * @param {number} [successCodeOverride] optionally override the success code specified in the error or the default OK
   * @param {number} [failureCodeOverride] optionally override the code specified in the error or the default 500
   * @returns {Function}
   */
  wrap(controllerFunction, successCodeOverride?, failureCodeOverride?): (request, response, next?) => Promise<void> {
    if (!isFunction(controllerFunction)) {
      throw new TypeError('controllerFunction must be a function');
    }

    successCodeOverride = successCodeOverride || (controllerFunction as any).successCodeOverride;
    failureCodeOverride = failureCodeOverride || (controllerFunction as any).failureCodeOverride;

    return async (request, response, next): Promise<void> => {
      if (isNil(request)) throw new Error('request must be an object');
      if (isNil(response)) throw new Error('response must be an object');

      if (successCodeOverride && !Object.values(HTTP_STATUS).includes(successCodeOverride)) {
        log.error('successCodeOverride must be a valid HTTP code, ignoring');
        successCodeOverride = undefined;
      }

      if (failureCodeOverride && !Object.values(HTTP_STATUS).includes(failureCodeOverride)) {
        log.error('failureCodeOverride must be a valid HTTP code, ignoring');
        failureCodeOverride = undefined;
      }

      let nextCalled = null as null | NextInterface;
      const nextCheck = (route): void => {
        nextCalled = (): void => next(route);
      };

      await Bluebird.try(() => (isFunction(controllerFunction) ? controllerFunction(request, response as any, nextCheck) : controllerFunction))
        // eslint-disable-next-line sonarjs/no-identical-functions
        .then((data) => {
          // eslint-disable-next-line lodash/prefer-lodash-typecheck
          if (data instanceof Error) {
            return this.errorResponse(data, failureCodeOverride);
          }

          return this.okResponse(data, successCodeOverride);
        })
        .catch((error) => this.errorResponse(error, failureCodeOverride))
        .then(async (output) => {
          if (response.headersSent) {
            return;
          }

          if (output.code >= HTTP_STATUS.BAD_REQUEST) {
            request.locals.limitResult = await this.services.limiters.error.consume(request.ip, request.locals.limitResult);
          }

          if (nextCalled) {
            nextCalled();
            return;
          }

          attachLimitToRequest(request, response);

          if (request.locals?.limitResult?.blockReason) {
            log.warn(`Overriding code: ${output.code} due to rate limit: ${request.locals?.limitResult?.blockReason} from IP: ${request.ip}`);
            output.message = request.locals?.limitResult?.blockReason;
            output.code = HTTP_STATUS.TOO_MANY_REQUESTS;
            response.status(HTTP_STATUS.TOO_MANY_REQUESTS).json(output);
          } else {
            response.status(output.code).json(output);
          }
        });
    };
  }
Example #16
Source File: go-to.tsx    From erda-ui with GNU Affero General Public License v3.0 5 votes vote down vote up
goTo = (pathStr: string, options?: IOptions) => {
  const { replace = false, forbidRepeat = false, jumpOut = false, query, ...rest } = (options as IOptions) || {};
  let _path = '';

  if (/^(http|https):\/\//.test(pathStr)) {
    // 外链
    if (jumpOut) {
      window.open(pathStr);
    } else {
      window.location.href = pathStr;
    }
    return;
  } else if (pathStr.startsWith(goTo.pagePrefix)) {
    const orgName = get(location.pathname.split('/'), '[1]') || '-';
    const [urlParams, urlQuery] = routeInfoStore.getState((s) => [s.params, s.query]);
    const pathParams = { orgName, ...urlParams, ...urlQuery, ...rest };
    const curPath = goTo.pagePathMap[pathStr.replace(goTo.pagePrefix, '')];
    // 缺少参数
    if (curPath === undefined) {
      return;
    }

    _path = isFunction(curPath) ? curPath(pathParams) : curPath;
  } else {
    _path = resolvePath(pathStr);
  }
  if (query && !isEmpty(query)) {
    _path += `?${qs.stringify(query)}`;
  }

  if (_path.endsWith('?')) _path = _path.replace('?', '');

  if (jumpOut) {
    window.open(_path);
    return;
  }
  const curPath = `${location.pathname}${location.search}`;
  if (curPath === _path) return;

  const action = replace ? 'replace' : 'push';

  if (forbidRepeat) {
    changeBrowserHistory(action, _path);
  } else {
    const history = getConfig('history');
    action === 'replace' ? history.replace(_path) : history.push(_path);
  }
}
Example #17
Source File: ResizableTable.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
function ResizableTable<RecordType = Record<string, unknown>>(
  props: TableProps<RecordType>,
  ref: React.ForwardedRef<HTMLDivElement>
) {
  const { columns = [], dataSource, ...restProps } = props;

  const [columnsState, setColumnsState] = useState<ColumnsType<RecordType>>(columns);
  const previousColumnsRef = useRef<ColumnsType<RecordType>>(columns);

  useEffect(() => {
    const handleResize =
      (index: number): ResizableProps['onResize'] =>
        (_event, { size }) => {
          const nextColumns = [...previousColumnsRef.current];

          const prevWidth = Number.parseInt(`${nextColumns[index].width}`, 10);
          const nextPrevWidth = Number.parseInt(`${nextColumns[index + 1].width}`, 10);

          nextColumns[index] = {
            ...nextColumns[index],
            width: size.width < prevWidth + nextPrevWidth - 58 ? size.width : prevWidth + nextPrevWidth - 58,
          };

          nextColumns[index + 1] = {
            ...nextColumns[index + 1],
            width: nextPrevWidth + (prevWidth - size.width) <= 58 ? 58 : nextPrevWidth + (prevWidth - size.width),
          };

          setColumnsState(nextColumns);
        };

    const getOnHeaderCell = (column: ColumnType<RecordType>, index: number) => {
      if (isFunction(column.onHeaderCell)) {
        const headerCell = column.onHeaderCell(column) || {};
        return (cell: ColumnType<RecordType>) => ({
          ...headerCell,
          width: cell.width,
          onResize: handleResize(index),
        });
      }
      return (cell: ColumnType<RecordType>) => ({
        width: cell.width,
        onResize: handleResize(index),
      });
    };

    setColumnsState((oldColumnsState) =>
      oldColumnsState.filter(Boolean).map<ColumnType<RecordType>>((column, index) => ({
        ...column,
        onHeaderCell: getOnHeaderCell(column, index) as unknown as ColumnType<RecordType>['onHeaderCell'],
      }))
    );
  }, []);

  useEffect(() => {
    previousColumnsRef.current = columnsState;
  }, [columnsState]);

  const components = useMemo(
    () => ({
      header: {
        cell: ResizableTitle,
      },
    }),
    []
  );

  return (
    <Table<RecordType>
      components={components}
      dataSource={dataSource}
      columns={columnsState}
      ref={ref}
      {...restProps}
    />
  );
}
Example #18
Source File: handlers.ts    From leda with MIT License 5 votes vote down vote up
suggestionClickHandlerCreator = ({
  data,
  isValueControlled,
  name,
  onChange,
  setIsFocused,
  setStateValue,
  setHighlightedSuggestion,
  textField,
}: {
  data: Suggestion[],
  textField?: string,
  name?: string,
  onChange: (event: ChangeEvent) => void,
  isValueControlled: boolean,
  setStateValue: SetState<string>,
  setIsFocused: SetState<boolean>,
  setHighlightedSuggestion: SetState<Suggestion>,
}): CustomEventHandler<React.MouseEvent<HTMLElement> & SuggestionTarget> => (event) => {
  if (isObject(event.target.value) && textField === undefined) {
    // todo handle error
    return;
  }

  const value = isObject(event.target.value)
    ? event.target.value[textField as string] as string
    : event.target.value.toString();

  const suggestion = isObject(event.target.value)
    ? event.target.value as DataObject
    : getSuggestionFromValue({ data, value, textField });

  const customEvent: ChangeEvent = {
    ...event,
    component: {
      method: CHANGE_METHOD.click,
      name,
      suggestion,
      value,
    },
  };

  setHighlightedSuggestion(suggestion);

  if (isFunction(onChange)) onChange(customEvent);
  if (!isValueControlled) setStateValue(value);
  setIsFocused(false);
}