From a0da145e3a585497d95f7a79af9625412deefbf1 Mon Sep 17 00:00:00 2001 From: 15241154745 Date: Fri, 12 Nov 2021 16:44:16 +0800 Subject: [PATCH 1/6] Signed-off-by: 15241154745 On branch master Your branch is up to date with 'origin/master'. --- README.md | 2 +- README_zh.md | 2 +- util/build_ts_js.py | 48 +++++++++++++++++++++++++-------------------- 3 files changed, 29 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index c57df85..d39b2d4 100755 --- a/README.md +++ b/README.md @@ -528,7 +528,7 @@ var result = pro.entries(); import util from '@ohos.util' var pro = new util.LruBuffer(); pro.put(2,10); -var result = aa[symbol.iterator](); +var result = pro[symbol.iterator](); ``` 50.afterRemoval() ``` diff --git a/README_zh.md b/README_zh.md index 3f2d966..a603192 100644 --- a/README_zh.md +++ b/README_zh.md @@ -529,7 +529,7 @@ var result = pro.entries(); import util from '@ohos.util' var pro = new util.LruBuffer(); pro.put(2,10); -var result = aa[symbol.iterator](); +var result = pro[symbol.iterator](); ``` 50.afterRemoval() ``` diff --git a/util/build_ts_js.py b/util/build_ts_js.py index e976212..cb4d8eb 100755 --- a/util/build_ts_js.py +++ b/util/build_ts_js.py @@ -17,33 +17,39 @@ import platform import argparse import subprocess -def run_command(cmd): - print(" ".join(cmd)) - proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, - stderr=subprocess.PIPE, universal_newlines=True) - out, err = proc.communicate() - if out != "": - print(out) +def run_command(in_cmd): + print(" ".join(in_cmd)) + proc = subprocess.Popen(in_cmd, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True, + shell=False) + stdout, stderr = proc.communicate() + if stdout != "": + print(stdout) exit(1) + if __name__ == '__main__': - - build_path = os.path.abspath(os.path.join(os.getcwd(), "../..")) - os.chdir("%s/base/compileruntime/js_util_module/util" % build_path) - parser = argparse.ArgumentParser() - parser.add_argument('--dst-file', + BUILD_PATH = os.path.abspath(os.path.join(os.getcwd(), "../..")) + os.chdir("%s/base/compileruntime/js_util_module/util" % BUILD_PATH) + + PARSER_INST = argparse.ArgumentParser() + PARSER_INST.add_argument('--dst-file', help='the converted target file') - input_arguments = parser.parse_args() + INPUT_ARGUMENTS = PARSER_INST.parse_args() + - node = '../../../../prebuilts/build-tools/common/nodejs/\ + NODE_PATH = '../../../../prebuilts/build-tools/common/nodejs/\ node-v12.18.4-linux-x64/bin/node' - tsc = '../../../../ark/ts2abc/ts2panda/node_modules/typescript/bin/tsc' - cmd = [node, tsc] - run_command(cmd) + TSC_PATH = '../../../../ark/ts2abc/ts2panda/node_modules/\ +typescript/bin/tsc' + CMD_INST = [NODE_PATH, TSC_PATH] + run_command(CMD_INST) - cmd = ['cp', "-r", './out/util_js.js', input_arguments.dst_file] - run_command(cmd) + CMD_INST = ['cp', "-r", './out/util_js.js', INPUT_ARGUMENTS.dst_file] + run_command(CMD_INST) - cmd = ['rm', "-rf", './out'] - run_command(cmd) \ No newline at end of file + CMD_INST = ['rm', "-rf", './out'] + run_command(CMD_INST) + exit(0) -- Gitee From 59b9c97e48ee8da3a509a516e47a64396c288aad Mon Sep 17 00:00:00 2001 From: clearme777 <9628372+clearme777@user.noreply.gitee.com> Date: Mon, 15 Nov 2021 07:30:40 +0000 Subject: [PATCH 2/6] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=96=87=E4=BB=B6=20util?= =?UTF-8?q?/src/util=5Fjs.ts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- util/src/util_js.ts | 975 -------------------------------------------- 1 file changed, 975 deletions(-) delete mode 100644 util/src/util_js.ts diff --git a/util/src/util_js.ts b/util/src/util_js.ts deleted file mode 100644 index 09cf79d..0000000 --- a/util/src/util_js.ts +++ /dev/null @@ -1,975 +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. - */ -declare function requireInternal(s : string) : any; -const helpUtil = requireInternal('util'); -let TextEncoder = helpUtil.TextEncoder; -let TextDecoder = helpUtil.TextDecoder; -let Base64 = helpUtil.Base64; - -function switchLittleObject(enter : string, obj : any, count : number) -{ - var str = ''; - if (obj === null) { - str += obj; - } else if (obj instanceof Array) { - str += '[ ' + arrayToString(enter, obj, count) + '[length]: ' + obj.length + ' ]'; - } else if (typeof obj === 'function') { - str += '{ [Function: ' + obj.name + ']' + enter - + '[length]: ' + obj.length + ',' + enter - + '[name] :\'' + obj.name + '\',' + enter - + '[prototype]: ' + obj.name + ' { [constructor]: [Circular] } }'; - } else if (typeof obj === 'object') { - str += '{ '; - let i; - let flag = false; - for (i in obj) { - flag = true; - str += switchLittleValue(enter, i, obj, count); - } - if (!flag) { - return obj; - } - str = str.substr(0, str.length - enter.length - 1); - str += ' }'; - } else if (typeof obj === 'string') { - str += '\'' + obj + '\''; - } else { - str += obj; - } - return str; -} - -function switchLittleValue(enter : string, protoName : any, obj : any, count : number) -{ - var str = ''; - if (obj[protoName] === null) { - str += protoName + ': null,' + enter; - } else if (obj[protoName] instanceof Array) { - str += protoName + ':' + enter - + '[ ' + arrayToString(enter + ' ', obj[protoName], count) + '[length]: ' - + obj[protoName].length + ' ],' + enter; - } else if (typeof obj[protoName] === 'object') { - if (obj[protoName] === obj) { - str += protoName + ': [Circular]' + enter; - } else { - str += protoName + ':' + enter; - str += switchLittleObject(enter + ' ', obj[protoName], count + 1) + ',' + enter; - } - } else if (typeof obj[protoName] === 'function') { - var space = enter; - if (obj[protoName].name !== '') { - str += obj[protoName].name + ':' + space; - } - space += ' '; - str += '{ [Function: ' + obj[protoName].name + ']' + space - + '[length]: ' + obj[protoName].length + ',' + space - + '[name] :\'' + obj[protoName].name + '\',' + space - + '[prototype]: ' + obj[protoName].name - + ' { [constructor]: [Circular] } },' + enter; - } else { - if (typeof obj[protoName] === 'string') { - str += protoName + ': \'' + obj[protoName] + '\',' + enter; - } else { - str += protoName + ': ' + obj[protoName] + ',' + enter; - } - } - return str; -} - -function arrayToString(enter : string, arr : any, count : number) -{ - var str = ''; - if (!arr.length) { - return ''; - } - var arrayEnter = ', '; - for (let k in arr) { - if (arr[k] !== null && (typeof arr[k] === 'function' || typeof arr[k] === 'object') && count <= 2) { - arrayEnter += enter; - break; - } - } - for (let i in arr) { - if (typeof arr[i] === 'string') { - str += '\'' + arr[i].toString() + '\'' + arrayEnter; - } else if (typeof arr[i] === 'object') { - str += switchLittleObject(enter + ' ', arr[i], count + 1); - str += arrayEnter; - } else if (typeof arr[i] === 'function') { - var space = enter; - space += ' '; - var end = ''; - if (arr[i].name !== '') { - str += '{ [Function: ' + arr[i].name + ']' + space; - end = arr[i].name + ' { [constructor]: [Circular] } }' + arrayEnter; - } else { - str += '{ [Function]' + space; - end = '{ [constructor]: [Circular] } }' + arrayEnter; - } - str += '[length]: ' - + arr[i].length + ',' + space - + '[name] :\'' + arr[i].name + '\',' + space - + '[prototype]: ' + end; - } else { - str += arr[i] + arrayEnter; - } - } - return str; -} - -function switchBigObject(enter : string, obj : any, count : number) -{ - var str = ''; - if (obj === null) { - str += obj; - } else if (obj instanceof Array) { - str += '[ ' + arrayToBigString(enter, obj, count) + ' ]'; - } else if (typeof obj === 'function') { - str += '{ [Function: ' + obj.name + '] }'; - } else if (typeof obj === 'object') { - str += '{ '; - let i; - let flag = false; - for (i in obj) { - flag = true; - str += switchBigValue(enter, i, obj, count); - } - if (!flag) { - return obj; - } - str = str.substr(0, str.length - enter.length - 1); - str += ' }'; - } else if (typeof obj === 'string') { - str += '\'' + obj + '\''; - } else { - str += obj; - } - return str; -} - -function switchBigValue(enter : string, protoName : any, obj : any, count : number) -{ - var str = ''; - if (obj[protoName] === null) { - str += protoName + ': null,' + enter; - } else if (obj[protoName] instanceof Array) { - str += protoName + ':' + enter - + '[ ' + arrayToBigString(enter + ' ', obj[protoName], count) + ' ],' + enter; - } else if (typeof obj[protoName] === 'object') { - if (obj[protoName] === obj) { - str += protoName + ': [Circular]' + enter; - } else { - str += protoName + ':' + enter; - str += switchBigObject(enter + ' ', obj[protoName], count + 1) + ',' + enter; - } - } else if (typeof obj[protoName] === 'function') { - if (obj[protoName].name !== '') { - str += obj[protoName].name + ': '; - } - str += '[Function: ' + obj[protoName].name + '],' + enter; - } else { - if (typeof obj[protoName] === 'string') { - str += protoName + ': \'' + obj[protoName] + '\',' + enter; - } else { - str += protoName + ': ' + obj[protoName] + ',' + enter; - } - } - return str; -} - -function arrayToBigString(enter : string, arr : any, count : number) -{ - var str = ''; - if (!arr.length) { - return ''; - } - - var arrayEnter = ', '; - for (let i in arr) { - if (arr[i] !== null && (typeof arr[i] === 'object') && count <= 2) { - arrayEnter += enter; - break; - } - } - for (let j in arr) { - if (typeof arr[j] === 'string') { - str += '\'' + arr[j] + '\'' + arrayEnter; - } else if (typeof arr[j] === 'object') { - str += switchBigObject(enter + ' ', arr[j], count + 1); - str += arrayEnter; - } else if (typeof arr[j] === 'function') { - if (arr[j].name !== '') { - str += '[Function: ' + arr[j].name + ']' + arrayEnter; - } else { - str += '[Function]' + arrayEnter; - } - } else { - str += arr[j] + arrayEnter; - } - } - str = str.substr(0, str.length - arrayEnter.length); - return str; -} - -function switchIntValue(value : any) -{ - var str = ''; - if (value === '') { - str += 'NaN'; - } else if (typeof value === 'bigint') { - str += value + 'n'; - } else if (typeof value === 'symbol') { - str += 'NaN'; - } else if (typeof value === 'number') { - str += parseInt(value, 10); // 10:The function uses decimal. - } else if (value instanceof Array) { - if (typeof value[0] === 'number') { - str += parseInt(value[0], 10); // 10:The function uses decimal. - } else if (typeof value[0] === 'string') { - if (isNaN(value[0])) { - str += 'NaN'; - } else { - str += parseInt(value[0], 10); // 10:The function uses decimal. - } - } - } else if (typeof value === 'string') { - if (isNaN(value)) { - str += 'NaN'; - } else { - str += parseInt(value, 10); // 10:The function uses decimal. - } - } else { - str += 'NaN'; - } - return str; -} - -function switchFloatValue(value : any) -{ - var str = ''; - if (value === '') { - str += 'NaN'; - } else if (typeof value === 'symbol') { - str += 'NaN'; - } else if (typeof value === 'number') { - str += value; - } else if (value instanceof Array) { - if (typeof value[0] === 'number') { - str += parseFloat(value); - } else if (typeof value[0] === 'string') { - if (isNaN(value[0])) { - str += 'NaN'; - } else { - str += parseFloat(value[0]); - } - } - } else if (typeof value === 'string') { - if (isNaN(value)) { - str += 'NaN'; - } else { - str += parseFloat(value); - } - } else if (typeof value === 'bigint') { - str += value; - } else { - str += 'NaN'; - } - return str; -} - -function switchNumberValue(value : any) -{ - var str = ''; - if (value === '') { - str += '0'; - } else if (typeof value === 'symbol') { - str += 'NaN'; - } else if (typeof value === 'number') { - str += value; - } else if (value instanceof Array) { - str += 'NaN'; - } else if (typeof value === 'string') { - if (isNaN(value)) { - str += 'NaN'; - } else { - str += Number(value); - } - } else if (typeof value === 'bigint') { - str += value.toString() + 'n'; - } else { - str += 'NaN'; - } - return str; -} - -function switchStringValue(value : any) -{ - var str = ''; - if (typeof value === 'undefined') { - str += 'undefined'; - } else if (typeof value === 'object') { - if (value === null) { - str += 'null'; - } else { - str += value; - } - } else if (typeof value === 'symbol') { - str += value.toString(); - } else { - str += value; - } - return str; -} - -function printf(formatString : any, ...valueString : any) -{ - var formats = helpUtil.dealwithformatstring(formatString); - var arr = []; - arr = formats.split(' '); - var switchString = []; - var valueLength = valueString.length; - var arrLength = arr.length; - var i = 0; - for (; i < valueLength && i < arrLength; i++) { - if (arr[i] === 'o') { - switchString.push(switchLittleObject('\n ', valueString[i], 1)); - } else if (arr[i] === 'O') { - switchString.push(switchBigObject('\n ', valueString[i], 1)); - } else if (arr[i] === 'i') { - switchString.push(switchIntValue(valueString[i])); - } else if (arr[i] === 'j') { - switchString.push(JSON.stringify(valueString[i])); - } else if (arr[i] === 'd') { - switchString.push(switchNumberValue(valueString[i])); - } else if (arr[i] === 's') { - switchString.push(switchStringValue(valueString[i])); - } else if (arr[i] === 'f') { - switchString.push(switchFloatValue(valueString[i])); - } else if (arr[i] === 'c') { - switchString.push(valueString[i].toString()); - } - } - while (i < valueLength) { - switchString.push(valueString[i].toString()); - i++; - } - var helpUtilString = helpUtil.printf(formatString, ...switchString); - return helpUtilString; -} - -function getErrorString(errnum : number) -{ - var errorString = helpUtil.geterrorstring(errnum); - return errorString; -} - -function callbackified(original : any, ...args : any) -{ - const maybeCb = args.pop(); - if (typeof maybeCb !== 'function') { - throw new Error('maybe is not function'); - } - const cb = (...args : any) => { - Reflect.apply(maybeCb, this, args); - }; - Reflect.apply(original, this, args).then((ret : any) => cb(null, ret), (rej : any) => cb(rej)); -} - -function getOwnPropertyDescriptors(obj : any) -{ - const result : any = {}; - for (let key of Reflect.ownKeys(obj)) { - result[key] = Object.getOwnPropertyDescriptor(obj, key); - } - return result; -} - -function callbackWrapper(original : any) -{ - if (typeof original !== 'function') { - throw new Error('original is not function'); - } - const descriptors = getOwnPropertyDescriptors(original); - if (typeof descriptors.length.value === 'number') { - descriptors.length.value++; - } - if (typeof descriptors.name.value === 'string') { - descriptors.name.value += 'callbackified'; - } - - function cb(...args : any) { - callbackified(original, ...args); - } - Object.defineProperties(cb, descriptors); - return cb; -} - -function promiseWrapper(func : any) { - // promiseWrapper - return function (...args : any) { - return new Promise((resolve, reject) => { - let callback = function (err : any, ...values : any) { - if (err) { - reject(err); - } else { - resolve(values); - } - }; - func.apply(null, [...args, callback]); - }); - }; -} - -class LruBuffer -{ - private cache: Map; - private maxSize : number = 64; - private putCount : number = 0; - private createCount : number = 0; - private evictionCount : number = 0; - private hitCount : number = 0; - private missCount : number = 0; - - public constructor(capacity?: number) - { - if(capacity !== undefined) { - if (capacity <= 0) { - throw new Error('data error'); - } - this.maxSize = capacity; - } - this.cache = new Map(); - } - public updateCapacity(newCapacity : number) - { - if (newCapacity <= 0) { - throw new Error('data error'); - } else if (this.cache.size >newCapacity) { - this.changeCapacity(newCapacity); - } - this.maxSize = newCapacity; - } - public get(key : any) - { - 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 !== undefined) { - this.put(key, value); - this.afterRemoval(false, key, createValue, value); - return value; - } - return createValue; - } - } - public put(key : any, value : any) - { - if (key === null || value === null) { - throw new Error('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, value); - } else if (this.cache.size >= this.maxSize) { - this.cache.delete(this.cache.keys().next().value); - this.evictionCount++; - } - this.cache.set(key, value); - return former; - } - public getCreateCount() - { - return this.createCount; - } - public getMissCount() - { - return this.missCount; - } - public getRemovalCount() - { - return this.evictionCount; - } - public getMatchCount() - { - return this.hitCount; - } - public getPutCount() - { - return this.putCount; - } - public capacity() - { - return this.maxSize; - } - public size() - { - return this.cache.size; - } - public clear() - { - this.cache.clear(); - this.afterRemoval(false, this.cache.keys(), this.cache.values(), null); - } - public isEmpty() - { - let temp : boolean = false; - if (this.cache.size === 0) { - temp = true; - } - return temp; - } - public contains(key : any) - { - let flag : boolean = 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; - } - public remove(key : any) - { - 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; - } - public toString() - { - let peek : number = 0; - let hitRate : number = 0; - peek = this.hitCount + this.missCount; - if (peek !== 0) { - hitRate = 100 * this.hitCount / peek; - } else { - hitRate = 0; - } - let str : string = ''; - str = 'Lrubuffer[ maxSize = ' + this.maxSize + ', hits = ' + this.hitCount + ', misses = ' + this.missCount - + ', hitRate = ' + hitRate + '% ]'; - return str; - } - public values() - { - let arr = []; - for(let value of this.cache.values()) { - arr.push(value); - } - return arr; - } - public keys() - { - let arr = []; - for(let key of this.cache.keys()) { - arr.push(key); - } - return arr; - } - protected afterRemoval(isEvict : boolean, key : any, value : any, newValue : any) - { - - } - protected createDefault(key : any) - { - return undefined; - } - public entries() - { - let arr = []; - for (let entry of this.cache.entries()) { - arr.push(entry); - } - return arr; - } - public [Symbol.iterator] () - { - let arr = []; - for (let [key, value] of this.cache) { - arr.push([key, value]); - } - return arr; - } - private changeCapacity(newCapacity : number) - { - 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 RationalNumber -{ - private mnum : number = 0; - private mden : number = 0; - public constructor(num : number, den : number) - { - num = den < 0 ? num * (-1) : num; - den = den < 0 ? den * (-1) : den; - if (den == 0) { - if (num > 0) { - this.mnum = 1; - this.mden = 0; - } else if (num < 0) { - this.mnum = -1; - this.mden = 0; - } else { - this.mnum = 0; - this.mden = 0; - } - } else if (num == 0) { - this.mnum = 0; - this.mden = 1; - } else { - let gnum : number = 0; - gnum = this.getCommonDivisor(num, den); - if (gnum != 0) { - this.mnum = num / gnum; - this.mden = den / gnum; - } - } - } - - public createRationalFromString(str : string) - { - if (str == null) { - throw new Error('string invalid!'); - } - if (str == 'NaN') { - return new RationalNumber(0, 0); - } - let colon : number = str.indexOf(':'); - let semicolon : number = str.indexOf('/'); - if ((colon < 0 && semicolon < 0) || (colon > 0 && semicolon > 0)) { - throw new Error('string invalid!'); - } - let index : number = (colon > 0) ? colon : semicolon; - let s1 : string = str.substr(0, index); - let s2 : string = str.substr(index + 1, str.length); - let num1 : number = Number(s1); - let num2 : number = Number(s2); - return new RationalNumber(num1, num2); - } - - public compareTo(other : RationalNumber) - { - if (this.mnum == other.mnum && this.mden == other.mden) { - return 0; - } else if (this.mnum == 0 && this.mden == 0) { - return 1; - } else if ((other.mnum == 0) && (other.mden == 0)) { - return -1; - } else if ((this.mden == 0 && this.mnum > 0) || (other.mden == 0 && other.mnum < 0)) { - return 1; - } else if ((this.mden == 0 && this.mnum < 0) || (other.mden == 0 && other.mnum > 0)) { - return -1; - } - let thisnum : number = this.mnum * other.mden; - let othernum : number = other.mnum * this.mden; - if (thisnum < othernum) { - return -1; - } else if (thisnum > othernum) { - return 1; - } else { - return 0; - } - } - - public equals(obj : object) - { - if (!(obj instanceof RationalNumber)) { - return false; - } - let thisnum : number = this.mnum * obj.mden; - let objnum : number = obj.mnum * this.mden; - if (this.mnum == obj.mnum && this.mden == obj.mden) { - return true; - } else if ((thisnum == objnum) && (this.mnum != 0 && this.mden != 0) && (obj.mnum != 0 && obj.mden != 0)) { - return true; - } else if ((this.mnum == 0 && this.mden != 0) && (obj.mnum == 0 && obj.mden != 0)) { - return true; - } else if ((this.mnum > 0 && this.mden == 0) && (obj.mnum > 0 && obj.mden == 0)) { - return true; - } else if ((this.mnum < 0 && this.mden == 0) && (obj.mnum < 0 && obj.mden == 0)) { - return true; - } else { - return false; - } - } - - public value() - { - if (this.mnum > 0 && this.mden == 0) { - return Number.POSITIVE_INFINITY; - } else if (this.mnum < 0 && this.mden == 0) { - return Number.NEGATIVE_INFINITY; - } else if ((this.mnum == 0) && (this.mden == 0)) { - return Number.NaN; - } else { - return this.mnum / this.mden; - } - } - - public getCommonDivisor(number1 : number, number2 : number) - { - if (number1 == 0 || number2 == 0) { - throw new Error("Parameter cannot be zero!"); - } - let temp : number = 0; - if (number1 < number2) { - temp = number1; - number1 = number2; - number2 = temp; - } - while (number1 % number2 != 0) { - temp = number1 % number2; - number1 = number2; - number2 = temp; - } - return number2; - } - - public getDenominator() - { - return this.mden; - } - - public getNumerator() - { - return this.mnum; - } - - public isFinite() - { - return this.mden != 0; - } - - public isNaN() - { - return this.mnum == 0 && this.mden == 0; - } - - public isZero() - { - return this.mnum == 0 && this.mden != 0; - } - - public toString() - { - let buf : string; - if (this.mnum == 0 && this.mden == 0) { - buf = "NaN"; - } else if (this.mnum > 0 && this.mden == 0) { - buf = "Infinity"; - } else if (this.mnum < 0 && this.mden == 0) { - buf = "-Infinity"; - } else { - buf = String(this.mnum) + '/' + String(this.mden); - } - return buf; - } -} - -interface ScopeComparable { - compareTo(other: ScopeComparable): boolean; -} - -type ScopeType = ScopeComparable; -class Scope { - - private readonly _lowerLimit: ScopeType; - private readonly _upperLimit: ScopeType; - - public constructor(readonly lowerObj: ScopeType, readonly upperObj: ScopeType) { - 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; - } - - public getLower(): ScopeType { - return this._lowerLimit; - } - - public getUpper(): ScopeType { - return this._upperLimit; - } - - public contains(value: ScopeType): boolean; - public contains(scope: Scope): boolean; - public contains(x: any): boolean { - let resLower: boolean; - let resUpper: boolean; - 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; - } - - public clamp(value: ScopeType): ScopeType { - 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; - } - } - - public intersect(scope: Scope): Scope; - public intersect(lowerObj: ScopeType, upperObj: ScopeType): Scope; - public intersect(x: any, y?: any): Scope { - let reLower: boolean; - let reUpper: boolean; - let mLower: ScopeType; - let mUpper: ScopeType; - 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); - } - } - } - - public expand(obj: ScopeType): Scope; - public expand(scope: Scope): Scope; - public expand(lowerObj: ScopeType, upperObj: ScopeType): Scope; - public expand(x: any, y?: any): Scope { - let reLower: boolean; - let reUpper: boolean; - let mLower: ScopeType; - let mUpper: ScopeType; - 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); - } - } - - public toString(): string { - let strLower = this._lowerLimit.toString(); - let strUpper = this._upperLimit.toString(); - return `[${strLower}, ${strUpper}]`; - } - - public checkNull(o: ScopeType, str: string): void { - if(o == null) { - throw new Error(str); - } - } -} - -export default { - printf: printf, - getErrorString: getErrorString, - callbackWrapper: callbackWrapper, - promiseWrapper: promiseWrapper, - TextEncoder: TextEncoder, - TextDecoder: TextDecoder, - Base64: Base64, - LruBuffer: LruBuffer, - RationalNumber : RationalNumber, - Scope : Scope, -}; \ No newline at end of file -- Gitee From 662e966890dbb1775c19fef4ac74df6aa89f580a Mon Sep 17 00:00:00 2001 From: clearme777 <9628372+clearme777@user.noreply.gitee.com> Date: Mon, 15 Nov 2021 07:30:55 +0000 Subject: [PATCH 3/6] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=96=87=E4=BB=B6=20READ?= =?UTF-8?q?ME=5Fzh.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README_zh.md | 684 --------------------------------------------------- 1 file changed, 684 deletions(-) delete mode 100644 README_zh.md diff --git a/README_zh.md b/README_zh.md deleted file mode 100644 index a603192..0000000 --- a/README_zh.md +++ /dev/null @@ -1,684 +0,0 @@ -# js_util_module子系统/组件 - -- [简介](#简介) -- [目录](#目录) -- [说明](#说明) - - [接口说明](#接口说明) - - [使用说明](#使用说明) - -- [相关仓](#相关仓) - -## 简介 - -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实例的构造函数用于创建具有指定下限和上限的对象,并要求这些对象必须具有可比性。 -## 目录 - -``` -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方法 -│ ├── encodeAsync() # encodeAsync方法 -│ ├── encodeToStringAsync() # encodeToStringAsync方法 -│ └── decodeAsync() # decodeAsync方法 -├── 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方法 -``` -## 说明 - -### 接口说明 - - -| 接口名 | 说明 | -| -------- | -------- | -| readonly encoding : string | 在TextEncoder类中,获取编码的格式,只支持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 | 在TextDecoder类中,获取设置的解码格式。 | -| readonly fatal : boolean | 获取抛出异常的设置。 | -| readonly ignoreBOM : boolean | 获取是否忽略bom标志的设置。 | -| decode(input : Uint8Array, options?: { stream?: false }) : string | 输入要解码的数据,解出对应的string字符串。第一个参数input表示要解码的数据,第二个参数options表示一个bool标志,表示将跟随附加数据,默认为false。 | -| encode(src: Uint8Array): Uint8Array; | 使用Base64编码方案将指定u8数组中的所有字节编码到新分配的u8数组中。 | -| encodeToString(src: Uint8Array): string; | 使用Base64编码方案将指定的字节数组编码为String。 | -| decode(src: Uint8Array \| string): Uint8Array; | 使用Base64编码方案将Base64编码的字符串或输入u8数组解码为新分配的u8数组。 | -| encodeAsync(src: Uint8Array): Promise\; | 使用Base64编码方案将指定u8数组中的所有字节异步编码到新分配的u8数组中。 | -| encodeToStringAsync(src: Uint8Array): Promise\; | 使用Base64编码方案将指定的字节数组异步编码为String。 | -| decodeAsync(src: Uint8Array \| string): Promise\; | 使用Base64编码方案将Base64编码的字符串或输入u8数组异步解码为新分配的u8数组。 | -| static createRationalFromString(rationalString: string): RationalNumber | 基于给定的字符串创建一个RationalNumber对象。 | -| compareTo(another: RationalNumber): number | 将当前的RationalNumber对象与给定的对象进行比较。 | -| equals(obj: object): number | 检查给定对象是否与当前 RationalNumber 对象相同。 | -| value(): number | 将当前的RationalNumber对象进行取整数值或者浮点数值。 | -| static getCommonDivisor(number1: number, number2: number,): number | 获得两个指定数的最大公约数。 | -| getDenominator(): number | 获取当前的RationalNumber对象的分母。 | -| getNumerator(): number | 获取当前的RationalNumber对象的分子。 | -| isFinite(): boolean | 检查当前的RationalNumber对象是有限的。 | -| isNaN(): boolean | 检查当前RationalNumber对象是否表示非数字(NaN)值。 | -| isZero(): boolean | 检查当前RationalNumber对象是否表示零值。 | -| toString(): string | 获取当前RationalNumber对象的字符串表示形式。 | -| constructor(capacity?: number) | 创建默认构造函数用于创建一个新的LruBuffer实例,默认容量为64。 | -| 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(key: K) : V \| undefined | 表示要查询的键,输出如果指定的键存在于缓冲区中,则返回与键关联的值;否则返回undefined。 | -| put(key: K , value: V): V | 将键值对添加到缓冲区,输出与添加的键关联的值;如果要添加的键已经存在,则返回原始值,如果键或值为空,则抛出此异常。 | -| keys(): K[ ] | 获取当前缓冲区中值的键列表,输出返回从最近访问到最近最少访问排序的键列表。 | -| remove​(key: K): V \| undefined | 从当前缓冲区中删除指定的键及其关联的值。 | -| afterRemoval(isEvict: boolean, key: K, value : V, newValue : V):void | 删除值后执行后续操作。 | -| contains(key: K): boolean | 检查当前缓冲区是否包含指定的键,输出如果缓冲区包含指定的键,则返回 true 。 | -| createDefault(key: K): 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 | 获取当前范围的上限。 | -| getLower(): ScopeType | 获取当前范围的下限。 | -| expand(lowerObj: ScopeType, upperObj: ScopeType): Scope | 创建并返回包括当前范围和给定下限和上限的并集。 | -| expand(range: Scope): Scope | 创建并返回包括当前范围和给定范围的并集。 | -| expand(value: ScopeType): Scope | 创建并返回包括当前范围和给定值的并集。 | -| contains(value: ScopeType): boolean | 检查给定value是否包含在当前范围内。 | -| contains(range: Scope): boolean | 检查给定range是否在当前范围内。 | -| clamp(value: ScopeType): ScopeType | 将给定value限定到当前范围内。 | -| 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'); -}) -``` -13.encode() -``` -import util from '@ohos.util' -var that = new util.Base64(); -var array = new Uint8Array([115,49,51]); -var result = that.encode(array); -``` -14.encodeToString() -``` -import util from '@ohos.util' -var that = new util.Base64(); -var array = new Uint8Array([115,49,51]); -var result = that.encodeToString(array); -``` -15.decode() -``` -import util from '@ohos.util' -var that = new util.Base64() -var buff = 'czEz'; -var result = that.decode(buff); - -``` -16.encodeAsync() -``` -import util from '@ohos.util' -var that = new util.Base64() -var array = new Uint8Array([115,49,51]); -await that.encodeAsync(array).then(val=>{ -}) -done() -``` -17.encodeToStringAsync() -``` -import util from '@ohos.util' -var that = new util.Base64() -var array = new Uint8Array([115,49,51]); -await that.encodeToStringAsync(array).then(val=>{ -}) -done() -``` -18.decodeAsync() -``` -import util from '@ohos.util' -var that = new util.Base64() -var buff = 'czEz'; -await that.decodeAsync(buff).then(val=>{ -}) -done() -``` -19.createRationalFromString() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(0, 0); -var res = pro.createRationalFromString("-1:2"); -var result1 = res.value(); -``` -20.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); -``` -21.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); -``` -22.value() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(2, 1); -var res = pro.value(); -``` -23.getCommonDivisor() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(0, 0); -var res = pro.getCommonDivisor(4, 8); -``` -24.getDenominator() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(2, 1); -var res = pro.getDenominator(); -``` -25.getNumerator() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(-2, 1); -var res = pro.getNumerator(); -``` -26.isFinite() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(-2, 1); -var res = pro.isFinite(); -``` -27.isNaN() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(-2, 1); -var res = pro.isNaN(); -``` -28.isZero() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(-2, 1); -var res = pro.isZero(); - -``` -29.toString() -``` -import util from '@ohos.util' -var pro = new util.RationalNumber(-2, 1); -var res = pro.toString(); - -``` -30.updateCapacity() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -var result = pro.updateCapacity(100); -``` -31.toString() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.get(2); -pro.remove(20); -var result = pro.toString(); -``` -32.values() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.put(2,"anhu"); -pro.put("afaf","grfb"); -var result = pro.values(); -``` -33.size() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.put(1,8); -var result = pro.size(); -``` -34.capacity() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -var result = pro.capacity(); -``` -35.clear() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.clear(); -``` -36.getCreateCount() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(1,8); -var result = pro.getCreateCount(); -``` -37.getMissCount() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.get(2) -var result = pro.getMissCount(); -``` -38.getRemovalCount() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.updateCapacity(2); -pro.put(50,22); -var result = pro.getRemovalCount(); -``` -39.getMatchCount() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -pro.get(2); -var result = pro.getMatchCount(); -``` -40.getPutCount() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var result = pro.getPutCount(); -``` -41.isEmpty() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var result = pro.isEmpty(); -``` -42.get() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var result = pro.get(2); -``` -43.put() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -var result = pro.put(2,10); -``` -44.keys() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var result = pro.keys(); -``` -45.remove() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var result = pro.remove(20); -``` -46.contains() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var result = pro.contains(20); -``` -47.createDefault() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -var result = pro.createDefault(50); -``` -48.entries() -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var result = pro.entries(); -``` -49.\[Symbol.iterator\]() - -``` -import util from '@ohos.util' -var pro = new util.LruBuffer(); -pro.put(2,10); -var result = pro[symbol.iterator](); -``` -50.afterRemoval() -``` -import util from '@ohos.util' -var arr = [ ]; -class ChildLruBuffer extends util.LruBuffer -{ - constructor() - { - super(); - } - static getInstance() - { - if(this.instance == null) - { - this.instance = new ChildLruBuffer(); - } - return this.instance; - } - afterRemoval(isEvict, key, value, newValue) - { - if (isEvict === false) - { - arr = [key, value, newValue]; - } - } -} -ChildLruBuffer.getInstance().afterRemoval(false,10,30,null) -``` -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(); - } -} -``` -51.constructor() -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var range = new Scope(tempLower, tempUpper); -``` -52.toString() -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var range = new Scope(tempLower, tempUpper); -var result = range.toString() // => [30,40] -``` -53.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); -var result = range.intersect(rangeFir) // => [35,39] -``` -54.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); -var result = range.intersect(tempMiDF, tempMidS) // => [35,39] -``` -55.getUpper() -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var range = new Scope(tempLower, tempUpper); -var result = range.getUpper() // => 40 -``` -56.getLower() -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var range = new Scope(tempLower, tempUpper); -var result = range.getLower() // => 30 -``` -57.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 result = range.expand(tempMiDF, tempMidS) // => [30,40] -``` -58.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); -var result = range.expand(rangeFir) // => [30,40] -``` -59.expand() -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var tempMiDF = new Temperature(35); -var range = new Scope(tempLower, tempUpper); -var result = range.expand(tempMiDF) // => [30,40] -``` -60.contains() -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var tempMiDF = new Temperature(35); -var range = new Scope(tempLower, tempUpper); -var result = range.contains(tempMiDF) // => true -``` -61.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); -var result = range.contains(rangeSec) // => true -``` -62.clamp() -``` -var tempLower = new Temperature(30); -var tempUpper = new Temperature(40); -var tempMiDF = new Temperature(35); -var range = new Scope(tempLower, tempUpper); -var result = range.clamp(tempMiDF) // => 35 -``` -## 相关仓 - -[js_util_module子系统](https://gitee.com/OHOS_STD/js_util_module) - -[base/compileruntime/js_util_module/](base/compileruntime/js_util_module-readme.md) - -- Gitee From d69a03b4e8986b6a6ffdf646913c88e50a370f38 Mon Sep 17 00:00:00 2001 From: 15241154745 Date: Mon, 15 Nov 2021 15:34:32 +0800 Subject: [PATCH 4/6] Signed-off-by: 15241154745 Signed-off-by:lifansheng On branch master Your branch is up to date with 'origin/master'. --- README_zh.md | 684 +++++++++++++++++++++++++++++++ util/src/util_js.ts | 975 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 1659 insertions(+) create mode 100644 README_zh.md create mode 100644 util/src/util_js.ts diff --git a/README_zh.md b/README_zh.md new file mode 100644 index 0000000..a603192 --- /dev/null +++ b/README_zh.md @@ -0,0 +1,684 @@ +# js_util_module子系统/组件 + +- [简介](#简介) +- [目录](#目录) +- [说明](#说明) + - [接口说明](#接口说明) + - [使用说明](#使用说明) + +- [相关仓](#相关仓) + +## 简介 + +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实例的构造函数用于创建具有指定下限和上限的对象,并要求这些对象必须具有可比性。 +## 目录 + +``` +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方法 +│ ├── encodeAsync() # encodeAsync方法 +│ ├── encodeToStringAsync() # encodeToStringAsync方法 +│ └── decodeAsync() # decodeAsync方法 +├── 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方法 +``` +## 说明 + +### 接口说明 + + +| 接口名 | 说明 | +| -------- | -------- | +| readonly encoding : string | 在TextEncoder类中,获取编码的格式,只支持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 | 在TextDecoder类中,获取设置的解码格式。 | +| readonly fatal : boolean | 获取抛出异常的设置。 | +| readonly ignoreBOM : boolean | 获取是否忽略bom标志的设置。 | +| decode(input : Uint8Array, options?: { stream?: false }) : string | 输入要解码的数据,解出对应的string字符串。第一个参数input表示要解码的数据,第二个参数options表示一个bool标志,表示将跟随附加数据,默认为false。 | +| encode(src: Uint8Array): Uint8Array; | 使用Base64编码方案将指定u8数组中的所有字节编码到新分配的u8数组中。 | +| encodeToString(src: Uint8Array): string; | 使用Base64编码方案将指定的字节数组编码为String。 | +| decode(src: Uint8Array \| string): Uint8Array; | 使用Base64编码方案将Base64编码的字符串或输入u8数组解码为新分配的u8数组。 | +| encodeAsync(src: Uint8Array): Promise\; | 使用Base64编码方案将指定u8数组中的所有字节异步编码到新分配的u8数组中。 | +| encodeToStringAsync(src: Uint8Array): Promise\; | 使用Base64编码方案将指定的字节数组异步编码为String。 | +| decodeAsync(src: Uint8Array \| string): Promise\; | 使用Base64编码方案将Base64编码的字符串或输入u8数组异步解码为新分配的u8数组。 | +| static createRationalFromString(rationalString: string): RationalNumber | 基于给定的字符串创建一个RationalNumber对象。 | +| compareTo(another: RationalNumber): number | 将当前的RationalNumber对象与给定的对象进行比较。 | +| equals(obj: object): number | 检查给定对象是否与当前 RationalNumber 对象相同。 | +| value(): number | 将当前的RationalNumber对象进行取整数值或者浮点数值。 | +| static getCommonDivisor(number1: number, number2: number,): number | 获得两个指定数的最大公约数。 | +| getDenominator(): number | 获取当前的RationalNumber对象的分母。 | +| getNumerator(): number | 获取当前的RationalNumber对象的分子。 | +| isFinite(): boolean | 检查当前的RationalNumber对象是有限的。 | +| isNaN(): boolean | 检查当前RationalNumber对象是否表示非数字(NaN)值。 | +| isZero(): boolean | 检查当前RationalNumber对象是否表示零值。 | +| toString(): string | 获取当前RationalNumber对象的字符串表示形式。 | +| constructor(capacity?: number) | 创建默认构造函数用于创建一个新的LruBuffer实例,默认容量为64。 | +| 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(key: K) : V \| undefined | 表示要查询的键,输出如果指定的键存在于缓冲区中,则返回与键关联的值;否则返回undefined。 | +| put(key: K , value: V): V | 将键值对添加到缓冲区,输出与添加的键关联的值;如果要添加的键已经存在,则返回原始值,如果键或值为空,则抛出此异常。 | +| keys(): K[ ] | 获取当前缓冲区中值的键列表,输出返回从最近访问到最近最少访问排序的键列表。 | +| remove​(key: K): V \| undefined | 从当前缓冲区中删除指定的键及其关联的值。 | +| afterRemoval(isEvict: boolean, key: K, value : V, newValue : V):void | 删除值后执行后续操作。 | +| contains(key: K): boolean | 检查当前缓冲区是否包含指定的键,输出如果缓冲区包含指定的键,则返回 true 。 | +| createDefault(key: K): 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 | 获取当前范围的上限。 | +| getLower(): ScopeType | 获取当前范围的下限。 | +| expand(lowerObj: ScopeType, upperObj: ScopeType): Scope | 创建并返回包括当前范围和给定下限和上限的并集。 | +| expand(range: Scope): Scope | 创建并返回包括当前范围和给定范围的并集。 | +| expand(value: ScopeType): Scope | 创建并返回包括当前范围和给定值的并集。 | +| contains(value: ScopeType): boolean | 检查给定value是否包含在当前范围内。 | +| contains(range: Scope): boolean | 检查给定range是否在当前范围内。 | +| clamp(value: ScopeType): ScopeType | 将给定value限定到当前范围内。 | +| 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'); +}) +``` +13.encode() +``` +import util from '@ohos.util' +var that = new util.Base64(); +var array = new Uint8Array([115,49,51]); +var result = that.encode(array); +``` +14.encodeToString() +``` +import util from '@ohos.util' +var that = new util.Base64(); +var array = new Uint8Array([115,49,51]); +var result = that.encodeToString(array); +``` +15.decode() +``` +import util from '@ohos.util' +var that = new util.Base64() +var buff = 'czEz'; +var result = that.decode(buff); + +``` +16.encodeAsync() +``` +import util from '@ohos.util' +var that = new util.Base64() +var array = new Uint8Array([115,49,51]); +await that.encodeAsync(array).then(val=>{ +}) +done() +``` +17.encodeToStringAsync() +``` +import util from '@ohos.util' +var that = new util.Base64() +var array = new Uint8Array([115,49,51]); +await that.encodeToStringAsync(array).then(val=>{ +}) +done() +``` +18.decodeAsync() +``` +import util from '@ohos.util' +var that = new util.Base64() +var buff = 'czEz'; +await that.decodeAsync(buff).then(val=>{ +}) +done() +``` +19.createRationalFromString() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(0, 0); +var res = pro.createRationalFromString("-1:2"); +var result1 = res.value(); +``` +20.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); +``` +21.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); +``` +22.value() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(2, 1); +var res = pro.value(); +``` +23.getCommonDivisor() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(0, 0); +var res = pro.getCommonDivisor(4, 8); +``` +24.getDenominator() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(2, 1); +var res = pro.getDenominator(); +``` +25.getNumerator() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.getNumerator(); +``` +26.isFinite() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.isFinite(); +``` +27.isNaN() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.isNaN(); +``` +28.isZero() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.isZero(); + +``` +29.toString() +``` +import util from '@ohos.util' +var pro = new util.RationalNumber(-2, 1); +var res = pro.toString(); + +``` +30.updateCapacity() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +var result = pro.updateCapacity(100); +``` +31.toString() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.get(2); +pro.remove(20); +var result = pro.toString(); +``` +32.values() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.put(2,"anhu"); +pro.put("afaf","grfb"); +var result = pro.values(); +``` +33.size() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.put(1,8); +var result = pro.size(); +``` +34.capacity() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +var result = pro.capacity(); +``` +35.clear() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.clear(); +``` +36.getCreateCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(1,8); +var result = pro.getCreateCount(); +``` +37.getMissCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.get(2) +var result = pro.getMissCount(); +``` +38.getRemovalCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.updateCapacity(2); +pro.put(50,22); +var result = pro.getRemovalCount(); +``` +39.getMatchCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +pro.get(2); +var result = pro.getMatchCount(); +``` +40.getPutCount() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.getPutCount(); +``` +41.isEmpty() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.isEmpty(); +``` +42.get() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.get(2); +``` +43.put() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +var result = pro.put(2,10); +``` +44.keys() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.keys(); +``` +45.remove() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.remove(20); +``` +46.contains() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.contains(20); +``` +47.createDefault() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +var result = pro.createDefault(50); +``` +48.entries() +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro.entries(); +``` +49.\[Symbol.iterator\]() + +``` +import util from '@ohos.util' +var pro = new util.LruBuffer(); +pro.put(2,10); +var result = pro[symbol.iterator](); +``` +50.afterRemoval() +``` +import util from '@ohos.util' +var arr = [ ]; +class ChildLruBuffer extends util.LruBuffer +{ + constructor() + { + super(); + } + static getInstance() + { + if(this.instance == null) + { + this.instance = new ChildLruBuffer(); + } + return this.instance; + } + afterRemoval(isEvict, key, value, newValue) + { + if (isEvict === false) + { + arr = [key, value, newValue]; + } + } +} +ChildLruBuffer.getInstance().afterRemoval(false,10,30,null) +``` +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(); + } +} +``` +51.constructor() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +``` +52.toString() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +var result = range.toString() // => [30,40] +``` +53.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); +var result = range.intersect(rangeFir) // => [35,39] +``` +54.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); +var result = range.intersect(tempMiDF, tempMidS) // => [35,39] +``` +55.getUpper() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +var result = range.getUpper() // => 40 +``` +56.getLower() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var range = new Scope(tempLower, tempUpper); +var result = range.getLower() // => 30 +``` +57.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 result = range.expand(tempMiDF, tempMidS) // => [30,40] +``` +58.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); +var result = range.expand(rangeFir) // => [30,40] +``` +59.expand() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var range = new Scope(tempLower, tempUpper); +var result = range.expand(tempMiDF) // => [30,40] +``` +60.contains() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var range = new Scope(tempLower, tempUpper); +var result = range.contains(tempMiDF) // => true +``` +61.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); +var result = range.contains(rangeSec) // => true +``` +62.clamp() +``` +var tempLower = new Temperature(30); +var tempUpper = new Temperature(40); +var tempMiDF = new Temperature(35); +var range = new Scope(tempLower, tempUpper); +var result = range.clamp(tempMiDF) // => 35 +``` +## 相关仓 + +[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/src/util_js.ts b/util/src/util_js.ts new file mode 100644 index 0000000..09cf79d --- /dev/null +++ b/util/src/util_js.ts @@ -0,0 +1,975 @@ +/* + * 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. + */ +declare function requireInternal(s : string) : any; +const helpUtil = requireInternal('util'); +let TextEncoder = helpUtil.TextEncoder; +let TextDecoder = helpUtil.TextDecoder; +let Base64 = helpUtil.Base64; + +function switchLittleObject(enter : string, obj : any, count : number) +{ + var str = ''; + if (obj === null) { + str += obj; + } else if (obj instanceof Array) { + str += '[ ' + arrayToString(enter, obj, count) + '[length]: ' + obj.length + ' ]'; + } else if (typeof obj === 'function') { + str += '{ [Function: ' + obj.name + ']' + enter + + '[length]: ' + obj.length + ',' + enter + + '[name] :\'' + obj.name + '\',' + enter + + '[prototype]: ' + obj.name + ' { [constructor]: [Circular] } }'; + } else if (typeof obj === 'object') { + str += '{ '; + let i; + let flag = false; + for (i in obj) { + flag = true; + str += switchLittleValue(enter, i, obj, count); + } + if (!flag) { + return obj; + } + str = str.substr(0, str.length - enter.length - 1); + str += ' }'; + } else if (typeof obj === 'string') { + str += '\'' + obj + '\''; + } else { + str += obj; + } + return str; +} + +function switchLittleValue(enter : string, protoName : any, obj : any, count : number) +{ + var str = ''; + if (obj[protoName] === null) { + str += protoName + ': null,' + enter; + } else if (obj[protoName] instanceof Array) { + str += protoName + ':' + enter + + '[ ' + arrayToString(enter + ' ', obj[protoName], count) + '[length]: ' + + obj[protoName].length + ' ],' + enter; + } else if (typeof obj[protoName] === 'object') { + if (obj[protoName] === obj) { + str += protoName + ': [Circular]' + enter; + } else { + str += protoName + ':' + enter; + str += switchLittleObject(enter + ' ', obj[protoName], count + 1) + ',' + enter; + } + } else if (typeof obj[protoName] === 'function') { + var space = enter; + if (obj[protoName].name !== '') { + str += obj[protoName].name + ':' + space; + } + space += ' '; + str += '{ [Function: ' + obj[protoName].name + ']' + space + + '[length]: ' + obj[protoName].length + ',' + space + + '[name] :\'' + obj[protoName].name + '\',' + space + + '[prototype]: ' + obj[protoName].name + + ' { [constructor]: [Circular] } },' + enter; + } else { + if (typeof obj[protoName] === 'string') { + str += protoName + ': \'' + obj[protoName] + '\',' + enter; + } else { + str += protoName + ': ' + obj[protoName] + ',' + enter; + } + } + return str; +} + +function arrayToString(enter : string, arr : any, count : number) +{ + var str = ''; + if (!arr.length) { + return ''; + } + var arrayEnter = ', '; + for (let k in arr) { + if (arr[k] !== null && (typeof arr[k] === 'function' || typeof arr[k] === 'object') && count <= 2) { + arrayEnter += enter; + break; + } + } + for (let i in arr) { + if (typeof arr[i] === 'string') { + str += '\'' + arr[i].toString() + '\'' + arrayEnter; + } else if (typeof arr[i] === 'object') { + str += switchLittleObject(enter + ' ', arr[i], count + 1); + str += arrayEnter; + } else if (typeof arr[i] === 'function') { + var space = enter; + space += ' '; + var end = ''; + if (arr[i].name !== '') { + str += '{ [Function: ' + arr[i].name + ']' + space; + end = arr[i].name + ' { [constructor]: [Circular] } }' + arrayEnter; + } else { + str += '{ [Function]' + space; + end = '{ [constructor]: [Circular] } }' + arrayEnter; + } + str += '[length]: ' + + arr[i].length + ',' + space + + '[name] :\'' + arr[i].name + '\',' + space + + '[prototype]: ' + end; + } else { + str += arr[i] + arrayEnter; + } + } + return str; +} + +function switchBigObject(enter : string, obj : any, count : number) +{ + var str = ''; + if (obj === null) { + str += obj; + } else if (obj instanceof Array) { + str += '[ ' + arrayToBigString(enter, obj, count) + ' ]'; + } else if (typeof obj === 'function') { + str += '{ [Function: ' + obj.name + '] }'; + } else if (typeof obj === 'object') { + str += '{ '; + let i; + let flag = false; + for (i in obj) { + flag = true; + str += switchBigValue(enter, i, obj, count); + } + if (!flag) { + return obj; + } + str = str.substr(0, str.length - enter.length - 1); + str += ' }'; + } else if (typeof obj === 'string') { + str += '\'' + obj + '\''; + } else { + str += obj; + } + return str; +} + +function switchBigValue(enter : string, protoName : any, obj : any, count : number) +{ + var str = ''; + if (obj[protoName] === null) { + str += protoName + ': null,' + enter; + } else if (obj[protoName] instanceof Array) { + str += protoName + ':' + enter + + '[ ' + arrayToBigString(enter + ' ', obj[protoName], count) + ' ],' + enter; + } else if (typeof obj[protoName] === 'object') { + if (obj[protoName] === obj) { + str += protoName + ': [Circular]' + enter; + } else { + str += protoName + ':' + enter; + str += switchBigObject(enter + ' ', obj[protoName], count + 1) + ',' + enter; + } + } else if (typeof obj[protoName] === 'function') { + if (obj[protoName].name !== '') { + str += obj[protoName].name + ': '; + } + str += '[Function: ' + obj[protoName].name + '],' + enter; + } else { + if (typeof obj[protoName] === 'string') { + str += protoName + ': \'' + obj[protoName] + '\',' + enter; + } else { + str += protoName + ': ' + obj[protoName] + ',' + enter; + } + } + return str; +} + +function arrayToBigString(enter : string, arr : any, count : number) +{ + var str = ''; + if (!arr.length) { + return ''; + } + + var arrayEnter = ', '; + for (let i in arr) { + if (arr[i] !== null && (typeof arr[i] === 'object') && count <= 2) { + arrayEnter += enter; + break; + } + } + for (let j in arr) { + if (typeof arr[j] === 'string') { + str += '\'' + arr[j] + '\'' + arrayEnter; + } else if (typeof arr[j] === 'object') { + str += switchBigObject(enter + ' ', arr[j], count + 1); + str += arrayEnter; + } else if (typeof arr[j] === 'function') { + if (arr[j].name !== '') { + str += '[Function: ' + arr[j].name + ']' + arrayEnter; + } else { + str += '[Function]' + arrayEnter; + } + } else { + str += arr[j] + arrayEnter; + } + } + str = str.substr(0, str.length - arrayEnter.length); + return str; +} + +function switchIntValue(value : any) +{ + var str = ''; + if (value === '') { + str += 'NaN'; + } else if (typeof value === 'bigint') { + str += value + 'n'; + } else if (typeof value === 'symbol') { + str += 'NaN'; + } else if (typeof value === 'number') { + str += parseInt(value, 10); // 10:The function uses decimal. + } else if (value instanceof Array) { + if (typeof value[0] === 'number') { + str += parseInt(value[0], 10); // 10:The function uses decimal. + } else if (typeof value[0] === 'string') { + if (isNaN(value[0])) { + str += 'NaN'; + } else { + str += parseInt(value[0], 10); // 10:The function uses decimal. + } + } + } else if (typeof value === 'string') { + if (isNaN(value)) { + str += 'NaN'; + } else { + str += parseInt(value, 10); // 10:The function uses decimal. + } + } else { + str += 'NaN'; + } + return str; +} + +function switchFloatValue(value : any) +{ + var str = ''; + if (value === '') { + str += 'NaN'; + } else if (typeof value === 'symbol') { + str += 'NaN'; + } else if (typeof value === 'number') { + str += value; + } else if (value instanceof Array) { + if (typeof value[0] === 'number') { + str += parseFloat(value); + } else if (typeof value[0] === 'string') { + if (isNaN(value[0])) { + str += 'NaN'; + } else { + str += parseFloat(value[0]); + } + } + } else if (typeof value === 'string') { + if (isNaN(value)) { + str += 'NaN'; + } else { + str += parseFloat(value); + } + } else if (typeof value === 'bigint') { + str += value; + } else { + str += 'NaN'; + } + return str; +} + +function switchNumberValue(value : any) +{ + var str = ''; + if (value === '') { + str += '0'; + } else if (typeof value === 'symbol') { + str += 'NaN'; + } else if (typeof value === 'number') { + str += value; + } else if (value instanceof Array) { + str += 'NaN'; + } else if (typeof value === 'string') { + if (isNaN(value)) { + str += 'NaN'; + } else { + str += Number(value); + } + } else if (typeof value === 'bigint') { + str += value.toString() + 'n'; + } else { + str += 'NaN'; + } + return str; +} + +function switchStringValue(value : any) +{ + var str = ''; + if (typeof value === 'undefined') { + str += 'undefined'; + } else if (typeof value === 'object') { + if (value === null) { + str += 'null'; + } else { + str += value; + } + } else if (typeof value === 'symbol') { + str += value.toString(); + } else { + str += value; + } + return str; +} + +function printf(formatString : any, ...valueString : any) +{ + var formats = helpUtil.dealwithformatstring(formatString); + var arr = []; + arr = formats.split(' '); + var switchString = []; + var valueLength = valueString.length; + var arrLength = arr.length; + var i = 0; + for (; i < valueLength && i < arrLength; i++) { + if (arr[i] === 'o') { + switchString.push(switchLittleObject('\n ', valueString[i], 1)); + } else if (arr[i] === 'O') { + switchString.push(switchBigObject('\n ', valueString[i], 1)); + } else if (arr[i] === 'i') { + switchString.push(switchIntValue(valueString[i])); + } else if (arr[i] === 'j') { + switchString.push(JSON.stringify(valueString[i])); + } else if (arr[i] === 'd') { + switchString.push(switchNumberValue(valueString[i])); + } else if (arr[i] === 's') { + switchString.push(switchStringValue(valueString[i])); + } else if (arr[i] === 'f') { + switchString.push(switchFloatValue(valueString[i])); + } else if (arr[i] === 'c') { + switchString.push(valueString[i].toString()); + } + } + while (i < valueLength) { + switchString.push(valueString[i].toString()); + i++; + } + var helpUtilString = helpUtil.printf(formatString, ...switchString); + return helpUtilString; +} + +function getErrorString(errnum : number) +{ + var errorString = helpUtil.geterrorstring(errnum); + return errorString; +} + +function callbackified(original : any, ...args : any) +{ + const maybeCb = args.pop(); + if (typeof maybeCb !== 'function') { + throw new Error('maybe is not function'); + } + const cb = (...args : any) => { + Reflect.apply(maybeCb, this, args); + }; + Reflect.apply(original, this, args).then((ret : any) => cb(null, ret), (rej : any) => cb(rej)); +} + +function getOwnPropertyDescriptors(obj : any) +{ + const result : any = {}; + for (let key of Reflect.ownKeys(obj)) { + result[key] = Object.getOwnPropertyDescriptor(obj, key); + } + return result; +} + +function callbackWrapper(original : any) +{ + if (typeof original !== 'function') { + throw new Error('original is not function'); + } + const descriptors = getOwnPropertyDescriptors(original); + if (typeof descriptors.length.value === 'number') { + descriptors.length.value++; + } + if (typeof descriptors.name.value === 'string') { + descriptors.name.value += 'callbackified'; + } + + function cb(...args : any) { + callbackified(original, ...args); + } + Object.defineProperties(cb, descriptors); + return cb; +} + +function promiseWrapper(func : any) { + // promiseWrapper + return function (...args : any) { + return new Promise((resolve, reject) => { + let callback = function (err : any, ...values : any) { + if (err) { + reject(err); + } else { + resolve(values); + } + }; + func.apply(null, [...args, callback]); + }); + }; +} + +class LruBuffer +{ + private cache: Map; + private maxSize : number = 64; + private putCount : number = 0; + private createCount : number = 0; + private evictionCount : number = 0; + private hitCount : number = 0; + private missCount : number = 0; + + public constructor(capacity?: number) + { + if(capacity !== undefined) { + if (capacity <= 0) { + throw new Error('data error'); + } + this.maxSize = capacity; + } + this.cache = new Map(); + } + public updateCapacity(newCapacity : number) + { + if (newCapacity <= 0) { + throw new Error('data error'); + } else if (this.cache.size >newCapacity) { + this.changeCapacity(newCapacity); + } + this.maxSize = newCapacity; + } + public get(key : any) + { + 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 !== undefined) { + this.put(key, value); + this.afterRemoval(false, key, createValue, value); + return value; + } + return createValue; + } + } + public put(key : any, value : any) + { + if (key === null || value === null) { + throw new Error('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, value); + } else if (this.cache.size >= this.maxSize) { + this.cache.delete(this.cache.keys().next().value); + this.evictionCount++; + } + this.cache.set(key, value); + return former; + } + public getCreateCount() + { + return this.createCount; + } + public getMissCount() + { + return this.missCount; + } + public getRemovalCount() + { + return this.evictionCount; + } + public getMatchCount() + { + return this.hitCount; + } + public getPutCount() + { + return this.putCount; + } + public capacity() + { + return this.maxSize; + } + public size() + { + return this.cache.size; + } + public clear() + { + this.cache.clear(); + this.afterRemoval(false, this.cache.keys(), this.cache.values(), null); + } + public isEmpty() + { + let temp : boolean = false; + if (this.cache.size === 0) { + temp = true; + } + return temp; + } + public contains(key : any) + { + let flag : boolean = 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; + } + public remove(key : any) + { + 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; + } + public toString() + { + let peek : number = 0; + let hitRate : number = 0; + peek = this.hitCount + this.missCount; + if (peek !== 0) { + hitRate = 100 * this.hitCount / peek; + } else { + hitRate = 0; + } + let str : string = ''; + str = 'Lrubuffer[ maxSize = ' + this.maxSize + ', hits = ' + this.hitCount + ', misses = ' + this.missCount + + ', hitRate = ' + hitRate + '% ]'; + return str; + } + public values() + { + let arr = []; + for(let value of this.cache.values()) { + arr.push(value); + } + return arr; + } + public keys() + { + let arr = []; + for(let key of this.cache.keys()) { + arr.push(key); + } + return arr; + } + protected afterRemoval(isEvict : boolean, key : any, value : any, newValue : any) + { + + } + protected createDefault(key : any) + { + return undefined; + } + public entries() + { + let arr = []; + for (let entry of this.cache.entries()) { + arr.push(entry); + } + return arr; + } + public [Symbol.iterator] () + { + let arr = []; + for (let [key, value] of this.cache) { + arr.push([key, value]); + } + return arr; + } + private changeCapacity(newCapacity : number) + { + 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 RationalNumber +{ + private mnum : number = 0; + private mden : number = 0; + public constructor(num : number, den : number) + { + num = den < 0 ? num * (-1) : num; + den = den < 0 ? den * (-1) : den; + if (den == 0) { + if (num > 0) { + this.mnum = 1; + this.mden = 0; + } else if (num < 0) { + this.mnum = -1; + this.mden = 0; + } else { + this.mnum = 0; + this.mden = 0; + } + } else if (num == 0) { + this.mnum = 0; + this.mden = 1; + } else { + let gnum : number = 0; + gnum = this.getCommonDivisor(num, den); + if (gnum != 0) { + this.mnum = num / gnum; + this.mden = den / gnum; + } + } + } + + public createRationalFromString(str : string) + { + if (str == null) { + throw new Error('string invalid!'); + } + if (str == 'NaN') { + return new RationalNumber(0, 0); + } + let colon : number = str.indexOf(':'); + let semicolon : number = str.indexOf('/'); + if ((colon < 0 && semicolon < 0) || (colon > 0 && semicolon > 0)) { + throw new Error('string invalid!'); + } + let index : number = (colon > 0) ? colon : semicolon; + let s1 : string = str.substr(0, index); + let s2 : string = str.substr(index + 1, str.length); + let num1 : number = Number(s1); + let num2 : number = Number(s2); + return new RationalNumber(num1, num2); + } + + public compareTo(other : RationalNumber) + { + if (this.mnum == other.mnum && this.mden == other.mden) { + return 0; + } else if (this.mnum == 0 && this.mden == 0) { + return 1; + } else if ((other.mnum == 0) && (other.mden == 0)) { + return -1; + } else if ((this.mden == 0 && this.mnum > 0) || (other.mden == 0 && other.mnum < 0)) { + return 1; + } else if ((this.mden == 0 && this.mnum < 0) || (other.mden == 0 && other.mnum > 0)) { + return -1; + } + let thisnum : number = this.mnum * other.mden; + let othernum : number = other.mnum * this.mden; + if (thisnum < othernum) { + return -1; + } else if (thisnum > othernum) { + return 1; + } else { + return 0; + } + } + + public equals(obj : object) + { + if (!(obj instanceof RationalNumber)) { + return false; + } + let thisnum : number = this.mnum * obj.mden; + let objnum : number = obj.mnum * this.mden; + if (this.mnum == obj.mnum && this.mden == obj.mden) { + return true; + } else if ((thisnum == objnum) && (this.mnum != 0 && this.mden != 0) && (obj.mnum != 0 && obj.mden != 0)) { + return true; + } else if ((this.mnum == 0 && this.mden != 0) && (obj.mnum == 0 && obj.mden != 0)) { + return true; + } else if ((this.mnum > 0 && this.mden == 0) && (obj.mnum > 0 && obj.mden == 0)) { + return true; + } else if ((this.mnum < 0 && this.mden == 0) && (obj.mnum < 0 && obj.mden == 0)) { + return true; + } else { + return false; + } + } + + public value() + { + if (this.mnum > 0 && this.mden == 0) { + return Number.POSITIVE_INFINITY; + } else if (this.mnum < 0 && this.mden == 0) { + return Number.NEGATIVE_INFINITY; + } else if ((this.mnum == 0) && (this.mden == 0)) { + return Number.NaN; + } else { + return this.mnum / this.mden; + } + } + + public getCommonDivisor(number1 : number, number2 : number) + { + if (number1 == 0 || number2 == 0) { + throw new Error("Parameter cannot be zero!"); + } + let temp : number = 0; + if (number1 < number2) { + temp = number1; + number1 = number2; + number2 = temp; + } + while (number1 % number2 != 0) { + temp = number1 % number2; + number1 = number2; + number2 = temp; + } + return number2; + } + + public getDenominator() + { + return this.mden; + } + + public getNumerator() + { + return this.mnum; + } + + public isFinite() + { + return this.mden != 0; + } + + public isNaN() + { + return this.mnum == 0 && this.mden == 0; + } + + public isZero() + { + return this.mnum == 0 && this.mden != 0; + } + + public toString() + { + let buf : string; + if (this.mnum == 0 && this.mden == 0) { + buf = "NaN"; + } else if (this.mnum > 0 && this.mden == 0) { + buf = "Infinity"; + } else if (this.mnum < 0 && this.mden == 0) { + buf = "-Infinity"; + } else { + buf = String(this.mnum) + '/' + String(this.mden); + } + return buf; + } +} + +interface ScopeComparable { + compareTo(other: ScopeComparable): boolean; +} + +type ScopeType = ScopeComparable; +class Scope { + + private readonly _lowerLimit: ScopeType; + private readonly _upperLimit: ScopeType; + + public constructor(readonly lowerObj: ScopeType, readonly upperObj: ScopeType) { + 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; + } + + public getLower(): ScopeType { + return this._lowerLimit; + } + + public getUpper(): ScopeType { + return this._upperLimit; + } + + public contains(value: ScopeType): boolean; + public contains(scope: Scope): boolean; + public contains(x: any): boolean { + let resLower: boolean; + let resUpper: boolean; + 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; + } + + public clamp(value: ScopeType): ScopeType { + 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; + } + } + + public intersect(scope: Scope): Scope; + public intersect(lowerObj: ScopeType, upperObj: ScopeType): Scope; + public intersect(x: any, y?: any): Scope { + let reLower: boolean; + let reUpper: boolean; + let mLower: ScopeType; + let mUpper: ScopeType; + 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); + } + } + } + + public expand(obj: ScopeType): Scope; + public expand(scope: Scope): Scope; + public expand(lowerObj: ScopeType, upperObj: ScopeType): Scope; + public expand(x: any, y?: any): Scope { + let reLower: boolean; + let reUpper: boolean; + let mLower: ScopeType; + let mUpper: ScopeType; + 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); + } + } + + public toString(): string { + let strLower = this._lowerLimit.toString(); + let strUpper = this._upperLimit.toString(); + return `[${strLower}, ${strUpper}]`; + } + + public checkNull(o: ScopeType, str: string): void { + if(o == null) { + throw new Error(str); + } + } +} + +export default { + printf: printf, + getErrorString: getErrorString, + callbackWrapper: callbackWrapper, + promiseWrapper: promiseWrapper, + TextEncoder: TextEncoder, + TextDecoder: TextDecoder, + Base64: Base64, + LruBuffer: LruBuffer, + RationalNumber : RationalNumber, + Scope : Scope, +}; \ No newline at end of file -- Gitee From 24cdc95d5a36d2df655a2def5682c4f62ca9467a Mon Sep 17 00:00:00 2001 From: 15241154745 Date: Mon, 15 Nov 2021 17:16:14 +0800 Subject: [PATCH 5/6] Signed-off-by: 15241154745 Signed-off-by:lifansheng On branch master Your branch is up to date with 'origin/master'. --- util/build_ts_js.py | 48 ++++++++++++++++++++------------------------- 1 file changed, 21 insertions(+), 27 deletions(-) diff --git a/util/build_ts_js.py b/util/build_ts_js.py index cb4d8eb..e976212 100755 --- a/util/build_ts_js.py +++ b/util/build_ts_js.py @@ -17,39 +17,33 @@ import platform import argparse import subprocess -def run_command(in_cmd): - print(" ".join(in_cmd)) - proc = subprocess.Popen(in_cmd, stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - universal_newlines=True, - shell=False) - stdout, stderr = proc.communicate() - if stdout != "": - print(stdout) +def run_command(cmd): + print(" ".join(cmd)) + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, universal_newlines=True) + out, err = proc.communicate() + if out != "": + print(out) exit(1) - if __name__ == '__main__': + + build_path = os.path.abspath(os.path.join(os.getcwd(), "../..")) + os.chdir("%s/base/compileruntime/js_util_module/util" % build_path) - BUILD_PATH = os.path.abspath(os.path.join(os.getcwd(), "../..")) - os.chdir("%s/base/compileruntime/js_util_module/util" % BUILD_PATH) - - PARSER_INST = argparse.ArgumentParser() - PARSER_INST.add_argument('--dst-file', + parser = argparse.ArgumentParser() + parser.add_argument('--dst-file', help='the converted target file') - INPUT_ARGUMENTS = PARSER_INST.parse_args() - + input_arguments = parser.parse_args() - NODE_PATH = '../../../../prebuilts/build-tools/common/nodejs/\ + node = '../../../../prebuilts/build-tools/common/nodejs/\ node-v12.18.4-linux-x64/bin/node' - TSC_PATH = '../../../../ark/ts2abc/ts2panda/node_modules/\ -typescript/bin/tsc' - CMD_INST = [NODE_PATH, TSC_PATH] - run_command(CMD_INST) + tsc = '../../../../ark/ts2abc/ts2panda/node_modules/typescript/bin/tsc' + cmd = [node, tsc] + run_command(cmd) - CMD_INST = ['cp', "-r", './out/util_js.js', INPUT_ARGUMENTS.dst_file] - run_command(CMD_INST) + cmd = ['cp', "-r", './out/util_js.js', input_arguments.dst_file] + run_command(cmd) - CMD_INST = ['rm', "-rf", './out'] - run_command(CMD_INST) - exit(0) + cmd = ['rm', "-rf", './out'] + run_command(cmd) \ No newline at end of file -- Gitee From 59f5994dab16925d31f3e521eb973fd0cc557011 Mon Sep 17 00:00:00 2001 From: 15241154745 Date: Mon, 15 Nov 2021 17:25:42 +0800 Subject: [PATCH 6/6] Signed-off-by: 15241154745 Signed-off-by:lifansheng On branch master Your branch is up to date with 'origin/master'. --- util/build_ts_js.py | 48 +++++++++++++++++++++++++-------------------- 1 file changed, 27 insertions(+), 21 deletions(-) diff --git a/util/build_ts_js.py b/util/build_ts_js.py index e976212..cb4d8eb 100755 --- a/util/build_ts_js.py +++ b/util/build_ts_js.py @@ -17,33 +17,39 @@ import platform import argparse import subprocess -def run_command(cmd): - print(" ".join(cmd)) - proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, - stderr=subprocess.PIPE, universal_newlines=True) - out, err = proc.communicate() - if out != "": - print(out) +def run_command(in_cmd): + print(" ".join(in_cmd)) + proc = subprocess.Popen(in_cmd, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True, + shell=False) + stdout, stderr = proc.communicate() + if stdout != "": + print(stdout) exit(1) + if __name__ == '__main__': - - build_path = os.path.abspath(os.path.join(os.getcwd(), "../..")) - os.chdir("%s/base/compileruntime/js_util_module/util" % build_path) - parser = argparse.ArgumentParser() - parser.add_argument('--dst-file', + BUILD_PATH = os.path.abspath(os.path.join(os.getcwd(), "../..")) + os.chdir("%s/base/compileruntime/js_util_module/util" % BUILD_PATH) + + PARSER_INST = argparse.ArgumentParser() + PARSER_INST.add_argument('--dst-file', help='the converted target file') - input_arguments = parser.parse_args() + INPUT_ARGUMENTS = PARSER_INST.parse_args() + - node = '../../../../prebuilts/build-tools/common/nodejs/\ + NODE_PATH = '../../../../prebuilts/build-tools/common/nodejs/\ node-v12.18.4-linux-x64/bin/node' - tsc = '../../../../ark/ts2abc/ts2panda/node_modules/typescript/bin/tsc' - cmd = [node, tsc] - run_command(cmd) + TSC_PATH = '../../../../ark/ts2abc/ts2panda/node_modules/\ +typescript/bin/tsc' + CMD_INST = [NODE_PATH, TSC_PATH] + run_command(CMD_INST) - cmd = ['cp', "-r", './out/util_js.js', input_arguments.dst_file] - run_command(cmd) + CMD_INST = ['cp', "-r", './out/util_js.js', INPUT_ARGUMENTS.dst_file] + run_command(CMD_INST) - cmd = ['rm', "-rf", './out'] - run_command(cmd) \ No newline at end of file + CMD_INST = ['rm', "-rf", './out'] + run_command(CMD_INST) + exit(0) -- Gitee