lodash#isNil TypeScript Examples

The following examples show how to use lodash#isNil. 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: analysis-utils.ts    From prism-frontend with MIT License 7 votes vote down vote up
export function getAlertMessage(
  aggregateData: AsyncReturnType<typeof fetchApiData>,
  alert: Alert,
): string | undefined {
  const { wcsConfig } = alert.alertConfig;
  const { scale, offset } = wcsConfig || {};
  const { min: alertMin, max: alertMax } = alert;

  let alertMessage;

  aggregateData.forEach((data) => {
    const minValue = scaleValueIfDefined(
      get(data, 'stats_min') as number,
      scale,
      offset,
    ) as number;
    const maxValue = scaleValueIfDefined(
      get(data, 'stats_max') as number,
      scale,
      offset,
    );

    if (!isNil(alertMin) && minValue < alertMin!) {
      // eslint-disable-next-line fp/no-mutation
      alertMessage = `Minimum value ${minValue} is below the threshold ${alertMin}.`;
    }

    if (!isNil(alertMax) && maxValue > alertMax!) {
      // eslint-disable-next-line fp/no-mutation
      alertMessage = `Maximum value ${maxValue} is above the threshold ${alertMax}.`;
    }
  });
  return alertMessage;
}
Example #2
Source File: util.ts    From S2 with MIT License 7 votes vote down vote up
getCellPadding = () => {
  const padding = [12, 4, 12, 4];
  const left = isNil(padding[3]) ? 0 : padding[3];
  const right = isNil(padding[1]) ? 0 : padding[1];
  const top = isNil(padding[0]) ? 0 : padding[0];
  const bottom = isNil(padding[2]) ? 0 : padding[2];
  return {
    left,
    right,
    top,
    bottom,
  };
}
Example #3
Source File: query.utils.ts    From nestjs-rest-microservices with MIT License 7 votes vote down vote up
async getPage(page: any): Promise<number> {
    let result = 1

    if (isEmpty(page)) return result

    if (!isNil(page)) result = parseInt(page, 10)
    if (result < 1) result = 1

    return result
  }
Example #4
Source File: utils.ts    From ts-di-starter with MIT License 7 votes vote down vote up
/**
 * Assert properties of object
 *
 * @param {{}} obj
 * @param {string[]} properties
 * @returns {void}
 */
export function assertProperties(obj: any, properties: string[]): void {
  if (!isObject(obj)) throw new Error('not object');
  if (properties.length === 0) throw new Error('no properties provided');

  properties.map((prop) => assert(!isNil(obj[prop]), `${prop} not found on obj`));
}
Example #5
Source File: utils.tsx    From gant-design with MIT License 7 votes vote down vote up
export function getSchemaRenderCount(schema: Schema): number {
	let index = 0
	const { propertyType } = schema
	const keys = Reflect.ownKeys(propertyType)
	return keys.reduce<number>((count, key: string) => {
		const subSchema = propertyType[key]
		if (!isNil(subSchema.propertyType)) return count + getSchemaRenderCount(subSchema)
		return count + (subSchema.hide ? 0 : 1)
	}, index)
}
Example #6
Source File: utils.ts    From gio-design with Apache License 2.0 7 votes vote down vote up
getColumnKey = <RecordType>(column: ColumnType<RecordType>, defaultKey: string): Key => {
  const { key, dataIndex } = column;
  if (!isNil(key)) return key;
  if (!isNil(dataIndex)) {
    return (isArray(dataIndex) ? dataIndex.join('-') : dataIndex) as Key;
  }

  return defaultKey;
}
Example #7
Source File: resolveCommentStatus.ts    From strapi-plugin-comments with MIT License 6 votes vote down vote up
resolveCommentStatus = ({
  removed,
  blocked,
  blockedThread,
  approvalStatus,
  reviewFlowEnabled,
}: ToBeFixed) => {
  const gotApprovalFlow = !isNil(approvalStatus);

  if (removed) {
    return COMMENT_STATUS.REMOVED;
  }

  if (blocked || blockedThread) {
    return COMMENT_STATUS.BLOCKED;
  }

  if (reviewFlowEnabled) {
    return COMMENT_STATUS.TO_REVIEW;
  }

  if (gotApprovalFlow) {
    const status = approvalStatus.toUpperCase();
    if (Object.keys(COMMENT_STATUS).includes(status)) {
      return status;
    }
    return COMMENT_STATUS.UNKNOWN;
  }

  return COMMENT_STATUS.OPEN;
}
Example #8
Source File: base-data-set.ts    From S2 with MIT License 6 votes vote down vote up
public getValueRangeByField(field: string): ValueRange {
    const cacheRange = getValueRangeState(this.spreadsheet, field);
    if (cacheRange) {
      return cacheRange;
    }
    const fieldValues = compact(
      map(this.originData, (item) => {
        const value = item[field] as string;
        return isNil(value) ? null : Number.parseFloat(value);
      }),
    );
    const range = {
      maxValue: max(fieldValues),
      minValue: min(fieldValues),
    };
    setValueRangeState(this.spreadsheet, {
      [field]: range,
    });
    return range;
  }
