unitmaster 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 sizone
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,125 @@
1
+ # UnitConvert
2
+
3
+ TypeScript 기반의 강력하고 유연한 단위 변환 라이브러리입니다.
4
+ 컴퓨터 용량, 전력, 거리 등 다양한 도메인의 단위 변환을 지원하며, 사용자 정의 단위를 쉽게 확장할 수 있습니다.
5
+
6
+ ## 설치 (Installation)
7
+
8
+ ```bash
9
+ npm install unitconvert
10
+ ```
11
+
12
+ ## 주요 기능 (Features)
13
+
14
+ - **다양한 기본 변환기 제공**: 컴퓨터 용량, 전력 용량/사용량, 거리 등
15
+ - **상대적 단위 정의**: 이전 단위 대비 배수(Step)를 통한 직관적인 단위 정의
16
+ - **최적 단위 자동 변환**: 값을 가장 읽기 쉬운 단위로 자동 포맷팅 (`formatBest`)
17
+ - **타입 안전성**: TypeScript로 작성되어 완벽한 타입 지원
18
+ - **확장 가능**: `UnitConverter` 클래스를 상속받아 나만의 변환기 제작 가능
19
+
20
+ ## 사용법 (Usage)
21
+
22
+ ### 1. 컴퓨터 용량 변환 (Computer Capacity)
23
+
24
+ Byte, KB, MB, GB, TB, PB, EB, ZB, YB 등을 지원합니다. (1024 배수 기준)
25
+
26
+ ```typescript
27
+ import { ComputerCapacityConverter } from 'unitconvert';
28
+
29
+ const converter = new ComputerCapacityConverter();
30
+
31
+ // 1. 단순 단위 변환
32
+ // 1024 Byte -> 1 KB
33
+ console.log(converter.convertTo(1024, 'Byte', 'KB')); // 1
34
+
35
+ // 1 MB -> Byte
36
+ console.log(converter.convertTo(1, 'MB', 'Byte')); // 1048576
37
+
38
+ // 2. 최적 단위 자동 포맷팅
39
+ console.log(converter.formatBest(1048576)); // "1 MB"
40
+ console.log(converter.formatBest(2048)); // "2 KB"
41
+ ```
42
+
43
+ ### 2. 거리 변환 (Distance)
44
+
45
+ mm, cm(10), m(100), km(1000) 단위를 지원합니다.
46
+
47
+ ```typescript
48
+ import { DistanceConverter } from 'unitconvert';
49
+
50
+ const distConverter = new DistanceConverter();
51
+
52
+ // 1 km -> m
53
+ console.log(distConverter.convertTo(1, 'km', 'm')); // 1000
54
+
55
+ // 100 cm -> 1 m
56
+ console.log(distConverter.formatBest(100, undefined)); // "10 cm" 가 아니라 최적 단위인 "1 m"로 변환 (로직에 따라 다름)
57
+ // formatBest는 값이 1 이상이 되는 가장 큰 단위를 찾습니다.
58
+ ```
59
+
60
+ ### 3. 전력 변환 (Power)
61
+
62
+ - **PowerCapacityConverter**: W, kW, MW, GW, TW (1000 배수)
63
+ - **PowerUsageConverter**: Wh, kWh, MWh, GWh, TWh (1000 배수)
64
+
65
+ ```typescript
66
+ import { PowerCapacityConverter } from 'unitconvert';
67
+
68
+ const powerConverter = new PowerCapacityConverter();
69
+ console.log(powerConverter.formatBest(1500)); // "1.5 kW" (기본 단위 W 기준)
70
+ ```
71
+
72
+ ## 고급 사용법 (Advanced)
73
+
74
+ ### 사용자 정의 단위 추가 (Custom Units)
75
+
76
+ 기존 변환기에 새로운 단위를 추가할 수 있습니다. `registerUnit`으로 추가하는 단위는 **마지막 단위**를 기준으로 계산됩니다.
77
+
78
+ ```typescript
79
+ const converter = new ComputerCapacityConverter();
80
+ // YB(YottaByte) 다음 단위로 BrontoByte(BB)를 추가한다고 가정 (1024배)
81
+ converter.registerUnit([{ unit: 'BB', unitValue: 1024 }]);
82
+ ```
83
+
84
+ ### 나만의 변환기 만들기 (Custom Converter)
85
+
86
+ `UnitConverter`를 상속받아 새로운 도메인의 변환기를 만들 수 있습니다.
87
+
88
+ ```typescript
89
+ import { UnitConverter } from 'unitconvert';
90
+
91
+ class TimeConverter extends UnitConverter {
92
+ constructor() {
93
+ super();
94
+ this.registerUnit([
95
+ { unit: 'Sec', unitValue: 1 }, // 기준 단위
96
+ { unit: 'Min', unitValue: 60 }, // 이전 단위(Sec) * 60
97
+ { unit: 'Hour', unitValue: 60 }, // 이전 단위(Min) * 60
98
+ { unit: 'Day', unitValue: 24 } // 이전 단위(Hour) * 24
99
+ ]);
100
+ }
101
+ }
102
+
103
+ const timeConverter = new TimeConverter();
104
+ console.log(timeConverter.formatBest(3600)); // "1 Hour"
105
+ ```
106
+
107
+ ### 복합 입력값 처리
108
+
109
+ 값과 단위 정의를 객체로 전달하여 처리할 수도 있습니다. 이 경우 동적으로 전달된 단위 정의를 사용합니다.
110
+
111
+ ```typescript
112
+ const complexInput = {
113
+ value: 2048,
114
+ unit: [
115
+ { unit: 'Byte', unitValue: 1 },
116
+ { unit: 'KB', unitValue: 1024 }
117
+ ]
118
+ };
119
+ // converter 인스턴스의 종류와 상관없이 formatBest는 입력받은 unit 정의를 우선할 수 있습니다.
120
+ // (단, formatBest 구현 상세에 따라 사용법이 다를 수 있음. 주로 내부 로직용)
121
+ ```
122
+
123
+ ## 라이선스
124
+
125
+ MIT
@@ -0,0 +1,51 @@
1
+ /**
2
+ * @file UnitConverter.ts
3
+ * @author 김영찬
4
+ * @since 2026-01-20
5
+ * @description 단위 변환 기능 및 최적 단위 표시 기능을 제공하는 메인 클래스입니다.
6
+ */
7
+ import { UnitDefinition, ComplexValueInput } from './types';
8
+ /**
9
+ * 단위 변환기 클래스
10
+ */
11
+ export declare class UnitConverter {
12
+ private units;
13
+ /**
14
+ * 생성자
15
+ * @description 기본 컴퓨터 용량 단위(Byte, KB, MB, GB, TB, PB)를 초기화합니다.
16
+ */
17
+ constructor();
18
+ /**
19
+ * 기본 컴퓨터 용량 단위 등록
20
+ */
21
+ private registerDefaultUnits;
22
+ /**
23
+ * 단위 등록 (Rule 5)
24
+ * @param units 단위 정의 목록
25
+ */
26
+ registerUnit(units: UnitDefinition[]): void;
27
+ /**
28
+ * 특정 단위로 값 변환 (Rule 1, Rule 4)
29
+ * @param value 값
30
+ * @param fromUnit 현재 단위 (문자열)
31
+ * @param toUnit 변환할 단위 (문자열)
32
+ * @returns 변환된 값
33
+ */
34
+ convertTo(value: number, fromUnit: string, toUnit: string): number;
35
+ /**
36
+ * 입력 값을 받아 최적의 단위로 변환 (Rule 1, Rule 2, Rule 3)
37
+ * @param input 복합 입력 값 ({value, unit[]}) 또는 단순 값
38
+ * @param fixedUnits 사용할 단위 목록 (없으면 등록된 단위 사용)
39
+ * @returns 변환된 문자열 (예: "100 MB")
40
+ */
41
+ formatBest(input: number, fixedUnits?: UnitDefinition[]): string;
42
+ formatBest(input: ComplexValueInput): string;
43
+ /**
44
+ * 단위 정의 검색
45
+ */
46
+ private findUnit;
47
+ /**
48
+ * 현재 등록된 단위 목록 반환
49
+ */
50
+ getUnits(): UnitDefinition[];
51
+ }
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ /**
3
+ * @file UnitConverter.ts
4
+ * @author 김영찬
5
+ * @since 2026-01-20
6
+ * @description 단위 변환 기능 및 최적 단위 표시 기능을 제공하는 메인 클래스입니다.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.UnitConverter = void 0;
10
+ /**
11
+ * 단위 변환기 클래스
12
+ */
13
+ class UnitConverter {
14
+ /**
15
+ * 생성자
16
+ * @description 기본 컴퓨터 용량 단위(Byte, KB, MB, GB, TB, PB)를 초기화합니다.
17
+ */
18
+ constructor() {
19
+ this.units = [];
20
+ this.registerDefaultUnits();
21
+ }
22
+ /**
23
+ * 기본 컴퓨터 용량 단위 등록
24
+ */
25
+ registerDefaultUnits() {
26
+ this.units = [
27
+ { unit: 'Byte', unitValue: 1 },
28
+ { unit: 'KB', unitValue: 1024 },
29
+ { unit: 'MB', unitValue: 1024 * 1024 },
30
+ { unit: 'GB', unitValue: 1024 * 1024 * 1024 },
31
+ { unit: 'TB', unitValue: 1024 * 1024 * 1024 * 1024 },
32
+ { unit: 'PB', unitValue: 1024 * 1024 * 1024 * 1024 * 1024 }
33
+ ];
34
+ }
35
+ /**
36
+ * 단위 등록 (Rule 5)
37
+ * @param units 단위 정의 목록
38
+ */
39
+ registerUnit(units) {
40
+ this.units = [...this.units, ...units];
41
+ // unitValue 기준으로 오름차순 정렬 (계산 편의성)
42
+ this.units.sort((a, b) => a.unitValue - b.unitValue);
43
+ }
44
+ /**
45
+ * 특정 단위로 값 변환 (Rule 1, Rule 4)
46
+ * @param value 값
47
+ * @param fromUnit 현재 단위 (문자열)
48
+ * @param toUnit 변환할 단위 (문자열)
49
+ * @returns 변환된 값
50
+ */
51
+ convertTo(value, fromUnit, toUnit) {
52
+ const fromDef = this.findUnit(fromUnit);
53
+ const toDef = this.findUnit(toUnit);
54
+ if (!fromDef || !toDef) {
55
+ throw new Error(`Unit not found: ${!fromDef ? fromUnit : toUnit}`);
56
+ }
57
+ // 기본 단위 값으로 변환 후 목표 단위로 변환
58
+ // 예: 1 KB (1024) -> MB (1024*1024)
59
+ // 1 * 1024 / (1024*1024) = 0.0009765625
60
+ const baseValue = value * fromDef.unitValue;
61
+ return baseValue / toDef.unitValue;
62
+ }
63
+ formatBest(input, fixedUnits) {
64
+ let value;
65
+ let unitDefs;
66
+ if (typeof input === 'object' && 'unit' in input) {
67
+ // Rule 2 Case
68
+ // 입력값은 기본 단위(unitValue:1 또는 가장 작은 단위) 기준이라고 가정하거나,
69
+ // 아니면 입력 구조에 대한 명확한 정의가 필요함.
70
+ // 여기서는 입력된 value가 제공된 unit[0] (혹은 unitValue=1)이 아니라,
71
+ // 제공된 unit 리스트를 '사용할 단위 체계'로 보고,
72
+ // value는 그 체계의 가장 작은 단위(혹은 기준 값)라고 가정함.
73
+ // *주의*: 요구사항의 예시가 모호하므로, 값은 Base Unit 기준이라고 가정.
74
+ value = input.value;
75
+ unitDefs = input.unit;
76
+ // 정렬
77
+ unitDefs.sort((a, b) => a.unitValue - b.unitValue);
78
+ }
79
+ else {
80
+ value = input;
81
+ unitDefs = fixedUnits || this.units;
82
+ }
83
+ if (unitDefs.length === 0)
84
+ return `${value}`;
85
+ // 가장 큰 단위부터 확인하여 값이 >= 1 인지 확인 (혹은 가장 적절한 단위)
86
+ // 오름차순 정렬되어 있다고 가정
87
+ // 예: 1000 Byte -> Byte (1000 >= 1)
88
+ // 1024 Byte -> KB (1024 >= 1024) => 1 KB
89
+ // 뒤(큰 단위)에서부터 탐색
90
+ for (let i = unitDefs.length - 1; i >= 0; i--) {
91
+ const unit = unitDefs[i];
92
+ if (value >= unit.unitValue) {
93
+ const converted = value / unit.unitValue;
94
+ // 정수로 딱 떨어지거나, 소수점 2자리까지 표시
95
+ const formatted = Number.isInteger(converted) ? converted : converted.toFixed(2);
96
+ return `${formatted} ${unit.unit}`;
97
+ }
98
+ }
99
+ // 가장 작은 단위보다도 작을 경우, 가장 작은 단위로 표시
100
+ const smallest = unitDefs[0];
101
+ const converted = value / smallest.unitValue;
102
+ const formatted = Number.isInteger(converted) ? converted : converted.toFixed(2);
103
+ return `${formatted} ${smallest.unit}`;
104
+ }
105
+ /**
106
+ * 단위 정의 검색
107
+ */
108
+ findUnit(unitName) {
109
+ return this.units.find(u => u.unit === unitName);
110
+ }
111
+ /**
112
+ * 현재 등록된 단위 목록 반환
113
+ */
114
+ getUnits() {
115
+ return this.units;
116
+ }
117
+ }
118
+ exports.UnitConverter = UnitConverter;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @file index.ts
3
+ * @author 김영찬
4
+ * @since 2026-01-20
5
+ * @description 라이브러리 엔트리 포인트입니다.
6
+ */
7
+ export * from './types';
8
+ export * from './UnitConverter';
package/dist/index.js ADDED
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ /**
3
+ * @file index.ts
4
+ * @author 김영찬
5
+ * @since 2026-01-20
6
+ * @description 라이브러리 엔트리 포인트입니다.
7
+ */
8
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
+ if (k2 === undefined) k2 = k;
10
+ var desc = Object.getOwnPropertyDescriptor(m, k);
11
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12
+ desc = { enumerable: true, get: function() { return m[k]; } };
13
+ }
14
+ Object.defineProperty(o, k2, desc);
15
+ }) : (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ o[k2] = m[k];
18
+ }));
19
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
20
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
21
+ };
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ __exportStar(require("./types"), exports);
24
+ __exportStar(require("./UnitConverter"), exports);
@@ -0,0 +1,34 @@
1
+ /**
2
+ * @file types.ts
3
+ * @author 김영찬
4
+ * @since 2026-01-20
5
+ * @description 단위 변환기에서 사용하는 타입 정의 파일입니다.
6
+ */
7
+ /**
8
+ * 단위 정의 인터페이스
9
+ * @interface UnitDefinition
10
+ */
11
+ export interface UnitDefinition {
12
+ /**
13
+ * 단위 명칭 (예: 'Byte', 'KB')
14
+ */
15
+ unit: string;
16
+ /**
17
+ * 단위 값 (기준 단위 대비 배수)
18
+ */
19
+ unitValue: number;
20
+ }
21
+ /**
22
+ * 복잡한 입력 값 구조
23
+ * @description 값과 해당 값의 단위 정의 목록을 포함하는 입력 형태입니다.
24
+ */
25
+ export interface ComplexValueInput {
26
+ /**
27
+ * 변환할 값
28
+ */
29
+ value: number;
30
+ /**
31
+ * 단위 정의 목록
32
+ */
33
+ unit: UnitDefinition[];
34
+ }
package/dist/types.js ADDED
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ /**
3
+ * @file types.ts
4
+ * @author 김영찬
5
+ * @since 2026-01-20
6
+ * @description 단위 변환기에서 사용하는 타입 정의 파일입니다.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "unitmaster",
3
+ "version": "1.0.0",
4
+ "description": "Unit Converter Library",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "scripts": {
11
+ "build": "tsc",
12
+ "test": "mocha -r ts-node/register test/**/*.test.ts"
13
+ },
14
+ "keywords": [
15
+ "unit",
16
+ "converter"
17
+ ],
18
+ "author": "김영찬",
19
+ "license": "MIT",
20
+ "devDependencies": {
21
+ "@types/chai": "^4.3.11",
22
+ "@types/mocha": "^10.0.6",
23
+ "@types/node": "^20.10.5",
24
+ "chai": "^4.3.10",
25
+ "mocha": "^10.2.0",
26
+ "ts-node": "^10.9.2",
27
+ "typescript": "^5.3.3"
28
+ }
29
+ }