lodash#isUndefined TypeScript Examples

The following examples show how to use lodash#isUndefined. 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: pivot-data-set.ts    From S2 with MIT License 6 votes vote down vote up
getCustomData = (path: number[]) => {
    let hadUndefined = false;
    let currentData: DataType | DataType[] | DataType[][] = this.indexesData;

    for (let i = 0; i < path.length; i++) {
      const current = path[i];
      if (hadUndefined) {
        if (isUndefined(current)) {
          currentData = customFlatten(currentData) as [];
        } else {
          currentData = values(currentData)?.map(
            (d) => d && get(d, current),
          ) as [];
        }
      } else if (isUndefined(current)) {
        hadUndefined = true;
      } else {
        currentData = currentData?.[current];
      }
    }

    return currentData;
  };
Example #2
Source File: collections.service.ts    From aqualink-app with MIT License 6 votes vote down vote up
async update(collectionId: number, updateCollectionDto: UpdateCollectionDto) {
    const collection = await this.collectionRepository.findOne(collectionId);

    if (!collection) {
      throw new NotFoundException(
        `Collection with ID ${collectionId} not found.`,
      );
    }

    const { name, isPublic, userId, addSiteIds, removeSiteIds } =
      updateCollectionDto;

    const filteredAddSiteIds = addSiteIds?.filter(
      (siteId) => !collection.siteIds.includes(siteId),
    );

    await this.collectionRepository
      .createQueryBuilder('collection')
      .relation('sites')
      .of(collection)
      .addAndRemove(filteredAddSiteIds || [], removeSiteIds || []);

    await this.collectionRepository.update(
      {
        id: collectionId,
      },
      {
        ...omitBy({ name, isPublic }, isUndefined),
        ...(userId !== undefined ? { user: { id: userId } } : {}),
      },
    );

    return this.collectionRepository.findOne(collection!.id);
  }
Example #3
Source File: CodeEditor.tsx    From hub with Apache License 2.0 6 votes vote down vote up
CodeEditor: ElementType = (props: Props) => {
  const { ctx } = useContext(AppCtx);
  const { effective } = ctx.prefs.theme;

  const isDisabled = !isUndefined(props.disabled) && props.disabled;

  return (
    <CodeMirror
      className={classnames('border position-relative h-100', styles.code, { [styles.disabled]: isDisabled })}
      value={props.value}
      options={{
        mode: {
          name: props.mode,
          json: true,
          statementIndent: 2,
        },
        theme: effective === 'dark' ? 'material-darker' : 'elegant',
        lineNumbers: true,
        inputStyle: 'contenteditable',
        viewportMargin: Infinity,
        readOnly: isDisabled ? 'nocursor' : false,
        tabindex: 0,
      }}
      editorDidMount={(editor) => {
        editor.setSize('', '100%');
      }}
      onBeforeChange={(editor: any, data: any, value: string) => {
        props.onChange(value);
      }}
    />
  );
}
Example #4
Source File: brickTableHelper.ts    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
compareFunMap: Record<string, any> = {
  $eq: isEqual,
  $lt: lt,
  $lte: lte,
  $gt: gt,
  $gte: gte,
  $ne: (value: any, fieldValue: any): boolean => !isEqual(value, fieldValue),
  $isEqual: isEqual,
  $notEqual: (value: any, fieldValue: any): boolean =>
    !isEqual(value, fieldValue),
  $in: includes,
  $nin: (value: any, fieldValue: any): boolean => !includes(value, fieldValue),
  $exists: (value: any, fieldValue: any): boolean =>
    value ? !isUndefined(fieldValue) : isUndefined(fieldValue),
}
Example #5
Source File: RangePicker.tsx    From gant-design with MIT License 6 votes vote down vote up
getValue = (value) => {
    const { format } = this.props
    let formateValue: any[] = value
    if (!isUndefined(formateValue)) {
      if (!Array.isArray(formateValue)) {
        formateValue = [formateValue]
      }
      formateValue = formateValue.map(time => getCurTime(time, format))
    }
    return formateValue
  }
