Extension functions and parameters for JavaScript inspired by Kotlin's extensions
npm i extensions.macro --save
Or if using yarn:
yarn add extensions.macro
Then just import
:
import extension from 'extensions.macro'
Note that you need to have
babel
andbabel-plugin-macros
installed
As you might know - providing new properties to JavaScript built-in objects pollutes the global scope and is widely considered unsafe. This macro solves the problem allowing you to use dot notation to access external functions and properties π
import extension from 'extensions.macro'
extension.String.plus = string => plusString => `${string} ${plusString}`
Note that it's initialized with function witch first argumument(
string
) provides an instance it's called on.
Then you can use it like:
'Hello'.plus('Extension!') //Outputs: Hello Extension!
import extension from 'extensions.macro'
extension.any.log = obj => () => {
console.log(obj)
return obj
}
'The cosmos is yours π'.log()
//Logs: The cosmos is yours π
It's the result of calling .constructor.name
on object the extension is dedicated for
;(15).constructor.name //Outputs: Number
You can write any
instead of constructor name to match any type of object
It's the name of the extension you choose
It's the function that takes an object and returns what should extension return
- Declare extension in module scope
- Extensions do not override object properties
- Be aware of recursive extension
//...
import curry from '@ramda/curry'
extension.Function.curry = fun => curry(fun) //β
{
extension.Function.curry = fun => curry(fun) //βThrows: Error
}
//...
extension.any.reduce = obj => reducer => reducer(obj)
'Who let the dogs out!?'.reduce(v => `${v} wow! wow! wow!`)
//Outputs: Who let the dogs out!? wow! wow! wow!
;[1, 2, 3].reduce((total, value) => total + value)
//Outputs: 6
Though you can do it (Since 1.0.0 it's no longer possible β) but it does not very performant and is considered to be blocked in future versions
extension.Number.factorial = num => () => {
if (num === 1 || num === 0) return 1
return num * (num - 1).factorial()
}
//Does not work anymoreβ
Do instead:
const factorial = num => {
if (num === 1 || num === 0) return 1
return num * factorial(num - 1)
}
extension.Number.factorial = num => () => factorial(num)
//Right way β
You can overload any
extension like so:
extension.any.plus = obj => plusObj => obj + plusObj
extension.String.plus = string => plusString => `${string} + ${plusString}`
'π½'.plus('π©') //Outputs π½ + π©
;(5).plus(2) ////Outputs 7
You might overlook that you needn't return function from extension
extension.Array.last = arr => arr[arr.length - 1]
console.log(['π₯', 'π'].last) //Logs: π
- Add
Import
andExport
feature for extension - Add more reliable
Errors
- Add extension setters?