Compare commits

..

9 Commits

Author SHA1 Message Date
yutent 22bb09a407 2.4.3:更新文档 2024-09-29 15:08:45 +08:00
yutent e91ce6387a fixed define 2024-09-29 15:05:05 +08:00
yutent 4e459de01c fixed 2024-09-12 10:56:54 +08:00
yutent e5d7304f66 2.4.1 equal -> equals 2024-08-22 18:26:06 +08:00
yutent dab02dbb64 2.4.0 2024-08-22 18:03:35 +08:00
yutent 2a598b2c23 fixed package.json 2024-08-07 11:46:42 +08:00
yutent 61caab972e 2.3.0 2024-08-07 11:45:27 +08:00
yutent be25f2dd4b 增加Obejct.groupBy和Map.groupBy 2024-03-28 18:50:40 +08:00
yutent 0afc54671b fixed 2023-11-06 14:05:13 +08:00
13 changed files with 276 additions and 61 deletions

View File

@ -1,3 +1,41 @@
2.4.3 / 2024-09-29
==================
* 修复`Object.defineProperty`定义声明
* 增加`Promise.withResolvers`
2.4.2 / 2024-09-12
==================
* 优化字符串转义
2.4.0 / 2024-08-22
==================
* 增加Set的一系列原型方法`union、equal、difference、symmetricDifference、intersection、isSubsetOf、isSupersetOf、isDisjointFrom`
2.3.0 / 2024-08-07
==================
* 增加修复版toFixed
2.2.2 / 2024-03-28
==================
* 增加Obejct.groupBy和Map.groupBy
2.2.1 / 2023-11-06
==================
* 一些小修复
2.2.0 / 2023-07-20
==================
* 数组增加一组原型方法
* 字符串增加版本号大小比较的原型方法
2.1.1 / 2023-02-27
==================
* 修复 Object.prototype.toParams()原型方法
2.1.0 / 2022-01-27 2.1.0 / 2022-01-27
================== ==================
* Array.prototype.item 更名为 Array.prototype.at * Array.prototype.item 更名为 Array.prototype.at

View File

@ -7,10 +7,15 @@
```js ```js
├── Obejct ├── Obejct
│ └── .empty(any) // 判断对象是否为空对象 │ ├── .empty(any) // 判断对象是否为空对象
│ ├── .groupBy(arr, fn) // 数组分组, 返回分组后的对象
│ └── .hasOwn(any, key) // 安全版的 Object.prototype.hasOwnProperty()
├── Obejct.prototype ├── Obejct.prototype
│ └── .toParams() // 把对象转为 key1=value1&key2=value2 格式 │ └── .toParams() // 把对象转为 key1=value1&key2=value2 格式
├── Map
│ └── .groupBy(any) // 数组分组, 返回分组后的对象
├── Array.prototype ├── Array.prototype
│ ├── .flat(depth) // 数组降维 │ ├── .flat(depth) // 数组降维
│ ├── .flatMap(fn) // 等价于 map(fn) -> flat(1) │ ├── .flatMap(fn) // 等价于 map(fn) -> flat(1)
@ -24,6 +29,16 @@
│ ├── .group(fn) // 数组分组 │ ├── .group(fn) // 数组分组
│ └── .groupToMap(fn) // 数组分组, 返回Map对象 │ └── .groupToMap(fn) // 数组分组, 返回Map对象
├── Set.prototype
│ ├── .union(other) // 合并2个集合
│ ├── .equals(other) // 判断2个集合是否一致(仅元素相同, 无关顺序)
│ ├── .difference(fn) // 返回不存在于另一个集合的所有元素集合
│ ├── .symmetricDifference(fn) // 返回当前集合与给定集合中, 不同时存在的所有元素集合
│ ├── .intersection(fn) // 返回共有的元素集合
│ ├── .isSubsetOf(fn) // 判断当前集合是否为给定集合的子集
│ ├── .isSupersetOf(fn) // 判断当前集合是否为给定集合的子超集
│ ├── .isDisjointFrom(fn) // 判断当前集合,是否与给定集合完全不重合
├── Date ├── Date
│ └── .isDate(any) // 判断对象是否为 日期对象 │ └── .isDate(any) // 判断对象是否为 日期对象
├── Date.prototype ├── Date.prototype
@ -48,9 +63,12 @@
├── Number ├── Number
│ ├── .parse(str) // 将安全范围内的数字字符串转为数字类型 │ ├── .parse(str) // 将安全范围内的数字字符串转为数字类型
│ └── .fromString(str) // 将字符串转为数字类型 │ └── .fromString(str) // 将字符串转为数字类型
├── Number.prototype
│ └── .toFixed(digits) // 修正版的toFixed
└── Promise └── Promise
└── .defer() // 创建一个延迟的Promise对象 ├── .defer() // 创建一个延迟的Promise对象
└── .withResolvers() // 创建一个延迟的Promise对象, 同defer
``` ```