Example #6
Source File: get-one-auto-extractor.ts    From js-client with MIT License 6 votes vote down vote up
makeGetOneAutoExtractor = (context: APIContext) => {
	const getAllAutoExtractors = makeGetAllAutoExtractors(context);

	return async (autoExtractorID: UUID): Promise<AutoExtractor> => {
		const autoExtractors = await getAllAutoExtractors();
		const autoExtractor = autoExtractors.find(ae => ae.id === autoExtractorID);
		if (isUndefined(autoExtractor)) throw Error('Not found');
		return autoExtractor;
	};
}
Example #7
Source File: Card.tsx    From gio-design with Apache License 2.0 6 votes vote down vote up
Card = ({
  prefixCls: customizePrefixCls,
  className,
  style,
  title,
  footer,
  children,
  disabled = false,
  clickable = true,
  onClick,
  ...rest
}: CardProps) => {
  const prefixCls = usePrefixCls('card-legacy', customizePrefixCls);

  const renderTitle = () => (isUndefined(title) ? undefined : <div className={`${prefixCls}-title`}>{title}</div>);

  const renderFooter = () => (isUndefined(footer) ? undefined : <div className={`${prefixCls}-footer`}>{footer}</div>);

  return (
    <div
      className={classNames(prefixCls, className, {
        [`${prefixCls}-disabled`]: disabled,
        [`${prefixCls}-clickable`]: clickable,
      })}
      style={style}
      onClick={() => disabled || (clickable && onClick?.())}
      aria-hidden="true"
      // eslint-disable-next-line react/jsx-props-no-spreading
      {...rest}
    >
      {renderTitle()}
      {children}
      {renderFooter()}
    </div>
  );
}
Example #8
Source File: ikea-onoff-switch.ts    From homebridge-zigbee-nt with Apache License 2.0 6 votes vote down vote up
update(state: DeviceState): void {
    const Characteristic = this.platform.Characteristic;
    const ProgrammableSwitchEvent = Characteristic.ProgrammableSwitchEvent;
    if (!isNull(state.battery) && !isUndefined(state.battery)) {
      this.batteryService.updateCharacteristic(Characteristic.BatteryLevel, state.battery || 0);
      this.batteryService.updateCharacteristic(
        Characteristic.StatusLowBattery,
        state.battery && state.battery < 10
      );
    }
    switch (state.action) {
      case 'brightness_move_up':
        this.switchServiceOn
          .getCharacteristic(ProgrammableSwitchEvent)
          .setValue(ProgrammableSwitchEvent.LONG_PRESS);
        break;
      case 'brightness_move_down':
        this.switchServiceOff
          .getCharacteristic(ProgrammableSwitchEvent)
          .setValue(ProgrammableSwitchEvent.LONG_PRESS);
        break;
      case 'on':
        this.switchServiceOn
          .getCharacteristic(ProgrammableSwitchEvent)
          .setValue(ProgrammableSwitchEvent.SINGLE_PRESS);
        break;
      case 'off':
        this.switchServiceOff
          .getCharacteristic(ProgrammableSwitchEvent)
          .setValue(ProgrammableSwitchEvent.SINGLE_PRESS);
        break;
    }
  }
Example #9
Source File: Registry.ts    From mo360-ftk with MIT License 6 votes vote down vote up
/**
   * @param id
   * @returns {Registry}
   */
  public remove(id: string): Registry<T> {
    if (isUndefined(this.keyValueMap[id])) {
      throw new Error(`Registry: Unknown id ${id}.`);
    }

    delete this.keyValueMap[id];
    this.keyCount--;

    return this;
  }
Example #10
Source File: resource.ts    From ue4-remote-control with MIT License 6 votes vote down vote up
async makeRequest<Req, Res>(method: HttpMethodCalls, endpoint: string, body: Req): Promise<Res> {
        const options: rp.Options = {
            uri: `http://localhost:${UE4_SERVER_PORT}${endpoint}`,
            method,
            body: omitBy(body, isUndefined),
            json: true
        };
        d('>> request', options)
        const result = await rp(options) as Res
        d('<< result', result)
        return result
    }
