# @ohos.util (util)
The util module provides common utility functions, such as [TextEncoder](#textencoder) and [TextDecoder](#textdecoder) for string encoding and decoding, [RationalNumber8+](#rationalnumber8) for rational number operations, [LRUCache9+](#lrucache9) for cache management, [ScopeHelper9+](#scopehelper9) for range determination, [Base64Helper9+](#base64helper9) for Base64 encoding and decoding, [types8+](#types8) for built-in object type check, and [Aspect11+](#aspect11) for instrumentation and replacement on methods.
> **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
import { util } from '@kit.ArkTS';
```
## util.format9+
format(format: string, ...args: Object[]): string
Formats a string by replacing the placeholders in it.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | -------- | ---- | -------------- |
| format | string | Yes | Format string. This string contains zero or more placeholders, which specify the position and format of the arguments to be inserted.|
| ...args | Object[] | No | Data used to replace the placeholders in **format**. If **null** is passed in, the first argument is returned by default.|
**Return value**
| Type | Description |
| ------ | -----------------|
| string | Formatted string.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Format Specifiers**
| Specifier| Description |
| ------ | -------------------------------- |
| %s | Converts a parameter into a string for all values except **Object**, **BigInt**, and **-0**.|
| %d | Converts a parameter into a decimal integer for all values except **Symbol** and **BigInt**.|
| %i | Converts a string into a decimal integer for all values except **Symbol** and **BigInt**.|
| %f | Converts a string into a floating point number for all values except **BigInt** and **Symbol**.|
| %j | Converts a JavaScript object into a JSON string.|
| %o | Converts a JavaScript object into a string, without containing the prototype chain information of the object.|
| %O | Converts a JavaScript object into a string.|
| %c | Valid only in the browser. It is ignored in other environments.|
| %% | Placeholder for escaping the percent sign.|
**Example**
```ts
import { util } from '@kit.ArkTS';
interface utilAddresstype {
city: string;
country: string;
}
interface utilPersontype {
name: string;
age: number;
address: utilAddresstype;
}
let name = 'John';
let age = 20;
let formattedString = util.format('My name is %s and I am %s years old', name, age);
console.info(formattedString);
// Output: My name is John and I am 20 years old
let num = 10.5;
formattedString = util.format('The number is %d', num);
console.info(formattedString);
// Output: The number is 10.5.
num = 100.5;
formattedString = util.format('The number is %i', num);
console.info(formattedString);
// Output: The number is 100.
const pi = 3.141592653;
formattedString = util.format('The value of pi is %f', pi);
console.info(formattedString);
// Output: The value of pi is 3.141592653
const obj: Record = { "name": 'John', "age": 20 };
formattedString = util.format('The object is %j', obj);
console.info(formattedString);
// Output: The object is {"name":"John","age":20}.
const person: utilPersontype = {
name: 'John',
age: 20,
address: {
city: 'New York',
country: 'USA'
}
};
console.info(util.format('Formatted object using %%O: %O', person));
console.info(util.format('Formatted object using %%o: %o', person));
/*
Output:
Formatted object using %O: { name: 'John',
age: 20,
address:
{ city: 'New York',
country: 'USA' } }
Formatted object using %o: { name: 'John',
age: 20,
address:
{ city: 'New York',
country: 'USA' } }
*/
const percentage = 80;
let arg = 'homework';
formattedString = util.format('John finished %d%% of the %s', percentage, arg);
console.info(formattedString);
// Output: John finished 80% of the homework
```
## util.errnoToString9+
errnoToString(errno: number): string
Obtains detailed information about a system error code.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------------------------- |
| errno | number | Yes | Error code generated.|
**Return value**
| Type | Description |
| ------ | ---------------------- |
| string | Detailed information about the error code.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Example**
```ts
let errnum = -1; // -1 is a system error code.
let result = util.errnoToString(errnum);
console.info("result = " + result);
// Output: result = operation not permitted
```
**Some error code and message examples**
| Error Code| Message |
| ------ | -------------------------------- |
| -1 | operation not permitted |
| -2 | no such file or directory |
| -3 | no such process |
| -4 | interrupted system call |
| -5 | i/o error |
| -11 | resource temporarily unavailable |
| -12 | not enough memory |
| -13 | permission denied |
| -100 | network is down |
## util.callbackWrapper
callbackWrapper(original: Function): (err: Object, value: Object )=>void
Calls back an asynchronous function. In the callback, the first parameter indicates the cause of the rejection (the value is **null** if the promise has been resolved), and the second parameter indicates the resolved value.
> **NOTE**
>
> **original** must be an asynchronous function. If a non-asynchronous function is passed in, the function is not intercepted, but the error message "callbackWrapper: The type of Parameter must be AsyncFunction" is displayed.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| original | Function | Yes| Asynchronous function.|
**Return value**
| Type| Description|
| -------- | -------- |
| Function | Callback function, in which the first parameter **err** indicates the cause of the rejection (the value is **null** if the promise has been resolved) and the second parameter **value** indicates the resolved value.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Example**
```ts
async function fn() {
return 'hello world';
}
let cb = util.callbackWrapper(fn);
cb(1, (err : Object, ret : string) => {
if (err) throw new Error;
console.info(ret);
});
// Output: hello world
```
## util.promisify9+
promisify(original: (err: Object, value: Object) => void): Function
Processes an asynchronous function and returns a promise.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| original | Function | Yes| Function, in which the first parameter **err** indicates the cause of the rejection (the value is **null** if the promise has been resolved) and the second parameter **value** indicates the resolved value. |
**Return value**
| Type| Description|
| -------- | -------- |
| Function | Promise function.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Example**
```ts
async function fn() {
return 'hello world';
}
const addCall = util.promisify(util.callbackWrapper(fn));
(async () => {
try {
let res: string = await addCall();
console.info(res);
// Output: hello world
} catch (err) {
console.info(err);
}
})();
```
## util.generateRandomUUID9+
generateRandomUUID(entropyCache?: boolean): string
Uses a secure random number generator to generate a random universally unique identifier (UUID) of the string type in RFC 4122 version 4. To improve performance, this API uses cached UUIDs by default, in which **entropyCache** is set to **true**. A maximum of 128 random UUIDs can be cached. After all the 128 UUIDs in the cache are used, a new set of UUIDs is generated to maintain their random distribution. If you do not need to use the cached UUID, set **entropyCache** to **false**.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| entropyCache | boolean | No| Whether a cached UUID can be used. The default value is **true**.|
**Return value**
| Type| Description|
| -------- | -------- |
| string | A string representing the UUID generated.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. |
**Example**
```ts
let uuid = util.generateRandomUUID(true);
console.info("RFC 4122 Version 4 UUID:" + uuid);
// Output a random UUID.
```
## util.generateRandomBinaryUUID9+
generateRandomBinaryUUID(entropyCache?: boolean): Uint8Array
Uses a secure random number generator to generate a random UUID of the Uint8Array type in RFC 4122 version 4.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| entropyCache | boolean | No| Whether a cached UUID can be used. The default value is **true**.|
**Return value**
| Type| Description|
| -------- | -------- |
| Uint8Array | A Uint8Array value representing the UUID generated.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. |
**Example**
```ts
let uuid = util.generateRandomBinaryUUID(true);
console.info(JSON.stringify(uuid));
// Output a random UUID.
```
## util.parseUUID9+
parseUUID(uuid: string): Uint8Array
Converts a UUID of the string type generated by **generateRandomUUID** to a UUID of the Uint8Array type generated by **generateRandomBinaryUUID**, as described in RFC 4122 version 4.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| uuid | string | Yes| A string representing the UUID.|
**Return value**
| Type| Description|
| -------- | -------- |
| Uint8Array | A Uint8Array value representing the UUID parsed. If the parsing fails, **SyntaxError** is thrown.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. |
| 10200002 | Invalid uuid string. |
**Example**
```ts
let uuid = util.parseUUID("84bdf796-66cc-4655-9b89-d6218d100f9c");
console.info("uuid = " + uuid);
// Output: uuid = 132,189,247,150,102,204,70,85,155,137,214,33,141,16,15,156
```
## util.printf(deprecated)
printf(format: string, ...args: Object[]): string
Formats a string by replacing the placeholders in it.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [util.format9+](#utilformat9) instead.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| format | string | Yes| Format string.|
| ...args | Object[] | No| Data used to replace the placeholders in **format**. If **null** is passed in, the first argument is returned by default.|
**Return value**
| Type| Description|
| -------- | -------- |
| string | String containing the formatted values.|
**Example**
```ts
let res = util.printf("%s", "hello world!");
console.info(res);
// Output: hello world!
```
## util.getErrorString(deprecated)
getErrorString(errno: number): string
Obtains detailed information about a system error code.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [util.errnoToString9+](#utilerrnotostring9) instead.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| errno | number | Yes| Error code generated.|
**Return value**
| Type| Description|
| -------- | -------- |
| string | Detailed information about the error code.|
**Example**
```ts
let errnum = -1; // -1 is a system error code.
let result = util.getErrorString(errnum);
console.info("result = " + result);
// Output: result = operation not permitted
```
## util.promiseWrapper(deprecated)
promiseWrapper(original: (err: Object, value: Object) => void): Object
Processes an asynchronous function and returns a promise.
> **NOTE**
>
> This API is unavailable. You are advised to use [util.promisify9+](#utilpromisify9) instead.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| original | Function | Yes| Asynchronous function.|
**Return value**
| Type| Description|
| -------- | -------- |
| Function | Function in the error-first style (that is, **(err, value) =>...** is called as the last parameter) and the promise.|
## util.getHash12+
getHash(object: object): number
Obtains the hash value of an object. If no hash value has been obtained, a random hash value is generated, saved to the **hash** field of the object, and returned. If a hash value has been obtained, the hash value saved in the **hash** field is returned (the same value is returned for the same object).
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| object | object | Yes| Object whose hash value is to be obtained.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Hash value.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Example**
```ts
interface Person {
name: string,
age: number
}
let obj: Person = { name: 'Jack', age: 20 };
let result1 = util.getHash(obj);
console.info('result1 is ' + result1);
let result2 = util.getHash(obj);
console.info('result2 is ' + result2);
// Output: The values of result1 and result2 are the same and are a random hash value.
```
## TextDecoderOptions11+
Describes decoding-related options, which include **fatal** and **ignoreBOM**.
**Atomic service API**: This API can be used in atomic services since API version 11.
**System capability**: SystemCapability.Utils.Lang
| Name | Type| Mandatory| Description |
| --------- | -------- | ---- | ------------------ |
| fatal | boolean | No | Whether to display fatal errors. The default value is **false**.|
| ignoreBOM | boolean | No | Whether to ignore the BOM. The default value is **false**. |
## DecodeToStringOptions12+
Describes the options used during the decoding to a string.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| stream | boolean | No| Whether the incomplete byte sequence at the end of the input needs to be appended to the parameter for the next call of **decodeToString**. The value **true** means that the incomplete byte sequence is stored in the internal buffer until the function is called next time. If the value is false, the byte sequence is directly decoded when the function is called currently. The default value is **false**.|
## DecodeWithStreamOptions11+
Defines whether decoding follows data blocks.
**Atomic service API**: This API can be used in atomic services since API version 11.
**System capability**: SystemCapability.Utils.Lang
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| stream | boolean | No| Whether to allow data blocks in subsequent **decodeWithStream()**. If data is processed in blocks, set this parameter to **true**. If this is the last data block to process or data is not divided into blocks, set this parameter to **false**. The default value is **false**.|
## Aspect11+
Provides APIs that support Aspect Oriented Programming (AOP). These APIs can be used to perform instrumentation or replacement on class methods.
### addBefore11+
static addBefore(targetClass: Object, methodName: string, isStatic: boolean, before: Function): void
Inserts a function before a method of a class object. The inserted function is executed in prior to the original method of the class object.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------- | ---- | -------------------------------------|
| targetClass | Object | Yes | Target class object. |
| methodName | string | Yes | Name of the method. Read-only methods are not supported. |
| isStatic | boolean | Yes | Whether the method is a static method. The value **true** indicates a static method, and **false** indicates an instance method. |
| before | Function | Yes | Function to insert. If the function carries parameters, then the first parameter is the **this** object, which is the target class object (specified by **targetClass**) if **isStatic** is **true** or the instance object of the method if **isStatic** is **false**; other parameters are the parameters carried in the original method. If the function does not carry any parameter, no processing is performed.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Example**
```ts
class MyClass {
msg: string = 'msg000';
foo(arg: string): string {
console.info('foo arg is ' + arg);
return this.msg;
}
static data: string = 'data000';
static bar(arg: string): string {
console.info('bar arg is ' + arg);
return MyClass.data;
}
}
let asp = new MyClass();
let result = asp.foo('123');
// Output: foo arg is 123
console.info('result is ' + result);
// Output: result is msg000
console.info('asp.msg is ' + asp.msg);
// Output: asp.msg is msg000
util.Aspect.addBefore(MyClass, 'foo', false, (instance: MyClass, arg: string) => {
console.info('arg is ' + arg);
instance.msg = 'msg111';
console.info('msg is changed to ' + instance.msg)
});
result = asp.foo('123');
// Output: arg is 123
// Output: msg is changed to msg111
// Output: foo arg is 123
console.info('result is ' + result);
// Output: result is msg111
console.info('asp.msg is ' + asp.msg);
// Output: asp.msg is msg111
let res = MyClass.bar('456');
// Output: bar arg is 456
console.info('res is ' + res);
// Output: res is data000
console.info('MyClass.data is ' + MyClass.data);
// Output: MyClass.data is data000
util.Aspect.addBefore(MyClass, 'bar', true, (target: Object, arg: string) => {
console.info('arg is ' + arg);
let newVal = 'data111';
Reflect.set(target, 'data', newVal);
console.info('data is changed to ' + newVal);
});
res = MyClass.bar('456');
// Output: arg is 456
// Output: data is changed to data111
// Output: bar arg is 456
console.info('res is ' + res);
//Output: res is data111
console.info('MyClass.data is ' + MyClass.data);
// Output: MyClass.data is data111
```
### addAfter11+
static addAfter(targetClass: Object, methodName: string, isStatic: boolean, after: Function): void
Inserts a function after a method of a class object. The final return value is the return value of the function inserted.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------- | ---- | -------------------------------------|
| targetClass | Object | Yes | Target class object. |
| methodName | string | Yes | Name of the method. Read-only methods are not supported. |
| isStatic | boolean | Yes | Whether the method is a static method. The value **true** indicates a static method, and **false** indicates an instance method. |
| after | Function | Yes | Function to insert. If the function carries parameters, then the first parameter is the **this** object, which is the target class object (specified by **targetClass**) if **isStatic** is **true** or the instance object of the method if **isStatic** is **false**; the second parameter is the return value of the original method (**undefined** if the original method does not have a return value); other parameters are the parameters carried by the original method. If the function does not carry any parameter, no processing is performed. |
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Example**
```ts
class MyClass {
msg: string = 'msg000';
foo(arg: string): string {
console.info('foo arg is ' + arg);
return this.msg;
}
}
let asp = new MyClass();
let result = asp.foo('123');
// Output: foo arg is 123
console.info('result is ' + result);
// Output: result is msg000
console.info('asp.msg is ' + asp.msg);
// Output: asp.msg is msg000
util.Aspect.addAfter(MyClass, 'foo', false, (instance: MyClass, ret: string, arg: string): string => {
console.info('arg is ' + arg);
console.info('ret is ' + ret);
instance.msg = 'msg111';
console.info('msg is changed to ' + instance.msg);
return 'msg222';
});
result = asp.foo('123');
// Output: foo arg is 123
// Output: arg is 123
// Output: ret is msg000
// Output: msg is changed to msg111
console.info('result is ' + result);
// Output: result is msg222
console.info('asp.msg is ' + asp.msg);
// Output: asp.msg is msg111
// Examples of addBefore() and addAfter()
class AroundTest {
foo(arg: string) {
console.info('execute foo with arg ' + arg);
}
}
util.Aspect.addBefore(AroundTest, 'foo', false, () => {
console.info('execute before');
});
util.Aspect.addAfter(AroundTest, 'foo', false, () => {
console.info('execute after');
});
(new AroundTest()).foo('hello');
// Output: execute before
// Output: execute foo with arg hello
// Output: execute after
```
### replace11+
static replace(targetClass: Object, methodName: string, isStatic: boolean, instead: Function) : void
Replaces a method of a class object with another function. After the replacement, only the new function logic is executed. The final return value is the return value of the new function.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------- | ---- | -------------------------------------|
| targetClass | Object | Yes | Target class object. |
| methodName | string | Yes | Name of the method. Read-only methods are not supported. |
| isStatic | boolean | Yes | Whether the method is a static method. The value **true** indicates a static method, and **false** indicates an instance method. |
| instead | Function | Yes | Function to be used replacement. If the function carries parameters, then the first parameter is the **this** object, which is the target class object (specified by **targetClass**) if **isStatic** is **true** or the instance object of the method if **isStatic** is **false**; other parameters are the parameters carried in the original method. If the function does not carry any parameter, no processing is performed. |
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Example**
```ts
class MyClass {
msg: string = 'msg000';
foo(arg: string): string {
console.info('foo arg is ' + arg);
return this.msg;
}
}
let asp = new MyClass();
let result = asp.foo('123');
// Output: foo arg is 123
console.info('result is ' + result);
// Output: result is msg000
console.info('asp.msg is ' + asp.msg);
// Output: asp.msg is msg000
util.Aspect.replace(MyClass, 'foo', false, (instance: MyClass, arg: string): string => {
console.info('execute instead')
console.info('arg is ' + arg);
instance.msg = 'msg111';
console.info('msg is changed to ' + instance.msg);
return 'msg222';
});
result = asp.foo('123');
// Output: execute instead
// Output: foo arg is 123
// Output: msg is changed to msg111
console.info('result is ' + result);
// Output: result is msg222
console.info('asp.msg is ' + asp.msg);
//Output: asp.msg is msg111
```
## TextDecoder
Provides APIs to decode byte arrays into strings. It supports multiple formats, including UTF-8, UTF-16LE, UTF-16BE, ISO-8859, and Windows-1251.
### Attributes
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| encoding | string | Yes| No| Encoding format. The following formats are supported: utf-8, ibm866, iso-8859-2, iso-8859-3, iso-8859-4, iso-8859-5, iso-8859-6, iso-8859-7, iso-8859-8, iso-8859-8-i, iso-8859-10, iso-8859-13, iso-8859-14, iso-8859-15, koi8-r, koi8-u, macintosh, windows-874, windows-1250, windows-1251, windows-1252, windows-1253, windows-1254, windows-1255, windows-1256, windows-1257, windows-1258, x-mac-cyrillic, gbk, gb18030, big5, euc-jp, iso-2022-jp, shift_jis, euc-kr, utf-16be, utf-16le, UTF-8, GBK, GB2312, gb2312, GB18030 and iso-8859-1.|
| fatal | boolean | Yes| No| Whether to display fatal errors.|
| ignoreBOM | boolean | Yes| No| Whether to ignore the byte order marker (BOM). The default value is **false**, which indicates that the result contains the BOM.|
### constructor9+
constructor()
A constructor used to create a **TextDecoder** object.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Example**
```ts
let textDecoder = new util.TextDecoder();
let retStr = textDecoder.encoding;
console.info('retStr = ' + retStr);
// Output: retStr = utf-8
```
### create9+
static create(encoding?: string, options?: TextDecoderOptions): TextDecoder
Creates a **TextDecoder** object. It provides the same function as the deprecated argument constructor.
**Atomic service API**: This API can be used in atomic services since API version 11.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------ |
| encoding | string | No | Encoding format. The default format is **'utf-8'**. |
| options | [TextDecoderOptions](#textdecoderoptions11) | No | Decoding-related options, which include **fatal** and **ignoreBOM**.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. |
**Example**
```ts
let textDecoderOptions: util.TextDecoderOptions = {
fatal: false,
ignoreBOM : true
}
let textDecoder = util.TextDecoder.create('utf-8', textDecoderOptions);
let retStr = textDecoder.encoding;
console.info('retStr = ' + retStr);
// Output: retStr = utf-8
```
### decodeToString12+
decodeToString(input: Uint8Array, options?: DecodeToStringOptions): string
Decodes the input content into a string.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| input | Uint8Array | Yes| Uint8Array object to decode.|
| options | [DecodeToStringOptions](#decodetostringoptions12) | No| Decoding-related options. The default value is **undefined**.|
**Return value**
| Type| Description|
| -------- | -------- |
| string | String obtained.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Example**
```ts
let textDecoderOptions: util.TextDecoderOptions = {
fatal: false,
ignoreBOM : true
}
let decodeToStringOptions: util.DecodeToStringOptions = {
stream: false
}
let textDecoder = util.TextDecoder.create('utf-8', textDecoderOptions);
let uint8 = new Uint8Array([0xEF, 0xBB, 0xBF, 0x61, 0x62, 0x63]);
let retStr = textDecoder.decodeToString(uint8, decodeToStringOptions);
console.info("retStr = " + retStr);
// Output: retStr = abc
```
### decodeWithStream(deprecated)
decodeWithStream(input: Uint8Array, options?: DecodeWithStreamOptions): string
Decodes the input content into a string. If **input** is an empty array, **undefined** is returned.
> **NOTE**
>
> This API is supported since API version 9 and deprecated since API version 12. You are advised to use [decodeToString12+](#decodetostring12) instead.
**Atomic service API**: This API can be used in atomic services since API version 11.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| input | Uint8Array | Yes| Uint8Array object to decode.|
| options | [DecodeWithStreamOptions](#decodewithstreamoptions11) | No| Decoding-related options.|
**Return value**
| Type| Description|
| -------- | -------- |
| string | String obtained.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Example**
```ts
let textDecoderOptions: util.TextDecoderOptions = {
fatal: false,
ignoreBOM : true
}
let decodeWithStreamOptions: util.DecodeWithStreamOptions = {
stream: false
}
let textDecoder = util.TextDecoder.create('utf-8', textDecoderOptions);
let uint8 = new Uint8Array(6);
uint8[0] = 0xEF;
uint8[1] = 0xBB;
uint8[2] = 0xBF;
uint8[3] = 0x61;
uint8[4] = 0x62;
uint8[5] = 0x63;
console.info("input num:");
let retStr = textDecoder.decodeWithStream(uint8, decodeWithStreamOptions);
console.info("retStr = " + retStr);
// Output: retStr = abc
```
### constructor(deprecated)
constructor(encoding?: string, options?: { fatal?: boolean; ignoreBOM?: boolean })
A constructor used to create a **TextDecoder** object.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [create9+](#create9) instead.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| encoding | string | No| Encoding format. The default format is **'utf-8'**.|
| options | object | No| Decoding-related options, which include **fatal** and **ignoreBOM**.|
**Table 1** options
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| fatal | boolean | No| Whether to display fatal errors. The default value is **false**.|
| ignoreBOM | boolean | No| Whether to ignore the BOM. The default value is **false**.|
**Example**
```ts
let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true});
```
### decode(deprecated)
decode(input: Uint8Array, options?: { stream?: false }): string
Decodes the input content into a string.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [decodeToString12+](#decodetostring12) instead.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| input | Uint8Array | Yes| Uint8Array object to decode.|
| options | object | No| Decoding-related options.|
**Table 2** options
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| stream | boolean | No| Whether to allow data blocks in subsequent **decode()**. If data is processed in blocks, set this parameter to **true**. If this is the last data block to process or data is not divided into blocks, set this parameter to **false**. The default value is **false**.|
**Return value**
| Type| Description|
| -------- | -------- |
| string | String obtained.|
**Example**
```ts
let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true});
let uint8 = new Uint8Array(6);
uint8[0] = 0xEF;
uint8[1] = 0xBB;
uint8[2] = 0xBF;
uint8[3] = 0x61;
uint8[4] = 0x62;
uint8[5] = 0x63;
console.info("input num:");
let retStr = textDecoder.decode(uint8, {stream: false});
console.info("retStr = " + retStr);
// Output: retStr = abc
```
## EncodeIntoUint8ArrayInfo11+
**System capability**: SystemCapability.Utils.Lang
Defines encoded text.
**Atomic service API**: This API can be used in atomic services since API version 11.
| Name | Type| Readable |Writable | Description |
| --------- | -------- | -------- |-------- |------------------ |
| read | number | Yes| No|Number of characters that have been read.|
| written | number | Yes|No|Number of bytes that have been written. |
## TextEncoder
Provides APIs to encode strings into byte arrays. Multiple encoding formats are supported.
Note that when **TextEncoder** is used for encoding, the number of bytes occupied by a character varies according to the encoding format. Therefore, when using **TextEncoder**, you must explicitly specify the encoding format to be used to obtain the required encoding result.
### Attributes
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| encoding | string | Yes| No| Encoding format. The following formats are supported: utf-8, UTF-8, GBK, GB2312, gb2312, GB18030, gb18030, ibm866, iso-8859-1, iso-8859-2, iso-8859-3, iso-8859-4, iso-8859-5, iso-8859-6, iso-8859-7, iso-8859-8, iso-8859-8-i, iso-8859-10, iso-8859-13, iso-8859-14, iso-8859-15, koi8-r, koi8-u, macintosh, windows-874, windows-1250, windows-1251, windows-1252, windows-1253, windows-1254, windows-1255, windows-1256, windows-1257, windows-1258, gbk, big5, euc-jp, iso-2022-jp, shift_jis, euc-kr, x-mac-cyrillic, utf-16be, and utf-16le. The default value is **'utf-8'**.|
### constructor
constructor()
A constructor used to create a **TextEncoder** object.
**Atomic service API**: This API can be used in atomic services since API version 11.
**System capability**: SystemCapability.Utils.Lang
**Example**
```ts
let textEncoder = new util.TextEncoder();
```
### constructor9+
constructor(encoding?: string)
A constructor used to create a **TextEncoder** object.
**Atomic service API**: This API can be used in atomic services since API version 11.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| ----- | ---- | ---- | ---- |
| encoding | string | No| Encoding format. The default format is **'utf-8'**.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. |
**Example**
```ts
let textEncoder = new util.TextEncoder("utf-8");
```
### create12+
static create(encoding?: string): TextEncoder
Creates a **TextEncoder** object.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| ----- | ---- | ---- | ---- |
| encoding | string | No| Encoding format. The default format is **'utf-8'**.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. |
**Example**
```ts
let textEncoder = util.TextEncoder.create("utf-8");
```
### encodeInto9+
encodeInto(input?: string): Uint8Array
Encodes the input content into a Uint8Array object.
**Atomic service API**: This API can be used in atomic services since API version 11.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ |
| input | string | No | String to encode. The default value is an empty string.|
**Return value**
| Type | Description |
| ---------- | ------------------ |
| Uint8Array | Uint8Array object obtained.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. |
**Example**
```ts
let textEncoder = new util.TextEncoder();
let result = textEncoder.encodeInto("\uD800¥¥");
console.info("result = " + result);
// Output: result = 237,160,128,194,165,194,165
```
### encodeIntoUint8Array9+
encodeIntoUint8Array(input: string, dest: Uint8Array): EncodeIntoUint8ArrayInfo
Encodes the input content into a Uint8Array object.
**Atomic service API**: This API can be used in atomic services since API version 11.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ---------- | ---- | ------------------------------------------------------- |
| input | string | Yes | String to encode. |
| dest | Uint8Array | Yes | Uint8Array object used to store the UTF-8 encoded text.|
**Return value**
| Type | Description |
| ---------- | ------------------ |
| [EncodeIntoUint8ArrayInfo](#encodeintouint8arrayinfo11) | Object obtained. **read** indicates the number of encoded characters, and **write** indicates the number of bytes in the encoded characters.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Example**
```ts
let textEncoder = new util.TextEncoder();
let buffer = new ArrayBuffer(4);
let uint8 = new Uint8Array(buffer);
let result = textEncoder.encodeIntoUint8Array('abcd', uint8);
console.info("uint8 = " + uint8);
// Output: uint8 = 97,98,99,100
```
### encodeInto(deprecated)
encodeInto(input: string, dest: Uint8Array): { read: number; written: number }
Stores the UTF-8 encoded text.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [encodeIntoUint8Array9+](#encodeintouint8array9) instead.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| input | string | Yes| String to encode.|
| dest | Uint8Array | Yes| Uint8Array object used to store the UTF-8 encoded text.|
**Return value**
| Type| Description|
| -------- | -------- |
| Uint8Array | Uint8Array object obtained.|
**Example**
```ts
let textEncoder = new util.TextEncoder();
let buffer = new ArrayBuffer(4);
let uint8 = new Uint8Array(buffer);
let result = textEncoder.encodeInto('abcd', uint8);
console.info("uint8 = " + uint8);
// Output: uint8 = 97,98,99,100
```
### encode(deprecated)
encode(input?: string): Uint8Array
Encodes the input content in to a Uint8Array object.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [encodeInto9+](#encodeinto9) instead.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| input | string | No| String to encode. The default value is an empty string.|
**Return value**
| Type| Description|
| -------- | -------- |
| Uint8Array | Uint8Array object obtained.|
**Example**
```ts
let textEncoder = new util.TextEncoder();
let result = textEncoder.encode("\uD800¥¥");
console.info("result = " + result);
// Output: result = 237,160,128,194,165,194,165
```
## RationalNumber8+
Provides APIs to compare rational numbers and obtain numerators and denominators. For example, the **toString()** API can be used to convert a rational number into a string.
### constructor9+
constructor()
A constructor used to create a **RationalNumber** object.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Example**
```ts
let rationalNumber = new util.RationalNumber();
```
### parseRationalNumber9+
static parseRationalNumber(numerator: number,denominator: number): RationalNumber
Create a **RationalNumber** instance with a given numerator and denominator.
> **NOTE**
>
> The **numerator** and **denominator** parameters must be integers. If a decimal number is passed in, the function is not intercepted, but the error message "parseRationalNumber: The type of Parameter must be integer" is displayed.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | ------ | ---- | ---------------- |
| numerator | number | Yes | Numerator, which is an integer. Value range: -Number.MAX_VALUE <= numerator <= Number.MAX_VALUE.|
| denominator | number | Yes | Denominator, which is an integer. Value range: -Number.MAX_VALUE <= denominator <= Number.MAX_VALUE.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Example**
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
```
### createRationalFromString8+
static createRationalFromString(rationalString: string): RationalNumber
Creates a **RationalNumber** object based on the given string.
> **NOTE**
>
> The **rationalString** parameter must be a string. If a decimal string is passed in, the function is not intercepted, but the error message "createRationalFromString: The type of Parameter must be integer string" is displayed.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| rationalString | string | Yes| String used to create the **RationalNumber** object.|
**Return value**
| Type| Description|
| -------- | -------- |
| Object | **RationalNumber** object obtained.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | The type of rationalString must be string. |
**Example**
```ts
let rational = util.RationalNumber.createRationalFromString("3/4");
```
### compare9+
compare(another: RationalNumber): number
Compares this **RationalNumber** object with another **RationalNumber** object.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | -------------- | ---- | ------------------ |
| another | [RationalNumber](#rationalnumber8) | Yes | Object used to compare with this **RationalNumber** object.|
**Return value**
| Type | Description |
| ------ | ------------------------------------------------------------ |
| number | Returns **0** if the two objects are equal; returns **1** if the given object is less than this object; return **-1** if the given object is greater than this object.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Example**
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let rational = util.RationalNumber.createRationalFromString("3/4");
let result = rationalNumber.compare(rational);
console.info("result = " + result);
// Output: result = -1
```
### valueOf8+
valueOf(): number
Obtains the value of this **RationalNumber** object as an integer or a floating-point number.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
| -------- | -------- |
| number | An integer or a floating-point number.|
**Example**
```ts
let rationalNumber = new util.RationalNumber(1,2);
let result = rationalNumber.valueOf();
console.info("result = " + result);
// Output: result = 0.5
```
You are advised to use the following code snippet for API version 9 and later versions:
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let result = rationalNumber.valueOf();
console.info("result = " + result);
// Output: result = 0.5
```
### equals8+
equals(obj: Object): boolean
Checks whether this **RationalNumber** object equals the given object.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| obj | Object | Yes| Object used to compare with this **RationalNumber** object.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the two objects are equal; returns **false** otherwise.|
**Example**
```ts
let rationalNumber = new util.RationalNumber(1,2);
let rational = util.RationalNumber.createRationalFromString("3/4");
let result = rationalNumber.equals(rational);
console.info("result = " + result);
// Output: result = false
```
You are advised to use the following code snippet for API version 9 and later versions:
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let rational = util.RationalNumber.createRationalFromString("3/4");
let result = rationalNumber.equals(rational);
console.info("result = " + result);
// Output: result = false
```
### getCommonFactor9+
static getCommonFactor(number1: number,number2: number): number
Obtains the greatest common divisor of two specified integers.
> **NOTE**
>
> The **number1** and **number2** parameters must be integers. If a decimal number is passed in, the function is not intercepted, but the error message "getCommonFactor: The type of Parameter must be integer" is displayed.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | ---------- |
| number1 | number | Yes | The first integer used to get the greatest common divisor. Value range: -Number.MAX_VALUE <= number1 <= Number.MAX_VALUE.|
| number2 | number | Yes | The second integer used to get the greatest common divisor. Value range: -Number.MAX_VALUE <= number2 <= Number.MAX_VALUE.|
**Return value**
| Type | Description |
| ------ | ------------------------------ |
| number | Greatest common divisor obtained.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Example**
```ts
let result = util.RationalNumber.getCommonFactor(4,6);
console.info("result = " + result);
// Output: result = 2
```
### getNumerator8+
getNumerator(): number
Obtains the numerator of this **RationalNumber** object.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
| -------- | -------- |
| number | Numerator of this **RationalNumber** object.|
**Example**
```ts
let rationalNumber = new util.RationalNumber(1,2);
let result = rationalNumber.getNumerator();
console.info("result = " + result);
// Output: result = 1
```
You are advised to use the following code snippet for API version 9 and later versions:
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let result = rationalNumber.getNumerator();
console.info("result = " + result);
// Output: result = 1
```
### getDenominator8+
getDenominator(): number
Obtains the denominator of this **RationalNumber** object.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
| -------- | -------- |
| number | Denominator of this **RationalNumber** object.|
**Example**
```ts
let rationalNumber = new util.RationalNumber(1,2);
let result = rationalNumber.getDenominator();
console.info("result = " + result);
// Output: result = 2
```
You are advised to use the following code snippet for API version 9 and later versions:
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2)
let result = rationalNumber.getDenominator();
console.info("result = " + result);
// Output: result = 2
```
### isZero8+
isZero():boolean
Checks whether this **RationalNumber** object is **0**.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the value of this **RationalNumber** object is **0**; returns **false** otherwise.|
**Example**
```ts
let rationalNumber = new util.RationalNumber(1,2);
let result = rationalNumber.isZero();
console.info("result = " + result);
// Output: result = false
```
You are advised to use the following code snippet for API version 9 and later versions:
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let result = rationalNumber.isZero();
console.info("result = " + result);
// Output: result = false
```
### isNaN8+
isNaN(): boolean
Checks whether this **RationalNumber** object is a Not a Number (NaN).
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if this **RationalNumber** object is a NaN (the denominator and numerator are both **0**); returns **false** otherwise.|
**Example**
```ts
let rationalNumber = new util.RationalNumber(1,2);
let result = rationalNumber.isNaN();
console.info("result = " + result);
// Output: result = false
```
You are advised to use the following code snippet for API version 9 and later versions:
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let result = rationalNumber.isNaN();
console.info("result = " + result);
// Output: result = false
```
### isFinite8+
isFinite():boolean
Checks whether this **RationalNumber** object represents a finite value.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if this **RationalNumber** object represents a finite value (the denominator is not **0**); returns **false** otherwise.|
**Example**
```ts
let rationalNumber = new util.RationalNumber(1,2);
let result = rationalNumber.isFinite();
console.info("result = " + result);
// Output: result = true
```
You are advised to use the following code snippet for API version 9 and later versions:
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let result = rationalNumber.isFinite();
console.info("result = " + result);
// Output: result = true
```
### toString8+
toString(): string
Obtains the string representation of this **RationalNumber** object.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
| -------- | -------- |
| string | Returns a string in Numerator/Denominator format in normal cases, for example, 3/5; returns **0/1** if the numerator of this object is **0**; returns **Infinity** if the denominator is **0**; returns **NaN** if the numerator and denominator are both **0**.|
**Example**
```ts
let rationalNumber = new util.RationalNumber(1,2);
let result = rationalNumber.toString();
console.info("result = " + result);
// Output: result = 1/2
```
You are advised to use the following code snippet for API version 9 and later versions:
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let result = rationalNumber.toString();
console.info("result = " + result);
// Output: result = 1/2
```
### constructor(deprecated)
constructor(numerator: number,denominator: number)
A constructor used to create a **RationalNumber** object.
> **NOTE**
>
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [parseRationalNumber9+](#parserationalnumber9) instead.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| numerator | number | Yes| Numerator, which is an integer.|
| denominator | number | Yes| Denominator, which is an integer.|
**Example**
```ts
let rationalNumber = new util.RationalNumber(1,2);
```
### compareTo(deprecated)
compareTo(another: RationalNumber): number
Compares this **RationalNumber** object with a given object.
> **NOTE**
>
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [compare9+](#compare9) instead.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| another | RationalNumber | Yes| Object used to compare with this **RationalNumber** object.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Returns **0** if the two objects are equal; returns **1** if the given object is less than this object; return **-1** if the given object is greater than this object.|
**Example**
```ts
let rationalNumber = new util.RationalNumber(1,2);
let rational = util.RationalNumber.createRationalFromString("3/4");
let result = rationalNumber.compareTo(rational);
console.info("result = " + result);
// Output: result = -1
```
### getCommonDivisor(deprecated)
static getCommonDivisor(number1: number,number2: number): number
Obtains the greatest common divisor of two specified integers.
> **NOTE**
>
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCommonFactor9+](#getcommonfactor9) instead.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| number1 | number | Yes| The first integer used to get the greatest common divisor.|
| number2 | number | Yes| The second integer used to get the greatest common divisor.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Greatest common divisor obtained.|
## LRUCache9+
Provides APIs to discard the least recently used data to make rooms for new elements when the cache is full. This class uses the Least Recently Used (LRU) algorithm, which believes that the recently used data may be accessed again in the near future and the least accessed data is the least valuable data and should be removed from the cache.
### Attributes
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
| Name | Type | Readable| Writable| Description |
| ------ | ------ | ---- | ---- | ---------------------- |
| length | number | Yes | No | Total number of values in this cache.|
**Example**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
pro.put(1, 8);
let result = pro.length;
console.info('result = ' + result);
// Output: result = 2
```
### constructor9+
constructor(capacity?: number)
A constructor used to create a **LRUCache** instance. The default capacity of the cache is 64.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ---------------------------- |
| capacity | number | No | Capacity of the cache to create. The default value is **64**, and the maximum value is **2147483647**.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1.Incorrect parameter types. |
**Example**
```ts
let pro = new util.LRUCache();
```
### updateCapacity9+
updateCapacity(newCapacity: number): void
Changes the cache capacity. If the new capacity is less than or equal to **0**, an exception will be thrown. If the total number of values in the cache is greater than the specified capacity, the deletion operation is performed.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | ------ | ---- | ---------------------------- |
| newCapacity | number | Yes | New capacity of the cache. The maximum value is **2147483647**.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. |
**Example**
```ts
let pro = new util.LRUCache();
pro.updateCapacity(100);
```
### toString9+
toString(): string
Obtains the string representation of this cache.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type | Description |
| ------ | -------------------------- |
| string | String representation of this cache.|
**Example**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
pro.get(2);
pro.get(3);
console.info(pro.toString());
// Output: LRUCache[ maxSize = 64, hits = 1, misses = 1, hitRate = 50% ]
// maxSize: maximum size of the cache. hits: number of matched queries. misses: number of mismatched queries. hitRate: matching rate.
```
### getCapacity9+
getCapacity(): number
Obtains the capacity of this cache.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type | Description |
| ------ | ---------------------- |
| number | Capacity of the cache.|
**Example**
```ts
let pro = new util.LRUCache();
let result = pro.getCapacity();
console.info('result = ' + result);
// Output: result = 64
```
### clear9+
clear(): void
Clears key-value pairs from this cache.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Example**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
let result = pro.length;
pro.clear();
let res = pro.length;
console.info('result = ' + result);
console.info('res = ' + res);
// Output: result = 1
// Output: res = 0
```
### getCreateCount9+
getCreateCount(): number
Obtains the number of times that an object is created.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type | Description |
| ------ | -------------------|
| number | Number of times that objects are created.|
**Example**
```ts
// Create the ChildLRUCache class that inherits LRUCache, and override createDefault() to return a non-undefined value.
class ChildLRUCache extends util.LRUCache {
constructor() {
super();
}
createDefault(key: number): number {
return key;
}
}
let lru = new ChildLRUCache();
lru.put(2, 10);
lru.get(3);
lru.get(5);
let res = lru.getCreateCount();
console.info('res = ' + res);
// Output: res = 2
```
### getMissCount9+
getMissCount(): number
Obtains the number of times that the queried values are mismatched.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type | Description |
| ------ | ------------------------ |
| number | Number of times that the queried values are mismatched.|
**Example**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
pro.get(2);
let result = pro.getMissCount();
console.info('result = ' + result);
// Output: result = 0
```
### getRemovalCount9+
getRemovalCount(): number
Obtains the number of times that key-value pairs in the cache are recycled.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type | Description |
| ------ | -------------------------- |
| number | Number of times that key-value pairs in the cache are recycled.|
**Example**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
pro.updateCapacity(2);
pro.put(50, 22);
let result = pro.getRemovalCount();
console.info('result = ' + result);
// Output: result = 0
```
### getMatchCount9+
getMatchCount(): number
Obtains the number of times that the queried values are matched.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type | Description |
| ------ | -------------------------- |
| number | Number of times that the queried values are matched.|
**Example**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
pro.get(2);
let result = pro.getMatchCount();
console.info('result = ' + result);
// Output: result = 1
```
### getPutCount9+
getPutCount(): number
Obtains the number of additions to this cache.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type | Description |
| ------ | ---------------------------- |
| number | Number of additions to the cache.|
**Example**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
let result = pro.getPutCount();
console.info('result = ' + result);
// Output: result = 1
```
### isEmpty9+
isEmpty(): boolean
Checks whether this cache is empty.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the cache does not contain any value.|
**Example**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
let result = pro.isEmpty();
console.info('result = ' + result);
// Output: result = false
```
### get9+
get(key: K): V | undefined
Obtains the value of a key. If the key is not in the cache, [createDefault9+](#createdefault9) is called to create the key. If the value specified in **createDefault** is not **undefined**, [afterRemoval9+](#afterremoval9) is called to return the value specified in **createDefault**.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description |
| ------ | ---- | ---- | ------------ |
| key | K | Yes | Key based on which the value is queried.|
**Return value**
| Type | Description |
| ------------------------ | ------------------------------------------------------------ |
| V \| undefined | Returns the value of the key if a match is found in the cache; returns the value specified in **createDefault** otherwise.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Example**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
let result = pro.get(2);
console.info('result = ' + result);
// Output: result = 10
```
### put9+
put(key: K,value: V): V
Adds a key-value pair to this cache and returns the value associated with the key. If the total number of values in the cache is greater than the specified capacity, the deletion operation is performed.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description |
| ------ | ---- | ---- | -------------------------- |
| key | K | Yes | Key of the key-value pair to add. |
| value | V | Yes | Value of the key-value pair to add.|
**Return value**
| Type| Description |
| ---- | ------------------------------------------------------------ |
| V | Value of the key-value pair added. If the key or value is empty, an exception is thrown.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Example**
```ts
let pro = new util.LRUCache();
let result = pro.put(2, 10);
console.info('result = ' + result);
// Output: result = 10
```
### values9+
values(): V[]
Obtains all values in this cache, listed from the most to the least recently accessed.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type | Description |
| --------- | ------------------------------------------------------------ |
| V [] | All values in the cache, listed from the most to the least recently accessed.|
**Example**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
pro.put(2, "anhu");
pro.put("afaf", "grfb");
let result = pro.values();
console.info('result = ' + result);
// Output: result = anhu,grfb
```
### keys9+
keys(): K[]
Obtains all keys in this cache, listed from the most to the least recently accessed.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type | Description |
| --------- | ------------------------------------------------------------ |
| K [] | All keys in the cache, listed from the most to the least recently accessed.|
**Example**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
pro.put(3, 1);
let result = pro.keys();
console.info('result = ' + result);
// Output: result = 2,3
```
### remove9+
remove(key: K): V | undefined
Removes a key and its associated value from this cache and returns the value associated with the key. If the key does not exist, **undefined** is returned.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description |
| ------ | ---- | ---- | -------------- |
| key | K | Yes | Key to remove.|
**Return value**
| Type | Description |
| ------------------------ | ------------------------------------------------------------ |
| V \| undefined | Returns an **Optional** object containing the removed key-value pair if the key exists in the cache; returns **undefined** if the key does not exist; throws an error if **null** is passed in for **key**.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Example**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
let result = pro.remove(20);
console.info('result = ' + result);
// Output: result = undefined
```
### afterRemoval9+
afterRemoval(isEvict: boolean,key: K,value: V,newValue: V): void
Performs subsequent operations after a value is removed. The subsequent operations must be implemented by developers. This API is called during deletion operations, such as [get9+](#get9), [put9+](#put9), [remove9+](#remove9), [clear9+](#clear9), and [updateCapacity9+](#updatecapacity9).
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------- | ---- | ------------------------------------------------------------ |
| isEvict | boolean | Yes | Whether the capacity is insufficient. If the value is **true**, this API is called due to insufficient capacity. |
| key | K | Yes | Key removed. |
| value | V | Yes | Value removed. |
| newValue | V | Yes | New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Example**
```ts
class ChildLRUCache extends util.LRUCache {
constructor(capacity?: number) {
super(capacity);
}
afterRemoval(isEvict: boolean, key: K, value: V, newValue: V): void {
if (isEvict === true) {
console.info('key = ' + key);
// Output: key = 1
console.info('value = ' + value);
// Output: value = 1
console.info('newValue = ' + newValue);
// Output: newValue = null
}
}
}
let lru = new ChildLRUCache(2);
lru.put(1, 1);
lru.put(2, 2);
lru.put(3, 3);
```
### contains9+
contains(key: K): boolean
Checks whether this cache contains the specified key.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------- |
| key | K | Yes | Key to check.|
**Return value**
| Type | Description |
| ------- | ------------------------------------------ |
| boolean | Returns **true** if the cache contains the specified key; returns **false** otherwise.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Example**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
let result = pro.contains(2);
console.info('result = ' + result);
// Output: result = true
```
### createDefault9+
createDefault(key: K): V
Performs subsequent operations if no key is matched in the cache and returns the value (**undefined** by default) associated with the key.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description |
| ------ | ---- | ---- | -------------- |
| key | K | Yes | Key.|
**Return value**
| Type| Description |
| ---- | ------------------ |
| V | Value of the key.|
**Error codes**
For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
| ID| Error Message|
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**Example**
```ts
let pro = new util.LRUCache();
let result = pro.createDefault(50);
console.info('result = ' + result);
// Output: result = undefined
```
### entries9+
entries(): IterableIterator<[K,V]>
Obtains a new iterator object that contains all key-value pairs in this object.
**Atomic service API**: This API can be used in atomic services since API version 12.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type | Description |
| ----------- | -------------------- |
| [K, V] | Iterable array.|
**Example**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
pro.put(3, 15);
let pair:Iterable