ramda#uniq TypeScript Examples

The following examples show how to use ramda#uniq. 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 reskript with MIT License 7 votes vote down vote up
resolveLintFiles = async (
    type: LintType,
    files: string[],
    {staged, changed, gitStatus}: ResolveOptions
): Promise<string[]> => {
    const extensions = TYPE_TO_EXTENSIONS[type];
    const extensionNames = TYPE_TO_EXTENSION_NAMES[type];
    const isLintable = (file: string) => extensionNames.has(path.extname(file));

    if (staged || changed) {
        // 当前目录可能不在git根目录下,所有的路径要相应做一次修复
        const gitRoot = await findGitRoot() || process.cwd();
        const cwdRelative = path.relative(gitRoot, process.cwd());
        const files = staged ? gitStatus.staged : gitStatus.modified;
        return files.filter(isLintable).map(v => path.relative(cwdRelative, v)).filter(v => !v.startsWith('..'));
    }

    const matchFiles = async (file: string): Promise<string[]> => {
        // 当前目录比较特殊,只要检查文件,不用去检查子目录
        if (file === '.') {
            return globby(`*.{${extensions.join(',')}}`);
        }

        const stat = await fs.stat(file);

        if (stat.isFile()) {
            return [file];
        }

        const found = await globby(`**/*.{${extensions.join(',')}}`, {cwd: file});
        return found.map(v => path.join(file, v));
    };
    const fileOrFolders = files.length ? files : ['.', 'src'];
    const matchedFiles = await Promise.all(fileOrFolders.map(matchFiles));
    return uniq(matchedFiles.flatMap(v => v).filter(isLintable));
}
Example #2
Source File: TExp.ts    From interpreters with MIT License 6 votes vote down vote up
equivalentTEs = (te1: TExp, te2: TExp): boolean => {
    // console.log(`EqTEs ${JSON.stringify(te1)} - ${JSON.stringify(te2)}`);
    const tvarsPairs = matchTVarsInTE(te1, te2, (x) => x, () => false);
    // console.log(`EqTEs pairs = ${map(JSON.stringify, tvarsPairs)}`)
    if (isBoolean(tvarsPairs))
        return false;
    else {
        return (uniq(map((p) => p.left.var, tvarsPairs)).length === uniq(map((p) => p.right.var, tvarsPairs)).length);
    }
}
Example #3
Source File: index.ts    From reskript with MIT License 6 votes vote down vote up
gitStatus = async (cwd: string): Promise<GitStatusResult> => {
    try {
        const items = await status({cwd});
        return {
            modified: uniq(filterChanged(items).map(extractName)),
            staged: uniq(filterStaged(items).map(extractName)),
            stagedOnly: uniq(filterStagedOnly(items).map(extractName)),
        };
    }
    catch {
        return {
            modified: [],
            staged: [],
            stagedOnly: [],
        };
    }
}
Example #4
Source File: duplicatePackages.ts    From reskript with MIT License 5 votes vote down vote up
extractUniqueModules = (compilations: StatsCompilation[]): string[] => {
    const modules = compilations.flatMap(c => c.modules);
    const names = modules.map(m => m?.nameForCondition);
    return uniq(reject(isNil, names));
}
Example #5
Source File: htmlImportable.ts    From reskript with MIT License 5 votes vote down vote up
extractScriptEntries = (compilations: StatsCompilation[]): string[] => {
    const entries = compilations.flatMap(c => Object.values(c.entrypoints ?? {}));
    // 这里的`assets`是有顺序的(大概),被别人依赖的在前面(大概),真正的入口是最后一个(大概)
    return uniq(reject(isNil, entries.map(v => last(v.assets ?? [])?.name)));
}
Example #6
Source File: generateCompositeTypeFile.ts    From kanel with MIT License 4 votes vote down vote up
generateCompositeTypeFile = (
  compositeType: CompositeType,
  {
    typeMap,
    userTypes,
    tableOrViewTypes,
    schemaName,
    nominators,
    externalTypesFolder,
    schemaFolderMap,
  }: {
    typeMap: TypeMap;
    userTypes: string[];
    tableOrViewTypes: string[];
    schemaName: string;
    nominators: Nominators;
    externalTypesFolder?: string;
    schemaFolderMap: {
      [schemaName: string]: string;
    };
  }
): string[] => {
  const fileNominator = nominators.fileNominator;

  const lines = [];
  const { comment } = compositeType;

  const importGenerator = new ImportGenerator(schemaFolderMap[schemaName]);
  const appliedUserTypes = uniq(
    map(
      (p: Attribute) => p.type,
      filter((p) => userTypes.indexOf(p.type) !== -1, compositeType.attributes)
    )
  );
  appliedUserTypes.forEach((t) => {
    const givenName = nominators.typeNominator(t);
    importGenerator.addImport(
      givenName,
      true,
      path.join(schemaFolderMap[schemaName], fileNominator(givenName, t)),
      false
    );
  });

  // Handle tables and views used as attribute types.
  const appliedTableOrViewTypes = uniq(
    map(
      (p: Attribute) => p.type,
      filter(
        (p) => tableOrViewTypes.indexOf(p.type) !== -1,
        compositeType.attributes
      )
    )
  );
  appliedTableOrViewTypes.forEach((t) => {
    const givenName = nominators.modelNominator(t);
    importGenerator.addImport(
      givenName,
      true,
      path.join(schemaFolderMap[schemaName], fileNominator(givenName, t)),
      false
    );
  });

  const overriddenTypes = map(
    (p: Attribute) => p.tags.type,
    filter((p) => Boolean(p.tags.type), compositeType.attributes)
  );
  forEach((importedType) => {
    const givenName = importedType as GivenName; // We expect people to have used proper casing in their comments
    importGenerator.addImport(
      givenName,
      true,
      path.join(
        externalTypesFolder,
        fileNominator(givenName, importedType as string)
      ),
      false
    );
  }, overriddenTypes);

  const importLines = importGenerator.generateLines();
  lines.push(...importLines);

  if (importLines.length) {
    lines.push('');
  }

  const properties = compositeType.attributes.map((a) => {
    let rawType = a.tags.type || typeMap[a.type];
    if (!rawType) {
      logger.warn(`Unrecognized type: '${a.type}'`);
      if (tableOrViewTypes.indexOf(a.type) !== -1) {
        rawType = nominators.modelNominator(a.type);
      } else {
        rawType = nominators.typeNominator(a.type);
      }
    }
    const typeName = (a.nullable ? `${rawType} | null` : rawType) as string;
    const modelAttributes = {
      commentLines: a.comment ? [a.comment] : [],
      optional: false,
    };

    return {
      name: nominators.propertyNominator(a.name, compositeType),
      optional: false,
      typeName,
      modelAttributes,
    };
  });

  const givenName = nominators.typeNominator(compositeType.name);

  const interfaceLines = generateInterface({
    name: givenName,
    properties: properties.map(({ modelAttributes, ...props }) => ({
      ...props,
      ...modelAttributes,
    })),
    comment,
    exportAsDefault: true,
  });
  lines.push(...interfaceLines);

  return lines;
}
Example #7
Source File: generateModelFile.ts    From kanel with MIT License 4 votes vote down vote up
generateModelFile = (
  model: TableModel | ViewModel,
  {
    typeMap,
    userTypes,
    schemaName,
    nominators,
    externalTypesFolder,
    schemaFolderMap,
    makeIdType,
  }: {
    typeMap: TypeMap;
    userTypes: (string | any)[];
    schemaName: string;
    nominators: Nominators;
    externalTypesFolder?: string;
    schemaFolderMap: { [schemaName: string]: string };
    makeIdType: (innerType: string, modelName: string) => string;
  }
): string[] => {
  const fileNominator = nominators.fileNominator;
  const makeIdName = (name) =>
    nominators.idNominator(nominators.modelNominator(name), name);

  const lines = [];
  const { comment, tags } = model;

  const importGenerator = new ImportGenerator(schemaFolderMap[schemaName]);
  const referencedIdTypes = pipe(
    filter((p: Column) => Boolean(p.reference)),
    map((p) => p.reference),
    reject((p: Reference) => p.schema === schemaName && p.table === model.name),
    uniq
  )(model.columns);
  referencedIdTypes.forEach((i) => {
    const givenName = nominators.modelNominator(i.table);
    importGenerator.addImport(
      makeIdName(i.table),
      false,
      path.join(schemaFolderMap[i.schema], fileNominator(givenName, i.table)),
      false
    );
  });
  const cols = map(
    ({ isArray, type, subType, ...rest }) => ({
      type: isArray ? subType : type,
      ...rest,
    }),
    model.columns
  );
  const appliedUserTypes = uniq(
    map(
      (p: Column | { type: string }) => p.type,
      filter((p) => userTypes.indexOf(p.type) !== -1, cols)
    )
  );
  appliedUserTypes.forEach((t) => {
    const givenName = nominators.typeNominator(t);
    importGenerator.addImport(
      givenName,
      true,
      path.join(schemaFolderMap[schemaName], fileNominator(givenName, t)),
      false
    );
  });

  const overriddenTypes = map(
    (p: Column) => p.tags.type as string,
    filter((p) => Boolean(p.tags.type), model.columns)
  );
  forEach((importedType) => {
    const givenName = importedType; // We expect people to have used proper casing in their comments
    importGenerator.addImport(
      givenName,
      true,
      path.join(externalTypesFolder, fileNominator(givenName, importedType)),
      false
    );
  }, overriddenTypes);

  const primaryColumns = filter((c) => c.isPrimary, model.columns);

  // If there's one and only one primary key, that's the identifier.
  const hasIdentifier = primaryColumns.length === 1;

  const properties = model.columns.map((c) => {
    const isIdentifier = hasIdentifier && c.isPrimary;
    const idType = isIdentifier && makeIdName(model.name);
    const referenceType = c.reference && makeIdName(c.reference.table);
    let rawType = c.tags.type || idType || referenceType || typeMap[c.type];
    if (typeof rawType === 'boolean') {
      throw new Error('@type tag must include the actual type: "@type:string"');
    }
    if (typeof rawType === 'object') {
      importGenerator.addImport(
        rawType.name,
        rawType.defaultImport,
        rawType.absoluteImport
          ? rawType.module
          : path.join(
              externalTypesFolder || schemaFolderMap[schemaName],
              rawType.module
            ),
        rawType.absoluteImport
      );
      rawType = rawType.name;
    }
    if (!rawType) {
      console.warn(`Unrecognized type: '${c.type}'`);
      rawType = nominators.typeNominator(c.type);
    }
    const typeName = c.nullable ? `${rawType} | null` : rawType;
    const modelAttributes = {
      commentLines: c.comment ? [c.comment] : [],
      optional: false,
    };
    const initializerAttributes = {
      omit: c.generated === 'ALWAYS',
      commentLines: c.comment ? [c.comment] : [],
      optional: c.defaultValue || c.nullable,
    };

    if (c.defaultValue) {
      initializerAttributes.commentLines.push(
        `Default value: ${c.defaultValue}`
      );
    }

    c.indices.forEach((index) => {
      const commentLine = index.isPrimary
        ? `Primary key. Index: ${index.name}`
        : `Index: ${index.name}`;
      modelAttributes.commentLines.push(commentLine);
      initializerAttributes.commentLines.push(commentLine);
    });

    return {
      name: nominators.propertyNominator(c.name, model),
      optional: false,
      typeName,
      modelAttributes,
      initializerAttributes,
    };
  });

  const importLines = importGenerator.generateLines();
  lines.push(...importLines);

  if (importLines.length) {
    lines.push('');
  }

  if (hasIdentifier) {
    const [{ type, tags }] = primaryColumns;

    const innerType = (tags.type ||
      typeMap[type] ||
      nominators.typeNominator(type)) as string;

    lines.push(
      `export type ${makeIdName(model.name)} = ${makeIdType(
        innerType,
        model.name
      )}`
    );
    lines.push('');
  }

  const givenName = nominators.modelNominator(model.name);

  const interfaceLines = generateInterface({
    name: givenName,
    properties: properties.map(({ modelAttributes, ...props }) => ({
      ...props,
      ...modelAttributes,
    })),
    comment,
    exportAsDefault: true,
  });
  lines.push(...interfaceLines);

  const generateInitializer = !tags['fixed'] && model.type === 'table';
  if (generateInitializer) {
    lines.push('');
    const initializerInterfaceLines = generateInterface({
      name: nominators.initializerNominator(givenName, model.name),
      properties: properties
        .filter((p) => !p.initializerAttributes.omit)
        .map(({ initializerAttributes, ...props }) => ({
          ...props,
          ...initializerAttributes,
        })),
      comment,
      exportAsDefault: false,
    });
    lines.push(...initializerInterfaceLines);
  }
  return lines;
}