Example #11
Source File: balance.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
toString = (value: string | BN | number): string => {
  if (BN.isBN(value)) {
    return value.toString();
  } else if (isString(value)) {
    return Number(value).toString(10);
  } else if (isNumber(value)) {
    return value.toString(10);
  } else if (isUndefined(value) || isNaN(value) || isNull(value)) {
    return '0';
  } else {
    throw new TypeError(
      // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
      `Can not convert the value ${value} to String type. Value type is ${typeof value}`
    );
  }
}
Example #12
Source File: effects.ts    From redux-with-domain with MIT License 5 votes vote down vote up
export default function createEffectsAndActions(
  namespace: string,
  normalActions,
  selectors,
  events,
  effectsOpt
) {
  const allActions = {}
  const effectActions = {}

  const sagaEffects = decorateSagaEffects(effects)

  const moduleEffects = effectsOpt(allActions, selectors, sagaEffects, events)
  const sagas: Function[] = []

  forEach({ ...moduleEffects }, (value, type) => {
    invariant(
      !normalActions[type],
      `Module ${namespace} action ${type} duplicated`
    )

    const actionType = getActionTypeWithNamespace(namespace, type)
    let generator
    let helper = effects.takeEvery // default helper is takeEvery
    let args: Array<any> = []

    if (isArray(value)) {
      const helperName = value[1] // effect function
      generator = value[0] // saga function
      helper = effects[helperName]

      invariant(
        helper,
        `Module ${namespace} effect ${type} use invalid helper ${helperName}`
      )

      if (!isUndefined(value[2])) {
        args = value.slice(2)
      }
    } else {
      generator = value
    }

    sagas.push(function*() {
      // fix redux-saga's bug
      // https://github.com/redux-saga/redux-saga/issues/1482
      yield (helper as any)(actionType, generator, ...args)
    })

    effectActions[type] = createAction({
      namespace,
      actionType: type,
      actionKind: ACTION_KIND.EFFECT,
      kopFunction: generator
    })
  })

  extend(allActions, normalActions, effectActions) // merge actions

  return {
    effectActions,
    allActions,
    effects: sagas
  }
}
Example #13
Source File: pivot-data-set.ts    From S2 with MIT License 5 votes vote down vote up
public getDimensionValues(field: string, query?: DataType): string[] {
    const { rows = [], columns = [] } = this.fields || {};
    let meta: PivotMeta = new Map();
    let dimensions: string[] = [];
    if (includes(rows, field)) {
      meta = this.rowPivotMeta;
      dimensions = rows;
    } else if (includes(columns, field)) {
      meta = this.colPivotMeta;
      dimensions = columns;
    }

    if (!isEmpty(query)) {
      let sortedMeta = [];
      const dimensionValuePath = [];
      for (const dimension of dimensions) {
        const value = get(query, dimension);
        dimensionValuePath.push(`${value}`);
        const cacheKey = dimensionValuePath.join(`${ID_SEPARATOR}`);
        if (meta.has(value) && !isUndefined(value)) {
          const childField = meta.get(value)?.childField;
          meta = meta.get(value).children;
          if (
            find(this.sortParams, (item) => item.sortFieldId === childField) &&
            this.sortedDimensionValues[childField]
          ) {
            const dimensionValues = this.sortedDimensionValues[
              childField
            ]?.filter((item) => item?.includes(cacheKey));
            sortedMeta = getDimensionsWithoutPathPre([...dimensionValues]);
          } else {
            sortedMeta = [...meta.keys()];
          }
        }
      }
      if (isEmpty(sortedMeta)) {
        return [];
      }
      return filterUndefined(getListBySorted([...meta.keys()], sortedMeta));
    }

    if (this.sortedDimensionValues[field]) {
      return filterUndefined(
        getDimensionsWithoutPathPre([...this.sortedDimensionValues[field]]),
      );
    }

    return filterUndefined([...meta.keys()]);
  }
Example #14
Source File: parse-date.pipe.ts    From aqualink-app with MIT License 5 votes vote down vote up
transform(value: string | undefined, metadata: ArgumentMetadata) {
    if (!isUndefined(value) && !isISO8601(value)) {
      throw new BadRequestException(`Date '${metadata.data}' is not valid`);
    }

    return value;
  }
Example #15
Source File: Alert.tsx    From hub with Apache License 2.0 5 votes vote down vote up
Alert: ElementType = (props: Props) => {
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const errorWrapper = useRef<HTMLDivElement>(null);
  const [isVisible, setIsVisible] = useState<boolean>(false);

  useEffect(() => {
    let timeout: NodeJS.Timeout;
    if (isNull(props.message)) {
      if (!isNull(errorMessage)) {
        setIsVisible(false);
        timeout = setTimeout(() => {
          setErrorMessage(null);
        }, 1000);
      }
    } else {
      if (props.message !== errorMessage) {
        setErrorMessage(props.message);
        setIsVisible(true);
        errorWrapper.current!.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth' });
      }
    }

    return () => {
      if (!isUndefined(timeout)) {
        clearTimeout(timeout);
      }
    };
  }, [props.message]); /* eslint-disable-line react-hooks/exhaustive-deps */

  return (
    <div
      data-testid="alertWrapper"
      className={classnames('overflow-hidden', styles.alertWrapper, { [styles.isAlertActive]: isVisible })}
      ref={errorWrapper}
    >
      {isVisible && (
        <div className={`alert alert-${props.type || DEFAULT_ALERT_TYPE} mt-3 mb-0`} role="alert">
          <div className="d-flex flex-row align-items-start justify-content-between">
            <div>{errorMessage || ''}</div>
            {!isUndefined(props.onClose) && (
              <button
                data-testid="closeAlertBtn"
                type="button"
                className="btn-close ms-3"
                onClick={props.onClose}
                aria-label="Close alert"
              ></button>
            )}
          </div>
        </div>
      )}
    </div>
  );
}