Example #9
Source File: augment-site-data.ts    From aqualink-app with MIT License 6 votes vote down vote up
async function getAugmentedData(
  site: Site,
  regionRepository: Repository<Region>,
) {
  const [longitude, latitude] = (site.polygon as Point).coordinates;

  const region =
    site.region || (await getRegion(longitude, latitude, regionRepository));

  const MMM = await getMMM(longitude, latitude);
  if (MMM === null) {
    console.warn(
      `Max Monthly Mean appears to be null for Site ${site.name} at (lat, lon): (${latitude}, ${longitude}) `,
    );
  }

  const timezones = geoTz(latitude, longitude);

  return omitBy(
    {
      region,
      timezone: timezones.length > 0 ? timezones[0] : null,
      maxMonthlyMean: MMM,
    },
    isNil,
  );
}
Example #10
Source File: pack-external-module.ts    From malagu with MIT License 6 votes vote down vote up
/**
 * Find the original module that required the transient dependency. Returns
 * undefined if the module is a first level dependency.
 * @param {Object} issuer - Module issuer
 */
// eslint-disable-next-line no-null/no-null
function findExternalOrigin(stats: Stats, issuer: Module | null): any {
    if (!isNil(issuer) && (issuer as any).rawRequest.startsWith('./')) {
        return findExternalOrigin(stats, stats.compilation.moduleGraph.getIssuer(issuer));
    }
    return issuer;
}
Example #11
Source File: calcFlowInfo.ts    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
export function calcFlowInfo(flowList: FlowInfo[], fieldData: FieldValue): any {
  const selectedFlow = flowList.find(
    (item) => item.stepId === fieldData.stepId
  );

  if (!selectedFlow) {
    // eslint-disable-next-line no-console
    console.warn(`The ${fieldData.stepId} of step don't exist`);
    return flowList;
  }

  const fieldsMappingFrontend = selectedFlow.action.fieldsMappingFrontend;

  if (isNil(fieldsMappingFrontend)) {
    selectedFlow.action.fieldsMappingFrontend = [omit(fieldData, "stepId")];
    return flowList;
  }

  if (isEmpty(fieldsMappingFrontend) && Array.isArray(fieldsMappingFrontend)) {
    fieldsMappingFrontend.push(omit(fieldData, "stepId"));
    return flowList;
  }

  const selectedField = selectedFlow.action.fieldsMappingFrontend?.find(
    (item) => item.name === fieldData.name
  );

  if (!selectedField) {
    fieldsMappingFrontend.push(omit(fieldData, "stepId"));
    return flowList;
  }

  selectedField.value = fieldData.value;
  selectedField.source = fieldData.source;
  selectedFlow.action.fieldsMappingType = "form";

  return flowList;
}
Example #12
Source File: menu.ts    From next-core with GNU General Public License v3.0 6 votes vote down vote up
export async function constructMenu(
  menuBar: MountRoutesResult["menuBar"],
  context: PluginRuntimeContext,
  kernel: Kernel
): Promise<void> {
  const hasSubMenu = !!menuBar.subMenuId;
  if (menuBar.menuId) {
    const defaultCollapsed = menuBar.menu?.defaultCollapsed;
    const menu = await processMenu(menuBar.menuId, context, kernel, hasSubMenu);

    if (!isNil(defaultCollapsed)) {
      menu.defaultCollapsed = defaultCollapsed;
    }

    menuBar.menu = menu;
  }
  if (hasSubMenu) {
    menuBar.subMenu = await processMenu(menuBar.subMenuId, context, kernel);
  } else {
    menuBar.subMenu = null;
  }
}
Example #13
Source File: index.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * This is a component which should be placed at a scrollable component
 * once prop triggerBy changes, it will automatically scroll to top(when toPageTop is true)
 * or the position it placed
 * @export
 * @param {IProps} props
 */
