Functional Weave
Code in TypeScript

net.cidr-hosts@1.0.0

impl/typescript.ts

936 bytes · the TypeScript implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { cidrInfo } from "./net_cidr_cidr_info.ts";
import { formatIpv4, parseIpv4 } from "./net_ipv4.ts";  ← from net.ipv4 ^1.0.0 · built alongside by fune

/**
 * Every usable host address of an IPv4 block, in order, for a sweep. The
 * limit is required, not optional: a typo of /8 for /28 is sixteen million
 * addresses, and the caller should hear about it before allocating them.
 */
export function cidrHosts(cidr: string, maxCount: number): readonly string[] {
  if (typeof maxCount !== "number" || !Number.isInteger(maxCount) || maxCount < 1) {
    throw new Error(`maxCount must be a whole number of at least 1, received ${maxCount}`);
  }
  const info = cidrInfo(cidr);
  if (info.hostCount > maxCount) {
    throw new Error(`${info.cidr} has ${info.hostCount} hosts, more than maxCount ${maxCount}`);
  }
  const first = parseIpv4(info.firstHost);
  const hosts: string[] = [];
  for (let i = 0; i < info.hostCount; i++) hosts.push(formatIpv4(first + i));
  return hosts;
}