lodash-es#difference TypeScript Examples

The following examples show how to use lodash-es#difference. 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: sample-size.spec.ts    From s-libs with MIT License 5 votes vote down vote up
describe('sampleSize()', () => {
  //
  // stolen from https://github.com/lodash/lodash
  //

  const array = [1, 2, 3];

  it('should return an array of random elements', () => {
    const actual = sampleSize(array, 2);
    expect(actual.length).toBe(2);
    expect(difference(actual, array)).toEqual([]);
  });

  it('should contain elements of the collection', () => {
    expect(sampleSize(array, array.length).sort()).toEqual(array);
  });

  it('should treat falsey `size` values, except `undefined`, as `0`', () => {
    expect(sampleSize(['a'], 0)).toEqual([]);
    expect(sampleSize(['a'])).toEqual(['a']);
    expect(sampleSize(['a'], undefined)).toEqual(['a']);
  });

  it('should return an empty array when `n` < `1` or `NaN`', () => {
    expect(sampleSize(array, 0)).toEqual([]);
    expect(sampleSize(array, -1)).toEqual([]);
    expect(sampleSize(array, -Infinity)).toEqual([]);
  });

  it('should return all elements when `n` >= `length`', () => {
    expect(sampleSize(array, 3).sort()).toEqual(array);
    expect(sampleSize(array, 4).sort()).toEqual(array);
    expect(sampleSize(array, 2 ** 32).sort()).toEqual(array);
    expect(sampleSize(array, Infinity).sort()).toEqual(array);
  });

  it('should return an empty array for empty collections', () => {
    expect(sampleSize([], 1)).toEqual([]);
    expect(sampleSize({}, 1)).toEqual([]);
    expect(sampleSize(null, 1)).toEqual([]);
    expect(sampleSize(undefined, 1)).toEqual([]);
  });

  it('should sample an object', () => {
    const object = { a: 1, b: 2, c: 3 };
    const actual = sampleSize(object, 2);
    expect(actual.length).toBe(2);
    expect(difference(actual, array)).toEqual([]);
  });
});
Example #2
Source File: code-generator.ts    From openapi-generator-typescript with MIT License 4 votes vote down vote up
generatePathsDefinition = (
  pathsObject: PathsObject,
  operations?: ReadonlyArray<string>
) =>
  pathsObjectEntries(pathsObject, operations)
    .map(x => {
      const { method, path: url, operationObject, operationIdIdentifier } = x;
      // TODO: 忽略了所有的 ReferenceObject
      const parameters = (operationObject.parameters ?? []).filter(
        isNotReferenceObject
      );
      const pathParameters = parameters.filter(x => x.in === 'path');
      const queryParameters = parameters.filter(x => x.in === 'query');
      const cookieParameters = parameters.filter(x => x.in === 'cookie');
      const headerParameters = parameters.filter(x => x.in === 'header');
      const parsedUrl = parseUrlTemplate(url);

      const conflictParameters = difference(
        parameters,
        pathParameters
      ).filter(x => parsedUrl.pathParams.includes(x.name));

      if (conflictParameters.length > 0) {
        console.warn(
          `operation ${operationObject.operationId} has conflictParameters, url: ${url}, conflictParameters:`,
          conflictParameters
        );
      }

      const freePathVariables = difference(
        parsedUrl.pathParams,
        pathParameters.map(x => x.name)
      );

      if (freePathVariables.length > 0) {
        console.warn(
          `operation ${operationObject.operationId} has freePathVariables, url: ${url}, freePathVariables:`,
          freePathVariables
        );
      }

      const interfacePathParameter =
        pathParameters.length === 0 && parsedUrl.pathParams.length === 0
          ? ''
          : `export interface PathParameter {
${
  pathParameters.length === 0
    ? ''
    : getObjectBody({
        type: 'object',
        required: pathParameters.filter(x => x.required).map(x => x.name),
        properties: fromEntries([
          ...pathParameters.map(x => [x.name, { ...x.schema! }] as const),
        ]),
      }) + '\n'
}${formatEntries(
              freePathVariables.map(key => ({
                key,
                value: 'string | number, // FIXME: free variable here',
                modifiers: ['readonly'],
              })),
              {
                endSeparator: '',
              }
            )}
}
`;
      const formatContent = (
        interfaceName: string,
        parameterObjectList: ReadonlyArray<ParameterObject>
      ) =>
        parameterObjectList.length === 0
          ? ''
          : `export interface ${interfaceName} ${getObject({
              type: 'object',
              required: parameterObjectList
                .filter(x => x.required)
                .map(x => x.name),
              properties: fromEntries([
                ...parameterObjectList.map(x => [x.name, x.schema!] as const),
              ]),
            })}`;

      const responsesEntries = Object.entries(operationObject.responses).map(
        ([statusCode, object]) =>
          ({
            statusCode,
            responseObject: object as ResponseObject, // FIXME: 这里没有考虑 referenceObject 的情况
          } as const)
      );
      const responseInterfaceBody = getObject({
        type: 'object',
        required: responsesEntries.map(({ statusCode }) => statusCode),
        properties: fromEntries(
          responsesEntries.map(
            ({
              responseObject: { content },
              statusCode,
            }): readonly [string, SchemaObject] =>
              content === undefined
                ? [
                    statusCode,
                    {
                      type: 'object',
                    },
                  ]
                : [
                    statusCode,
                    {
                      type: 'object',
                      required: Object.keys(content),
                      properties: mapValues(content, ({ schema }) => schema!),
                    },
                  ]
          )
        ),
      });
      const getUrlFunction =
        parsedUrl.pathParams.length > 0
          ? `({ ${parsedUrl.pathParams.join(', ')} }: PathParameter) => \`${
              parsedUrl.urlJsTemplate
            }\``
          : `({} : {}) => '${parsedUrl.urlJsTemplate}'`;
      const interfaceQueryParameter = formatContent(
        'QueryParameter',
        queryParameters
      );
      const interfaceHeaderParameter = formatContent(
        'HeaderParameter',
        headerParameters
      );
      const interfaceCookieParameter = formatContent(
        'CookieParameter',
        cookieParameters
      );
      const interfaceAllParameters =
        interfacePathParameter +
        interfaceQueryParameter +
        interfaceHeaderParameter +
        interfaceCookieParameter;

      const requestBody = (operationObject.requestBody as RequestBodyObject)
        ?.content
        ? (operationObject.requestBody as RequestBodyObject)
        : undefined;
      const requestBodyContent = requestBody?.content ?? {};
      const requestBodyInterfaceBody = getObject({
        type: 'object',
        required: Object.keys(requestBodyContent),
        properties: mapValues(requestBodyContent, ({ schema }) => schema!),
      });

      const content = `
export const method = '${method}';
export const url = '${url}';
export const getUrl = ${getUrlFunction};
export const parameterNames = ${JSON.stringify({
        path: pathParameters.map(x => x.name),
        query: queryParameters.map(x => x.name),
        header: headerParameters.map(x => x.name),
        cookie: cookieParameters.map(x => x.name),
      })} as const
${interfaceAllParameters}
export type Parameter = ${
        interfaceAllParameters === ''
          ? '{}'
          : '' +
            ([
              ['PathParameter', interfacePathParameter],
              ['QueryParameter', interfaceQueryParameter],
              ['HeaderParameter', interfaceHeaderParameter],
              ['CookieParameter', interfaceCookieParameter],
            ] as const)
              .filter(x => x[1] !== '')
              .map(x => x[0])
              .join(' & ')
      };${
        conflictParameters.length === 0 ? '' : ' // FIXME: Conflict Parameters'
      }
export interface Response ${responseInterfaceBody}
export const requestBody = ${
        JSON.stringify(requestBody) +
        (requestBody === undefined ? '' : ' as const')
      };
export interface RequestBody ${requestBodyInterfaceBody}
`;
      return `
${getOperationObjectJSDoc(x)}
export namespace ${operationIdIdentifier} {
${addIndentLevel(content)}
}`;
    })
    .join('')