function SwitchAutoScroll(props: IProps) {
  const positionRef = React.useRef(null);
  React.useEffect(() => {
    if (!isNil(props.triggerBy)) {
      if (props.toPageTop) {
        const mainDom = document.querySelector('#main');
        mainDom && (mainDom.scrollTop = 0);
      } else if (positionRef.current) {
        (positionRef.current as any).scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'start' });
      }
    }
  }, [props.toPageTop, props.triggerBy]);

  return props.toPageTop ? null : <div ref={positionRef} />;
}
Example #14
Source File: InputNumber.tsx    From gant-design with MIT License 6 votes vote down vote up
withInputNumber = compose(
  withProps(({ value, onChange, format }) => {
    let $value = value;
    const notnumber = value && !isNumber(value);
    if (notnumber) {
      $value = null
    }
    if (!isNil($value)) {
      $value = numeral($value).value()
    }

    return {
      value: $value,
      onChange: (val) => {
        let numberVal = val;
        if (format) {
          numberVal = Number(numeral(numberVal).format(format));
        }
        onChange && onChange(numberVal);
      }
    }
  })
)
Example #15
Source File: delete-many-scheduled-queries.ts    From js-client with MIT License 6 votes vote down vote up
makeDeleteManyScheduledQueries = (context: APIContext) => {
	const deleteOneScheduledQuery = makeDeleteOneScheduledQuery(context);
	const getAllScheduledQueries = makeGetAllScheduledQueries(context);

	return async (filter: ScheduledTasksFilter = {}): Promise<void> => {
		const queries = await getAllScheduledQueries();
		const filtered = queries.filter(q => {
			if (isNil(filter.userID)) return true;
			return q.userID === filter.userID;
		});

		const deletePs = filtered.map(q => deleteOneScheduledQuery(q.id));
		await Promise.all(deletePs);
	};
}
Example #16
Source File: useValue.ts    From gio-design with Apache License 2.0 6 votes vote down vote up
formatValue = (isMultiple: boolean, value?: MaybeArray<string | number>) => {
  if (isMultiple) {
    if (isNil(value)) {
      return [];
    }
    if (isString(value) || isNumber(value)) {
      return [value];
    }
    return value;
  }
  if (isNil(value)) {
    return '';
  }
  return value;
}
Example #17
Source File: helpers.ts    From leda with MIT License 6 votes vote down vote up
compareItems = (value: number | string | SomeObject | undefined | null, currentItem: number | string | SomeObject, textField?: string): boolean => {
  if (isNil(value)) return false;

  if (!isObject(value) && !isObject(currentItem)) return value === currentItem;

  return textField
    ? (value as SomeObject)[textField] === (currentItem as SomeObject)[textField]
    : false;
}
Example #18
Source File: index.tsx    From strapi-plugin-comments with MIT License 5 votes vote down vote up
DiscussionThread = ({
  level = [],
  selected = {},
  allowedActions,
  isReloading,
}) => {
  const rootThread = selected?.threadOf;
  return (
    <LoadingIndicatorContainer as={Box} padding={4}>
      {isReloading && <LoadingIndicatorOverlay />}
      <Flex
        as={Box}
        direction="row"
        justifyContent="space-between"
        marginBottom={2}
      >
        <Typography
          variant="delta"
          textColor="neutral800"
          id="discussion-thread"
        >
          {getMessage("page.details.panel.discussion", "Discussion")}
        </Typography>
        {rootThread && (
          <Link
            to={getUrl(`discover/${rootThread.id}`)}
            startIcon={<ArrowUp />}
          >
            {getMessage("page.details.panel.discussion.nav.back")}
          </Link>
        )}
      </Flex>
      <Flex as="ul" direction="column" alignItems="flex-start">
        {rootThread && (
          <DiscussionThreadItem
            {...rootThread}
            allowedActions={allowedActions}
            isThreadAuthor
            root
            pinned
          />
        )}
        {level.map((item) => {
          const isSelected = selected.id === item.id;
          const isThreadAuthor =
            !isNil(selected?.threadOf?.author?.id) &&
            selected?.threadOf?.author?.id === item?.author?.id;
          return (
            <DiscussionThreadItem
              key={`comment-${item.id}`}
              {...item}
              allowedActions={allowedActions}
              root={isNil(rootThread)}
              blockedThread={rootThread?.blockedThread || item.blockedThread}
              isSelected={isSelected}
              isThreadAuthor={isThreadAuthor}
            />
          );
        })}
      </Flex>
    </LoadingIndicatorContainer>
  );
}
Example #19
Source File: brush-selection.ts    From S2 with MIT License 5 votes vote down vote up
private getNextScrollDelta = (config: BrushAutoScrollConfig) => {
    const { scrollX, scrollY } = this.spreadsheet.facet.getScrollOffset();

    let x = 0;
    let y = 0;

    if (config.y.scroll) {
      const dir =
        config.y.value > 0 ? ScrollDirection.TRAILING : ScrollDirection.LEADING;
      const rowIndex = this.adjustNextRowIndexWithFrozen(
        this.endBrushPoint.rowIndex,
        dir,
      );
      const nextIndex = this.validateYIndex(
        rowIndex + (config.y.value > 0 ? 1 : -1),
      );
      y = isNil(nextIndex)
        ? 0
        : getScrollOffsetForRow(nextIndex, dir, this.spreadsheet) - scrollY;
    }

    if (config.x.scroll) {
      const dir =
        config.x.value > 0 ? ScrollDirection.TRAILING : ScrollDirection.LEADING;
      const colIndex = this.adjustNextColIndexWithFrozen(
        this.endBrushPoint.colIndex,
        dir,
      );
      const nextIndex = this.validateXIndex(
        colIndex + (config.x.value > 0 ? 1 : -1),
      );
      x = isNil(nextIndex)
        ? 0
        : getScrollOffsetForCol(nextIndex, dir, this.spreadsheet) - scrollX;
    }

    return {
      x,
      y,
    };
  };
