TypeScript综合练习2(文本处理)

Text Processor

You’ll practice creating and transforming arrays of strings.

Hello, fellow text editing and type setting enthusiast!
I hear you have a dual interest in both TypeScript and and type scripts.
That’s great because I have a few projects for you to help me out with all of those things.

I have a collection of raw text strings that represent some of my favorite pieces of literature.
I’d like to set up code that can turn those pieces of text into print-ready lines, each capped at a maximum character width.

Before we can do any of our fancy typography work on text, we need to split text into lines.
Much of our text data is stored in strings where the only whitespace is a single " " space between words.

More specifically: I’m going to give you an array of lines - each represented as a string.
For each of those lines, give me back an array of strings (so the final result is an array of array of strings).
Each of the strings in the array has as many of the words from the first line as it can fit, as long as there’s a " " space between them.

Additionally, for each line, I’ll need the ability to align it to the left, middle, or right.
Alignment means adding spaces to the beginning and/or end of the string to fit it to a specified character width.

Can you type this text processor up for me, fellow typography practitioner?

Setup

In one terminal, run the TypeScript compiler via the tsc script.
For example, to start the TypeScript compiler in watch mode:

npm run tsc -- --watch

In another terminal, run Jest via the test script.
For example, to start tests in watch mode:

npm run test -- --watch

Specification

In index.ts, export an alignTexts function.

Parameters:

  1. texts: An array of strings
  2. options: An object with the following properties:
    • align (optional): Whether to align to the left (default), middle, or right
    • width: Maximum character width for each processed line

Return type: An array of array of strings.

Examples

In this first example, each output string must be 3 characters long.
The first string can fit "ab" but can’t fit the additional word "c" because that would be 4 characters ("ab c").
The second string can git "c" and "d" with a space between them.

  • Input: alignTexts(["ab c d"], { width: 3 })

  • Output:

    [["ab ", "c d"]]
    

Here, there are three lines to be split, and each becomes one of the arrays in the output array.
align: "right" indicates that spaces must be added before characters (to their left), not after them (to their right).
The first line can only fit one word (first "ab", then "cd") in the allowed 4 spaces.
The second line again can only fit one word in its allowed spaces.
The third line is the only one that can fit two words together: "a" and "bc", which together with a space take up 4 characters.

  • Input: alignTexts(["ab cd", "abc def", "a bc def"], { align: "right", width: 4 })

  • Output:

    [
    	["  ab", "  cd"],
    	[" abc", " def"],
    	["a bc", " def"]
    ]
    

This last example shows aligning text to the middle.
If there’s an extra space, it’s added to the right (at the end).

  • Input: alignTexts(["a", "ab", "abc", "abcd"], { align: "middle", width: 4 })

  • Output:

    [[" a  "], [" ab "], ["abc "], ["abcd"]]
    

Files

  • index.ts: Add your alignTexts function and type annotations here
  • index.test.ts: Tests verifying your alignTexts function and type annotations
  • solution.ts: Solution code
    • solution-alternate.ts: Alternate solution code that uses a more functional approach

Notes

  • text.split(" ") is sufficient to split the original text into an array of words.
    • Don’t worry about spaces being off: words will only ever be separated by a single " " space.

代码

export type AlignmentOptions = {
	align?: "left" | "middle" | "right";
	width: number;
};

export function alignTexts(texts: string[], options: AlignmentOptions) {
	const alignedTextsLines: string[][] = [];

	for (const text of texts) {
		const lines = splitLines(text, options.width);
		const aligned = alignLines(lines, options);

		alignedTextsLines.push(aligned);
	}

	return alignedTextsLines;
}

function splitLines(text: string, width: number) {
	const lines: string[] = [];
	let line = "";

	for (const word of text.split(" ")) {
		if (line === "") {
			line = word;
		} else if (line.length + word.length < width) {
			line += ` ${word}`;
		} else {
			lines.push(line);
			line = word;
		}
	}

	lines.push(line);

	return lines;
}

function alignLines(
	lines: string[],
	{ align = "left", width }: AlignmentOptions
) {
	const aligned: string[] = [];

	for (const line of lines) {
		const remainingSpaces = width - line.length;
		let newLine = line;

		if (remainingSpaces) {
			switch (align) {
				case "left":
					for (let i = 0; i < remainingSpaces; i += 1) {
						newLine += " ";
					}
					break;

				case "middle":
					for (let i = 0; i < Math.ceil(remainingSpaces / 2); i += 1) {
						newLine += " ";
					}

					for (let i = 0; i < Math.floor(remainingSpaces / 2); i += 1) {
						newLine = " " + newLine;
					}

					break;

				case "right":
					for (let i = 0; i < remainingSpaces; i += 1) {
						newLine = " " + newLine;
					}
					break;
			}
		}

		aligned.push(newLine);
	}

	return aligned;
}

