-
-
Save ZilvinasKucinskas/b42a783252279423c12ead14ecc07a20 to your computer and use it in GitHub Desktop.
Quick Ruby implementation of https://www.npmjs.com/package/clsx
This file contains hidden or 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
module Clsx | |
def clsx(*args) | |
process_args = args.map do |arg| | |
if arg.is_a?(Array) | |
clsx(*arg) | |
elsif arg.is_a?(Hash) | |
arg.map do |key, value| | |
key if value | |
end | |
else | |
arg | |
end | |
end | |
process_args | |
.flatten | |
.compact | |
.keep_if { |arg| arg && arg.to_s.strip != "" } | |
.join(" ") | |
end | |
end |
This file contains hidden or 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
require "minitest/autorun" | |
require "./clsx" | |
class TestClsx < Minitest::Test | |
include Clsx | |
def test_a_simple_list | |
assert_equal "foo bar baz", clsx("foo", "bar", "baz") | |
end | |
def test_a_hash_of_items | |
assert_equal "foo baz", clsx("foo" => true, "bar" => false, "baz" => true) | |
assert_equal "foo baz", clsx(foo: true, bar: false, baz: true) | |
end | |
def test_an_array | |
assert_equal "foo bar baz", clsx(["foo", "bar", "baz"]) | |
end | |
def test_an_array_with_falsey_things | |
assert_equal "foo bar baz", clsx(["foo", nil, false, "bar", "", "baz"]) | |
end | |
def test_a_variadic_array_of_trash | |
# The javascript version evaluates 0 as falsey | |
assert_equal "foo bar baz hello there", clsx(["foo"], ["", false, "bar"], [["baz", [["hello"], "there"]]]) | |
end | |
def test_the_kitchen_sync | |
assert_equal "foo bar hello world cya", clsx("foo", [1 && "bar", {baz: false, bat: nil}, ["hello", ["world"]]], "cya") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment