lodash#isEqual TypeScript Examples

The following examples show how to use lodash#isEqual. 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 simulator with Apache License 2.0 7 votes vote down vote up
// eslint-disable-next-line import/prefer-default-export
export function reduxSet<T>(
  obj: Obj<T>,
  path: (string | number)[],
  val: CommonTypes
): Obj<T> | CommonTypes {
  const [prop, ...restPath] = path;
  if (typeof prop === 'undefined') {
    if (!isEqual(obj, val)) return val;
    return obj;
  }
  let before;
  if (prop in obj) {
    before = (obj as { [key: string | number]: T })[prop];
  } else {
    before = {};
  }
  const after = reduxSet(before, restPath, val);
  if (after !== before) {
    let result;
    if (Array.isArray(obj)) {
      result = [
        ...obj.slice(0, prop as number),
        after,
        ...obj.slice((prop as number) + 1, obj.length),
      ] as T[];
    } else {
      result = {
        ...obj,
        [prop]: after,
      } as { [key: string | number]: T };
    }
    return result;
  }
  return obj;
}
Example #2
Source File: utils.ts    From backstage with Apache License 2.0 7 votes vote down vote up
export function isLocationMatch(currentLocation: Location, toLocation: Path) {
  const toDecodedSearch = new URLSearchParams(toLocation.search).toString();
  const toQueryParameters = qs.parse(toDecodedSearch);

  const currentDecodedSearch = new URLSearchParams(
    currentLocation.search,
  ).toString();
  const currentQueryParameters = qs.parse(currentDecodedSearch);

  const matching =
    isEqual(toLocation.pathname, currentLocation.pathname) &&
    isMatch(currentQueryParameters, toQueryParameters);

  return matching;
}
Example #3
Source File: utils.ts    From gant-design with MIT License 7 votes vote down vote up
isEqualObj = (obj, obj2) => {
  let _EqualObj = true;
  if (!isPlainObject(obj) || !isPlainObject(obj2)) {
    if (isEmptyObj(obj) && isEmptyObj(obj2)) return true;
    return isEqual(obj, obj2);
  }
  if (isNull(obj) && isNull(obj2)) return true;
  if (isNull(obj) || isNull(obj2)) {
    return false;
  }
  const newObj = { ...obj, ...obj2 };
  for (let i in newObj) {
    let value1 = get(obj, i),
      value2 = get(obj2, i);
    if (
      typeof value1 === 'object' &&
      typeof value2 === 'object' &&
      !Array.isArray(value1) &&
      !Array.isArray(value2)
    ) {
      _EqualObj = isEqualObj(value1, value2);
    } else {
      if (!(isEmptyObj(value1) && isEmptyObj(value2))) {
        value2 = typeof value2 == 'number' ? value2 : value2 + '';
        value1 = typeof value1 == 'number' ? value1 : value1 + '';
        _EqualObj = isEqual(value2, value1);
      }
    }
    if (!_EqualObj) {
      return _EqualObj;
    }
  }
  return true;
}
Example #4
Source File: helper.ts    From sc2-planner with MIT License 6 votes vote down vote up
createUrlParams = (
    race: string | undefined,
    settings: Array<ISettingsElement> | undefined,
    optimizeSettings: Array<ISettingsElement> | undefined,
    buildOrder: Array<IBuildOrderElement> = []
): string => {
    let newUrl = "?"
    if (!race) {
        race = "terran"
    }
    newUrl += `&race=${race}`

    if (!settings) {
        settings = defaultSettings
    } else if (!isEqual(settings, defaultSettings)) {
        // Encode the settings
        const settingsEncoded = encodeSettings(settings, settingsDefaultValues)
        // const decoded = decodeSettings(settingsEncoded)
        newUrl += `&settings=${settingsEncoded}`
    }

    if (!optimizeSettings) {
        optimizeSettings = defaultOptimizeSettings
    } else if (!isEqual(optimizeSettings, defaultOptimizeSettings)) {
        // Encode the settings
        const settingsEncoded = encodeSettings(optimizeSettings, optimizeSettingsDefaultValues)
        newUrl += `&optimizeSettings=${settingsEncoded}`
    }

    if (buildOrder.length > 0) {
        // Encode the build order
        const buildOrderEncoded = encodeBuildOrder(buildOrder)
        // const buildOrderDecoded = decodebuildOrder(buildOrderEncoded)
        newUrl += `&bo=${buildOrderEncoded}`
    }
    return newUrl
}
Example #5
Source File: data-cell.ts    From S2 with MIT License 6 votes vote down vote up
protected handleHover(cells: CellMeta[]) {
    const currentHoverCell = first(cells) as CellMeta;
    if (currentHoverCell.type !== CellTypes.DATA_CELL) {
      this.hideInteractionShape();
      return;
    }

    if (this.spreadsheet.options.interaction.hoverHighlight) {
      // 如果当前是hover,要绘制出十字交叉的行列样式
      const currentColIndex = this.meta.colIndex;
      const currentRowIndex = this.meta.rowIndex;
      // 当视图内的 cell 行列 index 与 hover 的 cell 一致,绘制hover的十字样式
      if (
        currentColIndex === currentHoverCell?.colIndex ||
        currentRowIndex === currentHoverCell?.rowIndex
      ) {
        this.updateByState(InteractionStateName.HOVER);
      } else {
        // 当视图内的 cell 行列 index 与 hover 的 cell 不一致,隐藏其他样式
        this.hideInteractionShape();
      }
    }

    if (isEqual(currentHoverCell.id, this.getMeta().id)) {
      this.updateByState(InteractionStateName.HOVER_FOCUS);
    }
  }
