Last active
September 24, 2023 12:24
-
-
Save cowboy/8270edb119c8ca700c3b1093659b3e4c to your computer and use it in GitHub Desktop.
Abstraction.js 2020 Edition (ES6)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Abstraction.js 2020 Edition | |
* | |
* Copyright (c) 2020 "Cowboy" Ben Alman | |
* Licensed under the MIT license. | |
* http://benalman.com/about/license/ | |
*/ | |
let $elseif, $else, $if = state => state ? ( | |
$elseif = () => () => {}, | |
$else = () => {}, | |
f => f() | |
) : ( | |
$elseif = $if, | |
$else = f => f(), | |
() => {} | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Why log now when we can log later? | |
const abstractify = obj => new Proxy(obj, { get: (o, k) => (...args) => () => o[k](...args) }) | |
const $console = abstractify(console) | |
// Valid JavaScript | |
$if (true) ( | |
$console.log("1") | |
) | |
$elseif (true) ( | |
$console.log("shouldn't log a") | |
) | |
$else ( | |
$console.log("shouldn't log b") | |
) | |
$if (false) ( | |
$console.log("shouldn't log c") | |
) | |
$elseif (true) ( | |
$console.log("2") | |
) | |
$elseif (true) ( | |
$console.log("shouldn't log d") | |
) | |
$elseif (false) ( | |
$console.log("shouldn't log e") | |
) | |
$else ( | |
$console.log("shouldn't log f") | |
) | |
$if (false) ( | |
$console.log("shouldn't log g") | |
) | |
$elseif (false) ( | |
$console.log("shouldn't log h") | |
) | |
$else ( | |
$console.log("3") | |
) | |
// Logs: | |
// 1 | |
// 2 | |
// 3 |
Caveat being you can't nest your conditionals.
Caveat being you can't nest your conditionals.
I suppose you could with something like this, but IMO nesting conditionals makes coding too easy
let $elseif, $else, $if = ($ => state => state ? (
$elseif = () => () => {},
$else = () => {},
$
) : (
$elseif = $if,
$else = $,
() => {}
))(($, _ = [$if, $else, $elseif]) => (
$(), [$if, $else, $elseif] = _
))
$if (true) (()=>{
$if (false) (
$console.log("shouldn't log a")
)
$elseif (false) (
$console.log("shouldn't log b")
)
$else (
$console.log("1")
)
})
$elseif (true) (
$console.log("shouldn't log c")
)
$else (
$console.log("shouldn't log d")
)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Prior art: