目录

@ohos.util (util)

This module mainly provides common utility functions, implementing string encoding and decoding (TextEncoder, TextDecoder), rational number operations (RationalNumber8+), buffer management (LRUCache9+), range checking (ScopeHelper9+), Base64 encoding and decoding (Base64Helper9+), built-in object type checking (types8+), method instrumentation and replacement (Aspect11+), virtual machine debugging capabilities (ArkTSVM23+), binary stream decoding (StringDecoder12+), and heap memory threshold configuration (HeapMemoryThreshold24+). In addition, it provides utility functions such as obtaining the hash value of an object (util.getHash12+) and obtaining the main thread stack trace information (util.getMainThreadStackTrace20+).

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

import { util } from '@kit.ArkTS';

util.format9+

format(format: string, ...args: Object[]): string

Uses a styled string to output the input content in a specific format, suitable for scenarios such as log output and user interface text formatting.

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 the format parameter. When this parameter is missing, the formatted string itself is returned directly.

Return value

Type Description
string Formatted string.

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 Serializes a JavaScript object into a JSON string for formatted output.
%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 CSS style placeholder, valid only in the browser environment, used to specify the style of formatted output; other environments ignore this placeholder.
%% Placeholder for escaping the percent sign.

Example

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<string,number | string> = { "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 the detailed information corresponding to a system error code. It is suitable for converting a numeric error code into a readable description when a system call fails, helping developers quickly locate and troubleshoot system-level errors. It is commonly used for error log recording and error prompt display.

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 corresponding to the error code, including readable error description text to help developers locate the problem.

Example

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.

This API requires that the original parameter must be of the async function type. If the passed parameter is not an async function, no interception is performed, but an error message is output: "callbackWrapper: The type of Parameter must be AsyncFunction".

This API is used to convert an async function that returns a Promise into an error-first callback style function. The function returned by calling this API receives a callback function as the second input parameter. When this method is called, the original function is executed first. When the Promise of original returns resolve, the first parameter of the input callback function is null, and the second parameter is the resolved value. When the Promise of original returns reject, the first parameter of the input callback function is the error object, and the second parameter is null.

Since the return type of this method is declared as (err: Object, value: Object) => void, the TypeScript compiler performs parameter count validation according to this declaration. Therefore, when original is a function with no input parameters, the first input parameter of the function returned by this API must be an invalid placeholder parameter. When original is a function with multiple input parameters, the function returned by this API currently supports only one input parameter. You can use a container such as an array to pass multiple input parameters (refer to the sample code below).

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, which requires the function to return a Promise object. The resolve value of this asynchronous function is passed as the second parameter of the callback, and the reject reason is passed as the first parameter of the callback.

Return value

Type Description
(err: Object, value: Object)=>void 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.

Example

// original is an example of an input parameter
async function fn(input: string) {
  return input;
}
let cb = util.callbackWrapper(fn);
cb('hello world', (err : Object, ret : string) => {
  if (err) throw new Error();
  console.info(ret);
});
// Output: hello world
// Example of passing multiple arguments to original
async function fn(args: Array<string | number | Function>) {
  console.info('args[0]: ' + args[0]); // args[0]: hello world
  console.info('args[1]: ' + args[1]); // args[1]: 8
  return args[0];
}
let cb = util.callbackWrapper(fn);
let args: Array<string | number | Function> = ['hello world', 8]
cb(args, (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

Receives a function that adopts the "error-first" callback pattern, that is, a function with (err, value) => callback as the last parameter, and returns its Promise function. It is suitable for converting legacy callback-style asynchronous APIs into Promise style, so that they can be called using the async/await syntax, thereby simplifying asynchronous code writing.

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 (err: Object, value: Object) => void 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 Returns a Promise function that resolves to the callback's value when the original callback function executes successfully, and rejects with an error object when the original callback function fails.

Example

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 to use cached UUIDs. true means cached UUIDs are used to improve performance (up to 128 UUIDs are cached; after the cache is exhausted, UUIDs are regenerated to ensure randomness). false means cached UUIDs are not used. The default value is true.

Return value

Type Description
string A string representing the UUID generated.

Example

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 cryptographically secure random number generator to generate a random RFC 4122 version 4 UUID of the Uint8Array type. To improve performance, this API uses a cache by default, that is, the input parameter is true, and up to 128 random UUIDs can be cached. When the 128 UUIDs in the cache are exhausted, they are regenerated to ensure the randomness of the UUIDs. To disable the cache, set the input parameter 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 to use a cached UUID. The value true means to use a cached UUID, and false means the opposite. The default value is true.

Return value

Type Description
Uint8Array A Uint8Array value representing the UUID generated.

Example

let uuid = util.generateRandomBinaryUUID(true);
console.info(JSON.stringify(uuid));
// Output a random UUID.

util.parseUUID9+

parseUUID(uuid: string): Uint8Array

Converts the string-type UUID generated by generateRandomUUID into the UUID generated by util.generateRandomBinaryUUID, conforming to the RFC 4122 version specification.

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 UUID string, which must comply with the RFC 4122 version specification.

Return value

Type Description
Uint8Array Returns a Uint8Array representing this UUID. If parsing fails, an exception is thrown with error code 10200002.

Error codes

For details about the following error codes, see Utils Error Codes.

ID Error Message
10200002 Invalid uuid string.

Example

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.

This API is supported since API version 7 and deprecated since API version 9. You are advised to use util.format9+ 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 formatted according to the specified format, containing parameter values processed based on the format specifiers.

Example

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.

This API is supported since API version 7 and deprecated since API version 9. You are advised to use util.errnoToString9+ 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

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

Receives a function that uses the error-first callback mode, that is, uses (err, value) => callback as the last parameter, and uses a promise to return the result.

This API is supported since API version 7 and deprecated since API version 9. You are advised to use util.promisify9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
original (err: Object, value: Object) => void Yes A function that adopts the error-first callback pattern. The first parameter err is the rejection reason, and the second parameter value is the resolved value.

Return value

Type Description
Object Promise in the error-first style (that is, (err, value) => ... is called as the last parameter).

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 Non-primitive type object for which the hash value needs to be obtained.

Return value

Type Description
number Hash value of the object. A random value is returned when it is obtained for the first time, and the returned value remains unchanged for multiple acquisitions of the same object.

Example

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.

util.getMainThreadStackTrace20+

getMainThreadStackTrace(): string

Obtains the stack trace information of the main thread. A maximum of 64 call frames can be returned.

This API may affect the performance of the main thread. You are advised to use this API only when necessary, such as in log recording, error analysis, or debugging scenarios.

Atomic service API: This API can be used in atomic services since API version 20.

System capability: SystemCapability.Utils.Lang

Return value

Type Description
string Stack trace information of the main thread. If the main thread is not executing JavaScript code, an empty string is returned.

Example

let stack = util.getMainThreadStackTrace();
console.info(stack);
// Obtain the stack trace information of the main thread.

MultithreadingDetectionOptions

MultithreadingDetectionOptions is an interface class used to configure the behavior parameters of the ArkTSVM.setMultithreadingDetectionEnabled function.

Since: 26.0.0

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Utils.Lang

Attributes:

Name Type Read-Only Optional Description
abort boolean No Yes Controls whether to crash when a multithreading issue is detected. Passing true means crashing immediately when a multithreading issue is detected, which is suitable for scenarios where multithreading issues need to be exposed quickly during development and debugging. Passing false means not crashing but only reporting fault information, which is suitable for scenarios where service availability needs to be maintained in production environments. The default value is true.
frequency number No Yes Granularity of multithreading safety detection, indicating how many function calls occur before a multithreading safety detection is performed. A larger value means a lower sampling frequency and less impact on application performance, but some multithreading safety usage issue scenarios may be missed. The range is [100, 2147483647], and the default value is 100.
interval number No Yes Fault reporting time interval of multithreading safety detection. It takes effect only when not crashing. The range is [0, 1440], the unit is minutes, and the default value is 5 minutes. (It is not recommended to set it below 5 minutes, as it has a severe performance impact.)

ArkTSVM23+

ArkTSVM is a class that provides developers with diagnostic and maintenance capabilities for the virtual machine, including multithreading safety detection, heap memory information acquisition, memory leak prevention, global reference tracking, and heap memory warning.

[h2]setMultithreadingDetectionEnabled23+

static setMultithreadingDetectionEnabled(enabled: boolean, options?: MultithreadingDetectionOptions): void

If enabled is true, it is enabled; if false, it is disabled. When multithreading safety detection is enabled, the C/C++ crash dump file (cppcrash file) of multithreading issues will contain multithreading information (such as thread ID and lock status). When multithreading safety detection is disabled, the C/C++ crash dump file (cppcrash file) will not contain multithreading information.

options is used to configure the behavior parameters of multithreading safety detection.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
enabled boolean Yes Controls whether to enable or disable the multithreading safety detection switch. true means enabled, and false means disabled.
options MultithreadingDetectionOptions No Parameter configuration for multithreading safety detection. When this parameter is not set, the corresponding properties take the default values of MultithreadingDetectionOptions. Initial Version: 26.0.0

Example

import { util } from '@kit.ArkTS';

// Enable the thread safety detection switch.
util.ArkTSVM.setMultithreadingDetectionEnabled(true);
// Disable the thread safety detection switch.
util.ArkTSVM.setMultithreadingDetectionEnabled(false);
// Set the crash behavior.
util.ArkTSVM.setMultithreadingDetectionEnabled(true, { abort: false });
// Adjust the detection granularity.
util.ArkTSVM.setMultithreadingDetectionEnabled(true, { frequency: 200 });
// Adjust the reporting interval.
util.ArkTSVM.setMultithreadingDetectionEnabled(true, { interval: 10 });
// Set the three parameters at the same time.
util.ArkTSVM.setMultithreadingDetectionEnabled(true, {
  abort: false,
  frequency: 500,
  interval: 60
});

[h2]getAllVMHeapMemoryInfo24+

static getAllVMHeapMemoryInfo(): Promise<HeapMemoryInfo[]>

Obtains the heap memory information of all VM threads, including thread ID, thread name, heap type, and heap object size. This is applicable to scenarios such as memory leak troubleshooting and memory usage analysis. A Promise is used for asynchronous callback.

The heap obtained through this API contains two types: the local heap, which is the VM heap exclusive to each ArkTS thread in the application process; and the shared heap, which is the VM heap shared by all ArkTS threads in the application process.

When this API is executed, all VM threads are paused to obtain memory information. Because it needs to wait for all VM threads to pause, calling this API may take a long time in high-load scenarios.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Utils.Lang

Return value

Type Description
Promise<HeapMemoryInfo[]> Promise object that resolves to an array of HeapMemoryInfo objects, each containing the thread ID, thread name, heap type, and heap object size. This method can obtain the memory information of both the local heap and the shared heap.

Example

import { util } from '@kit.ArkTS';

util.ArkTSVM.getAllVMHeapMemoryInfo().then(
  result => {
    result.forEach(info => {
      console.info(info.threadId?.toString());
      console.info(info.threadName);
      console.info(info.heapType);
      console.info(info.heapObjectSize.toString());
    })
  }
);

[h2]enableLocalHandleDetection24+

static enableLocalHandleDetection(): void

When the asynchronous event loop mechanisms of EventHandler and libuv execute asynchronous tasks, the tasks are no longer executed within the management scope of the current handle scope, and the created napi_value is not automatically reclaimed. If developers do not add a scope in the task callback, a memory leak will occur. After this API is called, it ensures that tasks of these two mechanisms are executed within the scope, thereby avoiding memory leaks.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Utils.Lang

Example

// napi_init.cpp C++ example code
#include "napi/native_api.h"
#include "uv.h"

static napi_value CreateObject(napi_env env, napi_callback_info info)
{
    uv_loop_s* loop = nullptr;
    napi_status status = napi_get_uv_event_loop(env, &loop);
    if (status != napi_ok) {
        napi_throw_error(env, nullptr, "napi_get_uv_event_loop fail");
        return nullptr;
    }
    uv_work_t* work = new uv_work_t;
    work->data = env;
    int ret = uv_queue_work(loop, work,
        [](uv_work_t* work){},
        [](uv_work_t* work, int status){
            napi_env env = static_cast<napi_env>(work->data);
            for (int i = 0; i < 1000; i++) {
                napi_value obj = nullptr;
                // Not adding a scope in the asynchronous mechanism provided by libuv causes a memory leak
                napi_create_object(env, &obj);
            }
            delete work;
        }
    );
    if (ret != 0) {
        delete work;
    }
    return nullptr;
}

Add the following dynamic link library to CMakeLists.txt:

libuv.so
// index.d.ts interface declaration
export const createObject: () => void;
// Index.ets ArkTS example code
import { hilog } from '@kit.PerformanceAnalysisKit';
import testNapi from 'libentry.so';
import { util } from '@kit.ArkTS';

try {
  // If the LocalHandle memory leak fallback mechanism is not enabled, memory overflow may occur. After this mechanism is enabled, the system automatically reclaims the napi_value created in EventHandler and libuv asynchronous tasks
  util.ArkTSVM.enableLocalHandleDetection();
  testNapi.createObject();
  hilog.info(0x0000, 'testTag', 'Test Node-API createObject success');
} catch (error) {
  hilog.error(0x0000, 'testTag', 'Test Node-API createObject failed error: %{public}s', error.message);
}

Possible issues:

If an object that previously caused a memory leak continues to be used, after the enableLocalHandleDetection API is called, the system reclaims the memory-leaked object. Continuing to use this object will turn the memory leak problem into a stability problem.

napi_value global_js_object;
napi_value dangerous_function(napi_env env, napi_callback_info info) {
    napi_value js_obj;
    napi_create_object(env, &js_obj);
    global_js_object = js_obj; // Stored directly in a global variable, and released after the LocalHandle memory leak fallback mechanism is enabled
    return nullptr;
}

[h2]setTrackGlobalRef

static setTrackGlobalRef(enable: boolean): void

Enables or disables tracking of the association between napi_ref and global objects. After tracking is enabled, the global object nodes in the heap snapshot will contain the address information of napi_ref. After tracking is disabled (enable is false), tracking stops, and the association between napi_ref and global objects is no longer displayed in the heap snapshot.

After tracking is enabled, the virtual machine additionally records the association between napi_ref and global objects, which may incur certain memory and performance overhead. When debugging is not required, it is recommended to call util.ArkTSVM.setTrackGlobalRef(false) to disable tracking.

The switch of this API is process-level, and all threads in the process share the same switch state. After this API is called in any thread to set the switch, it takes effect for all threads in the process.

For details about napi_ref, see the napi_ref usage guide.

Since: 26.0.0

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
enable boolean Yes Whether to enable tracking. true indicates enabling tracking (which may incur certain memory and performance overhead), and false indicates disabling tracking. It is recommended to set this parameter to false when debugging is not required to avoid performance overhead.

Example

// napi_init.cpp C++ example code
#include "napi/native_api.h"

static napi_value CreateGlobalRef(napi_env env, napi_callback_info info)
{
    napi_value js_obj = nullptr;
    napi_create_object(env, &js_obj);
    // Create an napi_ref and associate it with the global handle
    napi_ref ref = nullptr;
    napi_create_reference(env, js_obj, 1, &ref);
    // After setTrackGlobalRef is enabled, the heap snapshot contains the native reference address information corresponding to this ref
    return nullptr;
}
// Index.d.ts interface declaration
export const createGlobalRef: () => void;
// Index.ets ArkTS example code
import { hilog } from '@kit.PerformanceAnalysisKit';
import testNapi from 'libentry.so';
import { util } from '@kit.ArkTS';

try {
  // Enable tracking of the association between napi_ref and the global handle. After it is enabled, the heap snapshot contains the native reference address information
  util.ArkTSVM.setTrackGlobalRef(true);
  testNapi.createGlobalRef();
  hilog.info(0x0000, 'testTag', 'Test Node-API createGlobalRef success');
} catch (error) {
  hilog.error(0x0000, 'testTag', 'Test Node-API createGlobalRef failed error: %{public}s', error.message);
}

[h2]onVMHeapMemoryPressure24+

static onVMHeapMemoryPressure(callback: Callback<string>, heapMemoryThreshold: HeapMemoryThreshold): boolean

Registers a callback function. After the VM main thread completes garbage collection, if the heap memory exceeds the warning threshold, the callback is triggered. This is applicable to proactive memory management (triggering resource cleanup when memory pressure is high), OOM prevention, and other scenarios.

The VM determines whether the memory warning threshold is reached by counting the size of surviving objects. Due to memory fragmentation and floating garbage in the VM heap, it cannot be guaranteed that the callback will definitely be triggered before OOM.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
callback Callback<string> Yes Callback function triggered when the memory reaches the warning threshold after garbage collection. The string parameter indicates the type of the memory pressure event. Currently, there are three event types: "LocalHeapMemPressure", "SharedHeapMemPressure", and "ProcessHeapMemPressure".
heapMemoryThreshold HeapMemoryThreshold Yes Heap memory warning threshold configuration, set as a percentage in the range [70, 95]. Values outside this range are automatically clamped to the valid interval.

Return value

Type Description
boolean Returns true if registration succeeds, and false if it is not called on the main thread or the callback is already registered.

Example

import { util } from '@kit.ArkTS';

let callback = (event: string) => {
  console.info('Memory pressure event: ' + event);
};

let threshold: util.HeapMemoryThreshold = {
  localHeapThreshold: 75,
  sharedHeapThreshold: 80,
  processHeapThreshold: 85
};

let result : boolean = util.ArkTSVM.onVMHeapMemoryPressure(callback, threshold);
console.info('Registration result: ' + result);

[h2]offVMHeapMemoryPressure24+

static offVMHeapMemoryPressure(): void

Cancels the registered memory pressure callback function. This API must be called in the main thread.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Utils.Lang

Example

import { util } from '@kit.ArkTS';

util.ArkTSVM.offVMHeapMemoryPressure();

HeapMemoryThreshold24+

Heap memory warning threshold configuration, used to specify the heap memory warning threshold that triggers the callback.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Utils.Lang

Name Type Read-Only Optional Description
localHeapThreshold number No Yes Local heap memory warning threshold configuration, set as a percentage in the range [70, 95]. Values out of range are automatically clamped to the valid range. If not set, the local heap is not monitored.
sharedHeapThreshold number No Yes Shared heap memory warning threshold configuration, set as a percentage in the range [70, 95]. Values out of range are automatically clamped to the valid range. If not set, the shared heap is not monitored.
processHeapThreshold number No Yes Process total VM heap memory warning threshold configuration, set as a percentage in the range [70, 95]. Values out of range are automatically clamped to the valid range. If not set, the process total VM heap size is not monitored.

HeapMemoryInfo24+

Describes the memory information of the local heap or shared heap, including detailed data such as the thread identifier and heap memory size.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Utils.Lang

Name Type Read-Only Optional Description
threadId number No Yes Thread ID. If this memory information describes the local heap, this value is an integer representing the running thread ID; if this memory information describes the shared heap, this value is undefined.
threadName string No Yes Thread name. If this memory information describes the local heap, this value is a string representing the running thread name; if this memory information describes the shared heap, this value is undefined.
heapType string No No Heap type. Currently there are two values: "local" indicates that the heap type is the local heap, and "shared" indicates that the heap type is the shared heap.
heapObjectSize number No No Heap object size, in KB (an integer rounded up).

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 Read-Only Optional Description
fatal boolean No Yes Whether to display fatal errors. The value true means to display fatal errors, and false means the opposite. The default value is false.
ignoreBOM boolean No Yes Whether to ignore the BOM. The value true means to ignore the BOM, and false means the opposite. The default value is false.

DecodeToStringOptions12+

Describes the behavioral parameters for the decodeToString method when decoding byte streams.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Utils.Lang

Name Type Read-Only Optional Description
stream boolean No Yes 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 Read-Only Optional Description
stream boolean No Yes Whether to follow additional data blocks in subsequent decodeWithStream calls. Set to true if data is processed in chunks; set to false if the final data is processed without chunking. Defaults to false.

Aspect11+

Provides APIs that support Aspect Oriented Programming (AOP). These APIs can be used to perform instrumentation or replacement on class methods.

[h2]addBefore11+

static addBefore(targetClass: Object, methodName: string, isStatic: boolean, before: Function): void

Inserts a function before the original method of the specified class object is executed. It is suitable for scenarios such as logging, performance monitoring, and permission verification that require interception before method execution. After the addBefore API is executed, the inserted function logic runs first, and then the original method of the specified class object is executed.

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 means a static method, and false means 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.

Example

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

[h2]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 means a static method, and false means 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.

Example

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

// Example of adding pre- and post-instrumentation separately
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

[h2]replace11+

static replace(targetClass: Object, methodName: string, isStatic: boolean, instead: Function) : void

Replaces the original method of the specified class with another function. It is suitable for scenarios such as behavior replacement, compatibility adaptation, and conditional execution that require completely changing the method implementation logic. After the replace API is executed, when the specified class method is called, only the replaced logic is executed. Finally, the return value of the replacement function 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
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 means a static method, and false means 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.

Example

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: 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.

[h2]Properties

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Utils.Lang

Name Type Read-Only Optional 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, gb2312, and iso-8859-1.

fatal boolean Yes No Whether to display fatal errors. The value true means to display fatal errors, and false means the opposite.
ignoreBOM boolean Yes No Whether to ignore the BOM (byte order marker). The value true means to ignore the BOM, and false means the decoding result contains the BOM. The default value is false.

[h2]constructor9+

constructor()

Constructor of TextDecoder. Creates a TextDecoder instance with the default encoding format 'utf-8', with fatal defaulting to false and ignoreBOM defaulting to false.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Utils.Lang

Example

let textDecoder = new util.TextDecoder();
let retStr = textDecoder.encoding;
console.info('retStr = ' + retStr);
// Output: retStr = utf-8

[h2]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. For supported formats, see encoding. The default value is 'utf-8'.
options TextDecoderOptions No Decoding-related option parameters, which include two attributes: fatal and ignoreBOM. When this parameter is not set, each attribute takes its default value.

Return value

Type Description
TextDecoder Returns a TextDecoder object used to decode a byte array into a string in the specified encoding format.

Example

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

[h2]decodeToString12+

decodeToString(input: Uint8Array, options?: DecodeToStringOptions): string

Decodes the input content into a string.

Note

This API parses bytes with the value \0 normally and converts them to the Unicode character \u0000 (null character), without causing decoding interruption or errors.

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 No Decoding-related option parameters used to control the decoding behavior. Pass this parameter and set stream to true when data needs to be processed in chunks in streaming mode while preserving incomplete byte sequences. If not passed, it defaults to undefined, meaning incomplete byte sequences are not preserved and decoding is performed directly in the current call.

Return value

Type Description
string String obtained.

Example

// Example code for parsing bytes that do not contain \0
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
// Example code for parsing bytes containing \0
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([97, 98, 0, 99]);
let retStr = textDecoder.decodeToString(uint8, decodeToStringOptions);
console.info("retStr = " + retStr);
// Output: retStr = abc
let retJson = JSON.stringify(retStr)
console.info("retJson = " + retJson);
// Output result: retJson = ab/u0000c

[h2]decodeWithStream(deprecated)

decodeWithStream(input: Uint8Array, options?: DecodeWithStreamOptions): string

Decodes the input content into a string. If input is an empty array, undefined is returned.

This API is supported since API version 9 and deprecated since API version 12. You are advised to use 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 No Decoding-related option parameters. This parameter does not need to be filled in; when omitted, each property takes its default value.

Return value

Type Description
string String obtained.

Example

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

[h2]constructor(deprecated)

constructor(encoding?: string, options?: { fatal?: boolean; ignoreBOM?: boolean })

A constructor used to create a TextDecoder object.

This API is supported since API version 7 and deprecated since API version 9. You are advised to use create9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
encoding string No Encoding format. The default format is 'utf-8'.
options { fatal?: boolean; ignoreBOM?: boolean } No Decoding-related option parameters, containing two properties: fatal and ignoreBOM. This parameter does not need to be filled in; when omitted, each property takes its default value false.

Table 1 options

Name Type Mandatory Description
fatal boolean No Whether to display fatal errors. The value true means to display fatal errors, and false means the opposite. The default value is false.
ignoreBOM boolean No Whether to ignore the BOM. The value true means to ignore the BOM, and false means the opposite. The default value is false.

Example

let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true});

[h2]decode(deprecated)

decode(input: Uint8Array, options?: { stream?: false }): string

Decodes the input content into a string.

This API is supported since API version 7 and deprecated since API version 9. You are advised to use decodeToString12+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
input Uint8Array Yes Uint8Array object to decode.
options { stream?: false } No Decoding-related option parameters. If this parameter is not passed, stream defaults to false, meaning it does not follow additional data blocks.

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 data is not divided into blocks, set this parameter to false. The default value is false.

Return value

Type Description
string String obtained.

Example

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+

Encrypted information, including the number of read characters and the number of written bytes.

[h2]Properties

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Utils.Lang

Name Type Read-Only Optional 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.

When TextEncoder is used for encoding, the number of bytes occupied by a character varies according to the encoding format. You must explicitly specify the encoding format to obtain the required encoding result.

[h2]Properties

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Utils.Lang

Name Type Read-Only Optional Description
encoding string Yes No

Encoding format.

The following formats are supported: utf-8, gb2312, 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'.

[h2]constructor

constructor()

Constructor of TextEncoder. Creates a TextEncoder instance with the default encoding format 'utf-8'.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Utils.Lang

Example

let textEncoder = new util.TextEncoder();

[h2]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. For supported formats, see encoding. The default value is 'utf-8'.

Example

let textEncoder = new util.TextEncoder("utf-8");

[h2]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'.

Return value

Type Description
TextEncoder Returns a TextEncoder object used to encode a string into a byte array in the specified encoding format.

Example

let textEncoder = util.TextEncoder.create("utf-8");

[h2]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. If the input parameter is an empty string, the return value is undefined.

Return value

Type Description
Uint8Array Returns the encoded Uint8Array object. When the input parameter is an empty string, undefined is returned.

Example

let textEncoder = new util.TextEncoder();
let result = textEncoder.encodeInto("\uD800¥¥");
console.info("result = " + result);
// Output: result = 237,160,128,194,165,194,165

[h2]encodeIntoUint8Array9+

encodeIntoUint8Array(input: string, dest: Uint8Array): EncodeIntoUint8ArrayInfo

Encodes the input content and stores the result 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 Object obtained. read indicates the number of encoded characters, and written indicates the number of bytes in the encoded characters.

Example

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
console.info("result.read = " + result.read);
// Output: result.read = 4
console.info("result.written = " + result.written);
// Output: result.written = 4

[h2]encodeInto(deprecated)

encodeInto(input: string, dest: Uint8Array): { read: number; written: number }

Writes the generated UTF-8 encoded text to an array.

This API is supported since API version 7 and deprecated since API version 9. You are advised to use 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
{ read: number; written: number } Object obtained. read indicates the number of encoded characters, and written indicates the number of bytes in the encoded characters.

Example

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

[h2]encode(deprecated)

encode(input?: string): Uint8Array

Encodes the input string and outputs the corresponding Uint8Array byte array.

This API is supported since API version 7 and deprecated since API version 9. You are advised to use 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

let textEncoder = new util.TextEncoder();
let result = textEncoder.encode("\uD800¥¥");
console.info("result = " + result);
// Output: result = 237,160,128,194,165,194,165

RationalNumber8+

RationalNumber is mainly used to compare rational numbers and provides methods for obtaining the numerator and denominator. RationalNumber stores rational numbers internally as numerator and denominator, and automatically simplifies the fraction when created. Note that when the denominator is 0, the rational number is represented as Infinity; when both the numerator and denominator are 0, the rational number is represented as NaN (not a number). The toString() method can be used to convert a rational number to a string, and this class can be used to conveniently perform various operations on rational numbers.

[h2]constructor9+

constructor()

Constructor of RationalNumber, which creates a RationalNumber instance with a default numerator of 0 and denominator of 1.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Utils.Lang

Example

let rationalNumber = new util.RationalNumber();

[h2]parseRationalNumber9+

static parseRationalNumber(numerator: number,denominator: number): RationalNumber

Creates a RationalNumber instance with a given numerator and denominator.

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.

Return value

Type Description
RationalNumber A RationalNumber object with the given numerator and denominator.

Example

let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);

