turbo-natives
v0.2.0
Published
Native extensions and polyfills for JavaScript/TypeScript that enhance built-in prototypes with powerful utility methods
Maintainers
Readme
turbo-natives
Native extensions and polyfills for JavaScript/TypeScript that enhance built-in prototypes with powerful utility methods.
Installation
npm install turbo-nativesUsage
Simply import at the top of your main TypeScript file:
import 'turbo-natives';This will automatically initialize all polyfills and native extensions.
Available Extensions
isOneOf()
Checks if the value equals any of the provided arguments. Works with any type (numbers, strings, booleans, objects, etc.).
turbo-natives
Comprehensive collection of small, well-tested polyfills and prototype helpers for JavaScript and TypeScript. Import once to register all helpers as non-enumerable properties on built-in prototypes.
Installation
npm install turbo-nativesUsage
Import at your application's entry point to initialize all helpers:
import 'turbo-natives';Reference & Examples
This project provides many small helpers. Examples below assume you've imported the package as shown above.
Array helpers
isOneOf(...values)— returnstrueif the value strictly equals any of the provided values.
const status = 200;
status.isOneOf(200, 201); // truechunk(size)— split array into chunks.
[1,2,3,4,5].chunk(2); // [[1,2],[3,4],[5]]shuffle()— returns a new array with randomized order.
[1,2,3].shuffle(); // e.g. [2,1,3]asyncForEach(callback)— runs async callbacks sequentially.
await [1,2,3].asyncForEach(async (n) => await fetch(`/api/${n}`));sum(selector?)— sums numbers or uses selector to extract numbers from objects.
[1,2,3].sum(); // 6
users.sum(u => u.salary);average(selector?)— arithmetic mean (0 for empty arrays).
[1,2,3].average(); // 2groupBy(fn)— groups items by returned key.
[{type:'Dog'},{type:'Cat'},{type:'Dog'}].groupBy(x => x.type);remove(item)— removes first matching item (mutates array), returnstruewhen removed.
const arr = ['a','b','c']; arr.remove('b'); // true, arr becomes ['a','c']intersect(other)— returns items present in both arrays (intersection).
[1,2,3].intersect([2,3,4]); // [2,3]diff(other)— returns items in this array but not in the other (difference).
[1,2,3].diff([2,3,4]); // [1]first()/last()/random()— array accessors: first element, last element, and a random element (may beundefined).
[1,2,3].first(); // 1
[1,2,3].last(); // 3
[1,2,3].random(); // e.g. 2Number helpers
isBetween(a,b,inclusive = true)— range check (parameters auto-sorted).
(50).isBetween(0,100); // trueclamp(min,max)— clamp value to range.
(150).clamp(0,100); // 100toMoney(currency = 'USD', locale = 'en-US')— format number as currency.
(1234.5).toMoney(); // "$1,234.50"fileSize(decimals = 2)— format a byte count into a human-readable string (KB, MB, ...).
(1024).fileSize(); // "1 KB"
(1234567).fileSize(1); // "1.2 MB"Promise helpers
Promise.retry(fn, attempts = 3, delayMs = 0)— retry an async operation.
await Promise.retry(() => fetch('/api').then(r => r.json()), 3, 1000);Promise.wait(ms)— delay helper.
await Promise.wait(500);Function helpers
Function.prototype.debounce(waitMs)— returns debounced function.
const save = (() => api.save()).debounce(500);Object helpers
pick(...keys)— returns new object with selected keys.
{id:1,name:'A',pwd:'x'}.pick('id','name');isEmpty()— returnstruewhen the value is empty. Supports strings, arrays, plain objects,Map/Set,nullandundefined.
''.isEmpty(); // true
[1,2].isEmpty(); // false
({}).isEmpty(); // true
new Map().isEmpty(); // trueConsole helpers
console.json(obj)— pretty-print an object as JSON (two-space indent).
console.json({ a: 1, b: [1,2,3] });console.divider(char?, colorHex?)— print a full-width divider line. Optionally pass a single character and a hex color (e.g.'#ff8800').
console.divider('-');
console.divider('=', '#ff8800');console.measure(label, fn)— measure sync or asyncfnexecution time and log result.
await console.measure('heavy task', async () => { await doWork(); });console.update(text)— overwrite the current terminal line (TTY-aware), useful for progress/status updates.
console.update('Processing 42%');omit(...keys)— returns new object excluding keys.
{id:1,name:'A',pwd:'x'}.omit('pwd');tap(fn)— run a side-effect function with the current value and return it; useful for debugging chains.
users
.filter(u => u.active)
.tap(list => console.log('Active users:', list.length))
.map(u => u.name);String helpers
stripHtml()— remove HTML tags from the string.
'<b>Hello</b>'.stripHtml(); // 'Hello'copyToClipboard()— copy the string to the system clipboard (browser only).
await 'Hello'.copyToClipboard();tryParse(fallback?)— safe JSON parse, returns fallback on error.
'{"x":1}'.tryParse(); // { x: 1 }
'bad'.tryParse(null); // nullslugify()— return URL-friendly slug.
'Olá Mundo!'.slugify(); // 'ola-mundo'mask(startVisible, endVisible, maskChar = '*')— mask middle of string.
'1234567890'.mask(3,2); // '123*****90'ANSI color helpers
- Basic getters:
red,green,blue,yellow,cyan,magenta,white,gray,bold— return the string wrapped in the corresponding ANSI color/style.
console.log('Error'.red);
console.log('Ok'.green.bold);hex(code)— color the string using a hex color (foreground).
console.log('Important'.hex('#FF8800'));bgHex(code)— set background color using a hex code.
console.log('Notice'.bgHex('#003366'));rgb(r,g,b)— color the string using explicit RGB values.
console.log('Custom'.rgb(128, 64, 200));Date helpers
format(mask)— simple date formatting (tokens:dd,MM,yyyy,HH,mm,ss).
new Date().format('dd/MM/yyyy');add(amount, unit)— add time to date (returns new Date).
new Date().add(1, 'days');isToday()/isWeekend()— convenience checks.
new Date().isToday();
new Date('2026-01-24').isWeekend();timeAgo(locale?)— human readable relative time usingIntl.RelativeTimeFormat.
const past = new Date(Date.now() - 1000*60*60);
past.timeAgo('en-US'); // '1 hour ago'RegExp helpers
RegExp.escape(str)— escape string for safe RegExp construction.
RegExp.escape('file.name?'); // 'file\.name\?'RegExp.prototype.getGroup(str, index = 1)— safely return capture group orundefined.
/(\d+)/.getGroup('ID: 123', 1); // '123'RegExp.prototype.scan(str)— requiresgflag; returns all matches asRegExpExecArrayentries.
/(\w+)-(\d+)/g.scan('a-1 b-2');Match helper
Object.prototype.match(cases)— map a value to outcomes via object literal, supports_default.
'active'.match({ active: 'green', inactive: 'red', _default: 'gray' });Development
Type-check:
npx tsc --noEmitBuild:
npm run buildContributing
Add new polyfills under src/, import them from src/polyfills.ts, add tests and documentation.
License
MIT © turbo-natives contributors
Checks whether a Date instance falls on a weekend (Saturday or Sunday).
