From 146f255b016765968c5b2db881b859256a518ac2 Mon Sep 17 00:00:00 2001 From: lifansheng Date: Sun, 26 Sep 2021 21:03:22 +0800 Subject: [PATCH 1/3] Signed-off-by: lifansheng On branch OpenHarmony-3.0-LTS Your branch is up to date with 'origin/OpenHarmony-3.0-LTS'. Changes to be committed: new file: README.en.md modified: README.md deleted: README_zh.md deleted: lrubuffer/BUILD.gn deleted: lrubuffer/js_lrubuffer.js deleted: lrubuffer/native_module_lrubuffer.cpp modified: ohos.build deleted: scope/BUILD.gn deleted: scope/native_module_scope.cpp deleted: scope/scope_js.js modified: util/BUILD.gn modified: util/util_js.js --- README.en.md | 655 ++++++++++++++++++++++++++ README.md | 600 ++++++++++++++++++++--- README_zh.md | 165 ------- lrubuffer/BUILD.gn | 59 --- lrubuffer/js_lrubuffer.js | 192 -------- lrubuffer/native_module_lrubuffer.cpp | 61 --- ohos.build | 4 +- scope/BUILD.gn | 59 --- scope/native_module_scope.cpp | 63 --- scope/scope_js.js | 147 ------ util/BUILD.gn | 34 ++ util/util_js.js | 394 +++++++++++++++- 12 files changed, 1618 insertions(+), 815 deletions(-) create mode 100644 README.en.md delete mode 100755 README_zh.md delete mode 100755 lrubuffer/BUILD.gn delete mode 100755 lrubuffer/js_lrubuffer.js delete mode 100755 lrubuffer/native_module_lrubuffer.cpp delete mode 100755 scope/BUILD.gn delete mode 100755 scope/native_module_scope.cpp delete mode 100755 scope/scope_js.js diff --git a/README.en.md b/README.en.md new file mode 100644 index 0000000..e3b2128 --- /dev/null +++ b/README.en.md @@ -0,0 +1,655 @@ +# js_util_module Subsystems / components + +- [Introduction](#Introduction) +- [Directory](#Directory) +- [Description](#Description) + - [Interface description](#Interface description) + - [Instruction for use](#Instruction for use) + +- [Related warehouse](#Related warehouse) + +## Introduction +The interface of util is used for character Textencoder, TextDecoder and HelpFunction module.The TextEncoder represents a text encoder that accepts a string as input, encodes it in UTF-8 format, and outputs UTF-8 byte stream. The TextDecoder interface represents a text decoder. The decoder takes the byte stream as the input and outputs the Stirng string. HelpFunction is mainly used to callback and promise functions, write and output error codes, and format class strings. +Encodes all bytes from the specified u8 array into a newly-allocated u8 array using the Base64 encoding scheme or Encodes the specified byte array into a String using the Base64 encoding scheme.Decodes a Base64 encoded String or input u8 array into a newly-allocated u8 array using the Base64 encoding scheme.The rational number is mainly to compare rational numbers and obtain the numerator and denominator.LruBuffer The algorithm replaces the least used data with new data when the buffer space is insufficient. The algorithm derives from the need to access resources: recently accessed data can be Will visit again in the near future. The least accessed data is the least valuable data that should be kicked out of the cache space. The Scope interface is used to describe the valid range of a field. The constructor for the Scope instance is used to create objects with specified lower and upper bounds and require that these objects be comparable + +## 目录 + +``` +base/compileruntime/js_util_module/ +├── Class:TextEncoder # TextEncoder class +│ ├── new TextEncoder() # create textencoder object +│ ├── encode() # encode method +│ ├── encoding # encoding property +│ └── encodeInto() # encodeInto method +├── Class:TextDecoder # TextDecoder class +│ ├── new TextDecoder() # create TextDecoder object +│ ├── decode() # decode method +│ ├── encoding # encoding property +│ ├── fatal # fatal property +│ └── ignoreBOM # ignoreBOM property +├── printf() # printf method +├── getErrorString() # getErrorString method +├── callbackWrapper() # callbackWrapper method +├── promiseWrapper() # promiseWrapper method +├── Class:Base64 # Base64 class +│ ├── new Base64() # create Base64 object +│ ├── encode() # encode method +│ ├── encodeToString() # encodeToString method +│ └── decode() # decode method +├── Class:RationalNumber # RationalNumber class +│ ├── new RationalNumber() # create RationalNumber object +│ ├── CreateRationalFromString() # CreatRationalFromString method +│ ├── CompareTo() # CompareTo method +│ ├── Equals() # Equals method +│ ├── Value() # Value method +│ ├── GetCommonDivisor() # GetCommonDivisor method +│ ├── GetDenominator() # GetDenominator method +│ ├── GetNumerator() # GetNumerator method +│ ├── IsFinite() # IsFinite method +│ ├── IsNaN() # IsNaN method +│ ├── IsZero() # IsZero method +│ └── ToString() # ToString method +├── Class:LruBuffer # LruBuffer class +│ ├── new LruBuffer() # create RationalNumber object +│ ├── updateCapacity() # updateCapacity method +│ ├── toString() # toString method +│ ├── values() # values method +│ ├── size() # size method +│ ├── capacity() # capacity method +│ ├── clear() # clear method +│ ├── getCreateCount # getCreateCount method +│ ├── getMissCount() # getMissCount method +│ ├── getRemovalCount() # getRemovalCount method +│ ├── getMatchCount() # getMatchCount method +│ ├── getPutCount() # getPutCount method +│ ├── isEmpty() # isEmpty method +│ ├── get() # get method +│ ├── put() # put method +│ ├── keys() # keys method +│ ├── remove() # remove method +│ ├── afterRemoval() # afterRemoval method +│ ├── contains() # contains method +│ ├── createDefault() # createDefault method +│ ├── entries() # entries method +│ └── [Symbol.iterator]() # Symboliterator method +└── Class:Scope # Scope class + ├── constructor() # create Scope object + ├── toString() # toString method + ├── intersect() # intersect method + ├── intersect() # intersect method + ├── getUpper() # getUpper method + ├── getLower() # getLower method + ├── expand() # expand method + ├── expand() # expand method + ├── expand() # expand method + ├── contains() # contains method + ├── contains() # contains method + └── clamp() # clamp method +``` + +## Description + +### Interface description + + +| Interface name | Description | +| -------- | -------- | +| readonly encoding : string | Get the encoding format, only UTF-8 is supported. | +| encode(input : string) : Uint8Array | Input stirng string, encode and output UTF-8 byte stream. | +| encodeInto(input : string, dest : Uint8Array) : {read : number, written : number} | Enter the stirng string, dest represents the storage location after encoding, and returns an object, read represents the number of characters that have been encoded,and written represents the size of bytes occupied by the encoded characters. | +| constructor(encoding? : string, options? : {fatal? : boolean, ignoreBOM? : boolean}) | Constructor, the first parameter encoding indicates the format of decoding.The second parameter represents some attributes.Fatal in the attribute indicates whether an exception is thrown, and ignoreBOM indicates whether to ignore the bom flag. | +| readonly encoding : string | Get the set decoding format. | +| readonly fatal : boolean | Get the setting that throws the exception. | +| readonly ignoreBOM : boolean | Get whether to ignore the setting of the bom flag. | +| decode(input : ArrayBuffer | Input the data to be decoded, and solve the corresponding string character string.The first parameter input represents the data to be decoded, and the second parameter options represents a bool flag, which means that additional data will be followed. The default is false. | +| function printf(format: string, ...args: Object[]): string | The util.format() method returns a formatted string using the first argument as a printf-like format string which can contain zero or more format specifiers. | +| function getErrorString(errno: number): string | The geterrorstring () method uses a system error number as a parameter to return system error information. | +| function callbackWrapper(original: Function): (err: Object, value: Object) => void | Takes an async function (or a function that returns a Promise) and returns a function following the error-first callback style, i.e. taking an (err, value) => ... callback as the last argument. In the callback, the first argument will be the rejection reason (or null if the Promise resolved), and the second argument will be the resolved value. | +| function promiseWrapper(original: (err: Object, value: Object) => void): Object | Takes a function following the common error-first callback style, i.e. taking an (err, value) => ... callback as the last argument, and returns a version that returns promises. | +| encode(src: Uint8Array): Uint8Array; | Encodes all bytes from the specified u8 array into a newly-allocated u8 array using the Base64 encoding scheme. | +| encodeToString(src: Uint8Array): string; | Encodes the specified byte array into a String using the Base64 encoding scheme. | +| decode(src: Uint8Array | string): Uint8Array; | +| Decodes a Base64 encoded String or input u8 array into a newly-allocated u8 array using the Base64 encoding scheme. || +| CreateRationalFromString(src: string): Rational | Create a RationalNumber object based on the given string | +| CompareTo(src: RationalNumber): number | Compare the current RationalNumber object with the given object | +| Equals(src: object): number | Check if the given object is the same as the current RationalNumber object | +| Value(): number | Take the current RationalNumber object to an integer value or a floating point value | +| GetCommonDivisor(arg1: int, arg2: int,): number | Obtain the greatest common divisor of two specified numbers | +| GetDenominator(): number | Get the denominator of the current RationalNumber object | +| GetNumerator(): number | Get the numerator of the current RationalNumber object | +| IsFinite(): bool | Check that the current RationalNumber object is limited | +| IsNaN(): bool | Check whether the current RationalNumber object represents a non-number (NaN) value | +| IsZero(): bool | Check whether the current RationalNumber object represents a zero value | +| ToString(): string | Get the string representation of the current RationalNumber object | +| updateCapacity(newCapacity:number):void | Updates the buffer capacity to the specified capacity. This exception is thrown if newCapacity is less than or equal to 0 | +| toString():string | Returns the string representation of the object and outputs the string representation of the object | +| values():V[ ] | Gets a list of all values in the current buffer, and the output returns a list of all values in the current buffer in ascending order, from most recently accessed to least recently accessed | +| size():number | Gets the total number of values in the current buffer. The output returns the total number of values in the current buffer | +| capacity():number | Gets the capacity of the current buffer. The output returns the capacity of the current buffer | +| clear():void | The key value pairs are cleared from the current buffer, after the key value is cleared, the afterRemoval () method is invoked to perform subsequent operations in turn | +| getCreateCount():number | Get the number of times the returned value of createdefault(), and output the number of times the returned value of createdefault() | +| getMissCount():number | Get the number of times the query value does not match, and output the number of times the query value does not match | +| getRemovalCount():number | Gets the number of evictions from the buffer, and outputs the number of evictions from the buffer | +| getMatchCount​():number | Obtain the number of successful matching of query values, and output the number of successful matching of query values | +| getPutCount():number | Gets the number of times the value was added to the buffer, and the output returns the number of times the value was added to the buffer | +| isEmpty():boolean | Checks whether the current buffer is empty and returns true if the current buffer does not contain any values | +| get(k:key):V / undefined | Indicates the key to query. If the specified key exists in the buffer, the value associated with the key will be returned; Otherwise, undefined is returned | +| put(K key, V value):V | Adding the key value pair to the buffer and outputting the value associated with the added key; If the key to be added already exists, the original value is returned. If the key or value is empty, this exception is thrown | +| keys():V[ ] | Get the key list of the value in the current buffer, and the output returns the key list sorted from the most recent access to the least recent access | +| remove​(k:key):V / undefined | Deletes the specified key and its associated value from the current buffer | +| afterRemoval(boolean isEvict, K key, V value, V newValue):void | Perform subsequent operations after deleting the value | +| contains(k:key):boolean | Checks whether the current buffer contains the specified key, and returns true if the buffer contains the specified key | +| createDefault(k:key):V | If the value of a specific key is not calculated, subsequent operations are performed. The parameter represents the missing key, and the output returns the value associated with the key | +| entries() : [K,V] | Allows you to iterate over all key / value pairs contained in this object. The keys and values of each pair are objects | +| [Symbol.iterator]():[K,V]| Returns a two-dimensional array in the form of key value pairs | +| constructor(lowerObj: ScopeType, upperObj: ScopeType) | Creates and returns a Scope object that creates a constructor for a scope instance that specifies a lower and upper bound. | +| toString():string | The stringification method returns a string representation that contains the current range. | +| intersect(range: Scope): Scope | This method returns the intersection of a given range and the current range. | +| intersect(lowerObj: ScopeType, upperObj: ScopeType): Scope | Passing in the upper and lower bounds of the given range returns the intersection of the current range and the range specified by the given lower and upper bounds. | +| getUpper(): ScopeType | Gets the upper bound of the current scope and returns a value of type ScopeType. | +| getLower(): ScopeType | Gets the lower bound of the current scope and returns a value of type ScopeType. | +| expand(lowerObj: ScopeType, upperObj: ScopeType): Scope | This method creates and returns a union that includes the current range and a given lower and upper bound. | +| expand(range: Scope): Scope | This method creates and returns a union that includes the current range and the given range. | +| expand(value: ScopeType): Scope | This method creates and returns a union that includes the current range and the given value. | +| contains(value: ScopeType): boolean | Checks whether the given value is included in the current range. If yes, true is returned. Otherwise, false is returned. | +| contains(range: Scope): boolean | Checks whether the given range is within the current range. Returns true if in, false otherwise. | +| clamp(value: ScopeType): ScopeType | Clips the specified value to the current range. If the value is less than the lower limit, lowerObj is returned. If the value is greater than the upper limit, upperObj is returned. Returns value if within the current range. | + +Each specifier in printf is replaced with a converted value from the corresponding parameter. Supported specifiers are: +| Stylized character | Style requirements | +| -------- | -------- | +| %s: | String will be used to convert all values except BigInt, Object and -0. | +| %d: | Number will be used to convert all values except BigInt and Symbol. | +| %i: | parseInt(value, 10) is used for all values except BigInt and Symbol. | +| %f: | parseFloat(value) is used for all values expect Symbol. | +| %j: | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| %o: | Object. A string representation of an object with generic JavaScript object formatting. Similar to util.inspect() with options { showHidden: true, showProxy: true }. This will show the full object including non-enumerable properties and proxies. | +| %O: | Object. A string representation of an object with generic JavaScript object formatting. Similar to util.inspect() without options. This will show the full object not including non-enumerable properties and proxies. | +| %c: | CSS. This specifier is ignored and will skip any CSS passed in. | +| %%: | single percent sign ('%'). This does not consume an argument. | + +### Instruction for use + + +The use methods of each interface are as follows: + +1.readonly encoding() + +``` +import util from '@ohos.util' +var textEncoder = new util.TextEncoder(); +var getEncoding = textEncoder.encoding(); +``` +2.encode() +``` +import util from '@ohos.util' +var textEncoder = new util.TextEncoder(); +var result = textEncoder.encode('abc'); +``` +3.encodeInto() +``` +import util from '@ohos.util' +var textEncoder = new util.TextEncoder(); +var obj = textEncoder.encodeInto('abc', dest); +``` +4.textDecoder() +``` +import util from '@ohos.util' +var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); +``` +5.readonly encoding() +``` +import util from '@ohos.util' +var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); +var getEncoding = textDecoder.encoding(); +``` +6.readonly fatal() +``` +import util from '@ohos.util' +var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); +var fatalStr = textDecoder.fatal(); +``` +7.readonly ignoreBOM() +``` +import util from '@ohos.util' +var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); +var ignoreBom = textDecoder.ignoreBOM(); +``` +8.decode() +``` +import util from '@ohos.util' +var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); +var result = textDecoder.decode(input, {stream : true}); +``` +9.printf() +``` +import util from '@ohos.util' +var format = "%%%o%%%i%s"; +var value = function aa(){}; +var value1 = 1.5; +var value2 = "qwer"; +var result = util.printf(format,value,value1,value2); +``` +10.getErrorString() +``` +import util from '@ohos.util' +var errnum = 13; +var result = util.getErrorString(errnum); +``` +11.callbackWrapper() +``` +import util from '@ohos.util' +async function promiseFn() { + return Promise.resolve('value'); +}; +var cb = util.callbackWrapper(promiseFn); +cb((err, ret) => { + expect(err).strictEqual(null); + expect(ret).strictEqual('value'); +}) +``` +12.promiseWrapper() +``` +import util from '@ohos.util' +function aysnFun(str1, str2, callback) { + if (typeof str1 === 'string' && typeof str1 === 'string') { + callback(null, str1 + str2); + } else { + callback('type err'); + } +} +let newPromiseObj = util.promiseWrapper(aysnFun)("Hello", 'World'); +newPromiseObj.then(res => { + expect(res).strictEqual('HelloWorld'); +}) +``` +13.encode() +``` +import util from '@ohos.util' +var that = new util.Base64(); +var array = new Uint8Array([115,49,51]); +var num = 0; +var result = that.encode(array,num); +``` +14.encodeToString() +``` +import util from '@ohos.util' +var that = new util.Base64(); +var array = new Uint8Array([115,49,51]); +var num = 0; +var result = that.encodeToString(array,num); +``` +15.decode() +``` +import util from '@ohos.util' +var that = new util.Base64() +var buff = 'czEz'; +var num = 0; +var result = that.decode(buff,num); +``` +16.createRationalFromString() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(0, 0); +var res = pro.createRationalFromString("-1:2"); +var result1 = res.value(); +``` +17.compareTo() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(2, 1); +var proc = new util.RationalNumber(3, 4); +var res = pro.compareTo(proc); +``` +18.equals() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(2, 1); +var proc = new util.RationalNumber(3, 4); +var res = pro.equals(proc); +``` +19.value() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(2, 1); +var res = pro.value(); +``` +20.getCommonDivisor() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(0, 0); +var res = pro.getCommonDivisor(4, 8); +``` +21.getDenominator() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(2, 1); +var res = pro.getDenominator(); +``` +22.getNumerator() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.getNumerator(); +``` +23.isFinite() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.isFinite(); +``` +24.isNaN() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.isNaN(); +``` +25.isZero() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.isZero(); +``` +26.toString() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.toString(); +``` +27.updateCapacity() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.updateCapacity(100); +``` +28.toString() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.get(2); +pro.remove(20); +var temp = pro.toString(); +``` +29.values() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.put(2,"anhu"); +pro.put("afaf","grfb"); +var temp = pro.values(); +``` +30.size() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.put(1,8); +var temp = pro.size(); +``` +31.capacity() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +var temp = pro.capacity(); +``` +32.clear() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.clear(); +``` +33.getCreatCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(1,8); +var temp = pro.getCreatCount(); +``` +34.getMissCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.get(2) +var temp = pro.getMissCount(); +``` +35.getRemovalCount() +``` + +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.updateCapacity(2); +pro.put(50,22); +var temp = pro.getRemovalCount(); + +``` +36.getMatchCount +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.get(2); +var temp5 = pro.getMatchCount(); +``` +37.getPutCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var temp = pro.getPutCount(); +``` +38.isEmpty() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var temp = pro.isEmpty(); +``` +39.get() + +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var temp = pro.get(2); +``` +40.put() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +var temp = pro.put(2,10); +``` +41.keys() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var temp = pro.keys(); +``` +42.remove() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var temp = pro.remove(20); +``` +43.contains() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var temp = pro.contains(20); +``` +44.createDefault() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +var trmp = pro .createDefault(50); +``` +45.entries() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var temp = pro.entries(); +``` +46.[Symbol.iterator]() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro .put(2,10); +var temp = pro[symbol.iterator](); +``` +Construct a new class in the scope interface to implement the compareTo method. + +``` +class Temperature { + constructor(value) { + this._temp = value; + } + compareTo(value) { + return this._temp >= value.getTemp(); + } + getTemp() { + return this._temp; + } + toString() { + return this._temp.toString(); + } +} +``` + +47.constructor() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +``` + +48.toString() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +range.toString() // => [30,40] +``` + +49.intersect() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +var tempMiDF = new Temperature(35); +var tempMidS = new Temperature(39); +var rangeFir = new Scope(tempMiDF, tempMidS); +range.intersect(rangeFir) // => [35,39] +``` + +50.intersect() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var tempMidS = new Temperature(39); +var range = new Scope(tempLower, tempUpper); +range.intersect(tempMiDF, tempMidS) // => [35,39] +``` + +51.getUpper() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +range.getUpper() // => 40 +``` + +52.getLower() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +range.getLower() // => 30 +``` + +53.expand() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var tempMidS = new Temperature(39); +var range = new Scope(tempLower, tempUpper); +range.expand(tempMiDF, tempMidS) // => [30,40] +``` + +54.expand() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var tempMidS = new Temperature(39); +var range = new Scope(tempLower, tempUpper); +var rangeFir = new Scope(tempMiDF, tempMidS); +range.expand(rangeFir) // => [30,40] +``` + +55.expand() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var range = new Scope(tempLower, tempUpper); +range.expand(tempMiDF) // => [30,40] +``` + +56.contains() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var range = new Scope(tempLower, tempUpper); +range.contains(tempMiDF) // => true +``` + +57.contains() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +var tempLess = new Temperature(20); +var tempMore = new Temperature(45); +var rangeSec = new Scope(tempLess, tempMore); +range.contains(rangeSec) // => true +``` + +58.clamp() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var range = new Scope(tempLower, tempUpper); +range.clamp(tempMiDF) // => 35 +``` + + + +## Related warehouse + +[js_util_module subsystem](https://gitee.com/OHOS_STD/js_util_module) + +[base/compileruntime/js_util_module/](base/compileruntime/js_util_module-readme.md) diff --git a/README.md b/README.md index 6f8cdb5..b6dd59c 100755 --- a/README.md +++ b/README.md @@ -1,75 +1,179 @@ -# js_util_module Subsystems / components +# js_util_module子系统/组件 -- [Introduction](#Introduction) -- [Directory](#Directory) -- [Description](#Description) - - [Interface description](#Interface description) - - [Instruction for use](#Instruction for use) +- [简介](#简介) +- [目录](#目录) +- [说明](#说明) + - [接口说明](#接口说明) + - [使用说明](#使用说明) + +- [相关仓](#相关仓) + +## 简介 + +UTIL接口用于字符编码TextEncoder、解码TextDecoder、帮助函数HelpFunction、基于Base64的字节编码encode和解码decode、有理数RationalNumber。TextEncoder表示一个文本编码器,接受字符串作为输入,以UTF-8格式进行编码,输出UTF-8字节流。TextDecoder接口表示一个文本解码器,解码器将字节流作为输入,输出stirng字符串。HelpFunction主要是对函数做callback化、promise化以及对错误码进行编写输出,及类字符串的格式化输出。encode接口使用Base64编码方案将指定u8数组中的所有字节编码到新分配的u8数组中或者使用Base64编码方案将指定的字节数组编码为String。decode接口使用Base64编码方案将Base64编码的字符串或输入u8数组解码为新分配的u8数组。rationalnumber有理数主要是对有理数进行比较,获取分子分母等方法。LruBuffer该算法在缓存空间不够的时候,将近期最少使用的数据替换为新数据。该算法源自这样一种访问资源的需求:近期访问的数据,可能在不久的将来会再次访问。于是最少访问的数据就是价值最小的,是最应该踢出缓存空间的数据。Scope接口用于描述一个字段的有效范围。 Scope实例的构造函数用于创建具有指定下限和上限的对象,并要求这些对象必须具有可比性。 -- [Related warehouse](#Related warehouse) -## Introduction -The interface of util is used for character Textencoder, TextDecoder and HelpFunction module.The TextEncoder represents a text encoder that accepts a string as input, encodes it in UTF-8 format, and outputs UTF-8 byte stream. The TextDecoder interface represents a text decoder. The decoder takes the byte stream as the input and outputs the Stirng string. HelpFunction is mainly used to callback and promise functions, write and output error codes, and format class strings. ## 目录 ``` base/compileruntime/js_util_module/ -├── Class:TextEncoder # TextEncoder class -│ ├── new TextEncoder() # create textencoder object -│ ├── encode() # encode method -│ ├── encoding # encoding property -│ └── encodeInto() # encodeInto method -├── Class:TextDecoder # TextDecoder class -│ ├── new TextDecoder() # create TextDecoder object -│ ├── decode() # decode method -│ ├── encoding # encoding property -│ ├── fatal # fatal property -│ └── ignoreBOM # ignoreBOM property -├── printf() # printf method -├── getErrorString() # getErrorString method -├── callbackWrapper() # callbackWrapper method -└── promiseWrapper() # promiseWrapper method +├── Class:TextEncoder # TextEncoder类 +│ ├── new TextEncoder() # 创建TextEncoder对象 +│ ├── encode() # encode方法 +│ ├── encoding # encoding属性 +│ └── encodeInto() # encodeInto方法 +├── Class:TextDecoder # TextDecoder类 +│ ├── new TextDecoder() # 创建TextDecoder对象 +│ ├── decode() # decode方法 +│ ├── encoding # encoding属性 +│ ├── fatal # fatal属性 +│ └── ignoreBOM # ignoreBOM属性 +├── printf() # printf方法 +├── getErrorString() # getErrorString方法 +├── callbackWrapper() # callbackWrapper方法 +├── promiseWrapper() # promiseWrapper方法 +├── Class:Base64 # Base64类 +│ ├── new Base64() # 创建Base64对象 +│ ├── encode() # encode方法 +│ ├── encodeToString() # encodeToString方法 +│ └── decode() # decode方法 +├── Class:RationalNumber # RationalNumber类 +│ ├── new RationalNumber() # 创建RationalNumber对象 +│ ├── CreateRationalFromString() # CreateRationalFromString方法 +│ ├── CompareTo() # CompareTo方法 +│ ├── Equals() # Equals方法 +│ ├── Value() # Value方法 +│ ├── GetCommonDivisor() # GetCommonDivisor方法 +│ ├── GetDenominator() # GetDenominator方法 +│ ├── GetNumerator() # GetNumerator方法 +│ ├── IsFinite() # IsFinite方法 +│ ├── IsNaN() # IsNaN方法 +│ ├── IsZero() # IsZero方法 +│ └── ToString() # ToString方法 +├── Class:LruBuffer # LruBuffer类 +│ ├── new LruBuffer() # 创建LruBuffer对象 +│ ├── updateCapacity() # updateCapacity方法 +│ ├── toString() # toString方法 +│ ├── values() # values方法 +│ ├── size() # size方法 +│ ├── capacity() # capacity方法 +│ ├── clear() # clear方法 +│ ├── getCreateCount() # getCreateCount方法 +│ ├── getMissCount() # getMissCount方法 +│ ├── getRemovalCount() # getRemovalCount方法 +│ ├── getMatchCount() # getMatchCount方法 +│ ├── getPutCount() # getPutCount方法 +│ ├── isEmpty() # isEmpty方法 +│ ├── get() # get方法 +│ ├── put() # put方法 +│ ├── keys() # keys方法 +│ ├── remove() # remove方法 +│ ├── afterRemoval() # afterRemoval方法 +│ ├── contains() # contains方法 +│ ├── createDefault() # createDefault方法 +│ ├── entries() # entries方法 +│ └── [Symbol.iterator]() # Symboliterator方法 +└── Class:Scope # Scope类 + ├── constructor() # 创建Scope对象 + ├── toString() # toString方法 + ├── intersect() # intersect方法 + ├── intersect() # intersect方法 + ├── getUpper() # getUpper方法 + ├── getLower() # getLower方法 + ├── expand() # expand方法 + ├── expand() # expand方法 + ├── expand() # expand法 + ├── contains() # contains方法 + ├── contains() # contains方法 + └── clamp() # clamp方法 ``` -## Description +## 说明 -### Interface description +### 接口说明 -| Interface name | Description | +| 接口名 | 说明 | | -------- | -------- | -| readonly encoding : string | Get the encoding format, only UTF-8 is supported. | -| encode(input : string) : Uint8Array | Input stirng string, encode and output UTF-8 byte stream. | -| encodeInto(input : string, dest : Uint8Array) : {read : number, written : number} | Enter the stirng string, dest represents the storage location after encoding, and returns an object, read represents the number of characters that have been encoded,and written represents the size of bytes occupied by the encoded characters. | -| constructor(encoding? : string, options? : {fatal? : boolean, ignoreBOM? : boolean}) | Constructor, the first parameter encoding indicates the format of decoding.The second parameter represents some attributes.Fatal in the attribute indicates whether an exception is thrown, and ignoreBOM indicates whether to ignore the bom flag. | -| readonly encoding : string | Get the set decoding format. | -| readonly fatal : boolean | Get the setting that throws the exception. | -| readonly ignoreBOM : boolean | Get whether to ignore the setting of the bom flag. | -| decode(input : ArrayBuffer | Input the data to be decoded, and solve the corresponding string character string.The first parameter input represents the data to be decoded, and the second parameter options represents a bool flag, which means that additional data will be followed. The default is false. | -| function printf(format: string, ...args: Object[]): string | The util.format() method returns a formatted string using the first argument as a printf-like format string which can contain zero or more format specifiers. | -| function getErrorString(errno: number): string | The geterrorstring () method uses a system error number as a parameter to return system error information. | -| function callbackWrapper(original: Function): (err: Object, value: Object) => void | Takes an async function (or a function that returns a Promise) and returns a function following the error-first callback style, i.e. taking an (err, value) => ... callback as the last argument. In the callback, the first argument will be the rejection reason (or null if the Promise resolved), and the second argument will be the resolved value. | -| function promiseWrapper(original: (err: Object, value: Object) => void): Object | Takes a function following the common error-first callback style, i.e. taking an (err, value) => ... callback as the last argument, and returns a version that returns promises. | - -Each specifier in printf is replaced with a converted value from the corresponding parameter. Supported specifiers are: -| Stylized character | Style requirements | -| -------- | -------- | -| %s: | String will be used to convert all values except BigInt, Object and -0. | -| %d: | Number will be used to convert all values except BigInt and Symbol. | -| %i: | parseInt(value, 10) is used for all values except BigInt and Symbol. | -| %f: | parseFloat(value) is used for all values expect Symbol. | -| %j: | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | -| %o: | Object. A string representation of an object with generic JavaScript object formatting. Similar to util.inspect() with options { showHidden: true, showProxy: true }. This will show the full object including non-enumerable properties and proxies. | -| %O: | Object. A string representation of an object with generic JavaScript object formatting. Similar to util.inspect() without options. This will show the full object not including non-enumerable properties and proxies. | -| %c: | CSS. This specifier is ignored and will skip any CSS passed in. | -| %%: | single percent sign ('%'). This does not consume an argument. | +| readonly encoding : string | 获取编码的格式,只支持UTF-8。 | +| encode(input : string) : Uint8Array | 输入stirng字符串,编码并输出UTF-8字节流。 | +| encodeInto(input : string, dest : Uint8Array) : {read : number, written : number} | 输入stirng字符串,dest表示编码后存放位置,返回一个对象,read表示已经编码的字符的个数,written表示已编码字符所占字节的大小。 | +| constructor(encoding? : string, options? : {fatal? : boolean, ignoreBOM? : boolean}) | 构造函数,第一个参数encoding表示解码的格式。第二个参数表示一些属性。属性中fatal表示是否抛出异常,ignoreBOM表示是否忽略bom标志。 | +| readonly encoding : string | 获取设置的解码格式。 | +| readonly fatal : boolean | 获取抛出异常的设置 | +| readonly ignoreBOM : boolean | 获取是否忽略bom标志的设置 | +| decode(input : ArrayBuffer | 输入要解码的数据,解出对应的string字符串。第一个参数input表示要解码的数据,第二个参数options表示一个bool标志,表示将跟随附加数据,默认为false。 | +| function printf(format: string, ...args: Object[]): string | printf()方法使用第一个参数作为格式字符串(其可以包含零个或多个格式说明符)来返回格式化的字符串。 | +| function getErrorString(errno: number): string | getErrorString()方法使用一个系统的错误数字作为参数,用来返回系统的错误信息。 | +| function callbackWrapper(original: Function): (err: Object, value: Object) => void | 参数为一个采用 async 函数(或返回 Promise 的函数)并返回遵循错误优先回调风格的函数,即将 (err, value) => ... 回调作为最后一个参数。 在回调中,第一个参数将是拒绝原因(如果 Promise 已解决,则为 null),第二个参数将是已解决的值。 | +| function promiseWrapper(original: (err: Object, value: Object) => void): Object | 参数为采用遵循常见的错误优先的回调风格的函数(也就是将 (err, value) => ... 回调作为最后一个参数),并返回一个返回 promise 的版本。 | +| encode(src: Uint8Array): Uint8Array; | 使用Base64编码方案将指定u8数组中的所有字节编码到新分配的u8数组中。 | +| encodeToString(src: Uint8Array): string; | 使用Base64编码方案将指定的字节数组编码为String。 | +| decode(src: Uint8Array / string): Uint8Array; | 使用Base64编码方案将Base64编码的字符串或输入u8数组解码为新分配的u8数组。 | +| CreateRationalFromString(src: string): Rational | 基于给定的字符串创建一个RationalNumber对象 | +| CompareTo(src: RationalNumber): number | 将当前的RationalNumber对象与给定的对象进行比较 | +| Equals(src: object): number | 检查给定对象是否与当前 RationalNumber 对象相同 | +| Value(): number | 将当前的RationalNumber对象进行取整数值或者浮点数值 | +| GetCommonDivisor(arg1: int, arg2: int,): number | 获得两个指定数的最大公约数 | +| GetDenominator(): number | 获取当前的RationalNumber对象的分母 | +| GetNumerator(): number | 获取当前的RationalNumber对象的分子 | +| IsFinite(): bool | 检查当前的RationalNumber对象是有限的 | +| IsNaN(): bool | 检查当前RationalNumber对象是否表示非数字(NaN)值 | +| IsZero(): bool | 检查当前RationalNumber对象是否表示零值 | +| ToString(): string | 获取当前RationalNumber对象的字符串表示形式 | +| updateCapacity(newCapacity:number):void | 将缓冲区容量更新为指定容量,如果 newCapacity 小于或等于 0,则抛出此异常 | +| toString():string | 返回对象的字符串表示形式,输出对象的字符串表示。 | +| values():V[ ] | 获取当前缓冲区中所有值的列表,输出按升序返回当前缓冲区中所有值的列表,从最近访问到最近最少访问 | +| size():number | 获取当前缓冲区中值的总数,输出返回当前缓冲区中值的总数 | +| capacity():number | 获取当前缓冲区的容量,输出返回当前缓冲区的容量 | +| clear():void | 从当前缓冲区清除键值对,清除键值对后,调用afterRemoval()方法依次对其执行后续操作 | +| getCreateCount():number | 获取createDefault()返回值的次数,输出返回createDefault()返回值的次数 | +| getMissCount():number | 获取查询值不匹配的次数,输出返回查询值不匹配的次数 | +| getRemovalCount():number | 获取从缓冲区中逐出值的次数,输出从缓冲区中驱逐的次数 | +| getMatchCount​():number | 获取查询值匹配成功的次数,输出返回查询值匹配成功的次数 | +| getPutCount():number | 获取将值添加到缓冲区的次数,输出返回将值添加到缓冲区的次数 | +| isEmpty():boolean | 检查当前缓冲区是否为空,输出如果当前缓冲区不包含任何值,则返回 true | +| get(k:key):V / undefined | 表示要查询的键,输出如果指定的键存在于缓冲区中,则返回与键关联的值;否则返回 undefined | +| put(K key, V value):V | 将键值对添加到缓冲区,输出与添加的键关联的值;如果要添加的键已经存在,则返回原始值,如果键或值为空,则抛出此异常 | +| keys():K[ ] | 获取当前缓冲区中值的键列表,输出返回从最近访问到最近最少访问排序的键列表 | +| remove​(k:key):V / undefined | 从当前缓冲区中删除指定的键及其关联的值 | +| afterRemoval(boolean isEvict, K key, V value, V newValue):void | 删除值后执行后续操作 | +| contains(k:key):boolean | 检查当前缓冲区是否包含指定的键,输出如果缓冲区包含指定的键,则返回 true | +| createDefault(k:key):V | 如果未计算特定键的值,则执行后续操作,参数表示丢失的键,输出返回与键关联的值 | +| entries() : [K,V] | 允许迭代包含在这个对象中的所有键/值对。每对的键和值都是对象 | +| Symbol.iterator():[K,V] | 返回以键值对得形式得一个二维数组 | +| constructor(lowerObj: ScopeType, upperObj: ScopeType) | 创建并返回一个Scope对象,用于创建指定下限和上限的作用域实例的构造函数。 | +| toString():string | 该字符串化方法返回一个包含当前范围的字符串表示形式。 | +| intersect(range: Scope): Scope | 该方法返回一个给定范围和当前范围的交集。 | +| intersect(lowerObj: ScopeType, upperObj: ScopeType): Scope | 传入给定范围的上限和下限,返回当前范围与给定下限和上限指定的范围的交集。 | +| getUpper(): ScopeType | 获取当前范围的上界,返回一个ScopeType类型的值。 | +| getLower(): ScopeType | 获取当前范围的下界,返回一个ScopeType类型的值。 | +| expand(lowerObj: ScopeType, upperObj: ScopeType): Scope | 该方法创建并返回包括当前范围和给定下限和上限的并集。 | +| expand(range: Scope): Scope | 该方法创建并返回包括当前范围和给定范围的并集。 | +| expand(value: ScopeType): Scope | 该方法创建并返回包括当前范围和给定值的并集。 | +| contains(value: ScopeType): boolean | 检查给定value是否包含在当前范围内。有则返回true,否则返回false。 | +| contains(range: Scope): boolean | 检查给定range是否在当前范围内。如果在则返回true,否则返回false。 | +| clamp(value: ScopeType): ScopeType | 将给定value限定到当前范围内,如果传入的value小于下限,则返回lowerObj;如果大于上限值则返回upperObj;如果在当前范围内,则返回value。 | -### Instruction for use +printf中每个说明符都替换为来自相应参数的转换后的值。 支持的说明符有: +| 式样化字符 | 式样要求 | +| -------- | -------- | +| %s: | String 将用于转换除 BigInt、Object 和 -0 之外的所有值。| +| %d: |Number 将用于转换除 BigInt 和 Symbol 之外的所有值。| +| %i: |parseInt(value, 10) 用于除 BigInt 和 Symbol 之外的所有值。| +| %f: |parseFloat(value) 用于除 Symbol 之外的所有值。| +| %j: |JSON。 如果参数包含循环引用,则替换为字符串 '[Circular]'。| +| %o: |Object. 具有通用 JavaScript 对象格式的对象的字符串表示形式。类似于具有选项 { showHidden: true, showProxy: true } 的 util.inspect()。这将显示完整的对象,包括不可枚举的属性和代理。| +| %O: |Object. 具有通用 JavaScript 对象格式的对象的字符串表示形式。类似于没有选项的 util.inspect()。 这将显示完整的对象,但不包括不可枚举的属性和代理。| +| %c: | 此说明符被忽略,将跳过任何传入的 CSS。| +| %%: |单个百分号 ('%')。 这不消耗待式样化参数。| +### 使用说明 -The use methods of each interface are as follows: +各接口使用方法如下: 1.readonly encoding() + ``` import util from '@ohos.util' var textEncoder = new util.TextEncoder(); @@ -158,8 +262,392 @@ newPromiseObj.then(res => { expect(res).strictEqual('HelloWorld'); }) ``` -## Related warehouse +13.encode() +``` +import util from '@ohos.util' +var that = new util.Base64(); +var array = new Uint8Array([115,49,51]); +var num = 0; +var result = that.encode(array,num); +``` +14.encodeToString() +``` +import util from '@ohos.util' +var that = new util.Base64(); +var array = new Uint8Array([115,49,51]); +var num = 0; +var result = that.encodeToString(array,num); +``` +15.decode() +``` +import util from '@ohos.util' +var that = new util.Base64() +var buff = 'czEz'; +var num = 0; +var result = that.decode(buff,num); +``` +16.createRationalFromString() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(0, 0); +var res = pro.createRationalFromString("-1:2"); +var result1 = res.value(); +``` +17.compareTo() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(2, 1); +var proc = new util.RationalNumber(3, 4); +var res = pro.compareTo(proc); +``` +18.equals() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(2, 1); +var proc = new util.RationalNumber(3, 4); +var res = pro.equals(proc); +``` +19.value() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(2, 1); +var res = pro.value(); +``` +20.getCommonDivisor() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(0, 0); +var res = pro.getCommonDivisor(4, 8); +``` +21.getDenominator() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(2, 1); +var res = pro.getDenominator(); +``` +22.getNumerator() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.getNumerator(); +``` +23.isFinite() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.isFinite(); +``` +24.isNaN() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.isNaN(); +``` +25.isZero() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.isZero(); + +``` +26.toString() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.toString(); + +``` +27.updateCapacity() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.updateCapacity(100); +``` +28.toString() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.get(2); +pro.remove(20); +var temp = pro.toString(); +``` +29.values() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.put(2,"anhu"); +pro.put("afaf","grfb"); +var temp = pro.values(); +``` +30.size() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.put(1,8); +var temp = pro.size(); +``` +31.capacity() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +var temp = pro.capacity(); +``` +32.clear() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.clear(); +``` +33.getCreatCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(1,8); +var temp = pro.getCreatCount(); +``` +34.getMissCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.get(2) +var temp = pro.getMissCount(); +``` +35.getRemovalCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.updateCapacity(2); +pro.put(50,22); +var temp = pro.getRemovalCount(); +``` +36.getMatchCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.get(2); +var temp = pro.getMatchCount(); +``` +37.getPutCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var temp = pro.getPutCount(); +``` +38.isEmpty() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var temp = pro.isEmpty(); +``` +39.get() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var temp = pro.get(2); +``` +40.put() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +var temp = pro.put(2,10); +``` +41.keys() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); + pro.put(2,10); +var temp = pro.keys(); +``` +42.remove() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var temp = pro.remove(20); +``` +43.contains() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var temp = pro.contains(20); +``` +44.createDefault() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +var temp = pro.createDefault(50); +``` +45.entries() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var temp = pro.entries(); +``` +46.[Symbol.iterator]() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var temp = aa[symbol.iterator](); +``` +Scope接口中构造新类,实现compareTo方法。 + +``` +class Temperature { + constructor(value) { + this._temp = value; + } + compareTo(value) { + return this._temp >= value.getTemp(); + } + getTemp() { + return this._temp; + } + toString() { + return this._temp.toString(); + } +} +``` + +47.constructor() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +``` + +48.toString() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +range.toString() // => [30,40] +``` + +49.intersect() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +var tempMiDF = new Temperature(35); +var tempMidS = new Temperature(39); +var rangeFir = new Scope(tempMiDF, tempMidS); +range.intersect(rangeFir) // => [35,39] +``` + +50.intersect() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var tempMidS = new Temperature(39); +var range = new Scope(tempLower, tempUpper); +range.intersect(tempMiDF, tempMidS) // => [35,39] +``` + +51.getUpper() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +range.getUpper() // => 40 +``` + +52.getLower() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +range.getLower() // => 30 +``` + +53.expand() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var tempMidS = new Temperature(39); +var range = new Scope(tempLower, tempUpper); +range.expand(tempMiDF, tempMidS) // => [30,40] +``` + +54.expand() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var tempMidS = new Temperature(39); +var range = new Scope(tempLower, tempUpper); +var rangeFir = new Scope(tempMiDF, tempMidS); +range.expand(rangeFir) // => [30,40] +``` + +55.expand() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var range = new Scope(tempLower, tempUpper); +range.expand(tempMiDF) // => [30,40] +``` + +56.contains() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var range = new Scope(tempLower, tempUpper); +range.contains(tempMiDF) // => true +``` + +57.contains() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +var tempLess = new Temperature(20); +var tempMore = new Temperature(45); +var rangeSec = new Scope(tempLess, tempMore); +range.contains(rangeSec) // => true +``` + +58.clamp() + +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var range = new Scope(tempLower, tempUpper); +range.clamp(tempMiDF) // => 35 +``` + + + +## 相关仓 -[js_util_module subsystem](https://gitee.com/OHOS_STD/js_util_module) +[js_util_module子系统](https://gitee.com/OHOS_STD/js_util_module) [base/compileruntime/js_util_module/](base/compileruntime/js_util_module-readme.md) diff --git a/README_zh.md b/README_zh.md deleted file mode 100755 index 9210368..0000000 --- a/README_zh.md +++ /dev/null @@ -1,165 +0,0 @@ -# js_util_module子系统/组件 - -- [简介](#简介) -- [目录](#目录) -- [说明](#说明) - - [接口说明](#接口说明) - - [使用说明](#使用说明) - -- [相关仓](#相关仓) - -## 简介 - -UTIL接口用于字符编码TextEncoder、解码TextDecoder和帮助函数HelpFunction。TextEncoder表示一个文本编码器,接受字符串作为输入,以UTF-8格式进行编码,输出UTF-8字节流。TextDecoder接口表示一个文本解码器,解码器将字节流作为输入,输出stirng字符串。HelpFunction主要是对函数做callback化、promise化以及对错误码进行编写输出,及类字符串的格式化输出。 -## 目录 - -``` -base/compileruntime/js_util_module/ -├── Class:TextEncoder # TextEncoder类 -│ ├── new TextEncoder() # 创建TextEncoder对象 -│ ├── encode() # encode方法 -│ ├── encoding # encoding属性 -│ └── encodeInto() # encodeInto方法 -├── Class:TextDecoder # TextDecoder类 -│ ├── new TextDecoder() # 创建TextDecoder对象 -│ ├── decode() # decode方法 -│ ├── encoding # encoding属性 -│ ├── fatal # fatal属性 -│ └── ignoreBOM # ignoreBOM属性 -├── printf() # printf方法 -├── getErrorString() # getErrorString方法 -├── callbackWrapper() # callbackWrapper方法 -└── promiseWrapper() # promiseWrapper方法 -``` - -## 说明 - -### 接口说明 - - -| 接口名 | 说明 | -| -------- | -------- | -| readonly encoding : string | 获取编码的格式,只支持UTF-8。 | -| encode(input : string) : Uint8Array | 输入stirng字符串,编码并输出UTF-8字节流。 | -| encodeInto(input : string, dest : Uint8Array) : {read : number, written : number} | 输入stirng字符串,dest表示编码后存放位置,返回一个对象,read表示已经编码的字符的个数,written表示已编码字符所占字节的大小。 | -| constructor(encoding? : string, options? : {fatal? : boolean, ignoreBOM? : boolean}) | 构造函数,第一个参数encoding表示解码的格式。第二个参数表示一些属性。属性中fatal表示是否抛出异常,ignoreBOM表示是否忽略bom标志。 | -| readonly encoding : string | 获取设置的解码格式。 | -| readonly fatal : boolean | 获取抛出异常的设置 | -| readonly ignoreBOM : boolean | 获取是否忽略bom标志的设置 | -| decode(input : ArrayBuffer | 输入要解码的数据,解出对应的string字符串。第一个参数input表示要解码的数据,第二个参数options表示一个bool标志,表示将跟随附加数据,默认为false。 | -| function printf(format: string, ...args: Object[]): string | printf()方法使用第一个参数作为格式字符串(其可以包含零个或多个格式说明符)来返回格式化的字符串。 | -| function getErrorString(errno: number): string | getErrorString()方法使用一个系统的错误数字作为参数,用来返回系统的错误信息。 | -| function callbackWrapper(original: Function): (err: Object, value: Object) => void | 参数为一个采用 async 函数(或返回 Promise 的函数)并返回遵循错误优先回调风格的函数,即将 (err, value) => ... 回调作为最后一个参数。 在回调中,第一个参数将是拒绝原因(如果 Promise 已解决,则为 null),第二个参数将是已解决的值。 | -| function promiseWrapper(original: (err: Object, value: Object) => void): Object | 参数为采用遵循常见的错误优先的回调风格的函数(也就是将 (err, value) => ... 回调作为最后一个参数),并返回一个返回 promise 的版本。 | - -printf中每个说明符都替换为来自相应参数的转换后的值。 支持的说明符有: -| 式样化字符 | 式样要求 | -| -------- | -------- | -| %s: | String 将用于转换除 BigInt、Object 和 -0 之外的所有值。| -| %d: |Number 将用于转换除 BigInt 和 Symbol 之外的所有值。| -| %i: |parseInt(value, 10) 用于除 BigInt 和 Symbol 之外的所有值。| -| %f: |parseFloat(value) 用于除 Symbol 之外的所有值。| -| %j: |JSON。 如果参数包含循环引用,则替换为字符串 '[Circular]'。| -| %o: |Object. 具有通用 JavaScript 对象格式的对象的字符串表示形式。类似于具有选项 { showHidden: true, showProxy: true } 的 util.inspect()。这将显示完整的对象,包括不可枚举的属性和代理。| -| %O: |Object. 具有通用 JavaScript 对象格式的对象的字符串表示形式。类似于没有选项的 util.inspect()。 这将显示完整的对象,但不包括不可枚举的属性和代理。| -| %c: | 此说明符被忽略,将跳过任何传入的 CSS。| -| %%: |单个百分号 ('%')。 这不消耗待式样化参数。| - -### 使用说明 - -各接口使用方法如下: - -1.readonly encoding() -``` -import util from '@ohos.util' -var textEncoder = new util.TextEncoder(); -var getEncoding = textEncoder.encoding(); -``` -2.encode() -``` -import util from '@ohos.util' -var textEncoder = new util.TextEncoder(); -var result = textEncoder.encode('abc'); -``` -3.encodeInto() -``` -import util from '@ohos.util' -var textEncoder = new util.TextEncoder(); -var obj = textEncoder.encodeInto('abc', dest); -``` -4.textDecoder() -``` -import util from '@ohos.util' -var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); -``` -5.readonly encoding() -``` -import util from '@ohos.util' -var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); -var getEncoding = textDecoder.encoding(); -``` -6.readonly fatal() -``` -import util from '@ohos.util' -var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); -var fatalStr = textDecoder.fatal(); -``` -7.readonly ignoreBOM() -``` -import util from '@ohos.util' -var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); -var ignoreBom = textDecoder.ignoreBOM(); -``` -8.decode() -``` -import util from '@ohos.util' -var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); -var result = textDecoder.decode(input, {stream : true}); -``` -9.printf() -``` -import util from '@ohos.util' -var format = "%%%o%%%i%s"; -var value = function aa(){}; -var value1 = 1.5; -var value2 = "qwer"; -var result = util.printf(format,value,value1,value2); -``` -10.getErrorString() -``` -import util from '@ohos.util' -var errnum = 13; -var result = util.getErrorString(errnum); -``` -11.callbackWrapper() -``` -import util from '@ohos.util' -async function promiseFn() { - return Promise.resolve('value'); -}; -var cb = util.callbackWrapper(promiseFn); -cb((err, ret) => { - expect(err).strictEqual(null); - expect(ret).strictEqual('value'); -}) -``` -12.promiseWrapper() -``` -import util from '@ohos.util' -function aysnFun(str1, str2, callback) { - if (typeof str1 === 'string' && typeof str1 === 'string') { - callback(null, str1 + str2); - } else { - callback('type err'); - } -} -let newPromiseObj = util.promiseWrapper(aysnFun)("Hello", 'World'); -newPromiseObj.then(res => { - expect(res).strictEqual('HelloWorld'); -}) -``` -## 相关仓 - -[js_util_module子系统](https://gitee.com/OHOS_STD/js_util_module) - -[base/compileruntime/js_util_module/](base/compileruntime/js_util_module-readme.md) diff --git a/lrubuffer/BUILD.gn b/lrubuffer/BUILD.gn deleted file mode 100755 index 97eae7a..0000000 --- a/lrubuffer/BUILD.gn +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//build/ohos/ace/ace.gni") - -base_output_path = get_label_info(":js_lrubuffer", "target_out_dir") -js_lrubuffer_obj_path = base_output_path + "/lrubuffer.o" - -gen_js_obj("js_lrubuffer") { - input = "//base/compileruntime/js_util_module/lrubuffer/js_lrubuffer.js" - output = js_lrubuffer_obj_path -} - -ohos_shared_library("lrubuffer") { - include_dirs = [ - "//foundation/ace/napi", - "//foundation/ace/napi/native_engine", - "//third_party/icu/icu4c/source/common", - "//third_party/node/src", - "//foundation/ace/napi/interfaces/kits", - "//base/compileruntime/js_util_module/lrubuffer", - ] - - sources = [ "native_module_lrubuffer.cpp" ] - - deps = [ - ":js_lrubuffer", - "//base/compileruntime/js_util_module/lrubuffer/:js_lrubuffer", - "//foundation/ace/napi/:ace_napi", - "//foundation/ace/napi/:ace_napi_quickjs", - "//third_party/icu/icu4c:static_icuuc", - "//utils/native/base:utils", - ] - - if (is_standard_system) { - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - } else { - external_deps = [ "hilog:libhilog" ] - } - subsystem_name = "ccruntime" - part_name = "jsapi_util" - - relative_install_dir = "module" -} - -group("lrubuffer_packages") { - deps = [ ":lrubuffer" ] -} diff --git a/lrubuffer/js_lrubuffer.js b/lrubuffer/js_lrubuffer.js deleted file mode 100755 index 71a4752..0000000 --- a/lrubuffer/js_lrubuffer.js +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the 'License'); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an 'AS IS' BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -class LruBuffer { - constructor(capacity) { - this.maxSize = 64; - this.putCount = 0; - this.createCount = 0; - this.evictionCount = 0; - this.hitCount = 0; - this.missCount = 0; - if (capacity !== undefined) { - if (capacity <= 0) { - throw new Error('data error'); - } - this.maxSize = capacity; - } - this.cache = new Map(); - } - updateCapacity(newCapacity) { - if (newCapacity <= 0) { - throw new Error('data error'); - } - else if (this.cache.size > newCapacity) { - this.changeCapacity(newCapacity); - } - this.maxSize = newCapacity; - } - get(key) { - if (key === null) { - throw new Error('key search failed'); - } - let value; - if (this.cache.has(key)) { - value = this.cache.get(key); - this.hitCount++; - this.cache.delete(key); - this.cache.set(key, value); - return value; - } - this.missCount++; - let createValue = this.createDefault(key); - if (createValue === undefined) { - return undefined; - } - else { - value = this.put(key, createValue); - this.createCount++; - if (value !== null) { - this.put(key, value); - this.afterRemoval(false, key, createValue, value); - return value; - } - return createValue; - } - } - put(key, value) { - if (key === null || value === null) { - throw new Error('key or value search failed'); - } - let former; - this.putCount++; - if (this.cache.has(key)) { - former = this.cache.get(key); - this.cache.delete(key); - this.afterRemoval(false, key, former, null); - } - else if (this.cache.size >= this.maxSize) { - this.cache.delete(this.cache.keys().next().value); - this.evictionCount++; - } - this.cache.set(key, value); - return former; - } - getCreatCount() { - return this.createCount; - } - getMissCount() { - return this.missCount; - } - getRemovalCount() { - return this.evictionCount; - } - getMatchCount() { - return this.hitCount; - } - getPutCount() { - return this.putCount; - } - capacity() { - return this.maxSize; - } - size() { - return this.cache.size; - } - clear() { - this.cache.clear(); - this.afterRemoval(false, this.cache.keys(), this.cache.values(), null); - } - isEmpty() { - let temp = false; - if (this.cache.size === 0) { - temp = true; - } - return temp; - } - contains(key) { - let flag = false; - if (this.cache.has(key)) { - flag = true; - let value; - this.hitCount++; - value = this.cache.get(key); - this.cache.delete(key); - this.cache.set(key, value); - return flag; - } - this.missCount++; - return flag; - } - remove(key) { - if (key === null) { - throw new Error('key search failed'); - } - else if (this.cache.has(key)) { - let former; - former = this.cache.get(key); - this.cache.delete(key); - if (former !== null) { - this.afterRemoval(false, key, former, null); - return former; - } - } - return undefined; - } - toString() { - let peek = 0; - let hitRate = 0; - peek = this.hitCount + this.missCount; - if (peek !== 0) { - hitRate = 100 * this.hitCount / peek; - } - else { - hitRate = 0; - } - let str = ''; - str = 'Lrubuffer[ maxSize = ' + this.maxSize + ', hits = ' + this.hitCount + ', misses = ' + this.missCount - + ', hitRate = ' + hitRate + '% ]'; - return str; - } - values() { - let arr = []; - for (let value of this.cache.values()) { - arr.push(value); - } - return arr; - } - keys() { - let arr = []; - for (let key of this.cache.keys()) { - arr.push(key); - } - return arr; - } - afterRemoval(isEvict, key, value, newValue) { - } - createDefault(key) { - return undefined; - } - changeCapacity(newCapacity) { - while (this.cache.size > newCapacity) { - this.cache.delete(this.cache.keys().next().value); - this.evictionCount++; - this.afterRemoval(true, this.cache.keys(), this.cache.values(), null); - } - } -} -export default { - LruBuffer: LruBuffer, -}; diff --git a/lrubuffer/native_module_lrubuffer.cpp b/lrubuffer/native_module_lrubuffer.cpp deleted file mode 100755 index cbd5a66..0000000 --- a/lrubuffer/native_module_lrubuffer.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include - -#include "napi/native_api.h" -#include "napi/native_node_api.h" - -static napi_value LruBufferInit(napi_env env, napi_value exports) -{ - const char *lruBufferClassName = "lrubuffer"; - napi_value lruBufferClass = nullptr; - NAPI_CALL(env, napi_define_class(env, lruBufferClassName, strlen(lruBufferClassName), nullptr, - nullptr, 0, nullptr, &lruBufferClass)); - static napi_property_descriptor desc[] = { - DECLARE_NAPI_PROPERTY("lrubuffer", lruBufferClass), - }; - napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); - return exports; -} - -// lrubuffer module define -static napi_module lrubufferModule = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = LruBufferInit, - .nm_modname = "lrubuffer", - .nm_priv = ((void*)0), - .reserved = { 0 }, -}; - -extern "C" __attribute__ ((constructor)) void RegisterModule() -{ - napi_module_register(&lrubufferModule); -} - -// lrubuffer JS register -extern "C" -__attribute__((visibility("default"))) void NAPI_lrubuffer_GetJSCode(const char **buf, int *buflen) -{ - extern const char _binary_js_lrubuffer_js_start[]; - extern const char _binary_js_lrubuffer_js_end[]; - if (buf != nullptr) { - *buf = _binary_js_lrubuffer_js_start; - } - if (buflen != nullptr) { - *buflen = _binary_js_lrubuffer_js_end - _binary_js_lrubuffer_js_start; - } -} \ No newline at end of file diff --git a/ohos.build b/ohos.build index b49feec..e5737bd 100755 --- a/ohos.build +++ b/ohos.build @@ -7,9 +7,7 @@ "phone" ], "module_list": [ - "//base/compileruntime/js_util_module/util:util_packages", - "//base/compileruntime/js_util_module/scope:scope_packages", - "//base/compileruntime/js_util_module/lrubuffer:lrubuffer_packages" + "//base/compileruntime/js_util_module/util:util_packages" ], "inner_kits": [ ], diff --git a/scope/BUILD.gn b/scope/BUILD.gn deleted file mode 100755 index 81b8580..0000000 --- a/scope/BUILD.gn +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//build/ohos/ace/ace.gni") - -base_output_path = get_label_info(":scope_js", "target_out_dir") -scope_js_obj_path = base_output_path + "/scope.o" - -gen_js_obj("scope_js") { - input = "//base/compileruntime/js_util_module/scope/scope_js.js" - output = scope_js_obj_path -} - -ohos_shared_library("scope") { - include_dirs = [ - "//foundation/ace/napi", - "//foundation/ace/napi/native_engine", - "//third_party/icu/icu4c/source/common", - "//third_party/node/src", - "//foundation/ace/napi/interfaces/kits", - "//base/compileruntime/js_util_module/scope", - ] - - sources = [ "native_module_scope.cpp" ] - - deps = [ - ":scope_js", - "//base/compileruntime/js_util_module/scope/:scope_js", - "//foundation/ace/napi/:ace_napi", - "//foundation/ace/napi/:ace_napi_quickjs", - "//third_party/icu/icu4c:static_icuuc", - "//utils/native/base:utils", - ] - - if (is_standard_system) { - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - } else { - external_deps = [ "hilog:libhilog" ] - } - subsystem_name = "ccruntime" - part_name = "jsapi_util" - - relative_install_dir = "module" -} - -group("scope_packages") { - deps = [ ":scope" ] -} diff --git a/scope/native_module_scope.cpp b/scope/native_module_scope.cpp deleted file mode 100755 index 3dd9411..0000000 --- a/scope/native_module_scope.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include - -#include "napi/native_api.h" -#include "napi/native_node_api.h" - -static napi_value ScopeInit(napi_env env, napi_value exports) -{ - const char *ClassName = "scope"; - napi_value scopeClass = nullptr; - NAPI_CALL(env, napi_define_class(env, ClassName, strlen(ClassName), nullptr, - nullptr, 0, nullptr, &scopeClass)); - static napi_property_descriptor desc[] = { - DECLARE_NAPI_PROPERTY("scope", scopeClass) - }; - napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); - return exports; -} - -// Scope module define -static napi_module scopeModule = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = ScopeInit, - .nm_modname = "scope", - .nm_priv = ((void*)0), - .reserved = {0}, -}; - -// Scope module register -extern "C" -__attribute__((constructor)) void RegisterModule() -{ - napi_module_register(&scopeModule); -} - -// Scope JS register -extern "C" -__attribute__((visibility("default"))) void NAPI_scope_GetJSCode(const char **buf, int *buflen) -{ - extern const char _binary_scope_js_js_start[]; - extern const char _binary_scope_js_js_end[]; - if (buf != nullptr) { - *buf = _binary_scope_js_js_start; - } - if (buflen != nullptr) { - *buflen = _binary_scope_js_js_end - _binary_scope_js_js_start; - } -} \ No newline at end of file diff --git a/scope/scope_js.js b/scope/scope_js.js deleted file mode 100755 index c93eec7..0000000 --- a/scope/scope_js.js +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -class Scope { - constructor(lowerObj, upperObj) { - this.lowerObj = lowerObj; - this.upperObj = upperObj; - this.checkNull(lowerObj, 'lower limit not be null'); - this.checkNull(upperObj, 'upper limit not be null'); - if (lowerObj.compareTo(upperObj)) { - throw new Error('lower limit must be less than or equal to upper limit'); - } - this._lowerLimit = lowerObj; - this._upperLimit = upperObj; - } - - getLower() { - return this._lowerLimit; - } - - getUpper() { - return this._upperLimit; - } - - contains(x) { - let resLower; - let resUpper; - this.checkNull(x, 'value must not be null'); - if (x instanceof Scope) { - resLower = x._lowerLimit.compareTo(this._lowerLimit); - resUpper = this._upperLimit.compareTo(x._upperLimit); - } else { - resLower = x.compareTo(this._lowerLimit); - resUpper = this._upperLimit.compareTo(x); - } - return resLower && resUpper; - } - - clamp(value) { - this.checkNull(value, 'value must not be null'); - if (!value.compareTo(this._lowerLimit)) { - return this._lowerLimit; - } else if (value.compareTo(this._upperLimit)) { - return this._upperLimit; - } else { - return value; - } - } - - intersect(x, y) { - let reLower; - let reUpper; - let mLower; - let mUpper; - if (y) { - this.checkNull(x, 'lower limit must not be null'); - this.checkNull(y, 'upper limit must not be null'); - reLower = this._lowerLimit.compareTo(x); - reUpper = y.compareTo(this._upperLimit); - if (reLower && reUpper) { - return this; - } else { - mLower = reLower ? this._lowerLimit : x; - mUpper = reUpper ? this._upperLimit : y; - return new Scope(mLower, mUpper); - } - } else { - this.checkNull(x, 'scope must not be null'); - reLower = this._lowerLimit.compareTo(x._lowerLimit); - reUpper = x._upperLimit.compareTo(this._upperLimit); - if (!reLower && !reUpper) { - return x; - } else if (reLower && reUpper) { - return this; - } else { - mLower = reLower ? this._lowerLimit : x._lowerLimit; - mUpper = reUpper ? this._upperLimit : x._upperLimit; - return new Scope(mLower, mUpper); - } - } - } - - expand(x, y) { - let reLower; - let reUpper; - let mLower; - let mUpper; - if (!y) { - this.checkNull(x, 'value must not be null'); - if (!(x instanceof Scope)) { - this.checkNull(x, 'value must not be null'); - return this.expand(x, x); - } - let reLower = x._lowerLimit.compareTo(this._lowerLimit); - let reUpper = this._upperLimit.compareTo(x._upperLimit); - if (reLower && reUpper) { - return this; - } else if (!reLower && !reUpper) { - return x; - } else { - let mLower = reLower ? this._lowerLimit : x._lowerLimit; - let mUpper = reUpper ? this._upperLimit : x._upperLimit; - return new Scope(mLower, mUpper); - } - } - else { - this.checkNull(x, 'lower limit must not be null'); - this.checkNull(y, 'upper limit must not be null'); - let reLower = x.compareTo(this._lowerLimit); - let reUpper = this._upperLimit.compareTo(y); - if (reLower && reUpper) { - return this; - } - let mLower = reLower ? this._lowerLimit : x; - let mUpper = reUpper ? this._upperLimit : y; - return new Scope(mLower, mUpper); - } - } - - toString() { - let strLower = this._lowerLimit.toString(); - let strUpper = this._upperLimit.toString(); - return `[${strLower}, ${strUpper}]`; - } - - checkNull(o, str) { - if (o == null) { - throw new Error(str); - } - } -} - -export default { - Scope: Scope, -}; \ No newline at end of file diff --git a/util/BUILD.gn b/util/BUILD.gn index ea5e47e..cc2856c 100755 --- a/util/BUILD.gn +++ b/util/BUILD.gn @@ -11,8 +11,33 @@ # See the License for the specific language governing permissions and # limitations under the License. +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") import("//build/ohos.gni") import("//build/ohos/ace/ace.gni") +import("//foundation/ace/ace_engine/ace_config.gni") + +# compile .js to .abc. +action("gen_util_abc") { + visibility = [ ":*" ] + script = "//ark/ts2abc/ts2panda/scripts/generate_js_bytecode.py" + + args = [ + "--src-js", + rebase_path("//base/compileruntime/js_util_module/util/util_js.js"), + "--dst-file", + rebase_path(target_out_dir + "/util.abc"), + "--node", + rebase_path("${node_path}"), + "--frontend-tool-path", + rebase_path("${ts2abc_build_path}"), + "--node-modules", + rebase_path("${node_modules}"), + ] + deps = [ "//ark/ts2abc/ts2panda:ark_ts2abc_build" ] + + inputs = [ "//base/compileruntime/js_util_module/util/util_js.js" ] + outputs = [ target_out_dir + "/util.abc" ] +} base_output_path = get_label_info(":util_js", "target_out_dir") util_js_obj_path = base_output_path + "/util.o" @@ -22,6 +47,14 @@ gen_js_obj("util_js") { output = util_js_obj_path } +abc_output_path = get_label_info(":util_abc", "target_out_dir") +util_abc_obj_path = abc_output_path + "/util_abc.o" +gen_js_obj("util_abc") { + input = "$target_out_dir/util.abc" + output = util_abc_obj_path + dep = ":gen_util_abc" +} + ohos_shared_library("util") { include_dirs = [ "//foundation/ace/napi", @@ -41,6 +74,7 @@ ohos_shared_library("util") { ] deps = [ + ":util_abc", ":util_js", "//base/compileruntime/js_util_module/util/:util_js", "//foundation/ace/napi/:ace_napi", diff --git a/util/util_js.js b/util/util_js.js index f3ce3a0..5de7643 100755 --- a/util/util_js.js +++ b/util/util_js.js @@ -378,16 +378,16 @@ function getErrorString(errnum) } function callbackified(original, ...args) - { - const maybeCb = args.pop(); - if (typeof maybeCb !== 'function') { - throw new Error('maybe is not function'); - } - const cb = (...args) => { - Reflect.apply(maybeCb, this, args); - }; - Reflect.apply(original, this, args).then((ret) => cb(null, ret), (rej) => cb(rej)); +{ + const maybeCb = args.pop(); + if (typeof maybeCb !== 'function') { + throw new Error('maybe is not function'); } + const cb = (...args) => { + Reflect.apply(maybeCb, this, args); + }; + Reflect.apply(original, this, args).then((ret) => cb(null, ret), (rej) => cb(rej)); +} function callbackWrapper(original) { @@ -410,7 +410,8 @@ function callbackWrapper(original) return cb; } -function promiseWrapper(func) { +function promiseWrapper(func) +{ return function (...args) { return new Promise((resolve, reject) => { let callback = function (err, ...values) { @@ -425,6 +426,377 @@ function promiseWrapper(func) { }; } +class LruBuffer { + constructor(capacity) + { + this.maxSize = 64; + this.putCount = 0; + this.createCount = 0; + this.evictionCount = 0; + this.hitCount = 0; + this.missCount = 0; + if (capacity !== undefined) { + if (capacity <= 0) { + throw new Error('data error'); + } + this.maxSize = capacity; + } + this.cache = new Map(); + } + + updateCapacity(newCapacity) + { + if (newCapacity <= 0) { + throw new Error('data error'); + } + else if (this.cache.size > newCapacity) { + this.changeCapacity(newCapacity); + } + this.maxSize = newCapacity; + } + + get(key) + { + if (key === null) { + throw new Error('key not be null'); + } + let value; + if (this.cache.has(key)) { + value = this.cache.get(key); + this.hitCount++; + this.cache.delete(key); + this.cache.set(key, value); + return value; + } + this.missCount++; + let createValue = this.createDefault(key); + if (createValue === undefined) { + return undefined; + } + else { + value = this.put(key, createValue); + this.createCount++; + if (value !== null) { + this.put(key, value); + this.afterRemoval(false, key, createValue, value); + return value; + } + return createValue; + } + } + + put(key, value) + { + if (key === null || value === null) { + throw new Error('key or value key or value not be null'); + } + let former; + this.putCount++; + if (this.cache.has(key)) { + former = this.cache.get(key); + this.cache.delete(key); + this.afterRemoval(false, key, former, null); + } + else if (this.cache.size >= this.maxSize) { + this.cache.delete(this.cache.keys().next().value); + this.evictionCount++; + } + this.cache.set(key, value); + return former; + } + + getCreatCount() + { + return this.createCount; + } + + getMissCount() + { + return this.missCount; + } + + getRemovalCount() + { + return this.evictionCount; + } + + getMatchCount() + { + return this.hitCount; + } + + getPutCount() + { + return this.putCount; + } + + capacity() + { + return this.maxSize; + } + + size() + { + return this.cache.size; + } + + clear() + { + this.cache.clear(); + this.afterRemoval(false, this.cache.keys(), this.cache.values(), null); + } + + isEmpty() + { + let temp = false; + if (this.cache.size === 0) { + temp = true; + } + return temp; + } + + contains(key) + { + let flag = false; + if (this.cache.has(key)) { + flag = true; + let value; + this.hitCount++; + value = this.cache.get(key); + this.cache.delete(key); + this.cache.set(key, value); + return flag; + } + this.missCount++; + return flag; + } + + remove(key) + { + if (key === null) { + throw new Error('key not be null'); + } + else if (this.cache.has(key)) { + let former; + former = this.cache.get(key); + this.cache.delete(key); + if (former !== null) { + this.afterRemoval(false, key, former, null); + return former; + } + } + return undefined; + } + + toString() + { + let peek = 0; + let hitRate = 0; + peek = this.hitCount + this.missCount; + if (peek !== 0) { + hitRate = 100 * this.hitCount / peek; + } + else { + hitRate = 0; + } + let str = ''; + str = 'Lrubuffer[ maxSize = ' + this.maxSize + ', hits = ' + this.hitCount + ', misses = ' + this.missCount + + ', hitRate = ' + hitRate + '% ]'; + return str; + } + + values() + { + let arr = []; + for (let value of this.cache.values()) { + arr.push(value); + } + return arr; + } + + keys() + { + let arr = []; + for (let key of this.cache.keys()) { + arr.push(key); + } + return arr; + } + + afterRemoval(isEvict, key, value, newValue) + { + + } + + createDefault(key) + { + return undefined; + } + + entries() + { + let arr = []; + for (let entry of this.cache.entries()) { + arr.push(entry); + } + return arr; + } + + [Symbol.iterator]() + { + let arr = []; + for (let [key, value] of this.cache) { + arr.push([key, value]); + } + return arr; + } + + changeCapacity(newCapacity) + { + while (this.cache.size > newCapacity) { + this.cache.delete(this.cache.keys().next().value); + this.evictionCount++; + this.afterRemoval(true, this.cache.keys(), this.cache.values(), null); + } + } +} +class Scope { + constructor(lowerObj, upperObj) + { + this.lowerObj = lowerObj; + this.upperObj = upperObj; + this.checkNull(lowerObj, 'lower limit not be null'); + this.checkNull(upperObj, 'upper limit not be null'); + if (lowerObj.compareTo(upperObj)) { + throw new Error('lower limit must be less than or equal to upper limit'); + } + this._lowerLimit = lowerObj; + this._upperLimit = upperObj; + } + + getLower() + { + return this._lowerLimit; + } + + getUpper() + { + return this._upperLimit; + } + + contains(x) + { + let resLower; + let resUpper; + this.checkNull(x, 'value must not be null'); + if (x instanceof Scope) { + resLower = x._lowerLimit.compareTo(this._lowerLimit); + resUpper = this._upperLimit.compareTo(x._upperLimit); + } else { + resLower = x.compareTo(this._lowerLimit); + resUpper = this._upperLimit.compareTo(x); + } + return resLower && resUpper; + } + + clamp(value) + { + this.checkNull(value, 'value must not be null'); + if (!value.compareTo(this._lowerLimit)) { + return this._lowerLimit; + } else if (value.compareTo(this._upperLimit)) { + return this._upperLimit; + } else { + return value; + } + } + + intersect(x, y) + { + let reLower; + let reUpper; + let mLower; + let mUpper; + if (y) { + this.checkNull(x, 'lower limit must not be null'); + this.checkNull(y, 'upper limit must not be null'); + reLower = this._lowerLimit.compareTo(x); + reUpper = y.compareTo(this._upperLimit); + if (reLower && reUpper) { + return this; + } else { + mLower = reLower ? this._lowerLimit : x; + mUpper = reUpper ? this._upperLimit : y; + return new Scope(mLower, mUpper); + } + } else { + this.checkNull(x, 'scope must not be null'); + reLower = this._lowerLimit.compareTo(x._lowerLimit); + reUpper = x._upperLimit.compareTo(this._upperLimit); + if (!reLower && !reUpper) { + return x; + } else if (reLower && reUpper) { + return this; + } else { + mLower = reLower ? this._lowerLimit : x._lowerLimit; + mUpper = reUpper ? this._upperLimit : x._upperLimit; + return new Scope(mLower, mUpper); + } + } + } + + expand(x, y) + { + let reLower; + let reUpper; + let mLower; + let mUpper; + if (!y) { + this.checkNull(x, 'value must not be null'); + if (!(x instanceof Scope)) { + this.checkNull(x, 'value must not be null'); + return this.expand(x, x); + } + let reLower = x._lowerLimit.compareTo(this._lowerLimit); + let reUpper = this._upperLimit.compareTo(x._upperLimit); + if (reLower && reUpper) { + return this; + } else if (!reLower && !reUpper) { + return x; + } else { + let mLower = reLower ? this._lowerLimit : x._lowerLimit; + let mUpper = reUpper ? this._upperLimit : x._upperLimit; + return new Scope(mLower, mUpper); + } + } + else { + this.checkNull(x, 'lower limit must not be null'); + this.checkNull(y, 'upper limit must not be null'); + let reLower = x.compareTo(this._lowerLimit); + let reUpper = this._upperLimit.compareTo(y); + if (reLower && reUpper) { + return this; + } + let mLower = reLower ? this._lowerLimit : x; + let mUpper = reUpper ? this._upperLimit : y; + return new Scope(mLower, mUpper); + } + } + + toString() + { + let strLower = this._lowerLimit.toString(); + let strUpper = this._upperLimit.toString(); + return `[${strLower}, ${strUpper}]`; + } + + checkNull(o, str) + { + if (o == null) { + throw new Error(str); + } + } +} export default { printf: printf, getErrorString: getErrorString, @@ -434,4 +806,6 @@ export default { TextDecoder: TextDecoder, RationalNumber: RationalNumber, Base64: Base64, + LruBuffer: LruBuffer, + Scope: Scope, }; \ No newline at end of file -- Gitee From 7276eb9a6427e6df58f7a2bd5c2f3cda99116796 Mon Sep 17 00:00:00 2001 From: lifansheng Date: Tue, 28 Sep 2021 16:13:46 +0800 Subject: [PATCH 2/3] Signed-off-by: lifansheng On branch OpenHarmony-3.0-LTS Your branch is up to date with 'origin/OpenHarmony-3.0-LTS'. Changes to be committed: modified: test/unittest/test_util.cpp modified: util/js_textdecoder.cpp --- test/unittest/test_util.cpp | 2 +- util/js_textdecoder.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/unittest/test_util.cpp b/test/unittest/test_util.cpp index 00ee997..3139e2a 100755 --- a/test/unittest/test_util.cpp +++ b/test/unittest/test_util.cpp @@ -93,7 +93,7 @@ HWTEST_F(NativeEngineTest, textEncodeTest001, testing::ext::TestSize.Level0) env, result, &type, &srcLength, &srcData, &srcBuffer, &byteOffset); ASSERT_EQ(srcLength, 6); - char* res = (char*)srcData; + char* res = reinterpret_cast(srcData); res[srcLength] = 0; ASSERT_STREQ(res, excepted); diff --git a/util/js_textdecoder.cpp b/util/js_textdecoder.cpp index 8f38672..05e574f 100755 --- a/util/js_textdecoder.cpp +++ b/util/js_textdecoder.cpp @@ -88,7 +88,7 @@ namespace OHOS::Util { return nullptr; } UChar *target = arr; - size_t tarStartPos = (intptr_t)arr; + size_t tarStartPos = reinterpret_cast(arr); ucnv_toUnicode(GetConverterPtr(), &target, target + len, &source, source + length, nullptr, flush, &codeFlag); size_t resultLength = 0; bool omitInitialBom = false; @@ -179,7 +179,7 @@ namespace OHOS::Util { } if (U_SUCCESS(codeFlag)) { if (decArr.limitLen > 0) { - rstLen = (intptr_t)decArr.target - decArr.tarStartPos; + rstLen = reinterpret_cast(decArr.target) - decArr.tarStartPos; if (rstLen > 0 && IsUnicode() && !IsIgnoreBom() && !IsBomFlag()) { bomFlag = (arr[0] == 0xFEFF) ? true : false; label_ |= static_cast(ConverterFlags::BOM_SEEN_FLG); -- Gitee From eaeb1740853866de0f16c8bb9aebb99601b8f645 Mon Sep 17 00:00:00 2001 From: lifansheng Date: Tue, 28 Sep 2021 17:33:37 +0800 Subject: [PATCH 3/3] Signed-off-by: lifansheng On branch OpenHarmony-3.0-LTS Your branch is up to date with 'origin/OpenHarmony-3.0-LTS'. --- README.en.md | 655 ------------------------------------------- README.md | 600 ++++----------------------------------- README_zh.md | 165 +++++++++++ util/js_rational.cpp | 27 +- util/js_rational.h | 1 + 5 files changed, 238 insertions(+), 1210 deletions(-) delete mode 100644 README.en.md create mode 100644 README_zh.md diff --git a/README.en.md b/README.en.md deleted file mode 100644 index e3b2128..0000000 --- a/README.en.md +++ /dev/null @@ -1,655 +0,0 @@ -# js_util_module Subsystems / components - -- [Introduction](#Introduction) -- [Directory](#Directory) -- [Description](#Description) - - [Interface description](#Interface description) - - [Instruction for use](#Instruction for use) - -- [Related warehouse](#Related warehouse) - -## Introduction -The interface of util is used for character Textencoder, TextDecoder and HelpFunction module.The TextEncoder represents a text encoder that accepts a string as input, encodes it in UTF-8 format, and outputs UTF-8 byte stream. The TextDecoder interface represents a text decoder. The decoder takes the byte stream as the input and outputs the Stirng string. HelpFunction is mainly used to callback and promise functions, write and output error codes, and format class strings. -Encodes all bytes from the specified u8 array into a newly-allocated u8 array using the Base64 encoding scheme or Encodes the specified byte array into a String using the Base64 encoding scheme.Decodes a Base64 encoded String or input u8 array into a newly-allocated u8 array using the Base64 encoding scheme.The rational number is mainly to compare rational numbers and obtain the numerator and denominator.LruBuffer The algorithm replaces the least used data with new data when the buffer space is insufficient. The algorithm derives from the need to access resources: recently accessed data can be Will visit again in the near future. The least accessed data is the least valuable data that should be kicked out of the cache space. The Scope interface is used to describe the valid range of a field. The constructor for the Scope instance is used to create objects with specified lower and upper bounds and require that these objects be comparable - -## 目录 - -``` -base/compileruntime/js_util_module/ -├── Class:TextEncoder # TextEncoder class -│ ├── new TextEncoder() # create textencoder object -│ ├── encode() # encode method -│ ├── encoding # encoding property -│ └── encodeInto() # encodeInto method -├── Class:TextDecoder # TextDecoder class -│ ├── new TextDecoder() # create TextDecoder object -│ ├── decode() # decode method -│ ├── encoding # encoding property -│ ├── fatal # fatal property -│ └── ignoreBOM # ignoreBOM property -├── printf() # printf method -├── getErrorString() # getErrorString method -├── callbackWrapper() # callbackWrapper method -├── promiseWrapper() # promiseWrapper method -├── Class:Base64 # Base64 class -│ ├── new Base64() # create Base64 object -│ ├── encode() # encode method -│ ├── encodeToString() # encodeToString method -│ └── decode() # decode method -├── Class:RationalNumber # RationalNumber class -│ ├── new RationalNumber() # create RationalNumber object -│ ├── CreateRationalFromString() # CreatRationalFromString method -│ ├── CompareTo() # CompareTo method -│ ├── Equals() # Equals method -│ ├── Value() # Value method -│ ├── GetCommonDivisor() # GetCommonDivisor method -│ ├── GetDenominator() # GetDenominator method -│ ├── GetNumerator() # GetNumerator method -│ ├── IsFinite() # IsFinite method -│ ├── IsNaN() # IsNaN method -│ ├── IsZero() # IsZero method -│ └── ToString() # ToString method -├── Class:LruBuffer # LruBuffer class -│ ├── new LruBuffer() # create RationalNumber object -│ ├── updateCapacity() # updateCapacity method -│ ├── toString() # toString method -│ ├── values() # values method -│ ├── size() # size method -│ ├── capacity() # capacity method -│ ├── clear() # clear method -│ ├── getCreateCount # getCreateCount method -│ ├── getMissCount() # getMissCount method -│ ├── getRemovalCount() # getRemovalCount method -│ ├── getMatchCount() # getMatchCount method -│ ├── getPutCount() # getPutCount method -│ ├── isEmpty() # isEmpty method -│ ├── get() # get method -│ ├── put() # put method -│ ├── keys() # keys method -│ ├── remove() # remove method -│ ├── afterRemoval() # afterRemoval method -│ ├── contains() # contains method -│ ├── createDefault() # createDefault method -│ ├── entries() # entries method -│ └── [Symbol.iterator]() # Symboliterator method -└── Class:Scope # Scope class - ├── constructor() # create Scope object - ├── toString() # toString method - ├── intersect() # intersect method - ├── intersect() # intersect method - ├── getUpper() # getUpper method - ├── getLower() # getLower method - ├── expand() # expand method - ├── expand() # expand method - ├── expand() # expand method - ├── contains() # contains method - ├── contains() # contains method - └── clamp() # clamp method -``` - -## Description - -### Interface description - - -| Interface name | Description | -| -------- | -------- | -| readonly encoding : string | Get the encoding format, only UTF-8 is supported. | -| encode(input : string) : Uint8Array | Input stirng string, encode and output UTF-8 byte stream. | -| encodeInto(input : string, dest : Uint8Array) : {read : number, written : number} | Enter the stirng string, dest represents the storage location after encoding, and returns an object, read represents the number of characters that have been encoded,and written represents the size of bytes occupied by the encoded characters. | -| constructor(encoding? : string, options? : {fatal? : boolean, ignoreBOM? : boolean}) | Constructor, the first parameter encoding indicates the format of decoding.The second parameter represents some attributes.Fatal in the attribute indicates whether an exception is thrown, and ignoreBOM indicates whether to ignore the bom flag. | -| readonly encoding : string | Get the set decoding format. | -| readonly fatal : boolean | Get the setting that throws the exception. | -| readonly ignoreBOM : boolean | Get whether to ignore the setting of the bom flag. | -| decode(input : ArrayBuffer | Input the data to be decoded, and solve the corresponding string character string.The first parameter input represents the data to be decoded, and the second parameter options represents a bool flag, which means that additional data will be followed. The default is false. | -| function printf(format: string, ...args: Object[]): string | The util.format() method returns a formatted string using the first argument as a printf-like format string which can contain zero or more format specifiers. | -| function getErrorString(errno: number): string | The geterrorstring () method uses a system error number as a parameter to return system error information. | -| function callbackWrapper(original: Function): (err: Object, value: Object) => void | Takes an async function (or a function that returns a Promise) and returns a function following the error-first callback style, i.e. taking an (err, value) => ... callback as the last argument. In the callback, the first argument will be the rejection reason (or null if the Promise resolved), and the second argument will be the resolved value. | -| function promiseWrapper(original: (err: Object, value: Object) => void): Object | Takes a function following the common error-first callback style, i.e. taking an (err, value) => ... callback as the last argument, and returns a version that returns promises. | -| encode(src: Uint8Array): Uint8Array; | Encodes all bytes from the specified u8 array into a newly-allocated u8 array using the Base64 encoding scheme. | -| encodeToString(src: Uint8Array): string; | Encodes the specified byte array into a String using the Base64 encoding scheme. | -| decode(src: Uint8Array | string): Uint8Array; | -| Decodes a Base64 encoded String or input u8 array into a newly-allocated u8 array using the Base64 encoding scheme. || -| CreateRationalFromString(src: string): Rational | Create a RationalNumber object based on the given string | -| CompareTo(src: RationalNumber): number | Compare the current RationalNumber object with the given object | -| Equals(src: object): number | Check if the given object is the same as the current RationalNumber object | -| Value(): number | Take the current RationalNumber object to an integer value or a floating point value | -| GetCommonDivisor(arg1: int, arg2: int,): number | Obtain the greatest common divisor of two specified numbers | -| GetDenominator(): number | Get the denominator of the current RationalNumber object | -| GetNumerator(): number | Get the numerator of the current RationalNumber object | -| IsFinite(): bool | Check that the current RationalNumber object is limited | -| IsNaN(): bool | Check whether the current RationalNumber object represents a non-number (NaN) value | -| IsZero(): bool | Check whether the current RationalNumber object represents a zero value | -| ToString(): string | Get the string representation of the current RationalNumber object | -| updateCapacity(newCapacity:number):void | Updates the buffer capacity to the specified capacity. This exception is thrown if newCapacity is less than or equal to 0 | -| toString():string | Returns the string representation of the object and outputs the string representation of the object | -| values():V[ ] | Gets a list of all values in the current buffer, and the output returns a list of all values in the current buffer in ascending order, from most recently accessed to least recently accessed | -| size():number | Gets the total number of values in the current buffer. The output returns the total number of values in the current buffer | -| capacity():number | Gets the capacity of the current buffer. The output returns the capacity of the current buffer | -| clear():void | The key value pairs are cleared from the current buffer, after the key value is cleared, the afterRemoval () method is invoked to perform subsequent operations in turn | -| getCreateCount():number | Get the number of times the returned value of createdefault(), and output the number of times the returned value of createdefault() | -| getMissCount():number | Get the number of times the query value does not match, and output the number of times the query value does not match | -| getRemovalCount():number | Gets the number of evictions from the buffer, and outputs the number of evictions from the buffer | -| getMatchCount​():number | Obtain the number of successful matching of query values, and output the number of successful matching of query values | -| getPutCount():number | Gets the number of times the value was added to the buffer, and the output returns the number of times the value was added to the buffer | -| isEmpty():boolean | Checks whether the current buffer is empty and returns true if the current buffer does not contain any values | -| get(k:key):V / undefined | Indicates the key to query. If the specified key exists in the buffer, the value associated with the key will be returned; Otherwise, undefined is returned | -| put(K key, V value):V | Adding the key value pair to the buffer and outputting the value associated with the added key; If the key to be added already exists, the original value is returned. If the key or value is empty, this exception is thrown | -| keys():V[ ] | Get the key list of the value in the current buffer, and the output returns the key list sorted from the most recent access to the least recent access | -| remove​(k:key):V / undefined | Deletes the specified key and its associated value from the current buffer | -| afterRemoval(boolean isEvict, K key, V value, V newValue):void | Perform subsequent operations after deleting the value | -| contains(k:key):boolean | Checks whether the current buffer contains the specified key, and returns true if the buffer contains the specified key | -| createDefault(k:key):V | If the value of a specific key is not calculated, subsequent operations are performed. The parameter represents the missing key, and the output returns the value associated with the key | -| entries() : [K,V] | Allows you to iterate over all key / value pairs contained in this object. The keys and values of each pair are objects | -| [Symbol.iterator]():[K,V]| Returns a two-dimensional array in the form of key value pairs | -| constructor(lowerObj: ScopeType, upperObj: ScopeType) | Creates and returns a Scope object that creates a constructor for a scope instance that specifies a lower and upper bound. | -| toString():string | The stringification method returns a string representation that contains the current range. | -| intersect(range: Scope): Scope | This method returns the intersection of a given range and the current range. | -| intersect(lowerObj: ScopeType, upperObj: ScopeType): Scope | Passing in the upper and lower bounds of the given range returns the intersection of the current range and the range specified by the given lower and upper bounds. | -| getUpper(): ScopeType | Gets the upper bound of the current scope and returns a value of type ScopeType. | -| getLower(): ScopeType | Gets the lower bound of the current scope and returns a value of type ScopeType. | -| expand(lowerObj: ScopeType, upperObj: ScopeType): Scope | This method creates and returns a union that includes the current range and a given lower and upper bound. | -| expand(range: Scope): Scope | This method creates and returns a union that includes the current range and the given range. | -| expand(value: ScopeType): Scope | This method creates and returns a union that includes the current range and the given value. | -| contains(value: ScopeType): boolean | Checks whether the given value is included in the current range. If yes, true is returned. Otherwise, false is returned. | -| contains(range: Scope): boolean | Checks whether the given range is within the current range. Returns true if in, false otherwise. | -| clamp(value: ScopeType): ScopeType | Clips the specified value to the current range. If the value is less than the lower limit, lowerObj is returned. If the value is greater than the upper limit, upperObj is returned. Returns value if within the current range. | - -Each specifier in printf is replaced with a converted value from the corresponding parameter. Supported specifiers are: -| Stylized character | Style requirements | -| -------- | -------- | -| %s: | String will be used to convert all values except BigInt, Object and -0. | -| %d: | Number will be used to convert all values except BigInt and Symbol. | -| %i: | parseInt(value, 10) is used for all values except BigInt and Symbol. | -| %f: | parseFloat(value) is used for all values expect Symbol. | -| %j: | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | -| %o: | Object. A string representation of an object with generic JavaScript object formatting. Similar to util.inspect() with options { showHidden: true, showProxy: true }. This will show the full object including non-enumerable properties and proxies. | -| %O: | Object. A string representation of an object with generic JavaScript object formatting. Similar to util.inspect() without options. This will show the full object not including non-enumerable properties and proxies. | -| %c: | CSS. This specifier is ignored and will skip any CSS passed in. | -| %%: | single percent sign ('%'). This does not consume an argument. | - -### Instruction for use - - -The use methods of each interface are as follows: - -1.readonly encoding() - -``` -import util from '@ohos.util' -var textEncoder = new util.TextEncoder(); -var getEncoding = textEncoder.encoding(); -``` -2.encode() -``` -import util from '@ohos.util' -var textEncoder = new util.TextEncoder(); -var result = textEncoder.encode('abc'); -``` -3.encodeInto() -``` -import util from '@ohos.util' -var textEncoder = new util.TextEncoder(); -var obj = textEncoder.encodeInto('abc', dest); -``` -4.textDecoder() -``` -import util from '@ohos.util' -var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); -``` -5.readonly encoding() -``` -import util from '@ohos.util' -var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); -var getEncoding = textDecoder.encoding(); -``` -6.readonly fatal() -``` -import util from '@ohos.util' -var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); -var fatalStr = textDecoder.fatal(); -``` -7.readonly ignoreBOM() -``` -import util from '@ohos.util' -var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); -var ignoreBom = textDecoder.ignoreBOM(); -``` -8.decode() -``` -import util from '@ohos.util' -var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); -var result = textDecoder.decode(input, {stream : true}); -``` -9.printf() -``` -import util from '@ohos.util' -var format = "%%%o%%%i%s"; -var value = function aa(){}; -var value1 = 1.5; -var value2 = "qwer"; -var result = util.printf(format,value,value1,value2); -``` -10.getErrorString() -``` -import util from '@ohos.util' -var errnum = 13; -var result = util.getErrorString(errnum); -``` -11.callbackWrapper() -``` -import util from '@ohos.util' -async function promiseFn() { - return Promise.resolve('value'); -}; -var cb = util.callbackWrapper(promiseFn); -cb((err, ret) => { - expect(err).strictEqual(null); - expect(ret).strictEqual('value'); -}) -``` -12.promiseWrapper() -``` -import util from '@ohos.util' -function aysnFun(str1, str2, callback) { - if (typeof str1 === 'string' && typeof str1 === 'string') { - callback(null, str1 + str2); - } else { - callback('type err'); - } -} -let newPromiseObj = util.promiseWrapper(aysnFun)("Hello", 'World'); -newPromiseObj.then(res => { - expect(res).strictEqual('HelloWorld'); -}) -``` -13.encode() -``` -import util from '@ohos.util' -var that = new util.Base64(); -var array = new Uint8Array([115,49,51]); -var num = 0; -var result = that.encode(array,num); -``` -14.encodeToString() -``` -import util from '@ohos.util' -var that = new util.Base64(); -var array = new Uint8Array([115,49,51]); -var num = 0; -var result = that.encodeToString(array,num); -``` -15.decode() -``` -import util from '@ohos.util' -var that = new util.Base64() -var buff = 'czEz'; -var num = 0; -var result = that.decode(buff,num); -``` -16.createRationalFromString() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(0, 0); -var res = pro.createRationalFromString("-1:2"); -var result1 = res.value(); -``` -17.compareTo() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(2, 1); -var proc = new util.RationalNumber(3, 4); -var res = pro.compareTo(proc); -``` -18.equals() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(2, 1); -var proc = new util.RationalNumber(3, 4); -var res = pro.equals(proc); -``` -19.value() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(2, 1); -var res = pro.value(); -``` -20.getCommonDivisor() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(0, 0); -var res = pro.getCommonDivisor(4, 8); -``` -21.getDenominator() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(2, 1); -var res = pro.getDenominator(); -``` -22.getNumerator() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(-2, 1); -var res = pro.getNumerator(); -``` -23.isFinite() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(-2, 1); -var res = pro.isFinite(); -``` -24.isNaN() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(-2, 1); -var res = pro.isNaN(); -``` -25.isZero() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(-2, 1); -var res = pro.isZero(); -``` -26.toString() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(-2, 1); -var res = pro.toString(); -``` -27.updateCapacity() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.updateCapacity(100); -``` -28.toString() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.get(2); -pro.remove(20); -var temp = pro.toString(); -``` -29.values() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.put(2,"anhu"); -pro.put("afaf","grfb"); -var temp = pro.values(); -``` -30.size() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.put(1,8); -var temp = pro.size(); -``` -31.capacity() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -var temp = pro.capacity(); -``` -32.clear() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.clear(); -``` -33.getCreatCount() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(1,8); -var temp = pro.getCreatCount(); -``` -34.getMissCount() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.get(2) -var temp = pro.getMissCount(); -``` -35.getRemovalCount() -``` - -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.updateCapacity(2); -pro.put(50,22); -var temp = pro.getRemovalCount(); - -``` -36.getMatchCount -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.get(2); -var temp5 = pro.getMatchCount(); -``` -37.getPutCount() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var temp = pro.getPutCount(); -``` -38.isEmpty() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var temp = pro.isEmpty(); -``` -39.get() - -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var temp = pro.get(2); -``` -40.put() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -var temp = pro.put(2,10); -``` -41.keys() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var temp = pro.keys(); -``` -42.remove() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var temp = pro.remove(20); -``` -43.contains() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var temp = pro.contains(20); -``` -44.createDefault() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -var trmp = pro .createDefault(50); -``` -45.entries() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var temp = pro.entries(); -``` -46.[Symbol.iterator]() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro .put(2,10); -var temp = pro[symbol.iterator](); -``` -Construct a new class in the scope interface to implement the compareTo method. - -``` -class Temperature { - constructor(value) { - this._temp = value; - } - compareTo(value) { - return this._temp >= value.getTemp(); - } - getTemp() { - return this._temp; - } - toString() { - return this._temp.toString(); - } -} -``` - -47.constructor() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var range = new Scope(tempLower, tempUpper); -``` - -48.toString() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var range = new Scope(tempLower, tempUpper); -range.toString() // => [30,40] -``` - -49.intersect() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var range = new Scope(tempLower, tempUpper); -var tempMiDF = new Temperature(35); -var tempMidS = new Temperature(39); -var rangeFir = new Scope(tempMiDF, tempMidS); -range.intersect(rangeFir) // => [35,39] -``` - -50.intersect() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var tempMiDF = new Temperature(35); -var tempMidS = new Temperature(39); -var range = new Scope(tempLower, tempUpper); -range.intersect(tempMiDF, tempMidS) // => [35,39] -``` - -51.getUpper() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var range = new Scope(tempLower, tempUpper); -range.getUpper() // => 40 -``` - -52.getLower() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var range = new Scope(tempLower, tempUpper); -range.getLower() // => 30 -``` - -53.expand() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var tempMiDF = new Temperature(35); -var tempMidS = new Temperature(39); -var range = new Scope(tempLower, tempUpper); -range.expand(tempMiDF, tempMidS) // => [30,40] -``` - -54.expand() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var tempMiDF = new Temperature(35); -var tempMidS = new Temperature(39); -var range = new Scope(tempLower, tempUpper); -var rangeFir = new Scope(tempMiDF, tempMidS); -range.expand(rangeFir) // => [30,40] -``` - -55.expand() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var tempMiDF = new Temperature(35); -var range = new Scope(tempLower, tempUpper); -range.expand(tempMiDF) // => [30,40] -``` - -56.contains() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var tempMiDF = new Temperature(35); -var range = new Scope(tempLower, tempUpper); -range.contains(tempMiDF) // => true -``` - -57.contains() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var range = new Scope(tempLower, tempUpper); -var tempLess = new Temperature(20); -var tempMore = new Temperature(45); -var rangeSec = new Scope(tempLess, tempMore); -range.contains(rangeSec) // => true -``` - -58.clamp() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var tempMiDF = new Temperature(35); -var range = new Scope(tempLower, tempUpper); -range.clamp(tempMiDF) // => 35 -``` - - - -## Related warehouse - -[js_util_module subsystem](https://gitee.com/OHOS_STD/js_util_module) - -[base/compileruntime/js_util_module/](base/compileruntime/js_util_module-readme.md) diff --git a/README.md b/README.md index b6dd59c..99ca7f8 100755 --- a/README.md +++ b/README.md @@ -1,179 +1,75 @@ -# js_util_module子系统/组件 +# js_util_module Subsystems / components -- [简介](#简介) -- [目录](#目录) -- [说明](#说明) - - [接口说明](#接口说明) - - [使用说明](#使用说明) - -- [相关仓](#相关仓) - -## 简介 - -UTIL接口用于字符编码TextEncoder、解码TextDecoder、帮助函数HelpFunction、基于Base64的字节编码encode和解码decode、有理数RationalNumber。TextEncoder表示一个文本编码器,接受字符串作为输入,以UTF-8格式进行编码,输出UTF-8字节流。TextDecoder接口表示一个文本解码器,解码器将字节流作为输入,输出stirng字符串。HelpFunction主要是对函数做callback化、promise化以及对错误码进行编写输出,及类字符串的格式化输出。encode接口使用Base64编码方案将指定u8数组中的所有字节编码到新分配的u8数组中或者使用Base64编码方案将指定的字节数组编码为String。decode接口使用Base64编码方案将Base64编码的字符串或输入u8数组解码为新分配的u8数组。rationalnumber有理数主要是对有理数进行比较,获取分子分母等方法。LruBuffer该算法在缓存空间不够的时候,将近期最少使用的数据替换为新数据。该算法源自这样一种访问资源的需求:近期访问的数据,可能在不久的将来会再次访问。于是最少访问的数据就是价值最小的,是最应该踢出缓存空间的数据。Scope接口用于描述一个字段的有效范围。 Scope实例的构造函数用于创建具有指定下限和上限的对象,并要求这些对象必须具有可比性。 +- [Introduction](#Introduction) +- [Directory](#Directory) +- [Description](#Description) + - [Interface description](#Interface description) + - [Instruction for use](#Instruction for use) +- [Related warehouse](#Related warehouse) +## Introduction +The interface of util is used for character Textencoder, TextDecoder and HelpFunction module.The TextEncoder represents a text encoder that accepts a string as input, encodes it in UTF-8 format, and outputs UTF-8 byte stream. The TextDecoder interface represents a text decoder. The decoder takes the byte stream as the input and outputs the Stirng string. HelpFunction is mainly used to callback and promise functions, write and output error codes, and format class strings. ## 目录 ``` base/compileruntime/js_util_module/ -├── Class:TextEncoder # TextEncoder类 -│ ├── new TextEncoder() # 创建TextEncoder对象 -│ ├── encode() # encode方法 -│ ├── encoding # encoding属性 -│ └── encodeInto() # encodeInto方法 -├── Class:TextDecoder # TextDecoder类 -│ ├── new TextDecoder() # 创建TextDecoder对象 -│ ├── decode() # decode方法 -│ ├── encoding # encoding属性 -│ ├── fatal # fatal属性 -│ └── ignoreBOM # ignoreBOM属性 -├── printf() # printf方法 -├── getErrorString() # getErrorString方法 -├── callbackWrapper() # callbackWrapper方法 -├── promiseWrapper() # promiseWrapper方法 -├── Class:Base64 # Base64类 -│ ├── new Base64() # 创建Base64对象 -│ ├── encode() # encode方法 -│ ├── encodeToString() # encodeToString方法 -│ └── decode() # decode方法 -├── Class:RationalNumber # RationalNumber类 -│ ├── new RationalNumber() # 创建RationalNumber对象 -│ ├── CreateRationalFromString() # CreateRationalFromString方法 -│ ├── CompareTo() # CompareTo方法 -│ ├── Equals() # Equals方法 -│ ├── Value() # Value方法 -│ ├── GetCommonDivisor() # GetCommonDivisor方法 -│ ├── GetDenominator() # GetDenominator方法 -│ ├── GetNumerator() # GetNumerator方法 -│ ├── IsFinite() # IsFinite方法 -│ ├── IsNaN() # IsNaN方法 -│ ├── IsZero() # IsZero方法 -│ └── ToString() # ToString方法 -├── Class:LruBuffer # LruBuffer类 -│ ├── new LruBuffer() # 创建LruBuffer对象 -│ ├── updateCapacity() # updateCapacity方法 -│ ├── toString() # toString方法 -│ ├── values() # values方法 -│ ├── size() # size方法 -│ ├── capacity() # capacity方法 -│ ├── clear() # clear方法 -│ ├── getCreateCount() # getCreateCount方法 -│ ├── getMissCount() # getMissCount方法 -│ ├── getRemovalCount() # getRemovalCount方法 -│ ├── getMatchCount() # getMatchCount方法 -│ ├── getPutCount() # getPutCount方法 -│ ├── isEmpty() # isEmpty方法 -│ ├── get() # get方法 -│ ├── put() # put方法 -│ ├── keys() # keys方法 -│ ├── remove() # remove方法 -│ ├── afterRemoval() # afterRemoval方法 -│ ├── contains() # contains方法 -│ ├── createDefault() # createDefault方法 -│ ├── entries() # entries方法 -│ └── [Symbol.iterator]() # Symboliterator方法 -└── Class:Scope # Scope类 - ├── constructor() # 创建Scope对象 - ├── toString() # toString方法 - ├── intersect() # intersect方法 - ├── intersect() # intersect方法 - ├── getUpper() # getUpper方法 - ├── getLower() # getLower方法 - ├── expand() # expand方法 - ├── expand() # expand方法 - ├── expand() # expand法 - ├── contains() # contains方法 - ├── contains() # contains方法 - └── clamp() # clamp方法 +├── Class:TextEncoder # TextEncoder class +│ ├── new TextEncoder() # create textencoder object +│ ├── encode() # encode method +│ ├── encoding # encoding property +│ └── encodeInto() # encodeInto method +├── Class:TextDecoder # TextDecoder class +│ ├── new TextDecoder() # create TextDecoder object +│ ├── decode() # decode method +│ ├── encoding # encoding property +│ ├── fatal # fatal property +│ └── ignoreBOM # ignoreBOM property +├── printf() # printf method +├── getErrorString() # getErrorString method +├── callbackWrapper() # callbackWrapper method +└── promiseWrapper() # promiseWrapper method ``` -## 说明 +## Description -### 接口说明 +### Interface description -| 接口名 | 说明 | +| Interface name | Description | | -------- | -------- | -| readonly encoding : string | 获取编码的格式,只支持UTF-8。 | -| encode(input : string) : Uint8Array | 输入stirng字符串,编码并输出UTF-8字节流。 | -| encodeInto(input : string, dest : Uint8Array) : {read : number, written : number} | 输入stirng字符串,dest表示编码后存放位置,返回一个对象,read表示已经编码的字符的个数,written表示已编码字符所占字节的大小。 | -| constructor(encoding? : string, options? : {fatal? : boolean, ignoreBOM? : boolean}) | 构造函数,第一个参数encoding表示解码的格式。第二个参数表示一些属性。属性中fatal表示是否抛出异常,ignoreBOM表示是否忽略bom标志。 | -| readonly encoding : string | 获取设置的解码格式。 | -| readonly fatal : boolean | 获取抛出异常的设置 | -| readonly ignoreBOM : boolean | 获取是否忽略bom标志的设置 | -| decode(input : ArrayBuffer | 输入要解码的数据,解出对应的string字符串。第一个参数input表示要解码的数据,第二个参数options表示一个bool标志,表示将跟随附加数据,默认为false。 | -| function printf(format: string, ...args: Object[]): string | printf()方法使用第一个参数作为格式字符串(其可以包含零个或多个格式说明符)来返回格式化的字符串。 | -| function getErrorString(errno: number): string | getErrorString()方法使用一个系统的错误数字作为参数,用来返回系统的错误信息。 | -| function callbackWrapper(original: Function): (err: Object, value: Object) => void | 参数为一个采用 async 函数(或返回 Promise 的函数)并返回遵循错误优先回调风格的函数,即将 (err, value) => ... 回调作为最后一个参数。 在回调中,第一个参数将是拒绝原因(如果 Promise 已解决,则为 null),第二个参数将是已解决的值。 | -| function promiseWrapper(original: (err: Object, value: Object) => void): Object | 参数为采用遵循常见的错误优先的回调风格的函数(也就是将 (err, value) => ... 回调作为最后一个参数),并返回一个返回 promise 的版本。 | -| encode(src: Uint8Array): Uint8Array; | 使用Base64编码方案将指定u8数组中的所有字节编码到新分配的u8数组中。 | -| encodeToString(src: Uint8Array): string; | 使用Base64编码方案将指定的字节数组编码为String。 | -| decode(src: Uint8Array / string): Uint8Array; | 使用Base64编码方案将Base64编码的字符串或输入u8数组解码为新分配的u8数组。 | -| CreateRationalFromString(src: string): Rational | 基于给定的字符串创建一个RationalNumber对象 | -| CompareTo(src: RationalNumber): number | 将当前的RationalNumber对象与给定的对象进行比较 | -| Equals(src: object): number | 检查给定对象是否与当前 RationalNumber 对象相同 | -| Value(): number | 将当前的RationalNumber对象进行取整数值或者浮点数值 | -| GetCommonDivisor(arg1: int, arg2: int,): number | 获得两个指定数的最大公约数 | -| GetDenominator(): number | 获取当前的RationalNumber对象的分母 | -| GetNumerator(): number | 获取当前的RationalNumber对象的分子 | -| IsFinite(): bool | 检查当前的RationalNumber对象是有限的 | -| IsNaN(): bool | 检查当前RationalNumber对象是否表示非数字(NaN)值 | -| IsZero(): bool | 检查当前RationalNumber对象是否表示零值 | -| ToString(): string | 获取当前RationalNumber对象的字符串表示形式 | -| updateCapacity(newCapacity:number):void | 将缓冲区容量更新为指定容量,如果 newCapacity 小于或等于 0,则抛出此异常 | -| toString():string | 返回对象的字符串表示形式,输出对象的字符串表示。 | -| values():V[ ] | 获取当前缓冲区中所有值的列表,输出按升序返回当前缓冲区中所有值的列表,从最近访问到最近最少访问 | -| size():number | 获取当前缓冲区中值的总数,输出返回当前缓冲区中值的总数 | -| capacity():number | 获取当前缓冲区的容量,输出返回当前缓冲区的容量 | -| clear():void | 从当前缓冲区清除键值对,清除键值对后,调用afterRemoval()方法依次对其执行后续操作 | -| getCreateCount():number | 获取createDefault()返回值的次数,输出返回createDefault()返回值的次数 | -| getMissCount():number | 获取查询值不匹配的次数,输出返回查询值不匹配的次数 | -| getRemovalCount():number | 获取从缓冲区中逐出值的次数,输出从缓冲区中驱逐的次数 | -| getMatchCount​():number | 获取查询值匹配成功的次数,输出返回查询值匹配成功的次数 | -| getPutCount():number | 获取将值添加到缓冲区的次数,输出返回将值添加到缓冲区的次数 | -| isEmpty():boolean | 检查当前缓冲区是否为空,输出如果当前缓冲区不包含任何值,则返回 true | -| get(k:key):V / undefined | 表示要查询的键,输出如果指定的键存在于缓冲区中,则返回与键关联的值;否则返回 undefined | -| put(K key, V value):V | 将键值对添加到缓冲区,输出与添加的键关联的值;如果要添加的键已经存在,则返回原始值,如果键或值为空,则抛出此异常 | -| keys():K[ ] | 获取当前缓冲区中值的键列表,输出返回从最近访问到最近最少访问排序的键列表 | -| remove​(k:key):V / undefined | 从当前缓冲区中删除指定的键及其关联的值 | -| afterRemoval(boolean isEvict, K key, V value, V newValue):void | 删除值后执行后续操作 | -| contains(k:key):boolean | 检查当前缓冲区是否包含指定的键,输出如果缓冲区包含指定的键,则返回 true | -| createDefault(k:key):V | 如果未计算特定键的值,则执行后续操作,参数表示丢失的键,输出返回与键关联的值 | -| entries() : [K,V] | 允许迭代包含在这个对象中的所有键/值对。每对的键和值都是对象 | -| Symbol.iterator():[K,V] | 返回以键值对得形式得一个二维数组 | -| constructor(lowerObj: ScopeType, upperObj: ScopeType) | 创建并返回一个Scope对象,用于创建指定下限和上限的作用域实例的构造函数。 | -| toString():string | 该字符串化方法返回一个包含当前范围的字符串表示形式。 | -| intersect(range: Scope): Scope | 该方法返回一个给定范围和当前范围的交集。 | -| intersect(lowerObj: ScopeType, upperObj: ScopeType): Scope | 传入给定范围的上限和下限,返回当前范围与给定下限和上限指定的范围的交集。 | -| getUpper(): ScopeType | 获取当前范围的上界,返回一个ScopeType类型的值。 | -| getLower(): ScopeType | 获取当前范围的下界,返回一个ScopeType类型的值。 | -| expand(lowerObj: ScopeType, upperObj: ScopeType): Scope | 该方法创建并返回包括当前范围和给定下限和上限的并集。 | -| expand(range: Scope): Scope | 该方法创建并返回包括当前范围和给定范围的并集。 | -| expand(value: ScopeType): Scope | 该方法创建并返回包括当前范围和给定值的并集。 | -| contains(value: ScopeType): boolean | 检查给定value是否包含在当前范围内。有则返回true,否则返回false。 | -| contains(range: Scope): boolean | 检查给定range是否在当前范围内。如果在则返回true,否则返回false。 | -| clamp(value: ScopeType): ScopeType | 将给定value限定到当前范围内,如果传入的value小于下限,则返回lowerObj;如果大于上限值则返回upperObj;如果在当前范围内,则返回value。 | - -printf中每个说明符都替换为来自相应参数的转换后的值。 支持的说明符有: -| 式样化字符 | 式样要求 | +| readonly encoding : string | Get the encoding format, only UTF-8 is supported. | +| encode(input : string) : Uint8Array | Input stirng string, encode and output UTF-8 byte stream. | +| encodeInto(input : string, dest : Uint8Array) : {read : number, written : number} | Enter the stirng string, dest represents the storage location after encoding, and returns an object, read represents the number of characters that have been encoded,and written represents the size of bytes occupied by the encoded characters. | +| constructor(encoding? : string, options? : {fatal? : boolean, ignoreBOM? : boolean}) | Constructor, the first parameter encoding indicates the format of decoding.The second parameter represents some attributes.Fatal in the attribute indicates whether an exception is thrown, and ignoreBOM indicates whether to ignore the bom flag. | +| readonly encoding : string | Get the set decoding format. | +| readonly fatal : boolean | Get the setting that throws the exception. | +| readonly ignoreBOM : boolean | Get whether to ignore the setting of the bom flag. | +| decode(input : Uint8Array, options?: { stream?: false }): string | Input the data to be decoded, and solve the corresponding string character string.The first parameter input represents the data to be decoded, and the second parameter options represents a bool flag, which means that additional data will be followed. The default is false. | +| function printf(format: string, ...args: Object[]): string | The util.format() method returns a formatted string using the first argument as a printf-like format string which can contain zero or more format specifiers. | +| function getErrorString(errno: number): string | The geterrorstring () method uses a system error number as a parameter to return system error information. | +| function callbackWrapper(original: Function): (err: Object, value: Object) => void | Takes an async function (or a function that returns a Promise) and returns a function following the error-first callback style, i.e. taking an (err, value) => ... callback as the last argument. In the callback, the first argument will be the rejection reason (or null if the Promise resolved), and the second argument will be the resolved value. | +| function promiseWrapper(original: (err: Object, value: Object) => void): Object | Takes a function following the common error-first callback style, i.e. taking an (err, value) => ... callback as the last argument, and returns a version that returns promises. | + +Each specifier in printf is replaced with a converted value from the corresponding parameter. Supported specifiers are: +| Stylized character | Style requirements | | -------- | -------- | -| %s: | String 将用于转换除 BigInt、Object 和 -0 之外的所有值。| -| %d: |Number 将用于转换除 BigInt 和 Symbol 之外的所有值。| -| %i: |parseInt(value, 10) 用于除 BigInt 和 Symbol 之外的所有值。| -| %f: |parseFloat(value) 用于除 Symbol 之外的所有值。| -| %j: |JSON。 如果参数包含循环引用,则替换为字符串 '[Circular]'。| -| %o: |Object. 具有通用 JavaScript 对象格式的对象的字符串表示形式。类似于具有选项 { showHidden: true, showProxy: true } 的 util.inspect()。这将显示完整的对象,包括不可枚举的属性和代理。| -| %O: |Object. 具有通用 JavaScript 对象格式的对象的字符串表示形式。类似于没有选项的 util.inspect()。 这将显示完整的对象,但不包括不可枚举的属性和代理。| -| %c: | 此说明符被忽略,将跳过任何传入的 CSS。| -| %%: |单个百分号 ('%')。 这不消耗待式样化参数。| +| %s: | String will be used to convert all values except BigInt, Object and -0. | +| %d: | Number will be used to convert all values except BigInt and Symbol. | +| %i: | parseInt(value, 10) is used for all values except BigInt and Symbol. | +| %f: | parseFloat(value) is used for all values expect Symbol. | +| %j: | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| %o: | Object. A string representation of an object with generic JavaScript object formatting. Similar to util.inspect() with options { showHidden: true, showProxy: true }. This will show the full object including non-enumerable properties and proxies. | +| %O: | Object. A string representation of an object with generic JavaScript object formatting. Similar to util.inspect() without options. This will show the full object not including non-enumerable properties and proxies. | +| %c: | CSS. This specifier is ignored and will skip any CSS passed in. | +| %%: | single percent sign ('%'). This does not consume an argument. | -### 使用说明 +### Instruction for use -各接口使用方法如下: -1.readonly encoding() +The use methods of each interface are as follows: +1.readonly encoding() ``` import util from '@ohos.util' var textEncoder = new util.TextEncoder(); @@ -262,392 +158,8 @@ newPromiseObj.then(res => { expect(res).strictEqual('HelloWorld'); }) ``` -13.encode() -``` -import util from '@ohos.util' -var that = new util.Base64(); -var array = new Uint8Array([115,49,51]); -var num = 0; -var result = that.encode(array,num); -``` -14.encodeToString() -``` -import util from '@ohos.util' -var that = new util.Base64(); -var array = new Uint8Array([115,49,51]); -var num = 0; -var result = that.encodeToString(array,num); -``` -15.decode() -``` -import util from '@ohos.util' -var that = new util.Base64() -var buff = 'czEz'; -var num = 0; -var result = that.decode(buff,num); -``` -16.createRationalFromString() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(0, 0); -var res = pro.createRationalFromString("-1:2"); -var result1 = res.value(); -``` -17.compareTo() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(2, 1); -var proc = new util.RationalNumber(3, 4); -var res = pro.compareTo(proc); -``` -18.equals() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(2, 1); -var proc = new util.RationalNumber(3, 4); -var res = pro.equals(proc); -``` -19.value() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(2, 1); -var res = pro.value(); -``` -20.getCommonDivisor() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(0, 0); -var res = pro.getCommonDivisor(4, 8); -``` -21.getDenominator() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(2, 1); -var res = pro.getDenominator(); -``` -22.getNumerator() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(-2, 1); -var res = pro.getNumerator(); -``` -23.isFinite() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(-2, 1); -var res = pro.isFinite(); -``` -24.isNaN() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(-2, 1); -var res = pro.isNaN(); -``` -25.isZero() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(-2, 1); -var res = pro.isZero(); - -``` -26.toString() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(-2, 1); -var res = pro.toString(); - -``` -27.updateCapacity() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.updateCapacity(100); -``` -28.toString() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.get(2); -pro.remove(20); -var temp = pro.toString(); -``` -29.values() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.put(2,"anhu"); -pro.put("afaf","grfb"); -var temp = pro.values(); -``` -30.size() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.put(1,8); -var temp = pro.size(); -``` -31.capacity() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -var temp = pro.capacity(); -``` -32.clear() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.clear(); -``` -33.getCreatCount() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(1,8); -var temp = pro.getCreatCount(); -``` -34.getMissCount() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.get(2) -var temp = pro.getMissCount(); -``` -35.getRemovalCount() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.updateCapacity(2); -pro.put(50,22); -var temp = pro.getRemovalCount(); -``` -36.getMatchCount() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.get(2); -var temp = pro.getMatchCount(); -``` -37.getPutCount() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var temp = pro.getPutCount(); -``` -38.isEmpty() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var temp = pro.isEmpty(); -``` -39.get() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var temp = pro.get(2); -``` -40.put() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -var temp = pro.put(2,10); -``` -41.keys() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); - pro.put(2,10); -var temp = pro.keys(); -``` -42.remove() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var temp = pro.remove(20); -``` -43.contains() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var temp = pro.contains(20); -``` -44.createDefault() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -var temp = pro.createDefault(50); -``` -45.entries() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var temp = pro.entries(); -``` -46.[Symbol.iterator]() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var temp = aa[symbol.iterator](); -``` -Scope接口中构造新类,实现compareTo方法。 - -``` -class Temperature { - constructor(value) { - this._temp = value; - } - compareTo(value) { - return this._temp >= value.getTemp(); - } - getTemp() { - return this._temp; - } - toString() { - return this._temp.toString(); - } -} -``` - -47.constructor() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var range = new Scope(tempLower, tempUpper); -``` - -48.toString() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var range = new Scope(tempLower, tempUpper); -range.toString() // => [30,40] -``` - -49.intersect() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var range = new Scope(tempLower, tempUpper); -var tempMiDF = new Temperature(35); -var tempMidS = new Temperature(39); -var rangeFir = new Scope(tempMiDF, tempMidS); -range.intersect(rangeFir) // => [35,39] -``` - -50.intersect() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var tempMiDF = new Temperature(35); -var tempMidS = new Temperature(39); -var range = new Scope(tempLower, tempUpper); -range.intersect(tempMiDF, tempMidS) // => [35,39] -``` - -51.getUpper() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var range = new Scope(tempLower, tempUpper); -range.getUpper() // => 40 -``` - -52.getLower() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var range = new Scope(tempLower, tempUpper); -range.getLower() // => 30 -``` - -53.expand() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var tempMiDF = new Temperature(35); -var tempMidS = new Temperature(39); -var range = new Scope(tempLower, tempUpper); -range.expand(tempMiDF, tempMidS) // => [30,40] -``` - -54.expand() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var tempMiDF = new Temperature(35); -var tempMidS = new Temperature(39); -var range = new Scope(tempLower, tempUpper); -var rangeFir = new Scope(tempMiDF, tempMidS); -range.expand(rangeFir) // => [30,40] -``` - -55.expand() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var tempMiDF = new Temperature(35); -var range = new Scope(tempLower, tempUpper); -range.expand(tempMiDF) // => [30,40] -``` - -56.contains() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var tempMiDF = new Temperature(35); -var range = new Scope(tempLower, tempUpper); -range.contains(tempMiDF) // => true -``` - -57.contains() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var range = new Scope(tempLower, tempUpper); -var tempLess = new Temperature(20); -var tempMore = new Temperature(45); -var rangeSec = new Scope(tempLess, tempMore); -range.contains(rangeSec) // => true -``` - -58.clamp() - -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var tempMiDF = new Temperature(35); -var range = new Scope(tempLower, tempUpper); -range.clamp(tempMiDF) // => 35 -``` - - - -## 相关仓 +## Related warehouse -[js_util_module子系统](https://gitee.com/OHOS_STD/js_util_module) +[js_util_module subsystem](https://gitee.com/OHOS_STD/js_util_module) [base/compileruntime/js_util_module/](base/compileruntime/js_util_module-readme.md) diff --git a/README_zh.md b/README_zh.md new file mode 100644 index 0000000..049a05b --- /dev/null +++ b/README_zh.md @@ -0,0 +1,165 @@ +# js_util_module子系统/组件 + +- [简介](#简介) +- [目录](#目录) +- [说明](#说明) + - [接口说明](#接口说明) + - [使用说明](#使用说明) + +- [相关仓](#相关仓) + +## 简介 + +UTIL接口用于字符编码TextEncoder、解码TextDecoder和帮助函数HelpFunction。TextEncoder表示一个文本编码器,接受字符串作为输入,以UTF-8格式进行编码,输出UTF-8字节流。TextDecoder接口表示一个文本解码器,解码器将字节流作为输入,输出stirng字符串。HelpFunction主要是对函数做callback化、promise化以及对错误码进行编写输出,及类字符串的格式化输出。 +## 目录 + +``` +base/compileruntime/js_util_module/ +├── Class:TextEncoder # TextEncoder类 +│ ├── new TextEncoder() # 创建TextEncoder对象 +│ ├── encode() # encode方法 +│ ├── encoding # encoding属性 +│ └── encodeInto() # encodeInto方法 +├── Class:TextDecoder # TextDecoder类 +│ ├── new TextDecoder() # 创建TextDecoder对象 +│ ├── decode() # decode方法 +│ ├── encoding # encoding属性 +│ ├── fatal # fatal属性 +│ └── ignoreBOM # ignoreBOM属性 +├── printf() # printf方法 +├── getErrorString() # getErrorString方法 +├── callbackWrapper() # callbackWrapper方法 +└── promiseWrapper() # promiseWrapper方法 +``` + +## 说明 + +### 接口说明 + + +| 接口名 | 说明 | +| -------- | -------- | +| readonly encoding : string | 获取编码的格式,只支持UTF-8。 | +| encode(input : string) : Uint8Array | 输入stirng字符串,编码并输出UTF-8字节流。 | +| encodeInto(input : string, dest : Uint8Array) : {read : number, written : number} | 输入stirng字符串,dest表示编码后存放位置,返回一个对象,read表示已经编码的字符的个数,written表示已编码字符所占字节的大小。 | +| constructor(encoding? : string, options? : {fatal? : boolean, ignoreBOM? : boolean}) | 构造函数,第一个参数encoding表示解码的格式。第二个参数表示一些属性。属性中fatal表示是否抛出异常,ignoreBOM表示是否忽略bom标志。 | +| readonly encoding : string | 获取设置的解码格式。 | +| readonly fatal : boolean | 获取抛出异常的设置 | +| readonly ignoreBOM : boolean | 获取是否忽略bom标志的设置 | +| decode(input : Uint8Array, options?: { stream?: false }): string| 输入要解码的数据,解出对应的string字符串。第一个参数input表示要解码的数据,第二个参数options表示一个bool标志,表示将跟随附加数据,默认为false。 | +| function printf(format: string, ...args: Object[]): string | printf()方法使用第一个参数作为格式字符串(其可以包含零个或多个格式说明符)来返回格式化的字符串。 | +| function getErrorString(errno: number): string | getErrorString()方法使用一个系统的错误数字作为参数,用来返回系统的错误信息。 | +| function callbackWrapper(original: Function): (err: Object, value: Object) => void | 参数为一个采用 async 函数(或返回 Promise 的函数)并返回遵循错误优先回调风格的函数,即将 (err, value) => ... 回调作为最后一个参数。 在回调中,第一个参数将是拒绝原因(如果 Promise 已解决,则为 null),第二个参数将是已解决的值。 | +| function promiseWrapper(original: (err: Object, value: Object) => void): Object | 参数为采用遵循常见的错误优先的回调风格的函数(也就是将 (err, value) => ... 回调作为最后一个参数),并返回一个返回 promise 的版本。 | + +printf中每个说明符都替换为来自相应参数的转换后的值。 支持的说明符有: +| 式样化字符 | 式样要求 | +| -------- | -------- | +| %s: | String 将用于转换除 BigInt、Object 和 -0 之外的所有值。| +| %d: |Number 将用于转换除 BigInt 和 Symbol 之外的所有值。| +| %i: |parseInt(value, 10) 用于除 BigInt 和 Symbol 之外的所有值。| +| %f: |parseFloat(value) 用于除 Symbol 之外的所有值。| +| %j: |JSON。 如果参数包含循环引用,则替换为字符串 '[Circular]'。| +| %o: |Object. 具有通用 JavaScript 对象格式的对象的字符串表示形式。类似于具有选项 { showHidden: true, showProxy: true } 的 util.inspect()。这将显示完整的对象,包括不可枚举的属性和代理。| +| %O: |Object. 具有通用 JavaScript 对象格式的对象的字符串表示形式。类似于没有选项的 util.inspect()。 这将显示完整的对象,但不包括不可枚举的属性和代理。| +| %c: | 此说明符被忽略,将跳过任何传入的 CSS。| +| %%: |单个百分号 ('%')。 这不消耗待式样化参数。| + +### 使用说明 + +各接口使用方法如下: + +1.readonly encoding() +``` +import util from '@ohos.util' +var textEncoder = new util.TextEncoder(); +var getEncoding = textEncoder.encoding(); +``` +2.encode() +``` +import util from '@ohos.util' +var textEncoder = new util.TextEncoder(); +var result = textEncoder.encode('abc'); +``` +3.encodeInto() +``` +import util from '@ohos.util' +var textEncoder = new util.TextEncoder(); +var obj = textEncoder.encodeInto('abc', dest); +``` +4.textDecoder() +``` +import util from '@ohos.util' +var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); +``` +5.readonly encoding() +``` +import util from '@ohos.util' +var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); +var getEncoding = textDecoder.encoding(); +``` +6.readonly fatal() +``` +import util from '@ohos.util' +var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); +var fatalStr = textDecoder.fatal(); +``` +7.readonly ignoreBOM() +``` +import util from '@ohos.util' +var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); +var ignoreBom = textDecoder.ignoreBOM(); +``` +8.decode() +``` +import util from '@ohos.util' +var textDecoder = new util.textDecoder("utf-16be", {fatal : ture, ignoreBOM : false}); +var result = textDecoder.decode(input, {stream : true}); +``` +9.printf() +``` +import util from '@ohos.util' +var format = "%%%o%%%i%s"; +var value = function aa(){}; +var value1 = 1.5; +var value2 = "qwer"; +var result = util.printf(format,value,value1,value2); +``` +10.getErrorString() +``` +import util from '@ohos.util' +var errnum = 13; +var result = util.getErrorString(errnum); +``` +11.callbackWrapper() +``` +import util from '@ohos.util' +async function promiseFn() { + return Promise.resolve('value'); +}; +var cb = util.callbackWrapper(promiseFn); +cb((err, ret) => { + expect(err).strictEqual(null); + expect(ret).strictEqual('value'); +}) +``` +12.promiseWrapper() +``` +import util from '@ohos.util' +function aysnFun(str1, str2, callback) { + if (typeof str1 === 'string' && typeof str1 === 'string') { + callback(null, str1 + str2); + } else { + callback('type err'); + } +} +let newPromiseObj = util.promiseWrapper(aysnFun)("Hello", 'World'); +newPromiseObj.then(res => { + expect(res).strictEqual('HelloWorld'); +}) +``` +## 相关仓 + +[js_util_module子系统](https://gitee.com/OHOS_STD/js_util_module) + +[base/compileruntime/js_util_module/](base/compileruntime/js_util_module-readme.md) diff --git a/util/js_rational.cpp b/util/js_rational.cpp index 5449740..4133feb 100755 --- a/util/js_rational.cpp +++ b/util/js_rational.cpp @@ -90,23 +90,28 @@ namespace OHOS::Util { size_t index = (colon != std::string::npos) ? colon : semicolon; std::string s1 = buf.substr(0, index); std::string s2 = buf.substr(index + 1, buf.size()); - for (int i = 1; i < s1.size(); i++) { - if (((s1[0] == '+') || (s1[0] == '-') || (isdigit(s1[0]))) && (isdigit(s1[i]))) { - flag = 1; - } else { - napi_throw_error(env_, "invalidRational", "string invalid!"); - } - } + size_t len1 = s1.size(); + size_t len2 = s2.size(); + SetFlag(s1, len1, flag); int num1 = stoi(s1) * flag; - for (int i = 1; i < s2.size(); i++) { - if (((s2[0] == '+') || (s2[0] == '-') || (isdigit(s2[0]))) && (isdigit(s2[i]))) { + flag = 0; + SetFlag(s2, len2, flag); + int num2 = stoi(s2) * flag; + return CreateObj(num1, num2, RationalNumberClass); + } + + void RationalNumber::SetFlag(const std::string str, const size_t len, int& flag) const + { + if (str == "") { + return; + } + for (size_t i = 1; i < len; i++) { + if (((str[0] == '+') || (str[0] == '-') || (isdigit(str[0]))) && (isdigit(str[i]))) { flag = 1; } else { napi_throw_error(env_, "invalidRational", "string invalid!"); } } - int num2 = stoi(s2) * flag; - return CreateObj(num1, num2, RationalNumberClass); } napi_value RationalNumber::CreateObj(int num1, int num2, napi_value RationalNumberClass) const diff --git a/util/js_rational.h b/util/js_rational.h index 8e6f022..49a9ccd 100755 --- a/util/js_rational.h +++ b/util/js_rational.h @@ -41,6 +41,7 @@ namespace OHOS::Util { int mden = 0; napi_env env_; napi_value CreateObj(int num1, int num2, napi_value RationalNumberClass) const; + void SetFlag(const std::string str, const size_t len, int& flag) const; }; } #endif \ No newline at end of file -- Gitee