View File

@ -1,6 +1,6 @@
{ {
"name": "es.shim", "name": "es.shim",
"version": "2.2.0", "version": "2.4.3",
"description": "实现部分新API, 以及一些常用的扩展方法", "description": "实现部分新API, 以及一些常用的扩展方法",
"keyworks": [ "keyworks": [
"es5", "es5",
@ -19,7 +19,10 @@
"scripts": { "scripts": {
"start": "node ./build.js" "start": "node ./build.js"
}, },
"repository": "https://github.com/bytedo/es.shim.git", "repository": {
"type": "git",
"url": "git+https://git.wkit.fun/bytedo/es.shim.git"
},
"author": "yutent", "author": "yutent",
"license": "MIT" "license": "MIT"
} }

View File

@ -4,8 +4,10 @@
* @date 2022/01/27 15:33:09 * @date 2022/01/27 15:33:09
*/ */
import './lib/object.js' import './lib/set.js'
import './lib/array.js' import './lib/array.js'
import './lib/object.js'
import './lib/map.js'
import './lib/string.js' import './lib/string.js'
import './lib/number.js' import './lib/number.js'
import './lib/date.js' import './lib/date.js'

View File

@ -7,7 +7,7 @@
* 重写原生的flat方法, 性能提升5~10(看数组的结构) * 重写原生的flat方法, 性能提升5~10(看数组的结构)
*/ */
Object.defineProperty(Array.prototype, 'flat', { Object.defineProperty(Array.prototype, 'flat', {
value: function (deep = 1, arr = []) { value(deep = 1, arr = []) {
for (let it of this) { for (let it of this) {
if (Array.isArray(it) && deep > 0) { if (Array.isArray(it) && deep > 0) {
it.flat(deep - 1, arr) it.flat(deep - 1, arr)
@ -22,7 +22,7 @@ Object.defineProperty(Array.prototype, 'flat', {
}) })
Object.defineProperty(Array.prototype, 'flatMap', { Object.defineProperty(Array.prototype, 'flatMap', {
value: function (fn) { value(fn) {
return this.map(fn).flat() return this.map(fn).flat()
}, },
writable: true writable: true
@ -30,20 +30,19 @@ Object.defineProperty(Array.prototype, 'flatMap', {
if (!Array.prototype.at) { if (!Array.prototype.at) {
Object.defineProperty(Array.prototype, 'at', { Object.defineProperty(Array.prototype, 'at', {
value: function (num) { value(num) {
let n = +num let n = +num
if (n < 0) { if (n < 0) {
n += this.length n += this.length
} }
return this[n] return this[n]
}, }
writable: true
}) })
} }
if (!Array.prototype.findLast) { if (!Array.prototype.findLast) {
Object.defineProperty(Array.prototype, 'findLast', { Object.defineProperty(Array.prototype, 'findLast', {
value: function (fn) { value(fn) {
let num = this.length let num = this.length
while (num > 0) { while (num > 0) {
let item = this[--num] let item = this[--num]
@ -51,13 +50,12 @@ if (!Array.prototype.findLast) {
return item return item
} }
} }
}, }
writable: true
}) })
// 没有findLast也不会有findLastIndex // 没有findLast也不会有findLastIndex
Object.defineProperty(Array.prototype, 'findLastIndex', { Object.defineProperty(Array.prototype, 'findLastIndex', {
value: function (fn) { value(fn) {
let num = this.length let num = this.length
while (num > 0) { while (num > 0) {
let item = this[--num] let item = this[--num]
@ -66,36 +64,32 @@ if (!Array.prototype.findLast) {
} }
} }
return -1 return -1
}, }
writable: true
}) })
} }
// 最新增加的几种方法 // 最新增加的几种方法
if (!Array.prototype.toSorted) { if (!Array.prototype.toSorted) {
Object.defineProperty(Array.prototype, 'toSorted', { Object.defineProperty(Array.prototype, 'toSorted', {
value: function (fn) { value(fn) {
return [...this].sort(fn) return [...this].sort(fn)
}, }
writable: true
}) })
Object.defineProperty(Array.prototype, 'toReversed', { Object.defineProperty(Array.prototype, 'toReversed', {
value: function () { value() {
return [...this].reverse() return [...this].reverse()
}, }
writable: true
}) })
Object.defineProperty(Array.prototype, 'toSpliced', { Object.defineProperty(Array.prototype, 'toSpliced', {
value: function (...args) { value(...args) {
return [...this].splice(...args) return [...this].splice(...args)
}, }
writable: true
}) })
Object.defineProperty(Array.prototype, 'with', { Object.defineProperty(Array.prototype, 'with', {
value: function (num, val) { value(num, val) {
let n = +num let n = +num
let arr = [...this] let arr = [...this]
if (n < 0) { if (n < 0) {
@ -103,15 +97,14 @@ if (!Array.prototype.toSorted) {
} }
arr[n] = val arr[n] = val
return arr return arr
}, }
writable: true
}) })
} }
// 数组分组 // 数组分组
if (!Array.prototype.group) { if (!Array.prototype.group) {
Object.defineProperty(Array.prototype, 'group', { Object.defineProperty(Array.prototype, 'group', {
value: function (fn) { value(fn) {
let output = {} let output = {}
if (typeof fn === 'function') { if (typeof fn === 'function') {
for (let it of this) { for (let it of this) {
@ -126,12 +119,11 @@ if (!Array.prototype.group) {
} else { } else {
throw Error('argument callback must be a function.') throw Error('argument callback must be a function.')
} }
}, }
writable: true
}) })
Object.defineProperty(Array.prototype, 'groupToMap', { Object.defineProperty(Array.prototype, 'groupToMap', {
value: function (fn) { value(fn) {
let output = new Map() let output = new Map()
if (typeof fn === 'function') { if (typeof fn === 'function') {
for (let it of this) { for (let it of this) {
@ -146,7 +138,6 @@ if (!Array.prototype.group) {
} else { } else {
throw Error('argument callback must be a function.') throw Error('argument callback must be a function.')
} }
}, }
writable: true
}) })
} }

View File

@ -6,17 +6,16 @@
//获取当天是本月第几周 //获取当天是本月第几周
if (!Date.isDate) { if (!Date.isDate) {
Object.defineProperty(Date, 'isDate', { Object.defineProperty(Date, 'isDate', {
value: function (obj) { value(obj) {
return obj && typeof obj === 'object' && obj.getTime ? true : false return obj && typeof obj === 'object' && obj.getTime ? true : false
}, }
writable: true
}) })
} }
if (!Date.prototype.getFullWeek) { if (!Date.prototype.getFullWeek) {
//获取当天是本年度第几周 //获取当天是本年度第几周
Object.defineProperty(Date.prototype, 'getFullWeek', { Object.defineProperty(Date.prototype, 'getFullWeek', {
value: function () { value() {
let thisYear = this.getFullYear() let thisYear = this.getFullYear()
let that = new Date(thisYear, 0, 1) let that = new Date(thisYear, 0, 1)
let firstDay = that.getDay() let firstDay = that.getDay()
@ -27,7 +26,7 @@ if (!Date.prototype.getFullWeek) {
//获取当天是本月第几周 //获取当天是本月第几周
Object.defineProperty(Date.prototype, 'getWeek', { Object.defineProperty(Date.prototype, 'getWeek', {
value: function () { value() {
let today = this.getDate() let today = this.getDate()
let thisMonth = this.getMonth() let thisMonth = this.getMonth()
let thisYear = this.getFullYear() let thisYear = this.getFullYear()
@ -40,7 +39,7 @@ if (!Date.prototype.getFullWeek) {
//时间格式化 //时间格式化
if (!Date.prototype.format) { if (!Date.prototype.format) {
Object.defineProperty(Date.prototype, 'format', { Object.defineProperty(Date.prototype, 'format', {
value: function (str) { value(str) {
let dt = { let dt = {
fullyear: this.getFullYear(), fullyear: this.getFullYear(),
year: this.getYear(), year: this.getYear(),
@ -48,7 +47,7 @@ if (!Date.prototype.format) {
week: this.getWeek(), week: this.getWeek(),
month: this.getMonth() + 1, month: this.getMonth() + 1,
date: this.getDate(), date: this.getDate(),
day: this.getDay() + 1, day: this.getDay(),
hours: this.getHours(), hours: this.getHours(),
minutes: this.getMinutes(), minutes: this.getMinutes(),
seconds: this.getSeconds() seconds: this.getSeconds()

13
src/lib/map.js Normal file
View File

@ -0,0 +1,13 @@
/**
* {}
* @author yutent<yutent.io@gmail.com>
* @date 2024/03/28 18:48:08
*/
if (!Map.groupBy) {
Object.defineProperty(Map, 'groupBy', {
value(arr, fn) {
return arr.groupToMap(fn)
}
})
}

View File

@ -3,12 +3,23 @@
* @date 2020/09/16 11:58:40 * @date 2020/09/16 11:58:40
*/ */
// Number.EPSILON
const NATIVE_TO_FIXED = Number.prototype.toFixed
Object.defineProperty(Number.prototype, 'toFixed', {
value(n) {
return NATIVE_TO_FIXED.call(this + Number.EPSILON, n)
},
writable: true
})
// 简单的数字处理 // 简单的数字处理
// 将安全范围内的数字字符串转为数字类型 // 将安全范围内的数字字符串转为数字类型
// 否则转为字符串类型 // 否则转为字符串类型
if (!Number.parse) { if (!Number.parse) {
Object.defineProperty(Number, 'parse', { Object.defineProperty(Number, 'parse', {
value: function(val) { value(val) {
if (typeof val === 'number' || typeof val === 'string') { if (typeof val === 'number' || typeof val === 'string') {
val += '' val += ''
if (val.startsWith('0') && !val.startsWith('0.')) { if (val.startsWith('0') && !val.startsWith('0.')) {
@ -19,7 +30,10 @@ if (!Number.parse) {
} }
} else { } else {
if (isFinite(val)) { if (isFinite(val)) {
if (val >= Number.MIN_SAFE_INTEGER && val <= Number.MAX_SAFE_INTEGER) { if (
val >= Number.MIN_SAFE_INTEGER &&
val <= Number.MAX_SAFE_INTEGER
) {
val = +val val = +val
} }
} }
@ -34,7 +48,7 @@ if (!Number.parse) {
// 将字符串转为数字类型 // 将字符串转为数字类型
if (!Number.fromString) { if (!Number.fromString) {
Object.defineProperty(Number, 'fromString', { Object.defineProperty(Number, 'fromString', {
value: function(val) { value(val) {
return +val || 0 return +val || 0
} }
}) })

View File

@ -10,7 +10,7 @@
*/ */
if (!Object.empty) { if (!Object.empty) {
Object.defineProperty(Object, 'empty', { Object.defineProperty(Object, 'empty', {
value: function (obj) { value(obj) {
try { try {
for (let i in obj) { for (let i in obj) {
return false return false
@ -21,13 +21,32 @@ if (!Object.empty) {
}) })
} }
if (!Object.groupBy) {
Object.defineProperty(Object, 'groupBy', {
value(arr, fn) {
return arr.group(fn)
}
})
}
if (!Object.hasOwn) {
Object.defineProperty(Object, 'hasOwn', {
value(obj, key) {
if (obj === null) {
return false
}
return obj.hasOwnProperty(key)
}
})
}
/** /**
* 将对象转为url参数字符串 * 将对象转为url参数字符串
* 注意: 这里不会处理复杂类型, 直接按toString结果拼接 * 注意: 这里不会处理复杂类型, 直接按toString结果拼接
*/ */
if (!Object.prototype.toParams) { if (!Object.prototype.toParams) {
Object.defineProperty(Object.prototype, 'toParams', { Object.defineProperty(Object.prototype, 'toParams', {
value: function () { value() {
let params = '' let params = ''
for (let k in this) { for (let k in this) {
if (this[k] === void 0) { if (this[k] === void 0) {

View File

@ -4,7 +4,7 @@
*/ */
if (!Promise.defer) { if (!Promise.defer) {
Promise.defer = function() { Promise.defer = function () {
let obj = {} let obj = {}
obj.promise = new Promise((resolve, reject) => { obj.promise = new Promise((resolve, reject) => {
obj.resolve = resolve obj.resolve = resolve
@ -13,3 +13,7 @@ if (!Promise.defer) {
return obj return obj
} }
} }
if (!Promise.withResolvers) {
Promise.withResolvers = Promise.defer
}

110
src/lib/set.js Normal file
View File

@ -0,0 +1,110 @@
/**
* @author yutent<yutent.io@gmail.com>
* @date 2020/09/16 11:54:31
*/
if (!Set.prototype.union) {
// 类似 Array的concat, 合并2个集合, 返回1个新集合, 原集合不发生变化
Object.defineProperty(Set.prototype, 'union', {
value(other) {
let output = new Set([...this])
if (
other.size !== void 0 &&
other.has !== void 0 &&
other.keys !== void 0
) {
for (let it of other.keys()) {
output.add(it)
}
}
return output
}
})
// 同一批 API
// 返回不存在于另一个集合的所有元素集合
Object.defineProperty(Set.prototype, 'difference', {
value(other) {
let output = new Set()
for (let it of this) {
if (!other.has(it)) {
output.add(it)
}
}
return output
}
})
// 返回当前集合与给定集合中, 不同时存在的所有元素集合
Object.defineProperty(Set.prototype, 'symmetricDifference', {
value(other) {
let output = this.difference(other)
for (let it of other) {
if (!this.has(it)) {
output.add(it)
}
}
return output
}
})
// 返回共有的元素集合
Object.defineProperty(Set.prototype, 'intersection', {
value(other) {
let output = new Set()
for (let it of this) {
if (other.has(it)) {
output.add(it)
}
}
return output
}
})
// 判断当前集合是否为给定集合的子集
Object.defineProperty(Set.prototype, 'isSubsetOf', {
value(other) {
for (let it of this) {
if (!other.has(it)) {
return false
}
}
return true
}
})
// 判断当前集合是否为给定集合的子超集
Object.defineProperty(Set.prototype, 'isSupersetOf', {
value(other) {
for (let it of other) {
if (!this.has(it)) {
return false
}
}
return true
}
})
// 判断当前集合,是否与给定集合完全不重合
Object.defineProperty(Set.prototype, 'isDisjointFrom', {
value(other) {
for (let it of this) {
if (other.has(it)) {
return false
}
}
return true
}
})
}
// 判断2个集合是否一致(仅元素相同, 无关顺序)
if (!Set.prototype.equals) {
Object.defineProperty(Set.prototype, 'equals', {
value(other) {
return this.size === other.size && this.isSubsetOf(other)
}
})
}

View File

@ -34,7 +34,7 @@ function compare(v1, v2) {
//类似于Array 的splice方法 //类似于Array 的splice方法
if (!String.prototype.splice) { if (!String.prototype.splice) {
Object.defineProperty(String.prototype, 'splice', { Object.defineProperty(String.prototype, 'splice', {
value: function (start, len, fill) { value(start, len, fill) {
let length = this.length let length = this.length
let argLen = arguments.length let argLen = arguments.length
@ -70,7 +70,7 @@ if (!String.prototype.splice) {
//同php的htmlspecialchars函数 //同php的htmlspecialchars函数
if (!String.prototype.htmlspecialchars) { if (!String.prototype.htmlspecialchars) {
Object.defineProperty(String.prototype, 'htmlspecialchars', { Object.defineProperty(String.prototype, 'htmlspecialchars', {
value: function (sign) { value(sign) {
let str = this.replace(/&(?!\w+;)/g, '&amp;') let str = this.replace(/&(?!\w+;)/g, '&amp;')
.replace(/</g, '&lt;') .replace(/</g, '&lt;')
.replace(/>/g, '&gt;') .replace(/>/g, '&gt;')
@ -89,10 +89,11 @@ if (!String.prototype.htmlspecialchars) {
//htmlspecialchars的还原 //htmlspecialchars的还原
if (!String.prototype.tohtml) { if (!String.prototype.tohtml) {
Object.defineProperty(String.prototype, 'tohtml', { Object.defineProperty(String.prototype, 'tohtml', {
value: function () { value() {
return this.replace(/&lt;/gi, '<') return this.replace(/&lt;/gi, '<')
.replace(/&gt;/gi, '>') .replace(/&gt;/gi, '>')
.replace(/&quot;/gi, '"') .replace(/&quot;/gi, '"')
.replace(/&#34;/g, '"')
.replace(/&#39;/g, "'") .replace(/&#39;/g, "'")
.replace(/&amp;/gi, '&') .replace(/&amp;/gi, '&')
} }
@ -102,7 +103,7 @@ if (!String.prototype.tohtml) {
//简单的过滤xss //简单的过滤xss
if (!String.prototype.xss) { if (!String.prototype.xss) {
Object.defineProperty(String.prototype, 'xss', { Object.defineProperty(String.prototype, 'xss', {
value: function () { value() {
let str = this.htmlspecialchars('ENT_QUOTES') let str = this.htmlspecialchars('ENT_QUOTES')
str = str str = str
.replace( .replace(
@ -118,7 +119,7 @@ if (!String.prototype.xss) {
// js特殊字符的转义 // js特殊字符的转义
if (!String.prototype.escape) { if (!String.prototype.escape) {
Object.defineProperty(String.prototype, 'escape', { Object.defineProperty(String.prototype, 'escape', {
value: function () { value() {
return this.replace(/('|"|&|\\|\}|\{|\(|\)|;|=|\,|&)/g, '\\$1') return this.replace(/('|"|&|\\|\}|\{|\(|\)|;|=|\,|&)/g, '\\$1')
} }
}) })
@ -126,14 +127,13 @@ if (!String.prototype.escape) {
if (!String.prototype.at) { if (!String.prototype.at) {
Object.defineProperty(String.prototype, 'at', { Object.defineProperty(String.prototype, 'at', {
value: function (num) { value(num) {
let n = +num let n = +num
if (n < 0) { if (n < 0) {
n += this.length n += this.length
} }
return this[n] return this[n]
}, }
writable: true
}) })
} }
@ -143,7 +143,7 @@ if (!String.prototype.at) {
*/ */
if (!String.prototype.toJson) { if (!String.prototype.toJson) {
Object.defineProperty(String.prototype, 'toJson', { Object.defineProperty(String.prototype, 'toJson', {
value: function () { value() {
let str = this.replace(/^\?/, '') let str = this.replace(/^\?/, '')
let params = decodeURIComponent(str) let params = decodeURIComponent(str)
.split('&') .split('&')
@ -161,31 +161,31 @@ if (!String.prototype.toJson) {
// 用于版本号的比较 // 用于版本号的比较
if (!String.prototype.lt) { if (!String.prototype.lt) {
Object.defineProperty(String.prototype, 'lt', { Object.defineProperty(String.prototype, 'lt', {
value: function (v) { value(v) {
return compare(this, v) === -1 return compare(this, v) === -1
} }
}) })
Object.defineProperty(String.prototype, 'lte', { Object.defineProperty(String.prototype, 'lte', {
value: function (v) { value(v) {
return compare(this, v) < 1 return compare(this, v) < 1
} }
}) })
Object.defineProperty(String.prototype, 'gt', { Object.defineProperty(String.prototype, 'gt', {
value: function (v) { value(v) {
return compare(this, v) === 1 return compare(this, v) === 1
} }
}) })
Object.defineProperty(String.prototype, 'gte', { Object.defineProperty(String.prototype, 'gte', {
value: function (v) { value(v) {
return compare(this, v) > -1 return compare(this, v) > -1
} }
}) })
Object.defineProperty(String.prototype, 'eq', { Object.defineProperty(String.prototype, 'eq', {
value: function (v) { value(v) {
return compare(this, v) === 0 return compare(this, v) === 0
} }
}) })

4
test/index.js Normal file
View File

@ -0,0 +1,4 @@
require('../dist/index.js')
console.log((1.345).toFixed())
console.log((1.345).toFixed(2))