diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6313b56 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2b316d3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,176 @@ + +# Created by https://www.gitignore.io/api/node,macos,windows,visualstudiocode +# Edit at https://www.gitignore.io/?templates=node,macos,windows,visualstudiocode + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### Node ### +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage +*.lcov + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# TypeScript v1 declaration files +typings/ + +# TypeScript cache +*.tsbuildinfo + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env +.env.test + +# parcel-bundler cache (https://parceljs.org/) +.cache + +# next.js build output +.next + +# nuxt.js build output +.nuxt + +# rollup.js default build output +dist/ + +# Uncomment the public line if your project uses Gatsby +# https://nextjs.org/blog/next-9-1#public-directory-support +# https://create-react-app.dev/docs/using-the-public-folder/#docsNav +# public + +# Storybook build outputs +.out +.storybook-out + +# vuepress build output +.vuepress/dist + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# Temporary folders +tmp/ +temp/ + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# End of https://www.gitignore.io/api/node,macos,windows,visualstudiocode diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..43c97e7 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +package-lock=false diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..89b57e4 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,11 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "type": "node", + "request": "launch", + "name": "Launch Program", + "program": "${workspaceRoot}\\index.js" + } + ] +} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..315e8b3 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,19 @@ +{ + // See https://go.microsoft.com/fwlink/?LinkId=733558 + // for the documentation about the tasks.json format + "version": "2.0.0", + "tasks": [ + { + "label": "install", + "type": "shell", + "command": "yarn", + "group": "none" + }, + { + "label": "autoclean", + "type": "shell", + "command": "yarn autoclean --force", + "group": "none" + } + ] +} \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..409519c --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Roderick Qiu (https://r-q.name) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..73e22d1 --- /dev/null +++ b/README.md @@ -0,0 +1,22 @@ +# node-shi + +It's a lib which let you to transfer human time to computer-readable time and also to transfer computer-generated time to human time, available for English and Chinese. + +## Features + +### Human time -> time in Arabic number + +- Chinese number + Chinese unix -> time in Arabic number as seconds +- Chinese number + English unix -> time in Arabic number as seconds +- Arabic number + Chinese unix -> time in Arabic number as seconds +- Arabic number + English unix -> time in Arabic number as seconds +- English number + Chinese unix -> time in Arabic number as seconds +- English number + English unix -> time in Arabic number as seconds +- Arabic number in different unixs *(h/min/s/ms)* -> time in Arabic number as seconds + +## Packages Using + +- js-pinyin, waterchestnet, MIT License. +- timestring, mike182uk, MIT License. +- chinese-numbers-converter, anton-bot, MIT License. +- english2number, TSavo, MIT License. diff --git a/index.js b/index.js new file mode 100644 index 0000000..5f76a28 --- /dev/null +++ b/index.js @@ -0,0 +1,8 @@ +/**** + * @module node-shi + * @copyright Roderick Qiu + */ + +'use strict'; + +module.exports = require("./src/shi") diff --git a/package.json b/package.json new file mode 100644 index 0000000..c1fffbe --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "node-shi", + "version": "0.2.0", + "description": "It's a lib which let you to transfer human time to computer-readable time and also to transfer computer-generated time to human time, available for English and Chinese.", + "main": "index.js", + "author": { + "name": "Roderick Qiu", + "url": "http://github.com/RoderickQiu" + }, + "license": "MIT", + "scripts": { + "test": "node test.js" + }, + "dependencies": { + "chinese-numbers-converter": "^2.3.1", + "english2number": "^1.0.8", + "js-pinyin": "^0.1.9" + } +} \ No newline at end of file diff --git a/src/shi.js b/src/shi.js new file mode 100644 index 0000000..5b6d7b2 --- /dev/null +++ b/src/shi.js @@ -0,0 +1,86 @@ +/*** + * Global + */ + +'use strict'; + +const timestring = require('./timestring/index') +const ChineseNumber = require('chinese-numbers-converter'); +let toNumber = require("english2number"); +let pinyin = require('js-pinyin'); +pinyin.setOptions({ checkPolyphone: false, charCase: 0 }); + +const ENGLISH_NUMBER_REGEX = /(((?<=\s|^)(zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand|million|billion|trillion|quadrillion|quintillion|sextillion|septillion|octillion|onillion|decillion)|(?<=zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand|million|billion|trillion|quadrillion|quintillion|sextillion|septillion|octillion|onillion|decillion)(\s|-))+)/gi; +const POSITIVE_ARABIC_NUMBER_REGEX = /^\d+(\.\d+)?$/; //non-negative floats & integers +const NEGATIVE_ARABIC_NUMBER_REGEX = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //negative floats + +function isNumber(val) { + if (POSITIVE_ARABIC_NUMBER_REGEX.test(val) || NEGATIVE_ARABIC_NUMBER_REGEX.test(val)) { + return true; + } else { + return false; + } +} + +/*** + * Func 1: Human time -> time in Arabic number + */ + +function englishConverter(str) { + if (isNumber(str)) { + return str; + } else { + try { + str = str.replace(/-/gi, ' ').replace(/and/gi, '');//delete '-' and unnecessary 'and's + return str.replace( + ENGLISH_NUMBER_REGEX, + match => { + return toNumber(match.replace(/[,\s|s](?=$)/i, ''));//delete blanks and unnecessary 's's in the end + } + );//find and replace and the english numbers + } + catch (e) { + console.log(e); + return str; + } + } +} + +function unitConverter(str, treatNumberAs) { + switch (treatNumberAs) { + case "h": + return str * 3600; + case "min": + return str * 60; + case "s": + return str; + case "ms": + return str / 1000; + default: + return str; + } +} + +/** + * human time parsed to Arabic number in seconds. + * @param {*} str The string or the time in different unixes. + * @param {String} treatNumberAs (optional) h, min, s, ms + * @returns {Number} The converted number + */ +function humanTimeParser(str, treatNumberAs) { + if (isNumber(str)) {//number only + if (treatNumberAs) return unitConverter(str, treatNumberAs); + else return str; + } else { + try { + str = pinyin.getFullChars(new ChineseNumber(englishConverter(str)).toArabicString());// to make it available for cn/en time + return timestring(str); + } + catch (e) { + console.log(e); + return; + } + } +} + +exports.humanTimeParser = humanTimeParser; diff --git a/src/timestring/index.js b/src/timestring/index.js new file mode 100644 index 0000000..931452b --- /dev/null +++ b/src/timestring/index.js @@ -0,0 +1,145 @@ +/*** + * By: Michael Barrett + * Package: timestring + * Edited by: Roderick Qiu + */ + +/** + * Exports + */ + +module.exports = parseTimestring + +/** + * Default options to use when parsing a timestring + * + * @type {Object} + */ + +const DEFAULT_OPTS = { + hoursPerDay: 24, + daysPerWeek: 7, + weeksPerMonth: 4, + monthsPerYear: 12, + daysPerYear: 365.25 +} + +/** + * Map of accepted strings to unit + * + * @type {Object} + */ + +const UNIT_MAP = { + ms: ['ms', 'milli', 'millisecond', 'milliseconds', 'haomiao', 'hm', 'hao'], + s: ['s', 'sec', 'secs', 'second', 'seconds', 'miao', 'miaozhong', 'mz'], + m: ['m', 'min', 'mins', 'minute', 'minutes', 'fen', 'fenzhong', 'fz'], + h: ['h', 'hr', 'hrs', 'hour', 'hours', 'xiaoshi', 'xs', 'shi', 'dianzhong'], + d: ['d', 'day', 'days', 'ri', 'tian'], + w: ['w', 'week', 'weeks', 'zhou', 'libai', 'xingqi'], + mth: ['mon', 'mth', 'mths', 'month', 'months', 'yue', 'yuefen', 'yf'], + y: ['y', 'yr', 'yrs', 'year', 'years', 'nian', 'nianfen', 'nf'] +} + +/** + * Parse a timestring + * + * @param {String} string + * @param {String} returnUnit + * @param {Object} opts + * @return {Number} + */ + +function parseTimestring(string, returnUnit, opts) { + opts = Object.assign({}, DEFAULT_OPTS, opts || {}) + + let totalSeconds = 0 + let unitValues = getUnitValues(opts) + let groups = string + .toLowerCase() + .replace(/[^.\w+-]+/g, '') + .match(/[-+]?[0-9.]+[a-z]+/g) + + if (groups === null) { + throw new Error(`The string [${string}] could not be parsed`) + } + + groups.forEach(group => { + let value = group.match(/[0-9.]+/g)[0] + let unit = group.match(/[a-z]+/g)[0] + + totalSeconds += getSeconds(value, unit, unitValues) + }) + + if (returnUnit) { + return convert(totalSeconds, returnUnit, unitValues) + } + + return totalSeconds +} + +/** + * Get unit values based on the passed options + * + * @param {Object} opts + * @returns {Object} + */ + +function getUnitValues(opts) { + let unitValues = { + ms: 0.001, + s: 1, + m: 60, + h: 3600 + } + + unitValues.d = opts.hoursPerDay * unitValues.h + unitValues.w = opts.daysPerWeek * unitValues.d + unitValues.mth = (opts.daysPerYear / opts.monthsPerYear) * unitValues.d + unitValues.y = opts.daysPerYear * unitValues.d + + return unitValues +} + +/** + * Get the key for a unit + * + * @param {String} unit + * @returns {String} + */ + +function getUnitKey(unit) { + for (let key of Object.keys(UNIT_MAP)) { + if (UNIT_MAP[key].indexOf(unit) > -1) { + return key + } + } + + throw new Error(`The unit [${unit}] is not supported`) +} + +/** + * Get the number of seconds for a value, based on the unit + * + * @param {Number} value + * @param {String} unit + * @param {Object} unitValues + * @returns {Number} + */ + +function getSeconds(value, unit, unitValues) { + return value * unitValues[getUnitKey(unit)] +} + +/** + * Convert a value from its existing unit to a new unit + * + * @param {Number} value + * @param {String} unit + * @param {Object} unitValues + * @returns {Number} + */ + +function convert(value, unit, unitValues) { + return value / unitValues[getUnitKey(unit)] +} diff --git a/test.js b/test.js new file mode 100644 index 0000000..04c6438 --- /dev/null +++ b/test.js @@ -0,0 +1,7 @@ +var shi = require('./index.js'); + +// human time -> time in Arabic number +console.log(shi.humanTimeParser("five hundreds and twenty one seconds")); +console.log(shi.humanTimeParser("1 day 52 min 16sec")); +console.log(shi.humanTimeParser("三十三分钟")); +console.log(shi.humanTimeParser("50", 'min')) \ No newline at end of file diff --git a/yarn.lock b/yarn.lock new file mode 100644 index 0000000..0beff44 --- /dev/null +++ b/yarn.lock @@ -0,0 +1,64 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +chinese-numbers-converter@^2.3.1: + version "2.3.1" + resolved "https://registry.npm.taobao.org/chinese-numbers-converter/download/chinese-numbers-converter-2.3.1.tgz#b22f578ffce42dc817ab0826508093e7c62a7bcb" + integrity sha1-si9Xj/zkLcgXqwgmUICT58Yqe8s= + dependencies: + should "^13.2.3" + +english2number@^1.0.8: + version "1.0.8" + resolved "https://registry.npm.taobao.org/english2number/download/english2number-1.0.8.tgz#7b83974bea539746b39ca831137c9feaf595c488" + integrity sha1-e4OXS+pTl0aznKgxE3yf6vWVxIg= + +js-pinyin@^0.1.9: + version "0.1.9" + resolved "https://registry.npm.taobao.org/js-pinyin/download/js-pinyin-0.1.9.tgz#cdf19335645ddb20d4630df1058aac25d256adfd" + integrity sha1-zfGTNWRd2yDUYw3xBYqsJdJWrf0= + +should-equal@^2.0.0: + version "2.0.0" + resolved "https://registry.npm.taobao.org/should-equal/download/should-equal-2.0.0.tgz#6072cf83047360867e68e98b09d71143d04ee0c3" + integrity sha1-YHLPgwRzYIZ+aOmLCdcRQ9BO4MM= + dependencies: + should-type "^1.4.0" + +should-format@^3.0.3: + version "3.0.3" + resolved "https://registry.npm.taobao.org/should-format/download/should-format-3.0.3.tgz#9bfc8f74fa39205c53d38c34d717303e277124f1" + integrity sha1-m/yPdPo5IFxT04w01xcwPidxJPE= + dependencies: + should-type "^1.3.0" + should-type-adaptors "^1.0.1" + +should-type-adaptors@^1.0.1: + version "1.1.0" + resolved "https://registry.npm.taobao.org/should-type-adaptors/download/should-type-adaptors-1.1.0.tgz#401e7f33b5533033944d5cd8bf2b65027792e27a" + integrity sha1-QB5/M7VTMDOUTVzYvytlAneS4no= + dependencies: + should-type "^1.3.0" + should-util "^1.0.0" + +should-type@^1.3.0, should-type@^1.4.0: + version "1.4.0" + resolved "https://registry.npm.taobao.org/should-type/download/should-type-1.4.0.tgz#0756d8ce846dfd09843a6947719dfa0d4cff5cf3" + integrity sha1-B1bYzoRt/QmEOmlHcZ36DUz/XPM= + +should-util@^1.0.0: + version "1.0.1" + resolved "https://registry.npm.taobao.org/should-util/download/should-util-1.0.1.tgz#fb0d71338f532a3a149213639e2d32cbea8bcb28" + integrity sha1-+w1xM49TKjoUkhNjni0yy+qLyyg= + +should@^13.2.3: + version "13.2.3" + resolved "https://registry.npm.taobao.org/should/download/should-13.2.3.tgz#96d8e5acf3e97b49d89b51feaa5ae8d07ef58f10" + integrity sha1-ltjlrPPpe0nYm1H+qlro0H71jxA= + dependencies: + should-equal "^2.0.0" + should-format "^3.0.3" + should-type "^1.4.0" + should-type-adaptors "^1.0.1" + should-util "^1.0.0"