Example #6
Source File: map.ts    From aqualink-app with MIT License 6 votes vote down vote up
samePosition = (
  polygon1: Polygon | Point,
  polygon2: Polygon | Point
) => {
  const coords1 =
    polygon1.type === "Polygon"
      ? getMiddlePoint(polygon1)
      : polygon1.coordinates;
  const coords2 =
    polygon2.type === "Polygon"
      ? getMiddlePoint(polygon2)
      : polygon2.coordinates;

  return isEqual(coords1, coords2);
}
Example #7
Source File: useQueryParamState.ts    From backstage with Apache License 2.0 6 votes vote down vote up
export function useQueryParamState<T>(
  stateName: string,
  /** @deprecated Don't configure a custom debouceTime */
  debounceTime: number = 250,
): [T | undefined, SetQueryParams<T>] {
  const [searchParams, setSearchParams] = useSearchParams();
  const searchParamsString = searchParams.toString();
  const [queryParamState, setQueryParamState] = useState<T>(
    extractState(searchParamsString, stateName),
  );

  useEffect(() => {
    const newState = extractState(searchParamsString, stateName);

    setQueryParamState(oldState =>
      isEqual(newState, oldState) ? oldState : newState,
    );
  }, [searchParamsString, setQueryParamState, stateName]);

  useDebouncedEffect(
    () => {
      const queryString = joinQueryString(
        searchParamsString,
        stateName,
        queryParamState,
      );

      if (searchParamsString !== queryString) {
        setSearchParams(queryString, { replace: true });
      }
    },
    [setSearchParams, queryParamState, searchParamsString, stateName],
    debounceTime,
  );

  return [queryParamState, setQueryParamState];
}
Example #8
Source File: contracts.ts    From webapp with MIT License 6 votes vote down vote up
contractAddresses$ = networkVars$.pipe(
  switchMapIgnoreThrow(networkVariables => {
    return fetchContractAddresses(networkVariables.contractRegistry).catch(() =>
      vxm.ethBancor.fetchContractAddresses(networkVariables.contractRegistry)
    );
  }),
  tap(x => {
    if (vxm && vxm.ethBancor) {
      vxm.ethBancor.setContractAddresses(x);
    }
  }),
  distinctUntilChanged<RegisteredContracts>(isEqual),
  shareReplay(1)
)
Example #9
Source File: handleDragDrop.ts    From brick-design with MIT License 6 votes vote down vote up
/**
 * 获取放置组件的容器组件信息
 * @param state
 * @param payload
 */
export function getDropTarget(
  state: StateType,
  payload: DropTargetType,
): StateType {
  /**
   * 如果location为undefined说明当前组件不是容器组件
   * 清除dropTarget信息
   */
  const { dropTarget } = state;
  if (isEqual(payload, dropTarget)) return state;
  return {
    ...state,
    dropTarget: payload,
  };
}
Example #10
Source File: SearchIndexer.ts    From advocacy-maps with MIT License 6 votes vote down vote up
async syncDocument(change: Change<DocumentSnapshot>) {
    if (!change.after.exists) {
      const { id } = this.config.convert(change.before.data()!)
      await (await this.getCollection()).documents().delete(id)
    } else if (!change.before.exists) {
      await (await this.getCollection())
        .documents()
        .upsert(this.config.convert(change.after.data()!))
    } else {
      const before = this.config.convert(change.before.data()!)
      const after = this.config.convert(change.after.data()!)
      if (!isEqual(before, after))
        await (await this.getCollection()).documents().upsert(after)
    }
  }
