UNPKG

kotlin-scope-functions-js

Version:

A JavaScript library implementing Kotlin-like scope functions: let and also

64 lines (58 loc) 1.67 kB
// scope-functions.js // 辅助函数:检查是否是基本类型的包装对象 function isPrimitiveWrapper(value) { return value instanceof String || value instanceof Number || value instanceof Boolean || value instanceof BigInt || value instanceof Symbol; } /** * 类似 Kotlin 的 let 函数 * @param {Function} block - 接收调用对象作为参数的函数 * @returns {*} block 函数的返回值 */ Object.defineProperty(Object.prototype, 'let', { value: function(block) { const self = isPrimitiveWrapper(this) ? this.valueOf() : this; return block(self); }, enumerable: false, writable: true, configurable: true }); /** * 类似 Kotlin 的 also 函数 * @param {Function} block - 接收调用对象作为参数的函数 * @returns {Object} 调用对象本身 */ Object.defineProperty(Object.prototype, 'also', { value: function(block) { const self = isPrimitiveWrapper(this) ? this.valueOf() : this; block(self); return self; }, enumerable: false, writable: true, configurable: true }); // 实现 takeIf 函数 Object.defineProperty(Object.prototype, 'takeIf', { value: function(predicate) { const self = isPrimitiveWrapper(this) ? this.valueOf() : this; return predicate(self) ? self : null; }, enumerable: false, writable: true, configurable: true }); // 实现 takeUnless 函数 Object.defineProperty(Object.prototype, 'takeUnless', { value: function(predicate) { const self = isPrimitiveWrapper(this) ? this.valueOf() : this; return !predicate(self) ? self : null; }, enumerable: false, writable: true, configurable: true });