let result = alignTexts(["abc def", "abc def ghi"], { align: "right", width: 5 });
console.log(result)

结果

[ [ '  abc', '  def' ], [ '  abc', '  def', '  ghi' ] ]

另一种解法

export type AlignmentOptions = {
	align?: "left" | "middle" | "right";
	width: number;
};

export function alignTexts(texts: string[], options: AlignmentOptions) {
	return texts.map((text) =>
		alignLines(splitLines(text, options.width), options)
	);
}

function splitLines(text: string, width: number) {
	const lines: string[] = [];
	let line = "";

	for (const word of text.split(" ")) {
		if (line === "") {
			line = word;
		} else if (line.length + word.length < width) {
			line += ` ${word}`;
		} else {
			lines.push(line);
			line = word;
		}
	}

	lines.push(line);

	return lines;
}

const aligners = {
	left: (line: string, width: number) => line.padEnd(width),
	middle: (line: string, width: number) => {
		const remainingSpaces = width - line.length;

		return remainingSpaces
			? [
					" ".repeat(Math.floor(remainingSpaces / 2)),
					line,
					" ".repeat(Math.ceil(remainingSpaces / 2)),
			  ].join("")
			: line;
	},
	right: (line: string, width: number) => line.padStart(width),
};

function alignLines(
	lines: string[],
	{ align = "left", width }: AlignmentOptions
) {
	return lines.map((line) => aligners[align](line, width));
}


let result = alignTexts(["abc def", "abc def ghi"], { align: "right", width: 5 });
console.log(result)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/608653.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

使用Postman进行接口测试---解析postman页面

一、Postman 是一款流行的 API 测试工具&#xff0c;它提供了丰富的功能来帮助开发者测试和调试 API。以下是 Postman 页面上的主要功能及其含义和作用&#xff1a; 1. 请求详情&#xff08;Request Details&#xff09; &#xff1a; - 方法&#xff08;Method&#xff0…

【读论文】Gaussian Grouping: Segment and Edit Anything in 3D Scenes

Gaussian Grouping: Segment and Edit Anything in 3D Scenes 文章目录 Gaussian Grouping: Segment and Edit Anything in 3D Scenes1. What2. Why3. How3.1 Anything Mask Input and Consistency3.2 3D Gaussian Rendering and Grouping3.3 Downstream: Local Gaussian Editi…

第二篇【AI与传奇开心果系列】Python的AI技术点库案例示例:详解AI工业应用算法原理

AI与传奇开心果系列博文 系列博文目录Python的AI技术点库案例示例系列 博文目录前言一、AI工业应用算法原理介绍二、机器学习在工业领域的应用算法示例代码三、深度学习算法在工业领域应用示例代码四、强化学习在工业领域应用示例代码五、自然语言处理在工业领域应用示例代码六…

C语言 变量的作用域

今天 我们来说变量的作用域和存储类型 每种事物 都有自己作用的范围限制 例如 汽车只能在路上跑 轮船只能在海洋 飞机只能通行于天空 函数的参数 也只有在函数被调用过程中分配内存资源 函数执行结束 空间也会被立即释放 这也说明了 行参变量只有在函数内才有效 离开了该函数 …

【JavaEE】博客系统(前端页面设计)

文章目录 一、预期效果二、实现博客列表页 一、预期效果 二、实现博客列表页 实现导航栏 编辑 blog_list.html, 创建导航栏的 html 代码. 导航栏里面包含 logo, 标题, 以及一些按钮(跳转链接). 为了实现左右排列, 在 logo 和 按钮 之间加一个 spacer 作为占位器. <!-- 导航…

初次查询大数据信用报告,需要注意哪些问题?

随着大数据的普及&#xff0c;基于大数据技术的大数据信用也变得越来越重要&#xff0c;比如在申贷之前&#xff0c;不少地方都会查询申贷人的大数据信用&#xff0c;作为风险控制的必要手段&#xff0c;那对于初次查询大数据信用报告的人来说&#xff0c;需要注意哪些问题呢?…

引领AI数据标注新纪元:景联文科技为智能未来筑基

在人工智能蓬勃发展的今天&#xff0c;数据如同燃料&#xff0c;驱动着每一次技术飞跃。在这场智能革命的浪潮中&#xff0c;景联文科技凭借其深厚的专业实力与前瞻性的战略眼光&#xff0c;正站在行业前沿&#xff0c;为全球的人工智能企业提供坚实的数据支撑。 全国布局&…

vscode的git插件使用教程

虽然git的命令我没有滚瓜烂熟&#xff0c;但vscode的git插件是尊嘟很好用啊&#xff0c;都被我用烂了。在网上看见一个讲的很不错的插件教程。借鉴一下。并在一些地方用块引用进行了补充说明&#xff01; 跳过了vscode安装过程。 克隆GitHub中的存储库&#xff1a; 1、复制Gi…

