ramda#filter TypeScript Examples

The following examples show how to use ramda#filter. 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: substitute.ts    From interpreters with MIT License 6 votes vote down vote up
substitute = (body: CExp[], vars: string[], exps: CExp[]): CExp[] => {
    const subVarRef = (e: VarRef): CExp => {
        const pos = indexOf(e.var, vars);
        return ((pos > -1) ? exps[pos] : e);
    };
    
    const subProcExp = (e: ProcExp): ProcExp => {
        const argNames = map((x) => x.var, e.args);
        const subst = zip(vars, exps);
        const freeSubst = filter((ve) => !includes(first(ve), argNames), subst);
        return makeProcExp(
            e.args,
            substitute(
                e.body,
                map((x: KeyValuePair<string, CExp>) => x[0], freeSubst),
                map((x: KeyValuePair<string, CExp>) => x[1], freeSubst)
            )
        );
    };
    
    const sub = (e: CExp): CExp => isNumExp(e) ? e :
        isBoolExp(e) ? e :
        isPrimOp(e) ? e :
        isLitExp(e) ? e :
        isStrExp(e) ? e :
        isVarRef(e) ? subVarRef(e) :
        isIfExp(e) ? makeIfExp(sub(e.test), sub(e.then), sub(e.alt)) :
        isProcExp(e) ? subProcExp(e) :
        isAppExp(e) ? makeAppExp(sub(e.rator), map(sub, e.rands)) :
        e;
    
    return map(sub, body);
}
Example #2
Source File: production.ts    From reskript with MIT License 6 votes vote down vote up
factory: ConfigurationFactory = async entry => {
    const {cwd} = entry;
    const nodeModule = async (...segments: string[]): Promise<string> => {
        const name = path.join('node_modules', ...segments);
        const module = await findUp(name, {cwd}) ?? '';
        return module;
    };
    const resolvingModules = [
        nodeModule('react', 'umd', 'react.production.min.js'),
        nodeModule('react-dom', 'umd', 'react-dom.production.min.js'),
        nodeModule('react-redux', 'dist', 'react-redux.min.js'),
        nodeModule('redux', 'dist', 'redux.min.js'),
    ] as const;
    const [react, reactDOM, reactRedux, redux] = await Promise.all(resolvingModules);
    const alias = {
        react$: react,
        'react-dom$': reactDOM,
        'react-redux$': reactRedux,
        redux$: redux,
    };

    const config: Configuration = {
        devtool: 'source-map',
        resolve: {
            alias: filter(v => !!v, alias),
        },
        performance: {
            maxEntrypointSize: Infinity,
            // 最大允许1.5MB的产出,在GZip后大致是250-400KB,在内网下还能接受
            maxAssetSize: 1.5 * 1024 * 1024,
        },
        optimization: {
            removeEmptyChunks: true,
            sideEffects: true,
        },
    };
    return config;
}
Example #3
Source File: fieldManager.ts    From react-js-tutorial with MIT License 6 votes vote down vote up
getDiagonals = (gameField: GameFieldType, bottomToTop = true) => {
  const Ylength = gameField.length;
  const Xlength = gameField[0].length;
  const maxLength = Math.max(Xlength, Ylength);
  const result: string[][] = [];
  for (let k = 0; k <= 2 * maxLength; k++) {
    for (let y = 0; y <= Ylength - 1; y++) {
      const x = k - (bottomToTop ? Ylength - y : y);
      if (x >= 0 && x < Xlength && gameField[y][x]) {
        if (!result[k]) {
          result[k] = [];
        }
        result[k].push(gameField[y][x]);
      }
    }
  }
  return filter(complement(isNil), result);
}
Example #4
Source File: SaiditIngestStore.ts    From notabug with MIT License 5 votes vote down vote up
getListingThings = pipe(
  pathOr<readonly any[]>([], ['data', 'children']),
  map(item => ({
    ...item.data,
    kind: item.kind
  })),
  filter(d => !!d)
)
Example #5
Source File: permission-overwriter.component.ts    From radiopanel with GNU General Public License v3.0 5 votes vote down vote up
public getPermissionCountByState(permissions: any[], state: string): number {
		// Jesus fuck, these typings suck ass...
		return Object.keys((compose as any)(
			filter(n => n === state),
			pick(permissions.map(x => x.value))
		)(this.control.value)).length;
	}
Example #6
Source File: permission-selector.component.ts    From radiopanel with GNU General Public License v3.0 5 votes vote down vote up
public getEnabledPermissionsCount(permissions: any[]): number {
		// Jesus fuck, these typings suck ass...
		return Object.keys((compose as any)(
			filter(n => !!n),
			pick(permissions.map(x => x.value))
		)(this.control.value)).length;
	}
Example #7
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 #8
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;
}