[h2]createRationalFromString8+

static createRationalFromString(rationalString: string): RationalNumber

Creates a RationalNumber object based on the given string.

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 Rational number string format, for example, "3/4". If a decimal string format is passed in, it is not intercepted but an error message is output.

Return value

Type Description
RationalNumber A RationalNumber object created from the given string.

Example

let rational = util.RationalNumber.createRationalFromString("3/4");

[h2]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 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

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

[h2]valueOf8+

valueOf(): number

Obtains the integer or floating-point value 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 An integer or a floating-point number.

Example

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:

let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let result = rationalNumber.valueOf();
console.info("result = " + result);
// Output: result = 0.5

[h2]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 the current RationalNumber object. Returns false when a non-RationalNumber type is passed in.

Return value

Type Description
boolean Check result. The value true is returned if the two objects are equal; otherwise, false is returned.

Example

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:

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

[h2]getCommonFactor9+

static getCommonFactor(number1: number, number2: number): number

Obtains the greatest common divisor of two specified integers.

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.

Example

let result = util.RationalNumber.getCommonFactor(4,6);
console.info("result = " + result);
// Output: result = 2

[h2]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

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:

let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let result = rationalNumber.getNumerator();
console.info("result = " + result);
// Output: result = 1

[h2]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

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:

let rationalNumber = util.RationalNumber.parseRationalNumber(1,2)
let result = rationalNumber.getDenominator();
console.info("result = " + result);
// Output: result = 2