Example #11
Source File: utils.ts    From yforms with MIT License 6 votes vote down vote up
useImmutableValue = (value: any) => {
  const v = useRef(value);
  if (!isEqual(value, v.current)) {
    v.current = value;
  }
  return v.current;
}
Example #12
Source File: index.tsx    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
/**
   * @description 更新按钮
   */
  @method() updateButton(id: string, btn: Partial<CustomButton>) {
    const customButton = this.customButtons.find((btn) => btn.id === id);
    if (customButton && btn) {
      const keys = Object.keys(btn);
      for (const key of keys) {
        if (
          !isEqual(
            customButton[key as keyof CustomButton],
            btn[key as keyof CustomButton]
          )
        ) {
          Object.assign(customButton, btn);
          this.customButtons = [...this.customButtons];
          break;
        }
      }
    }
  }
Example #13
Source File: index.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
static getDerivedStateFromProps(nextProps: IProps, preState: IState): Partial<IState> | null {
    if (!isEqual(nextProps.value, preState.imageUrl)) {
      if (nextProps.isMulti) {
        return { images: nextProps.value as unknown as string[] };
      } else {
        return { imageUrl: nextProps.value };
      }
    }
    return null;
  }
Example #14
Source File: report.service.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
userReportsSearchParamsGenerator(params, search) {
    const searchParams = this.getUserReportParams(search.state);

    let dateParams = null;
    // Filter expenses by date range
    // dateRange.from and dateRange.to needs to a valid date string (if present)
    // Example: dateRange.from = 'Jan 1, 2015', dateRange.to = 'Dec 31, 2017'

    if (search.dateRange && !isEqual(search.dateRange, {})) {
      // TODO: Fix before 2025
      let fromDate = new Date('Jan 1, 1970');
      let toDate = new Date('Dec 31, 2025');

      // Set fromDate to Jan 1, 1970 if none specified
      if (search.dateRange.from) {
        fromDate = new Date(search.dateRange.from);
      }

      // Set toDate to Dec 31, 2025 if none specified
      if (search.dateRange.to) {
        // Setting time to the end of the day
        toDate = new Date(new Date(search.dateRange.to).setHours(23, 59, 59, 999));
      }

      dateParams = {
        created_at: ['gte:' + new Date(fromDate).toISOString(), 'lte:' + new Date(toDate).toISOString()],
      };
    }

    return Object.assign({}, params, searchParams, dateParams);
  }
Example #15
Source File: index.tsx    From gant-design with MIT License 6 votes vote down vote up
componentDidUpdate(prevProps) {
		const { popupClassName, setPopupClassName, disabledBlur, setDisabledBlur } = this.props;
		if (!isEqual(prevProps.popupClassName, popupClassName)) {
			setPopupClassName(popupClassName)
		}
		if (!isEqual(prevProps.disabledBlur, disabledBlur)) {
			setDisabledBlur(disabledBlur)
		}

	}
Example #16
Source File: index.ts    From semantic-release-replace-plugin with Apache License 2.0 6 votes vote down vote up
export async function prepare(
  PluginConfig: PluginConfig,
  context: Context
): Promise<void> {
  for (const replacement of PluginConfig.replacements) {
    let { results } = replacement;

    delete replacement.results;

    const replaceInFileConfig = replacement as ReplaceInFileConfig;

    replaceInFileConfig.to =
      typeof replacement.to === "function"
        ? replacement.to
        : template(replacement.to)({ ...context });
    replaceInFileConfig.from = new RegExp(replacement.from, "gm");

    let actual = await replaceInFile(replaceInFileConfig);

    if (results) {
      results = results.sort();
      actual = actual.sort();

      if (!isEqual(actual.sort(), results.sort())) {
        throw new Error(
          `Expected match not found!\n${diffDefault(actual, results)}`
        );
      }
    }
  }
}
Example #17
Source File: client.ts    From js-client with MIT License 6 votes vote down vote up
private readonly _context$: Observable<APIContext> = combineLatest(
		this.host$,
		this.useEncryption$,
		this.authToken$,
	).pipe(
		map(([host, useEncryption, authToken]) => ({
			host,
			useEncryption,
			authToken,
			fetch: this._initialOptions.fetch ?? fetch,
		})),
		distinctUntilChanged((a, b) => isEqual(a, b)),
		shareReplay(1),
	);
