Bear Utilities
A library containing an assortment of features that facilitate and enhance the JavaScript language.
Type-Checking
Bear Utilities adds runtime type-checking in a clean and composable way.
const sum = (a, b) => typeMatch(a, Number) + typeMatch(b, Number);
console.log(sum(1, 2));
console.log(sum("1", 2));
Types can be as simple or as complex as the user needs them to be.
const createStringKeyMap = arr => {
typeMatch(arr, [Tuple(String, Any)]);
return new Map(arr);
};
console.log(createStringKeyMap([
["First", 1],
["Second", 2]
]));
console.log(createStringKeyMap([
["First", 2],
[2, 2],
]));
Conveniences
Bear Utilities offers many convenient features to help write simpler code.
These include Array.random(), Array.sum(), and String.replaceAt().
Functions that modify builtin prototypes can often cause issues between libraries, so to prevent this, it is required to run allowModification() before any of those functions are added.
allowModification(Array);
const arr1 = [1, 2, 3];
console.log(arr1.random());
console.log(arr1.sum());
console.log(arr1.average());
Function Modification
Some functions useful for adding properties to other functions are included, such as nonVariadic and memoize.
const sum = nonVariadic((a, b) => typeMatch(a, Number) + typeMatch(b, Number));
console.log(sum(20, 40));
console.log(sum(20, 40, 50));
Data Types
Bear Utilities offers new data types, such as Tag, Enum, Union, and Entity.
These choices allow programmers to represent data in a manner more suited to any particular scenario.
For example, Entities allow users to implement features in a more composable manner than the standard oop style, while still maintaining the ability to use features such as class-inheritance like normal. Users of FP languages will recognize them as very similar to typeclasses.
class Animal extends Entity {
constructor(name, age) {
super();
this.name = typeMatch(name, String);
this.age = typeMatch(age, Natural);
}
}
const Woofs = new Category("Woofs", [
function woof() {
console.log("Woof!");
}
]);
Animal.impl(Woofs);
const spot = new Animal("Spot", 14);
console.log(spot.name);
spot.woof();
Maybe is a built-in Union useful for handling the null case.
const value1 = Just(20);
typeMatch(value1, Maybe(Natural));
console.log(value1.toString());