python3有serial库吗

一、概述 pyserial模块封装了对串口的访问。 二、特性 在支持的平台上有统一的接口。 通过python属性访问串口设置。 支持不同的字节大小、停止位、校验位和流控设置。 可以有或者没有接收超时。 类似文件的API&#xff0c;例如read和write&#xff0c;也支持readline等…

探案录 | KingbaseES+SqlSugar为医疗用户排忧解难

在2024年的初春&#xff0c;某大型三甲医院的CT预约系统上线测试&#xff0c;如同新芽破土&#xff0c;充满了希望与活力。然而&#xff0c;仅仅两天后&#xff0c;一个技术难题如同迷雾中的幽灵&#xff0c;悄然出现&#xff1a;The connection pool has been exhausted…… 福…

5.07 Pneumonia Detection in Chest X-Rays using Neural Networks

肺炎诊断是一个耗时的过程&#xff0c;需要高技能的专业人员分析胸部X光片chest X-ray (CXR)&#xff0c;并通过临床病史、生命体征和实验室检查确认诊断。 它可以帮助医生确定肺部感染的程度和位置。呼吸道疾病在 X 光片上表现为一处膨胀的不透明区域。然而&#xff0c;由于不…

STM32 ADC学习

ADC Analog-to-Digital Converter&#xff0c;即模拟/数字转换器 常见ADC类型 分辨率和采样速度相互矛盾&#xff0c;分辨率越高&#xff0c;采样速率越低。 ADC的特性参数 分辨率&#xff1a;表示ADC能辨别的最小模拟量&#xff0c;用二进制位数表示&#xff0c;比如8,10…

OpenAI 正在开发一种可以防止版权诉讼的工具

OpenAI 正在开发一种名为 Media Manager 的工具&#xff0c;该工具将使内容创建者和所有者能够确定他们是否愿意将自己的内容用于 ML 研究和 AI 模型训练。 Media Manager 将做什么&#xff1f; 明年推出的 Media Manager 将使内容创作者和所有者能够更好地控制他们的工作是否…

C语言初阶(6) - 指针

目录 1.指针是什么&#xff1f; 2. 指针和指针类型 2.1 指针 - 整数 2.2 指针的解引用 3. 野指针 3.1 野指针成因 3.2 如何规避野指针 4. 常量指针和指针常量 (const) 4.1.常量指针 4.2.指针常量 5. 指针运算 5.1 指针-整数 5.2 指针-指针 5.3指针的关系运算 6.…

Vitis HLS 学习笔记--理解串流Stream(2)

目录 1. 简介 2. 极简的对比 3. 硬件模块的多次触发 4. 进一步探讨 do-while 5. 总结 1. 简介 在这篇博文中《Vitis HLS 学习笔记--AXI_STREAM_TO_MASTER-CSDN博客》&#xff0c;我分享了关于 AXI Stream 接口的实际应用案例。然而&#xff0c;尽管文章中提供了代码示例&…

如何向Linux内核提交开源补丁?

2021年&#xff0c;我曾经在openEuler社区上看到一项改进Linux内核工具的需求&#xff0c;因此参与过Linux内核社区的开源贡献。贡献开源社区的流程都可以在内核社区文档中找到&#xff0c;但是&#xff0c;单独学习需要一个较长的过程&#xff0c;新手难以入门&#xff0c;因此…

分享四种免费获取SSL的方式

SSL证书目前需要部署安装的网站很多&#xff0c;主要还是基于国内目前对证书的需求度在不断的升高&#xff0c;网站多了、服务器多了之后。网络安全问题就成为了大家不得不面对的一个重要的问题了。SSL证书的作用有很多&#xff0c;这里就不一一详述了&#xff0c;本期作品主要…

如何在线阅读Linux内核源码?

开源社区有一句名言&#xff1a;Talk is cheap, show me your code。阅读源代码是学习Linux操作系统的必经之路。但是&#xff0c;Linux内核的代码量超过3000万行&#xff0c;工程包非常大&#xff0c;直接下载耗时较长&#xff0c;这就需要使用一些在线阅读的技巧。 方式1&am…

【深度学习】【Lora训练0】StabelDiffusion,Lora训练,kohya_ss训练

文章目录 环境数据自动标注kohya_ss BLIP2kohya_ss WD14 后续 资源&#xff1a; &#xff08;1&#xff09;训练ui kohya_ss&#xff1a; https://github.com/bmaltais/kohya_ss &#xff08;2&#xff09;kohya_ss 的docker 其他docker https://github.com/ashleykleynhans…

韩顺平0基础学Java——第7天

p110-p154 控制结构&#xff08;第四章&#xff09; 多分支 if-elseif-else import java.util.Scanner; public class day7{public static void main(String[] args) {Scanner myscanner new Scanner(System.in);System.out.println("input your score?");int s…
最新文章