Example #18
Source File: generateManifest.ts    From nft-maker-js with Do What The F*ck You Want To Public License 6 votes vote down vote up
function duplicateFound(imageData: Image[], newImage: Image): boolean {
  return imageData.reduce((foundDuplicate: boolean, image: Image) => {
    if (foundDuplicate) {
      return true
    }

    foundDuplicate = isEqual(image, newImage)

    return foundDuplicate
  }, false)
}
Example #19
Source File: index.ts    From integration-services with Apache License 2.0 6 votes vote down vote up
static validateLogs(logs: ChannelData[], tangleLogs: ChannelData[]): ValidateResponse {
		return logs.map((channelData) => {
			const tangleLog = tangleLogs.find((l) => l.link === channelData.link);

			if (!tangleLog) {
				return {
					link: channelData.link,
					isValid: false,
					error: 'log not found on the tangle'
				};
			}

			const omitedLog = _(channelData.log).omitBy(_.isUndefined).omitBy(_.isNull).value();
			const omitedTangleLog = _(tangleLog.log).omitBy(_.isUndefined).omitBy(_.isNull).value();

			if (!isEqual(omitedLog, omitedTangleLog)) {
				return {
					link: channelData.link,
					isValid: false,
					error: 'not the same data',
					tangleLog: tangleLog.log
				};
			}

			return {
				link: channelData.link,
				isValid: true
			};
		});
	}
Example #20
Source File: utils.ts    From jetlinks-ui-antd with MIT License 6 votes vote down vote up
propsAreEqual = (prevProps: any, nextProps: any) => isEqual(prevProps.value, nextProps.value)
Example #21
Source File: useDeepMemo.ts    From jitsu with MIT License 6 votes vote down vote up
useDeepMemo = <T extends {}>(value: T): T => {
  const ref = useRef<T | null>(value) // will use the first passed value on the initial render

  const previousValue = ref.current

  if (value === previousValue) return value

  if (isEqual(value, previousValue)) {
    ref.current = value // helps to avoid deep comparisons on next renders
    return previousValue
  } else {
    ref.current = value
    return value
  }
}
Example #22
Source File: index.component.ts    From models-web-app with Apache License 2.0 6 votes vote down vote up
ngOnInit() {
    this.poller = new ExponentialBackoff({
      interval: 1000,
      retries: 3,
      maxInterval: 4000,
    });

    this.subs.add(
      this.poller.start().subscribe(() => {
        if (!this.currNamespace) {
          return;
        }

        this.backend
          .getInferenceServices(this.currNamespace)
          .subscribe((svcs: InferenceServiceK8s[]) => {
            if (isEqual(this.rawData, svcs)) {
              return;
            }

            this.inferenceServices = this.processIncomingData(svcs);
            this.rawData = svcs;
            this.poller.reset();
          });
      }),
    );

    // Reset the poller whenever the selected namespace changes
    this.subs.add(
      this.ns.getSelectedNamespace().subscribe(ns => {
        this.currNamespace = ns;
        this.poller.reset();
      }),
    );
  }
Example #23
Source File: apolloClient.ts    From next-page-tester with MIT License 6 votes vote down vote up
export function initializeApollo<T>(initialState?: T) {
  const _apolloClient = apolloClient ?? createApolloClient();

  // If your page has Next.js data fetching methods that use Apollo Client, the initial state
  // gets hydrated here
  if (initialState) {
    // Get existing cache, loaded during client side data fetching
    const existingCache = _apolloClient.extract();

    // Merge the existing cache into data passed from getStaticProps/getServerSideProps
    const data = all([initialState, existingCache], {
      // combine arrays using object equality (like in sets)
      arrayMerge: (destinationArray, sourceArray) => [
        ...sourceArray,
        ...destinationArray.filter((d) =>
          sourceArray.every((s) => !isEqual(d, s))
        ),
      ],
    });

    // Restore the cache with the merged data
    _apolloClient.cache.restore(data);
  }
  // For SSG and SSR always create a new Apollo Client
  if (typeof window === 'undefined') return _apolloClient;
  // Create the Apollo Client once in the client
  if (!apolloClient) apolloClient = _apolloClient;

  return _apolloClient;
}
Example #24
Source File: index.ts    From querybook with Apache License 2.0 6 votes vote down vote up
export function getChangedObject(
    orig: Record<any, unknown>,
    changed: Record<any, unknown>
) {
    const ret = {};

    for (const [key, value] of Object.entries(changed)) {
        if (!isEqual(orig[key], value)) {
            ret[key] = value;
        }
    }

    return ret;
}
Example #25
Source File: selection.ts    From am-editor with MIT License 6 votes vote down vote up
setAttribute(attr: Attribute, member: Member, refreshBG = false) {
		const item = this.data.get(attr.uuid);
		if (attr.force || !isEqual(item || {}, attr)) {
			this.data.set(
				attr.uuid,
				Object.assign({}, attr, { active: !item }),
			);
			if (attr.uuid === this.current?.uuid) {
				if (refreshBG === true) this.rangeColoring.updatePosition();
				this.emit('change', attr);
			} else {
				this.rangeColoring.render(attr, member);
			}
		}
	}
