imj
Not fastest but powerful immutable helper
Simple update
import imj from "imj";
const Increase = imj({
count: ({ value }) => value + 1
});
const Decrease = imj({
count: ({ value }) => value - 1
});
Increase({ count: 1 });
Decrease({ count: 1 });
Retrieve argument values
import imj from "imj";
const Increase = imj({
count: ({ value, $1 = 1 }) => value + $1
});
Increase({ count: 1 });
Increase({ count: 1 }, 2);
Update array
import imj from "imj";
const AddTodo = imj({
$args: "$text $done",
todos: ({ $text, $done, push }) =>
push({ text: $text, done: $done })
});
AddTodo({ todos: [{ text: "first", done: false }] }, "second", true);
Update specified items in array
import imj from "imj";
const ToggleDoneSpecs = { done: ({ toggle }) => toggle() };
const ToggleTodoByIndex = imj({
$args: "$index",
$extend: ({ $index }) => ({
todos: {
[$index]: ToggleDoneSpecs
}
})
});
const ToggleOneTodoByText = imj({
$args: "$text",
todos: {
$one: ({ value, $text }) =>
value.text === $text
?
ToggleDoneSpecs
:
null
}
});
const ToggleAllTodoByText = imj({
$args: "$text",
todos: {
$many: ({ value, $text }) =>
value.text === $text
?
ToggleDoneSpecs
:
null
}
});
const ToggleAll = imj({
todos: {
$many: ToggleDoneSpecs
}
});
Simple redux reducer
import imj from "imj";
const IncreaseAction = 1;
const DecreaseAction = 2;
const reducer = imj({
$when: [
"$1.type",
{
[IncreaseAction]: {
count: ({ value, $1: { payload = 1 } }) => value + payload
},
[DecreaseAction]: {
count: ({ value, $1: { payload = 1 } }) => value - payload
}
}
]
});
reducer({ count: 1 }, { type: IncreaseAction });
reducer({ count: 1 }, { type: IncreaseAction, payload: 2 });
reducer({ count: 1 }, { type: DecreaseAction });
reducer({ count: 1 }, { type: DecreaseAction, payload: 2 });
Other implementation
import imj from "imj";
const IncreaseAction = 1;
const DecreaseAction = 2;
const reducer = imj({
$when_increase: [
"$1.type",
IncreaseAction,
{
count: ({ value, $1: { payload = 1 } }) => value + payload
}
],
$when_decrease: [
"$1.type",
DecreaseAction,
{
count: ({ value, $1: { payload = 1 } }) => value - payload
}
]
});