[h2]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 Check result. The value true is returned if the value of this RationalNumber object is 0; otherwise, false is returned.

Example

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:

let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let result = rationalNumber.isZero();
console.info("result = " + result);
// Output: result = false

[h2]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 Check result. The value true is returned if this RationalNumber object is a NaN (the denominator and numerator are both 0); otherwise, false is returned.

Example

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:

let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let result = rationalNumber.isNaN();
console.info("result = " + result);
// Output: result = false

[h2]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 Check result. The value true is returned if this RationalNumber object represents a finite value (the denominator is not 0); otherwise, false is returned.

Example

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:

let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let result = rationalNumber.isFinite();
console.info("result = " + result);
// Output: result = true

[h2]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

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:

let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let result = rationalNumber.toString();
console.info("result = " + result);
// Output: result = 1/2

[h2]constructor(deprecated)

constructor(numerator: number,denominator: number)

A constructor used to create a RationalNumber object.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use parseRationalNumber9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
numerator number Yes Numerator, integer type. Value range: -Number.MAX_VALUE <= numerator <= Number.MAX_VALUE.
denominator number Yes Denominator, integer type. Value range: -Number.MAX_VALUE <= denominator <= Number.MAX_VALUE.

Example

let rationalNumber = new util.RationalNumber(1,2);

[h2]compareTo(deprecated)

compareTo(another: RationalNumber): number​

Compares this RationalNumber object with a given object.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use 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

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

[h2]getCommonDivisor(deprecated)

static getCommonDivisor(number1: number,number2: number): number

Obtains the greatest common divisor of two specified integers.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use getCommonFactor9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
number1 number Yes Integer type. -Number.MAX_VALUE <= number1 <= Number.MAX_VALUE.
number2 number Yes Integer type. -Number.MAX_VALUE <= number2 <= Number.MAX_VALUE.

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.

[h2]Properties

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Utils.Lang

Name Type Read-Only Optional Description
length number Yes No Total number of values in the current cache.

Example

let pro = new util.LRUCache<number, number>();
pro.put(2, 10);
pro.put(1, 8);
let result = pro.length;
console.info('result = ' + result);
// Output: result = 2

[h2]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 Indicates the custom capacity for the buffer. The value range is [0, 2147483647], and the default value is 64.

Example

let lruCache = new util.LRUCache<number, number>();

[h2]updateCapacity9+

updateCapacity(newCapacity: number): void

Updates the cache capacity to the specified value. If newCapacity is less than or equal to 0, an exception is thrown. When the total number of values in the cache is greater than the specified capacity, deletion 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 Indicates the custom capacity for the buffer, with a value range of [0, 2147483647].

Example

let pro = new util.LRUCache<number, number>();
pro.updateCapacity(100);

[h2]toString9+

toString(): string

Returns the string representation of the object in the format LRUCache[ maxSize = maximum cache size, hits = number of successful query matches, misses = number of failed query matches, hitRate = query match rate ].

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

let pro = new util.LRUCache<number, number>();
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.

[h2]getCapacity9+

getCapacity(): number

Obtains the current cache capacity.

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

let pro = new util.LRUCache<number, number>();
let result = pro.getCapacity();
console.info('result = ' + result);
// Output: result = 64

[h2]clear9+

clear(): void

Clears the key-value pairs in the current buffer and triggers the afterRemoval callback method to perform subsequent operations.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Utils.Lang

Example

let pro = new util.LRUCache<number, number>();
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

[h2]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

// Create the ChildLRUCache class that inherits LRUCache, and override createDefault() to return a non-undefined value.
class ChildLRUCache extends util.LRUCache<number, number> {
  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

[h2]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

let pro = new util.LRUCache<number, number>();
pro.put(2, 10);
pro.get(2);
let result = pro.getMissCount();
console.info('result = ' + result);
// Output: result = 0

[h2]getRemovalCount9+

getRemovalCount(): number

Obtains the number of times cache key-value pairs have been 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

let pro = new util.LRUCache<number, number>();
pro.put(2, 10);
pro.updateCapacity(2);
pro.put(50, 22);
let result = pro.getRemovalCount();
console.info('result = ' + result);
// Output: result = 0

[h2]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

let pro = new util.LRUCache<number, number>();
pro.put(2, 10);
pro.get(2);
let result = pro.getMatchCount();
console.info('result = ' + result);
// Output: result = 1

[h2]getPutCount9+

getPutCount(): number

Obtains the number of times values have been added to the 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

let pro = new util.LRUCache<number, number>();
pro.put(2, 10);
let result = pro.getPutCount();
console.info('result = ' + result);
// Output: result = 1

[h2]isEmpty9+

isEmpty(): boolean

Checks whether the 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; otherwise, returns false.

Example

let pro = new util.LRUCache<number, number>();
pro.put(2, 10);
let result = pro.isEmpty();
console.info('result = ' + result);
// Output: result = false

[h2]get9+

get(key: K): V | undefined

Returns the value corresponding to the key. When the key is not in the cache, the value is created through createDefault. If the value created by createDefault is not undefined, the afterRemoval interface is called and the value created by createDefault 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 based on which the value is queried.

Return value

Type Description
V | undefined Value of the key. If no match is found, the value specified in createDefault is returned.

Example

let pro = new util.LRUCache<number, number>();
pro.put(2, 10);
let result  = pro.get(2);
console.info('result = ' + result);
// Output: result = 10

[h2]put9+

put(key: K,value: V): V

Adds a key-value pair to the cache and returns the value associated with the added key. When the total number of values in the cache exceeds the capacity, a removal 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.

Example

let pro = new util.LRUCache<number, number>();
let result = pro.put(2, 10);
console.info('result = ' + result);
// Output: result = 10

[h2]values9+

values(): V[]

Obtains all values in the current cache, in the order from least recently accessed to most 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[] The list of all values in this cache, listed from the least to the most recently accessed.

Example

let pro = new util.LRUCache<number, string>();
pro.put(1, 'A');
pro.put(2, "B");
pro.put(3, 'C');
pro.put(4, 'D')
pro.put(5, 'E')
pro.put(6, 'F')
let result = pro.values();
console.info('result = ' + result);
// Output: result = A,B,C,D,E,F
pro.get(1);
pro.get(2);
result = pro.values();
console.info('result = ' + result);
// Output: result = C,D,E,F,A,B

[h2]keys9+

keys(): K[]

Obtains all keys in the current cache, in the order from least recently accessed to most 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[] The list of all keys in this cache, listed from the least to the most recently accessed.

Example

let pro = new util.LRUCache<number, string>();
pro.put(1, 'A');
pro.put(2, "B");
pro.put(3, 'C');
pro.put(4, 'D')
pro.put(5, 'E')
pro.put(6, 'F')
let result = pro.keys();
console.info('result = ' + result);
// Output: result = 1,2,3,4,5,6
pro.get(5);
pro.get(3);
result = pro.keys();
console.info('result = ' + result);
// Output: result = 1,2,4,6,5,3

[h2]remove9+

remove(key: K): V | undefined

Removes the specified key and its associated value from the current cache, and returns the value associated with the key. If the specified 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 be deleted.

Return value

Type Description
V | undefined Returns the value associated with the deleted key; returns undefined if the key does not exist, and throws an exception if the key is null.

Example

let pro = new util.LRUCache<number, number>();
pro.put(2, 10);
let result = pro.remove(20);
console.info('result = ' + result);
// Output: result = undefined

[h2]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+, put9+, remove9+, clear9+, and updateCapacity9+.

If the callback method is executed after clear9+ and updateCapacity9+ are called and the input key and value parameters are of the MapIterator type, perform subsequent operations by referring to example 2.

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.

Example 1

class ChildLRUCache<K, V> extends util.LRUCache<K, V> {
  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<number, number>(2);
lru.put(1, 1);
lru.put(2, 2);
lru.put(3, 3);

Example 2

class TestClass {
  str:string = '';
  constructor(input: string) {
    this.str = input;
  }
}

class ChildLRUCache extends util.LRUCache<string, TestClass> {
  constructor(capacity?: number) {
    super(capacity);
  }

  afterRemoval(isEvict: boolean, key: string, value: TestClass, newValue: TestClass): void {
    if(value.toString().indexOf('[object Map Iterator]') >= 0) {
      console.info('Entered via clear');
      console.info('isEvict = ' + isEvict);
      const keysIterator = (key as ESObject as IterableIterator<string>);
      const valuesIterator = (value as ESObject as IterableIterator<TestClass>);

      let keyEntry = keysIterator.next();
      let valueEntry = valuesIterator.next();
      while (!keyEntry.done && !valueEntry.done) {
        console.info(`key = ${keyEntry.value}, valueStr = ${valueEntry.value.str}`);
        keyEntry = keysIterator.next();
        valueEntry = valuesIterator.next();
      }
    } else {
      console.info('Entered via put');
      console.info('isEvict = ' + isEvict);
      console.info('key = ' + key + '  valueStr = ' + value.str);
    }
  }
}
let test1 = new TestClass('testA');
let test2 = new TestClass('testB');
let test3 = new TestClass('testC');
let lru = new ChildLRUCache(2);
lru.put('aa', test1);
lru.put('bb', test2);
lru.put('cc', test3);    // Remove the key-value pair for 'aa'.
lru.clear();             // Clear the entire cache buffer.
/*
Output: call put to enter
         isEvict = true
         key = aa  valueStr = testA
         call clear to enter
         isEvict = false
         key = bb, valueStr = testB
         key = cc, valueStr = testC
 */

[h2]contains9+

contains(key: K): boolean

Checks whether the current 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; otherwise, returns false.

Example

let pro = new util.LRUCache<number, number>();
pro.put(2, 10);
let result = pro.contains(2);
console.info('result = ' + result);
// Output: result = true

[h2]createDefault9+

createDefault(key: K): V

If no key is matched in the cache, the subsequent operation is performed. The parameter indicates the unmatched key, and the value associated with the key is returned. undefined is returned by default.

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.

Example

let pro = new util.LRUCache<number, number>();
let result = pro.createDefault(50);
console.info('result = ' + result);
// Output: result = undefined

[h2]entries9+

entries(): IterableIterator<[K, V]>

Returns an iterator object that traverses all key-value pairs ([key, value]) in this object in the insertion order.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Utils.Lang

Return value

Type Description
IterableIterator<[K, V]> Returns an iterator object used to traverse all key-value pairs [key, value] in the current buffer in insertion order.

Example

let pro = new util.LRUCache<number, number>();
pro.put(2, 10);
pro.put(3, 15);
let pair = pro.entries();
for (let value of pair) {
  console.info(value[0]+ ', '+ value[1]);
}
// Output:
// 2, 10
// 3, 15

[h2][Symbol.iterator]9+

[Symbol.iterator](): IterableIterator<[K, V]>

Obtains a two-dimensional array in key-value pairs.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Utils.Lang

Return value

Type Description
IterableIterator<[K, V]> Two-dimensional array in key-value pairs.

Example

let pro = new util.LRUCache<number, number>();
pro.put(2, 10);
pro.put(3, 15);

for (let value of pro) {
  console.info(value[0]+ ', '+ value[1]);
}
// Output:
// 2, 10
// 3, 15

ScopeComparable8+

The values of the ScopeComparable type are used to implement the compareTo method. Therefore, ensure that the input parameters are comparable.

System capability: SystemCapability.Utils.Lang

[h2]compareTo8+

compareTo(other: ScopeComparable): boolean

Compares two values and returns a Boolean value.

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
other ScopeComparable Yes The other value to be compared with the current value.

Return value

Type Description
boolean Check result. The value true is returned if the current value is greater than or equal to the input value; otherwise, false is returned.

Example

Create a class to implement the compareTo method. The Temperature class is used as an example in the following sample code.

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

ScopeType8+

type ScopeType = ScopeComparable | number

Defines the type of values in a Scope object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Utils.Lang

Type Description
number The value type is a number.
ScopeComparable The value type is ScopeComparable.

ScopeHelper9+

The ScopeHelper interface is used to describe the valid range of a field, and is commonly used in scenarios such as input value range validation and configuration parameter interval judgment. The constructor is used to create objects with specified lower and upper limits, and requires these objects to be comparable. Through ScopeHelper, developers can conveniently perform range intersection and union calculations as well as determine whether a value is within the range, preventing invalid data from entering business logic.

[h2]constructor9+

constructor(lowerObj: ScopeType, upperObj: ScopeType)

A constructor used to create a ScopeHelper object with the specified upper and lower limits.

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
lowerObj ScopeType Yes Specifies the lower bound of the scope instance, which must be comparable.
upperObj ScopeType Yes Specifies the upper bound of the scope instance, which must be comparable.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}
let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let range = new util.ScopeHelper(tempLower, tempUpper);
console.info("range = " + range);
// Output: range = [30, 40]

[h2]toString9+

toString(): string

Obtains a string representation that contains this Scope.

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 containing the Scope.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let range = new util.ScopeHelper(tempLower, tempUpper);
let result = range.toString();
console.info("result = " + result);
// Output: result = [30, 40]

[h2]intersect9+

intersect(range: ScopeHelper): ScopeHelper

Obtains the intersection of this Scope and the given Scope. If the intersection is empty, an exception is thrown.

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
range ScopeHelper Yes Scope specified.

Return value

Type Description
ScopeHelper Intersection of this Scope and the given Scope.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let range = new util.ScopeHelper(tempLower, tempUpper);
let tempMiDF = new Temperature(35);
let tempMidS = new Temperature(39);
let rangeFir = new util.ScopeHelper(tempMiDF, tempMidS);
let result = range.intersect(rangeFir);
console.info("result = " + result);
// Output: result = [35, 39]

[h2]intersect9+

intersect(lowerObj:ScopeType,upperObj:ScopeType):ScopeHelper

Obtains the intersection of this Scope and the given lower and upper limits. If the intersection is empty, an exception is thrown.

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
lowerObj ScopeType Yes Lower limit.
upperObj ScopeType Yes Upper limit.

Return value

Type Description
ScopeHelper Intersection of this Scope and the given lower and upper limits.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let tempMiDF = new Temperature(35);
let tempMidS = new Temperature(39);
let range = new util.ScopeHelper(tempLower, tempUpper);
let result = range.intersect(tempMiDF, tempMidS);
console.info("result = " + result);
// Output: result = [35, 39]

[h2]getUpper9+

getUpper(): ScopeType

Obtains the upper limit of this Scope.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Utils.Lang

Return value

Type Description
ScopeType Upper limit of this Scope.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let range = new util.ScopeHelper(tempLower, tempUpper);
let result = range.getUpper();
console.info("result = " + result);
// Output: result = 40

[h2]getLower9+

getLower(): ScopeType

Obtains the lower limit of this Scope.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Utils.Lang

Return value

Type Description
ScopeType Lower limit of this Scope.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let range = new util.ScopeHelper(tempLower, tempUpper);
let result = range.getLower();
console.info("result = " + result);
// Output: result = 30

[h2]expand9+

expand(lowerObj: ScopeType,upperObj: ScopeType): ScopeHelper

Obtains the union set of this Scope and the given lower and upper limits.

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
lowerObj ScopeType Yes Lower limit.
upperObj ScopeType Yes Upper limit.

Return value

Type Description
ScopeHelper Union set of this Scope and the given lower and upper limits.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let tempMiDF = new Temperature(35);
let tempMidS = new Temperature(39);
let range = new util.ScopeHelper(tempLower, tempUpper);
let result = range.expand(tempMiDF, tempMidS);
console.info("result = " + result);
// Output: result = [30, 40]

[h2]expand9+

expand(range: ScopeHelper): ScopeHelper

Obtains the union set of this Scope and the given Scope.

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
range ScopeHelper Yes Scope specified.

Return value

Type Description
ScopeHelper Union set of this Scope and the given Scope.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let tempMiDF = new Temperature(35);
let tempMidS = new Temperature(39);
let range = new util.ScopeHelper(tempLower, tempUpper);
let rangeFir = new util.ScopeHelper(tempMiDF, tempMidS);
let result = range.expand(rangeFir);
console.info("result = " + result);
// Output: result = [30, 40]

[h2]expand9+

expand(value: ScopeType): ScopeHelper

Obtains the union set of this Scope and the given value.

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
value ScopeType Yes Value to check whether it is within the current scope.

Return value

Type Description
ScopeHelper Union set of this Scope and the given value.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let tempMiDF = new Temperature(35);
let range = new util.ScopeHelper(tempLower, tempUpper);
let result = range.expand(tempMiDF);
console.info("result = " + result);
// Output: result = [30, 40]

[h2]contains9+

contains(value: ScopeType): boolean

Checks whether a range is within this Scope.

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
value ScopeType Yes Value specified.

Return value

Type Description
boolean Check result. The value true is returned if the value is within this Scope; otherwise, false is returned.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let tempMiDF = new Temperature(35);
let range = new util.ScopeHelper(tempLower, tempUpper);
let result = range.contains(tempMiDF);
console.info("result = " + result);
// Output: result = true

[h2]contains9+

contains(range: ScopeHelper): boolean

Checks whether a range is within this Scope.

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
range ScopeHelper Yes Scope specified.

Return value

Type Description
boolean Check result. The value true is returned if the range is within this Scope; otherwise, false is returned.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let range = new util.ScopeHelper(tempLower, tempUpper);
let tempLess = new Temperature(20);
let tempMore = new Temperature(45);
let rangeSec = new util.ScopeHelper(tempLess, tempMore);
let result = range.contains(rangeSec);
console.info("result = " + result);
// Output: result = false

[h2]clamp9+

clamp(value: ScopeType): ScopeType

Limits a value to this Scope.

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
value ScopeType Yes Value specified.

Return value

Type Description
ScopeType Returns lowerObj if the specified value is less than the lower limit; returns upperObj if the specified value is greater than the upper limit; returns the specified value if it is within this Scope.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let tempMiDF = new Temperature(35);
let range = new util.ScopeHelper(tempLower, tempUpper);
let result = range.clamp(tempMiDF);
console.info("result = " + result);
// Output: result = 35

Base64Helper9+

Provides encoding and decoding for Base64 and Base64URL. The Base64 encoding table contains 64 characters, which are the uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), and the special characters plus sign (+) and slash (/). During encoding, the original data is divided into groups of three bytes, and each group contains a 6-bit number. Then, the corresponding characters in the Base64 encoding table are used to represent these numbers. If the last group contains only one or two bytes, the equal sign (=) is used for padding. The Base64URL encoding table contains 64 characters, which are the uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), and the special characters plus sign (+) and slash (/). The Base64URL encoding result does not contain equal signs (=).

[h2]constructor9+

constructor()

The constructor of Base64Helper creates a Base64Helper instance for Base64 encoding and decoding.

System capability: SystemCapability.Utils.Lang

Atomic service API: This API can be used in atomic services since API version 11.

Example

let base64 = new util.Base64Helper();

[h2]encodeSync9+

encodeSync(src: Uint8Array, options?: Type): 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
src Uint8Array Yes Uint8Array object to encode.
options12+ Type No

Encoding format.

The following values are available:

- util.Type.BASIC (default): Base64 encoding.

- util.Type.BASIC_URL_SAFE: Base64URL encoding.

Return value

Type Description
Uint8Array Uint8Array object obtained.

Example

let base64Helper = new util.Base64Helper();
let array = new Uint8Array([115,49,51]);
let result = base64Helper.encodeSync(array);
console.info("result = " + result);
// Output: result = 99,122,69,122

[h2]encodeToStringSync9+

encodeToStringSync(src: Uint8Array, options?: Type): string

Performs Base64 encoding on the input Uint8Array byte array and returns a string. This method supports multiple encoding formats, including standard Base64 encoding, MIME-compliant Base64 encoding (with line breaks), and URL-safe Base64 encoding.

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
src Uint8Array Yes Uint8Array object to encode.
options10+ Type No

Encoding format.

The following values are available:

- util.Type.BASIC (default): Base64 encoding. The return value does not contain carriage return characters or newline characters.

- util.Type.MIME: Base64 encoding. If the return value exceeds 76 characters, a line break is inserted every 76 characters, and each line ends with '\r\n'. If the return value is fewer than 76 characters, an exception is thrown.

- util.Type.BASIC_URL_SAFE: Base64URL encoding. The return value does not contain carriage return characters or newline characters.

- util.Type.MIME_URL_SAFE: Base64URL encoding. Each line in the return value contains a maximum of 76 characters and ends with '\r\n'.

Return value

Type Description
string String obtained.

Example

// MIME encoding
let base64Helper = new util.Base64Helper();
let array =
  new Uint8Array([77, 97, 110, 105, 115, 100, 105, 115, 116, 105, 110, 103, 117, 105, 115, 104, 101, 100, 110, 111, 116,
    111, 110, 108, 121, 98, 121, 104, 105, 115, 114, 101, 97, 115, 111, 110, 98, 117, 116, 98, 121, 116, 104, 105, 115,
    115, 105, 110, 103, 117, 108, 97, 114, 112, 97, 115, 115, 105, 111, 110, 102, 114, 111, 109, 111, 116, 104, 101,
    114, 97, 110, 105, 109, 97, 108, 115, 119, 104, 105, 99, 104, 105, 115, 97, 108, 117, 115, 116, 111, 102, 116, 104,
    101, 109, 105, 110, 100, 101, 120, 99, 101, 101, 100, 115, 116, 104, 101, 115, 104, 111, 114, 116, 118, 101, 104,
    101, 109, 101, 110, 99, 101, 111, 102, 97, 110, 121, 99, 97, 114, 110, 97, 108, 112, 108, 101, 97, 115, 117, 114,
    101]);
let result = base64Helper.encodeToStringSync(array, util.Type.MIME);
console.info("result = " + result);
/*
Output result: result = TWFuaXNkaXN0aW5ndWlzaGVkbm90b25seWJ5aGlzcmVhc29uYnV0Ynl0aGlzc2luZ3VsYXJwYXNz
aW9uZnJvbW90aGVyYW5pbWFsc3doaWNoaXNhbHVzdG9mdGhlbWluZGV4Y2VlZHN0aGVzaG9ydHZl
aGVtZW5jZW9mYW55Y2FybmFscGxlYXN1cmU=
 */

// BASIC encoding
let base64Helper = new util.Base64Helper();
let array =
  new Uint8Array([77, 97, 110, 105, 115, 100, 105, 115, 116, 105, 110, 103, 117, 105, 115, 104, 101, 100, 110, 111, 116,
    111, 110, 108, 121, 98, 121, 104, 105, 115, 114, 101, 97, 115, 111, 110, 98, 117, 116, 98, 121, 116, 104, 105, 115,
    115, 105, 110, 103, 117, 108, 97, 114, 112, 97, 115, 115, 105, 111, 110, 102, 114, 111, 109, 111, 116, 104, 101,
    114, 97, 110, 105, 109, 97, 108, 115, 119, 104, 105, 99, 104, 105, 115, 97, 108, 117, 115, 116, 111, 102, 116, 104,
    101, 109, 105, 110, 100, 101, 120, 99, 101, 101, 100, 115, 116, 104, 101, 115, 104, 111, 114, 116, 118, 101, 104,
    101, 109, 101, 110, 99, 101, 111, 102, 97, 110, 121, 99, 97, 114, 110, 97, 108, 112, 108, 101, 97, 115, 117, 114,
    101]);
let result = base64Helper.encodeToStringSync(array, util.Type.BASIC);
console.info("result = " + result);
/*
Output result: result = TWFuaXNkaXN0aW5ndWlzaGVkbm90b25seWJ5aGlzcmVhc29uYnV0Ynl0aGlzc2luZ3VsYXJwYXNzaW9uZnJvbW90aGVyYW5pbWFsc3doaWNoaXNhbHVzdG9mdGhlbWluZGV4Y2VlZHN0aGVzaG9ydHZlaGVtZW5jZW9mYW55Y2FybmFscGxlYXN1cmU=
 */

// MIME_URL_SAFE encoding
let base64Helper = new util.Base64Helper();
let array =
  new Uint8Array([77, 97, 110, 105, 115, 100, 105, 115, 116, 105, 110, 103, 117, 105, 115, 104, 101, 100, 110, 111, 116,
    111, 110, 108, 121, 98, 121, 104, 105, 115, 114, 101, 97, 115, 111, 110, 98, 117, 116, 98, 121, 116, 104, 105, 115,
    115, 105, 110, 103, 117, 108, 97, 114, 112, 97, 115, 115, 105, 111, 110, 102, 114, 111, 109, 111, 116, 104, 101,
    114, 97, 110, 105, 109, 97, 108, 115, 119, 104, 105, 99, 104, 105, 115, 97, 108, 117, 115, 116, 111, 102, 116, 104,
    101, 109, 105, 110, 100, 101, 120, 99, 101, 101, 100, 115, 116, 104, 101, 115, 104, 111, 114, 116, 118, 101, 104,
    101, 109, 101, 110, 99, 101, 111, 102, 97, 110, 121, 99, 97, 114, 110, 97, 108, 112, 108, 101, 97, 115, 117, 114,
    101]);
let result = base64Helper.encodeToStringSync(array, util.Type.BASIC_URL_SAFE);
console.info("result = " + result);
/*
Output result: result = TWFuaXNkaXN0aW5ndWlzaGVkbm90b25seWJ5aGlzcmVhc29uYnV0Ynl0aGlzc2luZ3VsYXJwYXNzaW9uZnJvbW90aGVyYW5pbWFsc3doaWNoaXNhbHVzdG9mdGhlbWluZGV4Y2VlZHN0aGVzaG9ydHZlaGVtZW5jZW9mYW55Y2FybmFscGxlYXN1cmU
 */
// MIME_URL_SAFE encoding
let base64Helper = new util.Base64Helper();
let array =
  new Uint8Array([77, 97, 110, 105, 115, 100, 105, 115, 116, 105, 110, 103, 117, 105, 115, 104, 101, 100, 110, 111, 116,
    111, 110, 108, 121, 98, 121, 104, 105, 115, 114, 101, 97, 115, 111, 110, 98, 117, 116, 98, 121, 116, 104, 105, 115,
    115, 105, 110, 103, 117, 108, 97, 114, 112, 97, 115, 115, 105, 111, 110, 102, 114, 111, 109, 111, 116, 104, 101,
    114, 97, 110, 105, 109, 97, 108, 115, 119, 104, 105, 99, 104, 105, 115, 97, 108, 117, 115, 116, 111, 102, 116, 104,
    101, 109, 105, 110, 100, 101, 120, 99, 101, 101, 100, 115, 116, 104, 101, 115, 104, 111, 114, 116, 118, 101, 104,
    101, 109, 101, 110, 99, 101, 111, 102, 97, 110, 121, 99, 97, 114, 110, 97, 108, 112, 108, 101, 97, 115, 117, 114,
    101]);
let result = base64Helper.encodeToStringSync(array, util.Type.MIME_URL_SAFE);
console.info("result = " + result);
/*
Output result: result = TWFuaXNkaXN0aW5ndWlzaGVkbm90b25seWJ5aGlzcmVhc29uYnV0Ynl0aGlzc2luZ3VsYXJwYXNz
aW9uZnJvbW90aGVyYW5pbWFsc3doaWNoaXNhbHVzdG9mdGhlbWluZGV4Y2VlZHN0aGVzaG9ydHZl
aGVtZW5jZW9mYW55Y2FybmFscGxlYXN1cmU
 */

[h2]decodeSync9+

decodeSync(src: Uint8Array | string, options?: Type): Uint8Array

Decodes a string into a Uint8Array object. This API returns the result synchronously.

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
src Uint8Array | string Yes Uint8Array object or string to decode.
options10+ Type No

Decoding format.

The following values are available:

- util.Type.BASIC (default): Base64 decoding.

- util.Type.MIME: Base64 decoding. The input parameter src contains carriage return characters and newline characters.

- util.Type.BASIC_URL_SAFE: Base64URL decoding.

- util.Type.MIME_URL_SAFE: Base64 URL decoding. The input parameter src contains carriage return characters and newline characters.

Return value

Type Description
Uint8Array Uint8Array object obtained.

Example

let base64Helper = new util.Base64Helper();
let buff = 'TWFuaXNkaXN0aW5ndWlzaGVkbm90b25seWJ5aGlzcmVhc29uYnV0Ynl0aGlzc2luZ3VsYXJwYXNz\r\naW9uZnJvbW90aGVyYW5pbWFsc3doaWNoaXNhbHVzdG9mdGhlbWluZGV4Y2VlZHN0aGVzaG9ydHZl\r\naGVtZW5jZW9mYW55Y2FybmFscGxlYXN1cmU=\r\n';
let result = base64Helper.decodeSync(buff, util.Type.MIME);
console.info("result = " + result);
/*
Output result: result = 77,97,110,105,115,100,105,115,116,105,110,103,117,105,115,104,101,100,110,111,116,111,110,108,121,98,121,104,105,115,114,101,97,115,111,110,98,117,116,98,121,116,104,105,115,115,105,110,103,117,108,97,114,112,97,115,115,105,111,110,102,114,111,109,111,116,104,101,114,97,110,105,109,97,108,115,119,104,105,99,104,105,115,97,108,117,115,116,111,102,116,104,101,109,105,110,100,101,120,99,101,101,100,115,116,104,101,115,104,111,114,116,118,101,104,101,109,101,110,99,101,111,102,97,110,121,99,97,114,110,97,108,112,108,101,97,115,117,114,101
 */

[h2]encode9+

encode(src: Uint8Array, options?: Type): Promise<Uint8Array>

Encodes the input content into a Uint8Array object. This API uses a promise to return the result.

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
src Uint8Array Yes Uint8Array object to encode.
options12+ Type No

Encoding format.

The following values are available:

- util.Type.BASIC (default): Base64 encoding.

- util.Type.BASIC_URL_SAFE: Base64URL encoding.

Return value

Type Description
Promise<Uint8Array> Promise object. Resolves to a newly allocated Uint8Array object when encoding succeeds, and rejects with an error object when encoding fails.

Example

let base64Helper = new util.Base64Helper();
let array = new Uint8Array([115,49,51]);
base64Helper.encode(array).then((val) => {
  console.info(val.toString());
  // Output: 99,122,69,122
})

[h2]encodeToString9+

encodeToString(src: Uint8Array, options?: Type): Promise<string>

Encodes the input parameters asynchronously and outputs the corresponding text. This API uses a promise to return the result.

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
src Uint8Array Yes Uint8Array object to encode.
options10+ Type No

Encoding format.

The following values are available:

- util.Type.BASIC (default): Base64 encoding. The return value does not contain carriage return characters or newline characters.

- util.Type.MIME: Base64 encoding. Each line of the return value contains a maximum of 76 characters and ends with '\r\n'.

- util.Type.BASIC_URL_SAFE: Base64URL encoding. The return value does not contain carriage return characters or newline characters.

- util.Type.MIME_URL_SAFE: Base64URL encoding. Each line in the return value contains a maximum of 76 characters and ends with '\r\n'.

Return value

Type Description
Promise<string> Promise object. Resolves to the Base64-encoded string when encoding succeeds, and rejects with an error object when encoding fails.

Example

let base64Helper = new util.Base64Helper();
let array = new Uint8Array([77,97,110,105,115,100,105,115,116,105,110,103,117,105,115,104,101,100,110,111,116,111,110,108,121,98,121,104,105,115,114,101,97,115,111,110,98,117,116,98,121,116,104,105,115,115,105,110,103,117,108,97,114,112,97,115,115,105,111,110,102,114,111,109,111,116,104,101,114,97,110,105,109,97,108,115,119,104,105,99,104,105,115,97,108,117,115,116,111,102,116,104,101,109,105,110,100,101,120,99,101,101,100,115,116,104,101,115,104,111,114,116,118,101,104,101,109,101,110,99,101,111,102,97,110,121,99,97,114,110,97,108,112,108,101,97,115,117,114,101]);
base64Helper.encodeToString(array, util.Type.MIME).then((val) => {
  console.info(val);
  /*
  Output result: TWFuaXNkaXN0aW5ndWlzaGVkbm90b25seWJ5aGlzcmVhc29uYnV0Ynl0aGlzc2luZ3VsYXJwYXNz
  aW9uZnJvbW90aGVyYW5pbWFsc3doaWNoaXNhbHVzdG9mdGhlbWluZGV4Y2VlZHN0aGVzaG9ydHZl
  aGVtZW5jZW9mYW55Y2FybmFscGxlYXN1cmU=
   */

})

[h2]decode9+

decode(src: Uint8Array | string, options?: Type): Promise<Uint8Array>

Decodes the input parameters asynchronously and outputs the corresponding Uint8Array object. This API uses a promise to return the result.

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
src Uint8Array | string Yes Uint8Array object or string to decode.
options10+ Type No

Decoding format.

The following values are available:

- util.Type.BASIC (default): Base64 decoding.

- util.Type.MIME: Base64 decoding. The input parameter src contains carriage return characters and newline characters.

- util.Type.BASIC_URL_SAFE: Base64URL decoding.

- util.Type.MIME_URL_SAFE: Base64 URL decoding. The input parameter src contains carriage return characters and newline characters.

Return value

Type Description
Promise<Uint8Array> Promise used to return the Uint8Array object obtained.

Example

let base64Helper = new util.Base64Helper();
let array = 'TWFuaXNkaXN0aW5ndWlzaGVkbm90b25seWJ5aGlzcmVhc29uYnV0Ynl0aGlzc2luZ3VsYXJwYXNz\r\naW9uZnJvbW90aGVyYW5pbWFsc3doaWNoaXNhbHVzdG9mdGhlbWluZGV4Y2VlZHN0aGVzaG9ydHZl\r\naGVtZW5jZW9mYW55Y2FybmFscGxlYXN1cmU=\r\n';
base64Helper.decode(array, util.Type.MIME).then((val) => {
  console.info(val.toString());
  /*
  Output: 77,97,110,105,115,100,105,115,116,105,110,103,117,105,115,104,101,100,110,111,116,111,110,108,121,98,121,104,105,115,114,101,97,115,111,110,98,117,116,98,121,116,104,105,115,115,105,110,103,117,108,97,114,112,97,115,115,105,111,110,102,114,111,109,111,116,104,101,114,97,110,105,109,97,108,115,119,104,105,99,104,105,115,97,108,117,115,116,111,102,116,104,101,109,105,110,100,101,120,99,101,101,100,115,116,104,101,115,104,111,114,116,118,101,104,101,109,101,110,99,101,111,102,97,110,121,99,97,114,110,97,108,112,108,101,97,115,117,114,101
  */
})

StringDecoder12+

Provides the capability of decoding binary streams into strings. The following encoding types are supported: utf-8, iso-8859-2, koi8-r, macintosh, windows-1250, windows-1251, gbk, gb18030, big5, utf-16be, and UTF-16le.

[h2]constructor12+

constructor(encoding?: string)

Constructor of StringDecoder, which creates a StringDecoder instance with the default encoding 'utf-8'.

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 type of the input data. The default value is utf-8.

Example

let decoder = new util.StringDecoder();

[h2]write12+

write(chunk: string | Uint8Array): string

Decodes a string. Any incomplete multi-byte characters at the end of Uint8Array are filtered out from the returned string and stored in an internal buffer for the next call.

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
chunk string | Uint8Array Yes String to decode. Decoding is performed based on the input encoding type. If the input is of the Uint8Array type, decoding is performed normally. If the input is of the string type, the parameter is directly returned.

Return value

Type Description
string Returns the decoded string. Incomplete multibyte characters have been filtered out of the return value and stored in the internal buffer for processing in the next call.

Example

let decoder = new util.StringDecoder('utf-8');
let input =  new Uint8Array([0xE4, 0xBD, 0xA0, 0xE5, 0xA5, 0xBD]);
const decoded = decoder.write(input);
console.info("decoded:", decoded);
// Output: decoded: Hello, World

[h2]end12+

end(chunk?: string | Uint8Array): string

Ends the decoding process and returns any remaining input stored in the internal buffer as 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
chunk string | Uint8Array No The last portion of data to be decoded. Pass this parameter when there is remaining data to be processed together at the end of decoding. If not passed, it defaults to undefined, meaning only the decoding result of the incomplete byte sequence stored in the internal buffer is returned, and no new data is processed. The string to be decoded. Defaults to undefined.

Return value

Type Description
string Returns a string consisting of all remaining decoded content stored in the internal buffer.

Example

let decoder = new util.StringDecoder('utf-8');
let input = new Uint8Array([0xE4, 0xBD, 0xA0, 0xE5, 0xA5, 0xBD]);
const writeString = decoder.write(input.slice(0, 5));
const endString = decoder.end(input.slice(5));
console.info("writeString:", writeString);
// Output: writeString: Hello
console.info("endString:", endString);
// Output: endString: World

Type10+

Enumerates the Base64 encoding formats.

System capability: SystemCapability.Utils.Lang

Name Value Description
BASIC 0 Indicates the BASIC encoding format. Atomic service API: Since API version 11, this API is supported in atomic services.
MIME 1 Indicates the MIME encoding format. Atomic service API: Since API version 11, this API is supported in atomic services.
BASIC_URL_SAFE12+ 2

Indicates the BASIC_URL_SAFE encoding format.

This enum is supported since API version 12. Atomic service API: Since API version 12, this API is supported in atomic services.

MIME_URL_SAFE12+ 3

Indicates the MIME_URL_SAFE encoding format.

This enum is supported since API version 12. Atomic service API: Since API version 12, this API is supported in atomic services.

types8+

Provides APIs to check different types of built-in objects, such as ArrayBuffer, Map, and Set, so as to avoid exceptions caused by type errors.

[h2]constructor8+

constructor()

Constructor of Types, which creates a types instance for built-in object type checking.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Utils.Lang

Example

let type = new util.types();

[h2]isAnyArrayBuffer8+

isAnyArrayBuffer(value: Object): boolean

Checks whether the value is of the ArrayBuffer or SharedArrayBuffer type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the ArrayBuffer or SharedArrayBuffer type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isAnyArrayBuffer(new ArrayBuffer(0));
console.info("result = " + result);
// Output: result = true

[h2]isArrayBufferView8+

isArrayBufferView(value: Object): boolean

Checks whether the value is of the ArrayBufferView type.

ArrayBufferView is a type representing any of the following: Int8Array, Int16Array, Int32Array, Uint8Array, Uint8ClampedArray, Uint32Array, Float32Array, Float64Array, and DataView.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the ArrayBufferView type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isArrayBufferView(new Int8Array([]));
console.info("result = " + result);
// Output: result = true

[h2]isArgumentsObject8+

isArgumentsObject(value: Object): boolean

Checks whether the value is an arguments 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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is an arguments object; otherwise, false is returned.

Example

let type = new util.types();
function foo() {
    let result = type.isArgumentsObject(arguments);
    console.info("result = " + result);
}
let f = foo();
// Output: result = true

[h2]isArrayBuffer8+

isArrayBuffer(value: Object): boolean

Checks whether the value is of the ArrayBuffer type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the ArrayBuffer type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isArrayBuffer(new ArrayBuffer(0));
console.info("result = " + result);
// Output: result = true

[h2]isAsyncFunction8+

isAsyncFunction(value: Object): boolean

Checks whether the value is an asynchronous 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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is an asynchronous function; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isAsyncFunction(async () => {});
console.info("result = " + result);
// Output: result = true

This API cannot effectively determine an AsyncGenerator Function. It is recommended to obtain the constructor.name property of the function and compare it with 'AsyncGeneratorFunction' instead.

This API cannot effectively determine an async member function in a Sendable class. There is no alternative.

// /entry/src/main/ets/pages/test.ts
export async function* asyncGeneratorFunc() {}
import { asyncGeneratorFunc } from './test'

@Sendable
class SendableClass {
  async asyncFunction() {}
}

let type = new util.types();
let result1 = type.isAsyncFunction(asyncGeneratorFunc);
console.info("result = " + result1);
// Output: result = false

console.info("asyncGeneratorFunc.constructor.name === AsyncGeneratorFunction : " +
  (asyncGeneratorFunc.constructor.name === 'AsyncGeneratorFunction'));
// Output: asyncGeneratorFunc.constructor.name === AsyncGeneratorFunction : true

const instance = new SendableClass();
let result2 = type.isAsyncFunction(instance.asyncFunction);
console.info("result = " + result2);
// Output: result = false

[h2]isBooleanObject(deprecated)

isBooleanObject(value: Object): boolean

Checks whether the value is of the Boolean type.

This API is supported since API version 8 and deprecated since API version 14. There is no alternative API.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the Boolean type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isBooleanObject(new Boolean(true));
console.info("result = " + result);
// Output: result = true

[h2]isBoxedPrimitive(deprecated)

isBoxedPrimitive(value: Object): boolean

Checks whether the value is of the Boolean, Number, String, or Symbol type.

This API is supported since API version 8 and deprecated since API version 14. No substitute is provided.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the Boolean, Number, String, or Symbol type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isBoxedPrimitive(new Boolean(false));
console.info("result = " + result);
// Output: result = true

[h2]isDataView8+

isDataView(value: Object): boolean

Checks whether the value is of the DataView type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the DataView type; otherwise, false is returned.

Example

let type = new util.types();
const ab = new ArrayBuffer(20);
let result = type.isDataView(new DataView(ab));
console.info("result = " + result);
// Output: result = true

[h2]isDate8+

isDate(value: Object): boolean

Checks whether the value is of the Date type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the Date type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isDate(new Date());
console.info("result = " + result);
// Output: result = true

[h2]isExternal8+

isExternal(value: Object): boolean

Checks whether the value is of the native external type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the native external type; otherwise, false is returned.

Example

// /entry/src/main/cpp/napi_init.cpp
#include "napi/native_api.h"
#include <js_native_api.h>
#include <stdlib.h>

napi_value result;
static napi_value Testexternal(napi_env env, napi_callback_info info) {
    int* raw = (int*) malloc(1024);
    napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result);
    if (status != napi_ok) {
        napi_throw_error(env, NULL, "create external failed");
        return NULL;
    }
    return result;
}

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
    napi_property_descriptor desc[] = {
        {"testexternal", nullptr, Testexternal, nullptr, nullptr, nullptr, napi_default, nullptr},
    };
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END
// The code for module registration is omitted here. You may need to register the Testexternal method.
// ...
import testNapi from 'libentry.so';

let type = new util.types();
const data = testNapi.testexternal();
let result = type.isExternal(data);

let result01 = type.isExternal(true);
console.info("result = " + result);
console.info("result01 = " + result01);
// Output: result = true
// Output: result01 = false

[h2]isFloat32Array8+

isFloat32Array(value: Object): boolean

Checks whether the value is of the Float32Array type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the Float32Array type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isFloat32Array(new Float32Array());
console.info("result = " + result);
// Output: result = true

[h2]isFloat64Array8+

isFloat64Array(value: Object): boolean

Checks whether the value is of the Float64Array type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the Float64Array type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isFloat64Array(new Float64Array());
console.info("result = " + result);
// Output: result = true

[h2]isGeneratorFunction8+

isGeneratorFunction(value: Object): boolean

Checks whether the value is a generator 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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is a generator function; otherwise, false is returned.

Example

// /entry/src/main/ets/pages/test.ts
export function* foo() {}
import { foo } from './test'

let type = new util.types();
let result = type.isGeneratorFunction(foo);
console.info("result = " + result);
// Output: result = true

This API cannot effectively determine an AsyncGenerator Function. It is recommended to obtain the constructor.name property of the function and compare it with 'AsyncGeneratorFunction' instead.

// /entry/src/main/ets/pages/test.ts
export async function* asyncGeneratorFunc() {}
import { asyncGeneratorFunc } from './test'

let type = new util.types();
let result = type.isGeneratorFunction(asyncGeneratorFunc);
console.info("result = " + result);
// Output: result = false

console.info("asyncGeneratorFunc.constructor.name === AsyncGeneratorFunction : " +
  (asyncGeneratorFunc.constructor.name === 'AsyncGeneratorFunction'));
// Output: asyncGeneratorFunc.constructor.name === AsyncGeneratorFunction : true

[h2]isGeneratorObject8+

isGeneratorObject(value: Object): boolean

Checks whether the value is a generator 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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is a generator object; otherwise, false is returned.

Example

// /entry/src/main/ets/pages/test.ts
function* foo() {}
export const generator = foo();
import { generator } from './test'

let type = new util.types();
let result = type.isGeneratorObject(generator);
console.info("result = " + result);
// Output: result = true

[h2]isInt8Array8+

isInt8Array(value: Object): boolean

Checks whether the value is of the Int8Array type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the Int8Array type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isInt8Array(new Int8Array([]));
console.info("result = " + result);
// Output: result = true

[h2]isInt16Array8+

isInt16Array(value: Object): boolean

Checks whether the value is of the Int16Array type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the Int16Array type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isInt16Array(new Int16Array([]));
console.info("result = " + result);
// Output: result = true

[h2]isInt32Array8+

isInt32Array(value: Object): boolean

Checks whether the value is of the Int32Array type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the Int32Array type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isInt32Array(new Int32Array([]));
console.info("result = " + result);
// Output: result = true

[h2]isMap8+

isMap(value: Object): boolean

Checks whether the value is of the Map type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Returns true if the type is Map; returns false otherwise.

Example

let type = new util.types();
let result = type.isMap(new Map());
console.info("result = " + result);
// Output: result = true

[h2]isMapIterator8+

isMapIterator(value: Object): boolean

Checks whether the value is of the MapIterator type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the MapIterator type; otherwise, false is returned.

Example

let type = new util.types();
const map : Map<number,number> = new Map();
let result = type.isMapIterator(map.keys());
console.info("result = " + result);
// Output: result = true

[h2]isNativeError8+

isNativeError(value: Object): boolean

Checks whether the value is of the Error type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the Error type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isNativeError(new TypeError());
console.info("result = " + result);
// Output: result = true

[h2]isNumberObject(deprecated)

isNumberObject(value: Object): boolean

Checks whether the value is of the Number type.

This API is supported since API version 8 and deprecated since API version 14. No substitute is provided.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the Number type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isNumberObject(new Number(0));
console.info("result = " + result);
// Output: result = true

[h2]isPromise8+

isPromise(value: Object): boolean

Checks whether the value is 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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is a promise; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isPromise(Promise.resolve(1));
console.info("result = " + result);
// Output: result = true

[h2]isProxy8+

isProxy(value: Object): boolean

Checks whether the value is a proxy.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is a proxy; otherwise, false is returned.

Example

class Target{
}
let type = new util.types();
const target : Target = {};
const proxy = new Proxy(target, target);
let result = type.isProxy(proxy);
console.info("result = " + result);
// Output: result = true

[h2]isRegExp8+

isRegExp(value: Object): boolean

Checks whether the value is of the RegExp type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the RegExp type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isRegExp(new RegExp('abc'));
console.info("result = " + result);
// Output: result = true

[h2]isSet8+

isSet(value: Object): boolean

Checks whether the value is of the Set type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the Set type; otherwise, false is returned.

Example

let type = new util.types();
let set : Set<number> = new Set();
let result = type.isSet(set);
console.info("result = " + result);
// Output: result = true

[h2]isSetIterator8+

isSetIterator(value: Object): boolean

Checks whether the value is of the SetIterator type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the SetIterator type; otherwise, false is returned.

Example

let type = new util.types();
const set : Set<number> = new Set();
let result = type.isSetIterator(set.keys());
console.info("result = " + result);
// Output: result = true

[h2]isStringObject(deprecated)

isStringObject(value: Object): boolean

Checks whether the value is a string object.

This API is supported since API version 8 and deprecated since API version 14. No substitute is provided.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is a string object; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isStringObject(new String('foo'));
console.info("result = " + result);
// Output: result = true

[h2]isSymbolObject(deprecated)

isSymbolObject(value: Object): boolean

Checks whether the value is a symbol object.

This API is supported since API version 8 and deprecated since API version 14. No substitute is provided.

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
value Object Yes Object to check.

Return value

Type Description
boolean Returns true if the object is of the Symbol type; otherwise, returns false.

Example

// /entry/src/main/ets/pages/test.ts
export const symbols = Symbol('foo');
import { symbols } from './test'

let type = new util.types();
let result = type.isSymbolObject(Object(symbols));
console.info("result = " + result);
// Output: result = true

[h2]isTypedArray8+

isTypedArray(value: Object): boolean

Checks whether the value is of the TypedArray type.

TypedArray is a type representing any of the following: Int8Array, Int16Array, Int32Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, Float32Array, Float64Array, BigInt64Array, and BigUint64Array.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the TypedArray type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isTypedArray(new Float64Array([]));
console.info("result = " + result);
// Output: result = true

[h2]isUint8Array8+

isUint8Array(value: Object): boolean

Checks whether the value is of the Uint8Array type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the Uint8Array type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isUint8Array(new Uint8Array([]));
console.info("result = " + result);
// Output: result = true

[h2]isUint8ClampedArray8+

isUint8ClampedArray(value: Object): boolean

Checks whether the value is of the Uint8ClampedArray type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the Uint8ClampedArray type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isUint8ClampedArray(new Uint8ClampedArray([]));
console.info("result = " + result);
// Output: result = true

[h2]isUint16Array8+

isUint16Array(value: Object): boolean

Checks whether the value is of the Uint16Array type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the Uint16Array type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isUint16Array(new Uint16Array([]));
console.info("result = " + result);
// Output: result = true

[h2]isUint32Array8+

isUint32Array(value: Object): boolean

Checks whether the value is of the Uint32Array type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the Uint32Array type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isUint32Array(new Uint32Array([]));
console.info("result = " + result);
// Output: result = true

[h2]isWeakMap8+

isWeakMap(value: Object): boolean

Checks whether the value is of the WeakMap type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the WeakMap type; otherwise, false is returned.

Example

let type = new util.types();
let value : WeakMap<object, number> = new WeakMap();
let result = type.isWeakMap(value);
console.info("result = " + result);
// Output: result = true

[h2]isWeakSet8+

isWeakSet(value: Object): boolean

Checks whether the value is of the WeakSet type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the WeakSet type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isWeakSet(new WeakSet());
console.info("result = " + result);
// Output: result = true

[h2]isBigInt64Array8+

isBigInt64Array(value: Object): boolean

Checks whether the value is of the BigInt64Array type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the BigInt64Array type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isBigInt64Array(new BigInt64Array([]));
console.info("result = " + result);
// Output: result = true

[h2]isBigUint64Array8+

isBigUint64Array(value: Object): boolean

Checks whether the value is of the BigUint64Array type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the BigUint64Array type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isBigUint64Array(new BigUint64Array([]));
console.info("result = " + result);
// Output: result = true

[h2]isModuleNamespaceObject8+

isModuleNamespaceObject(value: Object): boolean

Checks whether the value is a module namespace 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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is a module namespace object; otherwise, false is returned.

Example

// /entry/src/main/ets/pages/test.ts
export function func() {
  console.info("hello world");
}
import * as nameSpace from './test';

let type = new util.types();
let result = type.isModuleNamespaceObject(nameSpace);
console.info("result = " + result);
// Output: result = true

[h2]isSharedArrayBuffer8+

isSharedArrayBuffer(value: Object): boolean

Checks whether the value is of the SharedArrayBuffer type.

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
value Object Yes Object to check.

Return value

Type Description
boolean Check result. The value true is returned if the value is of the SharedArrayBuffer type; otherwise, false is returned.

Example

let type = new util.types();
let result = type.isSharedArrayBuffer(new SharedArrayBuffer(0));
console.info("result = " + result);
// Output: result = true

AutoFinalizer<T>22+

AutoFinalizer is a class that provides callback APIs when an ArkTS object is released. By implementing it, you can customize the resource cleanup logic that triggers automatically when an object is reclaimed.

AutoFinalizer<T> must be used together with AutoFinalizerCleaner<T>. Implementing AutoFinalizer<T> alone will yield no functionality.

[h2]onFinalization22+

onFinalization(heldValue: T): void

Defines the resource cleanup callback that triggers automatically when an object is reclaimed.

Atomic service API: This API can be used in atomic services since API version 22.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
heldValue T Yes When the listened object is reclaimed, this value is passed to the onFinalization callback method.

AutoFinalizerCleaner<T>22+

AutoFinalizerCleaner is a utility class used to associate object lifecycle with resource cleanup logic, and it must be used together with AutoFinalizer<T>. Its main purpose is to bind an object that implements the AutoFinalizer<T> interface to a specific value, so that the resource cleanup callback is automatically triggered when the object is reclaimed. Using AutoFinalizerCleaner alone without implementing the AutoFinalizer interface has no effect.

[h2]register<T>22+

static register<T>(obj: AutoFinalizer<T>, heldValue: T): void

Associates an object implementing AutoFinalizer with an input value, and triggers the resource cleanup callback when the object is reclaimed.

Atomic service API: This API can be used in atomic services since API version 22.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
obj AutoFinalizer<T> Yes Object that implements AutoFinalizer. The onFinalization method is called when the object is reclaimed.
heldValue T Yes When the listened object is reclaimed, this value is passed to the obj.onFinalization method.

Example

class DeviceManageViewModel implements util.AutoFinalizer<string> {
  constructor(heldValue: string) {
    util.AutoFinalizerCleaner.register(this, heldValue);
  }

  onFinalization(heldValue: string) {
    console.info("onFinalization: ", heldValue);
    // Wait for the garbage collection to be triggered. Once it is triggered, the following result is displayed: onFinalization: test
  }
}

const device = new DeviceManageViewModel("test");

LruBuffer(deprecated)

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache9+ instead.

[h2]Properties

System capability: SystemCapability.Utils.Lang

Name Type Read-Only Optional Description
length number Yes No Total number of values in this cache.

Example

let pro : util.LruBuffer<number,number>= new util.LruBuffer();
pro.put(2,10);
pro.put(1,8);
let result = pro.length;
console.info("result = " + result);
// Output: result = 2

[h2]constructor(deprecated)

constructor(capacity?: number)

A constructor used to create a LruBuffer instance. The default capacity of the cache is 64.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.constructor9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
capacity number No Indicates the custom capacity for the buffer. The value range is [0, 2147483647], and the default value is 64.

Example

let pro : util.LruBuffer<number,number> = new util.LruBuffer();

[h2]updateCapacity(deprecated)

updateCapacity(newCapacity: number): void

Changes the cache capacity. If the new capacity is less than or equal to 0, an exception will be thrown.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.updateCapacity9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
newCapacity number Yes Indicates the capacity to be customized for the buffer, with a value range of [0, 2147483647].

Example

let pro : util.LruBuffer<number,number> = new util.LruBuffer();
pro.updateCapacity(100);

[h2]toString(deprecated)

toString(): string

Obtains the string representation of this cache.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.toString9+ instead.

System capability: SystemCapability.Utils.Lang

Return value

Type Description
string String representation of this cache.

Example

let pro : util.LruBuffer<number,number> = new util.LruBuffer();
pro.put(2,10);
pro.get(2);
pro.remove(20);
let result = pro.toString();
console.info("result = " + result);
// Output: result = Lrubuffer[ maxSize = 64, hits = 1, misses = 0, hitRate = 100% ]

[h2]getCapacity(deprecated)

getCapacity(): number

Obtains the capacity of this cache.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.getCapacity9+ instead.

System capability: SystemCapability.Utils.Lang

Return value

Type Description
number Capacity of the cache.

Example

let pro : util.LruBuffer<number,number> = new util.LruBuffer();
let result = pro.getCapacity();
console.info("result = " + result);
// Output: result = 64

[h2]clear(deprecated)

clear(): void

Clears the key-value pairs in the current buffer, and then calls the afterRemoval method to perform the operation.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.clear9+ instead.

System capability: SystemCapability.Utils.Lang

Example

let pro : util.LruBuffer<number,number> = new util.LruBuffer();
pro.put(2,10);
let result = pro.length;
pro.clear();

[h2]getCreateCount(deprecated)

getCreateCount(): number

Obtains the number of return values for createDefault().

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.getCreateCount9+ instead.

System capability: SystemCapability.Utils.Lang

Return value

Type Description
number Number of return values for createDefault().

Example

let pro : util.LruBuffer<number,number> = new util.LruBuffer();
pro.put(1,8);
let result = pro.getCreateCount();
console.info("result = " + result);
// Output: result = 0

[h2]getMissCount(deprecated)

getMissCount(): number

Obtains the number of times that the queried values are mismatched.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.getMissCount9+ instead.

System capability: SystemCapability.Utils.Lang

Return value

Type Description
number Number of times that the queried values are mismatched.

Example

let pro : util.LruBuffer<number,number> = new util.LruBuffer();
pro.put(2,10);
pro.get(2);
let result = pro.getMissCount();
console.info("result = " + result);
// Output: result = 0

[h2]getRemovalCount(deprecated)

getRemovalCount(): number

Obtains the number of removals from this cache.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.getRemovalCount9+ instead.

System capability: SystemCapability.Utils.Lang

Return value

Type Description
number Number of removals from the cache.

Example

let pro : util.LruBuffer<number,number> = new util.LruBuffer();
pro.put(2,10);
pro.updateCapacity(2);
pro.put(50,22);
let result = pro.getRemovalCount();
console.info("result = " + result);
// Output: result = 0

[h2]getMatchCount(deprecated)

getMatchCount(): number

Obtains the number of times that the queried values are matched.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.getMatchCount9+ instead.

System capability: SystemCapability.Utils.Lang

Return value

Type Description
number Number of times that the queried values are matched.

Example

let pro : util.LruBuffer<number,number> = new util.LruBuffer();
pro.put(2,10);
pro.get(2);
let result = pro.getMatchCount();
console.info("result = " + result);
// Output: result = 1

[h2]getPutCount(deprecated)

getPutCount(): number

Obtains the number of additions to this cache.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.getPutCount9+ instead.

System capability: SystemCapability.Utils.Lang

Return value

Type Description
number Number of additions to the cache.

Example

let pro : util.LruBuffer<number,number> = new util.LruBuffer();
pro.put(2,10);
let result = pro.getPutCount();
console.info("result = " + result);
// Output: result = 1

[h2]isEmpty(deprecated)

isEmpty(): boolean

Checks whether this cache is empty.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.isEmpty9+ instead.

System capability: SystemCapability.Utils.Lang

Return value

Type Description
boolean Returns true if the current buffer does not contain any value; otherwise returns false.

Example

let pro : util.LruBuffer<number,number> = new util.LruBuffer();
pro.put(2,10);
let result = pro.isEmpty();
console.info("result = " + result);
// Output: result = false

[h2]get(deprecated)

get(key: K): V | undefined

Returns the value corresponding to the key. If the key is not in the buffer, undefined is returned.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.get9+ instead.

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 Value of the key. If no match is found, undefined is returned.

Example

let pro : util.LruBuffer<number,number> = new util.LruBuffer();
pro.put(2,10);
let result  = pro.get(2);
console.info("result = " + result);
// Output: result = 10

[h2]put(deprecated)

put(key: K,value: V): V

Adds a key-value pair to this cache.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.put9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
key K Yes Key to be added.
value V Yes Value of the key-value pair to add.

Return value

Type Description
V Value added. If the key already exists, the existing value is returned; if null is passed in for key or value, an error is thrown.

Example

let pro : util.LruBuffer<number,number> = new util.LruBuffer();
let result = pro.put(2,10);
console.info("result = " + result);
// Output: result = 10

[h2]values(deprecated)

values(): V[]

Obtains all values in this cache, listed from the most to the least recently accessed.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.values9+ instead.

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

let pro : util.LruBuffer<number|string,number|string> = new util.LruBuffer();
pro.put(2,10);
pro.put(2,"anhu");
pro.put("afaf","grfb");
let result = pro.values();
console.info("result = " + result);
// Output: result = anhu,grfb

[h2]keys(deprecated)

keys(): K[]

Obtains all keys in this cache, listed from the most to the least recently accessed.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.keys9+ instead.

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

let pro : util.LruBuffer<number,number> = new util.LruBuffer();
pro.put(2,10);
let result = pro.keys();
console.info("result = " + result);
// Output: result = 2

[h2]remove(deprecated)

remove(key: K): V | undefined

Removes the specified key and its value from this cache.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.remove9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
key K Yes Key to be deleted.

Return value

Type Description
V | undefined Optional object containing the removed key-value pair. If the key does not exist, an empty Optional object is returned; if null is passed in for key, an error is thrown.

Example

let pro : util.LruBuffer<number,number> = new util.LruBuffer();
pro.put(2,10);
let result = pro.remove(20);
console.info("result = " + result);
// Output: result = undefined

[h2]afterRemoval(deprecated)

afterRemoval(isEvict: boolean,key: K,value: V,newValue: V): void

Performs subsequent operations after a value is removed.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.afterRemoval9+ instead.

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.

Example

class ChildLruBuffer<K, V> extends util.LruBuffer<K, V> {
  constructor(capacity?: number) {
    super(capacity);
  }

  afterRemoval(isEvict: boolean, key: K, value: V, newValue: V): void {
    if (isEvict === true) {
      console.info('key: ' + key);
      // Output: key: 11
      console.info('value: ' + value);
      // Output: value: 1
      console.info('newValue: ' + newValue);
      // Output: newValue: null
    }
  }
}
let lru: ChildLruBuffer<number, number> = new ChildLruBuffer(2);
lru.put(11, 1);
lru.put(22, 2);
lru.put(33, 3);

[h2]contains(deprecated)

contains(key: K): boolean

Checks whether this cache contains the specified key.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.contains9+ instead.

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 buffer contains the specified key; otherwise returns false.

Example

let pro : util.LruBuffer<number,number> = new util.LruBuffer();
pro.put(2,10);
let result = pro.contains(20);
console.info('result = ' + result);
// Output: result = false

[h2]createDefault(deprecated)

createDefault(key: K): V

When no matching key is found in the buffer, executes the subsequent processing logic. The parameter indicates the unmatched key, and the value associated with the key is returned, with undefined returned by default.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.createDefault9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
key K Yes Key of which the value is missing.

Return value

Type Description
V Value of the key.

Example

let pro : util.LruBuffer<number,number> = new util.LruBuffer();
let result = pro.createDefault(50);

[h2]entries(deprecated)

entries(): IterableIterator<[K, V]>

Obtains a new iterator object that contains all key-value pairs in this object.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.entries9+ instead.

System capability: SystemCapability.Utils.Lang

Return value

Type Description
IterableIterator<[K, V]> Iterable array.

Example

let pro : util.LruBuffer<number,number> = new util.LruBuffer();
pro.put(2,10);
let result = pro.entries();

[h2][Symbol.iterator](deprecated)

[Symbol.iterator](): IterableIterator<[K, V]>

Obtains a two-dimensional array in key-value pairs.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use LRUCache.[Symbol.iterator]9+ instead.

System capability: SystemCapability.Utils.Lang

Return value

Type Description
IterableIterator<[K, V]> Two-dimensional array in key-value pairs.

Example

let pro : util.LruBuffer<number,number> = new util.LruBuffer();
pro.put(2,10);
let result = pro[Symbol.iterator]();

Scope(deprecated)

This API is supported since API version 8 and deprecated since API version 9. You are advised to use ScopeHelper9+ instead.

[h2]constructor(deprecated)

constructor(lowerObj: ScopeType, upperObj: ScopeType)

A constructor used to create a Scope object with the specified upper and lower limits.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use ScopeHelper.constructor9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
lowerObj ScopeType Yes Lower limit of the Scope object.
upperObj ScopeType Yes Upper limit of the Scope object.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let range = new util.Scope(tempLower, tempUpper);
console.info("range = " + range);
// Output: range = [30, 40]

[h2]toString(deprecated)

toString(): string

Obtains a string representation that contains this Scope.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use ScopeHelper.toString9+ instead.

System capability: SystemCapability.Utils.Lang

Return value

Type Description
string String representation containing the Scope.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let range = new util.Scope(tempLower, tempUpper);
let result = range.toString();
console.info("result = " + result);
// Output: result = [30, 40]

[h2]intersect(deprecated)

intersect(range: Scope): Scope

Obtains the intersection of this Scope and the given Scope.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use ScopeHelper.intersect9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
range Scope Yes Scope specified.

Return value

Type Description
Scope Intersection of this Scope and the given Scope.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let range = new util.Scope(tempLower, tempUpper);
let tempMiDF = new Temperature(35);
let tempMidS = new Temperature(39);
let rangeFir = new util.Scope(tempMiDF, tempMidS);
let result = range.intersect(rangeFir );
console.info("result = " + result);
  // Output: result = [35, 39]

[h2]intersect(deprecated)

intersect(lowerObj:ScopeType,upperObj:ScopeType):Scope

Obtains the intersection of this Scope and the given lower and upper limits.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use ScopeHelper.intersect9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
lowerObj ScopeType Yes Lower limit.
upperObj ScopeType Yes Upper limit.

Return value

Type Description
Scope Intersection of this Scope and the given lower and upper limits.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let tempMiDF = new Temperature(35);
let tempMidS = new Temperature(39);
let range = new util.Scope(tempLower, tempUpper);
let result = range.intersect(tempMiDF, tempMidS);
console.info("result = " + result);
// Output: result = [35, 39]

[h2]getUpper(deprecated)

getUpper(): ScopeType

Obtains the upper limit of this Scope.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use ScopeHelper.getUpper9+ instead.

System capability: SystemCapability.Utils.Lang

Return value

Type Description
ScopeType Upper limit of this Scope.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let range = new util.Scope(tempLower, tempUpper);
let result = range.getUpper();
console.info("result = " + result);
// Output: result = 40

[h2]getLower(deprecated)

getLower(): ScopeType

Obtains the lower limit of this Scope.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use ScopeHelper.getLower9+ instead.

System capability: SystemCapability.Utils.Lang

Return value

Type Description
ScopeType Lower limit of this Scope.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let range = new util.Scope(tempLower, tempUpper);
let result = range.getLower();
console.info("result = " + result);
// Output: result = 30

[h2]expand(deprecated)

expand(lowerObj: ScopeType,upperObj: ScopeType): Scope

Obtains the union set of this Scope and the given lower and upper limits.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use ScopeHelper.expand9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
lowerObj ScopeType Yes Lower limit.
upperObj ScopeType Yes Upper limit.

Return value

Type Description
Scope Union set of this Scope and the given lower and upper limits.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let tempMiDF = new Temperature(35);
let tempMidS = new Temperature(39);
let range = new util.Scope(tempLower, tempUpper);
let result = range.expand(tempMiDF, tempMidS);
console.info("result = " + result);
// Output: result = [30, 40]

[h2]expand(deprecated)

expand(range: Scope): Scope

Obtains the union set of this Scope and the given Scope.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use ScopeHelper.expand9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
range Scope Yes Scope specified.

Return value

Type Description
Scope Union set of this Scope and the given Scope.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let tempMiDF = new Temperature(35);
let tempMidS = new Temperature(39);
let range = new util.Scope(tempLower, tempUpper);
let rangeFir = new util.Scope(tempMiDF, tempMidS);
let result = range.expand(rangeFir);
console.info("result = " + result);
// Output: result = [30, 40]

[h2]expand(deprecated)

expand(value: ScopeType): Scope

Obtains the union set of this Scope and the given value.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use ScopeHelper.expand9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
value ScopeType Yes Value specified.

Return value

Type Description
Scope Union set of this Scope and the given value.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let tempMiDF = new Temperature(35);
let range = new util.Scope(tempLower, tempUpper);
let result = range.expand(tempMiDF);
console.info("result = " + result);
// Output: result = [30, 40]

[h2]contains(deprecated)

contains(value: ScopeType): boolean

Checks whether a value is within this Scope.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use ScopeHelper.contains9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
value ScopeType Yes Value specified.

Return value

Type Description
boolean Check result. The value true is returned if the value is within this Scope; otherwise, false is returned.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let tempMiDF = new Temperature(35);
let range = new util.Scope(tempLower, tempUpper);
let result = range.contains(tempMiDF);
console.info("result = " + result);
// Output: result = true

[h2]contains(deprecated)

contains(range: Scope): boolean

Checks whether a range is within this Scope.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use ScopeHelper.contains9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
range Scope Yes Scope specified.

Return value

Type Description
boolean Check result. The value true is returned if the range is within this Scope; otherwise, false is returned.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let range = new util.Scope(tempLower, tempUpper);
let tempLess = new Temperature(20);
let tempMore = new Temperature(45);
let rangeSec = new util.Scope(tempLess, tempMore);
let result = range.contains(rangeSec);
console.info("result = " + result);
// Output: result = false

[h2]clamp(deprecated)

clamp(value: ScopeType): ScopeType

Limits a value to this Scope.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use ScopeHelper.clamp9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
value ScopeType Yes Value specified.

Return value

Type Description
ScopeType Returns lowerObj if the specified value is less than the lower limit; returns upperObj if the specified value is greater than the upper limit; returns the specified value if it is within this Scope.

Example

class Temperature implements util.ScopeComparable {
  private readonly _temp: number;

  constructor(value: number) {
    this._temp = value;
  }

  compareTo(value: Temperature) {
    return this._temp >= value.getTemp();
  }

  getTemp() {
    return this._temp;
  }

  toString(): string {
    return this._temp.toString();
  }
}

let tempLower = new Temperature(30);
let tempUpper = new Temperature(40);
let tempMiDF = new Temperature(35);
let range = new util.Scope(tempLower, tempUpper);
let result = range.clamp(tempMiDF);
console.info("result = " + result);
// Output: result = 35

Base64(deprecated)

This API is supported since API version 8 and deprecated since API version 9. You are advised to use Base64Helper9+ instead.

[h2]constructor(deprecated)

constructor()

A constructor used to create a Base64 object.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use Base64Helper.constructor9+ instead.

System capability: SystemCapability.Utils.Lang

Example

let base64 = new  util.Base64();

[h2]encodeSync(deprecated)

encodeSync(src: Uint8Array): Uint8Array

Performs Base64 encoding on the input Uint8Array byte array and returns the encoded Uint8Array.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use Base64Helper.encodeSync9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
src Uint8Array Yes Uint8Array object to encode.

Return value

Type Description
Uint8Array Uint8Array object obtained.

Example

let base64 = new util.Base64();
let array = new Uint8Array([115,49,51]);
let result = base64.encodeSync(array);
console.info("result = " + result);
// Output: result = 99,122,69,122

[h2]encodeToStringSync(deprecated)

encodeToStringSync(src: Uint8Array): string

Performs Base64 encoding on the input Uint8Array byte array and returns the encoded string.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use Base64Helper.encodeToStringSync9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
src Uint8Array Yes Uint8Array object to encode.

Return value

Type Description
string String obtained.

Example

let base64 = new util.Base64();
let array = new Uint8Array([115,49,51]);
let result = base64.encodeToStringSync(array);
console.info("result = " + result);
// Output: result = czEz

[h2]decodeSync(deprecated)

decodeSync(src: Uint8Array | string): Uint8Array

Decodes the input content into a Uint8Array object.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use Base64Helper.decodeSync9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
src Uint8Array | string Yes Uint8Array object or string to decode.

Return value

Type Description
Uint8Array Uint8Array object obtained.

Example

let base64 = new util.Base64();
let buff = 'czEz';
let result = base64.decodeSync(buff);
console.info("result = " + result);
// Output: result = 115,49,51

[h2]encode(deprecated)

encode(src: Uint8Array): Promise<Uint8Array>

Encodes the input content into a Uint8Array object. This API uses a promise to return the result.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use Base64Helper.encode9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
src Uint8Array Yes Uint8Array object to encode.

Return value

Type Description
Promise<Uint8Array> Promise used to return the Uint8Array object obtained.

Example

let base64 = new util.Base64();
let array = new Uint8Array([115,49,51]);
base64.encode(array).then((val) => {
  console.info(val.toString());
  // Output: 99,122,69,122
})

[h2]encodeToString(deprecated)

encodeToString(src: Uint8Array): Promise<string>

Encodes the input content into a string. This API uses a promise to return the result.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use Base64Helper.encodeToString9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
src Uint8Array Yes Uint8Array object to encode.

Return value

Type Description
Promise<string> Promise used to return the string obtained.

Example

let base64 = new util.Base64();
let array = new Uint8Array([115,49,51]);
base64.encodeToString(array).then((val) => {
    console.info(val);
    // Output: czEz
})

[h2]decode(deprecated)

decode(src: Uint8Array | string): Promise<Uint8Array>

Decodes the input content into a Uint8Array object. This API uses a promise to return the result.

This API is supported since API version 8 and deprecated since API version 9. You are advised to use Base64Helper.decode9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
src Uint8Array | string Yes Uint8Array object or string to decode.

Return value

Type Description
Promise<Uint8Array> Promise used to return the Uint8Array object obtained.

Example

let base64 = new util.Base64();
let array = new Uint8Array([99,122,69,122]);
base64.decode(array).then((val) => {
  console.info(val.toString());
  // Output: 115,49,51
})