Example #26
Source File: playlistProcessor.ts    From smil-player with MIT License 6 votes vote down vote up
private handleElementSynchronization = async (value: SMILMedia): Promise<boolean> => {
		if (value.regionInfo.sync && this.synchronization.shouldSync) {
			let currentSyncIndex = this.synchronization.syncValue;
			if (
				isNil(this.synchronization.syncValue) ||
				isEqual(value.syncIndex, this.synchronization.syncValue) ||
				this.synchronization.movingForward
			) {
				if (
					!isNil(this.synchronization.syncValue) &&
					isEqual(value.syncIndex, this.synchronization.syncValue) &&
					this.synchronization.syncingInAction
				) {
					//move one forward
					this.synchronization.syncingInAction = false;
					this.synchronization.movingForward = true;
					this.synchronization.syncValue = undefined;
					return false;
				}
				currentSyncIndex = await this.sos.sync.wait(
					value.syncIndex,
					`${this.synchronization.syncGroupName}-${value.regionInfo.regionName}`,
				);
				if (value.syncIndex !== currentSyncIndex) {
					this.synchronization.syncValue = currentSyncIndex;
				}
				this.synchronization.syncingInAction = false;
				this.synchronization.movingForward = false;
			}

			if (!isEqual(value.syncIndex, currentSyncIndex) && !isNil(currentSyncIndex)) {
				this.synchronization.syncingInAction = true;
				return false;
			}
		}

		return true;
	};
Example #27
Source File: connection.background.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
requestConnection = async (message: IRuntimeConnectMessage): Promise<IRuntimeConnectResponse | IRuntimeErrorResponse> => {
  const payload = message.payload;
  const savedPermissions = await getSitePermissions(payload.origin + '_' + payload.host);

  if (!!savedPermissions && isEqual(savedPermissions, payload.permissions)) {
    return {
      payload: savedPermissions,
      error: false,
    };
  }

  return new Promise((resolve) => {
    chrome.windows.create({
      type: 'popup',
      url: 'index.html#/sign-from-background/',
      left: 0,
      top: 0,
      height: 640,
      width: 380,
    }, async (popup) => {
      if (!popup) {
        return resolve({
          error: true,
          errorMessage: `We couldn't open the extension`
        });
      }

      // We wait a little before the tab is open
      await new Promise(r => setTimeout(r, 500));
      const extensionTab = popup.tabs && popup.tabs[0];

      if (!extensionTab) {
        return resolve({
          error: true,
          errorMessage: `We couldn't open the extension`
        });
      }

      const port = chrome.runtime.connect(chrome.runtime.id, { name: XBULL_CONNECT_BACKGROUND });
      port.onMessage.addListener((response: 'ready' | IRuntimeConnectResponse | IRuntimeErrorResponse) => {
        if (response === 'ready') {
          port.postMessage(message);
        } else {
          if (!response.error) {
            // Check if the response is formatted as expected
            if (
              typeof response.payload.canRequestPublicKey === 'undefined'
              || typeof response.payload.canRequestSign === 'undefined'
            ) {
              resolve({
                error: true,
                errorMessage: 'Response from extension was not the expected one'
              });
            } else {
              resolve({
                error: false,
                payload: {
                  canRequestPublicKey: response.payload.canRequestPublicKey,
                  canRequestSign: response.payload.canRequestSign
                }
              });
            }
          } else {
            resolve({
              error: true,
              errorMessage: response.errorMessage,
            });
          }
        }
      });

    });
  });

}
Example #28
Source File: memoize.ts    From taskcafe with MIT License 5 votes vote down vote up
useDeepCompareMemoize = (value: any) => {
  const valueRef = useRef();

  if (!isEqual(value, valueRef.current)) {
    valueRef.current = value;
  }
  return valueRef.current;
}
Example #29
Source File: filterPayload.service.ts    From whispr with MIT License 5 votes vote down vote up
matches = (filterValue: unknown, elementValue: unknown): boolean => {
  if (Array.isArray(filterValue)) {
    return filterValue.some((value) => matches(value, elementValue));
  }

  return isEqual(filterValue, elementValue);
}