Example #20
Source File: surveys.service.ts    From aqualink-app with MIT License 5 votes vote down vote up
async updateMedia(
    editSurveyMediaDto: EditSurveyMediaDto,
    mediaId: number,
  ): Promise<SurveyMedia> {
    if (
      isNil(editSurveyMediaDto.featured) ||
      isNil(editSurveyMediaDto.hidden)
    ) {
      throw new BadRequestException(
        'Features and hidden flags must be provided',
      );
    }

    const surveyMedia = await this.surveyMediaRepository.findOne(mediaId);

    if (!surveyMedia) {
      throw new NotFoundException(
        `Survey media with id ${mediaId} was not found`,
      );
    }

    // Media changes from featured to not featured
    if (
      surveyMedia.featured &&
      (editSurveyMediaDto.hidden || !editSurveyMediaDto.featured)
    ) {
      await this.assignFeaturedMedia(surveyMedia.surveyId.id, mediaId);
    }

    // Media changes from not featured to featured
    if (
      !surveyMedia.featured &&
      !editSurveyMediaDto.hidden &&
      editSurveyMediaDto.featured
    ) {
      await this.surveyMediaRepository.update(
        {
          surveyId: surveyMedia.surveyId,
          featured: true,
        },
        { featured: false },
      );
    }

    const trimmedComments = this.transformComments(editSurveyMediaDto.comments);
    await this.surveyMediaRepository.update(mediaId, {
      ...omit(editSurveyMediaDto, 'surveyPointId'),
      ...(editSurveyMediaDto.surveyPointId
        ? { surveyPoint: { id: editSurveyMediaDto.surveyPointId } }
        : {}),
      featured: !editSurveyMediaDto.hidden && editSurveyMediaDto.featured,
      ...(trimmedComments ? { comments: trimmedComments } : {}),
    });

    const updated = await this.surveyMediaRepository.findOne(mediaId);

    return updated!;
  }
Example #21
Source File: processFieldInitValue.ts    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
export function isInvalidValue(value: unknown): boolean {
  return isNil(value) || value === "";
}