lodash#isString TypeScript Examples

The following examples show how to use lodash#isString. 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.ts    From redux-with-domain with MIT License 7 votes vote down vote up
export function hasDuplicatedKeys(obj, ...others) {
  return some(obj, (val, key) =>
    some(others, compareItem => {
      if (isString(compareItem)) {
        return compareItem === key
      }
      return key in compareItem
    })
  )
}
Example #2
Source File: server-utils.ts    From prism-frontend with MIT License 7 votes vote down vote up
/**
 * Format the raw data to { [layerId]: availableDates }
 * @param rawLayers Layers data return by the server 'GetCapabilities' request
 * @param layerIdPath path to layer's id
 * @param datesPath path to layer's available dates
 * @returns an object shape like { [layerId]: availableDates }
 */
function formatCapabilitiesInfo(
  rawLayers: any,
  layerIdPath: string,
  datesPath: string,
): AvailableDates {
  return rawLayers.reduce((acc: any, layer: any) => {
    const layerId = get(layer, layerIdPath);
    const rawDates = get(layer, datesPath, []);

    const dates: (string | { _text: string })[] = isString(rawDates)
      ? rawDates.split(',')
      : rawDates;

    const availableDates = dates
      .filter((date) => !isEmpty(date))
      .map((date) =>
        // adding 12 hours to avoid  errors due to daylight saving
        moment.utc(get(date, '_text', date)).set({ hour: 12 }).valueOf(),
      );

    const { [layerId]: oldLayerDates } = acc;
    return {
      ...acc,
      [layerId]: union(availableDates, oldLayerDates),
    };
  }, {});
}
Example #3
Source File: utilities.ts    From react-native-jigsaw with MIT License 7 votes vote down vote up
export function getValueForRadioButton(value: string | number) {
  if (isString(value)) {
    return value;
  } else if (isNumber(value)) {
    return String(value);
  } else {
    throw new Error(`Invalid value: ${value}`);
  }
}
Example #4
Source File: search-map-getter.ts    From one-platform with MIT License 6 votes vote down vote up
/**
 * Get a nested value from an object/array using a string selector
 * @param data the input data object
 * @param prop the property selector
 * @param options additional options for response
 * @returns the object matching the selector, or null if nothing found
 */
export default function getValueBySelector(data: any, prop: string, opts: IOptions = { stringify: false }): any | null {
  const { stringify, fallback } = opts;
  const propsArray = prop
    .replace(/\[(\w+)\]/g, '.$1')
    .replace(/^\./, '')
    .split('.');

  let cursor = cloneDeep(data);
  try {
    const res = propsArray.reduce((value, propName) => {
      if (propName in cursor) {
        cursor = cursor[propName];
        return cursor;
      }
      logger.info('throwing...');
      throw new Error(`${propName} is not a property of ${typeof cursor}`);
    }, null);

    if (!isEmpty(res) && !isString(res) && stringify) {
      return JSON.stringify(res);
    }
    return res;
  } catch (err) {
    logger.debug(err);
    if (fallback) {
      return fallback;
    }
    throw err;
  }
}
Example #5
Source File: showError.tsx    From generator-earth with MIT License 6 votes vote down vote up
showError = (e?: Error | string): void => {
    let msg;

    if (isError(e)) {
        msg = e.message
    } else if (isString(e)) {
        msg = e;
    }

    msg = msg || '系统异常'

    Modal.error({
        title: '错误提示',
        content: <pre>{msg}</pre>,
    })
}
Example #6
Source File: getMessage.ts    From strapi-plugin-comments with MIT License 6 votes vote down vote up
getMessage = (
  input: ToBeFixed,
  defaultMessage = "",
  inPluginScope = true
) => {
  const { formatMessage } = useIntl();
  let formattedId = "";
  if (isString(input)) {
    formattedId = input;
  } else {
    formattedId = input?.id;
  }
  return formatMessage(
    {
      id: `${inPluginScope ? pluginId : "app.components"}.${formattedId}`,
      defaultMessage,
    },
    input?.props || undefined
  );
}
Example #7
Source File: spread-sheet.ts    From S2 with MIT License 6 votes vote down vote up
private getMountContainer(dom: S2MountContainer) {
    const mountContainer = isString(dom) ? document.querySelector(dom) : dom;

    if (!mountContainer) {
      throw new Error('Target mount container is not a DOM element');
    }

    return mountContainer;
  }
Example #8
Source File: helpers.ts    From aqualink-app with MIT License 6 votes vote down vote up
findRequestTimePeriod = (
  prevStart?: string,
  prevEnd?: string,
  newStart?: string,
  newEnd?: string
): "past" | "future" | "between" | undefined => {
  if (
    prevEnd === newEnd &&
    isString(prevStart) &&
    isString(newStart) &&
    isBefore(newStart, prevStart, true)
  ) {
    return "past";
  }

  if (
    prevStart === newStart &&
    isString(prevEnd) &&
    isString(newEnd) &&
    isBefore(prevEnd, newEnd, true)
  ) {
    return "future";
  }

  if (
    isString(newStart) &&
    isString(newEnd) &&
    isString(prevStart) &&
    isString(prevEnd) &&
    isBefore(prevStart, newStart) &&
    isBefore(newEnd, prevEnd)
  ) {
    return "between";
  }

  return undefined;
}
Example #9
Source File: JsonToMjml.ts    From easy-email with MIT License 6 votes vote down vote up
export function generaMjmlMetaData(data: IPage) {
  const values = data.data.value;
  const attributes = [
    'content-background-color',
    'text-color',
    'font-family',
    'font-size',
    'line-height',
    'font-weight',
    'user-style',
    'responsive',
  ];

  return `
    <mj-html-attributes>
      ${attributes
      .filter((key) => values[key as keyof typeof values] !== undefined)
      .map((key) => {
        const attKey = key as keyof typeof values;
        const isMultipleAttributes = isObject(values[attKey]);
        const value = isMultipleAttributes
          ? Object.keys(values[attKey]!)
            .map(
              (childKey) => {
                const childValue = (values[attKey] as any)[childKey];

                return `${childKey}="${isString(childValue) ? childValue.replace(/"/gm, '') : childValue}"`;
              }

            )
            .join(' ')
          : `${key}="${values[attKey]}"`;
        return `<mj-html-attribute class="easy-email" multiple-attributes="${isMultipleAttributes}" attribute-name="${key}" ${value}></mj-html-attribute>`;
      })
      .join('\n')}

    </mj-html-attributes>
  `;
}
Example #10
Source File: Pagination.tsx    From hub with Apache License 2.0 6 votes vote down vote up
PaginationBtn = (btnProps: ButtonProps) => (
  <button
    className={classnames('page-link', {
      'text-primary': !btnProps.disabled && btnProps.active !== btnProps.pageNumber,
    })}
    onClick={() => {
      if (btnProps.active !== btnProps.pageNumber) {
        btnProps.onChange(btnProps.pageNumber);
      }
    }}
    aria-label={`Open ${isString(btnProps.content) ? btnProps.content : `page ${btnProps.pageNumber}`}`}
    disabled={btnProps.disabled}
    tabIndex={btnProps.disabled ? -1 : 0}
  >
    {btnProps.content || btnProps.pageNumber}
  </button>
)
Example #11
Source File: bills.ts    From advocacy-maps with MIT License 6 votes vote down vote up
{ fetchBatch: fetchBillBatch, startBatches: startBillBatches } =
  createScraper({
    resourceName: "bills",
    batchesPerRun: 20,
    resourcesPerBatch: 50,
    startBatchSchedule: "every 3 hours",
    fetchBatchTimeout: 240,
    startBatchTimeout: 60,
    fetchResource: async (court: number, id: string, current) => {
      const content = await api.getDocument({ id, court })
      const history = await api
        .getBillHistory(court, id)
        .catch(logFetchError("bill history", id))
        .then(history => history ?? [])
      // Most of our time is spent fetching similar bills
      const similar = await api
        .getSimilarBills(court, id)
        .catch(logFetchError("similar bills", id))
        .then(bills => bills?.map(b => b.BillNumber).filter(isString) ?? [])
      const resource: Partial<Bill> = {
        content,
        history,
        similar,
        cosponsorCount: content.Cosponsors.length,
        testimonyCount: current?.testimonyCount ?? 0,
        latestTestimonyAt: current?.latestTestimonyAt ?? MISSING_TIMESTAMP,
        nextHearingAt: current?.nextHearingAt ?? MISSING_TIMESTAMP
      }

      return resource
    },
    listIds: (court: number) =>
      api.listDocuments({ court }).then(docs => docs.map(d => d.BillNumber))
  })
Example #12
Source File: CheckboxRow.tsx    From react-native-jigsaw with MIT License 6 votes vote down vote up
renderLabel = (
  value: string | React.ReactNode,
  labelStyle: StyleProp<TextStyle>,
  textStyle: StyleProp<TextStyle>
) => {
  if (isString(value)) {
    return <Text style={[textStyle, labelStyle]}>{value}</Text>;
  } else {
    return <>{value}</>;
  }
}
Example #13
Source File: BrickCodeDisplay.tsx    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
render() {
    return (
      <div className={styles.customCodeDisplay}>
        <pre
          className={classNames({
            "line-numbers": this.props.showLineNumber
          })}
          style={{ whiteSpace: "pre-wrap", margin: 0 }}
        >
          <code
            className={`language-${this.props.language}`}
            style={{ whiteSpace: "pre-wrap" }}
          >
            { isString(this.props.value) ? this.props.value : JSON.stringify(this.props.value, null, '  ')}
          </code>
        </pre>
      </div>
    );
  }
Example #14
Source File: events.ts    From ts-di-starter with MIT License 6 votes vote down vote up
/**
   * Add local listener for event
   *
   * @param {EVENT_NAMESPACES} namespace
   * @param {ACTIONS | EventListenerInterface} actionOrListener
   * @param {EventListenerInterface} listener
   * @returns {void}
   */
  onLocal(namespace: EVENT_NAMESPACES, actionOrListener: ACTIONS | EventListenerInterface, listener?: EventListenerInterface): void {
    if (listener && isFunction(listener) && isString(actionOrListener)) {
      this.localEventEmitter.on([namespace, actionOrListener], listener);
    } else if (isFunction(actionOrListener)) {
      this.localEventEmitter.on([namespace, '*'], actionOrListener);
    } else {
      log.error(`Unexpected parameters to "onLocal" in namespace: ${namespace}`);
    }
  }
Example #15
Source File: index.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
initClipBoard() {
    const { children, selector, opts = {}, onSuccess, onError, tipName = '' } = this.props;
    // click event bind on body, make sure one selector only trigger once
    this.selector = isString(children) ? innerSelector : selector || innerSelector;
    if (this.selector && !selectorMap[this.selector]) {
      selectorMap[this.selector] = true;
      this.clipboard = new Clipboard(this.selector, opts);
      this.clipboard.on('success', (e: any) => {
        if (typeof onSuccess === 'function') {
          onSuccess(e);
        }
        message.success(
          firstCharToUpper(
            `${e.trigger.getAttribute('data-clipboard-tip') || tipName} ${i18n.t('copied')} ${i18n.t('successfully')}`,
          ),
          1,
        );
        e.clearSelection();
      });
      this.clipboard.on('error', (e: any) => {
        if (typeof onError === 'function') {
          onError(e);
        }
        message.error(
          `${i18n.t('Copy')} ${e.trigger.getAttribute('data-clipboard-tip') || tipName} ${i18n.t('failed')}`,
          1,
        );
      });
    }
  }
Example #16
Source File: get-all-auto-extractor-modules.spec.ts    From js-client with MIT License 6 votes vote down vote up
describe('getAllAutoExtractorModules()', () => {
	const getAllAutoExtractorModules = makeGetAllAutoExtractorModules(TEST_BASE_API_CONTEXT);

	it(
		'Should return all auto extractors modules',
		integrationTest(async () => {
			const autoExtractorModules = await getAllAutoExtractorModules();
			expect(autoExtractorModules.every(isString)).toBeTrue();
			expect(autoExtractorModules.length).toBeGreaterThan(0);
		}),
	);
});
Example #17
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 #18
Source File: helpers.ts    From leda with MIT License 6 votes vote down vote up
getSuggestionFromValue = ({
  data,
  value,
  textField,
}: {
  data: Suggestion[],
  value: string | DataObject,
  textField?: string,
}): Suggestion => {
  const isEveryIsObject = every(data, isObject);

  const isValidTextField = isString(textField) && textField.length > 0;

  if (isEveryIsObject && !isValidTextField) {
    // todo: handle textField error
  }

  const suggestion: Suggestion | undefined = isEveryIsObject
    ? (data as DataObject[]).find((el: DataObject): boolean => (el[textField as string] === value))
    : (data as string[]).find((el: string): boolean => (el === value));

  return suggestion || null;
}